






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


lowerCamelCase     :							Dict    =logging.get_logger(__name__)

lowerCamelCase     :							Union[str, Any]    ={'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

lowerCamelCase     :							int    =[
    '''small''',
    '''small-base''',
    '''medium''',
    '''medium-base''',
    '''intermediate''',
    '''intermediate-base''',
    '''large''',
    '''large-base''',
    '''xlarge''',
    '''xlarge-base''',
]

lowerCamelCase     :							Dict    ={
    '''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'''
        ),
    },
}
lowerCamelCase     :							str    ={F"""funnel-transformer/{name}""": 512 for name in _model_names}
lowerCamelCase     :							int    ={F"""funnel-transformer/{name}""": {'''do_lower_case''': True} for name in _model_names}





class       __a  (   A__	):
 _lowerCAmelCase	:	Union[str, Any]				=			VOCAB_FILES_NAMES
 _lowerCAmelCase	:	Optional[int]				=			PRETRAINED_VOCAB_FILES_MAP
 _lowerCAmelCase	:	List[str]				=			PRETRAINED_INIT_CONFIGURATION
 _lowerCAmelCase	:	Optional[int]				=			FunnelTokenizer
 _lowerCAmelCase	:	Optional[Any]				=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _lowerCAmelCase	:	int				=			2







 def __init__(		self :       Union[str, Any]							,       SCREAMING_SNAKE_CASE :       Tuple=None							,       SCREAMING_SNAKE_CASE :       Union[str, Any]=None							,       SCREAMING_SNAKE_CASE :       Any=True							,       SCREAMING_SNAKE_CASE :       Dict="<unk>"							,       SCREAMING_SNAKE_CASE :       str="<sep>"							,       SCREAMING_SNAKE_CASE :       Union[str, Any]="<pad>"							,       SCREAMING_SNAKE_CASE :       Any="<cls>"							,       SCREAMING_SNAKE_CASE :       List[Any]="<mask>"							,       SCREAMING_SNAKE_CASE :       List[str]="<s>"							,       SCREAMING_SNAKE_CASE :       Tuple="</s>"							,       SCREAMING_SNAKE_CASE :       List[Any]=True							,       SCREAMING_SNAKE_CASE :       List[str]=True							,       SCREAMING_SNAKE_CASE :       Optional[Any]=None							,       SCREAMING_SNAKE_CASE :       Optional[Any]="##"							,       **SCREAMING_SNAKE_CASE :       Optional[Any]							,       ):


      '''simple docstring'''






      super().__init__(
          SCREAMING_SNAKE_CASE							,       tokenizer_file=SCREAMING_SNAKE_CASE							,       do_lower_case=SCREAMING_SNAKE_CASE							,       unk_token=SCREAMING_SNAKE_CASE							,       sep_token=SCREAMING_SNAKE_CASE							,       pad_token=SCREAMING_SNAKE_CASE							,       cls_token=SCREAMING_SNAKE_CASE							,       mask_token=SCREAMING_SNAKE_CASE							,       bos_token=SCREAMING_SNAKE_CASE							,       eos_token=SCREAMING_SNAKE_CASE							,       clean_text=SCREAMING_SNAKE_CASE							,       tokenize_chinese_chars=SCREAMING_SNAKE_CASE							,       strip_accents=SCREAMING_SNAKE_CASE							,       wordpieces_prefix=SCREAMING_SNAKE_CASE							,       **SCREAMING_SNAKE_CASE							,       )

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

      UpperCamelCase__      :       str	    =  do_lower_case







 def  __lowercase (		self :       Optional[Any]							,       SCREAMING_SNAKE_CASE :       Dict							,       SCREAMING_SNAKE_CASE :       List[Any]=None						):


      '''simple docstring'''






      UpperCamelCase__      :       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  __lowercase (		self :       int							,       SCREAMING_SNAKE_CASE :       List[int]							,       SCREAMING_SNAKE_CASE :       Optional[List[int]] = None						):


      '''simple docstring'''






      UpperCamelCase__      :       Optional[int]	    =  [self.sep_token_id]
      UpperCamelCase__      :       Tuple	    =  [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  __lowercase (		self :       Optional[int]							,       SCREAMING_SNAKE_CASE :       str							,       SCREAMING_SNAKE_CASE :       Optional[str] = None						):


      '''simple docstring'''






      UpperCamelCase__      :       Tuple	    =  self._tokenizer.model.save(SCREAMING_SNAKE_CASE							,       name=SCREAMING_SNAKE_CASE						)
      return tuple(SCREAMING_SNAKE_CASE						)







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     :							str    =logging.get_logger(__name__)





@add_end_docstrings(A__	)
class       __a  (   A__	):







 def __init__(		self :       List[str]							,       **SCREAMING_SNAKE_CASE :       Tuple						):


      '''simple docstring'''






      super().__init__(**SCREAMING_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 :       Dict							,       SCREAMING_SNAKE_CASE :       Union[str, List[str], "Image", List["Image"]]							,       **SCREAMING_SNAKE_CASE :       str						):


      '''simple docstring'''






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







 def  __lowercase (		self :       List[str]							,       **SCREAMING_SNAKE_CASE :       List[str]						):


      '''simple docstring'''






      UpperCamelCase__      :       List[Any]	    =  {}
      if "candidate_labels" in kwargs:
           UpperCamelCase__      :       Optional[Any]	    =  kwargs["candidate_labels"]
      if "hypothesis_template" in kwargs:
           UpperCamelCase__      :       int	    =  kwargs["hypothesis_template"]

      return preprocess_params, {}, {}







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


      '''simple docstring'''






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







 def  __lowercase (		self :       int							,       SCREAMING_SNAKE_CASE :       Union[str, Any]						):


      '''simple docstring'''






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

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

      UpperCamelCase__      :       Dict	    =  {
          "candidate_labels": candidate_labels,
          "logits": outputs.logits_per_image,
      }
      return model_outputs







 def  __lowercase (		self :       Any							,       SCREAMING_SNAKE_CASE :       List[str]						):


      '''simple docstring'''






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

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