

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

class        _UpperCamelCase	(						unittest.TestCase	):


  """simple docstring"""





  def __init__( self					: str       ,       snake_case					: Optional[Any]       ,       snake_case					: Optional[Any]=7       ,       snake_case					: Optional[Any]=3       ,       snake_case					: List[Any]=30       ,       snake_case					: str=400       ,       snake_case					: Any=True       ,       snake_case					: List[str]=None       ,       snake_case					: Any=True       ,       snake_case					: Tuple=[0.5, 0.5, 0.5]       ,       snake_case					: List[Any]=[0.5, 0.5, 0.5]       ,       snake_case					: Dict=False       ,       )	->			List[str]:


         '''simple docstring'''





         __magic_name__			:		Dict        =     size if size is not None else {'''height''': 30, '''width''': 30}
         __magic_name__			:		Tuple        =     parent
         __magic_name__			:		Optional[Any]        =     batch_size
         __magic_name__			:		int        =     num_channels
         __magic_name__			:		Union[str, Any]        =     min_resolution
         __magic_name__			:		Optional[int]        =     max_resolution
         __magic_name__			:		List[str]        =     do_resize
         __magic_name__			:		List[Any]        =     size
         __magic_name__			:		Optional[int]        =     do_normalize
         __magic_name__			:		List[str]        =     image_mean
         __magic_name__			:		int        =     image_std
         __magic_name__			:		str        =     do_reduce_labels




  def 							_UpperCAmelCase      ( self					: Dict      )	->			List[str]:


         '''simple docstring'''





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







def       UpperCamelCase_					(     )						->     Optional[Any]:



       """simple docstring"""







       __magic_name__			:		Optional[int]        =     load_dataset('''hf-internal-testing/fixtures_ade20k'''     , split='''test'''   )

       __magic_name__			:		Tuple        =     Image.open(dataset[0]['''file''']   )
       __magic_name__			:		Any        =     Image.open(dataset[1]['''file''']   )

       return image, map







def       UpperCamelCase_					(     )						->     Any:



       """simple docstring"""







       __magic_name__			:		int        =     load_dataset('''hf-internal-testing/fixtures_ade20k'''     , split='''test'''   )

       __magic_name__			:		List[str]        =     Image.open(dataset[0]['''file''']   )
       __magic_name__			:		Tuple        =     Image.open(dataset[1]['''file''']   )
       __magic_name__			:		Tuple        =     Image.open(dataset[2]['''file''']   )
       __magic_name__			:		Dict        =     Image.open(dataset[3]['''file''']   )

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



