

'''simple docstring'''
import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


lowerCamelCase			:				Dict 			=					logging.getLogger(__name__)







@dataclass
class 							A__   :
  A__					=    42
  A__					=    42
  A__					=    42







@dataclass
class 							A__   :
  A__					=    42
  A__					=    42
  A__					=    None
  A__					=    None







class 							A__   (	A__  ):
  A__					=    'train'
  A__					=    'dev'
  A__					=    'test'







class 							A__   :





  @staticmethod
  def 						A  (		_a				:     List[Any]							, _a				:     Union[Split, str]			)     ->   List[InputExample]:





       '''simple docstring'''






       raise NotImplementedError





  @staticmethod
  def 						A  (		_a				:     str			)     ->   List[str]:





       '''simple docstring'''






       raise NotImplementedError





  @staticmethod
  def 						A  (		_a				:     List[InputExample]							, _a				:     List[str]							, _a				:     int							, _a				:     PreTrainedTokenizer							, _a				:     Any=False							, _a				:     Union[str, Any]="[CLS]"							, _a				:     int=1							, _a				:     Optional[Any]="[SEP]"							, _a				:     List[str]=False							, _a				:     Tuple=False							, _a				:     int=0							, _a				:     Tuple=0							, _a				:     Union[str, Any]=-100							, _a				:     Union[str, Any]=0							, _a				:     Optional[int]=True							, )     ->   List[InputFeatures]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   ={label: i for i, label in enumerate(_a			)}

       _SCREAMING_SNAKE_CASE							   =[]
       for ex_index, example in enumerate(_a			):
            if ex_index % 1_0000 == 0:
                 logger.info('Writing example %d of %d'							, _a							, len(_a			)			)

            _SCREAMING_SNAKE_CASE							   =[]
            _SCREAMING_SNAKE_CASE							   =[]
            for word, label in zip(example.words							, example.labels			):
                 _SCREAMING_SNAKE_CASE							   =tokenizer.tokenize(_a			)

                 # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
                 if len(_a			) > 0:
                      tokens.extend(_a			)
                      # Use the real label id for the first token of the word, and padding ids for the remaining tokens
                      label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(_a			) - 1)			)

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
            _SCREAMING_SNAKE_CASE							   =tokenizer.num_special_tokens_to_add()
            if len(_a			) > max_seq_length - special_tokens_count:
                 _SCREAMING_SNAKE_CASE							   =tokens[: (max_seq_length - special_tokens_count)]
                 _SCREAMING_SNAKE_CASE							   =label_ids[: (max_seq_length - special_tokens_count)]

            # The convention in BERT is:
            # (a) For sequence pairs:
            #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
            #  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
            # (b) For single sequences:
            #  tokens:   [CLS] the dog is hairy . [SEP]
            #  type_ids:   0   0   0   0  0     0   0
            #
            # Where "type_ids" are used to indicate whether this is the first
            # sequence or the second sequence. The embedding vectors for `type=0` and
            # `type=1` were learned during pre-training and are added to the wordpiece
            # embedding vector (and position vector). This is not *strictly* necessary
            # since the [SEP] token unambiguously separates the sequences, but it makes
            # it easier for the model to learn the concept of sequences.
            #
            # For classification tasks, the first vector (corresponding to [CLS]) is
            # used as the "sentence vector". Note that this only makes sense because
            # the entire model is fine-tuned.
            tokens += [sep_token]
            label_ids += [pad_token_label_id]
            if sep_token_extra:
                 # roberta uses an extra separator b/w pairs of sentences
                 tokens += [sep_token]
                 label_ids += [pad_token_label_id]
            _SCREAMING_SNAKE_CASE							   =[sequence_a_segment_id] * len(_a			)

            if cls_token_at_end:
                 tokens += [cls_token]
                 label_ids += [pad_token_label_id]
                 segment_ids += [cls_token_segment_id]
            else:
                 _SCREAMING_SNAKE_CASE							   =[cls_token] + tokens
                 _SCREAMING_SNAKE_CASE							   =[pad_token_label_id] + label_ids
                 _SCREAMING_SNAKE_CASE							   =[cls_token_segment_id] + segment_ids

            _SCREAMING_SNAKE_CASE							   =tokenizer.convert_tokens_to_ids(_a			)

            # The mask has 1 for real tokens and 0 for padding tokens. Only real
            # tokens are attended to.
            _SCREAMING_SNAKE_CASE							   =[1 if mask_padding_with_zero else 0] * len(_a			)

            # Zero-pad up to the sequence length.
            _SCREAMING_SNAKE_CASE							   =max_seq_length - len(_a			)
            if pad_on_left:
                 _SCREAMING_SNAKE_CASE							   =([pad_token] * padding_length) + input_ids
                 _SCREAMING_SNAKE_CASE							   =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
                 _SCREAMING_SNAKE_CASE							   =([pad_token_segment_id] * padding_length) + segment_ids
                 _SCREAMING_SNAKE_CASE							   =([pad_token_label_id] * padding_length) + label_ids
            else:
                 input_ids += [pad_token] * padding_length
                 input_mask += [0 if mask_padding_with_zero else 1] * padding_length
                 segment_ids += [pad_token_segment_id] * padding_length
                 label_ids += [pad_token_label_id] * padding_length

            assert len(_a			) == max_seq_length
            assert len(_a			) == max_seq_length
            assert len(_a			) == max_seq_length
            assert len(_a			) == max_seq_length

            if ex_index < 5:
                 logger.info('*** Example ***'			)
                 logger.info('guid: %s'							, example.guid			)
                 logger.info('tokens: %s'							, ' '.join([str(_a			) for x in tokens]			)			)
                 logger.info('input_ids: %s'							, ' '.join([str(_a			) for x in input_ids]			)			)
                 logger.info('input_mask: %s'							, ' '.join([str(_a			) for x in input_mask]			)			)
                 logger.info('segment_ids: %s'							, ' '.join([str(_a			) for x in segment_ids]			)			)
                 logger.info('label_ids: %s'							, ' '.join([str(_a			) for x in label_ids]			)			)

            if "token_type_ids" not in tokenizer.model_input_names:
                 _SCREAMING_SNAKE_CASE							   =None

            features.append(
                InputFeatures(
                    input_ids=_a							, attention_mask=_a							, token_type_ids=_a							, label_ids=_a			)			)
       return features


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







     class 							A__   (	A__  ):
       A__					=    42
       A__					=    nn.CrossEntropyLoss().ignore_index





       def __init__(		self				:     List[str]							, _a				:     TokenClassificationTask							, _a				:     str							, _a				:     PreTrainedTokenizer							, _a				:     List[str]							, _a				:     str							, _a				:     Optional[int] = None							, _a				:     Dict=False							, _a				:     Split = Split.train							, )     ->   Union[str, Any]:





            '''simple docstring'''






            _SCREAMING_SNAKE_CASE							   =os.path.join(
                _a							, 'cached_{}_{}_{}'.format(mode.value							, tokenizer.__class__.__name__							, str(_a			)			)							, )

            # Make sure only the first process in distributed training processes the dataset,
            # and the others will use the cache.
            _SCREAMING_SNAKE_CASE							   =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}"			)
                      _SCREAMING_SNAKE_CASE							   =torch.load(_a			)
                 else:
                      logger.info(f"Creating features from dataset file at {data_dir}"			)
                      _SCREAMING_SNAKE_CASE							   =token_classification_task.read_examples_from_file(_a							, _a			)
                      # TODO clean up all this to leverage built-in features of tokenizers
                      _SCREAMING_SNAKE_CASE							   =token_classification_task.convert_examples_to_features(
                          _a							, _a							, _a							, _a							, cls_token_at_end=bool(model_type in ['xlnet']			)							, cls_token=tokenizer.cls_token							, cls_token_segment_id=2 if model_type in ['xlnet'] else 0							, sep_token=tokenizer.sep_token							, sep_token_extra=_a							, pad_on_left=bool(tokenizer.padding_side == 'left'			)							, pad_token=tokenizer.pad_token_id							, pad_token_segment_id=tokenizer.pad_token_type_id							, pad_token_label_id=self.pad_token_label_id							, )
                      logger.info(f"Saving features into cached file {cached_features_file}"			)
                      torch.save(self.features							, _a			)





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





            '''simple docstring'''






            return len(self.features			)





       def __getitem__(		self				:     Union[str, Any]							, _a				:     Union[str, Any]			)     ->   InputFeatures:





            '''simple docstring'''






            return self.features[i]


