
import logging
import os
from dataclasses import dataclass, field
from importlib import import_module
from typing import Dict, List, Optional, Tuple

import numpy as np
from seqeval.metrics import classification_report, fa_score, precision_score, recall_score
from utils_ner import Split, TFTokenClassificationDataset, TokenClassificationTask

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    TFAutoModelForTokenClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()


__lowerCamelCase							= logging.getLogger(__name__)






@dataclass
class 						UpperCAmelCase	:
   A__      :	str		  =  field(
       metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}				)
   A__      :	Optional[str]		  =  field(
       default=A_ ,metadata={"help": "Pretrained config name or path if not the same as model_name"}				)
   A__      :	Optional[str]		  =  field(
       default="NER" ,metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"}				)
   A__      :	Optional[str]		  =  field(
       default=A_ ,metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}				)
   A__      :	bool		  =  field(default=A_ ,metadata={"help": "Set this flag to use fast tokenization."}				)
   # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
   # or just modify its tokenizer_config.json.
   A__      :	Optional[str]		  =  field(
       default=A_ ,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,)






@dataclass
class 						UpperCAmelCase	:
   A__      :	str		  =  field(
       metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."}				)
   A__      :	Optional[str]		  =  field(
       metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."}				)
   A__      :	int		  =  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."
           )
       } ,)
   A__      :	bool		  =  field(
       default=A_ ,metadata={"help": "Overwrite the cached training and evaluation sets"}				)



