Spaces:
Running
Running
import asyncio | |
import httpx | |
from pathlib import Path | |
from typing import Optional | |
async def transcribe_audio( | |
file_path: str, | |
api_token: str, | |
model: str = "FunAudioLLM/SenseVoiceSmall", | |
api_url: str = "http://127.0.0.1:8000/v1/audio/transcriptions" | |
) -> Optional[dict]: | |
"""异步发送语音识别请求 | |
Args: | |
file_path: 音频文件路径 | |
api_token: API 认证令牌 | |
model: 模型名称,默认为 FunAudioLLM/SenseVoiceSmall | |
api_url: API 服务地址 | |
Returns: | |
dict: 包含识别结果的字典,失败时返回 None | |
""" | |
try: | |
# 检查文件是否存在 | |
audio_file = Path(file_path) | |
if not audio_file.exists(): | |
print(f"错误:文件 {file_path} 不存在") | |
return None | |
# 准备请求头和文件 | |
headers = {"Authorization": f"Bearer {api_token}"} | |
files = { | |
"file": (audio_file.name, audio_file.open("rb")), | |
"model": (None, model) | |
} | |
# 发送异步请求 | |
async with httpx.AsyncClient() as client: | |
response = await client.post( | |
api_url, | |
headers=headers, | |
files=files, | |
timeout=60, | |
) | |
print(response.text) | |
response.raise_for_status() | |
return response.json() | |
except httpx.HTTPError as e: | |
print(f"HTTP 请求错误:{str(e)}") | |
return None | |
except Exception as e: | |
print(f"发生错误:{str(e)}") | |
return None | |
async def main(): | |
# 使用示例 | |
file_path = "../examples/zh.mp3" | |
api_token = "your-secret-token-here" | |
result = await transcribe_audio(file_path, api_token) | |
if result: | |
print(f"识别结果:{result['text']}") | |
if __name__ == "__main__": | |
asyncio.run(main()) | |