





'''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__							:  List[str]    =logging.get_logger(__name__)




@add_end_docstrings(snake_case_  )
class 					UpperCAmelCase	(     snake_case_  ):




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




      def 							lowercase__       (     self     :					Union[str, Any]     ,     **__snake_case     :					Optional[Any]    )							-> List[str]:
            _lowerCAmelCase					=				{}
            if "candidate_labels" in kwargs:
                  _lowerCAmelCase					=				kwargs["""candidate_labels"""]
            if "hypothesis_template" in kwargs:
                  _lowerCAmelCase					=				kwargs["""hypothesis_template"""]

            return preprocess_params, {}, {}




      def 							lowercase__       (     self     :					Any     ,     __snake_case     :					Optional[int]     ,     __snake_case     :					int=None     ,     __snake_case     :					List[Any]="This is a photo of {}."    )							-> List[str]:
            _lowerCAmelCase					=				load_image(__snake_case    )
            _lowerCAmelCase					=				self.image_processor(images=[image]     ,     return_tensors=self.framework    )
            _lowerCAmelCase					=				candidate_labels
            _lowerCAmelCase					=				[hypothesis_template.format(__snake_case    ) for x in candidate_labels]
            _lowerCAmelCase					=				self.tokenizer(__snake_case     ,     return_tensors=self.framework     ,     padding=__snake_case    )
            _lowerCAmelCase					=				[text_inputs]
            return inputs




      def 							lowercase__       (     self     :					List[str]     ,     __snake_case     :					Any    )							-> Any:
            _lowerCAmelCase					=				model_inputs.pop("""candidate_labels"""    )
            _lowerCAmelCase					=				model_inputs.pop("""text_inputs"""    )
            if isinstance(text_inputs[0]     ,     __snake_case    ):
                  _lowerCAmelCase					=				text_inputs[0]
            else:
                  # Batching case.
                  _lowerCAmelCase					=				text_inputs[0][0]

            _lowerCAmelCase					=				self.model(**__snake_case     ,     **__snake_case    )

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




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

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













'''simple docstring'''






import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
      from .tokenization_xlnet import XLNetTokenizer
else:
      A__							:  Any    =None


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

A__							:  Union[str, Any]    ={'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''}

A__							:  List[str]    ={
    '''vocab_file''': {
        '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''',
        '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''',
    },
    '''tokenizer_file''': {
        '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json''',
        '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json''',
    },
}

A__							:  List[str]    ={
    '''xlnet-base-cased''': None,
    '''xlnet-large-cased''': None,
}

A__							:  List[str]    ='''▁'''

# Segments (not really needed)
A__							:  str    =0
A__							:  str    =1
A__							:  List[Any]    =2
A__							:  str    =3
A__							:  Optional[Any]    =4




class 					UpperCAmelCase	(     snake_case_  ):
      _lowercase:     Optional[int]			=  VOCAB_FILES_NAMES
      _lowercase:     Optional[int]			=  PRETRAINED_VOCAB_FILES_MAP
      _lowercase:     Dict			=  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      _lowercase:     Optional[Any]			=  '''left'''
      _lowercase:     Dict			=  XLNetTokenizer




      def __init__(     self     :					List[str]     ,     __snake_case     :					Optional[Any]=None     ,     __snake_case     :					str=None     ,     __snake_case     :					Union[str, Any]=False     ,     __snake_case     :					str=True     ,     __snake_case     :					Union[str, Any]=False     ,     __snake_case     :					List[Any]="<s>"     ,     __snake_case     :					List[Any]="</s>"     ,     __snake_case     :					str="<unk>"     ,     __snake_case     :					int="<sep>"     ,     __snake_case     :					int="<pad>"     ,     __snake_case     :					Dict="<cls>"     ,     __snake_case     :					int="<mask>"     ,     __snake_case     :					Optional[int]=["<eop>", "<eod>"]     ,     **__snake_case     :					List[str]     ,     )							-> List[str]:
            # Mask token behave like a normal word, i.e. include the space before it
            _lowerCAmelCase					=				AddedToken(__snake_case     ,     lstrip=__snake_case     ,     rstrip=__snake_case    ) if isinstance(__snake_case     ,     __snake_case    ) else mask_token

            super().__init__(
                vocab_file=__snake_case     ,     tokenizer_file=__snake_case     ,     do_lower_case=__snake_case     ,     remove_space=__snake_case     ,     keep_accents=__snake_case     ,     bos_token=__snake_case     ,     eos_token=__snake_case     ,     unk_token=__snake_case     ,     sep_token=__snake_case     ,     pad_token=__snake_case     ,     cls_token=__snake_case     ,     mask_token=__snake_case     ,     additional_special_tokens=__snake_case     ,     **__snake_case     ,     )

            _lowerCAmelCase					=				3
            _lowerCAmelCase					=				do_lower_case
            _lowerCAmelCase					=				remove_space
            _lowerCAmelCase					=				keep_accents
            _lowerCAmelCase					=				vocab_file
            _lowerCAmelCase					=				False if not self.vocab_file else True




      def 							lowercase__       (     self     :					Optional[int]     ,     __snake_case     :					List[int]     ,     __snake_case     :					Optional[List[int]] = None    )							-> List[int]:
            _lowerCAmelCase					=				[self.sep_token_id]
            _lowerCAmelCase					=				[self.cls_token_id]
            if token_ids_a is None:
                  return token_ids_a + sep + cls
            return token_ids_a + sep + token_ids_a + sep + cls




      def 							lowercase__       (     self     :					str     ,     __snake_case     :					List[int]     ,     __snake_case     :					Optional[List[int]] = None    )							-> List[int]:
            _lowerCAmelCase					=				[self.sep_token_id]
            _lowerCAmelCase					=				[2]

            if token_ids_a is None:
                  return len(token_ids_a + sep    ) * [0] + cls_segment_id
            return len(token_ids_a + sep    ) * [0] + len(token_ids_a + sep    ) * [1] + cls_segment_id




      def 							lowercase__       (     self     :					Optional[Any]     ,     __snake_case     :					str     ,     __snake_case     :					Optional[str] = None    )							-> Tuple[str]:
            if not self.can_save_slow_tokenizer:
                  raise ValueError(
                      """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
                      """tokenizer."""    )

            if not os.path.isdir(__snake_case    ):
                  logger.error(f"Vocabulary path ({save_directory}) should be a directory"    )
                  return
            _lowerCAmelCase					=				os.path.join(
                __snake_case     ,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]    )

            if os.path.abspath(self.vocab_file    ) != os.path.abspath(__snake_case    ):
                  copyfile(self.vocab_file     ,     __snake_case    )

            return (out_vocab_file,)






