


'''simple docstring'''



import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
	import jax.numpy as jnp

	from transformers.models.distilbert.modeling_flax_distilbert import (
	    FlaxDistilBertForMaskedLM,
	    FlaxDistilBertForMultipleChoice,
	    FlaxDistilBertForQuestionAnswering,
	    FlaxDistilBertForSequenceClassification,
	    FlaxDistilBertForTokenClassification,
	    FlaxDistilBertModel,
	)





class 							__UpperCamelCase				(		unittest.TestCase					):




	def __init__(   self						,				__a						,				__a=13						,				__a=7						,				__a=True						,				__a=True						,				__a=True						,				__a=True						,				__a=99						,				__a=32						,				__a=5						,				__a=4						,				__a=37						,				__a="gelu"						,				__a=0.1						,				__a=0.1						,				__a=512						,				__a=16						,				__a=2						,				__a=0.02						,				__a=4						,				):

						'''simple docstring'''





						__a			:       Optional[int]					    =  parent
						__a			:       str					    =  batch_size
						__a			:       Any					    =  seq_length
						__a			:       Union[str, Any]					    =  is_training
						__a			:       Tuple					    =  use_attention_mask
						__a			:       Tuple					    =  use_token_type_ids
						__a			:       Optional[Any]					    =  use_labels
						__a			:       Tuple					    =  vocab_size
						__a			:       Any					    =  hidden_size
						__a			:       Optional[Any]					    =  num_hidden_layers
						__a			:       Dict					    =  num_attention_heads
						__a			:       Union[str, Any]					    =  intermediate_size
						__a			:       Tuple					    =  hidden_act
						__a			:       List[str]					    =  hidden_dropout_prob
						__a			:       List[str]					    =  attention_probs_dropout_prob
						__a			:       Dict					    =  max_position_embeddings
						__a			:       Union[str, Any]					    =  type_vocab_size
						__a			:       Tuple					    =  type_sequence_label_size
						__a			:       Optional[int]					    =  initializer_range
						__a			:       str					    =  num_choices




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Optional[int]					    =  ids_tensor([self.batch_size, self.seq_length]						,				self.vocab_size							)

						__a			:       Optional[int]					    =  None
						if self.use_attention_mask:
											__a			:       Optional[Any]					    =  random_attention_mask([self.batch_size, self.seq_length]							)

						__a			:       Any					    =  DistilBertConfig(
						    vocab_size=self.vocab_size						,				dim=self.hidden_size						,				n_layers=self.num_hidden_layers						,				n_heads=self.num_attention_heads						,				hidden_dim=self.intermediate_size						,				hidden_act=self.hidden_act						,				dropout=self.hidden_dropout_prob						,				attention_dropout=self.attention_probs_dropout_prob						,				max_position_embeddings=self.max_position_embeddings						,				initializer_range=self.initializer_range						,				tie_weights_=_snake_case						,				)

						return config, input_ids, attention_mask





	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Tuple					    =  self.prepare_config_and_inputs()
						__a			:       List[str]					    =  config_and_inputs
						__a			:       Tuple					    =  {'''input_ids''': input_ids, '''attention_mask''': attention_mask}
						return config, inputs_dict





@require_flax
class 							__UpperCamelCase				(		A_		,      unittest.TestCase					):
	A_				=    (
	    (
	        FlaxDistilBertModel,
	        FlaxDistilBertForMaskedLM,
	        FlaxDistilBertForMultipleChoice,
	        FlaxDistilBertForQuestionAnswering,
	        FlaxDistilBertForSequenceClassification,
	        FlaxDistilBertForTokenClassification,
	        FlaxDistilBertForQuestionAnswering,
	    )
	    if is_flax_available()
	    else ()
	)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       int					    =  FlaxDistilBertModelTester(self							)





	@slow
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						for model_class_name in self.all_model_classes:
											__a			:       Union[str, Any]					    =  model_class_name.from_pretrained('distilbert-base-uncased'							)
											__a			:       str					    =  model(np.ones((1, 1)							)							)
											self.assertIsNotNone(_snake_case							)





