HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/aigenerator/AI-LG-backend/Ai_logo_generation/utils/validators.py
from PIL import Image
from io import BytesIO

from rest_framework.exceptions import ValidationError


def validate_image_with_tolerance(image_file, aspect_ratio_tolerance=0.05):
    try:
        image = Image.open(BytesIO(image_file))
        width, height = image.size
    except Exception as e:
        raise ValidationError(f"Invalid Image: {str(e)}")

    if height <= width:
        raise ValidationError("Image height must be greater than image width")

    ratio = height / width
    target_ratio = 4 / 3
    lower_bound = target_ratio - aspect_ratio_tolerance
    upper_bound = target_ratio + aspect_ratio_tolerance

    if not (lower_bound <= ratio <= upper_bound):
        raise ValidationError("Image must have a 4:3 aspect ratio")

    return True


def validate_hex_color_code(value):
    # Check if the hex color is valid
    if not value.startswith("#") or len(value) != 7:
        raise ValidationError("Hex color must start with '#' and be 7 characters long.")

    if not all(c in "0123456789ABCDEFabcdef" for c in value[1:]):
        raise ValidationError("Hex color must be a valid hex code.")

    return value