# Copyright 2023 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

from transformers.testing_utils import require_torch, require_vision, slow
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

    from transformers import AutoProcessor, Owlv2ForObjectDetection

if is_torch_available():
    import torch


class Owlv2ImageProcessingTester(ImageProcessingTester):
    def __init__(self, **kwargs):
        # Image processor init kwargs
        kwargs.setdefault("size", {"height": 18, "width": 18})

        super().__init__(**kwargs)


@require_torch
@require_vision
class Owlv2ImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
    image_processor_tester_class = Owlv2ImageProcessingTester

    @slow
    def test_image_processor_integration_test(self):
        for image_processing_class in self.image_processing_classes.values():
            processor = image_processing_class()

            image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
            pixel_values = processor(image, return_tensors="pt").pixel_values

            mean_value = round(pixel_values.mean().item(), 4)
            self.assertEqual(mean_value, -0.2303)

    @slow
    def test_image_processor_integration_test_resize(self):
        for backend_name in self.image_processing_classes.keys():
            checkpoint = "google/owlv2-base-patch16-ensemble"
            processor = AutoProcessor.from_pretrained(checkpoint, backend=backend_name)
            model = Owlv2ForObjectDetection.from_pretrained(checkpoint)

            image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
            text = ["cat"]
            target_size = image.size[::-1]
            expected_boxes = torch.tensor(
                [
                    [341.66656494140625, 23.38756561279297, 642.321044921875, 371.3482971191406],
                    [6.753320693969727, 51.96149826049805, 326.61810302734375, 473.12982177734375],
                ]
            )

            # single image
            inputs = processor(text=[text], images=[image], return_tensors="pt")
            with torch.no_grad():
                outputs = model(**inputs)

            results = processor.post_process_grounded_object_detection(
                outputs, threshold=0.2, target_sizes=[target_size]
            )[0]

            boxes = results["boxes"]
            torch.testing.assert_close(boxes, expected_boxes, atol=1e-1, rtol=1e-1)

            # batch of images
            inputs = processor(text=[text, text], images=[image, image], return_tensors="pt")
            with torch.no_grad():
                outputs = model(**inputs)
            results = processor.post_process_grounded_object_detection(
                outputs, threshold=0.2, target_sizes=[target_size, target_size]
            )

            for result in results:
                boxes = result["boxes"]
                torch.testing.assert_close(boxes, expected_boxes, atol=1e-1, rtol=1e-1)

    @unittest.skip(reason="OWLv2 doesn't treat 4 channel PIL and numpy consistently yet")  # FIXME Amy
    def test_call_numpy_4_channels(self):
        pass
