



'''simple docstring'''




import os
import re
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


a     :    str      						=					logging.get_logger(__name__)

a     :    Tuple      						=					{"""vocab_file""": """spiece.model"""}

a     :    Optional[Any]      						=					{
    """vocab_file""": {
        """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model""",
        """google/bigbird-roberta-large""": (
            """https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model"""
        ),
        """google/bigbird-base-trivia-itc""": (
            """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model"""
        ),
    }
}

a     :    Dict      						=					{
    """google/bigbird-roberta-base""": 4_0_9_6,
    """google/bigbird-roberta-large""": 4_0_9_6,
    """google/bigbird-base-trivia-itc""": 4_0_9_6,
}

class     UpperCamelCase_				(							__magic_name__    ):
	lowercase    =				VOCAB_FILES_NAMES
	lowercase    =				PRETRAINED_VOCAB_FILES_MAP
	lowercase    =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowercase    =				['input_ids', 'attention_mask']
	lowercase    =				[]





	def __init__(						self	,	A	,	A="<unk>"	,	A="<s>"	,	A="</s>"	,	A="<pad>"	,	A="[SEP]"	,	A="[MASK]"	,	A="[CLS]"	,	A = None	,	**A	,	)    ->    None:
								UpperCAmelCase  :	int							  =	AddedToken(A	,	lstrip=A	,	rstrip=A					) if isinstance(A	,	A					) else bos_token
								UpperCAmelCase  :	Dict							  =	AddedToken(A	,	lstrip=A	,	rstrip=A					) if isinstance(A	,	A					) else eos_token
								UpperCAmelCase  :	Optional[Any]							  =	AddedToken(A	,	lstrip=A	,	rstrip=A					) if isinstance(A	,	A					) else unk_token
								UpperCAmelCase  :	Union[str, Any]							  =	AddedToken(A	,	lstrip=A	,	rstrip=A					) if isinstance(A	,	A					) else pad_token
								UpperCAmelCase  :	Any							  =	AddedToken(A	,	lstrip=A	,	rstrip=A					) if isinstance(A	,	A					) else cls_token
								UpperCAmelCase  :	Tuple							  =	AddedToken(A	,	lstrip=A	,	rstrip=A					) if isinstance(A	,	A					) else sep_token

								# Mask token behave like a normal word, i.e. include the space before it
								UpperCAmelCase  :	Union[str, Any]							  =	AddedToken(A	,	lstrip=A	,	rstrip=A					) if isinstance(A	,	A					) else mask_token

								UpperCAmelCase  :	int							  =	{} if sp_model_kwargs is None else sp_model_kwargs

								super().__init__(
								    bos_token=A	,	eos_token=A	,	unk_token=A	,	pad_token=A	,	sep_token=A	,	mask_token=A	,	cls_token=A	,	sp_model_kwargs=self.sp_model_kwargs	,	**A	,	)

								UpperCAmelCase  :	Union[str, Any]							  =	vocab_file

								UpperCAmelCase  :	int							  =	spm.SentencePieceProcessor(**self.sp_model_kwargs					)
								self.sp_model.Load(A					)





	@property
	def 				_lowercase(						self					)    ->    Optional[int]:
								return self.sp_model.get_piece_size()





	def 				_lowercase(						self					)    ->    List[str]:
								UpperCAmelCase  :	int							  =	{self.convert_ids_to_tokens(A					): i for i in range(self.vocab_size					)}
								vocab.update(self.added_tokens_encoder					)
								return vocab





	def __getstate__(						self					)    ->    Optional[Any]:
								UpperCAmelCase  :	int							  =	self.__dict__.copy()
								UpperCAmelCase  :	Union[str, Any]							  =	None
								return state





	def __setstate__(						self	,	A					)    ->    int:
								UpperCAmelCase  :	Optional[Any]							  =	d

								# for backward compatibility
								if not hasattr(self	,	"""sp_model_kwargs"""					):
															UpperCAmelCase  :	int							  =	{}

								UpperCAmelCase  :	Tuple							  =	spm.SentencePieceProcessor(**self.sp_model_kwargs					)
								self.sp_model.Load(self.vocab_file					)





	def 				_lowercase(						self	,	A					)    ->    List[str]:
								return self.sp_model.encode(A	,	out_type=A					)





	def 				_lowercase(						self	,	A					)    ->    Union[str, Any]:
								return self.sp_model.piece_to_id(A					)





	def 				_lowercase(						self	,	A					)    ->    int:
								UpperCAmelCase  :	Dict							  =	self.sp_model.IdToPiece(A					)
								return token





	def 				_lowercase(						self	,	A					)    ->    List[Any]:
								UpperCAmelCase  :	int							  =	[]
								UpperCAmelCase  :	int							  =	""""""
								UpperCAmelCase  :	Dict							  =	False
								for token in tokens:
															# make sure that special tokens are not decoded using sentencepiece model
															if token in self.all_special_tokens:
																						if not prev_is_special:
																													out_string += " "
																						out_string += self.sp_model.decode(A					) + token
																						UpperCAmelCase  :	List[Any]							  =	True
																						UpperCAmelCase  :	Optional[int]							  =	[]
															else:
																						current_sub_tokens.append(A					)
																						UpperCAmelCase  :	Dict							  =	False
								out_string += self.sp_model.decode(A					)
								return out_string.strip()





	def 				_lowercase(						self	,	A	,	A = False	,	A = None	,	A = True	,	**A	,	)    ->    str:
								UpperCAmelCase  :	Tuple							  =	kwargs.pop("""use_source_tokenizer"""	,	A					)

								UpperCAmelCase  :	str							  =	self.convert_ids_to_tokens(A	,	skip_special_tokens=A					)

								# To avoid mixing byte-level and unicode for byte-level BPT
								# we need to build string separately for added tokens and byte-level tokens
								# cf. https://github.com/huggingface/transformers/issues/1133
								UpperCAmelCase  :	Tuple							  =	[]
								UpperCAmelCase  :	Dict							  =	[]
								for token in filtered_tokens:
															if skip_special_tokens and token in self.all_special_ids:
																						continue
															if token in self.added_tokens_encoder:
																						if current_sub_text:
																													sub_texts.append(self.convert_tokens_to_string(A					)					)
																													UpperCAmelCase  :	int							  =	[]
																						sub_texts.append(A					)
															else:
																						current_sub_text.append(A					)
								if current_sub_text:
															sub_texts.append(self.convert_tokens_to_string(A					)					)

								# Mimic the behavior of the Rust tokenizer:
								# No space before [MASK] and [SEP]
								if spaces_between_special_tokens:
															UpperCAmelCase  :	List[Any]							  =	re.sub(r""" (\[(MASK|SEP)\])"""	,	r"""\1"""	,	""" """.join(A					)					)
								else:
															UpperCAmelCase  :	str							  =	"""""".join(A					)

								UpperCAmelCase  :	List[str]							  =	(
								    clean_up_tokenization_spaces
								    if clean_up_tokenization_spaces is not None
								    else self.clean_up_tokenization_spaces
								)
								if clean_up_tokenization_spaces:
															UpperCAmelCase  :	List[Any]							  =	self.clean_up_tokenization(A					)
															return clean_text
								else:
															return text





	def 				_lowercase(						self	,	A	,	A = None					)    ->    Tuple[str]:
								if not os.path.isdir(A					):
															logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''					)
															return
								UpperCAmelCase  :	Any							  =	os.path.join(
								    A	,	(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]					)

								if os.path.abspath(self.vocab_file					) != os.path.abspath(A					) and os.path.isfile(self.vocab_file					):
															copyfile(self.vocab_file	,	A					)
								elif not os.path.isfile(self.vocab_file					):
															with open(A	,	"""wb"""					) as fi:
																						UpperCAmelCase  :	Tuple							  =	self.sp_model.serialized_model_proto()
																						fi.write(A					)

								return (out_vocab_file,)





	def 				_lowercase(						self	,	A	,	A = None					)    ->    List[int]:
								if token_ids_a is None:
															return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
								UpperCAmelCase  :	int							  =	[self.cls_token_id]
								UpperCAmelCase  :	List[Any]							  =	[self.sep_token_id]
								return cls + token_ids_a + sep + token_ids_a + sep





	def 				_lowercase(						self	,	A	,	A = None	,	A = False					)    ->    List[int]:
								if already_has_special_tokens:
															return super().get_special_tokens_mask(
															    token_ids_a=A	,	token_ids_a=A	,	already_has_special_tokens=A					)

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






	def 				_lowercase(						self	,	A	,	A = None					)    ->    List[int]:
								UpperCAmelCase  :	int							  =	[self.sep_token_id]
								UpperCAmelCase  :	Any							  =	[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					) * [0] + len(token_ids_a + sep					) * [1]






