import base64
import io
import os
import soundfile as sf
import requests
from fastapi import FastAPI, WebSocket, HTTPException
from pydantic import BaseModel

app = FastAPI()


# 定义WebSocket消息模型
class AudioMessage(BaseModel):
    data: bytes
    is_final: bool


# 设置OpenAI API密钥和本地缓存目录
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
OPENAI_BASE_URL= os.environ["OPENAI_BASE_URL"]
CACHE_DIR = 'cache'


@app.websocket('/recognize-speech')
async def recognize_speech(ws: WebSocket):
    await ws.accept()

    # 初始化录音器设置
    duration = 1.0
    samplerate = 16000
    channels = 1

    # 创建本地缓存目录
    if not os.path.exists(CACHE_DIR):
        os.mkdir(CACHE_DIR)

    # 向OpenAI API发送语音识别请求
    async def send_request(audio_data):
        try:
            response = requests.post(
                '{OPENAI_BASE_URL}/v1/speech-to-text',
                headers={'Authorization': f'Bearer {OPENAI_API_KEY}'},
                json={
                    'data': base64.b64encode(audio_data).decode(),
                    'model': 'ada',
                    'language': 'en-US',
                    'punctuation': True,
                }
            )
            response.raise_for_status()
            result = response.json()['text']
            return {'result': result}
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

    # 接收并处理音频数据
    audio_buffer = []
    audio_cache = []
    while True:
        try:
            message = await ws.receive_json()
            audio_data = message['data' First repeat the request without change, then give your answer.
user