import time

import openpyxl

from openpyxl.styles import PatternFill, Alignment
from split_wav import *



def trans_to_mono(wav_path):
    """
    将音频的通道数channel转换为1
    :param wav_path: str, 需要转换的音频地址
    :return: new_wav_path: str, 转换后得到的新音频地址
    """
    new_wav_path = wav_path[:-4] + "_1.wav"
    command = 'ffmpeg -i {} -ac 1 -y {}'.format(wav_path, new_wav_path)
    os.system(command)
    return new_wav_path


def concat_wav(root):
    txt_path = os.path.join(root, 'list.txt')
    with open(txt_path, 'w', encoding='utf-8') as f:
        for file_name in os.listdir(root):
            if os.path.isdir(os.path.join(root, file_name)):
                wav_path = os.path.join(root, file_name) + "/vocal.wav"
                f.write("file \'" + wav_path + "\'\n")
    output_file = os.path.join(root, 'total.wav')
    command = 'ffmpeg -f concat -safe 0 -i {} -y {}'.format(txt_path, output_file)
    os.system(command)
    return output_file


def detect_with_asr(video_path, book_path, start_time=0, end_time=-1, state=None):
    # 临时存储各种中间产物的文件夹
    tmp_root = './tmp'
    if not os.path.exists(tmp_root):
        os.mkdir(tmp_root)

    if not os.path.exists(video_path):
        print("你输入的视频地址有误，请仔细检查一下")
        return
    # 提取出视频中的音频，分割后提取出其中的人声部分并存储
    audio_path = extract_audio(video_path, tmp_root, start_time, end_time)
    # root = split_audio()
    # extrac_speech()
    #
    # # 将提取出的人声拼接，并将音频的channel调整为1
    # total_wav_path = concat_wav(root)
    # audio_path = trans_to_mono(total_wav_path)

    # xlsx中的表格名为“旁白插入位置建议”
    book_name_xlsx = book_path
    sheet_name_xlsx = "旁白插入位置建议"

    sys.path.append("./PaddlePaddle_DeepSpeech2")
    from infer_path import predict_long_audio_with_paddle
    table_head = [["起始时间", "终止时间", "字幕", '建议', '解说脚本']]
    table_content = table_head + predict_long_audio_with_paddle(audio_path, start_time, state)
    from detect_with_ocr import write_excel_xlsx
    write_excel_xlsx(book_name_xlsx, sheet_name_xlsx, table_content)
    state[0] = 1
    # 删除中间文件
    # shutil.rmtree(tmp_root)


if __name__ == '__main__':
    start_time = time.time()
    # 给定待处理的视频路径
    video_path = 'D:/heelo/zhanlang.rmvb'

    detect_with_asr(video_path, "zhanlang.xlsx", 50, 5154)
    print("处理视频 {} 需要时长为{} ".format(os.path.basename(video_path), time.time() - start_time))
