






'''simple docstring'''




import json
import os
import shutil
import tempfile
import unittest

from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.utils import FEATURE_EXTRACTOR_NAME

from .test_feature_extraction_wavaveca import floats_list

class      _UpperCAmelCase    (  unittest.TestCase		):




   """simple docstring"""

   def 		lowerCAmelCase				(	self				:			Optional[int]	):





         '''simple docstring'''





         _A      =			"""<pad> <s> </s> <unk> | E T A O N I H S R D L U M W C F G Y P B V K ' X J Q Z""".split(" "	)
         _A      =			dict(zip(_lowerCamelCase   ,   range(len(_lowerCamelCase	)	)	)	)

         _A      =			{
             """pad_token""": """<pad>""",
             """unk_token""": """<unk>""",
             """bos_token""": """<s>""",
             """eos_token""": """</s>""",
         }
         _A      =			{
             """feature_size""": 1,
             """padding_value""": 0.0,
             """sampling_rate""": 16000,
             """return_attention_mask""": False,
             """do_normalize""": True,
         }

         _A      =			tempfile.mkdtemp()
         _A      =			os.path.join(self.tmpdirname   ,   VOCAB_FILES_NAMES["vocab_file"]	)
         _A      =			os.path.join(self.tmpdirname   ,   _lowerCamelCase	)
         with open(self.vocab_file   ,   "w"   ,   encoding="utf-8"	) as fp:
               fp.write(json.dumps(_lowerCamelCase	) + "\n"	)

         with open(self.feature_extraction_file   ,   "w"   ,   encoding="utf-8"	) as fp:
               fp.write(json.dumps(_lowerCamelCase	) + "\n"	)

   def 		lowerCAmelCase				(	self				:			Optional[int]   ,   **__UpperCAmelCase				:			Union[str, Any]	):





         '''simple docstring'''





         _A      =			self.add_kwargs_tokens_map.copy()
         kwargs.update(_lowerCamelCase	)
         return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname   ,   **_lowerCamelCase	)

   def 		lowerCAmelCase				(	self				:			Any   ,   **__UpperCAmelCase				:			str	):





         '''simple docstring'''





         return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname   ,   **_lowerCamelCase	)

   def 		lowerCAmelCase				(	self				:			Any	):





         '''simple docstring'''





         shutil.rmtree(self.tmpdirname	)

   def 		lowerCAmelCase				(	self				:			Tuple	):





         '''simple docstring'''





         _A      =			self.get_tokenizer()
         _A      =			self.get_feature_extractor()

         _A      =			WavaVecaProcessor(tokenizer=_lowerCamelCase   ,   feature_extractor=_lowerCamelCase	)

         processor.save_pretrained(self.tmpdirname	)
         _A      =			WavaVecaProcessor.from_pretrained(self.tmpdirname	)

         self.assertEqual(processor.tokenizer.get_vocab()   ,   tokenizer.get_vocab()	)
         self.assertIsInstance(processor.tokenizer   ,   _lowerCamelCase	)

         self.assertEqual(processor.feature_extractor.to_json_string()   ,   feature_extractor.to_json_string()	)
         self.assertIsInstance(processor.feature_extractor   ,   _lowerCamelCase	)

   def 		lowerCAmelCase				(	self				:			Optional[Any]	):





         '''simple docstring'''





         _A      =			WavaVecaProcessor(tokenizer=self.get_tokenizer()   ,   feature_extractor=self.get_feature_extractor()	)
         processor.save_pretrained(self.tmpdirname	)

         _A      =			self.get_tokenizer(bos_token="(BOS)"   ,   eos_token="(EOS)"	)
         _A      =			self.get_feature_extractor(do_normalize=_lowerCamelCase   ,   padding_value=1.0	)

         _A      =			WavaVecaProcessor.from_pretrained(
             self.tmpdirname   ,   bos_token="(BOS)"   ,   eos_token="(EOS)"   ,   do_normalize=_lowerCamelCase   ,   padding_value=1.0	)

         self.assertEqual(processor.tokenizer.get_vocab()   ,   tokenizer_add_kwargs.get_vocab()	)
         self.assertIsInstance(processor.tokenizer   ,   _lowerCamelCase	)

         self.assertEqual(processor.feature_extractor.to_json_string()   ,   feature_extractor_add_kwargs.to_json_string()	)
         self.assertIsInstance(processor.feature_extractor   ,   _lowerCamelCase	)

   def 		lowerCAmelCase				(	self				:			int	):





         '''simple docstring'''





         _A      =			self.get_feature_extractor()
         _A      =			self.get_tokenizer()

         _A      =			WavaVecaProcessor(tokenizer=_lowerCamelCase   ,   feature_extractor=_lowerCamelCase	)

         _A      =			floats_list((3, 1000)	)

         _A      =			feature_extractor(_lowerCamelCase   ,   return_tensors="np"	)
         _A      =			processor(_lowerCamelCase   ,   return_tensors="np"	)

         for key in input_feat_extract.keys():
               self.assertAlmostEqual(input_feat_extract[key].sum()   ,   input_processor[key].sum()   ,   delta=1E-2	)

   def 		lowerCAmelCase				(	self				:			Optional[int]	):





         '''simple docstring'''





         _A      =			self.get_feature_extractor()
         _A      =			self.get_tokenizer()

         _A      =			WavaVecaProcessor(tokenizer=_lowerCamelCase   ,   feature_extractor=_lowerCamelCase	)

         _A      =			"""This is a test string"""

         _A      =			processor(text=_lowerCamelCase	)

         _A      =			tokenizer(_lowerCamelCase	)

         for key in encoded_tok.keys():
               self.assertListEqual(encoded_tok[key]   ,   encoded_processor[key]	)

   def 		lowerCAmelCase				(	self				:			List[str]	):





         '''simple docstring'''





         _A      =			self.get_feature_extractor()
         _A      =			self.get_tokenizer()

         _A      =			WavaVecaProcessor(tokenizer=_lowerCamelCase   ,   feature_extractor=_lowerCamelCase	)

         _A      =			[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

         _A      =			processor.batch_decode(_lowerCamelCase	)
         _A      =			tokenizer.batch_decode(_lowerCamelCase	)

         self.assertListEqual(_lowerCamelCase   ,   _lowerCamelCase	)

   def 		lowerCAmelCase				(	self				:			Optional[int]	):





         '''simple docstring'''





         _A      =			self.get_feature_extractor()
         _A      =			self.get_tokenizer()

         _A      =			WavaVecaProcessor(tokenizer=_lowerCamelCase   ,   feature_extractor=_lowerCamelCase	)

         self.assertListEqual(
             processor.model_input_names   ,   feature_extractor.model_input_names   ,   msg="`processor` and `feature_extractor` model input names do not match"   ,   )








'''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      _UpperCAmelCase    :




   """simple docstring"""

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





@dataclass
class      _UpperCAmelCase    :




   """simple docstring"""

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





def       __lowercase		(    ) ->		Any:

      '''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(__lowercase     ,						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"     ,						__lowercase )

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

      # 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=__lowercase     ,						idalabel=__lowercase     ,						labelaid={label: i for i, label in enumerate(__lowercase )}     ,						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=__lowercase     ,						cache_dir=model_args.cache_dir     ,						)

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

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

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

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

      # 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(__lowercase     ,						"w" ) as writer:
                  logger.info("***** Eval results *****" )

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

                  results.update(__lowercase )

    # Predict
      if training_args.do_predict:
            _A      =			TFTokenClassificationDataset(
                token_classification_task=__lowercase     ,						data_dir=data_args.data_dir     ,						tokenizer=__lowercase     ,						labels=__lowercase     ,						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(__lowercase     ,						__lowercase )
            _A      =			classification_report(__lowercase     ,						__lowercase )

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

            _A      =			os.path.join(training_args.output_dir     ,						"test_results.txt" )

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

            # Save predictions
            _A      =			os.path.join(training_args.output_dir     ,						"test_predictions.txt" )

            with open(__lowercase     ,						"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(__lowercase )

                                    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(__lowercase )
                              else:
                                    logger.warning("Maximum sequence length exceeded: No prediction for '%s'."     ,						line.split()[0] )

      return results


if __name__ == "__main__":
    main()





