



from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig


lowercase_													=      logging.get_logger(__name__)

# General docstring
lowercase_													=      '''RegNetConfig'''

# Base docstring
lowercase_													=      '''facebook/regnet-y-040'''
lowercase_													=      [1, 10_88, 7, 7]

# Image classification docstring
lowercase_													=      '''facebook/regnet-y-040'''
lowercase_													=      '''tabby, tabby cat'''

lowercase_													=      [
    '''facebook/regnet-y-040''',
    # See all regnet models at https://huggingface.co/models?filter=regnet
]






class     __a			(  tf.keras.layers.Layer					):



	def __init__(    self				:     Dict					,						snake_case_				:     int					,						snake_case_				:     int = 3					,						snake_case_				:     int = 1					,						snake_case_				:     int = 1					,						snake_case_				:     Optional[str] = "relu"					,						**snake_case_				:     List[Any]					,						)->				Union[str, Any]:
						super().__init__(**snake_case_)
						# The padding and conv has been verified in
						# https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
						__lowerCAmelCase						 =tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2)
						__lowerCAmelCase						 =tf.keras.layers.ConvaD(
						    filters=snake_case_					,						kernel_size=snake_case_					,						strides=snake_case_					,						padding="""VALID"""					,						groups=snake_case_					,						use_bias=snake_case_					,						name="""convolution"""					,						)
						__lowerCAmelCase						 =tf.keras.layers.BatchNormalization(epsilon=1e-5					,						momentum=0.9					,						name="""normalization""")
						__lowerCAmelCase						 =ACTaFN[activation] if activation is not None else tf.identity



	def 		UpperCamelCase				(    self				:     Dict					,						snake_case_				:     str)->				Optional[int]:
						__lowerCAmelCase						 =self.convolution(self.padding(snake_case_))
						__lowerCAmelCase						 =self.normalization(snake_case_)
						__lowerCAmelCase						 =self.activation(snake_case_)
						return hidden_state






class     __a			(  tf.keras.layers.Layer					):



	def __init__(    self				:     Optional[Any]					,						snake_case_				:     RegNetConfig					,						**snake_case_				:     str)->				int:
						super().__init__(**snake_case_)
						__lowerCAmelCase						 =config.num_channels
						__lowerCAmelCase						 =TFRegNetConvLayer(
						    out_channels=config.embedding_size					,						kernel_size=3					,						stride=2					,						activation=config.hidden_act					,						name="""embedder"""					,						)



	def 		UpperCamelCase				(    self				:     Union[str, Any]					,						snake_case_				:     Optional[Any])->				Any:
						__lowerCAmelCase						 =shape_list(snake_case_)[1]
						if tf.executing_eagerly() and num_channels != self.num_channels:
											raise ValueError(
											    """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""")

						# When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
						# So change the input format from `NCHW` to `NHWC`.
						# shape = (batch_size, in_height, in_width, in_channels=num_channels)
						__lowerCAmelCase						 =tf.transpose(snake_case_					,						perm=(0, 2, 3, 1))
						__lowerCAmelCase						 =self.embedder(snake_case_)
						return hidden_state






class     __a			(  tf.keras.layers.Layer					):



	def __init__(    self				:     Optional[int]					,						snake_case_				:     int					,						snake_case_				:     int = 2					,						**snake_case_				:     Optional[Any])->				int:
						super().__init__(**snake_case_)
						__lowerCAmelCase						 =tf.keras.layers.ConvaD(
						    filters=snake_case_					,						kernel_size=1					,						strides=snake_case_					,						use_bias=snake_case_					,						name="""convolution""")
						__lowerCAmelCase						 =tf.keras.layers.BatchNormalization(epsilon=1e-5					,						momentum=0.9					,						name="""normalization""")



	def 		UpperCamelCase				(    self				:     Dict					,						snake_case_				:     tf.Tensor					,						snake_case_				:     bool = False)->				tf.Tensor:
						return self.normalization(self.convolution(snake_case_)					,						training=snake_case_)






