泉州做外贸网站/青岛网站制作seo

泉州做外贸网站,青岛网站制作seo,软件开发工程师工作条件,58同城官网大家好,我是烤鸭: 最近在尝试做视频的质量分析,打算利用asr针对声音判断是否有人声,以及识别出来的文本进行进一步操作。asr看了几个开源的,最终选择了openai的whisper,后来发现性能不行,又换了…

大家好,我是烤鸭:

   最近在尝试做视频的质量分析,打算利用asr针对声音判断是否有人声,以及识别出来的文本进行进一步操作。asr看了几个开源的,最终选择了openai的whisper,后来发现性能不行,又换了whisperX。这是一篇实战和代码为主的文章。

引言

OpenAI的Whisper是一款强大的自动语音识别(ASR)模型,它支持多语种识别,包括中文,且经过大量的多语言和多任务监督数据训练,具有出色的鲁棒性和准确性。Python作为一种功能强大的编程语言,其丰富的库和简洁的语法使其成为实现语音识别功能的理想选择。本文将介绍如何利用Python集成Whisper,实现高效的语音识别。

目前一天小千的视频调用,平均时长3分钟。显卡是4090,平均识别耗时30s以内,业务无压力。

Whisper模型简介

Whisper是一个开源的语音识别模型,它基于Transformer架构,通过从网络上收集的680,000小时多语言数据进行训练,能够实现对多种语言的准确识别。此外,该模型对口音、背景噪音和技术语言具有很好的鲁棒性,使得其在实际应用中具有广泛的应用前景。

WhisperX 地址:
https://github.com/m-bain/whisperX

安装环境

linux
显卡是 4090
cuda pytorch
ffmpeg

python 需要的依赖

pip install --no-cache-dir flask -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir ffmpeg-python -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir wheel -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir zhconv -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir numpy -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir openai-whisper -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir kafka-python -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir fastapi -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir uvicorn -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir psutil -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir gputil -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir requests -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir use-nacos -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir pyyaml -i https://mirrors.aliyun.com/pypi/simple
pip install --no-cache-dir rocketmq-client-python -i https://mirrors.aliyun.com/pypi/simple

预期的功能

我想实现的是单台机器性能打满,并行识别asr,接口可以无限制接收请求,异步返回结果。

接口层

使用的是 fastapi 框架

