# encoding=utf8
import os.path
import argparse
import time

from judge_subtitle import detect_movie
from detect_with_asr import detect_with_asr
from detect_with_ocr import detect_with_ocr


def trans_to_seconds(timepoint):
    time_in_seconds = 0
    timepoint = timepoint.split(':')
    units = 1
    for i in range(len(timepoint) - 1, -1, -1):
        time_in_seconds += units * float(timepoint[i])
        units *= 60
    return time_in_seconds


def detect(video_path, start_time, end_time, book_path, state, subtitle=None):
    print("开始检测")
    if book_path is None:
        book_path = os.path.basename(video_path).split('.')[0] + ".xlsx"
    else:
        book_path = book_path

    start_time = trans_to_seconds(start_time)
    end_time = trans_to_seconds(end_time)

    # 根据用户的选择来确定电影是否有字幕，如果“未知”，则自动检测
    if subtitle == 0:
        has_subtitle = detect_movie(video_path, start_time, end_time, 180)
    elif subtitle == 1:
        has_subtitle = True
    else:
        has_subtitle = False

    if has_subtitle:
        detect_with_ocr(video_path, book_path, start_time, end_time, state)
    else:
        detect_with_asr(video_path, book_path, start_time, end_time, state)


if __name__ == '__main__':
    # 定义参数
    parser = argparse.ArgumentParser(description='Speech Synthesis guideness')
    parser.add_argument("--video_path", required=True, type=str, help="待处理的视频存储路径")
    parser.add_argument("--start_time", required=True, type=str, help="视频中影片除开场动画外的实际开始时间点，格式为'时:分:秒'，也可以输入对应的秒数")
    parser.add_argument("--end_time", required=True, type=str, help="视频中影片除演职表外的实际结束时间点，格式为'时:分:秒'，也可以输入对应的秒数")
    parser.add_argument("--book_path", type=str, help='旁白解说表格存储路径，包含表格名，如"D:\AddCaption\hysxm.xlsx"')

    args = parser.parse_args()

    detect(args.video_path, args.start_time, args.end_time, args.book_path)
