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


lowerCamelCase_		      =	logging.getLogger(__name__)




@dataclass(frozen=_a					)
class       __A:

  """simple docstring"""
  SCREAMING_SNAKE_CASE__            =     42
  SCREAMING_SNAKE_CASE__            =     42
  SCREAMING_SNAKE_CASE__            =     None
  SCREAMING_SNAKE_CASE__            =     None
  SCREAMING_SNAKE_CASE__            =     None






@dataclass(frozen=_a					)
class       __A:

  """simple docstring"""
  SCREAMING_SNAKE_CASE__            =     42
  SCREAMING_SNAKE_CASE__            =     None
  SCREAMING_SNAKE_CASE__            =     None
  SCREAMING_SNAKE_CASE__            =     None
  SCREAMING_SNAKE_CASE__            =     None


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




    class       __A(							_a					):

      """simple docstring"""
      SCREAMING_SNAKE_CASE__            =     42







      def __init__(self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_ = None			,     SCREAMING_SNAKE_CASE_=False			,     SCREAMING_SNAKE_CASE_ = False			,     ):
           UpperCamelCase__												=							hans_processors[task]()

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

                     UpperCamelCase__												=							(
                         processor.get_dev_examples(__lowerCAmelCase		) if evaluate else processor.get_train_examples(__lowerCAmelCase		)
                     )

                     logger.info("""Training examples: %s"""			,     len(__lowerCAmelCase		)		)
                     UpperCamelCase__												=							hans_convert_examples_to_features(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase		)
                     logger.info("""Saving features into cached file %s"""			,     __lowerCAmelCase		)
                     torch.save(self.features			,     __lowerCAmelCase		)







      def __len__(self		):
           return len(self.features		)







      def __getitem__(self			,     SCREAMING_SNAKE_CASE_		):
           return self.features[i]







      def 			UpperCAmelCase_   (self		):
           return self.label_list


