
'''simple docstring'''






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 			UpperCAmelCase__    (							unittest.TestCase			):



    def __init__(						self   :							Dict,__A   :							Tuple,__A   :							str=7,__A   :							Dict=3,__A   :							Any=1_8,__A   :							List[str]=3_0,__A   :							str=4_0_0,__A   :							Union[str, Any]=True,__A   :							Optional[int]=None,__A   :							List[Any]=True,__A   :							Optional[int]=None,__A   :							Dict=True,__A   :							str=[0.5, 0.5, 0.5],__A   :							Dict=[0.5, 0.5, 0.5],__A   :							Any=False,):
          _lowerCamelCase					: List[str]		    = size if size is not None else {"height": 2_0, "width": 2_0}
          _lowerCamelCase					: Union[str, Any]		    = crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
          _lowerCamelCase					: str		    = parent
          _lowerCamelCase					: int		    = batch_size
          _lowerCamelCase					: Optional[int]		    = num_channels
          _lowerCamelCase					: str		    = image_size
          _lowerCamelCase					: Tuple		    = min_resolution
          _lowerCamelCase					: List[str]		    = max_resolution
          _lowerCamelCase					: Tuple		    = do_resize
          _lowerCamelCase					: Union[str, Any]		    = size
          _lowerCamelCase					: Any		    = do_center_crop
          _lowerCamelCase					: str		    = crop_size
          _lowerCamelCase					: Dict		    = do_normalize
          _lowerCamelCase					: List[str]		    = image_mean
          _lowerCamelCase					: Dict		    = image_std
          _lowerCamelCase					: Dict		    = do_reduce_labels



    def 	lowerCamelCase_	(						self   :							Union[str, Any]  ):
          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 		A_							(						):



      """simple docstring"""




      _lowerCamelCase					: Tuple		    = load_dataset("hf-internal-testing/fixtures_ade20k"					,						split="test"				)

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

      return image, map







def 		A_							(						):



      """simple docstring"""




      _lowerCamelCase					: Optional[Any]		    = load_dataset("hf-internal-testing/fixtures_ade20k"					,						split="test"				)

      _lowerCamelCase					: Dict		    = Image.open(ds[0]["file"]				)
      _lowerCamelCase					: Dict		    = Image.open(ds[1]["file"]				)
      _lowerCamelCase					: Optional[Any]		    = Image.open(ds[2]["file"]				)
      _lowerCamelCase					: List[str]		    = Image.open(ds[3]["file"]				)

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