@require_flax
class 							__UpperCamelCase				(		unittest.TestCase					):




	@slow
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Tuple					    =  FlaxDistilBertModel.from_pretrained('distilbert-base-uncased'							)
						__a			:       str					    =  np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]							)
						__a			:       Optional[Any]					    =  np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
						__a			:       Optional[Any]					    =  model(_snake_case						,				attention_mask=_snake_case							)[0]
						__a			:       Union[str, Any]					    =  (1, 11, 768)
						self.assertEqual(output.shape						,				_snake_case							)
						__a			:       Tuple					    =  np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]							)

						self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]						,				_snake_case						,				atol=1E-4							)							)








"""simple docstring"""







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

lowerCAmelCase_   						=   logging.get_logger(__name__)
@add_end_docstrings(A_    )
class        __A       (	A_    ):







		'''simple docstring'''





		def __init__(	self						:  List[str]			,**_snake_case						:  Dict						)					->		List[Any]:






				"""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						:  Optional[int]			,_snake_case						:  Union[str, List[str], "Image", List["Image"]]			,**_snake_case						:  int						)					->		Optional[Any]:






				"""simple docstring"""



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







		def 					UpperCAmelCase    (	self						:  Dict			,**_snake_case						:  Optional[int]						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    List[str]				=			{}
				if "candidate_labels" in kwargs:
						lowercase__   :    Any				=			kwargs['''candidate_labels''']
				if "hypothesis_template" in kwargs:
						lowercase__   :    Optional[Any]				=			kwargs['''hypothesis_template''']

				return preprocess_params, {}, {}







		def 					UpperCAmelCase    (	self						:  Optional[Any]			,_snake_case						:  Optional[int]			,_snake_case						:  Dict=None			,_snake_case						:  Union[str, Any]="This is a photo of {}."						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			load_image(_snake_case						)
				lowercase__   :    int				=			self.image_processor(images=[image]			,return_tensors=self.framework						)
				lowercase__   :    str				=			candidate_labels
				lowercase__   :    Dict				=			[hypothesis_template.format(_snake_case						) for x in candidate_labels]
				lowercase__   :    Any				=			self.tokenizer(_snake_case			,return_tensors=self.framework			,padding=_snake_case						)
				lowercase__   :    Optional[int]				=			[text_inputs]
				return inputs







		def 					UpperCAmelCase    (	self						:  Optional[Any]			,_snake_case						:  Optional[int]						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    Optional[int]				=			model_inputs.pop('''candidate_labels'''						)
				lowercase__   :    Union[str, Any]				=			model_inputs.pop('''text_inputs'''						)
				if isinstance(text_inputs[0]			,_snake_case						):
						lowercase__   :    List[str]				=			text_inputs[0]
				else:
						# Batching case.
						lowercase__   :    int				=			text_inputs[0][0]

				lowercase__   :    Tuple				=			self.model(**_snake_case			,**_snake_case						)

				lowercase__   :    Union[str, Any]				=			{
				    '''candidate_labels''': candidate_labels,
				    '''logits''': outputs.logits_per_image,
				}
				return model_outputs







		def 					UpperCAmelCase    (	self						:  Any			,_snake_case						:  Tuple						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Dict				=			model_outputs.pop('''candidate_labels'''						)
				lowercase__   :    Optional[Any]				=			model_outputs['''logits'''][0]
				if self.framework == "pt":
						lowercase__   :    Optional[int]				=			logits.softmax(dim=-1						).squeeze(-1						)
						lowercase__   :    Tuple				=			probs.tolist()
						if not isinstance(_snake_case			,_snake_case						):
								lowercase__   :    Any				=			[scores]
				elif self.framework == "tf":
						lowercase__   :    List[str]				=			stable_softmax(_snake_case			,axis=-1						)
						lowercase__   :    Optional[Any]				=			probs.numpy().tolist()
				else:
						raise ValueError(f"""Unsupported framework: {self.framework}"""						)

				lowercase__   :    Union[str, Any]				=			[
				    {'''score''': score, '''label''': candidate_label}
				    for score, candidate_label in sorted(zip(_snake_case			,_snake_case						)			,key=lambda _snake_case						: -x[0]						)
				]
				return result