def     UpperCamelCase      (					):
       # See all possible arguments in src/transformers/training_args.py
       # or by passing the --help flag to this script.
       # We now keep distinct sets of args, for a cleaner separation of concerns.
       snake_case :     Optional[Any]           =   HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)					)
       snake_case       ,      snake_case       ,      snake_case :     Optional[Any]           =   parser.parse_args_into_dataclasses()

       if (
           os.path.exists(training_args.output_dir					)
           and os.listdir(training_args.output_dir					)
           and training_args.do_train
           and not training_args.overwrite_output_dir
       ):
              raise ValueError(
                  f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use"""
                  " --overwrite_output_dir to overcome."					)

       snake_case :     Optional[int]           =   import_module("tasks"					)

       try:
              snake_case :     Tuple           =   getattr(__lowerCamelCase       ,      model_args.task_type					)
              snake_case :     TokenClassificationTask           =   token_classification_task_clazz()
       except AttributeError:
              raise ValueError(
                  f"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """
                  f"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}"""					)

       # Setup logging
       logging.basicConfig(
           format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"       ,      datefmt="%m/%d/%Y %H:%M:%S"       ,      level=logging.INFO       ,      )
       logger.info(
           "n_replicas: %s, distributed training: %s, 16-bits training: %s"       ,      training_args.n_replicas       ,      bool(training_args.n_replicas > 1					)       ,      training_args.fpaa       ,      )
       logger.info("Training/evaluation parameters %s"       ,      __lowerCamelCase					)

       # Prepare Token Classification task
       snake_case :     Union[str, Any]           =   token_classification_task.get_labels(data_args.labels					)
       snake_case :     Dict[int, str]           =   dict(enumerate(__lowerCamelCase					)					)
       snake_case :     Dict           =   len(__lowerCamelCase					)

       # Load pretrained model and tokenizer
       #
       # Distributed training:
       # The .from_pretrained methods guarantee that only one local process can concurrently
       # download model & vocab.

       snake_case :     Dict           =   AutoConfig.from_pretrained(
           model_args.config_name if model_args.config_name else model_args.model_name_or_path       ,      num_labels=__lowerCamelCase       ,      idalabel=__lowerCamelCase       ,      labelaid={label: i for i, label in enumerate(__lowerCamelCase					)}       ,      cache_dir=model_args.cache_dir       ,      )
       snake_case :     Union[str, Any]           =   AutoTokenizer.from_pretrained(
           model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path       ,      cache_dir=model_args.cache_dir       ,      use_fast=model_args.use_fast       ,      )

       with training_args.strategy.scope():
              snake_case :     str           =   TFAutoModelForTokenClassification.from_pretrained(
                  model_args.model_name_or_path       ,      from_pt=bool(".bin" in model_args.model_name_or_path					)       ,      config=__lowerCamelCase       ,      cache_dir=model_args.cache_dir       ,      )

       # Get datasets
       snake_case :     str           =   (
           TFTokenClassificationDataset(
               token_classification_task=__lowerCamelCase       ,      data_dir=data_args.data_dir       ,      tokenizer=__lowerCamelCase       ,      labels=__lowerCamelCase       ,      model_type=config.model_type       ,      max_seq_length=data_args.max_seq_length       ,      overwrite_cache=data_args.overwrite_cache       ,      mode=Split.train       ,      )
           if training_args.do_train
           else None
       )
       snake_case :     Tuple           =   (
           TFTokenClassificationDataset(
               token_classification_task=__lowerCamelCase       ,      data_dir=data_args.data_dir       ,      tokenizer=__lowerCamelCase       ,      labels=__lowerCamelCase       ,      model_type=config.model_type       ,      max_seq_length=data_args.max_seq_length       ,      overwrite_cache=data_args.overwrite_cache       ,      mode=Split.dev       ,      )
           if training_args.do_eval
           else None
       )

       def align_predictions(__lowerCamelCase  :				np.ndarray       ,      __lowerCamelCase  :				np.ndarray					) -> Tuple[List[int], List[int]]:
              snake_case :     Tuple           =   np.argmax(__lowerCamelCase       ,      axis=2					)
              snake_case       ,      snake_case :     Union[str, Any]           =   preds.shape
              snake_case :     Dict           =   [[] for _ in range(__lowerCamelCase					)]
              snake_case :     str           =   [[] for _ in range(__lowerCamelCase					)]

              for i in range(__lowerCamelCase					):
                     for j in range(__lowerCamelCase					):
                            if label_ids[i, j] != -100:
                                   out_label_list[i].append(label_map[label_ids[i][j]]					)
                                   preds_list[i].append(label_map[preds[i][j]]					)

              return preds_list, out_label_list

       def compute_metrics(__lowerCamelCase  :				EvalPrediction					) -> Dict:
              snake_case       ,      snake_case :     Union[str, Any]           =   align_predictions(p.predictions       ,      p.label_ids					)

              return {
                  "precision": precision_score(__lowerCamelCase       ,      __lowerCamelCase					),
                  "recall": recall_score(__lowerCamelCase       ,      __lowerCamelCase					),
                  "f1": fa_score(__lowerCamelCase       ,      __lowerCamelCase					),
              }

       # Initialize our Trainer
       snake_case :     Any           =   TFTrainer(
           model=__lowerCamelCase       ,      args=__lowerCamelCase       ,      train_dataset=train_dataset.get_dataset() if train_dataset else None       ,      eval_dataset=eval_dataset.get_dataset() if eval_dataset else None       ,      compute_metrics=__lowerCamelCase       ,      )

       # Training
       if training_args.do_train:
              trainer.train()
              trainer.save_model()
              tokenizer.save_pretrained(training_args.output_dir					)

       # Evaluation
       snake_case :     List[Any]           =   {}
       if training_args.do_eval:
              logger.info("*** Evaluate ***"					)

              snake_case :     str           =   trainer.evaluate()
              snake_case :     Optional[Any]           =   os.path.join(training_args.output_dir       ,      "eval_results.txt"					)

              with open(__lowerCamelCase       ,      "w"					) as writer:
                     logger.info("***** Eval results *****"					)

                     for key, value in result.items():
                            logger.info("  %s = %s"       ,      __lowerCamelCase       ,      __lowerCamelCase					)
                            writer.write("%s = %s\n" % (key, value)					)

                     results.update(__lowerCamelCase					)

    # Predict
       if training_args.do_predict:
              snake_case :     Union[str, Any]           =   TFTokenClassificationDataset(
                  token_classification_task=__lowerCamelCase       ,      data_dir=data_args.data_dir       ,      tokenizer=__lowerCamelCase       ,      labels=__lowerCamelCase       ,      model_type=config.model_type       ,      max_seq_length=data_args.max_seq_length       ,      overwrite_cache=data_args.overwrite_cache       ,      mode=Split.test       ,      )

              snake_case       ,      snake_case       ,      snake_case :     Union[str, Any]           =   trainer.predict(test_dataset.get_dataset()					)
              snake_case       ,      snake_case :     List[Any]           =   align_predictions(__lowerCamelCase       ,      __lowerCamelCase					)
              snake_case :     Union[str, Any]           =   classification_report(__lowerCamelCase       ,      __lowerCamelCase					)

              logger.info("\n%s"       ,      __lowerCamelCase					)

              snake_case :     Optional[Any]           =   os.path.join(training_args.output_dir       ,      "test_results.txt"					)

              with open(__lowerCamelCase       ,      "w"					) as writer:
                     writer.write("%s\n" % report					)

              # Save predictions
              snake_case :     Optional[Any]           =   os.path.join(training_args.output_dir       ,      "test_predictions.txt"					)

              with open(__lowerCamelCase       ,      "w"					) as writer:
                     with open(os.path.join(data_args.data_dir       ,      "test.txt"					)       ,      "r"					) as f:
                            snake_case :     Dict           =   0

                            for line in f:
                                   if line.startswith("-DOCSTART-"					) or line == "" or line == "\n":
                                          writer.write(__lowerCamelCase					)

                                          if not preds_list[example_id]:
                                                 example_id += 1
                                   elif preds_list[example_id]:
                                          snake_case :     Optional[int]           =   line.split()[0] + " " + preds_list[example_id].pop(0					) + "\n"

                                          writer.write(__lowerCamelCase					)
                                   else:
                                          logger.warning("Maximum sequence length exceeded: No prediction for '%s'."       ,      line.split()[0]					)

       return results


if __name__ == "__main__":
   main()







import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class 						UpperCAmelCase	(		A_ ,unittest.TestCase				):
   A__      :	Dict		  =  PreTrainedTokenizerFast
   A__      :	str		  =  False
   A__      :	List[Any]		  =  True
   A__      :	List[str]		  =  "tokenizer_file"



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


          '''simple docstring'''


          snake_case :     Union[str, Any]           =   False  # because we don't have pretrained_vocab_files_map
          super().setUp()
          snake_case :     Optional[int]           =   True

          snake_case :     List[str]           =   ["robot-test/dummy-tokenizer-fast", "robot-test/dummy-tokenizer-wordlevel"]
          snake_case :     Optional[Any]           =   "SaulLu/dummy-tokenizer-bytelevel-bpe"

          # Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
          snake_case :     int           =   [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

          snake_case :     List[Any]           =   PreTrainedTokenizerFast.from_pretrained(model_paths[0]				)
          tokenizer.save_pretrained(self.tmpdirname				)



   def        _SCREAMING_SNAKE_CASE     (self	:      Dict				)	->			int:


          '''simple docstring'''


          pass



   def        _SCREAMING_SNAKE_CASE     (self	:      Any				)	->			int:


          '''simple docstring'''


          pass



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


          '''simple docstring'''


          pass



   def        _SCREAMING_SNAKE_CASE     (self	:      Tuple				)	->			List[str]:


          '''simple docstring'''


          pass



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


          '''simple docstring'''


          snake_case :     Optional[int]           =   self.tmpdirname
          # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                 with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""				):
                        try:
                               snake_case :     Any           =   tempfile.mkdtemp()
                               snake_case :     int           =   self.rust_tokenizer_class.from_pretrained(snake_case__					,		**snake_case__				)

                               tokenizer.save_pretrained(self.tmpdirname				)
                               super().test_training_new_tokenizer()
                        finally:
                               # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
                               # is restored
                               shutil.rmtree(self.tmpdirname				)
                               snake_case :     int           =   tmpdirname_orig



   def        _SCREAMING_SNAKE_CASE     (self	:      Tuple				)	->			Dict:


          '''simple docstring'''


          snake_case :     Optional[int]           =   self.tmpdirname
          # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                 with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""				):
                        try:
                               snake_case :     Union[str, Any]           =   tempfile.mkdtemp()
                               snake_case :     str           =   self.rust_tokenizer_class.from_pretrained(snake_case__					,		**snake_case__				)

                               tokenizer.save_pretrained(self.tmpdirname				)
                               super().test_training_new_tokenizer_with_special_tokens_change()
                        finally:
                               # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
                               # is restored
                               shutil.rmtree(self.tmpdirname				)
                               snake_case :     Dict           =   tmpdirname_orig



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


          '''simple docstring'''


          snake_case :     int           =   self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name				)

          snake_case :     int           =   ("a" for _ in range(10_00				))
          snake_case :     Optional[int]           =   tokenizer.train_new_from_iterator(text_iterator=snake_case__					,		length=10_00					,		vocab_size=50				)

          snake_case :     str           =   new_tokenizer.encode("a🤗"				)
          self.assertEqual(snake_case__					,		[64, 1_72, 2_53, 97, 2_45]				)






@require_tokenizers
class 						UpperCAmelCase	(		unittest.TestCase				):



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


          '''simple docstring'''


          snake_case :     List[str]           =   AutoTokenizer.from_pretrained("bert-base-cased"				)
          snake_case :     Union[str, Any]           =   json.loads(tokenizer._tokenizer.to_str()				)
          snake_case :     Tuple           =   len(snake_case__				)

          with tempfile.TemporaryDirectory() as tmp_dir:
                 # Hack to save this in the tokenizer_config.json
                 snake_case :     List[str]           =   ["tokenizer.4.0.0.json"]
                 tokenizer.save_pretrained(snake_case__				)
                 json.dump(snake_case__					,		open(os.path.join(snake_case__					,		"tokenizer.4.0.0.json"				)					,		"w"				)				)

                 # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
                 snake_case :     Optional[Any]           =   AutoTokenizer.from_pretrained(snake_case__				)
                 self.assertEqual(len(snake_case__				)					,		len(snake_case__				) + 1				)
                 snake_case :     Union[str, Any]           =   json.loads(new_tokenizer._tokenizer.to_str()				)
                 self.assertIn("huggingface"					,		json_tokenizer["model"]["vocab"]				)

                 # Will need to be adjusted if we reach v42 and this test is still here.
                 # Should pick the old tokenizer file as the version of Transformers is < 4.0.0
                 shutil.move(os.path.join(snake_case__					,		"tokenizer.4.0.0.json"				)					,		os.path.join(snake_case__					,		"tokenizer.42.0.0.json"				)				)
                 snake_case :     Optional[Any]           =   ["tokenizer.42.0.0.json"]
                 tokenizer.save_pretrained(snake_case__				)
                 snake_case :     Dict           =   AutoTokenizer.from_pretrained(snake_case__				)
                 self.assertEqual(len(snake_case__				)					,		len(snake_case__				)				)
                 snake_case :     Optional[int]           =   json.loads(new_tokenizer._tokenizer.to_str()				)
                 self.assertNotIn("huggingface"					,		json_tokenizer["model"]["vocab"]				)



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


          '''simple docstring'''


          snake_case :     int           =   "hf-internal-testing/test-two-tokenizers"

          # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
          snake_case :     int           =   AutoTokenizer.from_pretrained(snake_case__				)
          self.assertEqual(len(snake_case__				)					,		2_89_97				)
          snake_case :     Optional[int]           =   json.loads(tokenizer._tokenizer.to_str()				)
          self.assertIn("huggingface"					,		json_tokenizer["model"]["vocab"]				)

          # Testing an older version by monkey-patching the version in the module it's used.
          import transformers as old_transformers

          snake_case :     Dict           =   "3.0.0"
          snake_case :     Union[str, Any]           =   old_transformers.models.auto.AutoTokenizer.from_pretrained(snake_case__				)
          self.assertEqual(len(snake_case__				)					,		2_89_96				)
          snake_case :     Optional[Any]           =   json.loads(old_tokenizer._tokenizer.to_str()				)
          self.assertNotIn("huggingface"					,		json_tokenizer["model"]["vocab"]				)






@require_tokenizers
class 						UpperCAmelCase	(		unittest.TestCase				):



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


          '''simple docstring'''


          snake_case :     Tuple           =   PreTrainedTokenizerFast.from_pretrained("robot-test/dummy-tokenizer-wordlevel"				)
          snake_case :     List[Any]           =   "The Matrix is a 1999 science fiction action film."

          with concurrent.futures.ThreadPoolExecutor() as executor:
                 snake_case :     Union[str, Any]           =   [executor.submit(self.fetch					,		snake_case__					,		snake_case__				) for i in range(10				)]
                 snake_case :     Optional[Any]           =   [future.result() for future in futures]
                 self.assertEqual(snake_case__					,		[[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10				)]				)



   def        _SCREAMING_SNAKE_CASE     (self	:      str					,		snake_case__	:      List[str]					,		snake_case__	:      str				)	->			List[str]:


          '''simple docstring'''


          return tokenizer.encode(snake_case__					,		truncation="longest_first"					,		padding="longest"				)





