whisper-api语音识别语音翻译高性能兼容openai接口协议的开源项目

whisper-api

介绍

使用openai的开源项目winsper语音识别开源模型封装成openai chatgpt兼容接口

软件架构

使用uvicorn、fastapi、openai-whisper等开源库实现高性能接口

更多介绍 [https://blog.csdn.net/weixin_40986713/article/details/138712293](https://blog.csdn.net/weixin_40986713/article/details/138712293)

使用说明
  1. 下载代码
  2. 安装 ffmpeg https://ffmpeg.org/download.html
  3. 安装依赖 项目根目录下执行命令 pip install -r requirements.txt
  4. 运行代码 项目根目录下执行命令 python main.py

这里的 http://0.0.0.0:3003 就是连接地址。

启动类代码
import atexit
import json
import os
import tempfile
import time

import uvicorn
from fastapi import FastAPI, UploadFile, File, Security, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

from whisper_script import WhisperHandler

app = FastAPI()
security = HTTPBearer()
env_bearer_token = 'sk-tarzan'
model_size = os.getenv("MODEL_SIZE", "base")
language = os.getenv("LANGUAGE", "Chinese")


def cleanup_temp_file(path):
    if os.path.exists(path):
        os.remove(path)


with open('options.json', 'r') as options:
    # 使用json.load()函数读取并解析文件内容
    load_options = json.load(options)


# 语音识别
@app.post("/v1/audio/transcriptions")
async def transcribe(file: UploadFile = File(...), credentials: HTTPAuthorizationCredentials = Security(security)):
    if env_bearer_token is not None and credentials.credentials != env_bearer_token:
        raise HTTPException(status_code=401, detail="Invalid token")
    file_bytes = await file.read()
    return {"text": audio_to_text(file_bytes, 'transcribe')}


# 语音翻译
@app.post("/v1/audio/translations")
async def translate(file: UploadFile = File(...), credentials: HTTPAuthorizationCredentials = Security(security)):
    if env_bearer_token is not None and credentials.credentials != env_bearer_token:
        raise HTTPException(status_code=401, detail="Invalid token")
    file_bytes = await file.read()
    return {"text": audio_to_text(file_bytes, 'translate')}


def audio_to_text(file_bytes, task):
    start_time = time.time()
    max_file_size = 500 * 1024 * 1024
    if len(file_bytes) > max_file_size:
        raise HTTPException(status_code=400, detail="File is too large")
    temp_path = None
    try:
        with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio:
            temp_audio.write(file_bytes)
            temp_path = temp_audio.name
        model_size = load_options.get("model_size")
        language = load_options.get("language")
        prompts = {
            "verbose": load_options.get("verbose"),
            "temperature": load_options.get("temperature"),
            "compression_ratio_threshold": load_options.get("compression_ratio_threshold"),
            "logprob_threshold": load_options.get("logprob_threshold"),
            "no_speech_threshold": load_options.get("no_speech_threshold"),
            "condition_on_previous_text": load_options.get("condition_on_previous_text"),
            "initial_prompt": load_options.get("initial_prompt"),
            "word_timestamps": load_options.get("word_timestamps"),
            "prepend_punctuations": load_options.get("prepend_punctuations"),
            "append_punctuations": load_options.get("append_punctuations")
        }
        print('temp_path', temp_path)
        handler = WhisperHandler(temp_path, model_size=model_size, language=language, task=task, prompt=prompts)
        result = handler.transcribe()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        atexit.register(cleanup_temp_file, temp_path)
    end_time = time.time()
    print(f"audio to text took {end_time - start_time:.2f} seconds")
    return result['text']


if __name__ == "__main__":
    token = os.getenv("ACCESS_TOKEN")
    if token is not None:
        env_bearer_token = token
    try:
        uvicorn.run("main:app", reload=True, host="0.0.0.0", port=3003)
    except Exception as e:
        print(f"API启动失败!\n报错:\n{e}")

docker
  1. docker打包命令
docker build -t whisper .

2.docker命令启动

gpu显卡模式

docker run -itd --name whisper-api -p 3003:3003 --gpus all --restart=always whisper
  • 默认 ACCESS_TOKEN=sk-tarzan

cpu模式

docker run -itd --name whisper-api -p 3003:3003 --restart=always whisper
  • 默认 ACCESS_TOKEN=sk-tarzan

鉴权模式

docker run -itd --name whisper-api -p 3003:3003-e ACCESS_TOKEN=yourtoken --gpus all --restart=always whisper
docker run -itd --name whisper-api -p 3003:3003-e ACCESS_TOKEN=yourtoken --restart=always whisper
  • yourtoken 修改你设置的鉴权token,接口调用header 里传 Authorization:Bearer sk-tarzan

docker日志查看

docker logs -f [容器id或容器名称]
配置文件

options.json

{
  "model_size": "base",
  "language": "Chinese"
}
  • 13
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Whisper是一款可以实现语音识别转文字的应用软件。它可以通过下载安装在手机或电脑上,实现将语音转化为文字的功能。 使用Whisper进行语音识别转文字非常简便。首先,用户需要下载并安装Whisper应用,可以在各大应用商店或官方网站上获取。安装完成后,用户可以打开应用,并按照界面上的提示进行设置和授权。接下来,用户可以开始使用Whisper进行语音转文字的操作。 在使用Whisper进行语音识别转文字时,用户可以选择两种方式。一种是通过录制语音进行识别,用户只需按下录制按钮,开始说话,Whisper会自动将语音转化为文字。另一种方式是通过实时语音输入进行识别,用户可以直接讲话到麦克风,Whisper会实时将语音转为文字显示在屏幕上。 Whisper语音识别转文字功能非常准确和快速。它采用了先进的语音识别技术,能够准确地识别各种语音,并将其转化为文字。同时,Whisper还支持多国语言的识别,可以满足不同用户的需求。 通过Whisper进行语音识别转文字,用户可以享受到很多便利。无论是需要记录会议内容、学习笔记,还是进行语音交流的转化,Whisper都能够帮助用户快速准确地将语音转化为文字,并保存在手机或电脑上。这样,用户可以方便地进行查看、编辑和分享。 总之,Whisper是一个功能强大、操作简便的语音识别转文字应用软件,通过下载安装,用户可以随时随地将语音转化为文字,提高工作和学习的效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泰山AI

原创不易,感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值