






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__      :	Dict       	=      logging.get_logger(__name__)


class 						_a       (  enum.Enum    ):






  """simple docstring"""





  A_						=   0
  A_						=   1



@add_end_docstrings(UpperCAmelCase__    )
class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """generated"""




  def __init__(     self		,		*_UpperCAmelCase		,		**_UpperCAmelCase )			-> Union[str, Any]:
     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    _UpperCAmelCase     (     self		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		**_UpperCAmelCase		,		)			-> Dict:
     UpperCamelCase_									=     {}
     if truncation is not None:
        UpperCamelCase_									=     truncation

     UpperCamelCase_									=     generate_kwargs

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

     if clean_up_tokenization_spaces is not None:
        UpperCamelCase_									=     clean_up_tokenization_spaces

     if stop_sequence is not None:
        UpperCamelCase_									=     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.' )
        UpperCamelCase_									=     stop_sequence_ids[0]

     return preprocess_params, forward_params, postprocess_params




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Dict:
     return True




  def    _UpperCAmelCase     (     self		,		*_UpperCAmelCase		,		_UpperCAmelCase )			-> Dict:
     UpperCamelCase_									=     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' )
        UpperCamelCase_									=     ([prefix + arg for arg in args[0]],)
        UpperCamelCase_									=     True

     elif isinstance(args[0]		,		_UpperCAmelCase ):
        UpperCamelCase_									=     (prefix + args[0],)
        UpperCamelCase_									=     False
     else:
        raise ValueError(
            f""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" )
     UpperCamelCase_									=     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		,		*_UpperCAmelCase		,		**_UpperCAmelCase )			-> Optional[Any]:
     UpperCamelCase_									=     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    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase=TruncationStrategy.DO_NOT_TRUNCATE		,		**_UpperCAmelCase )			-> Union[str, Any]:
     UpperCamelCase_									=     self._parse_and_tokenize(_UpperCAmelCase		,		truncation=_UpperCAmelCase		,		**_UpperCAmelCase )
     return inputs




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		**_UpperCAmelCase )			-> Union[str, Any]:
     if self.framework == "pt":
        UpperCamelCase_		,      UpperCamelCase_									=     model_inputs['input_ids'].shape
     elif self.framework == "tf":
        UpperCamelCase_		,      UpperCamelCase_									=     tf.shape(model_inputs['input_ids'] ).numpy()

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




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase=ReturnType.TEXT		,		_UpperCAmelCase=False )			-> Optional[int]:
     UpperCamelCase_									=     []
     for output_ids in model_outputs["output_ids"][0]:
        if return_type == ReturnType.TENSORS:
           UpperCamelCase_									=     {f"""{self.return_name}_token_ids""": output_ids}
        elif return_type == ReturnType.TEXT:
           UpperCamelCase_									=     {
               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 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """summary"""




  def __call__(     self		,		*_UpperCAmelCase		,		**_UpperCAmelCase )			-> Tuple:
     return super().__call__(*_UpperCAmelCase		,		**_UpperCAmelCase )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> bool:
     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 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """translation"""




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[str]:
     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    _UpperCAmelCase     (     self		,		*_UpperCAmelCase		,		_UpperCAmelCase=TruncationStrategy.DO_NOT_TRUNCATE		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None )			-> Union[str, Any]:
     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    _UpperCAmelCase     (     self		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		**_UpperCAmelCase )			-> List[Any]:
     UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_									=     super()._sanitize_parameters(**_UpperCAmelCase )
     if src_lang is not None:
        UpperCamelCase_									=     src_lang
     if tgt_lang is not None:
        UpperCamelCase_									=     tgt_lang
     if src_lang is None and tgt_lang is None:
        # Backward compatibility, direct arguments use is preferred.
        UpperCamelCase_									=     kwargs.get('task'		,		self.task )
        UpperCamelCase_									=     task.split('_' )
        if task and len(_UpperCAmelCase ) == 4:
           # translation, XX, to YY
           UpperCamelCase_									=     items[1]
           UpperCamelCase_									=     items[3]
     return preprocess_params, forward_params, postprocess_params




  def __call__(     self		,		*_UpperCAmelCase		,		**_UpperCAmelCase )			-> Any:
     return super().__call__(*_UpperCAmelCase		,		**_UpperCAmelCase )













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__      :	str       	=      logging.getLogger(__name__)


@dataclass(frozen=UpperCAmelCase__    )
class 						_a       :






  """simple docstring"""





  A_						=   42
  A_						=   42
  A_						=   None
  A_						=   None
  A_						=   None




@dataclass(frozen=UpperCAmelCase__    )
class 						_a       :






  """simple docstring"""





  A_						=   42
  A_						=   None
  A_						=   None
  A_						=   None
  A_						=   None


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


 class 						_a       (  UpperCAmelCase__    ):






   """simple docstring"""





   A_						=   42




   def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		_UpperCAmelCase=False		,		_UpperCAmelCase = False		,		)			-> Any:
      UpperCamelCase_									=     hans_processors[task]()

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

      # Make sure only the first process in distributed training processes the dataset,
      # and the others will use the cache.
      UpperCamelCase_									=     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}""" )
            UpperCamelCase_									=     torch.load(_UpperCAmelCase )
         else:
            logger.info(f"""Creating features from dataset file at {data_dir}""" )

            UpperCamelCase_									=     (
                processor.get_dev_examples(_UpperCAmelCase ) if evaluate else processor.get_train_examples(_UpperCAmelCase )
            )

            logger.info('Training examples: %s'		,		len(_UpperCAmelCase ) )
            UpperCamelCase_									=     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 )			-> Dict:
      return len(self.features )




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




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


if is_tf_available():
 import tensorflow as tf


 class 						_a       :






   """simple docstring"""





   A_						=   42




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

      UpperCamelCase_									=     processor.get_dev_examples(_UpperCAmelCase ) if evaluate else processor.get_train_examples(_UpperCAmelCase )
      UpperCamelCase_									=     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 % 10000 == 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,
            )

      UpperCamelCase_									=     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    _UpperCAmelCase     (     self )			-> List[str]:
      return self.dataset




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




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




   def    _UpperCAmelCase     (     self )			-> int:
      return self.label_list


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> Tuple:
     return self._create_examples(self._read_tsv(os.path.join(_UpperCAmelCase		,		'heuristics_train_set.txt' ) )		,		'train' )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase )			-> Dict:
     return self._create_examples(self._read_tsv(os.path.join(_UpperCAmelCase		,		'heuristics_evaluation_set.txt' ) )		,		'dev' )




  def    _UpperCAmelCase     (     self )			-> List[Any]:
     return ["contradiction", "entailment", "neutral"]




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[str]:
     UpperCamelCase_									=     []
     for i, line in enumerate(_UpperCAmelCase ):
        if i == 0:
           continue
        UpperCamelCase_									=     '%s-%s' % (set_type, line[0])
        UpperCamelCase_									=     line[5]
        UpperCamelCase_									=     line[6]
        UpperCamelCase_									=     line[7][2:] if line[7].startswith('ex' ) else line[7]
        UpperCamelCase_									=     line[0]
        examples.append(InputExample(guid=_UpperCAmelCase		,		text_a=_UpperCAmelCase		,		text_b=_UpperCAmelCase		,		label=_UpperCAmelCase		,		pairID=_UpperCAmelCase ) )
     return examples






def     _snake_case    (__lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase    ,      ):
   UpperCamelCase_									=     {label: i for i, label in enumerate(__lowercase)}

   UpperCamelCase_									=     []
   for ex_index, example in tqdm.tqdm(enumerate(__lowercase)    ,      desc='convert examples to features'):
      if ex_index % 10000 == 0:
         logger.info('Writing example %d' % (ex_index))

      UpperCamelCase_									=     tokenizer(
          example.text_a    ,      example.text_b    ,      add_special_tokens=__lowercase    ,      max_length=__lowercase    ,      padding='max_length'    ,      truncation=__lowercase    ,      return_overflowing_tokens=__lowercase    ,      )

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

      UpperCamelCase_									=     int(example.pairID)

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

   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__      :	List[str]       	=      {
    """hans""": 3,
}

snake_case__      :	Union[str, Any]       	=      {
    """hans""": HansProcessor,
}





