
"""simple docstring"""



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,
)


_snake_case          =						logging.getLogger(__name__)
@dataclass(frozen=UpperCAmelCase__							)
class        _SCREAMING_SNAKE_CASE  :






    '''simple docstring'''



    SCREAMING_SNAKE_CASE_:							str
    SCREAMING_SNAKE_CASE_:							str
    SCREAMING_SNAKE_CASE_:							Optional[str]							=					None
    SCREAMING_SNAKE_CASE_:							Optional[str]							=					None
    SCREAMING_SNAKE_CASE_:							Optional[str]							=					None






@dataclass(frozen=UpperCAmelCase__							)
class        _SCREAMING_SNAKE_CASE  :






    '''simple docstring'''



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


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






     '''simple docstring'''



     SCREAMING_SNAKE_CASE_:							List[InputFeatures]


     def __init__(					self	:			Any				,     UpperCAmelCase_	:			str				,     UpperCAmelCase_	:			PreTrainedTokenizer				,     UpperCAmelCase_	:			str				,     UpperCAmelCase_	:			Optional[int] = None				,     UpperCAmelCase_	:			str=False				,     UpperCAmelCase_	:			bool = False				,     )		->  Dict:







            """simple docstring"""




            _lowerCAmelCase  	=			hans_processors[task]()

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

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

                          _lowerCAmelCase  	=			(
                              processor.get_dev_examples(UpperCAmelCase_  ) if evaluate else processor.get_train_examples(UpperCAmelCase_  )
                          )

                          logger.info('Training examples: %s'				,     len(UpperCAmelCase_  )  )
                          _lowerCAmelCase  	=			hans_convert_examples_to_features(UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_  )
                          logger.info('Saving features into cached file %s'				,     UpperCAmelCase_  )
                          torch.save(self.features				,     UpperCAmelCase_  )


     def __len__(					self	:			Any  )		->  str:







            """simple docstring"""




            return len(self.features  )


     def __getitem__(					self	:			Any				,     UpperCAmelCase_	:			Any  )		->  InputFeatures:







            """simple docstring"""




            return self.features[i]







     def 				__lowerCamelCase	(					self	:			str  )		->  str:







            """simple docstring"""




            return self.label_list