class     __a			(  tf.keras.layers.Layer					):



	def __init__(    self				:     Any					,						snake_case_				:     int					,						snake_case_				:     int					,						**snake_case_				:     List[Any])->				Dict:
						super().__init__(**snake_case_)
						__lowerCAmelCase						 =tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case_					,						name="""pooler""")
						__lowerCAmelCase						 =[
						    tf.keras.layers.ConvaD(filters=snake_case_					,						kernel_size=1					,						activation="""relu"""					,						name="""attention.0"""),
						    tf.keras.layers.ConvaD(filters=snake_case_					,						kernel_size=1					,						activation="""sigmoid"""					,						name="""attention.2"""),
						]



	def 		UpperCamelCase				(    self				:     Dict					,						snake_case_				:     Union[str, Any])->				int:
						# [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels]
						__lowerCAmelCase						 =self.pooler(snake_case_)
						for layer_module in self.attention:
											__lowerCAmelCase						 =layer_module(snake_case_)
						__lowerCAmelCase						 =hidden_state * pooled
						return hidden_state






class     __a			(  tf.keras.layers.Layer					):



	def __init__(    self				:     int					,						snake_case_				:     RegNetConfig					,						snake_case_				:     int					,						snake_case_				:     int					,						snake_case_				:     int = 1					,						**snake_case_				:     Union[str, Any])->				Union[str, Any]:
						super().__init__(**snake_case_)
						__lowerCAmelCase						 =in_channels != out_channels or stride != 1
						__lowerCAmelCase						 =max(1					,						out_channels // config.groups_width)
						__lowerCAmelCase						 =(
						    TFRegNetShortCut(snake_case_					,						stride=snake_case_					,						name="""shortcut""")
						    if should_apply_shortcut
						    else tf.keras.layers.Activation("""linear"""					,						name="""shortcut""")
						)
						# `self.layers` instead of `self.layer` because that is a reserved argument.
						__lowerCAmelCase						 =[
						    TFRegNetConvLayer(snake_case_					,						kernel_size=1					,						activation=config.hidden_act					,						name="""layer.0"""),
						    TFRegNetConvLayer(
						        snake_case_					,						stride=snake_case_					,						groups=snake_case_					,						activation=config.hidden_act					,						name="""layer.1"""),
						    TFRegNetConvLayer(snake_case_					,						kernel_size=1					,						activation=snake_case_					,						name="""layer.2"""),
						]
						__lowerCAmelCase						 =ACTaFN[config.hidden_act]



	def 		UpperCamelCase				(    self				:     Tuple					,						snake_case_				:     int)->				Any:
						__lowerCAmelCase						 =hidden_state
						for layer_module in self.layers:
											__lowerCAmelCase						 =layer_module(snake_case_)
						__lowerCAmelCase						 =self.shortcut(snake_case_)
						hidden_state += residual
						__lowerCAmelCase						 =self.activation(snake_case_)
						return hidden_state






class     __a			(  tf.keras.layers.Layer					):



	def __init__(    self				:     List[Any]					,						snake_case_				:     RegNetConfig					,						snake_case_				:     int					,						snake_case_				:     int					,						snake_case_				:     int = 1					,						**snake_case_				:     Tuple)->				Optional[int]:
						super().__init__(**snake_case_)
						__lowerCAmelCase						 =in_channels != out_channels or stride != 1
						__lowerCAmelCase						 =max(1					,						out_channels // config.groups_width)
						__lowerCAmelCase						 =(
						    TFRegNetShortCut(snake_case_					,						stride=snake_case_					,						name="""shortcut""")
						    if should_apply_shortcut
						    else tf.keras.layers.Activation("""linear"""					,						name="""shortcut""")
						)
						__lowerCAmelCase						 =[
						    TFRegNetConvLayer(snake_case_					,						kernel_size=1					,						activation=config.hidden_act					,						name="""layer.0"""),
						    TFRegNetConvLayer(
						        snake_case_					,						stride=snake_case_					,						groups=snake_case_					,						activation=config.hidden_act					,						name="""layer.1"""),
						    TFRegNetSELayer(snake_case_					,						reduced_channels=int(round(in_channels / 4))					,						name="""layer.2"""),
						    TFRegNetConvLayer(snake_case_					,						kernel_size=1					,						activation=snake_case_					,						name="""layer.3"""),
						]
						__lowerCAmelCase						 =ACTaFN[config.hidden_act]



	def 		UpperCamelCase				(    self				:     int					,						snake_case_				:     Tuple)->				Optional[Any]:
						__lowerCAmelCase						 =hidden_state
						for layer_module in self.layers:
											__lowerCAmelCase						 =layer_module(snake_case_)
						__lowerCAmelCase						 =self.shortcut(snake_case_)
						hidden_state += residual
						__lowerCAmelCase						 =self.activation(snake_case_)
						return hidden_state






class     __a			(  tf.keras.layers.Layer					):



	def __init__(    self				:     Optional[int]					,						snake_case_				:     RegNetConfig					,						snake_case_				:     int					,						snake_case_				:     int					,						snake_case_				:     int = 2					,						snake_case_				:     int = 2					,						**snake_case_				:     List[Any])->				str:
						super().__init__(**snake_case_)

						__lowerCAmelCase						 =TFRegNetXLayer if config.layer_type == """x""" else TFRegNetYLayer
						__lowerCAmelCase						 =[
						    # downsampling is done in the first layer with stride of 2
						    layer(snake_case_					,						snake_case_					,						snake_case_					,						stride=snake_case_					,						name="""layers.0"""),
						    *[layer(snake_case_					,						snake_case_					,						snake_case_					,						name=F"""layers.{i+1}""") for i in range(depth - 1)],
						]



	def 		UpperCamelCase				(    self				:     int					,						snake_case_				:     str)->				Optional[Any]:
						for layer_module in self.layers:
											__lowerCAmelCase						 =layer_module(snake_case_)
						return hidden_state






class     __a			(  tf.keras.layers.Layer					):



	def __init__(    self				:     int					,						snake_case_				:     RegNetConfig					,						**snake_case_				:     Union[str, Any])->				Union[str, Any]:
						super().__init__(**snake_case_)
						__lowerCAmelCase						 =[]
						# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
						self.stages.append(
						    TFRegNetStage(
						        snake_case_					,						config.embedding_size					,						config.hidden_sizes[0]					,						stride=2 if config.downsample_in_first_stage else 1					,						depth=config.depths[0]					,						name="""stages.0"""					,						))
						__lowerCAmelCase						 =zip(config.hidden_sizes					,						config.hidden_sizes[1:])
						for i, ((in_channels, out_channels), depth) in enumerate(zip(snake_case_					,						config.depths[1:])):
											self.stages.append(TFRegNetStage(snake_case_					,						snake_case_					,						snake_case_					,						depth=snake_case_					,						name=F"""stages.{i+1}"""))



	def 		UpperCamelCase				(    self				:     Optional[Any]					,						snake_case_				:     tf.Tensor					,						snake_case_				:     bool = False					,						snake_case_				:     bool = True)->				TFBaseModelOutputWithNoAttention:
						__lowerCAmelCase						 =() if output_hidden_states else None

						for stage_module in self.stages:
											if output_hidden_states:
																__lowerCAmelCase						 =hidden_states + (hidden_state,)

											__lowerCAmelCase						 =stage_module(snake_case_)

						if output_hidden_states:
											__lowerCAmelCase						 =hidden_states + (hidden_state,)

						if not return_dict:
											return tuple(v for v in [hidden_state, hidden_states] if v is not None)

						return TFBaseModelOutputWithNoAttention(last_hidden_state=snake_case_					,						hidden_states=snake_case_)






@keras_serializable
class     __a			(  tf.keras.layers.Layer					):
	SCREAMING_SNAKE_CASE  	=							RegNetConfig



	def __init__(    self				:     Any					,						snake_case_				:     str					,						**snake_case_				:     int)->				int:
						super().__init__(**snake_case_)
						__lowerCAmelCase						 =config
						__lowerCAmelCase						 =TFRegNetEmbeddings(snake_case_					,						name="""embedder""")
						__lowerCAmelCase						 =TFRegNetEncoder(snake_case_					,						name="""encoder""")
						__lowerCAmelCase						 =tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case_					,						name="""pooler""")



	@unpack_inputs
	def 		UpperCamelCase				(    self				:     Dict					,						snake_case_				:     tf.Tensor					,						snake_case_				:     Optional[bool] = None					,						snake_case_				:     Optional[bool] = None					,						snake_case_				:     bool = False					,						)->				TFBaseModelOutputWithPoolingAndNoAttention:
						__lowerCAmelCase						 =(
						    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
						)
						__lowerCAmelCase						 =return_dict if return_dict is not None else self.config.use_return_dict

						__lowerCAmelCase						 =self.embedder(snake_case_					,						training=snake_case_)

						__lowerCAmelCase						 =self.encoder(
						    snake_case_					,						output_hidden_states=snake_case_					,						return_dict=snake_case_					,						training=snake_case_)

						__lowerCAmelCase						 =encoder_outputs[0]
						__lowerCAmelCase						 =self.pooler(snake_case_)

						# Change to NCHW output format have uniformity in the modules
						__lowerCAmelCase						 =tf.transpose(snake_case_					,						perm=(0, 3, 1, 2))
						__lowerCAmelCase						 =tf.transpose(snake_case_					,						perm=(0, 3, 1, 2))

						# Change the other hidden state outputs to NCHW as well
						if output_hidden_states:
											__lowerCAmelCase						 =tuple([tf.transpose(snake_case_					,						perm=(0, 3, 1, 2)) for h in encoder_outputs[1]])

						if not return_dict:
											return (last_hidden_state, pooled_output) + encoder_outputs[1:]

						return TFBaseModelOutputWithPoolingAndNoAttention(
						    last_hidden_state=snake_case_					,						pooler_output=snake_case_					,						hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states					,						)






class     __a			(  SCREAMING_SNAKE_CASE					):
	SCREAMING_SNAKE_CASE  	=							RegNetConfig
	SCREAMING_SNAKE_CASE  	=							"regnet"
	SCREAMING_SNAKE_CASE  	=							"pixel_values"



	@property
	def 		UpperCamelCase				(    self				:     Dict)->				Union[str, Any]:
						return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24)					,						dtype=tf.floataa)}