if is_tf_available():
    import tensorflow as tf




    class       __A:

      """simple docstring"""
      SCREAMING_SNAKE_CASE__            =     42







      def __init__(self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_ = 1_28			,     SCREAMING_SNAKE_CASE_=False			,     SCREAMING_SNAKE_CASE_ = False			,     ):
           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(__lowerCAmelCase		) if evaluate else processor.get_train_examples(__lowerCAmelCase		)
           UpperCamelCase__												=							hans_convert_examples_to_features(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase		)

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

                     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(
               __lowerCAmelCase			,     (
                   {
                       """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		):
           return self.dataset







      def __len__(self		):
           return len(self.features		)







      def __getitem__(self			,     SCREAMING_SNAKE_CASE_		):
           return self.features[i]







      def 			UpperCAmelCase_   (self		):
           return self.label_list




class       __A(							_a					):

  """simple docstring"""







  def 			UpperCAmelCase_   (self			,     SCREAMING_SNAKE_CASE_		):
       return self._create_examples(self._read_tsv(os.path.join(__lowerCAmelCase			,     """heuristics_train_set.txt"""		)		)			,     """train"""		)







  def 			UpperCAmelCase_   (self			,     SCREAMING_SNAKE_CASE_		):
       return self._create_examples(self._read_tsv(os.path.join(__lowerCAmelCase			,     """heuristics_evaluation_set.txt"""		)		)			,     """dev"""		)







  def 			UpperCAmelCase_   (self		):
       return ["contradiction", "entailment", "neutral"]







  def 			UpperCAmelCase_   (self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_		):
       UpperCamelCase__												=							[]
       for i, line in enumerate(__lowerCAmelCase		):
            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=__lowerCAmelCase			,     text_a=__lowerCAmelCase			,     text_b=__lowerCAmelCase			,     label=__lowerCAmelCase			,     pairID=__lowerCAmelCase		)		)
       return examples






def 		__magic_name__					(       __a     :			List[InputExample]			,						__a     :			List[str]			,						__a     :			int			,						__a     :			PreTrainedTokenizer			,						):



     '''simple docstring'''




     UpperCamelCase__												=							{label: i for i, label in enumerate(a__		)}

     UpperCamelCase__												=							[]
     for ex_index, example in tqdm.tqdm(enumerate(a__		)			,						desc="""convert examples to features"""		):
          if ex_index % 10_000 == 0:
               logger.info("""Writing example %d""" % (ex_index)		)

          UpperCamelCase__												=							tokenizer(
              example.text_a			,						example.text_b			,						add_special_tokens=a__			,						max_length=a__			,						padding="""max_length"""			,						truncation=a__			,						return_overflowing_tokens=a__			,						)

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

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


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




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












import json
import os
import shutil
import tempfile
from unittest import TestCase

from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow
from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available


if is_torch_available() and is_datasets_available() and is_faiss_available():
					from transformers.models.rag.configuration_rag import RagConfig
					from transformers.models.rag.tokenization_rag import RagTokenizer

@require_faiss
@require_torch
class 							__SCREAMING_SNAKE_CASE       (  _a							):






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      tempfile.mkdtemp()
														UpperCamelCase__					  =      8

														# DPR tok
														UpperCamelCase__					  =      [
														    """[UNK]""",
														    """[CLS]""",
														    """[SEP]""",
														    """[PAD]""",
														    """[MASK]""",
														    """want""",
														    """##want""",
														    """##ed""",
														    """wa""",
														    """un""",
														    """runn""",
														    """##ing""",
														    """,""",
														    """low""",
														    """lowest""",
														]
														UpperCamelCase__					  =      os.path.join(self.tmpdirname	,			"""dpr_tokenizer"""	)
														os.makedirs(__lowerCAmelCase	,			exist_ok=__lowerCAmelCase	)
														UpperCamelCase__					  =      os.path.join(__lowerCAmelCase	,			DPR_VOCAB_FILES_NAMES["""vocab_file"""]	)
														with open(self.vocab_file	,			"""w"""	,			encoding="""utf-8"""	) as vocab_writer:
																					vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]	)	)

														# BART tok
														UpperCamelCase__					  =      [
														    """l""",
														    """o""",
														    """w""",
														    """e""",
														    """r""",
														    """s""",
														    """t""",
														    """i""",
														    """d""",
														    """n""",
														    """\u0120""",
														    """\u0120l""",
														    """\u0120n""",
														    """\u0120lo""",
														    """\u0120low""",
														    """er""",
														    """\u0120lowest""",
														    """\u0120newer""",
														    """\u0120wider""",
														    """<unk>""",
														]
														UpperCamelCase__					  =      dict(zip(__lowerCAmelCase	,			range(len(__lowerCAmelCase	)	)	)	)
														UpperCamelCase__					  =      ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
														UpperCamelCase__					  =      {"""unk_token""": """<unk>"""}

														UpperCamelCase__					  =      os.path.join(self.tmpdirname	,			"""bart_tokenizer"""	)
														os.makedirs(__lowerCAmelCase	,			exist_ok=__lowerCAmelCase	)
														UpperCamelCase__					  =      os.path.join(__lowerCAmelCase	,			BART_VOCAB_FILES_NAMES["""vocab_file"""]	)
														UpperCamelCase__					  =      os.path.join(__lowerCAmelCase	,			BART_VOCAB_FILES_NAMES["""merges_file"""]	)
														with open(self.vocab_file	,			"""w"""	,			encoding="""utf-8"""	) as fp:
																					fp.write(json.dumps(__lowerCAmelCase	) + """\n"""	)
														with open(self.merges_file	,			"""w"""	,			encoding="""utf-8"""	) as fp:
																					fp.write("""\n""".join(__lowerCAmelCase	)	)






							def 					_lowerCamelCase		(    self	):
														return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname	,			"""dpr_tokenizer"""	)	)






							def 					_lowerCamelCase		(    self	):
														return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname	,			"""bart_tokenizer"""	)	)






							def 					_lowerCamelCase		(    self	):
														shutil.rmtree(self.tmpdirname	)






							@require_tokenizers
							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      os.path.join(self.tmpdirname	,			"""rag_tokenizer"""	)
														UpperCamelCase__					  =      RagConfig(question_encoder=DPRConfig().to_dict()	,			generator=BartConfig().to_dict()	)
														UpperCamelCase__					  =      RagTokenizer(question_encoder=self.get_dpr_tokenizer()	,			generator=self.get_bart_tokenizer()	)
														rag_config.save_pretrained(__lowerCAmelCase	)
														rag_tokenizer.save_pretrained(__lowerCAmelCase	)
														UpperCamelCase__					  =      RagTokenizer.from_pretrained(__lowerCAmelCase	,			config=__lowerCAmelCase	)
														self.assertIsInstance(new_rag_tokenizer.question_encoder	,			__lowerCAmelCase	)
														self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab()	,			rag_tokenizer.question_encoder.get_vocab()	)
														self.assertIsInstance(new_rag_tokenizer.generator	,			__lowerCAmelCase	)
														self.assertEqual(new_rag_tokenizer.generator.get_vocab()	,			rag_tokenizer.generator.get_vocab()	)






							@slow
							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      RagTokenizer.from_pretrained("""facebook/rag-token-nq"""	)
														UpperCamelCase__					  =      [
														    """who got the first nobel prize in physics""",
														    """when is the next deadpool movie being released""",
														    """which mode is used for short wave broadcast service""",
														    """who is the owner of reading football club""",
														    """when is the next scandal episode coming out""",
														    """when is the last time the philadelphia won the superbowl""",
														    """what is the most current adobe flash player version""",
														    """how many episodes are there in dragon ball z""",
														    """what is the first step in the evolution of the eye""",
														    """where is gall bladder situated in human body""",
														    """what is the main mineral in lithium batteries""",
														    """who is the president of usa right now""",
														    """where do the greasers live in the outsiders""",
														    """panda is a national animal of which country""",
														    """what is the name of manchester united stadium""",
														]
														UpperCamelCase__					  =      tokenizer(__lowerCAmelCase	)
														self.assertIsNotNone(__lowerCAmelCase	)







							@slow
							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      RagTokenizer.from_pretrained("""facebook/rag-sequence-nq"""	)
														UpperCamelCase__					  =      [
														    """who got the first nobel prize in physics""",
														    """when is the next deadpool movie being released""",
														    """which mode is used for short wave broadcast service""",
														    """who is the owner of reading football club""",
														    """when is the next scandal episode coming out""",
														    """when is the last time the philadelphia won the superbowl""",
														    """what is the most current adobe flash player version""",
														    """how many episodes are there in dragon ball z""",
														    """what is the first step in the evolution of the eye""",
														    """where is gall bladder situated in human body""",
														    """what is the main mineral in lithium batteries""",
														    """who is the president of usa right now""",
														    """where do the greasers live in the outsiders""",
														    """panda is a national animal of which country""",
														    """what is the name of manchester united stadium""",
														]
														UpperCamelCase__					  =      tokenizer(__lowerCAmelCase	)
														self.assertIsNotNone(__lowerCAmelCase	)




