from blake3 import blake3 from tqdm.auto import tqdm def compute_blake3_hash(data, is_file=False, logger=None): """ Compute BLAKE3 hash of a file or string. Args: data (str): File path (if is_file=True) or raw string. is_file (bool): Whether the input is a file path. Defaults to False. logger: Optional logger for error messages (e.g., Django `self` or `tqdm`). Returns: str: BLAKE3 hash or None if an error occurs. """ try: hasher = blake3() if is_file: with open(data, "rb") as f: while chunk := f.read(65536): hasher.update(chunk) else: hasher.update(data.encode()) return hasher.hexdigest() except Exception as e: error_message = f"Error computing hash: {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 # Convenience wrappers for readability def compute_file_hash_blake3(file_path, logger=None): return compute_blake3_hash(file_path, is_file=True, logger=logger) def compute_string_hash_blake3(string, logger=None): return compute_blake3_hash(string, is_file=False, logger=logger)