'''simple docstring'''




from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


a     :    List[str]      						=					logging.get_logger(__name__)

class     UpperCamelCase_				(							__magic_name__    ):





	def 				_lowercase(						self	,	A					)    ->    Optional[int]:
								if isinstance(A	,	A					):
															UpperCAmelCase  :	Union[str, Any]							  =	[label.strip() for label in labels.split(""","""					) if label.strip()]
								return labels






	def __call__(						self	,	A	,	A	,	A					)    ->    str:
								if len(A					) == 0 or len(A					) == 0:
															raise ValueError("""You must include at least one label and at least one sequence."""					)
								if hypothesis_template.format(labels[0]					) == hypothesis_template:
															raise ValueError(
															    (
															        """The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. """
															        """Make sure the passed template includes formatting syntax such as {{}} where the label should go."""
															    ).format(A					)					)

								if isinstance(A	,	A					):
															UpperCAmelCase  :	Tuple							  =	[sequences]

								UpperCAmelCase  :	Optional[Any]							  =	[]
								for sequence in sequences:
															sequence_pairs.extend([[sequence, hypothesis_template.format(A					)] for label in labels]					)

								return sequence_pairs, sequences




@add_end_docstrings(__magic_name__    )
class     UpperCamelCase_				(							__magic_name__    ):





	def __init__(						self	,	A=ZeroShotClassificationArgumentHandler()	,	*A	,	**A					)    ->    Optional[int]:
								UpperCAmelCase  :	Tuple							  =	args_parser
								super().__init__(*A	,	**A					)
								if self.entailment_id == -1:
															logger.warning(
															    """Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to """
															    """-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."""					)





	@property
	def 				_lowercase(						self					)    ->    List[Any]:
								for label, ind in self.model.config.labelaid.items():
															if label.lower().startswith("""entail"""					):
																						return ind
								return -1





	def 				_lowercase(						self	,	A	,	A=True	,	A=True	,	A=TruncationStrategy.ONLY_FIRST	,	**A					)    ->    str:
								UpperCAmelCase  :	Tuple							  =	self.framework
								if self.tokenizer.pad_token is None:
															# Override for tokenizers not supporting padding
															logger.error(
															    """Tokenizer was not supporting padding necessary for zero-shot, attempting to use """
															    """ `pad_token=eos_token`"""					)
															UpperCAmelCase  :	Any							  =	self.tokenizer.eos_token
								try:
															UpperCAmelCase  :	Tuple							  =	self.tokenizer(
															    A	,	add_special_tokens=A	,	return_tensors=A	,	padding=A	,	truncation=A	,	)
								except Exception as e:
															if "too short" in str(A					):
																						# tokenizers might yell that we want to truncate
																						# to a value that is not even reached by the input.
																						# In that case we don't want to truncate.
																						# It seems there's not a really better way to catch that
																						# exception.

																						UpperCAmelCase  :	List[str]							  =	self.tokenizer(
																						    A	,	add_special_tokens=A	,	return_tensors=A	,	padding=A	,	truncation=TruncationStrategy.DO_NOT_TRUNCATE	,	)
															else:
																						raise e

								return inputs





	def 				_lowercase(						self	,	**A					)    ->    Tuple:
								if kwargs.get("""multi_class"""	,	A					) is not None:
															UpperCAmelCase  :	Any							  =	kwargs["""multi_class"""]
															logger.warning(
															    """The `multi_class` argument has been deprecated and renamed to `multi_label`. """
															    """`multi_class` will be removed in a future version of Transformers."""					)
								UpperCAmelCase  :	int							  =	{}
								if "candidate_labels" in kwargs:
															UpperCAmelCase  :	Tuple							  =	self._args_parser._parse_labels(kwargs["""candidate_labels"""]					)
								if "hypothesis_template" in kwargs:
															UpperCAmelCase  :	List[Any]							  =	kwargs["""hypothesis_template"""]

								UpperCAmelCase  :	Dict							  =	{}
								if "multi_label" in kwargs:
															UpperCAmelCase  :	Union[str, Any]							  =	kwargs["""multi_label"""]
								return preprocess_params, {}, postprocess_params





	def __call__(						self	,	A	,	*A	,	**A	,	)    ->    Tuple:
								if len(A					) == 0:
															pass
								elif len(A					) == 1 and "candidate_labels" not in kwargs:
															UpperCAmelCase  :	Optional[Any]							  =	args[0]
								else:
															raise ValueError(f'''Unable to understand extra arguments {args}'''					)

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





	def 				_lowercase(						self	,	A	,	A=None	,	A="This example is {}."					)    ->    List[Any]:
								UpperCAmelCase  ,  UpperCAmelCase  :	List[Any]							  =	self._args_parser(A	,	A	,	A					)

								for i, (candidate_label, sequence_pair) in enumerate(zip(A	,	A					)					):
															UpperCAmelCase  :	Any							  =	self._parse_and_tokenize([sequence_pair]					)

															yield {
															    "candidate_label": candidate_label,
															    "sequence": sequences[0],
															    "is_last": i == len(A					) - 1,
															    **model_input,
															}





	def 				_lowercase(						self	,	A					)    ->    Optional[int]:
								UpperCAmelCase  :	Optional[Any]							  =	inputs["""candidate_label"""]
								UpperCAmelCase  :	Tuple							  =	inputs["""sequence"""]
								UpperCAmelCase  :	List[Any]							  =	{k: inputs[k] for k in self.tokenizer.model_input_names}
								UpperCAmelCase  :	Tuple							  =	self.model(**A					)

								UpperCAmelCase  :	Optional[int]							  =	{
								    """candidate_label""": candidate_label,
								    """sequence""": sequence,
								    """is_last""": inputs["""is_last"""],
								    **outputs,
								}
								return model_outputs






	def 				_lowercase(						self	,	A	,	A=False					)    ->    List[str]:
								UpperCAmelCase  :	Dict							  =	[outputs["""candidate_label"""] for outputs in model_outputs]
								UpperCAmelCase  :	List[Any]							  =	[outputs["""sequence"""] for outputs in model_outputs]
								UpperCAmelCase  :	List[Any]							  =	np.concatenate([output["""logits"""].numpy() for output in model_outputs]					)
								UpperCAmelCase  :	Optional[Any]							  =	logits.shape[0]
								UpperCAmelCase  :	int							  =	len(A					)
								UpperCAmelCase  :	List[Any]							  =	N // n
								UpperCAmelCase  :	int							  =	logits.reshape((num_sequences, n, -1)					)

								if multi_label or len(A					) == 1:
															# softmax over the entailment vs. contradiction dim for each label independently
															UpperCAmelCase  :	str							  =	self.entailment_id
															UpperCAmelCase  :	str							  =	-1 if entailment_id == 0 else 0
															UpperCAmelCase  :	Optional[Any]							  =	reshaped_outputs[..., [contradiction_id, entailment_id]]
															UpperCAmelCase  :	int							  =	np.exp(A					) / np.exp(A					).sum(-1	,	keepdims=A					)
															UpperCAmelCase  :	int							  =	scores[..., 1]
								else:
															# softmax the "entailment" logits over all candidate labels
															UpperCAmelCase  :	Dict							  =	reshaped_outputs[..., self.entailment_id]
															UpperCAmelCase  :	Optional[int]							  =	np.exp(A					) / np.exp(A					).sum(-1	,	keepdims=A					)

								UpperCAmelCase  :	int							  =	list(reversed(scores[0].argsort()					)					)
								return {
								    "sequence": sequences[0],
								    "labels": [candidate_labels[i] for i in top_inds],
								    "scores": scores[0, top_inds].tolist(),
								}

