





# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run

import doctest
import sys
import warnings
from os.path import abspath, dirname, join

import _pytest

from transformers.testing_utils import HfDoctestModule, HfDocTestParser


# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
A__:    Optional[Any]  	=	abspath(join(dirname(__file__), '''src'''))
sys.path.insert(1, git_repo_path)

# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='''ignore''', category=FutureWarning)



def 				lowerCAmelCase_ (							A_):
    config.addinivalue_line(
        "markers"    ,"is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested")
    config.addinivalue_line(
        "markers"    ,"is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested")
    config.addinivalue_line("markers"    ,"is_pipeline_test: mark test to run only when pipelines are tested")
    config.addinivalue_line("markers"    ,"is_staging_test: mark test to run only in the staging environment")
    config.addinivalue_line("markers"    ,"accelerate_tests: mark test that require accelerate")
    config.addinivalue_line("markers"    ,"tool_tests: mark the tool tests that are run on their specific schedule")



def 				lowerCAmelCase_ (							A_):
    from transformers.testing_utils import pytest_addoption_shared

    pytest_addoption_shared(A_)



def 				lowerCAmelCase_ (							A_):
    from transformers.testing_utils import pytest_terminal_summary_main

    UpperCamelCase__:	List[str]					=     terminalreporter.config.getoption("--make-reports")
    if make_reports:
        pytest_terminal_summary_main(A_    ,id=A_)



def 				lowerCAmelCase_ (							A_    ,A_):
    # If no tests are collected, pytest exists with code 5, which makes the CI fail.
    if exitstatus == 5:
        UpperCamelCase__:	List[str]					=     0


# Doctest custom flag to ignore output.
A__:    Dict  	=	doctest.register_optionflag('''IGNORE_RESULT''')

A__:    Optional[Any]  	=	doctest.OutputChecker




class        _a    (    UpperCamelCase__):

      """simple docstring"""


      def 			UpperCAmelCase_       (		self:			str	,    __lowerCamelCase:			List[str]	,    __lowerCamelCase:			Union[str, Any]	,    __lowerCamelCase:			Tuple					):
          '''simple docstring'''


          if IGNORE_RESULT & optionflags:
              return True
          return OutputChecker.check_output(self	,    __lowerCamelCase	,    __lowerCamelCase	,    __lowerCamelCase					)
A__:    Optional[int]  	=	CustomOutputChecker
A__:    Dict  	=	HfDoctestModule




A__:    Optional[Any]  	=	HfDocTestParser








import unittest

import numpy as np
from datasets import load_dataset

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 ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import BeitImageProcessor




class        _a    (    unittest.TestCase):

      """simple docstring"""


      def __init__(		self:			Dict	,    __lowerCamelCase:			Any	,    __lowerCamelCase:			Optional[int]=7	,    __lowerCamelCase:			Any=3	,    __lowerCamelCase:			List[str]=18	,    __lowerCamelCase:			List[Any]=30	,    __lowerCamelCase:			Tuple=400	,    __lowerCamelCase:			List[str]=True	,    __lowerCamelCase:			Any=None	,    __lowerCamelCase:			int=True	,    __lowerCamelCase:			Any=None	,    __lowerCamelCase:			Dict=True	,    __lowerCamelCase:			List[Any]=[0.5, 0.5, 0.5]	,    __lowerCamelCase:			Optional[Any]=[0.5, 0.5, 0.5]	,    __lowerCamelCase:			int=False	,    ):
          '''simple docstring'''


          UpperCamelCase__:	Optional[int]					=     size if size is not None else {"height": 20, "width": 20}
          UpperCamelCase__:	List[Any]					=     crop_size if crop_size is not None else {"height": 18, "width": 18}
          UpperCamelCase__:	Optional[int]					=     parent
          UpperCamelCase__:	int					=     batch_size
          UpperCamelCase__:	int					=     num_channels
          UpperCamelCase__:	str					=     image_size
          UpperCamelCase__:	Any					=     min_resolution
          UpperCamelCase__:	Union[str, Any]					=     max_resolution
          UpperCamelCase__:	Optional[Any]					=     do_resize
          UpperCamelCase__:	Any					=     size
          UpperCamelCase__:	str					=     do_center_crop
          UpperCamelCase__:	Any					=     crop_size
          UpperCamelCase__:	Any					=     do_normalize
          UpperCamelCase__:	int					=     image_mean
          UpperCamelCase__:	Tuple					=     image_std
          UpperCamelCase__:	int					=     do_reduce_labels






      def 			UpperCAmelCase_       (		self:			Tuple					):
          '''simple docstring'''


          return {
              "do_resize": self.do_resize,
              "size": self.size,
              "do_center_crop": self.do_center_crop,
              "crop_size": self.crop_size,
              "do_normalize": self.do_normalize,
              "image_mean": self.image_mean,
              "image_std": self.image_std,
              "do_reduce_labels": self.do_reduce_labels,
          }