if is_tf_available():
 import tensorflow as tf
 class        _SCREAMING_SNAKE_CASE  :






     '''simple docstring'''



     SCREAMING_SNAKE_CASE_:							List[InputFeatures]


     def __init__(					self	:			Optional[Any]				,     UpperCAmelCase_	:			str				,     UpperCAmelCase_	:			PreTrainedTokenizer				,     UpperCAmelCase_	:			str				,     UpperCAmelCase_	:			Optional[int] = 128				,     UpperCAmelCase_	:			Tuple=False				,     UpperCAmelCase_	:			bool = False				,     )		->  Any:







            """simple docstring"""




            _lowerCAmelCase  	=			hans_processors[task]()
            _lowerCAmelCase  	=			processor.get_labels()
            if tokenizer.__class__ in (
                RobertaTokenizer,
                RobertaTokenizerFast,
                XLMRobertaTokenizer,
                BartTokenizer,
                BartTokenizerFast,
            ):
                   # HACK(label indices are swapped in RoBERTa pretrained model)
                   _lowerCAmelCase  	=			label_list[2], label_list[1]
            _lowerCAmelCase  	=			label_list

            _lowerCAmelCase  	=			processor.get_dev_examples(UpperCAmelCase_  ) if evaluate else processor.get_train_examples(UpperCAmelCase_  )
            _lowerCAmelCase  	=			hans_convert_examples_to_features(UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_  )

            def gen():
                   for ex_index, ex in tqdm.tqdm(enumerate(self.features  )				,     desc='convert examples to features'  ):
                          if ex_index % 10_000 == 0:
                                 logger.info('Writing example %d of %d' % (ex_index, len(UpperCAmelCase_  ))  )

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

            _lowerCAmelCase  	=			tf.data.Dataset.from_generator(
                UpperCAmelCase_				,     (
                    {
                        '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	:			Any  )		->  Dict:







            """simple docstring"""




            return self.dataset


     def __len__(					self	:			str  )		->  Dict:







            """simple docstring"""




            return len(self.features  )


     def __getitem__(					self	:			List[str]				,     UpperCAmelCase_	:			Optional[Any]  )		->  InputFeatures:







            """simple docstring"""




            return self.features[i]







     def 				__lowerCamelCase	(					self	:			Union[str, Any]  )		->  Optional[Any]:







            """simple docstring"""




            return self.label_list
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase__							):






    '''simple docstring'''



    def 				__lowerCamelCase	(					self	:			str				,     UpperCAmelCase_	:			List[Any]  )		->  int:







           """simple docstring"""




           return self._create_examples(self._read_tsv(os.path.join(UpperCAmelCase_				,     'heuristics_train_set.txt'  )  )				,     'train'  )


    def 				__lowerCamelCase	(					self	:			int				,     UpperCAmelCase_	:			Tuple  )		->  Optional[Any]:







           """simple docstring"""




           return self._create_examples(self._read_tsv(os.path.join(UpperCAmelCase_				,     'heuristics_evaluation_set.txt'  )  )				,     'dev'  )


    def 				__lowerCamelCase	(					self	:			Optional[Any]  )		->  Dict:







           """simple docstring"""




           return ["contradiction", "entailment", "neutral"]







    def 				__lowerCamelCase	(					self	:			Dict				,     UpperCAmelCase_	:			Dict				,     UpperCAmelCase_	:			List[Any]  )		->  Tuple:







           """simple docstring"""




           _lowerCAmelCase  	=			[]
           for i, line in enumerate(UpperCAmelCase_  ):
                  if i == 0:
                         continue
                  _lowerCAmelCase  	=			"""%s-%s""" % (set_type, line[0])
                  _lowerCAmelCase  	=			line[5]
                  _lowerCAmelCase  	=			line[6]
                  _lowerCAmelCase  	=			line[7][2:] if line[7].startswith('ex'  ) else line[7]
                  _lowerCAmelCase  	=			line[0]
                  examples.append(InputExample(guid=UpperCAmelCase_				,     text_a=UpperCAmelCase_				,     text_b=UpperCAmelCase_				,     label=UpperCAmelCase_				,     pairID=UpperCAmelCase_  )  )
           return examples






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					Optional[Any]     ,  SCREAMING_SNAKE_CASE:					Optional[int]     ,  SCREAMING_SNAKE_CASE:					List[str]     ,  SCREAMING_SNAKE_CASE:					Optional[int]     ,  ):






       """simple docstring"""



       _lowerCAmelCase  	=			{label: i for i, label in enumerate(SCREAMING_SNAKE_CASE						)}

       _lowerCAmelCase  	=			[]
       for ex_index, example in tqdm.tqdm(enumerate(SCREAMING_SNAKE_CASE						)     ,  desc='convert examples to features'						):
              if ex_index % 1_0000 == 0:
                     logger.info('Writing example %d' % (ex_index)						)

              _lowerCAmelCase  	=			tokenizer(
                  example.text_a     ,  example.text_b     ,  add_special_tokens=SCREAMING_SNAKE_CASE     ,  max_length=SCREAMING_SNAKE_CASE     ,  padding='max_length'     ,  truncation=SCREAMING_SNAKE_CASE     ,  return_overflowing_tokens=SCREAMING_SNAKE_CASE     ,  )

              _lowerCAmelCase  	=			label_map[example.label] if example.label in label_map else 0

              _lowerCAmelCase  	=			int(example.pairID						)

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

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

       return features


_snake_case          =						{
    '''hans''': 3,
}

_snake_case          =						{
    '''hans''': HansProcessor,
}








"""simple docstring"""



import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
	import tensorflow as tf

	from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

if is_torch_available():
	from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

_snake_case          =						logging.get_logger(__name__)
class        _SCREAMING_SNAKE_CASE  (  enum.Enum							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Any							=					0
				SCREAMING_SNAKE_CASE_:							str							=					1






@add_end_docstrings(UpperCAmelCase							)
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							int							=					"generated"


				def __init__(					self	:			Optional[Any]				,     *UpperCAmelCase_	:			Dict				,     **UpperCAmelCase_	:			Union[str, Any]  )		->  Optional[Any]:







											"""simple docstring"""




											super().__init__(*UpperCAmelCase_				,     **UpperCAmelCase_  )

											self.check_model_type(
											    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
											    if self.framework == 'tf'
											    else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING  )


				def 				__lowerCamelCase	(					self	:			List[str]				,     UpperCAmelCase_	:			Any=None				,     UpperCAmelCase_	:			List[str]=None				,     UpperCAmelCase_	:			Union[str, Any]=None				,     UpperCAmelCase_	:			List[str]=None				,     UpperCAmelCase_	:			Tuple=None				,     UpperCAmelCase_	:			Optional[Any]=None				,     **UpperCAmelCase_	:			Union[str, Any]				,     )		->  int:







											"""simple docstring"""




											_lowerCAmelCase  	=			{}
											if truncation is not None:
																		_lowerCAmelCase  	=			truncation

											_lowerCAmelCase  	=			generate_kwargs

											_lowerCAmelCase  	=			{}
											if return_tensors is not None and return_type is None:
																		_lowerCAmelCase  	=			ReturnType.TENSORS if return_tensors else ReturnType.TEXT
											if return_type is not None:
																		_lowerCAmelCase  	=			return_type

											if clean_up_tokenization_spaces is not None:
																		_lowerCAmelCase  	=			clean_up_tokenization_spaces

											if stop_sequence is not None:
																		_lowerCAmelCase  	=			self.tokenizer.encode(UpperCAmelCase_				,     add_special_tokens=UpperCAmelCase_  )
																		if len(UpperCAmelCase_  ) > 1:
																									warnings.warn(
																									    'Stopping on a multiple token sequence is not yet supported on transformers. The first token of'
																									    ' the stop sequence will be used as the stop sequence string in the interim.'  )
																		_lowerCAmelCase  	=			stop_sequence_ids[0]

											return preprocess_params, forward_params, postprocess_params


				def 				__lowerCamelCase	(					self	:			List[Any]				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int  )		->  Optional[Any]:







											"""simple docstring"""




											return True


				def 				__lowerCamelCase	(					self	:			Union[str, Any]				,     *UpperCAmelCase_	:			str				,     UpperCAmelCase_	:			int  )		->  str:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.model.config.prefix if self.model.config.prefix is not None else ''
											if isinstance(args[0]				,     UpperCAmelCase_  ):
																		if self.tokenizer.pad_token_id is None:
																									raise ValueError('Please make sure that the tokenizer has a pad_token_id when using a batch input'  )
																		_lowerCAmelCase  	=			([prefix + arg for arg in args[0]],)
																		_lowerCAmelCase  	=			True

											elif isinstance(args[0]				,     UpperCAmelCase_  ):
																		_lowerCAmelCase  	=			(prefix + args[0],)
																		_lowerCAmelCase  	=			False
											else:
																		raise ValueError(
																		    F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`"""  )
											_lowerCAmelCase  	=			self.tokenizer(*UpperCAmelCase_				,     padding=UpperCAmelCase_				,     truncation=UpperCAmelCase_				,     return_tensors=self.framework  )
											# This is produced by tokenizers but is an invalid generate kwargs
											if "token_type_ids" in inputs:
																		del inputs["token_type_ids"]
											return inputs


				def __call__(					self	:			Union[str, Any]				,     *UpperCAmelCase_	:			Optional[Any]				,     **UpperCAmelCase_	:			Tuple  )		->  str:







											"""simple docstring"""




											_lowerCAmelCase  	=			super().__call__(*UpperCAmelCase_				,     **UpperCAmelCase_  )
											if (
											    isinstance(args[0]				,     UpperCAmelCase_  )
											    and all(isinstance(UpperCAmelCase_				,     UpperCAmelCase_  ) for el in args[0]  )
											    and all(len(UpperCAmelCase_  ) == 1 for res in result  )
											):
																		return [res[0] for res in result]
											return result


				def 				__lowerCamelCase	(					self	:			int				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			Dict=TruncationStrategy.DO_NOT_TRUNCATE				,     **UpperCAmelCase_	:			Tuple  )		->  Tuple:







											"""simple docstring"""




											_lowerCAmelCase  	=			self._parse_and_tokenize(UpperCAmelCase_				,     truncation=UpperCAmelCase_				,     **UpperCAmelCase_  )
											return inputs


				def 				__lowerCamelCase	(					self	:			Optional[Any]				,     UpperCAmelCase_	:			List[Any]				,     **UpperCAmelCase_	:			List[str]  )		->  Any:







											"""simple docstring"""




											if self.framework == "pt":
																		_lowerCAmelCase	,		_lowerCAmelCase  	=			model_inputs['input_ids'].shape
											elif self.framework == "tf":
																		_lowerCAmelCase	,		_lowerCAmelCase  	=			tf.shape(model_inputs['input_ids']  ).numpy()

											_lowerCAmelCase  	=			generate_kwargs.get('min_length'				,     self.model.config.min_length  )
											_lowerCAmelCase  	=			generate_kwargs.get('max_length'				,     self.model.config.max_length  )
											self.check_inputs(UpperCAmelCase_				,     generate_kwargs['min_length']				,     generate_kwargs['max_length']  )
											_lowerCAmelCase  	=			self.model.generate(**UpperCAmelCase_				,     **UpperCAmelCase_  )
											_lowerCAmelCase  	=			output_ids.shape[0]
											if self.framework == "pt":
																		_lowerCAmelCase  	=			output_ids.reshape(UpperCAmelCase_				,     out_b // in_b				,     *output_ids.shape[1:]  )
											elif self.framework == "tf":
																		_lowerCAmelCase  	=			tf.reshape(UpperCAmelCase_				,     (in_b, out_b // in_b, *output_ids.shape[1:])  )
											return {"output_ids": output_ids}







				def 				__lowerCamelCase	(					self	:			Dict				,     UpperCAmelCase_	:			Tuple				,     UpperCAmelCase_	:			Union[str, Any]=ReturnType.TEXT				,     UpperCAmelCase_	:			Optional[Any]=False  )		->  str:







											"""simple docstring"""




											_lowerCAmelCase  	=			[]
											for output_ids in model_outputs["output_ids"][0]:
																		if return_type == ReturnType.TENSORS:
																									_lowerCAmelCase  	=			{F"""{self.return_name}_token_ids""": output_ids}
																		elif return_type == ReturnType.TEXT:
																									_lowerCAmelCase  	=			{
																									    F"""{self.return_name}_text""": self.tokenizer.decode(
																									        UpperCAmelCase_				,     skip_special_tokens=UpperCAmelCase_				,     clean_up_tokenization_spaces=UpperCAmelCase_				,     )
																									}
																		records.append(UpperCAmelCase_  )
											return records






@add_end_docstrings(UpperCAmelCase							)
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Optional[Any]							=					"summary"


				def __call__(					self	:			Optional[int]				,     *UpperCAmelCase_	:			Optional[Any]				,     **UpperCAmelCase_	:			Dict  )		->  int:







											"""simple docstring"""




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







				def 				__lowerCamelCase	(					self	:			Dict				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int  )		->  bool:







											"""simple docstring"""




											if max_length < min_length:
																		logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}."""  )

											if input_length < max_length:
																		logger.warning(
																		    F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """
																		    'a summarization task, where outputs shorter than the input are typically wanted, you might '
																		    F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})"""  )






@add_end_docstrings(UpperCAmelCase							)
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Optional[int]							=					"translation"


				def 				__lowerCamelCase	(					self	:			str				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			int  )		->  Any:







											"""simple docstring"""




											if input_length > 0.9 * max_length:
																		logger.warning(
																		    F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """
																		    'increasing your max_length manually, e.g. translator(\'...\', max_length=400)'  )
											return True


				def 				__lowerCamelCase	(					self	:			Optional[Any]				,     *UpperCAmelCase_	:			List[Any]				,     UpperCAmelCase_	:			Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE				,     UpperCAmelCase_	:			Tuple=None				,     UpperCAmelCase_	:			Dict=None  )		->  Optional[int]:







											"""simple docstring"""




											if getattr(self.tokenizer				,     '_build_translation_inputs'				,     UpperCAmelCase_  ):
																		return self.tokenizer._build_translation_inputs(
																		    *UpperCAmelCase_				,     return_tensors=self.framework				,     truncation=UpperCAmelCase_				,     src_lang=UpperCAmelCase_				,     tgt_lang=UpperCAmelCase_  )
											else:
																		return super()._parse_and_tokenize(*UpperCAmelCase_				,     truncation=UpperCAmelCase_  )


				def 				__lowerCamelCase	(					self	:			Union[str, Any]				,     UpperCAmelCase_	:			Tuple=None				,     UpperCAmelCase_	:			Union[str, Any]=None				,     **UpperCAmelCase_	:			Optional[int]  )		->  Union[str, Any]:







											"""simple docstring"""




											_lowerCAmelCase	,		_lowerCAmelCase	,		_lowerCAmelCase  	=			super()._sanitize_parameters(**UpperCAmelCase_  )
											if src_lang is not None:
																		_lowerCAmelCase  	=			src_lang
											if tgt_lang is not None:
																		_lowerCAmelCase  	=			tgt_lang
											if src_lang is None and tgt_lang is None:
																		# Backward compatibility, direct arguments use is preferred.
																		_lowerCAmelCase  	=			kwargs.get('task'				,     self.task  )
																		_lowerCAmelCase  	=			task.split('_'  )
																		if task and len(UpperCAmelCase_  ) == 4:
																									# translation, XX, to YY
																									_lowerCAmelCase  	=			items[1]
																									_lowerCAmelCase  	=			items[3]
											return preprocess_params, forward_params, postprocess_params







				def __call__(					self	:			Optional[int]				,     *UpperCAmelCase_	:			int				,     **UpperCAmelCase_	:			Optional[int]  )		->  Union[str, Any]:







											"""simple docstring"""




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






