From e67f5f2dd76f56cf37d8ba2abad497a0d349ab59 Mon Sep 17 00:00:00 2001 From: Aroy-Art Date: Mon, 24 Feb 2025 22:26:29 +0100 Subject: [PATCH] Add: blur hash utils function --- backend/utils/hash.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/backend/utils/hash.py b/backend/utils/hash.py index 376c04a..03ae563 100644 --- a/backend/utils/hash.py +++ b/backend/utils/hash.py @@ -1,6 +1,10 @@ from blake3 import blake3 +from blurhash import encode + from tqdm.auto import tqdm +from PIL import Image + def compute_blake3_hash(data, is_file=False, logger=None): """ @@ -45,3 +49,34 @@ def compute_file_hash_blake3(file_path, logger=None): def compute_string_hash_blake3(string, logger=None): return compute_blake3_hash(string, is_file=False, logger=logger) + + +def compute_blur_hash(image_path, components_x=4, components_y=4, logger=None): + """ + Compute the BlurHash of an image. + + Args: + image_path (str): Path to the image file. + components_x (int): Number of horizontal components for BlurHash. + components_y (int): Number of vertical components for BlurHash. + logger: Optional logger for error messages. + + Returns: + str: BlurHash string or None if an error occurs. + """ + try: + with Image.open(image_path) as img: + img = img.convert("RGB") # Ensure it's in RGB mode + blur_hash = encode(img, components_x, components_y) + return blur_hash + + except Exception as e: + error_message = f"Error computing BlurHash: {e}" + + if logger: + if hasattr(logger, "style") and hasattr(logger, "stdout"): # Django command + logger.stdout.write(logger.style.WARNING(error_message)) + else: # Default to tqdm + tqdm.write(error_message) + + return None