


"""simple docstring"""







import json
import os
from functools import lru_cache
from typing import Dict, List, Optional, Tuple, Union

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding, EncodedInput
from ...utils import PaddingStrategy, logging


__lowercase    					=      logging.get_logger(__name__)


__lowercase    					=      {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt"""}

# See all LED models at https://huggingface.co/models?filter=LED
__lowercase    					=      {
    """vocab_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json""",
    },
}

__lowercase    					=      {
    """allenai/led-base-16384""": 16384,
}


@lru_cache()
# Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode
def      lowercase			(				)->      Dict:
  '''simple docstring'''







  a						:		int      							=			(
      list(range(ord("!"       )  ,   ord("~"       ) + 1       )       ) + list(range(ord("¡"       )  ,   ord("¬"       ) + 1       )       ) + list(range(ord("®"       )  ,   ord("ÿ"       ) + 1       )       )
  )
  a						:		int      							=			bs[:]
  a						:		List[str]      							=			0
  for b in range(2**8       ):
    if b not in bs:
      bs.append(A_       )
      cs.append(2**8 + n       )
      n += 1
  a						:		List[str]      							=			[chr(A_       ) for n in cs]
  return dict(zip(A_  ,   A_       )       )


def      lowercase			(				A_       )->      Optional[Any]:
  '''simple docstring'''







  a						:		Any      							=			set()
  a						:		Tuple      							=			word[0]
  for char in word[1:]:
    pairs.add((prev_char, char)       )
    a						:		int      							=			char
  return pairs







class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase       :							Dict	=       VOCAB_FILES_NAMES
    UpperCAmelCase       :							List[Any]	=       PRETRAINED_VOCAB_FILES_MAP
    UpperCAmelCase       :							Optional[Any]	=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    UpperCAmelCase       :							List[Any]	=       ["""input_ids""", """attention_mask"""]






    def __init__(					self				:    Tuple				, __UpperCAmelCase				:    Union[str, Any]				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    Union[str, Any]="replace"				, __UpperCAmelCase				:    Any="<s>"				, __UpperCAmelCase				:    Any="</s>"				, __UpperCAmelCase				:    Tuple="</s>"				, __UpperCAmelCase				:    Dict="<s>"				, __UpperCAmelCase				:    List[str]="<unk>"				, __UpperCAmelCase				:    str="<pad>"				, __UpperCAmelCase				:    Union[str, Any]="<mask>"				, __UpperCAmelCase				:    Any=False				, **__UpperCAmelCase				:    Any				, ):
      a						:		Optional[Any]      							=			AddedToken(__UpperCAmelCase				, lstrip=__UpperCAmelCase				, rstrip=__UpperCAmelCase) if isinstance(__UpperCAmelCase				, __UpperCAmelCase) else bos_token
      a						:		Optional[Any]      							=			AddedToken(__UpperCAmelCase				, lstrip=__UpperCAmelCase				, rstrip=__UpperCAmelCase) if isinstance(__UpperCAmelCase				, __UpperCAmelCase) else eos_token
      a						:		Dict      							=			AddedToken(__UpperCAmelCase				, lstrip=__UpperCAmelCase				, rstrip=__UpperCAmelCase) if isinstance(__UpperCAmelCase				, __UpperCAmelCase) else sep_token
      a						:		Dict      							=			AddedToken(__UpperCAmelCase				, lstrip=__UpperCAmelCase				, rstrip=__UpperCAmelCase) if isinstance(__UpperCAmelCase				, __UpperCAmelCase) else cls_token
      a						:		Union[str, Any]      							=			AddedToken(__UpperCAmelCase				, lstrip=__UpperCAmelCase				, rstrip=__UpperCAmelCase) if isinstance(__UpperCAmelCase				, __UpperCAmelCase) else unk_token
      a						:		int      							=			AddedToken(__UpperCAmelCase				, lstrip=__UpperCAmelCase				, rstrip=__UpperCAmelCase) if isinstance(__UpperCAmelCase				, __UpperCAmelCase) else pad_token

      # Mask token behave like a normal word, i.e. include the space before it
      a						:		Tuple      							=			AddedToken(__UpperCAmelCase				, lstrip=__UpperCAmelCase				, rstrip=__UpperCAmelCase) if isinstance(__UpperCAmelCase				, __UpperCAmelCase) else mask_token

      super().__init__(
          errors=__UpperCAmelCase				, bos_token=__UpperCAmelCase				, eos_token=__UpperCAmelCase				, unk_token=__UpperCAmelCase				, sep_token=__UpperCAmelCase				, cls_token=__UpperCAmelCase				, pad_token=__UpperCAmelCase				, mask_token=__UpperCAmelCase				, add_prefix_space=__UpperCAmelCase				, **__UpperCAmelCase				, )

      with open(__UpperCAmelCase				, encoding="utf-8") as vocab_handle:
        a						:		int      							=			json.load(__UpperCAmelCase)
      a						:		Optional[int]      							=			{v: k for k, v in self.encoder.items()}
      a						:		Optional[int]      							=			errors  # how to handle errors in decoding
      a						:		Any      							=			bytes_to_unicode()
      a						:		Optional[int]      							=			{v: k for k, v in self.byte_encoder.items()}
      with open(__UpperCAmelCase				, encoding="utf-8") as merges_handle:
        a						:		Any      							=			merges_handle.read().split("\n")[1:-1]
      a						:		Optional[Any]      							=			[tuple(merge.split()) for merge in bpe_merges]
      a						:		List[Any]      							=			dict(zip(__UpperCAmelCase				, range(len(__UpperCAmelCase))))
      a						:		Tuple      							=			{}
      a						:		List[Any]      							=			add_prefix_space

      # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
      a						:		List[Any]      							=			re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+")






    @property
    # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size
    def 	__snake_case							(					self				:    Optional[int]):
      return len(self.encoder)






    def 	__snake_case							(					self				:    Any):
      return dict(self.encoder				, **self.added_tokens_encoder)






    def 	__snake_case							(					self				:    List[str]				, __UpperCAmelCase				:    int):
      if token in self.cache:
        return self.cache[token]
      a						:		List[Any]      							=			tuple(__UpperCAmelCase)
      a						:		Any      							=			get_pairs(__UpperCAmelCase)

      if not pairs:
        return token

      while True:
        a						:		Union[str, Any]      							=			min(__UpperCAmelCase				, key=lambda __UpperCAmelCase: self.bpe_ranks.get(__UpperCAmelCase				, float("inf")))
        if bigram not in self.bpe_ranks:
          break
        a							,		a						:		str      							=			bigram
        a						:		Tuple      							=			[]
        a						:		Optional[int]      							=			0
        while i < len(__UpperCAmelCase):
          try:
            a						:		str      							=			word.index(__UpperCAmelCase				, __UpperCAmelCase)
          except ValueError:
            new_word.extend(word[i:])
            break
          else:
            new_word.extend(word[i:j])
            a						:		Tuple      							=			j

          if word[i] == first and i < len(__UpperCAmelCase) - 1 and word[i + 1] == second:
            new_word.append(first + second)
            i += 2
          else:
            new_word.append(word[i])
            i += 1
        a						:		str      							=			tuple(__UpperCAmelCase)
        a						:		Dict      							=			new_word
        if len(__UpperCAmelCase) == 1:
          break
        else:
          a						:		str      							=			get_pairs(__UpperCAmelCase)
      a						:		Any      							=			" ".join(__UpperCAmelCase)
      a						:		Dict      							=			word
      return word






    def 	__snake_case							(					self				:    Optional[int]				, __UpperCAmelCase				:    str):
      a						:		int      							=			[]
      for token in re.findall(self.pat				, __UpperCAmelCase):
        a						:		List[str]      							=			"".join(
            self.byte_encoder[b] for b in token.encode("utf-8"))  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
        bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__UpperCAmelCase).split(" "))
      return bpe_tokens






    def 	__snake_case							(					self				:    Dict				, __UpperCAmelCase				:    str):
      return self.encoder.get(__UpperCAmelCase				, self.encoder.get(self.unk_token))






    def 	__snake_case							(					self				:    Optional[int]				, __UpperCAmelCase				:    Optional[Any]):
      return self.decoder.get(__UpperCAmelCase)






    def 	__snake_case							(					self				:    List[Any]				, __UpperCAmelCase				:    List[str]):
      a						:		Union[str, Any]      							=			"".join(__UpperCAmelCase)
      a						:		List[Any]      							=			bytearray([self.byte_decoder[c] for c in text]).decode("utf-8"				, errors=self.errors)
      return text






    def 	__snake_case							(					self				:    List[Any]				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    Optional[str] = None):
      if not os.path.isdir(__UpperCAmelCase):
        logger.error(f'''Vocabulary path ({save_directory}) should be a directory''')
        return
      a						:		List[Any]      							=			os.path.join(
          __UpperCAmelCase				, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"])
      a						:		int      							=			os.path.join(
          __UpperCAmelCase				, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"])

      with open(__UpperCAmelCase				, "w"				, encoding="utf-8") as f:
        f.write(json.dumps(self.encoder				, indent=2				, sort_keys=__UpperCAmelCase				, ensure_ascii=__UpperCAmelCase) + "\n")

      a						:		Tuple      							=			0
      with open(__UpperCAmelCase				, "w"				, encoding="utf-8") as writer:
        writer.write("#version: 0.2\n")
        for bpe_tokens, token_index in sorted(self.bpe_ranks.items()				, key=lambda __UpperCAmelCase: kv[1]):
          if index != token_index:
            logger.warning(
                f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
                " Please check that the tokenizer is not corrupted!")
            a						:		List[Any]      							=			token_index
          writer.write(" ".join(__UpperCAmelCase) + "\n")
          index += 1

      return vocab_file, merge_file






    def 	__snake_case							(					self				:    Any				, __UpperCAmelCase				:    List[int]				, __UpperCAmelCase				:    Optional[List[int]] = None):
      if token_ids_a is None:
        return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
      a						:		Optional[int]      							=			[self.cls_token_id]
      a						:		Tuple      							=			[self.sep_token_id]
      return cls + token_ids_a + sep + sep + token_ids_a + sep






    def 	__snake_case							(					self				:    Any				, __UpperCAmelCase				:    List[int]				, __UpperCAmelCase				:    Optional[List[int]] = None				, __UpperCAmelCase				:    bool = False):
      if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_a=__UpperCAmelCase				, token_ids_a=__UpperCAmelCase				, already_has_special_tokens=__UpperCAmelCase)

      if token_ids_a is None:
        return [1] + ([0] * len(__UpperCAmelCase)) + [1]
      return [1] + ([0] * len(__UpperCAmelCase)) + [1, 1] + ([0] * len(__UpperCAmelCase)) + [1]






    def 	__snake_case							(					self				:    List[str]				, __UpperCAmelCase				:    List[int]				, __UpperCAmelCase				:    Optional[List[int]] = None):
      a						:		Optional[Any]      							=			[self.sep_token_id]
      a						:		str      							=			[self.cls_token_id]

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






    def 	__snake_case							(					self				:    Dict				, __UpperCAmelCase				:    List[str]				, __UpperCAmelCase				:    List[Any]=False				, **__UpperCAmelCase				:    Union[str, Any]):
      a						:		int      							=			kwargs.pop("add_prefix_space"				, self.add_prefix_space)
      if (is_split_into_words or add_prefix_space) and (len(__UpperCAmelCase) > 0 and not text[0].isspace()):
        a						:		List[Any]      							=			" " + text
      return (text, kwargs)






    def 	__snake_case							(					self				:    Union[str, Any]				, __UpperCAmelCase				:    Union[Dict[str, EncodedInput], BatchEncoding]				, __UpperCAmelCase				:    Optional[int] = None				, __UpperCAmelCase				:    PaddingStrategy = PaddingStrategy.DO_NOT_PAD				, __UpperCAmelCase				:    Optional[int] = None				, __UpperCAmelCase				:    Optional[bool] = None				, ):
      a						:		Union[str, Any]      							=			super()._pad(
          encoded_inputs=__UpperCAmelCase				, max_length=__UpperCAmelCase				, padding_strategy=__UpperCAmelCase				, pad_to_multiple_of=__UpperCAmelCase				, return_attention_mask=__UpperCAmelCase				, )

      # Load from model defaults
      if return_attention_mask is None:
        a						:		List[Any]      							=			"attention_mask" in self.model_input_names

      if return_attention_mask and "global_attention_mask" in encoded_inputs:
        a						:		Tuple      							=			encoded_inputs[self.model_input_names[0]]
        # `global_attention_mask` need to have the same length as other (sequential) inputs.
        a						:		Tuple      							=			len(encoded_inputs["global_attention_mask"]) != len(__UpperCAmelCase)

        if needs_to_be_padded:
          a						:		Union[str, Any]      							=			len(__UpperCAmelCase) - len(encoded_inputs["global_attention_mask"])

          if self.padding_side == "right":
            # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
            a						:		str      							=			(
                encoded_inputs["global_attention_mask"] + [-1] * difference
            )
          elif self.padding_side == "left":
            a						:		Optional[Any]      							=			[-1] * difference + encoded_inputs[
                "global_attention_mask"
            ]
          else:
            raise ValueError("Invalid padding strategy:" + str(self.padding_side))

      return encoded_inputs











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