






import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch
       from torch import nn

       from transformers import RegNetForImageClassification, RegNetModel
       from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor
class        a       :



      """simple docstring"""


      def __init__( self   :     int						, __lowercase   :     str						, __lowercase   :     Any=3						, __lowercase   :     str=32						, __lowercase   :     Tuple=3						, __lowercase   :     int=10						, __lowercase   :     Tuple=[10, 20, 30, 40]						, __lowercase   :     Tuple=[1, 1, 2, 1]						, __lowercase   :     Tuple=True						, __lowercase   :     List[str]=True						, __lowercase   :     str="relu"						, __lowercase   :     Optional[Any]=3						, __lowercase   :     List[Any]=None						, )				-> Optional[Any]:
        __UpperCAmelCase				:      Optional[int]	 =    parent
        __UpperCAmelCase				:      List[str]	 =    batch_size
        __UpperCAmelCase				:      List[str]	 =    image_size
        __UpperCAmelCase				:      Optional[Any]	 =    num_channels
        __UpperCAmelCase				:      List[Any]	 =    embeddings_size
        __UpperCAmelCase				:      Dict	 =    hidden_sizes
        __UpperCAmelCase				:      Optional[Any]	 =    depths
        __UpperCAmelCase				:      Optional[Any]	 =    is_training
        __UpperCAmelCase				:      Optional[int]	 =    use_labels
        __UpperCAmelCase				:      str	 =    hidden_act
        __UpperCAmelCase				:      Optional[int]	 =    num_labels
        __UpperCAmelCase				:      str	 =    scope
        __UpperCAmelCase				:      Dict	 =    len(__lowercase   )
      def       UpperCAmelCase ( self   :     Any   )				-> int:
        __UpperCAmelCase				:      List[str]	 =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

        __UpperCAmelCase				:      Any	 =    None
        if self.use_labels:
          __UpperCAmelCase				:      Dict	 =    ids_tensor([self.batch_size]						, self.num_labels   )

        __UpperCAmelCase				:      str	 =    self.get_config()

        return config, pixel_values, labels
      def       UpperCAmelCase ( self   :     Dict   )				-> Any:
        return RegNetConfig(
            num_channels=self.num_channels						, embeddings_size=self.embeddings_size						, hidden_sizes=self.hidden_sizes						, depths=self.depths						, hidden_act=self.hidden_act						, num_labels=self.num_labels						, )
      def       UpperCAmelCase ( self   :     Optional[int]						, __lowercase   :     Union[str, Any]						, __lowercase   :     Optional[int]						, __lowercase   :     str   )				-> str:
        __UpperCAmelCase				:      str	 =    RegNetModel(config=__lowercase   )
        model.to(__lowercase   )
        model.eval()
        __UpperCAmelCase				:      List[Any]	 =    model(__lowercase   )
        # expected last hidden states: B, C, H // 32, W // 32
        self.parent.assertEqual(
            result.last_hidden_state.shape						, (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						, )
      def       UpperCAmelCase ( self   :     List[str]						, __lowercase   :     Optional[Any]						, __lowercase   :     int						, __lowercase   :     Tuple   )				-> Optional[Any]:
        __UpperCAmelCase				:      str	 =    self.num_labels
        __UpperCAmelCase				:      Any	 =    RegNetForImageClassification(__lowercase   )
        model.to(__lowercase   )
        model.eval()
        __UpperCAmelCase				:      Optional[Any]	 =    model(__lowercase						, labels=__lowercase   )
        self.parent.assertEqual(result.logits.shape						, (self.batch_size, self.num_labels)   )




      def       UpperCAmelCase ( self   :     int   )				-> Tuple:
        __UpperCAmelCase				:      List[str]	 =    self.prepare_config_and_inputs()
        __UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase				:      Optional[int]	 =    config_and_inputs
        __UpperCAmelCase				:      Optional[int]	 =    {"""pixel_values""": pixel_values}
        return config, inputs_dict


@require_torch
class        a       (					lowercase__				,			lowercase__				,			unittest.TestCase  ):



      """simple docstring"""


      a    :					List[Any]							=      (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
      a    :					Optional[int]							=      (
          {'feature-extraction': RegNetModel, 'image-classification': RegNetForImageClassification}
          if is_torch_available()
          else {}
      )

      a    :					List[Any]							=      False
      a    :					Optional[Any]							=      False
      a    :					Tuple							=      False
      a    :					Tuple							=      False
      def       UpperCAmelCase ( self   :     Optional[Any]   )				-> Optional[Any]:
        __UpperCAmelCase				:      int	 =    RegNetModelTester(self   )
        __UpperCAmelCase				:      Dict	 =    ConfigTester(self						, config_class=__lowercase						, has_text_modality=__lowercase   )
      def       UpperCAmelCase ( self   :     int   )				-> Tuple:
        self.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()
      def       UpperCAmelCase ( self   :     Tuple   )				-> int:
        return
      @unittest.skip(reason="""RegNet does not use inputs_embeds"""   )
      def       UpperCAmelCase ( self   :     List[str]   )				-> Any:
        pass
      @unittest.skip(reason="""RegNet does not support input and output embeddings"""   )
      def       UpperCAmelCase ( self   :     Tuple   )				-> Any:
        pass
      def       UpperCAmelCase ( self   :     Dict   )				-> Optional[Any]:
        __UpperCAmelCase ,					__UpperCAmelCase				:      Tuple	 =    self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          __UpperCAmelCase				:      Dict	 =    model_class(__lowercase   )
          __UpperCAmelCase				:      Tuple	 =    inspect.signature(model.forward   )
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          __UpperCAmelCase				:      int	 =    [*signature.parameters.keys()]

          __UpperCAmelCase				:      Tuple	 =    ["""pixel_values"""]
          self.assertListEqual(arg_names[:1]						, __lowercase   )
      def       UpperCAmelCase ( self   :     str   )				-> List[Any]:
        __UpperCAmelCase				:      Tuple	 =    self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowercase   )
      def       UpperCAmelCase ( self   :     Any   )				-> List[Any]:
        __UpperCAmelCase ,					__UpperCAmelCase				:      Optional[Any]	 =    self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          __UpperCAmelCase				:      Dict	 =    model_class(config=__lowercase   )
          for name, module in model.named_modules():
            if isinstance(__lowercase						, (nn.BatchNormad, nn.GroupNorm)   ):
              self.assertTrue(
                  torch.all(module.weight == 1   )						, msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""						, )
              self.assertTrue(
                  torch.all(module.bias == 0   )						, msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""						, )
      def       UpperCAmelCase ( self   :     str   )				-> str:
        def check_hidden_states_output(__lowercase   :     List[Any]						, __lowercase   :     Union[str, Any]						, __lowercase   :     List[str]   ):
          __UpperCAmelCase				:      Dict	 =    model_class(__lowercase   )
          model.to(__lowercase   )
          model.eval()

          with torch.no_grad():
            __UpperCAmelCase				:      Any	 =    model(**self._prepare_for_class(__lowercase						, __lowercase   )   )

          __UpperCAmelCase				:      Union[str, Any]	 =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          __UpperCAmelCase				:      List[Any]	 =    self.model_tester.num_stages
          self.assertEqual(len(__lowercase   )						, expected_num_stages + 1   )

          # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
          self.assertListEqual(
              list(hidden_states[0].shape[-2:]   )						, [self.model_tester.image_size // 2, self.model_tester.image_size // 2]						, )

        __UpperCAmelCase ,					__UpperCAmelCase				:      int	 =    self.model_tester.prepare_config_and_inputs_for_common()
        __UpperCAmelCase				:      Union[str, Any]	 =    ["""basic""", """bottleneck"""]
        for model_class in self.all_model_classes:
          for layer_type in layers_type:
            __UpperCAmelCase				:      str	 =    layer_type
            __UpperCAmelCase				:      Optional[Any]	 =    True
            check_hidden_states_output(__lowercase						, __lowercase						, __lowercase   )

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            __UpperCAmelCase				:      Union[str, Any]	 =    True

            check_hidden_states_output(__lowercase						, __lowercase						, __lowercase   )
      def       UpperCAmelCase ( self   :     List[Any]   )				-> Tuple:
        __UpperCAmelCase				:      str	 =    self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__lowercase   )




      @slow
      def       UpperCAmelCase ( self   :     int   )				-> Any:
        for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          __UpperCAmelCase				:      List[str]	 =    RegNetModel.from_pretrained(__lowercase   )
          self.assertIsNotNone(__lowercase   )






def 							lowerCamelCase__ (       ):
  __UpperCAmelCase				:      List[Any]	 =    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
  return image







@require_torch
@require_vision
class        a       (					unittest.TestCase  ):



      """simple docstring"""


      @cached_property
      def       UpperCAmelCase ( self   :     Any   )				-> Union[str, Any]:
        return (
            AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )
            if is_vision_available()
            else None
        )




      @slow
      def       UpperCAmelCase ( self   :     int   )				-> List[Any]:
        __UpperCAmelCase				:      str	 =    RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   ).to(__lowercase   )

        __UpperCAmelCase				:      Any	 =    self.default_image_processor
        __UpperCAmelCase				:      Optional[int]	 =    prepare_img()
        __UpperCAmelCase				:      Optional[int]	 =    image_processor(images=__lowercase						, return_tensors="""pt"""   ).to(__lowercase   )

        # forward pass
        with torch.no_grad():
          __UpperCAmelCase				:      Any	 =    model(**__lowercase   )

        # verify the logits
        __UpperCAmelCase				:      int	 =    torch.Size((1, 1000)   )
        self.assertEqual(outputs.logits.shape						, __lowercase   )

        __UpperCAmelCase				:      Dict	 =    torch.tensor([-0.4_180, -1.5_051, -3.4_836]   ).to(__lowercase   )

        self.assertTrue(torch.allclose(outputs.logits[0, :3]						, __lowercase						, atol=1e-4   )   )








