




"""simple docstring"""


import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


A_						=				logging.get_logger(__name__)






@dataclass
class 					lowercase:







 '''simple docstring'''





 lowercase__ 					=					field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys() )} )
 lowercase__ 					=					field(
     metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} )
 lowercase__ 					=					field(
     default=1_28       ,			metadata={
         "help": (
             "The maximum total input sequence length after tokenization. Sequences longer "
             "than this will be truncated, sequences shorter will be padded."
         )
     }       ,			)
 lowercase__ 					=					field(
     default=__a       ,			metadata={"help": "Overwrite the cached training and evaluation sets"} )


 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   _snake_case							:		int								=  self.task_name.lower()







class 					lowercase(     __a ):







 '''simple docstring'''





 lowercase__ 					=					"train"
 lowercase__ 					=					"dev"
 lowercase__ 					=					"test"







class 					lowercase(     __a ):







 '''simple docstring'''





 lowercase__ 					=					42
 lowercase__ 					=					42
 lowercase__ 					=					42


 def __init__(				self:		str,      a_:		GlueDataTrainingArguments,      a_:		PreTrainedTokenizerBase,      a_:		Optional[int] = None,      a_:		Union[str, Split] = Split.train,      a_:		Optional[str] = None,      ):




   '''simple docstring'''



   warnings.warn(
       """This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """
       """library. You can have a look at this example script for pointers: """
       """https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py""",      a_,      )
   _snake_case							:		List[str]								=  args
   _snake_case							:		Any								=  glue_processors[args.task_name]()
   _snake_case							:		str								=  glue_output_modes[args.task_name]
   if isinstance(a_,      a_		):
     try:
       _snake_case							:		Optional[Any]								=  Split[mode]
     except KeyError:
       raise KeyError("""mode is not a valid split name"""		)
        # Load data features from cache or dataset file
   _snake_case							:		Tuple								=  os.path.join(
       cache_dir if cache_dir is not None else args.data_dir,      f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}",      )
   _snake_case							:		Dict								=  self.processor.get_labels()
   if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
       "RobertaTokenizer",
       "RobertaTokenizerFast",
       "XLMRobertaTokenizer",
       "BartTokenizer",
       "BartTokenizerFast",
   ):
     # HACK(label indices are swapped in RoBERTa pretrained model)
     _snake_case		,					_snake_case							:		int								=  label_list[2], label_list[1]
   _snake_case							:		Optional[int]								=  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(a_		):
     if os.path.exists(a_		) and not args.overwrite_cache:
       _snake_case							:		Optional[Any]								=  time.time()
       _snake_case							:		Tuple								=  torch.load(a_		)
       logger.info(
           f"Loading features from cached file {cached_features_file} [took %.3f s]",      time.time() - start		)
     else:
       logger.info(f"Creating features from dataset file at {args.data_dir}"		)

       if mode == Split.dev:
         _snake_case							:		str								=  self.processor.get_dev_examples(args.data_dir		)
       elif mode == Split.test:
         _snake_case							:		int								=  self.processor.get_test_examples(args.data_dir		)
       else:
         _snake_case							:		List[Any]								=  self.processor.get_train_examples(args.data_dir		)
       if limit_length is not None:
         _snake_case							:		Union[str, Any]								=  examples[:limit_length]
       _snake_case							:		Tuple								=  glue_convert_examples_to_features(
           a_,      a_,      max_length=args.max_seq_length,      label_list=a_,      output_mode=self.output_mode,      )
       _snake_case							:		List[str]								=  time.time()
       torch.save(self.features,      a_		)
       # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
       logger.info(
           f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"		)


 def __len__(				self:		int		):




   '''simple docstring'''



   return len(self.features		)


 def __getitem__(				self:		List[str],      a_:		List[Any]		):




   '''simple docstring'''



   return self.features[i]


 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   return self.label_list








"""simple docstring"""


import json
import os
import re
import unittest

from transformers import CodeGenTokenizer, CodeGenTokenizerFast
from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class 					lowercase(     __a       ,			unittest.TestCase ):







 '''simple docstring'''





 lowercase__ 					=					CodeGenTokenizer
 lowercase__ 					=					CodeGenTokenizerFast
 lowercase__ 					=					True
 lowercase__ 					=					{"add_prefix_space": True}
 lowercase__ 					=					False


 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   super().setUp()

   # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
   _snake_case							:		Tuple								=  [
       """l""",
       """o""",
       """w""",
       """e""",
       """r""",
       """s""",
       """t""",
       """i""",
       """d""",
       """n""",
       """\u0120""",
       """\u0120l""",
       """\u0120n""",
       """\u0120lo""",
       """\u0120low""",
       """er""",
       """\u0120lowest""",
       """\u0120newer""",
       """\u0120wider""",
       """<unk>""",
       """<|endoftext|>""",
   ]
   _snake_case							:		Tuple								=  dict(zip(a_,      range(len(a_		)		)		)		)
   _snake_case							:		str								=  ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
   _snake_case							:		List[Any]								=  {"""unk_token""": """<unk>"""}

   _snake_case							:		Optional[int]								=  os.path.join(self.tmpdirname,      VOCAB_FILES_NAMES["""vocab_file"""]		)
   _snake_case							:		Optional[Any]								=  os.path.join(self.tmpdirname,      VOCAB_FILES_NAMES["""merges_file"""]		)
   with open(self.vocab_file,      """w""",      encoding="""utf-8"""		) as fp:
     fp.write(json.dumps(a_		) + """\n"""		)
   with open(self.merges_file,      """w""",      encoding="""utf-8"""		) as fp:
     fp.write("""\n""".join(a_		)		)


 def  UpperCamelCase_   (				self:		Any,      **a_:		int		):




   '''simple docstring'''



   kwargs.update(self.special_tokens_map		)
   return CodeGenTokenizer.from_pretrained(self.tmpdirname,      **a_		)


 def  UpperCamelCase_   (				self:		Any,      **a_:		str		):




   '''simple docstring'''



   kwargs.update(self.special_tokens_map		)
   return CodeGenTokenizerFast.from_pretrained(self.tmpdirname,      **a_		)


 def  UpperCamelCase_   (				self:		Union[str, Any],      a_:		Dict		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  """lower newer"""
   _snake_case							:		Tuple								=  """lower newer"""
   return input_text, output_text


 def  UpperCamelCase_   (				self:		int		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  CodeGenTokenizer(self.vocab_file,      self.merges_file,      **self.special_tokens_map		)
   _snake_case							:		Optional[Any]								=  """lower newer"""
   _snake_case							:		Optional[int]								=  ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""]
   _snake_case							:		int								=  tokenizer.tokenize(a_,      add_prefix_space=a_		)
   self.assertListEqual(a_,      a_		)

   _snake_case							:		str								=  tokens + [tokenizer.unk_token]
   _snake_case							:		Optional[int]								=  [14, 15, 10, 9, 3, 2, 15, 19]
   self.assertListEqual(tokenizer.convert_tokens_to_ids(a_		),      a_		)


 def  UpperCamelCase_   (				self:		Union[str, Any]		):




   '''simple docstring'''



   if not self.test_rust_tokenizer:
     return

   _snake_case							:		int								=  self.get_tokenizer()
   _snake_case							:		int								=  self.get_rust_tokenizer(add_prefix_space=a_		)

   _snake_case							:		Dict								=  """lower newer"""

   # Testing tokenization
   _snake_case							:		Dict								=  tokenizer.tokenize(a_,      add_prefix_space=a_		)
   _snake_case							:		List[str]								=  rust_tokenizer.tokenize(a_		)
   self.assertListEqual(a_,      a_		)

   # Testing conversion to ids without special tokens
   _snake_case							:		Optional[Any]								=  tokenizer.encode(a_,      add_special_tokens=a_,      add_prefix_space=a_		)
   _snake_case							:		Tuple								=  rust_tokenizer.encode(a_,      add_special_tokens=a_		)
   self.assertListEqual(a_,      a_		)

   # Testing conversion to ids with special tokens
   _snake_case							:		Tuple								=  self.get_rust_tokenizer(add_prefix_space=a_		)
   _snake_case							:		int								=  tokenizer.encode(a_,      add_prefix_space=a_		)
   _snake_case							:		Optional[Any]								=  rust_tokenizer.encode(a_		)
   self.assertListEqual(a_,      a_		)

   # Testing the unknown token
   _snake_case							:		Tuple								=  tokens + [rust_tokenizer.unk_token]
   _snake_case							:		List[Any]								=  [14, 15, 10, 9, 3, 2, 15, 19]
   self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(a_		),      a_		)


 def  UpperCamelCase_   (				self:		Dict,      *a_:		Dict,      **a_:		int		):




   '''simple docstring'''



   pass


 def  UpperCamelCase_   (				self:		int,      a_:		List[Any]=15		):




   '''simple docstring'''



   for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
     with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"		):
       _snake_case							:		List[Any]								=  self.rust_tokenizer_class.from_pretrained(a_,      **a_		)

       # Simple input
       _snake_case							:		Any								=  """This is a simple input"""
       _snake_case							:		Optional[int]								=  ["""This is a simple input 1""", """This is a simple input 2"""]
       _snake_case							:		Optional[int]								=  ("""This is a simple input""", """This is a pair""")
       _snake_case							:		Optional[Any]								=  [
           ("""This is a simple input 1""", """This is a simple input 2"""),
           ("""This is a simple pair 1""", """This is a simple pair 2"""),
       ]

       # Simple input tests
       self.assertRaises(a_,      tokenizer_r.encode,      a_,      max_length=a_,      padding="""max_length"""		)

       # Simple input
       self.assertRaises(a_,      tokenizer_r.encode_plus,      a_,      max_length=a_,      padding="""max_length"""		)

       # Simple input
       self.assertRaises(
           a_,      tokenizer_r.batch_encode_plus,      a_,      max_length=a_,      padding="""max_length""",      )

       # Pair input
       self.assertRaises(a_,      tokenizer_r.encode,      a_,      max_length=a_,      padding="""max_length"""		)

       # Pair input
       self.assertRaises(a_,      tokenizer_r.encode_plus,      a_,      max_length=a_,      padding="""max_length"""		)

       # Pair input
       self.assertRaises(
           a_,      tokenizer_r.batch_encode_plus,      a_,      max_length=a_,      padding="""max_length""",      )


 def  UpperCamelCase_   (				self:		Optional[Any]		):




   '''simple docstring'''



   _snake_case							:		List[str]								=  CodeGenTokenizer.from_pretrained(self.tmpdirname,      pad_token="""<pad>"""		)

   # Simple input
   _snake_case							:		List[Any]								=  """This is a simple input"""
   _snake_case							:		int								=  ["""This is a simple input looooooooong""", """This is a simple input"""]
   _snake_case							:		Any								=  ("""This is a simple input""", """This is a pair""")
   _snake_case							:		str								=  [
       ("""This is a simple input loooooong""", """This is a simple input"""),
       ("""This is a simple pair loooooong""", """This is a simple pair"""),
   ]

   _snake_case							:		str								=  tokenizer.pad_token_id

   _snake_case							:		Optional[int]								=  tokenizer(a_,      padding="""max_length""",      max_length=30,      return_tensors="""np"""		)
   _snake_case							:		Dict								=  tokenizer(a_,      padding=a_,      truncate=a_,      return_tensors="""np"""		)
   _snake_case							:		Tuple								=  tokenizer(*a_,      padding="""max_length""",      max_length=60,      return_tensors="""np"""		)
   _snake_case							:		Optional[Any]								=  tokenizer(a_,      padding=a_,      truncate=a_,      return_tensors="""np"""		)

   # s
   # test single string max_length padding
   self.assertEqual(out_s["""input_ids"""].shape[-1],      30		)
   self.assertTrue(pad_token_id in out_s["""input_ids"""]		)
   self.assertTrue(0 in out_s["""attention_mask"""]		)

   # s2
   # test automatic padding
   self.assertEqual(out_sa["""input_ids"""].shape[-1],      33		)
   # long slice doesn't have padding
   self.assertFalse(pad_token_id in out_sa["""input_ids"""][0]		)
   self.assertFalse(0 in out_sa["""attention_mask"""][0]		)
   # short slice does have padding
   self.assertTrue(pad_token_id in out_sa["""input_ids"""][1]		)
   self.assertTrue(0 in out_sa["""attention_mask"""][1]		)

   # p
   # test single pair max_length padding
   self.assertEqual(out_p["""input_ids"""].shape[-1],      60		)
   self.assertTrue(pad_token_id in out_p["""input_ids"""]		)
   self.assertTrue(0 in out_p["""attention_mask"""]		)

   # p2
   # test automatic padding pair
   self.assertEqual(out_pa["""input_ids"""].shape[-1],      52		)
   # long slice pair doesn't have padding
   self.assertFalse(pad_token_id in out_pa["""input_ids"""][0]		)
   self.assertFalse(0 in out_pa["""attention_mask"""][0]		)
   # short slice pair does have padding
   self.assertTrue(pad_token_id in out_pa["""input_ids"""][1]		)
   self.assertTrue(0 in out_pa["""attention_mask"""][1]		)


 def  UpperCamelCase_   (				self:		Union[str, Any]		):




   '''simple docstring'''



   _snake_case							:		Tuple								=  """$$$"""
   _snake_case							:		List[Any]								=  CodeGenTokenizer.from_pretrained(self.tmpdirname,      bos_token=a_,      add_bos_token=a_		)

   _snake_case							:		str								=  """This is a simple input"""
   _snake_case							:		int								=  ["""This is a simple input 1""", """This is a simple input 2"""]

   _snake_case							:		Union[str, Any]								=  tokenizer.bos_token_id

   _snake_case							:		Tuple								=  tokenizer(a_		)
   _snake_case							:		Optional[Any]								=  tokenizer(a_		)

   self.assertEqual(out_s.input_ids[0],      a_		)
   self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids		)		)

   _snake_case							:		Optional[int]								=  tokenizer.decode(out_s.input_ids		)
   _snake_case							:		int								=  tokenizer.batch_decode(out_sa.input_ids		)

   self.assertEqual(decode_s.split()[0],      a_		)
   self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa		)		)


 @slow
 def  UpperCamelCase_   (				self:		str		):




   '''simple docstring'''



   _snake_case							:		Optional[int]								=  CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono"""		)

   _snake_case							:		Dict								=  """\nif len_a > len_b:\n    result = a\nelse:\n    result = b\n\n\n\n#"""
   _snake_case							:		Union[str, Any]								=  """\nif len_a > len_b:      result = a\nelse:      result = b"""

   _snake_case							:		Optional[Any]								=  tokenizer.encode(a_		)
   _snake_case							:		Dict								=  ["""^#""", re.escape("""<|endoftext|>"""		), """^'''""", """^\"\"\"""", """\n\n\n"""]
   _snake_case							:		Optional[Any]								=  tokenizer.decode(a_,      truncate_before_pattern=a_		)
   self.assertEqual(a_,      a_		)


 def  UpperCamelCase_   (				self:		str		):




   '''simple docstring'''



   pass


