

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


_a					:			int							=    logging.getLogger(__name__)



@dataclass(frozen=a			)
class 							lowercase_						:

  '''simple docstring'''





  __lowerCAmelCase       :			str
  __lowerCAmelCase       :			str
  __lowerCAmelCase       :			Optional[str]     	= None
  __lowerCAmelCase       :			Optional[str]     	= None
  __lowerCAmelCase       :			Optional[str]     	= None




@dataclass(frozen=a			)
class 							lowercase_						:

  '''simple docstring'''





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


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



  class 							lowercase_						(		a			):

    '''simple docstring'''





    __lowerCAmelCase       :			List[InputFeatures]
    def __init__(  self ,			a_ ,			a_ ,			a_ ,			a_ = None ,			a_=False ,			a_ = False ,			)				->					Any:


      """simple docstring"""
      UpperCAmelCase    				=						hans_processors[task]()

      UpperCAmelCase    				=						os.path.join(
          a_ ,			'cached_{}_{}_{}_{}'.format(
              'dev' if evaluate else 'train' ,			tokenizer.__class__.__name__ ,			str(a_  ) ,			a_ ,			) ,			)
      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(a_  ):
        if os.path.exists(a_  ) and not overwrite_cache:
          logger.info(F'''Loading features from cached file {cached_features_file}'''  )
          UpperCAmelCase    				=						torch.load(a_  )
        else:
          logger.info(F'''Creating features from dataset file at {data_dir}'''  )

          UpperCAmelCase    				=						(
              processor.get_dev_examples(a_  ) if evaluate else processor.get_train_examples(a_  )
          )

          logger.info('Training examples: %s' ,			len(a_  )  )
          UpperCAmelCase    				=						hans_convert_examples_to_features(a_ ,			a_ ,			a_ ,			a_  )
          logger.info('Saving features into cached file %s' ,			a_  )
          torch.save(self.features ,			a_  )
    def __len__(  self  )				->					Any:


      """simple docstring"""
      return len(self.features  )
    def __getitem__(  self ,			a_  )				->					InputFeatures:


      """simple docstring"""
      return self.features[i]





    def     snake_case_      (  self  )				->					Tuple:


      """simple docstring"""
      return self.label_list


if is_tf_available():
  import tensorflow as tf



  class 							lowercase_						:

    '''simple docstring'''





    __lowerCAmelCase       :			List[InputFeatures]
    def __init__(  self ,			a_ ,			a_ ,			a_ ,			a_ = 1_2_8 ,			a_=False ,			a_ = False ,			)				->					Optional[Any]:


      """simple docstring"""
      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(a_  ) if evaluate else processor.get_train_examples(a_  )
      UpperCAmelCase    				=						hans_convert_examples_to_features(a_ ,			a_ ,			a_ ,			a_  )

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

          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(
          a_ ,			(
              {
                  '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     snake_case_      (  self  )				->					Optional[Any]:


      """simple docstring"""
      return self.dataset
    def __len__(  self  )				->					Tuple:


      """simple docstring"""
      return len(self.features  )
    def __getitem__(  self ,			a_  )				->					InputFeatures:


      """simple docstring"""
      return self.features[i]





    def     snake_case_      (  self  )				->					Dict:


      """simple docstring"""
      return self.label_list



class 							lowercase_						(		a			):

  '''simple docstring'''





  def     snake_case_      (  self ,			a_  )				->					Dict:


    """simple docstring"""
    return self._create_examples(self._read_tsv(os.path.join(a_ ,			'heuristics_train_set.txt'  )  ) ,			'train'  )
  def     snake_case_      (  self ,			a_  )				->					str:


    """simple docstring"""
    return self._create_examples(self._read_tsv(os.path.join(a_ ,			'heuristics_evaluation_set.txt'  )  ) ,			'dev'  )
  def     snake_case_      (  self  )				->					Tuple:


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





  def     snake_case_      (  self ,			a_ ,			a_  )				->					Dict:


    """simple docstring"""
    UpperCAmelCase    				=						[]
    for i, line in enumerate(a_  ):
      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=a_ ,			text_a=a_ ,			text_b=a_ ,			label=a_ ,			pairID=a_  )  )
    return examples




def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : List[InputExample]							, SCREAMING_SNAKE_CASE   : List[str]							, SCREAMING_SNAKE_CASE   : int							, SCREAMING_SNAKE_CASE   : PreTrainedTokenizer							, ):
  UpperCAmelCase    				=						{label: i for i, label in enumerate(SCREAMING_SNAKE_CASE    )}

  UpperCAmelCase    				=						[]
  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)    )

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

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

    UpperCAmelCase    				=						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


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



_a					:			str							=    {
    'hans': HansProcessor,
}





'''simple docstring'''




def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : list[int]							, SCREAMING_SNAKE_CASE   : list[int]							, SCREAMING_SNAKE_CASE   : int    ):
  return not any(
      neighbour == 1 and colored_vertices[i] == color
      for i, neighbour in enumerate(SCREAMING_SNAKE_CASE    )    )


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : list[list[int]]							, SCREAMING_SNAKE_CASE   : int							, SCREAMING_SNAKE_CASE   : list[int]							, SCREAMING_SNAKE_CASE   : int    ):

  # Base Case
  if index == len(SCREAMING_SNAKE_CASE    ):
    return True

  # Recursive Step
  for i in range(SCREAMING_SNAKE_CASE    ):
    if valid_coloring(graph[index]							, SCREAMING_SNAKE_CASE							, SCREAMING_SNAKE_CASE    ):
      # Color current vertex
      UpperCAmelCase    				=						i
      # Validate coloring
      if util_color(SCREAMING_SNAKE_CASE							, SCREAMING_SNAKE_CASE							, SCREAMING_SNAKE_CASE							, index + 1    ):
        return True
      # Backtrack
      UpperCAmelCase    				=						-1
  return False



def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : list[list[int]]							, SCREAMING_SNAKE_CASE   : int    ):
  UpperCAmelCase    				=						[-1] * len(SCREAMING_SNAKE_CASE    )

  if util_color(SCREAMING_SNAKE_CASE							, SCREAMING_SNAKE_CASE							, SCREAMING_SNAKE_CASE							, 0    ):
    return colored_vertices

  return []


