



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







		'''simple docstring'''





		def __init__(	self						:  Optional[int]			,_snake_case						:  int			,_snake_case						:  Tuple=13			,_snake_case						:  Dict=7			,_snake_case						:  Any=True			,_snake_case						:  Optional[Any]=True			,_snake_case						:  List[Any]=True			,_snake_case						:  Optional[int]=True			,_snake_case						:  Any=99			,_snake_case						:  Dict=32			,_snake_case						:  Optional[int]=5			,_snake_case						:  List[Any]=4			,_snake_case						:  Union[str, Any]=37			,_snake_case						:  Dict="gelu"			,_snake_case						:  List[Any]=0.1			,_snake_case						:  Dict=0.1			,_snake_case						:  Optional[Any]=512			,_snake_case						:  Dict=16			,_snake_case						:  List[Any]=2			,_snake_case						:  List[Any]=0.02			,_snake_case						:  str=4			,)					->		Tuple:






				"""simple docstring"""



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







		def 					UpperCAmelCase    (	self						:  Any						)					->		str:






				"""simple docstring"""



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

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

				lowercase__   :    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						:  Tuple						)					->		Any:






				"""simple docstring"""



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





@require_flax
class        __A       (	A_     ,unittest.TestCase    ):







		'''simple docstring'''





		lowerCAmelCase			:					Dict   	=				(
		    (
		        FlaxDistilBertModel,
		        FlaxDistilBertForMaskedLM,
		        FlaxDistilBertForMultipleChoice,
		        FlaxDistilBertForQuestionAnswering,
		        FlaxDistilBertForSequenceClassification,
		        FlaxDistilBertForTokenClassification,
		        FlaxDistilBertForQuestionAnswering,
		    )
		    if is_flax_available()
		    else ()
		)







		def 					UpperCAmelCase    (	self						:  Dict						)					->		Tuple:






				"""simple docstring"""



				lowercase__   :    int				=			FlaxDistilBertModelTester(self						)







		@slow
		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		Optional[int]:






				"""simple docstring"""



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





@require_flax
class        __A       (	unittest.TestCase    ):







		'''simple docstring'''





		@slow
		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    Tuple				=			FlaxDistilBertModel.from_pretrained('''distilbert-base-uncased'''						)
				lowercase__   :    str				=			np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]						)
				lowercase__   :    Optional[Any]				=			np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]						)
				lowercase__   :    Optional[Any]				=			model(_snake_case			,attention_mask=_snake_case						)[0]
				lowercase__   :    Union[str, Any]				=			(1, 11, 768)
				self.assertEqual(output.shape			,_snake_case						)
				lowercase__   :    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
