# Copyright 2023 The Intel Team Authors, The HuggingFace Inc. team. All rights reserved.
#
# 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, prepare_video_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image


class TvpImageProcessingTester(ImageProcessingTester):
    def __init__(self, **kwargs):
        # Random test inputs kwargs
        kwargs.setdefault("fill", 0)
        kwargs.setdefault("num_frames", 2)
        kwargs.setdefault("batch_size", 2)
        kwargs.setdefault("min_resolution", 40)
        kwargs.setdefault("max_resolution", 80)

        # Image processor init kwargs
        kwargs.setdefault("crop_size", None)
        kwargs.setdefault("size", {"longest_edge": 40})
        kwargs.setdefault("do_rescale", False)
        kwargs.setdefault("do_center_crop", False)
        kwargs.setdefault("pad_size", {"height": 80, "width": 80})

        super().__init__(**kwargs)

    def expected_output_image_shape(self, images):
        return self.num_channels, self.pad_size["height"], self.pad_size["width"]

    def prepare_video_inputs(self, equal_resolution=False, numpify=False, torchify=False):
        return prepare_video_inputs(
            batch_size=self.batch_size,
            num_frames=self.num_frames,
            num_channels=self.num_channels,
            min_resolution=self.min_resolution,
            max_resolution=self.max_resolution,
            equal_resolution=equal_resolution,
            numpify=numpify,
            torchify=torchify,
        )


@require_torch
@require_vision
class TvpImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
    image_processor_tester_class = TvpImageProcessingTester

    def test_call_pil(self):
        for image_processing_class in self.image_processing_classes.values():
            # Initialize image_processing
            image_processing = image_processing_class(**self.image_processor_dict)
            # create random PIL videos
            video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False)
            for video in video_inputs:
                self.assertIsInstance(video, list)
                self.assertIsInstance(video[0], Image.Image)

            # Test not batched input
            _, expected_height, expected_width = self.image_processor_tester.expected_output_image_shape(video_inputs)
            encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values
            self.assertEqual(
                encoded_videos.shape,
                (
                    1,
                    self.image_processor_tester.num_frames,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                ),
            )

            # Test batched
            _, expected_height, expected_width = self.image_processor_tester.expected_output_image_shape(video_inputs)
            encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values
            self.assertEqual(
                encoded_videos.shape,
                (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_frames,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                ),
            )

    def test_call_numpy(self):
        # Test numpy with both processors
        for backend_name, image_processing_class in self.image_processing_classes.items():
            # Initialize image_processing
            image_processing = image_processing_class(**self.image_processor_dict)
            # create random numpy tensors
            video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, numpify=True)
            for video in video_inputs:
                self.assertIsInstance(video, list)
                self.assertIsInstance(video[0], np.ndarray)

            # For torchvision processor, convert numpy to tensor
            if backend_name == "torchvision":
                # Convert numpy arrays to tensors for torchvision processor
                tensor_video_inputs = []
                for video in video_inputs:
                    tensor_video = [torch.from_numpy(frame) for frame in video]
                    tensor_video_inputs.append(tensor_video)
                test_inputs = tensor_video_inputs
            else:  # pil
                test_inputs = video_inputs

            # Test not batched input
            _, expected_height, expected_width = self.image_processor_tester.expected_output_image_shape(video_inputs)
            encoded_videos = image_processing(test_inputs[0], return_tensors="pt").pixel_values
            self.assertListEqual(
                list(encoded_videos.shape),
                [
                    1,
                    self.image_processor_tester.num_frames,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                ],
            )

            # Test batched
            _, expected_height, expected_width = self.image_processor_tester.expected_output_image_shape(video_inputs)
            encoded_videos = image_processing(test_inputs, return_tensors="pt").pixel_values
            self.assertListEqual(
                list(encoded_videos.shape),
                [
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_frames,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                ],
            )

    def test_call_numpy_4_channels(self):
        # Test numpy with both processors
        for backend_name, image_processing_class in self.image_processing_classes.items():
            # Initialize image_processing
            image_processing = image_processing_class(**self.image_processor_dict)
            # create random numpy tensors
            video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, numpify=True)
            for video in video_inputs:
                self.assertIsInstance(video, list)
                self.assertIsInstance(video[0], np.ndarray)

            # For torchvision processor, convert numpy to tensor
            if backend_name == "torchvision":
                # Convert numpy arrays to tensors for torchvision processor
                tensor_video_inputs = []
                for video in video_inputs:
                    tensor_video = [torch.from_numpy(frame) for frame in video]
                    tensor_video_inputs.append(tensor_video)
                test_inputs = tensor_video_inputs
            else:  # pil
                test_inputs = video_inputs

            # Test not batched input
            _, expected_height, expected_width = self.image_processor_tester.expected_output_image_shape(video_inputs)
            encoded_videos = image_processing(
                test_inputs[0],
                return_tensors="pt",
                image_mean=(0.0, 0.0, 0.0),
                image_std=(1.0, 1.0, 1.0),
                input_data_format="channels_first",
            ).pixel_values
            self.assertListEqual(
                list(encoded_videos.shape),
                [
                    1,
                    self.image_processor_tester.num_frames,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                ],
            )

            # Test batched
            _, expected_height, expected_width = self.image_processor_tester.expected_output_image_shape(video_inputs)
            encoded_videos = image_processing(
                test_inputs,
                return_tensors="pt",
                image_mean=(0.0, 0.0, 0.0),
                image_std=(1.0, 1.0, 1.0),
                input_data_format="channels_first",
            ).pixel_values
            self.assertListEqual(
                list(encoded_videos.shape),
                [
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_frames,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                ],
            )
        self.image_processor_tester.num_channels = 3

    def test_call_pytorch(self):
        # Test PyTorch tensors with both processors
        for image_processing_class in self.image_processing_classes.values():
            # Initialize image_processing
            image_processing = image_processing_class(**self.image_processor_dict)
            # create random PyTorch tensors
            video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, torchify=True)
            for video in video_inputs:
                self.assertIsInstance(video, list)
                self.assertIsInstance(video[0], torch.Tensor)

            # Test not batched input
            _, expected_height, expected_width = self.image_processor_tester.expected_output_image_shape(video_inputs)
            encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values
            self.assertEqual(
                encoded_videos.shape,
                (
                    1,
                    self.image_processor_tester.num_frames,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                ),
            )

            # Test batched
            _, expected_height, expected_width = self.image_processor_tester.expected_output_image_shape(video_inputs)
            encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values
            self.assertEqual(
                encoded_videos.shape,
                (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_frames,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                ),
            )

    @require_vision
    @require_torch
    def test_backends_equivalence_batched(self):
        if len(self.image_processing_classes) < 2:
            self.skipTest(reason="Skipping backends equivalence test as there are less than 2 backends")

        dummy_images = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, torchify=True)
        image_processor_torchvision = self.image_processing_classes["torchvision"](**self.image_processor_dict)
        image_processor_pil = self.image_processing_classes["pil"](**self.image_processor_dict)

        encoding_torchvision = image_processor_torchvision(dummy_images, return_tensors="pt")
        encoding_pil = image_processor_pil(dummy_images, return_tensors="pt")
        # Higher max atol for video processing, mean_atol still 5e-3 -> 1e-1
        self._assert_tensors_equivalence(
            encoding_torchvision.pixel_values, encoding_pil.pixel_values, atol=10.0, mean_atol=1e-1
        )