import concurrent.futures
import os
import timeimport ffmpeg
import platform
import uvicorn
import asyncio
import psutil
from fastapi import FastAPI, BackgroundTasks, HTTPException, status, Query
from fastapi.responses import JSONResponse
import GPUtil
import requests
import jsonfrom dict_time import TimedMap
from parse_video_param import VideoRequest
from parse_video_callback_param import VideoCallbackRequest
from api_result import ApiResult
from whisper_processor import video_process
from whisperX_processor20241119 import video_process_whisperX
from logging_config import KAFKA_LOGGER
from nacos_config20241119 import register_nacosapp = FastAPI()
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)  # 线程池
# 定义CPU使用率阈值
threshold_cpu_usage = 95  # 例如,你希望CPU使用率不超过95%
threshold_gpu_usage_MB = 2400  # 例如,你希望显存使用大小 MB
timed_map = TimedMap()@app.post("/xxxx-video/whisperx")
async def parse_video(request: VideoRequest, background_tasks: BackgroundTasks):if not request or not request.path:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No video URL provided")print(f"parse_video, params:{request}")# 将处理任务添加到后台任务中,以便不阻塞主线程background_tasks.add_task(process_video_whisperx, request, background_tasks)# 立即返回处理中响应,告诉客户端请求已经被接收并正在处理api_result = ApiResult(1, "success", "", "")return JSONResponse(api_result.to_dict(), status_code=status.HTTP_200_OK)
# 异步函数来下载和处理视频
async def process_video_whisperx(request: VideoRequest, background_tasks: BackgroundTasks):def sync_process_video_whisperx(request):text = ''try:# 记录方法耗时start_time_single = time.time()# 下载视频并保存到临时文件url = request.pathchunk_size = request.chunk_size# 如果当前cpu使用率超过80%,就把该数据重新加到任务里# 获取当前CPU使用率cpu_usage = psutil.cpu_percent(interval=1, percpu=False)print(f"当前cpu利用率:{cpu_usage}")KAFKA_LOGGER.info(f"当前cpu利用率:{cpu_usage}")# 获取所有GPU的信息gpus = GPUtil.getGPUs()isGpuSuffiencent = True# 判断CPU使用率是否达到阈值if cpu_usage <= threshold_cpu_usage or isGpuSuffiencent:# 解析音频地址wavPath = getWav(url)print(f"mp3 url={wavPath}")# 不存在再去生成# 异步处理方法,解析音频这块可以忽略,也可以直接用视频地址if(not os.path.exists(wavPath)):(ffmpeg.input(url).output(wavPath, acodec='mp3').global_args('-loglevel', 'quiet').run())# 使用whisper处理音频text = process_audio_with_whisperx(wavPath, chunk_size)end_time_single = time.time()# 创建任务并添加到事件循环中,通知业务方asyncio.run(callback_task(request, text))print(f"视频地址:{url}, 函数执行耗时: {end_time_single - start_time_single}秒")KAFKA_LOGGER.info(f"视频地址:{url}, 函数执行耗时: {end_time_single - start_time_single}秒")# 清理临时文件os.remove(wavPath)else:print(f"当前cpu已超限,该视频重新加入队列:{url}")KAFKA_LOGGER.info(f"当前cpu已超限,该视频重新加入队列:{url}")# 暂停5秒time.sleep(5)# 重新加到队列里# 将处理任务添加到后台任务中,以便不阻塞主线程background_tasks.add_task(process_video_whisperx, request, background_tasks)except Exception as ex:print(f"sync_process_video error: {str(ex)}")KAFKA_LOGGER.error(f"sync_process_video error: {ex}")return textloop = asyncio.get_running_loop()# 使用线程池运行同步函数,避免阻塞异步事件循环return await loop.run_in_executor(executor, sync_process_video_whisperx, request)
# 获取文件路径
def getWav(input_video):try:# 判断系统是windows还是linuxoperating_system = platform.system()# 判断操作系统类型if operating_system == 'Windows':print("当前系统是Windows")audio_path = "C:\\Users\\xxx\\Downloads\\"else :audio_path = "/tmp/"# 从原始路径中获取文件名filename = os.path.basename(input_video)# 生成新文件的完整路径filename_without_extension = os.path.splitext(filename)[0]# 使用ffmpeg-python提取音频new_filename = os.path.join(audio_path, filename_without_extension) + ".mp3"except Exception as ex1:print("getWav ex:", str(ex1))return new_filename
# 音频解析
def process_audio_with_whisperx(audio_file_path: str, chunk_size: int) -> str:text = video_process_whisperX(audio_file_path, chunk_size)return text
# 异步回调
async def callback_task(request: VideoRequest, text: str):# 创建任务并添加到事件循环中task = asyncio.create_task(callback(request, text))# 等待任务完成await task
# 回调请求方法
async def callback(request: VideoRequest, text: str):# 目标URLurl = request.callback_url# JSON格式的参数data = {'id': request.id,'text': text,# 添加更多键值对...}# 设置一些键值对timed_map.set(request.path, json.dumps(data), timeout=1800)# 设置请求头,告诉服务器我们发送的是JSON数据headers = {'Content-Type': 'application/json'}# 设置超时时间,这里设置为5秒timeout = 5.0# 发送POST请求response = requests.post(url, data=json.dumps(data), headers=headers, timeout=timeout)print(f"url:{url},data: {json.dumps(data)},headers:{headers},response:{response}")# 检查请求是否成功if response.status_code == 200:# 请求成功,处理响应内容print("请求成功")print(response.json())  # 如果响应内容是JSON格式,可以直接解析else:# 请求失败,打印错误信息print(f"请求失败,状态码:{response.status_code}")print(response.text)  # 打印响应的文本内容
# 启动应用
if __name__ == "__main__":register_nacos()uvicorn.run(app, host="0.0.0.0", port=5000)    

whisperX

import whisperx
from whisperx.asr import FasterWhisperPipeline
import time
import torch
import gc
import osENV = os.environ.get('ENV', 'development')
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
if ENV == 'production':batch_size = 16compute_type = "float16"model_name = "large-v2"
else:# reduce if low on GPU membatch_size = 4# compute_type = "float16"  # change to "int8" if low on GPU mem (may reduce accuracy)# change to "int8" if low on GPU mem (may reduce accuracy)compute_type = "int8"model_name = "medium"
class WhisperXProcessor:fast_model: FasterWhisperPipelinedef loadModel(self):# 1. Transcribe with original whisper (batched)self.fast_model = whisperx.load_model("medium", device.type, compute_type=compute_type)print("模型加载完成")def asr(self, filePath: str, chunk_size: int):print(f'asr start filePath:{filePath}')start = time.time()audio = whisperx.load_audio(filePath)result = self.fast_model.transcribe(audio, batch_size=batch_size, chunk_size = chunk_size)print(result)end = time.time()print('识别使用的时间:', end - start, 's')torch.cuda.empty_cache()gc.collect()return resultdef video_process_whisperX(audio_path, chunk_size):app = WhisperXProcessor()app.loadModel()text = app.asr(audio_path, chunk_size)return text

