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

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





@add_end_docstrings(UpperCamelCase_)
class       lowercase__		(     UpperCamelCase_):


	def __init__( self			:       Union[str, Any]					,	**UpperCamelCase__			:       int		):





							'''simple docstring'''





							super().__init__(**UpperCamelCase__		)

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





							'''simple docstring'''





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


	def  __A ( self			:       List[Any]					,	**UpperCamelCase__			:       Dict		):





							'''simple docstring'''





							SCREAMING_SNAKE_CASE							:					Dict           =							{}
							if "candidate_labels" in kwargs:
													SCREAMING_SNAKE_CASE							:					Dict           =							kwargs['''candidate_labels''']
							if "hypothesis_template" in kwargs:
													SCREAMING_SNAKE_CASE							:					int           =							kwargs['''hypothesis_template''']

							return preprocess_params, {}, {}


	def  __A ( self			:       Tuple					,	UpperCamelCase__			:       int					,	UpperCamelCase__			:       Optional[int]=None					,	UpperCamelCase__			:       Any="This is a photo of {}."		):





							'''simple docstring'''





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


	def  __A ( self			:       Optional[Any]					,	UpperCamelCase__			:       List[Any]		):





							'''simple docstring'''





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

							SCREAMING_SNAKE_CASE							:					Any           =							self.model(**UpperCamelCase__					,	**UpperCamelCase__		)

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



	def  __A ( self			:       Dict					,	UpperCamelCase__			:       Dict		):





							'''simple docstring'''





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

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






import os
import unittest

from transformers import FunnelTokenizer, FunnelTokenizerFast
from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class       lowercase__		(     UpperCamelCase_			,							unittest.TestCase):
						UpperCamelCase_  =	FunnelTokenizer
						UpperCamelCase_  =	FunnelTokenizerFast
						UpperCamelCase_  =	True
						UpperCamelCase_  =	True


						def  __A ( self			:       Union[str, Any]		):





												'''simple docstring'''





												super().setUp()

												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							[
												    '''<unk>''',
												    '''<cls>''',
												    '''<sep>''',
												    '''want''',
												    '''##want''',
												    '''##ed''',
												    '''wa''',
												    '''un''',
												    '''runn''',
												    '''##ing''',
												    ''',''',
												    '''low''',
												    '''lowest''',
												]
												SCREAMING_SNAKE_CASE							:					List[str]           =							os.path.join(self.tmpdirname					,	VOCAB_FILES_NAMES['''vocab_file''']		)
												with open(self.vocab_file					,	'''w'''					,	encoding='''utf-8'''		) as vocab_writer:
																		vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]		)		)


						def  __A ( self			:       int					,	**UpperCamelCase__			:       List[Any]		):





												'''simple docstring'''





												return FunnelTokenizer.from_pretrained(self.tmpdirname					,	**UpperCamelCase__		)


						def  __A ( self			:       int					,	**UpperCamelCase__			:       List[Any]		):





												'''simple docstring'''





												return FunnelTokenizerFast.from_pretrained(self.tmpdirname					,	**UpperCamelCase__		)


						def  __A ( self			:       Any					,	UpperCamelCase__			:       List[str]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							'''UNwant\u00E9d,running'''
												SCREAMING_SNAKE_CASE							:					int           =							'''unwanted, running'''
												return input_text, output_text


						def  __A ( self			:       Any		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					List[Any]           =							self.tokenizer_class(self.vocab_file		)

												SCREAMING_SNAKE_CASE							:					int           =							tokenizer.tokenize('''UNwant\u00E9d,running'''		)
												self.assertListEqual(UpperCamelCase__					,	['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing''']		)
												self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__		)					,	[7, 4, 5, 10, 8, 9]		)



						def  __A ( self			:       str		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Dict           =							self.get_tokenizers(do_lower_case=UpperCamelCase__		)
												for tokenizer in tokenizers:
																		SCREAMING_SNAKE_CASE							:					int           =							tokenizer('''UNwant\u00E9d,running'''		)
																		SCREAMING_SNAKE_CASE							:					Optional[Any]           =							len(inputs['''input_ids''']		) - 1
																		self.assertListEqual(inputs['''token_type_ids''']					,	[2] + [0] * sentence_len		)

																		SCREAMING_SNAKE_CASE							:					List[Any]           =							tokenizer('''UNwant\u00E9d,running'''					,	'''UNwant\u00E9d,running'''		)
																		self.assertListEqual(inputs['''token_type_ids''']					,	[2] + [0] * sentence_len + [1] * sentence_len		)