if is_tf_available():
     import tensorflow as tf







     class 							A__   :
       A__					=    42
       A__					=    -1_00





       def __init__(		self				:     Dict							, _a				:     TokenClassificationTask							, _a				:     str							, _a				:     PreTrainedTokenizer							, _a				:     List[str]							, _a				:     str							, _a				:     Optional[int] = None							, _a				:     Optional[Any]=False							, _a				:     Split = Split.train							, )     ->   Dict:





            '''simple docstring'''






            _SCREAMING_SNAKE_CASE							   =token_classification_task.read_examples_from_file(_a							, _a			)
            # TODO clean up all this to leverage built-in features of tokenizers
            _SCREAMING_SNAKE_CASE							   =token_classification_task.convert_examples_to_features(
                _a							, _a							, _a							, _a							, cls_token_at_end=bool(model_type in ['xlnet']			)							, cls_token=tokenizer.cls_token							, cls_token_segment_id=2 if model_type in ['xlnet'] else 0							, sep_token=tokenizer.sep_token							, sep_token_extra=_a							, pad_on_left=bool(tokenizer.padding_side == 'left'			)							, pad_token=tokenizer.pad_token_id							, pad_token_segment_id=tokenizer.pad_token_type_id							, pad_token_label_id=self.pad_token_label_id							, )

            def gen():
                 for ex in self.features:
                      if ex.token_type_ids is None:
                           yield (
                               {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
                               ex.label_ids,
                           )
                      else:
                           yield (
                               {
                                   "input_ids": ex.input_ids,
                                   "attention_mask": ex.attention_mask,
                                   "token_type_ids": ex.token_type_ids,
                               },
                               ex.label_ids,
                           )

            if "token_type_ids" not in tokenizer.model_input_names:
                 _SCREAMING_SNAKE_CASE							   =tf.data.Dataset.from_generator(
                     _a							, ({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa)							, (
                         {'input_ids': tf.TensorShape([None]			), 'attention_mask': tf.TensorShape([None]			)},
                         tf.TensorShape([None]			),
                     )							, )
            else:
                 _SCREAMING_SNAKE_CASE							   =tf.data.Dataset.from_generator(
                     _a							, ({'input_ids': tf.intaa, 'attention_mask': tf.intaa, 'token_type_ids': tf.intaa}, tf.intaa)							, (
                         {
                             'input_ids': tf.TensorShape([None]			),
                             'attention_mask': tf.TensorShape([None]			),
                             'token_type_ids': tf.TensorShape([None]			),
                         },
                         tf.TensorShape([None]			),
                     )							, )





       def 						A  (		self				:     List[Any]			)     ->   Dict:





            '''simple docstring'''






            _SCREAMING_SNAKE_CASE							   =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features			)			)			)

            return self.dataset





       def __len__(		self				:     Optional[int]			)     ->   Optional[Any]:





            '''simple docstring'''






            return len(self.features			)





       def __getitem__(		self				:     Union[str, Any]							, _a				:     Any			)     ->   InputFeatures:





            '''simple docstring'''






            return self.features[i]