from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
						from PIL import Image

						from ..image_utils import load_image

if is_torch_available():
						from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
						from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
						from ..tf_utils import stable_softmax

SCREAMING_SNAKE_CASE:     Optional[int]									= logging.get_logger(__name__)



@add_end_docstrings(SCREAMING_SNAKE_CASE__ )
class    lowercase_		(SCREAMING_SNAKE_CASE__ ):



						def __init__(			self	:   Any					,							**snake_case__	:   str  ):

								"""simple docstring"""

								super().__init__(**snake_case__  )

								requires_backends(self					,							'vision'  )
								self.check_model_type(
								    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
								    if self.framework == 'tf'
								    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING  )



						def __call__(			self	:   str					,							snake_case__	:   Union[str, List[str], "Image", List["Image"]]					,							**snake_case__	:   Optional[Any]  ):

								"""simple docstring"""

								return super().__call__(snake_case__					,							**snake_case__  )



						def 	__a					(			self	:   str					,							**snake_case__	:   str  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							{}
								if "candidate_labels" in kwargs:
										SCREAMING_SNAKE_CASE_					      =							kwargs['candidate_labels']
								if "hypothesis_template" in kwargs:
										SCREAMING_SNAKE_CASE_					      =							kwargs['hypothesis_template']

								return preprocess_params, {}, {}



						def 	__a					(			self	:   List[str]					,							snake_case__	:   Optional[int]					,							snake_case__	:   Optional[Any]=None					,							snake_case__	:   List[str]="This is a photo of {}."  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							load_image(snake_case__  )
								SCREAMING_SNAKE_CASE_					      =							self.image_processor(images=[image]					,							return_tensors=self.framework  )
								SCREAMING_SNAKE_CASE_					      =							candidate_labels
								SCREAMING_SNAKE_CASE_					      =							[hypothesis_template.format(snake_case__  ) for x in candidate_labels]
								SCREAMING_SNAKE_CASE_					      =							self.tokenizer(snake_case__					,							return_tensors=self.framework					,							padding=snake_case__  )
								SCREAMING_SNAKE_CASE_					      =							[text_inputs]
								return inputs



						def 	__a					(			self	:   List[Any]					,							snake_case__	:   Any  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							model_inputs.pop('candidate_labels'  )
								SCREAMING_SNAKE_CASE_					      =							model_inputs.pop('text_inputs'  )
								if isinstance(text_inputs[0]					,							snake_case__  ):
										SCREAMING_SNAKE_CASE_					      =							text_inputs[0]
								else:
										# Batching case.
										SCREAMING_SNAKE_CASE_					      =							text_inputs[0][0]

								SCREAMING_SNAKE_CASE_					      =							self.model(**snake_case__					,							**snake_case__  )

								SCREAMING_SNAKE_CASE_					      =							{
								    'candidate_labels': candidate_labels,
								    'logits': outputs.logits_per_image,
								}
								return model_outputs






						def 	__a					(			self	:   List[Any]					,							snake_case__	:   Optional[Any]  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							model_outputs.pop('candidate_labels'  )
								SCREAMING_SNAKE_CASE_					      =							model_outputs['logits'][0]
								if self.framework == "pt":
										SCREAMING_SNAKE_CASE_					      =							logits.softmax(dim=-1  ).squeeze(-1  )
										SCREAMING_SNAKE_CASE_					      =							probs.tolist()
										if not isinstance(snake_case__					,							snake_case__  ):
												SCREAMING_SNAKE_CASE_					      =							[scores]
								elif self.framework == "tf":
										SCREAMING_SNAKE_CASE_					      =							stable_softmax(snake_case__					,							axis=-1  )
										SCREAMING_SNAKE_CASE_					      =							probs.numpy().tolist()
								else:
										raise ValueError(f'''Unsupported framework: {self.framework}'''  )

								SCREAMING_SNAKE_CASE_					      =							[
								    {'score': score, 'label': candidate_label}
								    for score, candidate_label in sorted(zip(snake_case__					,							snake_case__  )					,							key=lambda snake_case__  : -x[0]  )
								]
								return result