import time
import json
import requests
import functools
from typing import Optional, Dict, Any


# 配置类
class Config:
    APP_ID = '6523591376'
    TOKEN = '8jkXUl2u90wL1drhXMfvs65Cq2JMVhwT'
    CLUSTER = 'volc_auc_common'
    SERVICE_URL = 'https://openspeech.bytedance.com/api/v1/auc'
    MAX_RETRY_COUNT = 1000
    MAX_TASK_ATTEMPTS = 500


# 重试装饰器
def retry(max_attempts: int, delay: int = 5):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt < max_attempts - 1:
                        time.sleep(delay)
            return None

        return wrapper

    return decorator


class SpeechRecognizer:
    def __init__(self):
        self.headers = {
            'Authorization': f'Bearer; {Config.TOKEN}',
            'Content-Type': 'application/json'
        }

    @retry(Config.MAX_RETRY_COUNT)
    def _submit_task(self, audio_url: str) -> Optional[str]:
        """提交语音识别任务（内部方法）"""
        request_data = {
            "app": {
                "appid": Config.APP_ID,
                "token": Config.TOKEN,
                "cluster": Config.CLUSTER
            },
            "user": {
                "uid": "dcc_live"
            },
            "audio": {
                "format": "mp3",
                "url": audio_url
            },
            "additions": {
                'with_speaker_info': 'False',
            }
        }

        response = requests.post(
            f"{Config.SERVICE_URL}/submit",
            data=json.dumps(request_data),
            headers=self.headers
        )
        response.raise_for_status()
        print(response.text)
        return response.json()['resp']['id']

    @retry(Config.MAX_RETRY_COUNT)
    def _query_task(self, task_id: str) -> Optional[Dict[str, Any]]:
        query_data = {
            'appid': Config.APP_ID,
            'token': Config.TOKEN,
            'id': task_id,
            'cluster': Config.CLUSTER
        }

        response = requests.post(
            f"{Config.SERVICE_URL}/query",
            data=json.dumps(query_data),
            headers=self.headers
        )
        response.raise_for_status()
        print("kakakaka")
        return response.json()

    @retry(Config.MAX_RETRY_COUNT)
    def recognize_audio(self, audio_url: str) -> Optional[Dict[str, Any]]:

        task_id = self._submit_task(audio_url)
        if not task_id:
            return None


        for attempt in range(Config.MAX_TASK_ATTEMPTS):
            result = self._query_task(task_id)
            if not result:
                return None

            code = result['resp']['code']

            if code >= 2000:
                time.sleep(1)
                print("重拾")
                continue


            elif code == 1000:
                return result.get('resp').get('text')

            else:
                return None

        return None


if __name__ == "__main__":
    recognizer = SpeechRecognizer()
    audio_url = "https://douchacha-web.tos-cn-beijing.volces.com/assets/7552163083708321058/7552163083708321058.mp4"  # 替换为实际音频URL
    result = recognizer.recognize_audio(audio_url)
    print(result)