import random
import time

import cv2
import numpy as np
from paddleocr import PaddleOCR
from collections import Counter

ocr = PaddleOCR(use_angle_cls=True, lang="ch", show_log=False)


def random_int_list(start, stop, length):
    """
    在某一段区间内取n个随机数
    :param start: 随机数区间的最小值
    :param stop: 随机数区间的最大值
    :param length: 随机数个数
    :return: 随机数数组[list]
    """
    start, stop = (int(start), int(stop)) if start <= stop else (int(stop), int(start))
    length = int(abs(length)) if length else 0
    random_list = []
    while True:
        tmp = random.randint(start, stop)
        if tmp not in random_list:
            random_list.append(tmp)
        if len(random_list) == length:
            break
    return random_list


def detect_subtitle(frame):
    """
    判断画面中是否含字幕
    :param frame: 视频的某一帧画面
    :return: Ture or False
    """
    frame = frame[int(frame.shape[0] * 0.7):]
    subtitle = ocr.ocr(frame, cls=True)
    print(subtitle)
    for x in subtitle:
        position, (txt, confidence) = x
        height = position[2][1] - position[0][1]
        mid = (position[0][0] + position[1][0]) / 2
        print(height, txt)
        # 求倾斜度
        gradient = np.arctan(abs((position[1][1] - position[0][1]) / (position[1][0] - position[0][0])))
        print(gradient)
        if confidence > 0.7 and 0.4 * frame.shape[1] < mid < 0.6 * frame.shape[1] \
                and gradient < 0.1:
            return True
        else:
            continue
    return False


def detect_movie(video_path, start, end, interval):
    """
    使用整部视频进行测试，确定视频是否提供字幕
    :param video_path: 视频的地址
    :param start: 取随机帧的时间区间的开始时间
    :param interval: 取随机帧的每段区间时长，单位为秒
    :return: True or False（视频是否含字幕）
    """
    video = cv2.VideoCapture(video_path)
    fps = np.ceil(video.get(cv2.CAP_PROP_FPS))
    if start + interval * 3 > end:
        interval = int((end - start) / 3)
    start = start * fps
    interval = interval * fps
    random_number = 50
    ans = [False] * 3
    for i in range(3):
        random_list = random_int_list(start, start + interval, random_number)
        start = start + interval
        for _, random_point in enumerate(random_list):
            video.set(cv2.CAP_PROP_POS_FRAMES, float(random_point))
            if video.isOpened():
                success, frame = video.read()
                if not success:
                    break
                ans[i] = detect_subtitle(frame)
            if ans[i]:
                print(random_point)
                break
        if not ans[i]:
            print('{}-{}时间段内未检测到字幕'.format(start, start + interval))
        if i == 1 and Counter(ans).most_common(1)[0][0] is False:
            break
    video.release()
    print(ans)
    return Counter(ans).most_common(1)[0][0]


if __name__ == '__main__':
    pass
    # video_path = r'D:\heelo\hysxm.mp4'
    # start_time = time.time()
    # start = 90
    # interval = 120
    # print(detect_movie(video_path, start, interval))
    # print(time.time() - start_time)