@require_torch
@require_vision
class        _UpperCamelCase	(						lowerCamelCase__   ,				unittest.TestCase	):


  """simple docstring"""





  snake_case_        =    SegformerImageProcessor if is_vision_available() else None



  def 							_UpperCAmelCase      ( self					: Optional[Any]      )	->			str:


         '''simple docstring'''





         __magic_name__			:		int        =     SegformerImageProcessingTester(self      )



  @property
  def 							_UpperCAmelCase      ( self					: Dict      )	->			List[Any]:


         '''simple docstring'''





         return self.image_processor_tester.prepare_image_processor_dict()



  def 							_UpperCAmelCase      ( self					: Union[str, Any]      )	->			Dict:


         '''simple docstring'''





         __magic_name__			:		Dict        =     self.image_processing_class(**self.image_processor_dict      )
         self.assertTrue(hasattr(snake_case       ,       '''do_resize'''      )      )
         self.assertTrue(hasattr(snake_case       ,       '''size'''      )      )
         self.assertTrue(hasattr(snake_case       ,       '''do_normalize'''      )      )
         self.assertTrue(hasattr(snake_case       ,       '''image_mean'''      )      )
         self.assertTrue(hasattr(snake_case       ,       '''image_std'''      )      )
         self.assertTrue(hasattr(snake_case       ,       '''do_reduce_labels'''      )      )



  def 							_UpperCAmelCase      ( self					: List[Any]      )	->			Optional[int]:


         '''simple docstring'''





         __magic_name__			:		Optional[int]        =     self.image_processing_class.from_dict(self.image_processor_dict      )
         self.assertEqual(image_processor.size       ,       {'''height''': 30, '''width''': 30}      )
         self.assertEqual(image_processor.do_reduce_labels       ,       snake_case      )

         __magic_name__			:		Optional[int]        =     self.image_processing_class.from_dict(self.image_processor_dict       ,       size=42       ,       reduce_labels=snake_case      )
         self.assertEqual(image_processor.size       ,       {'''height''': 42, '''width''': 42}      )
         self.assertEqual(image_processor.do_reduce_labels       ,       snake_case      )



  def 							_UpperCAmelCase      ( self					: List[Any]      )	->			List[Any]:


         '''simple docstring'''





         pass



  def 							_UpperCAmelCase      ( self					: List[str]      )	->			List[str]:


         '''simple docstring'''





         __magic_name__			:		Union[str, Any]        =     self.image_processing_class(**self.image_processor_dict      )
         # create random PIL images
         __magic_name__			:		List[str]        =     prepare_image_inputs(self.image_processor_tester       ,       equal_resolution=snake_case      )
         for image in image_inputs:
                self.assertIsInstance(snake_case       ,       Image.Image      )

         # Test not batched input
         __magic_name__			:		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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )       ,       )

         # Test batched
         __magic_name__			:		Dict        =     image_processing(snake_case       ,       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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )       ,       )



  def 							_UpperCAmelCase      ( self					: str      )	->			Dict:


         '''simple docstring'''





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

         # Test not batched input
         __magic_name__			:		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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )       ,       )

         # Test batched
         __magic_name__			:		List[Any]        =     image_processing(snake_case       ,       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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )       ,       )



  def 							_UpperCAmelCase      ( self					: Optional[Any]      )	->			Any:


         '''simple docstring'''





         __magic_name__			:		int        =     self.image_processing_class(**self.image_processor_dict      )
         # create random PyTorch tensors
         __magic_name__			:		List[str]        =     prepare_image_inputs(self.image_processor_tester       ,       equal_resolution=snake_case       ,       torchify=snake_case      )
         for image in image_inputs:
                self.assertIsInstance(snake_case       ,       torch.Tensor      )

         # Test not batched input
         __magic_name__			:		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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )       ,       )

         # Test batched
         __magic_name__			:		Any        =     image_processing(snake_case       ,       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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )       ,       )



  def 							_UpperCAmelCase      ( self					: str      )	->			Optional[int]:


         '''simple docstring'''





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

         # Test not batched input
         __magic_name__			:		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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )       ,       )
         self.assertEqual(
             encoding['''labels'''].shape       ,       (
                 1,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.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
         __magic_name__			:		Union[str, Any]        =     image_processing(snake_case       ,       snake_case       ,       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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )       ,       )
         self.assertEqual(
             encoding['''labels'''].shape       ,       (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.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)
         __magic_name__       ,							__magic_name__			:		int        =     prepare_semantic_single_inputs()

         __magic_name__			:		int        =     image_processing(snake_case       ,       snake_case       ,       return_tensors='''pt'''      )
         self.assertEqual(
             encoding['''pixel_values'''].shape       ,       (
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )       ,       )
         self.assertEqual(
             encoding['''labels'''].shape       ,       (
                 1,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.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)
         __magic_name__       ,							__magic_name__			:		Optional[Any]        =     prepare_semantic_batch_inputs()

         __magic_name__			:		List[Any]        =     image_processing(snake_case       ,       snake_case       ,       return_tensors='''pt'''      )
         self.assertEqual(
             encoding['''pixel_values'''].shape       ,       (
                 2,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )       ,       )
         self.assertEqual(
             encoding['''labels'''].shape       ,       (
                 2,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.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					: int      )	->			List[Any]:


         '''simple docstring'''





         __magic_name__			:		List[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
         __magic_name__       ,							__magic_name__			:		Union[str, Any]        =     prepare_semantic_single_inputs()
         __magic_name__			:		Optional[Any]        =     image_processing(snake_case       ,       snake_case       ,       return_tensors='''pt'''      )
         self.assertTrue(encoding['''labels'''].min().item() >= 0      )
         self.assertTrue(encoding['''labels'''].max().item() <= 150      )

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



"""simple docstring"""
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


A									=						{
    """configuration_imagegpt""": ["""IMAGEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ImageGPTConfig""", """ImageGPTOnnxConfig"""]
}

try:
 if not is_vision_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 A									=						["""ImageGPTFeatureExtractor"""]
 A									=						["""ImageGPTImageProcessor"""]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 A									=						[
     """IMAGEGPT_PRETRAINED_MODEL_ARCHIVE_LIST""",
     """ImageGPTForCausalImageModeling""",
     """ImageGPTForImageClassification""",
     """ImageGPTModel""",
     """ImageGPTPreTrainedModel""",
     """load_tf_weights_in_imagegpt""",
 ]


if TYPE_CHECKING:
 from .configuration_imagegpt import IMAGEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ImageGPTConfig, ImageGPTOnnxConfig

 try:
  if not is_vision_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .feature_extraction_imagegpt import ImageGPTFeatureExtractor
  from .image_processing_imagegpt import ImageGPTImageProcessor

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_imagegpt import (
      IMAGEGPT_PRETRAINED_MODEL_ARCHIVE_LIST,
      ImageGPTForCausalImageModeling,
      ImageGPTForImageClassification,
      ImageGPTModel,
      ImageGPTPreTrainedModel,
      load_tf_weights_in_imagegpt,
  )

else:
 import sys

 A									=						_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
