#!/usr/bin/env python3
"""用 CosyVoice API 为每个音色生成试听样本"""
import requests, json, os, time

API_KEY = "sk-c25679401ba24c749f53be86b0c9a7a6"
API_URL = "https://dashscope.aliyuncs.com/api/v1/services/audio/tts/SpeechSynthesizer"
MODEL = "cosyvoice-v3-flash"
OUTPUT_DIR = "voices"

# 从文档整理的完整音色列表
VOICES = [
    # 标杆音色
    ("longanyang", "龙安洋-阳光大男孩"), ("longanhuan", "龙安欢-欢脱元气女"),
    ("longhuhu_v3", "龙呼呼-天真烂漫女童"),
    # 有声书
    ("longmiao_v3", "龙妙-抑扬顿挫女"), ("longsanshu_v3", "龙三叔-沉稳质感男"),
    ("longyuan_v3", "龙媛-温暖治愈女"), ("longyue_v3", "龙悦-温暖磁性女"),
    ("longxiu_v3", "龙修-博才说书男"), ("longnan_v3", "龙楠-睿智青年男"),
    ("longwanjun_v3", "龙婉君-细腻柔声女"), ("longyichen_v3", "龙逸尘-洒脱活力男"),
    ("longlaobo_v3", "龙老伯-沧桑岁月爷"), ("longlaoyi_v3", "龙老姨-烟火从容阿姨"),
    # 客服
    ("longyingxun_v3", "龙应询-年轻青涩男"), ("longyingjing_v3", "龙应静-低调冷静女"),
    ("longyingling_v3", "龙应聆-温和共情女"), ("longyingtao_v3", "龙应桃-温柔淡定女"),
    ("longyingmu_v3", "龙应沐-优雅知性女"), ("longyingxiao_v3", "龙应笑-清甜推销女"),
    # 语音助手
    ("longxiaochun_v3", "龙小淳-知性积极女"), ("longxiaoxia_v3", "龙小夏-沉稳权威女"),
    ("longanyun_v3", "龙安昀-居家暖男"), ("longanwen_v3", "龙安温-优雅知性女"),
    ("longanli_v3", "龙安莉-利落从容女"), ("longanlang_v3", "龙安朗-清爽利落男"),
    ("longyumi_v3", "YUMI-正经青年女"),
    # 社交
    ("longanqin_v3", "龙安亲-亲和活泼女"), ("longanya_v3", "龙安雅-高雅气质女"),
    ("longanzhi_v3", "龙安智-睿智轻熟男"), ("longanling_v3", "龙安灵-思维灵动女"),
    ("longantai_v3", "龙安台-嗲甜台湾女"), ("longhua_v3", "龙华-元气甜美女"),
    ("longcheng_v3", "龙橙-智慧青年男"), ("longze_v3", "龙泽-温暖元气男"),
    ("longzhe_v3", "龙哲-呆板大暖男"), ("longyan_v3", "龙颜-温暖春风女"),
    ("longxing_v3", "龙星-温婉邻家女"), ("longtian_v3", "龙天-磁性理智男"),
    ("longwan_v3", "龙婉-细腻柔声女"), ("longqiang_v3", "龙嫱-浪漫风情女"),
    ("longfeifei_v3", "龙菲菲-甜美娇气女"), ("longhao_v3", "龙浩-多情忧郁男"),
    ("longanrou_v3", "龙安柔-温柔闺蜜女"), ("longhan_v3", "龙寒-温暖痴情男"),
    # 童声
    ("longpaopao_v3", "龙泡泡-飞天泡泡音"), ("longjielidou_v3", "龙杰力豆-阳光顽皮男"),
    ("longxian_v3", "龙仙-豪放可爱女"), ("longling_v3", "龙铃-稚气呆板女"),
    ("longshanshan_v3", "龙闪闪-戏剧化童声"), ("longniuniu_v3", "龙牛牛-阳光男童声"),
    # 方言
    ("longjiaxin_v3", "龙嘉欣-优雅粤语女"), ("longjiayi_v3", "龙嘉怡-知性粤语女"),
    ("longanyue_v3", "龙安粤-欢脱粤语男"), ("longlaotie_v3", "龙老铁-东北直率男"),
    ("longshange_v3", "龙陕哥-陕北男"),
    # 新闻/直播
    ("longshuo_v3", "龙硕-博才干练男"), ("longshu_v3", "龙书-沉稳青年男"),
    ("loongbella_v3", "Bella3.0-精准干练女"), ("longanran_v3", "龙安燃-活泼质感女"),
    ("longanxuan_v3", "龙安宣-经典直播女"),
    # 特色
    ("longjiqi_v3", "龙机器-呆萌机器人"), ("longhouge_v3", "龙猴哥-经典猴哥"),
    ("longdaiyu_v3", "龙黛玉-娇率才女音"), ("longfei_v3", "龙飞-热血磁性男"),
    # 外语
    ("loongkyong_v3", "loongkyong-韩语女"), ("loongriko_v3", "Riko-霓虹女"),
    ("loongabby_v3", "美式英文女"), ("loongandy_v3", "美式英文男"),
]

os.makedirs(OUTPUT_DIR, exist_ok=True)

# 测试短句
TEST_TEXT = "你好，欢迎使用语音合成服务，我是你的智能语音助手。"
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

done = skip = fail = 0
total = len(VOICES)
print(f"模型: {MODEL}, 待生成: {total} 个音色\n")

for i, (voice, name) in enumerate(VOICES):
    fpath = os.path.join(OUTPUT_DIR, f"{voice}.mp3")
    if os.path.exists(fpath):
        skip += 1
        if skip % 10 == 0:
            print(f"  [{i+1}/{total}] 跳过已存在 ({skip}个)")
        continue

    payload = {
        "model": MODEL,
        "input": {"text": TEST_TEXT, "voice": voice, "format": "mp3", "sample_rate": 24000}
    }
    try:
        resp = requests.post(API_URL, headers=headers, json=payload, timeout=60)
        if resp.status_code == 200:
            data = resp.json()
            audio_url = data["output"]["audio"]["url"]
            ar = requests.get(audio_url, timeout=30)
            if ar.status_code == 200:
                with open(fpath, 'wb') as f:
                    f.write(ar.content)
                done += 1
                print(f"  ✅ [{i+1}/{total}] {name} ({voice}) - {len(ar.content)} bytes")
            else:
                fail += 1
                print(f"  ❌ [{i+1}/{total}] {voice} 下载失败")
        else:
            err = resp.json().get('message', resp.text)[:60]
            fail += 1
            print(f"  ⚠️  [{i+1}/{total}] {voice} 不支持: {err}")
    except Exception as e:
        fail += 1
        print(f"  ❌ [{i+1}/{total}] {voice} 异常: {e}")
    time.sleep(0.5)

print(f"\n========== 完成 ==========")
print(f"生成: {done}  跳过: {skip}  失败: {fail}")
print(f"保存目录: {OUTPUT_DIR}/")

# 统计
files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith('.mp3')]
total_size = sum(os.path.getsize(os.path.join(OUTPUT_DIR, f)) for f in files)
print(f"共 {len(files)} 个 mp3, 总大小 {total_size/1024/1024:.1f} MB")
