

import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
       from PIL import Image
else:







       class 		__magic_name__     :

          '''simple docstring'''




          @staticmethod
          def 					_UpperCAmelCase					(							*lowercase_,       **lowercase_			)				->       List[Any]:






            """simple docstring"""






            pass







@is_pipeline_test
@require_torch_or_tf
@require_vision
class 		__magic_name__     (				unittest.TestCase				):

   '''simple docstring'''




   lowerCamelCase__					:      Optional[int]        =  MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
   lowerCamelCase__					:      List[str]        =  TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING



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






     """simple docstring"""






     a__    =ImageClassificationPipeline(model=lowercase_,       image_processor=lowercase_,       top_k=2			)
     a__    =[
         Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			),
         '''http://images.cocodataset.org/val2017/000000039769.jpg''',
     ]
     return image_classifier, examples



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_			)				->       int:






     """simple docstring"""






     a__    =image_classifier('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)

     self.assertEqual(
         lowercase_,       [
             {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
             {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
         ],       )

     import datasets

     a__    =datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''',       '''image''',       split='''test'''			)

     # Accepts URL + PIL.Image + lists
     a__    =image_classifier(
         [
             Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			),
             '''http://images.cocodataset.org/val2017/000000039769.jpg''',
             # RGBA
             dataset[0]['''file'''],
             # LA
             dataset[1]['''file'''],
             # L
             dataset[2]['''file'''],
         ]			)
     self.assertEqual(
         lowercase_,       [
             [
                 {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
                 {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
             ],
             [
                 {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
                 {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
             ],
             [
                 {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
                 {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
             ],
             [
                 {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
                 {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
             ],
             [
                 {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
                 {'''score''': ANY(lowercase_			), '''label''': ANY(lowercase_			)},
             ],
         ],       )



   @require_torch
   def 					_UpperCAmelCase					(							self			)				->       Any:






     """simple docstring"""






     a__    ='''hf-internal-testing/tiny-random-vit'''
     a__    =pipeline('''image-classification''',       model=lowercase_			)

     a__    =image_classifier('''http://images.cocodataset.org/val2017/000000039769.jpg'''			)
     self.assertEqual(
         nested_simplify(lowercase_,       decimals=4			),       [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}],       )

     a__    =image_classifier(
         [
             '''http://images.cocodataset.org/val2017/000000039769.jpg''',
             '''http://images.cocodataset.org/val2017/000000039769.jpg''',
         ],       top_k=2,       )
     self.assertEqual(
         nested_simplify(lowercase_,       decimals=4			),       [
             [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}],
             [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}],
         ],       )



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






     """simple docstring"""






     a__    ='''hf-internal-testing/tiny-random-vit'''
     a__    =pipeline('''image-classification''',       model=lowercase_,       framework='''tf'''			)

     a__    =image_classifier('''http://images.cocodataset.org/val2017/000000039769.jpg'''			)
     self.assertEqual(
         nested_simplify(lowercase_,       decimals=4			),       [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}],       )

     a__    =image_classifier(
         [
             '''http://images.cocodataset.org/val2017/000000039769.jpg''',
             '''http://images.cocodataset.org/val2017/000000039769.jpg''',
         ],       top_k=2,       )
     self.assertEqual(
         nested_simplify(lowercase_,       decimals=4			),       [
             [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}],
             [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}],
         ],       )



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






     """simple docstring"""






     a__    =PreTrainedTokenizer()

     # Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
     a__    =pipeline(
         '''image-classification''',       model='''hf-internal-testing/tiny-random-vit''',       tokenizer=lowercase_			)

     self.assertIs(image_classifier.tokenizer,       lowercase_			)



   @slow
   @require_torch
   def 					_UpperCAmelCase					(							self			)				->       Any:






     """simple docstring"""






     a__    =pipeline('''image-classification''',       model='''deepmind/vision-perceiver-conv'''			)
     a__    =image_classifier('''http://images.cocodataset.org/val2017/000000039769.jpg'''			)
     self.assertEqual(
         nested_simplify(lowercase_,       decimals=4			),       [
             {'''score''': 0.4385, '''label''': '''tabby, tabby cat'''},
             {'''score''': 0.321, '''label''': '''tiger cat'''},
             {'''score''': 0.0502, '''label''': '''Egyptian cat'''},
             {'''score''': 0.0137, '''label''': '''crib, cot'''},
             {'''score''': 0.007, '''label''': '''radiator'''},
         ],       )

     a__    =pipeline('''image-classification''',       model='''deepmind/vision-perceiver-fourier'''			)
     a__    =image_classifier('''http://images.cocodataset.org/val2017/000000039769.jpg'''			)
     self.assertEqual(
         nested_simplify(lowercase_,       decimals=4			),       [
             {'''score''': 0.5658, '''label''': '''tabby, tabby cat'''},
             {'''score''': 0.1309, '''label''': '''tiger cat'''},
             {'''score''': 0.0722, '''label''': '''Egyptian cat'''},
             {'''score''': 0.0707, '''label''': '''remote control, remote'''},
             {'''score''': 0.0082, '''label''': '''computer keyboard, keypad'''},
         ],       )

     a__    =pipeline('''image-classification''',       model='''deepmind/vision-perceiver-learned'''			)
     a__    =image_classifier('''http://images.cocodataset.org/val2017/000000039769.jpg'''			)
     self.assertEqual(
         nested_simplify(lowercase_,       decimals=4			),       [
             {'''score''': 0.3022, '''label''': '''tabby, tabby cat'''},
             {'''score''': 0.2362, '''label''': '''Egyptian cat'''},
             {'''score''': 0.1856, '''label''': '''tiger cat'''},
             {'''score''': 0.0324, '''label''': '''remote control, remote'''},
             {'''score''': 0.0096, '''label''': '''quilt, comforter, comfort, puff'''},
         ],       )



import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase 	=   logging.get_logger(__name__)

lowerCamelCase 	=   {
    '''facebook/sam-vit-huge''': '''https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json''',
    '''facebook/sam-vit-large''': '''https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json''',
    '''facebook/sam-vit-base''': '''https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json''',
}







class 		__magic_name__     (				lowerCamelCase__				):

   '''simple docstring'''




   def __init__(							self,       lowercase_=256,       lowercase_=1024,       lowercase_=16,       lowercase_=16,       lowercase_=4,       lowercase_="gelu",       lowercase_=1E-6,       **lowercase_,       )				->       int:






     """simple docstring"""






     super().__init__(**lowercase_			)
     a__    =hidden_size
     a__    =image_size
     a__    =patch_size
     a__    =image_size // patch_size
     a__    =mask_input_channels
     a__    =num_point_embeddings
     a__    =hidden_act
     a__    =layer_norm_eps







class 		__magic_name__     (				lowerCamelCase__				):

   '''simple docstring'''




   def __init__(							self,       lowercase_=256,       lowercase_="relu",       lowercase_=2048,       lowercase_=2,       lowercase_=8,       lowercase_=2,       lowercase_=3,       lowercase_=3,       lowercase_=256,       lowercase_=1E-6,       **lowercase_,       )				->       int:






     """simple docstring"""






     super().__init__(**lowercase_			)
     a__    =hidden_size
     a__    =hidden_act
     a__    =mlp_dim
     a__    =num_hidden_layers
     a__    =num_attention_heads
     a__    =attention_downsample_rate
     a__    =num_multimask_outputs
     a__    =iou_head_depth
     a__    =iou_head_hidden_dim
     a__    =layer_norm_eps







class 		__magic_name__     (				lowerCamelCase__				):

   '''simple docstring'''




   def __init__(							self,       lowercase_=768,       lowercase_=256,       lowercase_=12,       lowercase_=12,       lowercase_=3,       lowercase_=1024,       lowercase_=16,       lowercase_="gelu",       lowercase_=1E-06,       lowercase_=0.0,       lowercase_=1E-10,       lowercase_=True,       lowercase_=4.0,       lowercase_=True,       lowercase_=True,       lowercase_=14,       lowercase_=[2, 5, 8, 11],       lowercase_=128,       lowercase_=None,       **lowercase_,       )				->       Union[str, Any]:






     """simple docstring"""






     super().__init__(**lowercase_			)

     a__    =hidden_size
     a__    =output_channels
     a__    =num_hidden_layers
     a__    =num_attention_heads
     a__    =num_channels
     a__    =image_size
     a__    =patch_size
     a__    =hidden_act
     a__    =layer_norm_eps
     a__    =attention_dropout
     a__    =initializer_range
     a__    =qkv_bias
     a__    =mlp_ratio
     a__    =use_abs_pos
     a__    =use_rel_pos
     a__    =window_size
     a__    =global_attn_indexes
     a__    =num_pos_feats
     a__    =int(hidden_size * mlp_ratio			) if mlp_dim is None else mlp_dim







class 		__magic_name__     (				lowerCamelCase__				):

   '''simple docstring'''




   lowerCamelCase__					:      Optional[int]        =  'sam'
   lowerCamelCase__					:      str        =  True



   def __init__(							self,       lowercase_=None,       lowercase_=None,       lowercase_=None,       lowercase_=0.02,       **lowercase_,       )				->       Tuple:






     """simple docstring"""






     super().__init__(**lowercase_			)
     a__    =vision_config if vision_config is not None else {}
     a__    =prompt_encoder_config if prompt_encoder_config is not None else {}
     a__    =mask_decoder_config if mask_decoder_config is not None else {}

     if isinstance(lowercase_,       lowercase_			):
       a__    =vision_config.to_dict()
     if isinstance(lowercase_,       lowercase_			):
       a__    =prompt_encoder_config.to_dict()
     if isinstance(lowercase_,       lowercase_			):
       a__    =mask_decoder_config.to_dict()

     a__    =SamVisionConfig(**lowercase_			)
     a__    =SamPromptEncoderConfig(**lowercase_			)
     a__    =SamMaskDecoderConfig(**lowercase_			)
     a__    =initializer_range



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






     """simple docstring"""






     a__    =copy.deepcopy(self.__dict__			)
     a__    =self.vision_config.to_dict()
     a__    =self.prompt_encoder_config.to_dict()
     a__    =self.mask_decoder_config.to_dict()
     a__    =self.__class__.model_type
     return output
