Qwen3-ASR与FastAPI集成:高性能语音识别API开发

张开发
2026/4/12 17:18:19 15 分钟阅读

分享文章

Qwen3-ASR与FastAPI集成:高性能语音识别API开发
Qwen3-ASR与FastAPI集成高性能语音识别API开发引言语音识别技术正在改变我们与设备交互的方式从智能助手到语音转文字应用处处都有它的身影。今天我们要介绍的是如何将强大的Qwen3-ASR语音识别模型与FastAPI框架结合打造一个高性能的语音识别API服务。如果你正在寻找一个能够处理高并发请求、响应迅速的语音识别解决方案那么这篇文章正是为你准备的。我们将从零开始一步步教你如何搭建这样一个系统让你能够轻松地将语音文件转换为准确的文字内容。1. 环境准备与依赖安装在开始之前我们需要准备好开发环境。确保你的系统已经安装了Python 3.8或更高版本。首先创建一个新的项目目录并进入mkdir qwen3-asr-api cd qwen3-asr-api创建并激活虚拟环境python -m venv venv source venv/bin/activate # Linux/Mac # 或者 venv\Scripts\activate # Windows安装必要的依赖包pip install fastapi uvicorn python-multipart dashscope这里我们安装了FastAPI作为Web框架uvicorn作为ASGI服务器python-multipart用于处理文件上传dashscope则是阿里云提供的SDK用于调用Qwen3-ASR服务。2. 获取API密钥要使用Qwen3-ASR服务你需要一个API密钥。前往阿里云百炼平台注册账号并获取API密钥。获取到密钥后我们可以通过环境变量来管理它export DASHSCOPE_API_KEY你的API密钥 # Linux/Mac # 或者 set DASHSCOPE_API_KEY你的API密钥 # Windows3. 基础FastAPI应用搭建让我们从创建一个简单的FastAPI应用开始。创建一个名为main.py的文件from fastapi import FastAPI, File, UploadFile from fastapi.responses import JSONResponse import dashscope import os from typing import Optional app FastAPI( titleQwen3-ASR语音识别API, description基于FastAPI和Qwen3-ASR的高性能语音识别服务, version1.0.0 ) # 配置DashScope API密钥 dashscope.api_key os.getenv(DASHSCOPE_API_KEY) app.get(/) async def root(): return {message: Qwen3-ASR语音识别API服务已启动} app.get(/health) async def health_check(): return {status: healthy, service: qwen3-asr-api}这个基础应用包含了根路由和健康检查端点。现在启动服务测试一下uvicorn main:app --reload --host 0.0.0.0 --port 8000访问 http://localhost:8000 你应该能看到API服务已经正常运行。4. 实现语音识别端点接下来我们实现核心的语音识别功能。在main.py中添加以下代码from fastapi import HTTPException import tempfile import json app.post(/transcribe) async def transcribe_audio( file: UploadFile File(..., description上传的音频文件), language: Optional[str] None, enable_itn: bool False ): 将音频文件转换为文字 - **file**: 要转换的音频文件支持MP3、WAV等格式 - **language**: 可选指定音频语言如zh、en - **enable_itn**: 是否启用逆文本标准化 # 检查文件类型 if not file.content_type.startswith(audio/): raise HTTPException(status_code400, detail请上传音频文件) # 创建临时文件保存上传的音频 with tempfile.NamedTemporaryFile(deleteFalse, suffix.mp3) as temp_audio: content await file.read() temp_audio.write(content) temp_audio_path ffile://{temp_audio.name} try: # 构建请求消息 messages [ {role: system, content: [{text: }]}, {role: user, content: [{audio: temp_audio_path}]} ] # 配置ASR选项 asr_options {enable_itn: enable_itn} if language: asr_options[language] language # 调用Qwen3-ASR服务 response dashscope.MultiModalConversation.call( modelqwen3-asr-flash, messagesmessages, result_formatmessage, asr_optionsasr_options ) # 处理响应 if response.status_code 200: # 提取识别结果 transcript response.output.choices[0].message.content[0].text return { status: success, transcript: transcript, file_name: file.filename } else: raise HTTPException( status_coderesponse.status_code, detailf语音识别失败: {response.message} ) except Exception as e: raise HTTPException(status_code500, detailf处理过程中发生错误: {str(e)}) finally: # 清理临时文件 import os if os.path.exists(temp_audio.name): os.unlink(temp_audio.name)这个端点接收音频文件调用Qwen3-ASR服务进行识别并返回转换后的文字内容。5. 处理高并发场景为了处理高并发请求我们需要对代码进行一些优化。首先创建一个专门的服务类来处理语音识别from concurrent.futures import ThreadPoolExecutor import asyncio class SpeechRecognitionService: def __init__(self, max_workers10): self.executor ThreadPoolExecutor(max_workersmax_workers) async def transcribe_async(self, file_path: str, language: Optional[str] None, enable_itn: bool False): loop asyncio.get_event_loop() return await loop.run_in_executor( self.executor, self._transcribe_sync, file_path, language, enable_itn ) def _transcribe_sync(self, file_path: str, language: Optional[str], enable_itn: bool): messages [ {role: system, content: [{text: }]}, {role: user, content: [{audio: file_path}]} ] asr_options {enable_itn: enable_itn} if language: asr_options[language] language response dashscope.MultiModalConversation.call( modelqwen3-asr-flash, messagesmessages, result_formatmessage, asr_optionsasr_options ) if response.status_code 200: return response.output.choices[0].message.content[0].text else: raise Exception(f识别失败: {response.message}) # 初始化服务 speech_service SpeechRecognitionService(max_workers20)然后更新我们的端点来使用这个服务app.post(/transcribe/v2) async def transcribe_audio_v2( file: UploadFile File(..., description上传的音频文件), language: Optional[str] None, enable_itn: bool False ): if not file.content_type.startswith(audio/): raise HTTPException(status_code400, detail请上传音频文件) with tempfile.NamedTemporaryFile(deleteFalse, suffix.mp3) as temp_audio: content await file.read() temp_audio.write(content) temp_audio_path ffile://{temp_audio.name} try: transcript await speech_service.transcribe_async( temp_audio_path, language, enable_itn ) return { status: success, transcript: transcript, file_name: file.filename } except Exception as e: raise HTTPException(status_code500, detailstr(e)) finally: import os if os.path.exists(temp_audio.name): os.unlink(temp_audio.name)6. 添加批处理功能对于需要处理大量音频文件的场景我们可以添加批处理功能from fastapi import BackgroundTasks import uuid # 用于存储处理结果 processing_results {} app.post(/transcribe/batch) async def transcribe_batch( files: list[UploadFile] File(..., description批量上传的音频文件), background_tasks: BackgroundTasks None, language: Optional[str] None ): 批量处理音频文件 batch_id str(uuid.uuid4()) processing_results[batch_id] { status: processing, total_files: len(files), processed_files: 0, results: [] } # 在后台处理任务 background_tasks.add_task(process_batch, batch_id, files, language) return { batch_id: batch_id, message: 批处理任务已开始, total_files: len(files) } async def process_batch(batch_id: str, files: list[UploadFile], language: Optional[str]): results [] for i, file in enumerate(files): try: with tempfile.NamedTemporaryFile(deleteFalse, suffix.mp3) as temp_audio: content await file.read() temp_audio.write(content) temp_audio_path ffile://{temp_audio.name} transcript await speech_service.transcribe_async(temp_audio_path, language) results.append({ file_name: file.filename, status: success, transcript: transcript }) # 清理临时文件 import os if os.path.exists(temp_audio.name): os.unlink(temp_audio.name) except Exception as e: results.append({ file_name: file.filename, status: error, error: str(e) }) # 更新处理进度 processing_results[batch_id][processed_files] i 1 processing_results[batch_id][results] results processing_results[batch_id][status] completed app.get(/batch/{batch_id}) async def get_batch_result(batch_id: str): 获取批处理结果 if batch_id not in processing_results: raise HTTPException(status_code404, detail批处理任务不存在) result processing_results[batch_id] return result7. 添加API文档和测试FastAPI自动为我们生成了API文档访问 http://localhost:8000/docs 即可查看和测试所有端点。我们还可以添加一些自定义的文档说明from fastapi.openapi.utils import get_openapi def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema get_openapi( titleQwen3-ASR语音识别API, version1.0.0, description基于FastAPI和Qwen3-ASR的高性能语音识别服务, routesapp.routes, ) # 添加自定义文档信息 openapi_schema[info][x-logo] { url: https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png } app.openapi_schema openapi_schema return app.openapi_schema app.openapi custom_openapi8. 部署和性能优化建议当准备将应用部署到生产环境时考虑以下优化建议使用Gunicorn作为进程管理器pip install gunicorn gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app配置适当的超时设置# 在FastAPI应用中添加超时中间件 from fastapi import Request import time app.middleware(http) async def add_timeout_middleware(request: Request, call_next): start_time time.time() response await call_next(request) process_time time.time() - start_time response.headers[X-Process-Time] str(process_time) return response使用Redis缓存结果import redis import json # 初始化Redis连接 redis_client redis.Redis(hostlocalhost, port6379, db0) app.post(/transcribe/cached) async def transcribe_cached( file: UploadFile File(...), language: Optional[str] None ): # 生成文件哈希作为缓存键 file_content await file.read() file_hash hashlib.md5(file_content).hexdigest() cache_key ftranscribe:{file_hash}:{language or auto} # 检查缓存 cached_result redis_client.get(cache_key) if cached_result: return json.loads(cached_result) # 处理并缓存结果 result await transcribe_audio_v2(file, language) redis_client.setex(cache_key, 3600, json.dumps(result)) # 缓存1小时 return result总结通过本文的介绍我们成功构建了一个基于FastAPI和Qwen3-ASR的高性能语音识别API服务。这个服务不仅能够处理单个音频文件的转换还支持批量处理和结果缓存适合高并发场景下的使用。实际使用下来这个方案部署简单性能表现也不错能够满足大多数语音识别需求。当然在生产环境中还需要考虑更多的因素比如监控、日志、错误处理等。如果你有大量音频处理需求建议先从小的规模开始测试逐步优化和扩展。希望这个教程对你有所帮助如果有任何问题或建议欢迎交流讨论。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

更多文章