# Copyright 2022 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, prepare_video_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image


class VideoMAEImageProcessingTester(ImageProcessingTester):
    def __init__(self, **kwargs):
        # Random test inputs kwargs
        kwargs.setdefault("num_frames", 10)

        # Image processor init kwargs
        kwargs.setdefault("size", {"shortest_edge": 18})
        kwargs.setdefault("crop_size", {"height": 18, "width": 18})

        super().__init__(**kwargs)

    def expected_output_image_shape(self, images):
        return self.num_frames, self.num_channels, self.crop_size["height"], self.crop_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 VideoMAEImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
    image_processor_tester_class = VideoMAEImageProcessingTester

    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
            encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values
            expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]])
            self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape))

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

    def test_call_numpy(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 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)

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

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

    def test_call_numpy_4_channels(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 numpy tensors
            self.image_processor_tester.num_channels = 4
            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)

            # Test not batched input
            encoded_videos = image_processing(
                video_inputs[0],
                return_tensors="pt",
                image_mean=(0.0, 0.0, 0.0, 0.0),
                image_std=(1.0, 1.0, 1.0, 1.0),
                input_data_format="channels_first",
            ).pixel_values
            expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]])
            self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape))

            # Test batched
            encoded_videos = image_processing(
                video_inputs,
                return_tensors="pt",
                image_mean=(0.0, 0.0, 0.0, 0.0),
                image_std=(1.0, 1.0, 1.0, 1.0),
                input_data_format="channels_first",
            ).pixel_values
            expected_output_video_shape = self.image_processor_tester.expected_output_image_shape(encoded_videos)
            self.assertEqual(
                tuple(encoded_videos.shape), (self.image_processor_tester.batch_size, *expected_output_video_shape)
            )
            self.image_processor_tester.num_channels = 3

    def test_call_pytorch(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 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
            encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values
            expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]])
            self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape))

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

    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")

        video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=True, torchify=True)

        encodings = {}
        for backend_name, image_processing_class in self.image_processing_classes.items():
            image_processor = image_processing_class(**self.image_processor_dict)
            encodings[backend_name] = image_processor(video_inputs, return_tensors="pt")

        backend_names = list(encodings.keys())
        reference_backend = backend_names[0]
        reference_encoding = encodings[reference_backend].pixel_values
        for backend_name in backend_names[1:]:
            self._assert_tensors_equivalence(reference_encoding, encodings[backend_name].pixel_values)