@require_torch
@require_vision
class 			UpperCAmelCase__    (							A    ,						unittest.TestCase			):
    lowerCAmelCase_					     =		BeitImageProcessor if is_vision_available() else None



    def 	lowerCamelCase_	(						self   :							List[Any]  ):
          _lowerCamelCase					: Tuple		    = BeitImageProcessingTester(self  )



    @property
    def 	lowerCamelCase_	(						self   :							Dict  ):
          return self.image_processor_tester.prepare_image_processor_dict()



    def 	lowerCamelCase_	(						self   :							int  ):
          _lowerCamelCase					: List[Any]		    = self.image_processing_class(**self.image_processor_dict  )
          self.assertTrue(hasattr(__A,"do_resize"  )  )
          self.assertTrue(hasattr(__A,"size"  )  )
          self.assertTrue(hasattr(__A,"do_center_crop"  )  )
          self.assertTrue(hasattr(__A,"center_crop"  )  )
          self.assertTrue(hasattr(__A,"do_normalize"  )  )
          self.assertTrue(hasattr(__A,"image_mean"  )  )
          self.assertTrue(hasattr(__A,"image_std"  )  )



    def 	lowerCamelCase_	(						self   :							Optional[Any]  ):
          _lowerCamelCase					: Optional[int]		    = self.image_processing_class.from_dict(self.image_processor_dict  )
          self.assertEqual(image_processor.size,{"height": 2_0, "width": 2_0}  )
          self.assertEqual(image_processor.crop_size,{"height": 1_8, "width": 1_8}  )
          self.assertEqual(image_processor.do_reduce_labels,__A  )

          _lowerCamelCase					: str		    = self.image_processing_class.from_dict(
              self.image_processor_dict,size=4_2,crop_size=8_4,reduce_labels=__A  )
          self.assertEqual(image_processor.size,{"height": 4_2, "width": 4_2}  )
          self.assertEqual(image_processor.crop_size,{"height": 8_4, "width": 8_4}  )
          self.assertEqual(image_processor.do_reduce_labels,__A  )



    def 	lowerCamelCase_	(						self   :							int  ):
          pass



    def 	lowerCamelCase_	(						self   :							List[Any]  ):
          # Initialize image_processing
          _lowerCamelCase					: Any		    = self.image_processing_class(**self.image_processor_dict  )
          # create random PIL images
          _lowerCamelCase					: Dict		    = prepare_image_inputs(self.image_processor_tester,equal_resolution=__A  )
          for image in image_inputs:
                self.assertIsInstance(__A,Image.Image  )

          # Test not batched input
          _lowerCamelCase					: Optional[int]		    = 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
          _lowerCamelCase					: Optional[int]		    = image_processing(__A,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 	lowerCamelCase_	(						self   :							Optional[Any]  ):
          # Initialize image_processing
          _lowerCamelCase					: Union[str, Any]		    = self.image_processing_class(**self.image_processor_dict  )
          # create random numpy tensors
          _lowerCamelCase					: Optional[Any]		    = prepare_image_inputs(self.image_processor_tester,equal_resolution=__A,numpify=__A  )
          for image in image_inputs:
                self.assertIsInstance(__A,np.ndarray  )

          # Test not batched input
          _lowerCamelCase					: Tuple		    = 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
          _lowerCamelCase					: Optional[int]		    = image_processing(__A,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 	lowerCamelCase_	(						self   :							int  ):
          # Initialize image_processing
          _lowerCamelCase					: Any		    = self.image_processing_class(**self.image_processor_dict  )
          # create random PyTorch tensors
          _lowerCamelCase					: List[str]		    = prepare_image_inputs(self.image_processor_tester,equal_resolution=__A,torchify=__A  )
          for image in image_inputs:
                self.assertIsInstance(__A,torch.Tensor  )

          # Test not batched input
          _lowerCamelCase					: Optional[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
          _lowerCamelCase					: Union[str, Any]		    = image_processing(__A,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 	lowerCamelCase_	(						self   :							Dict  ):
          # Initialize image_processing
          _lowerCamelCase					: Optional[Any]		    = self.image_processing_class(**self.image_processor_dict  )
          # create random PyTorch tensors
          _lowerCamelCase					: int		    = prepare_image_inputs(self.image_processor_tester,equal_resolution=__A,torchify=__A  )
          _lowerCamelCase					: Dict		    = []
          for image in image_inputs:
                self.assertIsInstance(__A,torch.Tensor  )
                maps.append(torch.zeros(image.shape[-2:]  ).long()  )

          # Test not batched input
          _lowerCamelCase					: Optional[Any]		    = 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() <= 2_5_5  )

          # Test batched
          _lowerCamelCase					: Tuple		    = image_processing(__A,__A,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() <= 2_5_5  )

          # Test not batched input (PIL images)
          _lowerCamelCase    ,		_lowerCamelCase					: int		    = prepare_semantic_single_inputs()

          _lowerCamelCase					: Union[str, Any]		    = image_processing(__A,__A,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() <= 2_5_5  )

          # Test batched input (PIL images)
          _lowerCamelCase    ,		_lowerCamelCase					: Tuple		    = prepare_semantic_batch_inputs()

          _lowerCamelCase					: List[str]		    = image_processing(__A,__A,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() <= 2_5_5  )



    def 	lowerCamelCase_	(						self   :							Union[str, Any]  ):
          # Initialize image_processing
          _lowerCamelCase					: Union[str, Any]		    = 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
          _lowerCamelCase    ,		_lowerCamelCase					: int		    = prepare_semantic_single_inputs()
          _lowerCamelCase					: int		    = image_processing(__A,__A,return_tensors="pt"  )
          self.assertTrue(encoding["labels"].min().item() >= 0  )
          self.assertTrue(encoding["labels"].max().item() <= 1_5_0  )

          _lowerCamelCase					: Any		    = True
          _lowerCamelCase					: List[Any]		    = image_processing(__A,__A,return_tensors="pt"  )
          self.assertTrue(encoding["labels"].min().item() >= 0  )
          self.assertTrue(encoding["labels"].max().item() <= 2_5_5  )






a__: str							   =						'0.21.0'

from .accelerator import Accelerator
from .big_modeling import (
    cpu_offload,
    cpu_offload_with_hook,
    disk_offload,
    dispatch_model,
    init_empty_weights,
    init_on_device,
    load_checkpoint_and_dispatch,
)
from .data_loader import skip_first_batches
from .launchers import debug_launcher, notebook_launcher
from .state import PartialState
from .utils import (
    DeepSpeedPlugin,
    DistributedDataParallelKwargs,
    DistributedType,
    FullyShardedDataParallelPlugin,
    GradScalerKwargs,
    InitProcessGroupKwargs,
    find_executable_batch_size,
    infer_auto_device_map,
    is_rich_available,
    load_checkpoint_in_model,
    synchronize_rng_states,
)


if is_rich_available():
       from .utils import rich





