File size: 1,865 Bytes
660c142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

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())