






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


lowercase  :							Dict			  =    logging.get_logger(__name__)




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[Any]:
								if isinstance(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				):
										snake_case_				:							List[str]						 =       [label.strip() for label in labels.split(","				) if label.strip()]
								return labels






						def __call__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Optional[Any]:
								if len(_SCREAMING_SNAKE_CASE				) == 0 or len(_SCREAMING_SNAKE_CASE				) == 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(_SCREAMING_SNAKE_CASE				)				)

								if isinstance(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				):
										snake_case_				:							List[str]						 =       [sequences]

								snake_case_				:							List[str]						 =       []
								for sequence in sequences:
										sequence_pairs.extend([[sequence, hypothesis_template.format(_SCREAMING_SNAKE_CASE				)] for label in labels]				)

								return sequence_pairs, sequences




@add_end_docstrings(SCREAMING_SNAKE_CASE__					)
class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						def __init__(	self		,				_SCREAMING_SNAKE_CASE=ZeroShotClassificationArgumentHandler()		,				*_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				) ->				Optional[Any]:
								snake_case_				:							Dict						 =       args_parser
								super().__init__(*_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				)
								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       _lowerCAmelCase       (	self				) ->				str:
								for label, ind in self.model.config.labelaid.items():
										if label.lower().startswith("entail"				):
												return ind
								return -1






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE=True		,				_SCREAMING_SNAKE_CASE=True		,				_SCREAMING_SNAKE_CASE=TruncationStrategy.ONLY_FIRST		,				**_SCREAMING_SNAKE_CASE				) ->				Dict:
								snake_case_				:							List[Any]						 =       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`"				)
										snake_case_				:							List[str]						 =       self.tokenizer.eos_token
								try:
										snake_case_				:							Union[str, Any]						 =       self.tokenizer(
										    _SCREAMING_SNAKE_CASE		,				add_special_tokens=_SCREAMING_SNAKE_CASE		,				return_tensors=_SCREAMING_SNAKE_CASE		,				padding=_SCREAMING_SNAKE_CASE		,				truncation=_SCREAMING_SNAKE_CASE		,				)
								except Exception as e:
										if "too short" in str(_SCREAMING_SNAKE_CASE				):
												# 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.

												snake_case_				:							Union[str, Any]						 =       self.tokenizer(
												    _SCREAMING_SNAKE_CASE		,				add_special_tokens=_SCREAMING_SNAKE_CASE		,				return_tensors=_SCREAMING_SNAKE_CASE		,				padding=_SCREAMING_SNAKE_CASE		,				truncation=TruncationStrategy.DO_NOT_TRUNCATE		,				)
										else:
												raise e

								return inputs






						def       _lowerCAmelCase       (	self		,				**_SCREAMING_SNAKE_CASE				) ->				Optional[int]:
								if kwargs.get("multi_class"		,				_SCREAMING_SNAKE_CASE				) is not None:
										snake_case_				:							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."				)
								snake_case_				:							Any						 =       {}
								if "candidate_labels" in kwargs:
										snake_case_				:							Tuple						 =       self._args_parser._parse_labels(kwargs["candidate_labels"]				)
								if "hypothesis_template" in kwargs:
										snake_case_				:							Optional[Any]						 =       kwargs["hypothesis_template"]

								snake_case_				:							Dict						 =       {}
								if "multi_label" in kwargs:
										snake_case_				:							List[Any]						 =       kwargs["multi_label"]
								return preprocess_params, {}, postprocess_params






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

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






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE=None		,				_SCREAMING_SNAKE_CASE="This example is {}."				) ->				str:
								snake_case_ ,       snake_case_				:							Optional[int]						 =       self._args_parser(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)

								for i, (candidate_label, sequence_pair) in enumerate(zip(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)				):
										snake_case_				:							str						 =       self._parse_and_tokenize([sequence_pair]				)

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






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				Any:
								snake_case_				:							Optional[Any]						 =       inputs["candidate_label"]
								snake_case_				:							Dict						 =       inputs["sequence"]
								snake_case_				:							Optional[int]						 =       {k: inputs[k] for k in self.tokenizer.model_input_names}
								snake_case_				:							Dict						 =       self.model(**_SCREAMING_SNAKE_CASE				)

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






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

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

								snake_case_				:							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(),
								}








import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


lowercase  :							Optional[Any]			  =    logging.getLogger(__name__)




@dataclass(frozen=SCREAMING_SNAKE_CASE__					)
class 		UpperCAmelCase_						:


						'''simple docstring'''




						A     :   str
						A     :   str
						A     :   Optional[str]						=					None
						A     :   Optional[str]						=					None
						A     :   Optional[str]						=					None




@dataclass(frozen=SCREAMING_SNAKE_CASE__					)
class 		UpperCAmelCase_						:


						'''simple docstring'''




						A     :   List[int]
						A     :   Optional[List[int]]						=					None
						A     :   Optional[List[int]]						=					None
						A     :   Optional[Union[int, float]]						=					None
						A     :   Optional[int]						=					None


if is_torch_available():
							import torch
							from torch.utils.data import Dataset




							class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


													'''simple docstring'''




													A     :   List[InputFeatures]






													def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE=False		,				_SCREAMING_SNAKE_CASE = False		,				) ->				Union[str, Any]:
															snake_case_				:							str						 =       hans_processors[task]()

															snake_case_				:							Tuple						 =       os.path.join(
															    _SCREAMING_SNAKE_CASE		,				"cached_{}_{}_{}_{}".format(
															        "dev" if evaluate else "train"		,				tokenizer.__class__.__name__		,				str(_SCREAMING_SNAKE_CASE				)		,				_SCREAMING_SNAKE_CASE		,				)		,				)
															snake_case_				:							Dict						 =       processor.get_labels()
															if tokenizer.__class__ in (
															    RobertaTokenizer,
															    RobertaTokenizerFast,
															    XLMRobertaTokenizer,
															    BartTokenizer,
															    BartTokenizerFast,
															):
																	# HACK(label indices are swapped in RoBERTa pretrained model)
																	snake_case_ ,       snake_case_				:							Any						 =       label_list[2], label_list[1]
															snake_case_				:							Tuple						 =       label_list

															# Make sure only the first process in distributed training processes the dataset,
															# and the others will use the cache.
															snake_case_				:							Dict						 =       cached_features_file + ".lock"
															with FileLock(_SCREAMING_SNAKE_CASE				):
																	if os.path.exists(_SCREAMING_SNAKE_CASE				) and not overwrite_cache:
																			logger.info(f'''Loading features from cached file {cached_features_file}'''				)
																			snake_case_				:							Dict						 =       torch.load(_SCREAMING_SNAKE_CASE				)
																	else:
																			logger.info(f'''Creating features from dataset file at {data_dir}'''				)

																			snake_case_				:							Any						 =       (
																			    processor.get_dev_examples(_SCREAMING_SNAKE_CASE				) if evaluate else processor.get_train_examples(_SCREAMING_SNAKE_CASE				)
																			)

																			logger.info("Training examples: %s"		,				len(_SCREAMING_SNAKE_CASE				)				)
																			snake_case_				:							Union[str, Any]						 =       hans_convert_examples_to_features(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)
																			logger.info("Saving features into cached file %s"		,				_SCREAMING_SNAKE_CASE				)
																			torch.save(self.features		,				_SCREAMING_SNAKE_CASE				)






													def __len__(	self				) ->				Tuple:
															return len(self.features				)






													def __getitem__(	self		,				_SCREAMING_SNAKE_CASE				) ->				InputFeatures:
															return self.features[i]






													def       _lowerCAmelCase       (	self				) ->				Dict:
															return self.label_list


if is_tf_available():
							import tensorflow as tf




							class 		UpperCAmelCase_						:


													'''simple docstring'''




													A     :   List[InputFeatures]






													def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = 128		,				_SCREAMING_SNAKE_CASE=False		,				_SCREAMING_SNAKE_CASE = False		,				) ->				Optional[int]:
															snake_case_				:							Tuple						 =       hans_processors[task]()
															snake_case_				:							Dict						 =       processor.get_labels()
															if tokenizer.__class__ in (
															    RobertaTokenizer,
															    RobertaTokenizerFast,
															    XLMRobertaTokenizer,
															    BartTokenizer,
															    BartTokenizerFast,
															):
																	# HACK(label indices are swapped in RoBERTa pretrained model)
																	snake_case_ ,       snake_case_				:							List[str]						 =       label_list[2], label_list[1]
															snake_case_				:							Dict						 =       label_list

															snake_case_				:							int						 =       processor.get_dev_examples(_SCREAMING_SNAKE_CASE				) if evaluate else processor.get_train_examples(_SCREAMING_SNAKE_CASE				)
															snake_case_				:							str						 =       hans_convert_examples_to_features(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)

															def gen():
																	for ex_index, ex in tqdm.tqdm(enumerate(self.features				)		,				desc="convert examples to features"				):
																			if ex_index % 1_0000 == 0:
																					logger.info("Writing example %d of %d" % (ex_index, len(_SCREAMING_SNAKE_CASE				))				)

																			yield (
																			    {
																			        "example_id": 0,
																			        "input_ids": ex.input_ids,
																			        "attention_mask": ex.attention_mask,
																			        "token_type_ids": ex.token_type_ids,
																			    },
																			    ex.label,
																			)

															snake_case_				:							List[Any]						 =       tf.data.Dataset.from_generator(
															    _SCREAMING_SNAKE_CASE		,				(
															        {
															            "example_id": tf.intaa,
															            "input_ids": tf.intaa,
															            "attention_mask": tf.intaa,
															            "token_type_ids": tf.intaa,
															        },
															        tf.intaa,
															    )		,				(
															        {
															            "example_id": tf.TensorShape([]				),
															            "input_ids": tf.TensorShape([None, None]				),
															            "attention_mask": tf.TensorShape([None, None]				),
															            "token_type_ids": tf.TensorShape([None, None]				),
															        },
															        tf.TensorShape([]				),
															    )		,				)






													def       _lowerCAmelCase       (	self				) ->				int:
															return self.dataset






													def __len__(	self				) ->				int:
															return len(self.features				)






													def __getitem__(	self		,				_SCREAMING_SNAKE_CASE				) ->				InputFeatures:
															return self.features[i]






													def       _lowerCAmelCase       (	self				) ->				Dict:
															return self.label_list




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				int:
								return self._create_examples(self._read_tsv(os.path.join(_SCREAMING_SNAKE_CASE		,				"heuristics_train_set.txt"				)				)		,				"train"				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[Any]:
								return self._create_examples(self._read_tsv(os.path.join(_SCREAMING_SNAKE_CASE		,				"heuristics_evaluation_set.txt"				)				)		,				"dev"				)






						def       _lowerCAmelCase       (	self				) ->				Dict:
								return ["contradiction", "entailment", "neutral"]






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Optional[int]:
								snake_case_				:							Optional[Any]						 =       []
								for i, line in enumerate(_SCREAMING_SNAKE_CASE				):
										if i == 0:
												continue
										snake_case_				:							List[Any]						 =       "%s-%s" % (set_type, line[0])
										snake_case_				:							int						 =       line[5]
										snake_case_				:							str						 =       line[6]
										snake_case_				:							Any						 =       line[7][2:] if line[7].startswith("ex"				) else line[7]
										snake_case_				:							Dict						 =       line[0]
										examples.append(InputExample(guid=_SCREAMING_SNAKE_CASE		,				text_a=_SCREAMING_SNAKE_CASE		,				text_b=_SCREAMING_SNAKE_CASE		,				label=_SCREAMING_SNAKE_CASE		,				pairID=_SCREAMING_SNAKE_CASE				)				)
								return examples




def      lowerCAmelCase__	(    _a       :			List[InputExample]  ,      _a       :			List[str]  ,      _a       :			int  ,      _a       :			PreTrainedTokenizer  ,      ):
		snake_case_				:							Optional[Any]						 =       {label: i for i, label in enumerate(_a    )}

		snake_case_				:							Optional[Any]						 =       []
		for ex_index, example in tqdm.tqdm(enumerate(_a    )  ,      desc="convert examples to features"    ):
				if ex_index % 1_00_00 == 0:
						logger.info("Writing example %d" % (ex_index)    )

				snake_case_				:							Optional[Any]						 =       tokenizer(
				    example.text_a  ,      example.text_b  ,      add_special_tokens=_a  ,      max_length=_a  ,      padding="max_length"  ,      truncation=_a  ,      return_overflowing_tokens=_a  ,      )

				snake_case_				:							Dict						 =       label_map[example.label] if example.label in label_map else 0

				snake_case_				:							Optional[Any]						 =       int(example.pairID    )

				features.append(InputFeatures(**_a  ,      label=_a  ,      pairID=_a    )    )

		for i, example in enumerate(examples[:5]    ):
				logger.info("*** Example ***"    )
				logger.info(F'''guid: {example}'''    )
				logger.info(F'''features: {features[i]}'''    )

		return features


lowercase  :							List[str]			  =    {
    '''hans''': 3,
}

lowercase  :							int			  =    {
    '''hans''': HansProcessor,
}