结果验证

发送请求

curl -XPOST 'http://localhost:5000/xxxx-video/whisperX' -H 'Content-Type: application/json' -d '{"id":1,"path":"https://vc16-bd1-pl-agv.autohome.com.cn/video-26/0A33363922E51BDE/2025-02-10/FC68CC971BB8B9A46F15C4841F4F2CE2-200-wm.mp4?key=F77E8D3251C4560FA47E36563A5D5668&time=1739187850","callback_url":"http://localhost:8088/xxx/demo/testParseVideo"}'

结果日志,2分钟的视频,大概用了60s。

在这里插入图片描述

文章参考

ASR强力模型「Whisper」:解密Whisper

Python实现语音识别(whisperX)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/895497.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mapbox 从入门到精通 - 目录

&#x1f468;‍⚕️ 主页&#xff1a; gis分享者 &#x1f468;‍⚕️ 感谢各位大佬 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍⚕️ 收录于专栏&#xff1a;mapbox 从入门到精通 文章目录 一、&#x1f340;总目录1.1 ☘️ mapbox基础1.2 ☘️…

sqlilabs--小实验

一、先盲注判断 ?id1 and sleep(2)-- 如果发现页面存在注点&#xff0c;使用时间盲注脚本进行注入 import requestsdef inject_database(url):name for i in range(1, 20): # 假设数据库名称长度不超过20low 48 # 0high 122 # zmiddle (low high) // 2while low &l…

【数字】异步FIFO面试的几个小问题与跨时钟域时序约束

入门数字设计的时候&#xff0c;跨时钟域的数据处理是绕不开的课题&#xff0c;特别是多比特数据跨时钟域时&#xff0c;都会采用异步FIFO的方法。 异步FIFO中涉及较多的考点这里记录几个以供大家参考。 1. 异步FIFO的空满判断分别在哪个域&#xff1f; 根据异步FIFO的结构&…

RabbitMQ学习—day2—安装

目录 普通Linux安装 安装RabbitMQ 1、下载 2、安装 3. Web管理界面及授权操作 Docker 安装 强力推荐学docker&#xff0c;使用docker安装 普通Linux安装 安装RabbitMQ 1、下载 官网下载地址&#xff1a;https://www.rabbitmq.com/download.html(opens new window) 这…

降本增效 - VGF 构建轻量高性能日志管理平台

VFG 技术架构 Filebeat 接收Syslog &#xff0c;并进行日志分段&#xff0c;VictoriaLogs 持久化存储日志 &#xff0c;Grafana 可视化、数据查询、告警、数据导出。 为什么要用VictoriaLogs &#xff1f; 与Elasticsearch /Grafana Loki相比几十倍的CPU/内存/存储资源占用的…

初识camel智能体(一)

同目录下配置环境变量.env&#xff0c;内容如下&#xff0c; apikey从魔搭社区获取 QWEN_API_KEY4ff3ac8f-aebc******** 先上干货代码&#xff0c;主代码如下&#xff1a; from colorama import Forefrom camel.societies import RolePlaying from camel.utils import prin…

如何保持 mysql 和 redis 中数据的一致性?PegaDB 给出答案

MySQL 与 Redis 数据保持一致性是一个常见且复杂的问题&#xff0c;一般来说需要结合多种策略来平衡性能与一致性。 传统的解决策略是先读缓存&#xff0c;未命中则读数据库并回填缓存&#xff0c;但方式这种维护成本较高。 随着云数据库技术的发展&#xff0c;目前国内云厂商…

探索ELK 的魅力

在大数据时代&#xff0c;海量日志和数据的收集、存储、处理与可视化分析变得越来越重要。而 ELK 堆栈&#xff0c;由 Elasticsearch、Logstash、Beats 和 Kibana 组成&#xff0c;正是一个强大的开源解决方案&#xff0c;帮助开发者和运维人员高效管理和分析日志数据。本文将详…

深度学习实战基础案例——卷积神经网络(CNN)基于DenseNet的眼疾检测|第4例

文章目录 前言一、数据准备二、项目实战2.1 设置GPU2.2 数据加载2.3 数据预处理2.4 数据划分2.5 搭建网络模型2.6 构建densenet1212.7 训练模型2.8 结果可视化 三、UI设计四、结果展示总结 前言 在当今社会&#xff0c;眼科疾病尤其是白内障对人们的视力健康构成了严重威胁。白…

代码随想录二叉树篇(含源码)

