#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
根据字幕图片和双语时间生成完整视频流
用法: python generate_bilingual_video.py <adid>
"""

import os
import re
import sys
import sqlite3
import subprocess
import glob
import tempfile

import joinbiliad

def get_subtitlesx(adid, db_path):
    """
    从数据库获取字幕信息
    """
    import inspect
    func_name = inspect.currentframe().f_code.co_name
    line_no = inspect.currentframe().f_lineno
    
    conn = None
    try:
        conn = sqlite3.connect(db_path, timeout=10.0)
        cursor = conn.cursor()
        
        cursor.execute("""
            SELECT idx, start, end, cn, en FROM srts 
            WHERE adid = ? 
            ORDER BY idx
        """, (adid,))
        
        subtitles = []
        for row in cursor.fetchall():
            idx, start, end, cn, en = row
            # 解析时间格式
            start_ms = int(start)
            end_ms = int(end)
            subtitles.append((idx, start_ms, end_ms, cn, en))
        
        return subtitles
    except Exception as e:
        import traceback
        print(f"错误 [函数: {func_name}, 行号: {line_no}]: 操作失败: {e}")
        traceback.print_exc()
        return []
    finally:
        if conn:
            conn.close()
def get_adname(adid, db_path):
    """
    从数据库获取adname
    """
    import inspect
    func_name = inspect.currentframe().f_code.co_name
    line_no = inspect.currentframe().f_lineno
    
    conn = None
    try:
        conn = sqlite3.connect(db_path, timeout=180)
        cursor = conn.cursor()
        
        cursor.execute("SELECT DISTINCT adname FROM srts WHERE adid = ? LIMIT 1", (adid,))
        result = cursor.fetchone()
        
        if result:
            return result[0]
        return f"adid_{adid}"
    except Exception as e:
        import traceback
        print(f"错误 [函数: {func_name}, 行号: {line_no}]: 操作失败: {e}")
        traceback.print_exc()
        return f"adid_{adid}"
    finally:
        if conn:
            conn.close()
def get_bilingual_time(adid):
    """
    读取双语时间信息
    """
    # 配置
    db_path = r'\\ll\D\xtrssvjj\db\dpd.db'
    
    # 获取adname
    adname = get_adname(adid, db_path)
    
    # 目录路径
    cn_audio_dir = f"{adname}_cn_audio"
    en_tts_dir = os.path.join(r'\\ll\D\xtrssvjj', 'tts', adname)
    
    # 获取字幕
    # subtitles = get_subtitles(adid, db_path)
    subtitles = joinbiliad.get_subtitles(adid, db_path)
    
    # 音频文件路径
    audio_file = os.path.join(r'\\ll\D\xtrssvjj', f"{adname}.mp3")
    
    # 获取音频文件总长度
    def get_file_duration(file_path):
        # cmd = ["ffprobe", "-f","mp3","-v", "quiet", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file_path]
        cmd = ["ffprobe","-v", "quiet", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", "-i",f"file:{file_path}"]
        result = subprocess.run(cmd, capture_output=True, text=True)
        # print('stdout:',result.stdout)
# 完美的 Windows 还原方法（不管文件名带不带空格、特殊符号，都能精准加双引号和转义）
        # actual_cmdline = subprocess.list2cmdline(cmd)
        # print(actual_cmdline)

        if result.returncode == 0:
            return int(float(result.stdout.strip()) * 1000)
        return 0
    
    audio_duration = get_file_duration(audio_file)
    
    # 计算每句的startpos、endpos、addstart、addend
    bilingual_times = []
    for i, (idx, start, end, cn, en) in enumerate(subtitles):
        prevend = subtitles[i-1][2] if i > 0 else 0
        startgap = start - prevend if i > 0 else 0
        
        if i < len(subtitles)-1:
            nextstart = subtitles[i+1][1]
            endgap = nextstart - end
        else:
            # 最后一句的nextstart为音频文件的实际总长度
            nextstart = audio_duration
            endgap = nextstart - end if audio_duration > end else 0
        
        # 计算startpos和endpos
        # 第一句的startpos固定为0
        if i == 0:
            startpos = 0
        else:
            startpos = (prevend + start) // 2
        
        # 最后一句的endpos为视频的最后位置(总长度-1)
        if i == len(subtitles)-1:
            endpos = audio_duration - 1
        else:
            endpos = (end + nextstart) // 2
        
        # 计算addstart值：第一句addstart=0，后面的用400-(start-startpos)
        if i == 0:
            addstart = 0
        else:
            addstart = 400 - (start - startpos)
            if addstart <= 0:
                addstart = 0
        
        # 计算addend值：最后一句addend=0，其他用400-(endpos-end)
        if i == len(subtitles)-1:
            addend = 0
        else:
            addend = 400 - (endpos - end)
            if addend <= 0:
                addend = 0
        
        # 获取中文音频长度
        cn_audio_file = os.path.join(cn_audio_dir, f"seg{idx:03d}-{startpos}-{endpos}-*.mp3")
        cn_files = glob.glob(cn_audio_file)
        cn_duration = 0
        if cn_files:
            cn_file=cn_files[0]
            filenamestartposidx=len(cn_audio_file)-5
            filenameendposidx=len(cn_file)-4           
            durstr=cn_file[filenamestartposidx:filenameendposidx]
            try:
                cn_duration =int(durstr)        
            except Exception as ex:
                print('xxx',ex)
                return []
        # 获取英文TTS长度 - 只使用网络共享位置的TTS文件
        en_tts_pattern = os.path.join(en_tts_dir, f"*-{idx:04d}.mp3")
        en_files = glob.glob(en_tts_pattern)
        
        en_duration = 0
        if en_files:
            # 打印使用的网络TTS文件路径
            if i%100==0:
                print(f"使用网络TTS文件: {en_files[0]}")
            # 计算调整语速后的TTS长度（原长度 / 0.7）
            original_duration = get_file_duration(en_files[0])
            en_duration = original_duration / 0.7
        
        # 计算双语总时间
        bilingual_time = addstart + cn_duration + addend + en_duration
        
        bilingual_times.append((idx, bilingual_time))
    
    return bilingual_times

def make_bili_vd(adid):
    """
    生成完整的视频流
    """
    # 配置
    db_path = r'\\ll\D\xtrssvjj\db\dpd.db'
    
    # 获取adname
    adname = get_adname(adid, db_path)
    print(f"adname: {adname}")
    
    # 目录路径
    image_dir = f"{adname}_images"
    
    # 检查目录是否存在
    if not os.path.exists(image_dir):
        print(f"错误：字幕图片目录不存在: {image_dir}")
        return False
    
    # 获取双语时间
    bilingual_times = get_bilingual_time(adid)
    print(f"找到 {len(bilingual_times)} 句双语时间信息")
    
    if not bilingual_times:
        print("错误：未找到双语时间信息")
        return False
    
    # 创建临时目录
    with tempfile.TemporaryDirectory() as temp_dir:
        # 生成视频片段
        video_fragments = []
        
        for idx, duration_ms in bilingual_times:
            # 找到对应的图片文件
            image_file = os.path.join(image_dir, f"vertical_subtitle_{idx:03d}.png")
            
            if not os.path.exists(image_file):
                print(f"警告：图片文件不存在: {image_file}")
                continue
            
            # 转换时长为秒
            duration_sec = duration_ms / 1000
            
            # 输出文件名
            output_file = os.path.join(temp_dir, f"fragment_{idx:03d}.mp4")
            
            # 生成视频片段
            cmd = [
                "ffmpeg", "-y",
                "-loop", "1",
                "-i", image_file,
                "-c:v", "libx264",
                "-tune", "stillimage",
                "-c:a", "aac",
                "-b:a", "192k",
                "-pix_fmt", "yuv420p",
                "-t", str(duration_sec),
                "-shortest",
                output_file
            ]
            
            subprocess.run(cmd, capture_output=True)
            
            if os.path.exists(output_file):
                video_fragments.append(output_file)
                
        print(f"生成了 {len(video_fragments)} 个视频片段")
        
        if not video_fragments:
            print("错误：未生成任何视频片段")
            return False
        
        # 生成拼接文件列表
        filelist_path = os.path.join(temp_dir, "filelist.txt")
        
        with open(filelist_path, 'w', encoding='utf-8') as f:
            for fragment in video_fragments:
                f.write(f"file '{os.path.abspath(fragment)}'\n")
        
        # 执行拼接
        output_file = os.path.join(image_dir, f"{adname}_bilingual_video.mp4")
        cmd = [
            "ffmpeg", "-y",
            "-f", "concat",
            "-safe", "0",
            "-i", filelist_path,
            "-c", "copy",
            output_file
        ]
        
        print("开始拼接视频流...")
        result = subprocess.run(cmd, capture_output=True)
        
        if result.returncode == 0:
            print(f"拼接完成！输出文件: {output_file}")
            return True
        else:
            # 尝试解码错误信息
            try:
                error_msg = result.stderr.decode('utf-8', errors='replace')
            except:
                try:
                    error_msg = result.stderr.decode('gbk', errors='replace')
                except:
                    error_msg = str(result.stderr)
            print(f"拼接失败！错误信息: {error_msg}")
            return False
def clean_filename_suffix(adname):
    # 模式解析：
    # \s*      : 匹配可能存在的空格
    # [(_-]    : 匹配 ( 或 _ 或 -
    # \d+      : 匹配数字
    # [)]?     : 匹配右括号（如果有）
    # $        : 强制匹配字符串的末尾
    pattern = r"\s*[(_-]\d+[)]?$"   
    cleaned = re.sub(pattern, "", adname.strip())
    return cleaned
def calccoverimgfilename(filemain):
    cover_dir = r"y:\xtrssvjj"
    # 1. 搜寻封面
    cover_imgfilenamemain=clean_filename_suffix(filemain)
    search_pattern = os.path.join(cover_dir, f"{cover_imgfilenamemain}*.jpg")    
    found_covers = glob.glob(search_pattern)
    print("search_pattern:",search_pattern)
    if found_covers:
        image_path = max(found_covers, key=os.path.getmtime)
        return image_path
    print("❌ 未找到封面图")
    print(os.path.basename(__file__))
import os

def calccoverimgfilename(filemain):
    cover_dir = r"y:\xtrssvjj"
    
    # 1. 提取视频主干名称并剥离扩展名
    base_name = os.path.basename(filemain)
    name_without_ext, _ = os.path.splitext(base_name)
    
    # 2. 如果你的 clean_filename_suffix 去掉了 (1)，那我们就用去掉后的核心名
    # 为了保险，这里直接使用原视频的名字作为核心匹配关键词
    core_keyword = name_without_ext
    
    print(f"[DEBUG_RAW] 正在绝对匹配关键词: {core_keyword}")

    try:
        # 3. 简单粗暴：直接无脑拉取目录下所有的真实文件名
        all_files = os.listdir(cover_dir)
        found_covers = []
        
        for f in all_files:
            # 4. 【核心破局点】用纯文本 in 匹配，彻底废掉 glob 的中括号正则干扰
            if core_keyword in f and f.lower().endswith('.jpg'):
                found_covers.append(os.path.join(cover_dir, f))
                
        # 5. 保持你原有的逻辑，有多张时取最新修改的
        if found_covers:
            image_path = max(found_covers, key=os.path.getmtime)
            print(f"🎯 【大捷】成功捞出封面: {image_path}")
            return image_path
            
    except Exception as e:
        print(f"❌ 目录读取失败: {e}")

    print("❌ 纯文本过滤后依然未找到封面图")
    print(os.path.basename(__file__))
    return None

import subprocess
from pathlib import Path

def create_cover_video(adname, coverimgfile):
    # 1. 预处理：标准化路径并确保绝对路径，解决特殊字符干扰
    img_abs_path = str(Path(coverimgfile).resolve())
    output_video = f"{adname}_cover.mp4"
    duration_sec = 1    

    # 2. 构建命令：遵循 [输入] -> [处理参数] -> [输出] 的优雅顺序
    cmd = [
        "ffmpeg", "-y", "-hide_banner",
        "-loop", "1", 
        "-i", f"file:{img_abs_path}",  # 优雅点1：显式 file: 协议，彻底解决 # ? 等符号问题
        "-c:v", "libx264",
        "-tune", "stillimage",
        "-t", str(duration_sec),       # 优雅点2：时长限制明确
        "-pix_fmt", "yuv420p",
        # 优雅点3：使用 scale 滤镜强制将宽度/高度变为偶数，解决 405 等奇数分辨率报错
        "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2",
        # 优雅点4：即使是封面，建议补齐静音轨，防止合并时部分播放器黑屏或无声
        "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100",
        "-c:a", "aac",
        "-b:a", "192k",
        "-shortest",
        output_video
    ]

    try:
        # 执行。注意：去掉 text=True 和 encoding，改用默认字节捕获，或者显式处理
        result = subprocess.run(cmd, capture_output=True)
        
        if result.returncode == 0:
            print(f"✅ 封面视频已生成: {output_video}")
        else:
            # 报错时，尝试用系统默认编码解码错误信息（通常是 gbk 或 utf-8）
            error_msg = result.stderr.decode('utf-8', errors='ignore')
            print(f"❌ 生成失败！错误详情：\n{error_msg}")
    except Exception as e:
        print(f"💥 脚本崩溃: {e}")
import subprocess
from pathlib import Path

def create_cover_video_perfect(adname, coverimgfile):
    # 输出文件名依然可能因为 # 出错，所以输出文件名我们用一个“绝对安全”的短名，最后再改名
    temp_output = "temp_safe_cover.mp4"
    final_output = f"{adname}_cover.mp4"
    
    # 1. 构建命令：输入改为 '-'，告诉 FFmpeg 从标准输入管道读取数据
    cmd = [
        "ffmpeg", "-y", "-hide_banner",
        "-loop", "1", 
        "-f", "image2pipe",       # 关键：指定从管道读取图片
        "-i", "-",                # 关键：从 stdin 读取
        "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100",
        "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p",
        "-c:v", "libx264",
        "-tune", "stillimage",
        "-c:a", "aac",
        "-b:a", "192k",
        "-t", "1",
        "-shortest",
        temp_output               # 先输出到一个安全的名字
    ]

    try:
        # 2. 以二进制流的形式打开图片文件
        with open(coverimgfile, 'rb') as f:
            img_data = f.read()

        # 3. 运行并注入数据
        process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate(input=img_data)

        if process.returncode == 0:
            # 4. 优雅地重命名回带 # 的中文名（os.replace 是系统原子操作，无视 FFmpeg 编码 Bug）
            import os
            if os.path.exists(final_output): os.remove(final_output)
            os.rename(temp_output, final_output)
            print(f"✅ 真正成功了：{final_output}")
        else:
            print(f"❌ 还是报错：{stderr.decode('utf-8', errors='ignore')}")
            
    except Exception as e:
        print(f"💥 崩溃: {e}")

def create_cover_video_perfect(adname, coverimgfile):
    temp_output = "temp_safe_cover.mp4"
    final_output = f"{adname}_cover.mp4"
    
    cmd = [
        "ffmpeg", "-y", "-hide_banner",
        "-loop", "1", 
        "-f", "image2pipe", 
        "-i", "-", 
        "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100",
        # --- 这里的 scale 是核心：强制 544x960 ---
        "-vf", "scale=960:544,format=yuv420p", 
        "-c:v", "libx264",
        "-tune", "stillimage",
        "-c:a", "aac",
        "-b:a", "192k",
        "-t", "1",
        "-shortest",
        temp_output
    ]

    try:
        with open(coverimgfile, 'rb') as f:
            img_data = f.read()

        process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate(input=img_data)

        if process.returncode == 0:
            import os
            # 即使文件名带 #，Python 的 rename 也是绝对安全的
            if os.path.exists(final_output): os.remove(final_output)
            os.rename(temp_output, final_output)
            print(f"✅ 完美生成 544x960 封面：{final_output}")
        else:
            print(f"❌ 报错：{stderr.decode('utf-8', errors='ignore')}")
    except Exception as e:
        print(f"💥 崩溃: {e}")

# 调用示例
import subprocess
import os
from pathlib import Path

def create_cover_video(adname, coverimgfile):
    # 1. 绝对安全的临时名与最终名
    temp_output = f"temp_{os.getpid()}.mp4" 
    final_output = f"{adname}_cover.mp4"
    
    # 2. 竖屏核心滤镜：保持比例缩放 + 居中补黑边 + 格式对齐
    # force_original_aspect_ratio=decrease 确保图能完整装进 544x960
    # pad 确保最终输出绝对是 544x960，不足处居中补黑
    video_filter = (
        "scale=544:960:force_original_aspect_ratio=decrease,"
        "pad=544:960:(ow-iw)/2:(oh-ih)/2:black,"
        "format=yuv420p"
    )

    cmd = [
        "ffmpeg", "-y", "-hide_banner",
        "-f", "image2pipe", "-i", "-", # 管道输入，无视文件名特殊符号
        "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100", # 补齐音频
        "-vf", video_filter,
        "-c:v", "libx264",
        "-tune", "stillimage",
        "-c:a", "aac",
        "-b:a", "192k",
        "-t", "1",
        "-shortest",
        temp_output
    ]

    try:
        # 3. 读入图片字节流，避开路径编码陷阱
        with open(coverimgfile, 'rb') as f:
            img_data = f.read()

        process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate(input=img_data)

        if process.returncode == 0:
            # 4. Python 原生 rename，完美处理 #、中文等特殊路径
            if os.path.exists(final_output): os.remove(final_output)
            os.rename(temp_output, final_output)
            print(f"✅ 竖屏封面(544x960)已生成: {final_output}")
        else:
            print(f"❌ 报错: {stderr.decode('utf-8', errors='ignore')}")
            
    except Exception as e:
        print(f"💥 崩溃: {e}")

# 调用
# create_vertical_cover("台积电#半导体", "pic.jpg")
import subprocess
import os

def create_cover_video(adname, coverimgfile,final_output):
    # 保持输出名逻辑，但使用临时文件绕过 FFmpeg 的 # 号 Bug
    temp_output = f"temp_task_{os.getpid()}.mp4"
    duration_sec = 1    

    # 优雅修正：
    # 1. 将 -t 1 放在 -i 之前（作为输入限制），强制图片流和音频流都只读1秒
    # 2. 移除 -shortest，改用明确的时长控制，确保 Windows 属性里显示 00:00:01
    cmd = [
        "ffmpeg", "-y", "-hide_banner",
        "-t", str(duration_sec), "-loop", "1", "-f", "image2pipe", "-i", "-", 
        "-t", str(duration_sec), "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100",
        "-vf", "scale=544:960:force_original_aspect_ratio=decrease,pad=544:960:(ow-iw)/2:(oh-ih)/2,format=yuv420p",
        "-c:v", "libx264",
        "-tune", "stillimage",
        "-c:a", "aac",
        "-b:a", "192k",
        temp_output
    ]

    try:
        with open(coverimgfile, 'rb') as f:
            img_data = f.read()

        process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate(input=img_data)

        if process.returncode == 0:
            if os.path.exists(final_output): os.remove(final_output)
            os.rename(temp_output, final_output)
            print(f"✅ {final_output} 生成成功，时长已对齐。")
            return final_output
        else:
            print(f"❌ 报错: {stderr.decode('utf-8', errors='ignore')}")            
    except Exception as e:
        print(f"💥 异常: {e}")
    return final_output
def make_bili_vd(adid,adname):
    """
    生成完整的视频流
    """
    # 配置
    db_path = r'\\ll\D\xtrssvjj\db\dpd.db'
    
    # 获取adname
    # adname = get_adname(adid, db_path)
    print(f"adname: {adname}")
    coverimgfile = calccoverimgfilename(adname)
    covervideofile = f"{adname}_cover.mp4"    
    if coverimgfile:
        covervideofile=create_cover_video(adname, coverimgfile,covervideofile)
        if os.path.exists(covervideofile):
            print('vvv 封面视频已生成')
        else:
            print('!!! 封面视频未生成 -封面文件不存在?')
    # 目录路径
    image_dir = f"{adname}_images"    
    # 检查目录是否存在
    print('chking 字幕图片目录是否ok:',image_dir)
    if not os.path.exists(image_dir):
        print(f"错误：字幕图片目录不存在: {image_dir}")
        print(f"错误：字幕图片目录不存在: {image_dir}")
        print(f"错误：字幕图片目录不存在: {image_dir}")
        return False
    
    # 获取双语时间
    bilingual_times = get_bilingual_time(adid)
    print(f"找到 {len(bilingual_times)} 句双语时间信息")
    
    if not bilingual_times:
        print("错误：未找到双语时间信息")
        return False
    
    # 创建临时目录
    with tempfile.TemporaryDirectory() as temp_dir:
        # 生成视频片段
        video_fragments = []
        
        for idx, duration_ms in bilingual_times:
            # 找到对应的图片文件
            if idx%100==0:
                print('生成各视频句段:',idx+1,"/",len(bilingual_times))
            image_file = os.path.join(image_dir, f"vertical_subtitle_{idx:03d}.png")
            
            if not os.path.exists(image_file):
                print(f"警告：图片文件不存在: {image_file}")
                continue
            
            # 转换时长为秒
            duration_sec = duration_ms / 1000
            
            # 输出文件名
            output_file = os.path.join(temp_dir, f"fragment_{idx:03d}.mp4")
            
            # 生成视频片段
            cmd = [
                "ffmpeg", "-y",
                "-loop", "1",
                "-i", image_file,
                "-c:v", "libx264",
                "-tune", "stillimage",
                "-c:a", "aac",
                "-b:a", "192k",
                "-pix_fmt", "yuv420p",
                "-t", str(duration_sec),
                "-shortest",
                output_file
            ]
            
            subprocess.run(cmd, capture_output=True)
            
            if os.path.exists(output_file):
                video_fragments.append(output_file)
                
        print(f"生成了 {len(video_fragments)} 个视频片段")
        
        if not video_fragments:
            print("错误：未生成任何视频片段")
            return False
        
        # 生成拼接文件列表
        filelist_path = os.path.join(temp_dir, "filelist.txt")
        
        with open(filelist_path, 'w', encoding='utf-8') as f:
            if os.path.exists(covervideofile):
                f.write(f"file '{os.path.abspath(covervideofile)}'\n")
            for fragment in video_fragments:
                f.write(f"file '{os.path.abspath(fragment)}'\n")
        
        # 执行拼接
        output_file = os.path.join(image_dir, f"{adname}_bilingual_video.mp4")
        cmd = [
            "ffmpeg", "-y",
            "-f", "concat",
            "-safe", "0",
            "-i", filelist_path,
            "-c", "copy",
            output_file
        ]
        
        print("开始拼接视频流...")
        result = subprocess.run(cmd, capture_output=True)
        
        if result.returncode == 0:
            print(f"拼接完成！输出文件: {output_file}")
            return True
        else:
            # 尝试解码错误信息
            try:
                error_msg = result.stderr.decode('utf-8', errors='replace')
            except:
                try:
                    error_msg = result.stderr.decode('gbk', errors='replace')
                except:
                    error_msg = str(result.stderr)
            print(f"拼接失败！错误信息: {error_msg}")
            return False

def main():
    """
    主函数
    """
    if len(sys.argv) != 2:
        print("用法: python generate_bilingual_video.py <adid>")
        print("示例: python generate_bilingual_video.py 8496")
        sys.exit(1)
    
    try:
        adid = int(sys.argv[1])
    except ValueError:
        print("错误：adid必须是数字")
        sys.exit(1)
    
    print(f"=== 双语视频流生成工具 ===")
    print(os.path.basename(__file__))    
    print(f"adid: {adid}")
    
    success = make_bili_vd(adid)
    
    if success:
        print("\n视频流生成完成！")
    else:
        print("\n视频流生成失败！")
        sys.exit(1)

def main():
    """
    主函数
    """
    if len(sys.argv) != 2:
        print("用法: python generate_bilingual_video.py <adid>")
        print("示例: python generate_bilingual_video.py 8496")
        sys.exit(1)
    
    try:
        adid = int(sys.argv[1])
    except ValueError:
        print("错误：adid必须是数字")
        sys.exit(1)
    
    print(f"=== 双语视频流生成工具 ===")
    print(os.path.basename(__file__))    
    print(f"adid: {adid}")
    
    success = make_bili_vd(adid)
    
    if success:
        print("\n视频流生成完成！")
    else:
        print("\n视频流生成失败！")
        sys.exit(1)

if __name__ == "__main__":
    main()
