"""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

__A  =				logging.get_logger(__name__)
@add_end_docstrings(a__		)
class  _snake_case     (					a__		):






						def __init__(       self      :			Tuple							,					**UpperCAmelCase      :			Optional[int]    ):
													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      :			Dict							,					UpperCAmelCase      :			Union[str, List[str], "Image", List["Image"]]							,					**UpperCAmelCase      :			Union[str, Any]    ):
													return super().__call__(UpperCAmelCase							,					**UpperCAmelCase    )






						def       lowerCamelCase__     (       self      :			Tuple							,					**UpperCAmelCase      :			Union[str, Any]    ):
													__lowerCamelCase					:		Optional[int]		   =     {}
													if "candidate_labels" in kwargs:
																				__lowerCamelCase					:		Dict		   =     kwargs["candidate_labels"]
													if "hypothesis_template" in kwargs:
																				__lowerCamelCase					:		List[str]		   =     kwargs["hypothesis_template"]

													return preprocess_params, {}, {}






						def       lowerCamelCase__     (       self      :			List[str]							,					UpperCAmelCase      :			Dict							,					UpperCAmelCase      :			Dict=None							,					UpperCAmelCase      :			Union[str, Any]="This is a photo of {}."    ):
													__lowerCamelCase					:		Optional[Any]		   =     load_image(UpperCAmelCase    )
													__lowerCamelCase					:		Optional[int]		   =     self.image_processor(images=[image]							,					return_tensors=self.framework    )
													__lowerCamelCase					:		str		   =     candidate_labels
													__lowerCamelCase					:		Tuple		   =     [hypothesis_template.format(UpperCAmelCase    ) for x in candidate_labels]
													__lowerCamelCase					:		Dict		   =     self.tokenizer(UpperCAmelCase							,					return_tensors=self.framework							,					padding=UpperCAmelCase    )
													__lowerCamelCase					:		Tuple		   =     [text_inputs]
													return inputs






						def       lowerCamelCase__     (       self      :			int							,					UpperCAmelCase      :			Dict    ):
													__lowerCamelCase					:		Optional[Any]		   =     model_inputs.pop("candidate_labels"    )
													__lowerCamelCase					:		Union[str, Any]		   =     model_inputs.pop("text_inputs"    )
													if isinstance(text_inputs[0]							,					UpperCAmelCase    ):
																				__lowerCamelCase					:		int		   =     text_inputs[0]
													else:
																				# Batching case.
																				__lowerCamelCase					:		Tuple		   =     text_inputs[0][0]

													__lowerCamelCase					:		Optional[Any]		   =     self.model(**UpperCAmelCase							,					**UpperCAmelCase    )

													__lowerCamelCase					:		List[str]		   =     {
													    "candidate_labels": candidate_labels,
													    "logits": outputs.logits_per_image,
													}
													return model_outputs







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

													__lowerCamelCase					:		str		   =     [
													    {"score": score, "label": candidate_label}
													    for score, candidate_label in sorted(zip(UpperCAmelCase							,					UpperCAmelCase    )							,					key=lambda UpperCAmelCase    : -x[0]    )
													]
													return result
"""simple docstring"""





import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_funnel import FunnelTokenizer


__A  =				logging.get_logger(__name__)

__A  =				{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

__A  =				[
    '''small''',
    '''small-base''',
    '''medium''',
    '''medium-base''',
    '''intermediate''',
    '''intermediate-base''',
    '''large''',
    '''large-base''',
    '''xlarge''',
    '''xlarge-base''',
]

__A  =				{
    '''vocab_file''': {
        '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt''',
        '''funnel-transformer/small-base''': '''https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt''',
        '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt''',
        '''funnel-transformer/medium-base''': (
            '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt'''
        ),
        '''funnel-transformer/intermediate''': (
            '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt'''
        ),
        '''funnel-transformer/intermediate-base''': (
            '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt'''
        ),
        '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt''',
        '''funnel-transformer/large-base''': '''https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt''',
        '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt''',
        '''funnel-transformer/xlarge-base''': (
            '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json''',
        '''funnel-transformer/small-base''': (
            '''https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json'''
        ),
        '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json''',
        '''funnel-transformer/medium-base''': (
            '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json'''
        ),
        '''funnel-transformer/intermediate''': (
            '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json'''
        ),
        '''funnel-transformer/intermediate-base''': (
            '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json'''
        ),
        '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json''',
        '''funnel-transformer/large-base''': (
            '''https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json'''
        ),
        '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json''',
        '''funnel-transformer/xlarge-base''': (
            '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json'''
        ),
    },
}
__A  =				{F"""funnel-transformer/{name}""": 512 for name in _model_names}
__A  =				{F"""funnel-transformer/{name}""": {'''do_lower_case''': True} for name in _model_names}
class  _snake_case     (					a__		):
						snake_case__			  =			VOCAB_FILES_NAMES
						snake_case__			  =			PRETRAINED_VOCAB_FILES_MAP
						snake_case__			  =			PRETRAINED_INIT_CONFIGURATION
						snake_case__			  =			FunnelTokenizer
						snake_case__			  =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						snake_case__			  =			2






						def __init__(       self      :			List[Any]							,					UpperCAmelCase      :			List[str]=None							,					UpperCAmelCase      :			Optional[int]=None							,					UpperCAmelCase      :			List[Any]=True							,					UpperCAmelCase      :			int="<unk>"							,					UpperCAmelCase      :			List[Any]="<sep>"							,					UpperCAmelCase      :			List[str]="<pad>"							,					UpperCAmelCase      :			Union[str, Any]="<cls>"							,					UpperCAmelCase      :			int="<mask>"							,					UpperCAmelCase      :			List[str]="<s>"							,					UpperCAmelCase      :			Union[str, Any]="</s>"							,					UpperCAmelCase      :			List[Any]=True							,					UpperCAmelCase      :			Tuple=True							,					UpperCAmelCase      :			int=None							,					UpperCAmelCase      :			int="##"							,					**UpperCAmelCase      :			Dict							,					):
													super().__init__(
													    UpperCAmelCase							,					tokenizer_file=UpperCAmelCase							,					do_lower_case=UpperCAmelCase							,					unk_token=UpperCAmelCase							,					sep_token=UpperCAmelCase							,					pad_token=UpperCAmelCase							,					cls_token=UpperCAmelCase							,					mask_token=UpperCAmelCase							,					bos_token=UpperCAmelCase							,					eos_token=UpperCAmelCase							,					clean_text=UpperCAmelCase							,					tokenize_chinese_chars=UpperCAmelCase							,					strip_accents=UpperCAmelCase							,					wordpieces_prefix=UpperCAmelCase							,					**UpperCAmelCase							,					)

													__lowerCamelCase					:		List[Any]		   =     json.loads(self.backend_tokenizer.normalizer.__getstate__()    )
													if (
													    normalizer_state.get("lowercase"							,					UpperCAmelCase    ) != do_lower_case
													    or normalizer_state.get("strip_accents"							,					UpperCAmelCase    ) != strip_accents
													    or normalizer_state.get("handle_chinese_chars"							,					UpperCAmelCase    ) != tokenize_chinese_chars
													):
																				__lowerCamelCase					:		Tuple		   =     getattr(UpperCAmelCase							,					normalizer_state.pop("type"    )    )
																				__lowerCamelCase					:		Optional[int]		   =     do_lower_case
																				__lowerCamelCase					:		Union[str, Any]		   =     strip_accents
																				__lowerCamelCase					:		Optional[Any]		   =     tokenize_chinese_chars
																				__lowerCamelCase					:		Optional[Any]		   =     normalizer_class(**UpperCAmelCase    )

													__lowerCamelCase					:		List[Any]		   =     do_lower_case






						def       lowerCamelCase__     (       self      :			Union[str, Any]							,					UpperCAmelCase      :			Union[str, Any]							,					UpperCAmelCase      :			Tuple=None    ):
													__lowerCamelCase					:		List[Any]		   =     [self.cls_token_id] + token_ids_a + [self.sep_token_id]

													if token_ids_a:
																				output += token_ids_a + [self.sep_token_id]

													return output






						def       lowerCamelCase__     (       self      :			Dict							,					UpperCAmelCase      :			List[int]							,					UpperCAmelCase      :			Optional[List[int]] = None    ):
													__lowerCamelCase					:		Tuple		   =     [self.sep_token_id]
													__lowerCamelCase					:		int		   =     [self.cls_token_id]
													if token_ids_a is None:
																				return len(cls    ) * [self.cls_token_type_id] + len(token_ids_a + sep    ) * [0]
													return len(cls    ) * [self.cls_token_type_id] + len(token_ids_a + sep    ) * [0] + len(token_ids_a + sep    ) * [1]







						def       lowerCamelCase__     (       self      :			Tuple							,					UpperCAmelCase      :			str							,					UpperCAmelCase      :			Optional[str] = None    ):
													__lowerCamelCase					:		List[Any]		   =     self._tokenizer.model.save(UpperCAmelCase							,					name=UpperCAmelCase    )
													return tuple(UpperCAmelCase    )