


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

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

       def     UpperCAmelCase( self   :  int     ):
            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 			_a      (    ):
     a_     :  Any				      =     load_dataset("""hf-internal-testing/fixtures_ade20k"""	,	split="""test"""			)

     a_     :  List[Any]				      =     Image.open(dataset[0]["""file"""]			)
     a_     :  List[Any]				      =     Image.open(dataset[1]["""file"""]			)

     return image, map



def 			_a      (    ):
     a_     :  str				      =     load_dataset("""hf-internal-testing/fixtures_ade20k"""	,	split="""test"""			)

     a_     :  str				      =     Image.open(dataset[0]["""file"""]			)
     a_     :  str				      =     Image.open(dataset[1]["""file"""]			)
     a_     :  List[Any]				      =     Image.open(dataset[2]["""file"""]			)
     a_     :  str				      =     Image.open(dataset[3]["""file"""]			)

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


@require_torch
@require_vision
class 	a__						(    lowerCAmelCase_    ,							unittest.TestCase     ):
       lowerCamelCase__:  Optional[int]				     =  SegformerImageProcessor if is_vision_available() else None

       def     UpperCAmelCase( self   :  Dict     ):
            a_     :  Dict				      =     SegformerImageProcessingTester(self     )

       @property
       def     UpperCAmelCase( self   :  List[str]     ):
            return self.image_processor_tester.prepare_image_processor_dict()

       def     UpperCAmelCase( self   :  Union[str, Any]     ):
            a_     :  str				      =     self.image_processing_class(**self.image_processor_dict     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""do_resize"""     )     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""size"""     )     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""do_normalize"""     )     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""image_mean"""     )     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""image_std"""     )     )
            self.assertTrue(hasattr(lowerCamelCase_   ,				"""do_reduce_labels"""     )     )

       def     UpperCAmelCase( self   :  Union[str, Any]     ):
            a_     :  Optional[int]				      =     self.image_processing_class.from_dict(self.image_processor_dict     )
            self.assertEqual(image_processor.size   ,				{"""height""": 3_0, """width""": 3_0}     )
            self.assertEqual(image_processor.do_reduce_labels   ,				lowerCamelCase_     )

            a_     :  Any				      =     self.image_processing_class.from_dict(self.image_processor_dict   ,				size=4_2   ,				reduce_labels=lowerCamelCase_     )
            self.assertEqual(image_processor.size   ,				{"""height""": 4_2, """width""": 4_2}     )
            self.assertEqual(image_processor.do_reduce_labels   ,				lowerCamelCase_     )

       def     UpperCAmelCase( self   :  List[Any]     ):
            pass

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

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

       def     UpperCAmelCase( self   :  Any     ):
            # Initialize image_processing
            a_     :  Any				      =     self.image_processing_class(**self.image_processor_dict     )
            # create random numpy tensors
            a_     :  Union[str, Any]				      =     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
            a_     :  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.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)

            # Test batched
            a_     :  Tuple				      =     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.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)

       def     UpperCAmelCase( self   :  str     ):
            # Initialize image_processing
            a_     :  Dict				      =     self.image_processing_class(**self.image_processor_dict     )
            # create random PyTorch tensors
            a_     :  List[Any]				      =     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
            a_     :  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.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)

            # Test batched
            a_     :  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.size["""height"""],
                    self.image_processor_tester.size["""width"""],
                )   ,				)

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

            # Test not batched input
            a_     :  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.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() <= 2_5_5     )

            # Test batched
            a_     :  Optional[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.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() <= 2_5_5     )

            # Test not batched input (PIL images)
            a_      ,      a_     :  Tuple				      =     prepare_semantic_single_inputs()

            a_     :  Optional[int]				      =     image_processing(lowerCamelCase_   ,				lowerCamelCase_   ,				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() <= 2_5_5     )

            # Test batched input (PIL images)
            a_      ,      a_     :  int				      =     prepare_semantic_batch_inputs()

            a_     :  str				      =     image_processing(lowerCamelCase_   ,				lowerCamelCase_   ,				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() <= 2_5_5     )

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

            a_     :  Tuple				      =     True
            a_     :  Dict				      =     image_processing(lowerCamelCase_   ,				lowerCamelCase_   ,				return_tensors="""pt"""     )
            self.assertTrue(encoding["""labels"""].min().item() >= 0     )
            self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5     )







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__lowerCamelCase   	=  {'''configuration_visual_bert''': ['''VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VisualBertConfig''']}

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __lowerCamelCase   	=  [
           '''VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''',
           '''VisualBertForMultipleChoice''',
           '''VisualBertForPreTraining''',
           '''VisualBertForQuestionAnswering''',
           '''VisualBertForRegionToPhraseAlignment''',
           '''VisualBertForVisualReasoning''',
           '''VisualBertLayer''',
           '''VisualBertModel''',
           '''VisualBertPreTrainedModel''',
       ]


if TYPE_CHECKING:
       from .configuration_visual_bert import VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, VisualBertConfig

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_visual_bert import (
                  VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
                  VisualBertForMultipleChoice,
                  VisualBertForPreTraining,
                  VisualBertForQuestionAnswering,
                  VisualBertForRegionToPhraseAlignment,
                  VisualBertForVisualReasoning,
                  VisualBertLayer,
                  VisualBertModel,
                  VisualBertPreTrainedModel,
              )


else:
       import sys

       __lowerCamelCase   	=  _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