lowercase_													=      r'''
    Parameters:
    This model is a Tensorflow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and
    behavior.
        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
'''

lowercase_													=      r'''
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConveNextImageProcessor.__call__`] for details.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
'''






@add_start_docstrings(
    "The bare RegNet model outputting raw features without any specific head on top."						,     SCREAMING_SNAKE_CASE						,     )
class     __a			(  SCREAMING_SNAKE_CASE					):



	def __init__(    self				:     Tuple					,						snake_case_				:     RegNetConfig					,						*snake_case_				:     Any					,						**snake_case_				:     List[Any])->				Optional[int]:
						super().__init__(snake_case_					,						*snake_case_					,						**snake_case_)
						__lowerCAmelCase						 =TFRegNetMainLayer(snake_case_					,						name="""regnet""")



	@unpack_inputs
	@add_start_docstrings_to_model_forward(snake_case_)
	@add_code_sample_docstrings(
	    checkpoint=_CHECKPOINT_FOR_DOC					,						output_type=snake_case_					,						config_class=_CONFIG_FOR_DOC					,						modality="""vision"""					,						expected_output=_EXPECTED_OUTPUT_SHAPE					,						)
	def 		UpperCamelCase				(    self				:     str					,						snake_case_				:     tf.Tensor					,						snake_case_				:     Optional[bool] = None					,						snake_case_				:     Optional[bool] = None					,						snake_case_				:     List[str]=False					,						)->				Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]:
						__lowerCAmelCase						 =(
						    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
						)
						__lowerCAmelCase						 =return_dict if return_dict is not None else self.config.use_return_dict

						__lowerCAmelCase						 =self.regnet(
						    pixel_values=snake_case_					,						output_hidden_states=snake_case_					,						return_dict=snake_case_					,						training=snake_case_					,						)
						if not return_dict:
											return (outputs[0],) + outputs[1:]

						return TFBaseModelOutputWithPoolingAndNoAttention(
						    last_hidden_state=outputs.last_hidden_state					,						pooler_output=outputs.pooler_output					,						hidden_states=outputs.hidden_states					,						)






