#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生成Artemis_II_十天绕月的每句字幕TTS音频（英文）
"""

import os
import sqlite3
import asyncio
import edge_tts


async def generate_tts(text, output_file):
    """
    生成TTS音频
    """
    try:
        communicate = edge_tts.Communicate(text, "en-US-AriaNeural", rate="-30%")
        await communicate.save(output_file)
        return True
    except Exception as e:
        print(f"  TTS生成失败: {e}")
        return False


def main():
    # 连接数据库
    db_path = "\\\\ll\\d\\xtrssvjj\\dpd.db"
    conn = sqlite3.connect(db_path)
    cur = conn.cursor()
    
    # 查询Artemis的字幕数据
    cur.execute("SELECT idx, en FROM srts WHERE adid=? ORDER BY idx", (8404,))
    srtsdata = cur.fetchall()
    conn.close()
    
    print(f"找到 {len(srtsdata)} 条字幕数据")
    
    # 创建输出目录
    output_dir = "Artemis_II_十天绕月_tts"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 生成TTS音频
    for idx, en_text in srtsdata:
        output_file = os.path.join(output_dir, f"tts_{idx:03d}.mp3")
        
        # 如果文件已存在，跳过
        if os.path.exists(output_file):
            print(f"TTS音频 {idx:03d} 已存在，跳过...")
            continue
        
        print(f"正在生成TTS音频 {idx:03d}: {en_text[:50]}...")
        
        # 异步生成TTS
        loop = asyncio.get_event_loop()
        success = loop.run_until_complete(generate_tts(en_text, output_file))
        
        if success:
            print(f"  成功: {output_file}")
        else:
            print(f"  失败: tts_{idx:03d}.mp3")
    
    print(f"\n完成！TTS音频保存到: {output_dir}")


if __name__ == "__main__":
    main()
