import cv2
import urllib
import numpy as np

class BlurryDetection:
    def __init__(self):
        # initialize the detector
        pass

    def variance_of_laplacian(self, image):
        # compute the Laplacian of the image and then return the focus
        # measure, which is simply the variance of the Laplacian
        return cv2.Laplacian(image, cv2.CV_64F).var()

    def __call__(self, img, thr=100):
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        fm = self.variance_of_laplacian(gray)

        if fm >= thr:
            return "non_blurry", fm
        else:
            return "blurry", fm


detector = BlurryDetection()


def check_blur(image_url):
    req = urllib.request.urlopen(image_url)
    arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
    img = cv2.imdecode(arr, -1)
    pred = detector(img, thr=10)
    score = pred[0]
    return score