'''simple docstring'''
import os
import sys
import unittest


lowerCamelCase			:				Optional[Any] 			=					os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
lowerCamelCase			:				Optional[int] 			=					os.path.join(git_repo_path, "src", "transformers")

lowerCamelCase			:				Union[str, Any] 			=					"\n{0} = None\n"

lowerCamelCase			:				Optional[Any] 			=					"\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n"


lowerCamelCase			:				List[Any] 			=					"\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n"







class 							A__   (	unittest.TestCase  ):





  def 						A  (		self				:     Optional[int]			)     ->   Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =find_backend('    _import_structure["models.albert"].append("AlbertTokenizerFast")'			)
       self.assertIsNone(_a			)

       _SCREAMING_SNAKE_CASE							   =find_backend('    if not is_tokenizers_available():'			)
       self.assertEqual(_a							, 'tokenizers'			)

       _SCREAMING_SNAKE_CASE							   =find_backend('    if not is_tensorflow_text_available():'			)
       self.assertEqual(_a							, 'tensorflow_text'			)

       _SCREAMING_SNAKE_CASE							   =find_backend('    if not (is_sentencepiece_available() and is_tokenizers_available()):'			)
       self.assertEqual(_a							, 'sentencepiece_and_tokenizers'			)

       _SCREAMING_SNAKE_CASE							   =find_backend(
           '    if not (is_sentencepiece_available() and is_tensorflow_text_available()):'			)
       self.assertEqual(_a							, 'sentencepiece_and_tensorflow_text'			)

       _SCREAMING_SNAKE_CASE							   =find_backend(
           '    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):'			)
       self.assertEqual(_a							, 'sentencepiece_and_tokenizers_and_vision'			)





  def 						A  (		self				:     Optional[int]			)     ->   Any:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =read_init()
       # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
       self.assertIn('torch'							, _a			)
       self.assertIn('tensorflow_text'							, _a			)
       self.assertIn('sentencepiece_and_tokenizers'							, _a			)

       # Likewise, we can't assert on the exact content of a key
       self.assertIn('BertModel'							, objects['torch']			)
       self.assertIn('TFBertModel'							, objects['tf']			)
       self.assertIn('FlaxBertModel'							, objects['flax']			)
       self.assertIn('BertModel'							, objects['torch']			)
       self.assertIn('TFBertTokenizer'							, objects['tensorflow_text']			)
       self.assertIn('convert_slow_tokenizer'							, objects['sentencepiece_and_tokenizers']			)





  def 						A  (		self				:     Optional[int]			)     ->   List[str]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =create_dummy_object('CONSTANT'							, '\'torch\''			)
       self.assertEqual(_a							, '\nCONSTANT = None\n'			)

       _SCREAMING_SNAKE_CASE							   =create_dummy_object('function'							, '\'torch\''			)
       self.assertEqual(
           _a							, '\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'			)

       _SCREAMING_SNAKE_CASE							   ='\nclass FakeClass(metaclass=DummyObject):\n    _backends = \'torch\'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, \'torch\')\n'
       _SCREAMING_SNAKE_CASE							   =create_dummy_object('FakeClass'							, '\'torch\''			)
       self.assertEqual(_a							, _a			)





  def 						A  (		self				:     Optional[int]			)     ->   Optional[int]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   ='# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = ["torch"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, ["torch"])\n'
       _SCREAMING_SNAKE_CASE							   =create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']}			)
       self.assertEqual(dummy_files['torch']							, _a			)
