import cv2
import numpy as np


class InferenceGate:
    def __init__(self, sensitivity=0.015):
        self.last_frame = None
        self.sensitivity = sensitivity

    def is_active(self, frame):

        small = cv2.resize(frame, (160, 160))
        gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (21, 21), 0)

        if self.last_frame is None:
            self.last_frame = gray
            return True, 0

        frame_delta = cv2.absdiff(self.last_frame, gray)
        thresh = cv2.threshold(frame_delta, 25, 255, cv2.THRESH_BINARY)[1]

        change_ratio = np.count_nonzero(thresh) / thresh.size
        self.last_frame = gray

        return change_ratio > self.sensitivity, change_ratio