# Copyright 2024 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingTester, ImageProcessingTestMixin


if is_vision_available():
    from PIL import Image

if is_torch_available():
    import torch


class AriaImageProcessingTester(ImageProcessingTester):
    def __init__(self, **kwargs):
        # Random test inputs kwargs
        kwargs.setdefault("max_resolution", 40)
        kwargs.setdefault("num_images", 1)

        # Image processor init kwargs
        kwargs.setdefault("max_image_size", 980)
        kwargs.setdefault("split_resolutions", [[980, 980]])
        kwargs.setdefault("split_image", True)
        kwargs.setdefault("size", {"longest_edge": 40})

        super().__init__(**kwargs)

    def expected_output_image_shape(self, images):
        return self.num_channels, self.max_image_size, self.max_image_size

    def prepare_image_inputs(
        self,
        batch_size=None,
        min_resolution=None,
        max_resolution=None,
        num_channels=None,
        num_images=None,
        size_divisor=None,
        equal_resolution=False,
        numpify=False,
        torchify=False,
    ):
        """This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True,
        or a list of PyTorch tensors if one specifies torchify=True.

        One can specify whether the images are of the same resolution or not.
        """
        batch_size = batch_size if batch_size is not None else self.batch_size
        num_images = num_images if num_images is not None else self.num_images
        # super() must be called outside list comprehension on Python <= 3.12
        prepare_images = super().prepare_image_inputs
        image_inputs = [
            prepare_images(
                batch_size=num_images,
                min_resolution=min_resolution,
                max_resolution=max_resolution,
                num_channels=num_channels,
                size_divisor=size_divisor,
                equal_resolution=equal_resolution,
                numpify=numpify,
                torchify=torchify,
            )
            for _ in range(batch_size)
        ]
        return image_inputs


@require_torch
@require_vision
class AriaImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
    image_processor_tester_class = AriaImageProcessingTester

    def test_call_numpy(self):
        for image_processing_class in self.image_processing_classes.values():
            image_processing = image_processing_class(**self.image_processor_dict)
            # create random numpy tensors
            image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
            for sample_images in image_inputs:
                for image in sample_images:
                    self.assertIsInstance(image, np.ndarray)

            # Test not batched input
            encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
            expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
            self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))

            # Test batched
            encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
            expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
            self.assertEqual(
                tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape)
            )

    def test_call_numpy_4_channels(self):
        # Aria always processes images as RGB, so it always returns images with 3 channels
        for image_processing_class in self.image_processing_classes.values():
            image_processor_dict = self.image_processor_dict
            image_processing = image_processing_class(**image_processor_dict)
            # create random numpy tensors
            image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)

            for sample_images in image_inputs:
                for image in sample_images:
                    self.assertIsInstance(image, np.ndarray)

            # Test not batched input
            encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
            expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
            self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))

            # Test batched
            encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
            expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
            self.assertEqual(
                tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape)
            )

    def test_call_pil(self):
        for image_processing_class in self.image_processing_classes.values():
            image_processing = image_processing_class(**self.image_processor_dict)
            # create random PIL images
            image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
            for images in image_inputs:
                for image in images:
                    self.assertIsInstance(image, Image.Image)

            # Test not batched input
            encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
            expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
            self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))

            # Test batched
            encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
            expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
            self.assertEqual(
                tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape)
            )

    def test_call_pytorch(self):
        for image_processing_class in self.image_processing_classes.values():
            image_processing = image_processing_class(**self.image_processor_dict)
            # create random PyTorch tensors
            image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)

            for images in image_inputs:
                for image in images:
                    self.assertIsInstance(image, torch.Tensor)

            # Test not batched input
            encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
            expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
            self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))

            # Test batched
            expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
            encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
            self.assertEqual(
                tuple(encoded_images.shape),
                (self.image_processor_tester.batch_size, *expected_output_image_shape),
            )

    def test_pad_for_patching(self):
        for backend_name, image_processing_class in self.image_processing_classes.items():
            numpify = backend_name == "pil"
            torchify = backend_name == "torchvision"
            image_processing = image_processing_class(**self.image_processor_dict)
            # Create odd-sized images
            image_input = self.image_processor_tester.prepare_image_inputs(
                batch_size=1,
                max_resolution=400,
                num_images=1,
                equal_resolution=True,
                numpify=numpify,
                torchify=torchify,
            )[0][0]
            self.assertIn(image_input.shape, [(3, 400, 400), (400, 400, 3)])

            # Both backends use channels-first internally; transpose if numpify returned HWC
            if numpify:
                image_input = image_input.transpose(2, 0, 1)

            # Test odd-width
            image_shape = (400, 601)
            encoded_images = image_processing._pad_for_patching(image_input, image_shape)
            self.assertEqual(encoded_images.shape[-2:], image_shape)

            # Test odd-height
            image_shape = (503, 400)
            encoded_images = image_processing._pad_for_patching(image_input, image_shape)
            self.assertEqual(encoded_images.shape[-2:], image_shape)

    def test_get_num_patches_without_images(self):
        for image_processing_class in self.image_processing_classes.values():
            image_processing = image_processing_class(**self.image_processor_dict)
            num_patches = image_processing.get_number_of_image_patches(height=100, width=100, images_kwargs={})
            self.assertEqual(num_patches, 1)

            num_patches = image_processing.get_number_of_image_patches(
                height=300, width=500, images_kwargs={"split_image": True}
            )
            self.assertEqual(num_patches, 1)

            # The test fixture uses split_resolutions=[[980, 980]], so best_resolution=(980,980).
            # divide_to_patches with patch_size=200 iterates range(0,980,200) -> 5 steps each dim -> 25 patches.
            num_patches = image_processing.get_number_of_image_patches(
                height=100, width=100, images_kwargs={"split_image": True, "max_image_size": 200}
            )
            self.assertEqual(num_patches, 25)

    def test_get_num_patches_ceil_matches_actual_patch_count(self):
        # Regression test for https://github.com/huggingface/transformers/issues/46728.
        # With max_image_size=980 the default split_resolutions include odd multiples of 490
        # (e.g. 490, 1470) that are not divisible by 980.  The old floor-division formula
        # returned wrong counts (as low as 0); ceil division matches what divide_to_patches
        # actually produces.
        for image_processing_class in self.image_processing_classes.values():
            # Use the full default split_resolutions so odd-multiple slots are reachable.
            image_processing = image_processing_class(**{**self.image_processor_dict, "split_resolutions": None})

            # Portrait image -> best_resolution = [490, 980] -> ceil(490/980)*ceil(980/980) = 1*1 = 1
            num_patches = image_processing.get_number_of_image_patches(
                height=300, width=600, images_kwargs={"split_image": True, "max_image_size": 980}
            )
            self.assertEqual(num_patches, 1)

            # Landscape image -> best_resolution = [980, 490] -> ceil(980/980)*ceil(490/980) = 1*1 = 1
            num_patches = image_processing.get_number_of_image_patches(
                height=600, width=300, images_kwargs={"split_image": True, "max_image_size": 980}
            )
            self.assertEqual(num_patches, 1)

            # Wide image -> best_resolution = [490, 1470] -> ceil(490/980)*ceil(1470/980) = 1*2 = 2
            num_patches = image_processing.get_number_of_image_patches(
                height=300, width=1470, images_kwargs={"split_image": True, "max_image_size": 980}
            )
            self.assertEqual(num_patches, 2)