def 				lowerCAmelCase_ (							):
    UpperCamelCase__:	Dict					=     load_dataset("hf-internal-testing/fixtures_ade20k"    ,split="test")

    UpperCamelCase__:	Optional[Any]					=     Image.open(dataset[0]["file"])
    UpperCamelCase__:	str					=     Image.open(dataset[1]["file"])

    return image, map



def 				lowerCAmelCase_ (							):
    UpperCamelCase__:	Dict					=     load_dataset("hf-internal-testing/fixtures_ade20k"    ,split="test")

    UpperCamelCase__:	int					=     Image.open(ds[0]["file"])
    UpperCamelCase__:	int					=     Image.open(ds[1]["file"])
    UpperCamelCase__:	List[str]					=     Image.open(ds[2]["file"])
    UpperCamelCase__:	List[Any]					=     Image.open(ds[3]["file"])

    return [imagea, imagea], [mapa, mapa]




@require_torch
@require_vision
class        _a    (    UpperCamelCase__						,			unittest.TestCase):

      """simple docstring"""


      UpperCamelCase__  		=       BeitImageProcessor if is_vision_available() else None






      def 			UpperCAmelCase_       (		self:			Optional[int]					):
          '''simple docstring'''


          UpperCamelCase__:	str					=     BeitImageProcessingTester(self					)






      @property
      def 			UpperCAmelCase_       (		self:			Any					):
          '''simple docstring'''


          return self.image_processor_tester.prepare_image_processor_dict()






      def 			UpperCAmelCase_       (		self:			Dict					):
          '''simple docstring'''


          UpperCamelCase__:	int					=     self.image_processing_class(**self.image_processor_dict					)
          self.assertTrue(hasattr(__lowerCamelCase	,    "do_resize"					)					)
          self.assertTrue(hasattr(__lowerCamelCase	,    "size"					)					)
          self.assertTrue(hasattr(__lowerCamelCase	,    "do_center_crop"					)					)
          self.assertTrue(hasattr(__lowerCamelCase	,    "center_crop"					)					)
          self.assertTrue(hasattr(__lowerCamelCase	,    "do_normalize"					)					)
          self.assertTrue(hasattr(__lowerCamelCase	,    "image_mean"					)					)
          self.assertTrue(hasattr(__lowerCamelCase	,    "image_std"					)					)






      def 			UpperCAmelCase_       (		self:			Optional[int]					):
          '''simple docstring'''


          UpperCamelCase__:	Tuple					=     self.image_processing_class.from_dict(self.image_processor_dict					)
          self.assertEqual(image_processor.size	,    {"height": 20, "width": 20}					)
          self.assertEqual(image_processor.crop_size	,    {"height": 18, "width": 18}					)
          self.assertEqual(image_processor.do_reduce_labels	,    __lowerCamelCase					)

          UpperCamelCase__:	int					=     self.image_processing_class.from_dict(
              self.image_processor_dict	,    size=42	,    crop_size=84	,    reduce_labels=__lowerCamelCase					)
          self.assertEqual(image_processor.size	,    {"height": 42, "width": 42}					)
          self.assertEqual(image_processor.crop_size	,    {"height": 84, "width": 84}					)
          self.assertEqual(image_processor.do_reduce_labels	,    __lowerCamelCase					)






      def 			UpperCAmelCase_       (		self:			Tuple					):
          '''simple docstring'''


          pass






      def 			UpperCAmelCase_       (		self:			Dict					):
          '''simple docstring'''


          UpperCamelCase__:	Tuple					=     self.image_processing_class(**self.image_processor_dict					)
          # create random PIL images
          UpperCamelCase__:	Optional[Any]					=     prepare_image_inputs(self.image_processor_tester	,    equal_resolution=__lowerCamelCase					)
          for image in image_inputs:
              self.assertIsInstance(__lowerCamelCase	,    Image.Image					)

          # Test not batched input
          UpperCamelCase__:	List[Any]					=     image_processing(image_inputs[0]	,    return_tensors="pt"					).pixel_values
          self.assertEqual(
              encoded_images.shape	,    (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )

          # Test batched
          UpperCamelCase__:	str					=     image_processing(__lowerCamelCase	,    return_tensors="pt"					).pixel_values
          self.assertEqual(
              encoded_images.shape	,    (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )






      def 			UpperCAmelCase_       (		self:			Dict					):
          '''simple docstring'''


          UpperCamelCase__:	Optional[Any]					=     self.image_processing_class(**self.image_processor_dict					)
          # create random numpy tensors
          UpperCamelCase__:	List[str]					=     prepare_image_inputs(self.image_processor_tester	,    equal_resolution=__lowerCamelCase	,    numpify=__lowerCamelCase					)
          for image in image_inputs:
              self.assertIsInstance(__lowerCamelCase	,    np.ndarray					)

          # Test not batched input
          UpperCamelCase__:	Union[str, Any]					=     image_processing(image_inputs[0]	,    return_tensors="pt"					).pixel_values
          self.assertEqual(
              encoded_images.shape	,    (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )

          # Test batched
          UpperCamelCase__:	Dict					=     image_processing(__lowerCamelCase	,    return_tensors="pt"					).pixel_values
          self.assertEqual(
              encoded_images.shape	,    (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )






      def 			UpperCAmelCase_       (		self:			Union[str, Any]					):
          '''simple docstring'''


          UpperCamelCase__:	int					=     self.image_processing_class(**self.image_processor_dict					)
          # create random PyTorch tensors
          UpperCamelCase__:	int					=     prepare_image_inputs(self.image_processor_tester	,    equal_resolution=__lowerCamelCase	,    torchify=__lowerCamelCase					)
          for image in image_inputs:
              self.assertIsInstance(__lowerCamelCase	,    torch.Tensor					)

          # Test not batched input
          UpperCamelCase__:	Dict					=     image_processing(image_inputs[0]	,    return_tensors="pt"					).pixel_values
          self.assertEqual(
              encoded_images.shape	,    (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )

          # Test batched
          UpperCamelCase__:	str					=     image_processing(__lowerCamelCase	,    return_tensors="pt"					).pixel_values
          self.assertEqual(
              encoded_images.shape	,    (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )






      def 			UpperCAmelCase_       (		self:			Tuple					):
          '''simple docstring'''


          UpperCamelCase__:	Union[str, Any]					=     self.image_processing_class(**self.image_processor_dict					)
          # create random PyTorch tensors
          UpperCamelCase__:	Dict					=     prepare_image_inputs(self.image_processor_tester	,    equal_resolution=__lowerCamelCase	,    torchify=__lowerCamelCase					)
          UpperCamelCase__:	str					=     []
          for image in image_inputs:
              self.assertIsInstance(__lowerCamelCase	,    torch.Tensor					)
              maps.append(torch.zeros(image.shape[-2:]					).long()					)

          # Test not batched input
          UpperCamelCase__:	Dict					=     image_processing(image_inputs[0]	,    maps[0]	,    return_tensors="pt"					)
          self.assertEqual(
              encoding["pixel_values"].shape	,    (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )
          self.assertEqual(
              encoding["labels"].shape	,    (
                  1,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )
          self.assertEqual(encoding["labels"].dtype	,    torch.long					)
          self.assertTrue(encoding["labels"].min().item() >= 0					)
          self.assertTrue(encoding["labels"].max().item() <= 255					)

          # Test batched
          UpperCamelCase__:	Any					=     image_processing(__lowerCamelCase	,    __lowerCamelCase	,    return_tensors="pt"					)
          self.assertEqual(
              encoding["pixel_values"].shape	,    (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )
          self.assertEqual(
              encoding["labels"].shape	,    (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )
          self.assertEqual(encoding["labels"].dtype	,    torch.long					)
          self.assertTrue(encoding["labels"].min().item() >= 0					)
          self.assertTrue(encoding["labels"].max().item() <= 255					)

          # Test not batched input (PIL images)
          UpperCamelCase__				, UpperCamelCase__:	str					=     prepare_semantic_single_inputs()

          UpperCamelCase__:	Any					=     image_processing(__lowerCamelCase	,    __lowerCamelCase	,    return_tensors="pt"					)
          self.assertEqual(
              encoding["pixel_values"].shape	,    (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )
          self.assertEqual(
              encoding["labels"].shape	,    (
                  1,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )
          self.assertEqual(encoding["labels"].dtype	,    torch.long					)
          self.assertTrue(encoding["labels"].min().item() >= 0					)
          self.assertTrue(encoding["labels"].max().item() <= 255					)

          # Test batched input (PIL images)
          UpperCamelCase__				, UpperCamelCase__:	List[str]					=     prepare_semantic_batch_inputs()

          UpperCamelCase__:	Optional[int]					=     image_processing(__lowerCamelCase	,    __lowerCamelCase	,    return_tensors="pt"					)
          self.assertEqual(
              encoding["pixel_values"].shape	,    (
                  2,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )
          self.assertEqual(
              encoding["labels"].shape	,    (
                  2,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )	,    )
          self.assertEqual(encoding["labels"].dtype	,    torch.long					)
          self.assertTrue(encoding["labels"].min().item() >= 0					)
          self.assertTrue(encoding["labels"].max().item() <= 255					)






      def 			UpperCAmelCase_       (		self:			Any					):
          '''simple docstring'''


          UpperCamelCase__:	Dict					=     self.image_processing_class(**self.image_processor_dict					)

          # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
          UpperCamelCase__				, UpperCamelCase__:	Any					=     prepare_semantic_single_inputs()
          UpperCamelCase__:	int					=     image_processing(__lowerCamelCase	,    __lowerCamelCase	,    return_tensors="pt"					)
          self.assertTrue(encoding["labels"].min().item() >= 0					)
          self.assertTrue(encoding["labels"].max().item() <= 150					)

          UpperCamelCase__:	List[Any]					=     True
          UpperCamelCase__:	List[str]					=     image_processing(__lowerCamelCase	,    __lowerCamelCase	,    return_tensors="pt"					)
          self.assertTrue(encoding["labels"].min().item() >= 0					)
          self.assertTrue(encoding["labels"].max().item() <= 255					)

