#!/usr/bin/env python3
"""
生成"师徒一场_中"前10句的字幕图片
"""
import sqlite3
from PIL import Image, ImageDraw, ImageFont
import os

db_path = "\\\\ll\\D\\xtrssvjj\\dpd.db"
output_dir = "shituyichang_middle_frames_10"

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

conn = sqlite3.connect(db_path)
cursor = conn.cursor()

# 查询前10句字幕
adid = 8341
cursor.execute("SELECT idx, cn, en FROM srts WHERE adid = ? AND idx < 10 ORDER BY idx", (adid,))
subtitles = cursor.fetchall()

# 字体设置
font_path = "C:/Windows/Fonts/simhei.ttf"
title_font = ImageFont.truetype(font_path, 58)
subtitle_font = ImageFont.truetype(font_path, 44)
cn_font = ImageFont.truetype(font_path, 66)
en_font = ImageFont.truetype(font_path, 66)

# 标题和副标题
title_text = "师徒一场_张雪峰走好_中"
subtitle_text = "中文源自@晓松故事会"

for idx, cn, en in subtitles:
    # 创建黑色背景图片
    img = Image.new('RGB', (1080, 1920), color='black')
    draw = ImageDraw.Draw(img)
    
    # 计算标题位置（居中）
    bbox = draw.textbbox((0, 0), title_text, font=title_font)
    title_width = bbox[2] - bbox[0]
    x_title = (1080 - title_width) // 2
    y_title = 100
    
    # 绘制标题（白色）
    draw.text((x_title, y_title), title_text, font=title_font, fill='white')
    
    # 副标题与标题隔开一行
    bbox = draw.textbbox((0, 0), subtitle_text, font=subtitle_font)
    subtitle_width = bbox[2] - bbox[0]
    x_subtitle = (1080 - subtitle_width) // 2
    y_subtitle = y_title + bbox[3] - bbox[1] + 40
    
    # 绘制副标题（白色）
    draw.text((x_subtitle, y_subtitle), subtitle_text, font=subtitle_font, fill='white')
    
    # 再隔五行显示字幕
    y_text = y_subtitle + bbox[3] - bbox[1] + 40 + 5 * 40
    
    # 绘制中文（黄色）
    bbox = draw.textbbox((0, 0), cn, font=cn_font)
    cn_width = bbox[2] - bbox[0]
    x_cn = (1080 - cn_width) // 2
    draw.text((x_cn, y_text), cn, font=cn_font, fill='#FFD700')
    
    # 英文在中文下方（白色）
    y_en = y_text + (bbox[3] - bbox[1]) + 60
    bbox = draw.textbbox((0, 0), en, font=en_font)
    en_width = bbox[2] - bbox[0]
    x_en = (1080 - en_width) // 2
    draw.text((x_en, y_en), en, font=en_font, fill='white')
    
    # 保存图片
    output_path = os.path.join(output_dir, f"frame_{idx:03d}.jpg")
    img.save(output_path)
    print(f"  已生成 frame_{idx:03d}.jpg")

print(f"\n完成！共生成 {len(subtitles)} 张图片")
print(f"保存路径: {output_dir}")

conn.close()
