import cv2
import string
from PIL import Image, ImageOps, ImageEnhance
import pytesseract
from datetime import timedelta

vc = cv2.VideoCapture('asmr.mp4')

def get_frame(n):
    vc.set(cv2.CAP_PROP_POS_FRAMES, n - 1)
    _, im = vc.read()
    return im

def get_digit(image, show=False):
    crop = image[260:360, 0:150]
    crop[crop < 240] = 0
    im = Image.fromarray(crop)
    crop2 = ImageOps.invert(im)
    crop3 = ImageOps.grayscale(crop2)
    if show:
        crop3.show()
    s = pytesseract.image_to_string(crop3, config='--psm 7 --oem 0 digits')
    s = ''.join(c for c in s if c in string.digits)
    if not s:
        return crop3, 0
    return crop3, int(s)

def main():
    approx_frame_for_digit = {}
    frame_for_digit = {}

    prev_digit = 0

    for i in range(2700):
        frameno = i*25
        _, digit = get_digit(get_frame(frameno))
        ts = timedelta(seconds=i)
        # print(f"<debug>: {digit} at {ts}")
        if (digit > prev_digit):
            approx_frame_for_digit[digit] = frameno
            prev_digit = digit
            print(f"{ts}: {digit}")

    for digit, frame in approx_frame_for_digit.items():
        min_frame = frame
        for frame2 in range(frame - 24, frame):
            _, digit2 = get_digit(get_frame(frame2))
            if digit == digit2 and frame2 < min_frame:
                min_frame = frame2
        frame_for_digit[digit] = min_frame

    for digit, frame in frame_for_digit.items():
        print(f"{timedelta(seconds=frame/25)}: {digit}")

if __name__ == '__main__':
    main()