@add_start_docstrings(
    "\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "						,     SCREAMING_SNAKE_CASE						,     )
class     __a			(  SCREAMING_SNAKE_CASE						,     SCREAMING_SNAKE_CASE					):



	def __init__(    self				:     Union[str, Any]					,						snake_case_				:     RegNetConfig					,						*snake_case_				:     Dict					,						**snake_case_				:     int)->				Tuple:
						super().__init__(snake_case_					,						*snake_case_					,						**snake_case_)
						__lowerCAmelCase						 =config.num_labels
						__lowerCAmelCase						 =TFRegNetMainLayer(snake_case_					,						name="""regnet""")
						# classification head
						__lowerCAmelCase						 =[
						    tf.keras.layers.Flatten(),
						    tf.keras.layers.Dense(config.num_labels					,						name="""classifier.1""") if config.num_labels > 0 else tf.identity,
						]



	@unpack_inputs
	@add_start_docstrings_to_model_forward(snake_case_)
	@add_code_sample_docstrings(
	    checkpoint=_IMAGE_CLASS_CHECKPOINT					,						output_type=snake_case_					,						config_class=_CONFIG_FOR_DOC					,						expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT					,						)
	def 		UpperCamelCase				(    self				:     str					,						snake_case_				:     tf.Tensor = None					,						snake_case_				:     tf.Tensor = None					,						snake_case_				:     bool = None					,						snake_case_				:     bool = None					,						snake_case_				:     str=False					,						)->				Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
						__lowerCAmelCase						 =(
						    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
						)
						__lowerCAmelCase						 =return_dict if return_dict is not None else self.config.use_return_dict

						__lowerCAmelCase						 =self.regnet(
						    snake_case_					,						output_hidden_states=snake_case_					,						return_dict=snake_case_					,						training=snake_case_)

						__lowerCAmelCase						 =outputs.pooler_output if return_dict else outputs[1]

						__lowerCAmelCase						 =self.classifier[0](snake_case_)
						__lowerCAmelCase						 =self.classifier[1](snake_case_)

						__lowerCAmelCase						 =None if labels is None else self.hf_compute_loss(labels=snake_case_					,						logits=snake_case_)

						if not return_dict:
											__lowerCAmelCase						 =(logits,) + outputs[2:]
											return ((loss,) + output) if loss is not None else output

						return TFSequenceClassifierOutput(loss=snake_case_					,						logits=snake_case_					,						hidden_states=outputs.hidden_states)









