




'''simple docstring'''







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   _snake_case:
 __snake_case:       str									=				field(
     metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}			)
 __snake_case:       Optional[str]									=				field(
     default=UpperCAmelCase					,   metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}			)
 __snake_case:       Optional[str]									=				field(
     default='''NER'''					,   metadata={'''help''': '''Task type to fine tune in training (e.g. NER, POS, etc)'''}			)
 __snake_case:       Optional[str]									=				field(
     default=UpperCAmelCase					,   metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''}			)
 __snake_case:       bool									=				field(default=UpperCAmelCase					,   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.
 __snake_case:       Optional[str]									=				field(
     default=UpperCAmelCase					,   metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}					,   )




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







def 	_A			(   ):






   '''simple docstring'''







   A__         =    HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)	)
   A__     , A__     , A__         =    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.'	)

   A__         =    import_module('tasks'	)

   try:
      A__         =    getattr(UpperCAmelCase			,model_args.task_type	)
      A__         =    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'			,UpperCAmelCase	)

   # Prepare Token Classification task
   A__         =    token_classification_task.get_labels(data_args.labels	)
   A__         =    dict(enumerate(UpperCAmelCase	)	)
   A__         =    len(UpperCAmelCase	)

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

   A__         =    AutoConfig.from_pretrained(
       model_args.config_name if model_args.config_name else model_args.model_name_or_path			,num_labels=UpperCAmelCase			,idalabel=UpperCAmelCase			,labelaid={label: i for i, label in enumerate(UpperCAmelCase	)}			,cache_dir=model_args.cache_dir			,)
   A__         =    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():
      A__         =    TFAutoModelForTokenClassification.from_pretrained(
          model_args.model_name_or_path			,from_pt=bool('.bin' in model_args.model_name_or_path	)			,config=UpperCAmelCase			,cache_dir=model_args.cache_dir			,)

   # Get datasets
   A__         =    (
       TFTokenClassificationDataset(
           token_classification_task=UpperCAmelCase			,data_dir=data_args.data_dir			,tokenizer=UpperCAmelCase			,labels=UpperCAmelCase			,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
   )
   A__         =    (
       TFTokenClassificationDataset(
           token_classification_task=UpperCAmelCase			,data_dir=data_args.data_dir			,tokenizer=UpperCAmelCase			,labels=UpperCAmelCase			,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(UpperCAmelCase			,UpperCAmelCase	) -> Tuple[List[int], List[int]]:
      A__         =    np.argmax(UpperCAmelCase			,axis=2	)
      A__     , A__         =    preds.shape
      A__         =    [[] for _ in range(UpperCAmelCase	)]
      A__         =    [[] for _ in range(UpperCAmelCase	)]

      for i in range(UpperCAmelCase	):
         for j in range(UpperCAmelCase	):
            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(UpperCAmelCase	) -> Dict:
      A__     , A__         =    align_predictions(p.predictions			,p.label_ids	)

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

   # Initialize our Trainer
   A__         =    TFTrainer(
       model=UpperCAmelCase			,args=UpperCAmelCase			,train_dataset=train_dataset.get_dataset() if train_dataset else None			,eval_dataset=eval_dataset.get_dataset() if eval_dataset else None			,compute_metrics=UpperCAmelCase			,)

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

   # Evaluation
   A__         =    {}
   if training_args.do_eval:
      logger.info('*** Evaluate ***'	)

      A__         =    trainer.evaluate()
      A__         =    os.path.join(training_args.output_dir			,'eval_results.txt'	)

      with open(UpperCAmelCase			,'w'	) as writer:
         logger.info('***** Eval results *****'	)

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

         results.update(UpperCAmelCase	)

    # Predict
   if training_args.do_predict:
      A__         =    TFTokenClassificationDataset(
          token_classification_task=UpperCAmelCase			,data_dir=data_args.data_dir			,tokenizer=UpperCAmelCase			,labels=UpperCAmelCase			,model_type=config.model_type			,max_seq_length=data_args.max_seq_length			,overwrite_cache=data_args.overwrite_cache			,mode=Split.test			,)

      A__     , A__     , A__         =    trainer.predict(test_dataset.get_dataset()	)
      A__     , A__         =    align_predictions(UpperCAmelCase			,UpperCAmelCase	)
      A__         =    classification_report(UpperCAmelCase			,UpperCAmelCase	)

      logger.info('\n%s'			,UpperCAmelCase	)

      A__         =    os.path.join(training_args.output_dir			,'test_results.txt'	)

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

      # Save predictions
      A__         =    os.path.join(training_args.output_dir			,'test_predictions.txt'	)

      with open(UpperCAmelCase			,'w'	) as writer:
         with open(os.path.join(data_args.data_dir			,'test.txt'	)			,'r'	) as f:
            A__         =    0

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

                  if not preds_list[example_id]:
                     example_id += 1
               elif preds_list[example_id]:
                  A__         =    line.split()[0] + ' ' + preds_list[example_id].pop(0	) + '\n'

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

   return results


if __name__ == "__main__":
    main()








'''simple docstring'''







import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


lowerCAmelCase_    	=							logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
lowerCAmelCase_    	=							direct_transformers_import(Path(__file__).parent)


lowerCAmelCase_    	=							{
    '''AutoTokenizer''': '''PreTrainedTokenizerBase''',
    '''AutoFeatureExtractor''': '''FeatureExtractionMixin''',
    '''AutoImageProcessor''': '''ImageProcessingMixin''',
}

class   _snake_case( UpperCAmelCase			):
 __snake_case:       str									=				['''feature_extractor''', '''tokenizer''']
 # Names need to be attr_class for attr in attributes
 __snake_case:       Optional[Any]									=				None
 __snake_case:       List[str]									=				None
 __snake_case:       Any									=				None






 def __init__(self					:     List[Any]						,		*a					:     Union[str, Any]						,		**a					:     Optional[int]						)					->      Any:






    """simple docstring"""


    for key in kwargs:
       if key not in self.attributes:
          raise TypeError(f"""Unexpected keyword argument {key}."""						)
    for arg, attribute_name in zip(a						,		self.attributes						):
       if attribute_name in kwargs:
          raise TypeError(f"""Got multiple values for argument {attribute_name}."""						)
       else:
          A__         =    arg

    if len(a						) != len(self.attributes						):
       raise ValueError(
           f"""This processor requires {len(self.attributes						)} arguments: {", ".join(self.attributes						)}. Got """
           f"""{len(a						)} arguments instead."""						)

    # Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
    for attribute_name, arg in kwargs.items():
       A__         =    getattr(self						,		f"""{attribute_name}_class"""						)
       # Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
       A__         =    AUTO_TO_BASE_CLASS_MAPPING.get(a						,		a						)
       if isinstance(a						,		a						):
          A__         =    tuple(getattr(a						,		a						) for n in class_name if n is not None						)
       else:
          A__         =    getattr(a						,		a						)

       if not isinstance(a						,		a						):
          raise ValueError(
              f"""Received a {type(a						).__name__} for argument {attribute_name}, but a {class_name} was expected."""						)

       setattr(self						,		a						,		a						)






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






    """simple docstring"""


    A__         =    [f"""- {name}: {repr(getattr(self						,		a						)						)}""" for name in self.attributes]
    A__         =    '\n'.join(a						)
    return f"""{self.__class__.__name__}:\n{attributes_repr}"""






 def 	_UpperCamelCase   (self					:     Union[str, Any]						,		a					:     Tuple						,		a					:     bool = False						,		**a					:     int						)					->      List[str]:






    """simple docstring"""


    os.makedirs(a						,		exist_ok=a						)

    if push_to_hub:
       A__         =    kwargs.pop('commit_message'						,		a						)
       A__         =    kwargs.pop('repo_id'						,		save_directory.split(os.path.sep						)[-1]						)
       A__         =    self._create_repo(a						,		**a						)
       A__         =    self._get_files_timestamps(a						)
    # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
    # loaded from the Hub.
    if self._auto_class is not None:
       A__         =    [getattr(self						,		a						) for attribute_name in self.attributes]
       A__         =    [(a.init_kwargs if isinstance(a						,		a						) else a) for a in attrs]
       custom_object_save(self						,		a						,		config=a						)

    for attribute_name in self.attributes:
       A__         =    getattr(self						,		a						)
       # Include the processor class in the attribute config so this processor can then be reloaded with the
       # `AutoProcessor` API.
       if hasattr(a						,		'_set_processor_class'						):
          attribute._set_processor_class(self.__class__.__name__						)
       attribute.save_pretrained(a						)

    if self._auto_class is not None:
       # We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
       for attribute_name in self.attributes:
          A__         =    getattr(self						,		a						)
          if isinstance(a						,		a						):
             del attribute.init_kwargs["auto_map"]

    if push_to_hub:
       self._upload_modified_files(
           a						,		a						,		a						,		commit_message=a						,		token=kwargs.get('use_auth_token'						)						,		)






 @classmethod
 def 	_UpperCamelCase   (cls					:     int						,		a					:     Union[str, os.PathLike]						,		a					:     Optional[Union[str, os.PathLike]] = None						,		a					:     bool = False						,		a					:     bool = False						,		a					:     Optional[Union[str, bool]] = None						,		a					:     str = "main"						,		**a					:     Union[str, Any]						,		)					->      Optional[Any]:






    """simple docstring"""


    A__         =    cache_dir
    A__         =    force_download
    A__         =    local_files_only
    A__         =    revision

    A__         =    kwargs.pop('use_auth_token'						,		a						)
    if use_auth_token is not None:
       warnings.warn(
           'The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.'						,		a						)
       if token is not None:
          raise ValueError(
              '`token` and `use_auth_token` are both specified. Please set only the argument `token`.'						)
       A__         =    use_auth_token

    if token is not None:
       # change to `token` in a follow-up PR
       A__         =    token

    A__         =    cls._get_arguments_from_pretrained(a						,		**a						)
    return cls(*a						)






 @classmethod
 def 	_UpperCamelCase   (cls					:     Optional[int]						,		a					:     Union[str, Any]="AutoProcessor"						)					->      Any:






    """simple docstring"""


    if not isinstance(a						,		a						):
       A__         =    auto_class.__name__

    import transformers.models.auto as auto_module

    if not hasattr(a						,		a						):
       raise ValueError(f"""{auto_class} is not a valid auto class."""						)

    A__         =    auto_class






 @classmethod
 def 	_UpperCamelCase   (cls					:     Optional[Any]						,		a					:     Optional[Any]						,		**a					:     Tuple						)					->      int:






    """simple docstring"""


    A__         =    []
    for attribute_name in cls.attributes:
       A__         =    getattr(cls						,		f"""{attribute_name}_class"""						)
       if isinstance(a						,		a						):
          A__         =    tuple(getattr(a						,		a						) if n is not None else None for n in class_name						)
          A__         =    kwargs.get('use_fast'						,		a						)
          if use_fast and classes[1] is not None:
             A__         =    classes[1]
          else:
             A__         =    classes[0]
       else:
          A__         =    getattr(a						,		a						)

       args.append(attribute_class.from_pretrained(a						,		**a						)						)
    return args






 @property
 def 	_UpperCamelCase   (self					:     str						)					->      List[str]:






    """simple docstring"""


    A__         =    getattr(self						,		self.attributes[0]						)
    return getattr(a						,		'model_input_names'						,		a						)




lowerCAmelCase_    	=							copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
    lowerCAmelCase_    	=							ProcessorMixin.push_to_hub.__doc__.format(
        object='''processor''', object_class='''AutoProcessor''', object_files='''processor files'''
    )


