#!/usr/bin/env python3
"""
生成前5句字幕的视频（使用绝对路径）
"""
import sqlite3
import os
import subprocess

# 数据库路径
db_path = "\\\\ll\\D\\xtrssvjj\\dpd.db"

# 输入输出
mp3_path = "\\\\ll\\D\\wxvddata\\师徒一场_张雪峰走好_上.mp3"
frames_dir = os.path.abspath("shitu_frames")
temp_dir = "shitu_temp"
if not os.path.exists(temp_dir):
    os.makedirs(temp_dir)

# 查询前5句字幕
try:
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    cursor.execute("SELECT idx, start, end, cn, en FROM srts WHERE adid = 8281 ORDER BY idx ASC LIMIT 5")
    subtitles = cursor.fetchall()
    
    print(f"处理前 {len(subtitles)} 句字幕")
    
    # 创建图片列表文件
    list_file = os.path.join(temp_dir, "image_list.txt")
    
    with open(list_file, 'w', encoding='utf-8') as f:
        for idx, start, end, cn, en in subtitles:
            duration = (end - start) / 1000
            frame_path = os.path.join(frames_dir, f"frame_{idx:03d}.jpg")
            frame_path = frame_path.replace('\\', '/')  # 使用正斜杠
            # 每帧显示指定时长
            f.write(f"file '{frame_path}'\nduration {duration:.2f}\n")
        # 最后一帧需要重复一次以确保时长正确
        last_idx = subtitles[-1][0]
        last_frame = os.path.join(frames_dir, f"frame_{last_idx:03d}.jpg")
        last_frame = last_frame.replace('\\', '/')
        f.write(f"file '{last_frame}'\n")
    
    # 生成视频
    output_video = "shitu_test_first5.mp4"
    cmd = [
        'ffmpeg', '-y',
        '-f', 'concat',
        '-safe', '0',
        '-i', list_file,
        '-i', mp3_path,
        '-shortest',
        '-c:v', 'libx264',
        '-preset', 'fast',
        '-c:a', 'aac',
        '-ar', '44100',
        '-ac', '1',
        '-pix_fmt', 'yuv420p',
        output_video
    ]
    
    print("合成视频...")
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode == 0:
        print(f"完成！视频保存在: {output_video}")
        print(f"时长: 约 {sum((end - start)/1000 for idx, start, end, cn, en in subtitles):.2f}s")
    else:
        print(f"错误: {result.stderr}")
    
    conn.close()
    
except Exception as e:
    print(f"错误: {e}")