import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
				from PIL import Image
else:






				class     __a			:



					@staticmethod
					def 		UpperCamelCase				(    *snake_case_				:     Any					,						**snake_case_				:     str)->				int:
										pass






@is_pipeline_test
@require_vision
class     __a			(  unittest.TestCase					):



	@require_torch
	def 		UpperCamelCase				(    self				:     Dict)->				List[str]:
						__lowerCAmelCase						 =pipeline(
						    model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""					,						)
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""a""", """b""", """c"""])

						# The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
						# python and torch versions.
						self.assertIn(
						    nested_simplify(snake_case_)					,						[
						        [{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """b"""}, {"""score""": 0.3_3_3, """label""": """c"""}],
						        [{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """c"""}, {"""score""": 0.3_3_3, """label""": """b"""}],
						    ]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""A""", """B""", """C"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						    ]					,						)



	@require_tf
	def 		UpperCamelCase				(    self				:     Dict)->				Optional[Any]:
						__lowerCAmelCase						 =pipeline(
						    model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""					,						framework="""tf""")
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""a""", """b""", """c"""])

						self.assertEqual(
						    nested_simplify(snake_case_)					,						[{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """b"""}, {"""score""": 0.3_3_3, """label""": """c"""}]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""A""", """B""", """C"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						    ]					,						)



	@slow
	@require_torch
	def 		UpperCamelCase				(    self				:     Any)->				Dict:
						__lowerCAmelCase						 =pipeline(
						    task="""zero-shot-image-classification"""					,						model="""openai/clip-vit-base-patch32"""					,						)
						# This is an image of 2 cats with remotes and no planes
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""cat""", """plane""", """remote"""])

						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        {"""score""": 0.5_1_1, """label""": """remote"""},
						        {"""score""": 0.4_8_5, """label""": """cat"""},
						        {"""score""": 0.0_0_4, """label""": """plane"""},
						    ]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""cat""", """plane""", """remote"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.5_1_1, """label""": """remote"""},
						            {"""score""": 0.4_8_5, """label""": """cat"""},
						            {"""score""": 0.0_0_4, """label""": """plane"""},
						        ],
						    ]
						    * 5					,						)



	@slow
	@require_tf
	def 		UpperCamelCase				(    self				:     Optional[int])->				int:
						__lowerCAmelCase						 =pipeline(
						    task="""zero-shot-image-classification"""					,						model="""openai/clip-vit-base-patch32"""					,						framework="""tf""")
						# This is an image of 2 cats with remotes and no planes
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""cat""", """plane""", """remote"""])
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        {"""score""": 0.5_1_1, """label""": """remote"""},
						        {"""score""": 0.4_8_5, """label""": """cat"""},
						        {"""score""": 0.0_0_4, """label""": """plane"""},
						    ]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""cat""", """plane""", """remote"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.5_1_1, """label""": """remote"""},
						            {"""score""": 0.4_8_5, """label""": """cat"""},
						            {"""score""": 0.0_0_4, """label""": """plane"""},
						        ],
						    ]
						    * 5					,						)