二叉树与递归 前言226.翻转二叉树算法思路及代码solution 1 用分解问题的思路来解决solution 2 用遍历的思路来解决 101.对称二叉树算法思路及代码solution 104.二叉树的最大深度算法思路及代码solution 1 遍历solution 2 分解问题 111.二叉树的最小深度算法思路及代码solution…

MyBatis映射文件 <resultMap> 元素详解与示例

引言 <resultMap> 是 MyBatis 中最核心的映射配置元素&#xff0c;用于解决数据库字段与 Java 对象属性之间的复杂映射问题&#xff0c;尤其是字段名不一致、嵌套对象关联、集合映射等场景。ResultMap 的设计思想是&#xff0c;对简单的语句做到零配置&#xff0c;对于复…

WIN11上使用GraalVM打包springboot3项目为本地可执行文件exe

耐心肝才能成功 概念步骤概要详细步骤一. GraalVM 17二. 安装Visual Studio 2022三. 创建springboot四. IDEA最新版或者eclipse2025调试项目五. 打包exe 概念 springboot3生成的jar编译成windows本地C文件&#xff0c;不再依赖JVM运行 WINDOW编译较为复杂&#xff0c;限制条件…

【git-hub项目:YOLOs-CPP】本地实现01:项目构建

目录 写在前面 项目介绍 最新发布说明 Segmentation示例 功能特点 依赖项 安装 克隆代码仓库 配置 构建项目 写在前面 前面刚刚实现的系列文章: 【Windows/C++/yolo开发部署01】 【Windows/C++/yolo开发部署02】 【Windows/C++/yolo开发部署03】 【Windows/C++/yolo…

超越 DeepSeek V3 -->【Qwen2.5-Max】

&#x1f525; 先说明&#xff0c;不是广子&#xff0c;不是广子&#xff01;&#xff01;&#xff01;单纯分享这个工具给大家&#xff0c;毕竟最近使用 DeepSeek 太容易崩了&#xff0c;每天深度思考一次之后就开始转圈圈用不了&#xff0c;然后就找到了这个工具使用 一、前言…

python自动化测试之Pytest框架之YAML详解以及Parametrize数据驱动!

一、YAML详解 YAML是一种数据类型&#xff0c;它能够和JSON数据相互转化&#xff0c;它本身也是有很多数据类型可以满足我们接口 的参数类型&#xff0c;扩展名可以是.yml或.yaml 作用&#xff1a; 1.全局配置文件 基础路径&#xff0c;数据库信息&#xff0c;账号信息&…

CentOS 7操作系统部署KVM软件和创建虚拟机

CentOS 7.9操作系统部署KVM软件和配置指南&#xff0c;包括如何创建一个虚拟机。 步骤 1: 检查硬件支持 首先&#xff0c;确认您的CPU支持虚拟化技术&#xff0c;并且已在BIOS中启用&#xff1a; egrep -c (vmx|svm) /proc/cpuinfo 如果输出大于0&#xff0c;则表示支持虚拟…

日本 万叶假名

万叶假名&#xff08;まんようがな&#xff0c;Manyōgana&#xff09;是一种早期的日语书写系统&#xff0c;主要用于《万叶集》等古代文献中。它的特点是完全使用汉字来表示日语的音&#xff0c;不考虑汉字的原意。可以将其视为平假名和片假名的前身。 记住是唐代的发音不是…

【鸿蒙HarmonyOS Next实战开发】实现组件动态创建和卸载-优化性能

一、简介 为了解决页面和组件加载缓慢的问题&#xff0c;ArkUI框架引入了动态操作功能&#xff0c;支持组件的预创建&#xff0c;并允许应用在运行时根据实际需求动态加载和渲染组件。 这些动态操作包括动态创建组件&#xff08;即动态添加组件&#xff09;和动态卸载组件&am…

MongoDB 7 分片副本集升级方案详解(上)

#作者&#xff1a;任少近 文章目录 前言&#xff1a;Mongodb版本升级升级步骤环境1.1环境准备1.2standalone升级1.3分片、副本集升级 前言&#xff1a;Mongodb版本升级 在开始升级之前&#xff0c;请参阅 MongoDB下个版本中的兼容性变更文档&#xff0c;以确保您的应用程序和…

AI前端开发:跨领域合作的新引擎

随着人工智能技术的飞速发展&#xff0c;AI代码生成器等工具的出现正深刻地改变着软件开发的模式。 AI前端开发的兴起&#xff0c;不仅提高了开发效率&#xff0c;更重要的是促进了跨领域合作&#xff0c;让数据科学家、UI/UX设计师和前端工程师能够更紧密地协同工作&#xff0…