

import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_splinter import SplinterTokenizer


_UpperCamelCase     =    logging.get_logger(__name__)

_UpperCamelCase     =    {'''vocab_file''': '''vocab.txt'''}

_UpperCamelCase     =    {
    '''vocab_file''': {
        '''tau/splinter-base''': '''https://huggingface.co/tau/splinter-base/resolve/main/vocab.txt''',
        '''tau/splinter-base-qass''': '''https://huggingface.co/tau/splinter-base-qass/resolve/main/vocab.txt''',
        '''tau/splinter-large''': '''https://huggingface.co/tau/splinter-large/resolve/main/vocab.txt''',
        '''tau/splinter-large-qass''': '''https://huggingface.co/tau/splinter-large-qass/resolve/main/vocab.txt''',
    }
}

_UpperCamelCase     =    {
    '''tau/splinter-base''': 512,
    '''tau/splinter-base-qass''': 512,
    '''tau/splinter-large''': 512,
    '''tau/splinter-large-qass''': 512,
}

_UpperCamelCase     =    {
    '''tau/splinter-base''': {'''do_lower_case''': False},
    '''tau/splinter-base-qass''': {'''do_lower_case''': False},
    '''tau/splinter-large''': {'''do_lower_case''': False},
    '''tau/splinter-large-qass''': {'''do_lower_case''': False},
}



class 					lowercase		( _UpperCamelCase      ):



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE      							=       VOCAB_FILES_NAMES
 __SCREAMING_SNAKE_CASE      							=       PRETRAINED_VOCAB_FILES_MAP
 __SCREAMING_SNAKE_CASE      							=       PRETRAINED_INIT_CONFIGURATION
 __SCREAMING_SNAKE_CASE      							=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __SCREAMING_SNAKE_CASE      							=       SplinterTokenizer




 def __init__(self , __a=None , __a=None , __a=True , __a="[UNK]" , __a="[SEP]" , __a="[PAD]" , __a="[CLS]" , __a="[MASK]" , __a="[QUESTION]" , __a=True , __a=None , **__a , )				->      Optional[Any]:






  """simple docstring"""





  super().__init__(
      __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , additional_special_tokens=(question_token,) , **__a , )

  UpperCAmelCase__           =       json.loads(self.backend_tokenizer.normalizer.__getstate__()				)
  if (
      pre_tok_state.get('lowercase' , __a				) != do_lower_case
      or pre_tok_state.get('strip_accents' , __a				) != strip_accents
  ):
   UpperCAmelCase__           =       getattr(__a , pre_tok_state.pop('type'				)				)
   UpperCAmelCase__           =       do_lower_case
   UpperCAmelCase__           =       strip_accents
   UpperCAmelCase__           =       pre_tok_class(**__a				)

  UpperCAmelCase__           =       do_lower_case




 @property
 def 						UpperCamelCase__							(self				)				->      Union[str, Any]:






  """simple docstring"""





  return self.convert_tokens_to_ids(self.question_token				)




 def 						UpperCamelCase__							(self , __a , __a = None				)				->      List[int]:






  """simple docstring"""





  if token_ids_a is None:
   return [self.cls_token_id] + token_ids_a + [self.sep_token_id]

  UpperCAmelCase__           =       [self.cls_token_id]
  UpperCAmelCase__           =       [self.sep_token_id]
  UpperCAmelCase__           =       [self.question_token_id] + [self.convert_tokens_to_ids('.'				)]
  if self.padding_side == "right":
   # Input is question-then-context
   return cls + token_ids_a + question_suffix + sep + token_ids_a + sep
  else:
   # Input is context-then-question
   return cls + token_ids_a + sep + token_ids_a + question_suffix + sep




 def 						UpperCamelCase__							(self , __a , __a = None				)				->      List[int]:






  """simple docstring"""





  UpperCAmelCase__           =       [self.sep_token_id]
  UpperCAmelCase__           =       [self.cls_token_id]
  UpperCAmelCase__           =       [self.question_token_id] + [self.convert_tokens_to_ids('.'				)]
  if token_ids_a is None:
   return len(cls + token_ids_a + sep				) * [0]

  if self.padding_side == "right":
   # Input is question-then-context
   return len(cls + token_ids_a + question_suffix + sep				) * [0] + len(token_ids_a + sep				) * [1]
  else:
   # Input is context-then-question
   return len(cls + token_ids_a + sep				) * [0] + len(token_ids_a + question_suffix + sep				) * [1]




 def 						UpperCamelCase__							(self , __a , __a = None				)				->      Tuple[str]:






  """simple docstring"""





  UpperCAmelCase__           =       self._tokenizer.model.save(__a , name=__a				)
  return tuple(__a				)






import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import transformers
from transformers import (
    AutoConfig,
    AutoModelForQuestionAnswering,
    AutoTokenizer,
    DataCollatorWithPadding,
    HfArgumentParser,
    SquadDataset,
    Trainer,
    TrainingArguments,
)
from transformers import SquadDataTrainingArguments as DataTrainingArguments
from transformers.trainer_utils import is_main_process


_UpperCamelCase     =    logging.getLogger(__name__)



@dataclass
class 					lowercase		:



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE      							=       field(
     metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}      )
 __SCREAMING_SNAKE_CASE      							=       field(
     default=_UpperCamelCase				,       metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}      )
 __SCREAMING_SNAKE_CASE      							=       field(
     default=_UpperCamelCase				,       metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}      )
 __SCREAMING_SNAKE_CASE      							=       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.
 __SCREAMING_SNAKE_CASE      							=       field(
     default=_UpperCamelCase				,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}				,       )







def 		UpperCamelCase_(    ) ->				List[str]:
 # 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.

 UpperCAmelCase__           =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )

 if len(sys.argv     ) == 2 and sys.argv[1].endswith('.json'     ):
  # If we pass only one argument to the script and it's the path to a json file,
  # let's parse it to get our arguments.
  UpperCAmelCase__       ,					UpperCAmelCase__       ,					UpperCAmelCase__           =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
 else:
  UpperCAmelCase__       ,					UpperCAmelCase__       ,					UpperCAmelCase__           =       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.'     )

 # Setup logging
 logging.basicConfig(
     format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'						,					datefmt='%m/%d/%Y %H:%M:%S'						,					level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN						,					)
 logger.warning(
     'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'						,					training_args.local_rank						,					training_args.device						,					training_args.n_gpu						,					bool(training_args.local_rank != -1     )						,					training_args.fpaa						,					)
 # Set the verbosity to info of the Transformers logger (on main process only):
 if is_main_process(training_args.local_rank     ):
  transformers.utils.logging.set_verbosity_info()
  transformers.utils.logging.enable_default_handler()
  transformers.utils.logging.enable_explicit_format()
 logger.info('Training/evaluation parameters %s'						,					snake_case__     )

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

 UpperCAmelCase__           =       AutoConfig.from_pretrained(
     model_args.config_name if model_args.config_name else model_args.model_name_or_path						,					cache_dir=model_args.cache_dir						,					)
 UpperCAmelCase__           =       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=snake_case__						,					)
 UpperCAmelCase__           =       AutoModelForQuestionAnswering.from_pretrained(
     model_args.model_name_or_path						,					from_tf=bool('.ckpt' in model_args.model_name_or_path     )						,					config=snake_case__						,					cache_dir=model_args.cache_dir						,					)

 # Get datasets
 UpperCAmelCase__           =       hasattr(model.config						,					'lang2id'     )
 UpperCAmelCase__           =       (
     SquadDataset(
         snake_case__						,					tokenizer=snake_case__						,					is_language_sensitive=snake_case__						,					cache_dir=model_args.cache_dir     )
     if training_args.do_train
     else None
 )
 UpperCAmelCase__           =       (
     SquadDataset(
         snake_case__						,					tokenizer=snake_case__						,					mode='dev'						,					is_language_sensitive=snake_case__						,					cache_dir=model_args.cache_dir						,					)
     if training_args.do_eval
     else None
 )

 # Data collator
 UpperCAmelCase__           =       DataCollatorWithPadding(snake_case__						,					pad_to_multiple_of=8     ) if training_args.fpaa else None

 # Initialize our Trainer
 UpperCAmelCase__           =       Trainer(
     model=snake_case__						,					args=snake_case__						,					train_dataset=snake_case__						,					eval_dataset=snake_case__						,					data_collator=snake_case__						,					)

 # Training
 if training_args.do_train:
  trainer.train(
      model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path     ) else None     )
  trainer.save_model()
  # For convenience, we also re-save the tokenizer to the same directory,
  # so that you can share your model easily on huggingface.co/models =)
  if trainer.is_world_master():
   tokenizer.save_pretrained(training_args.output_dir     )
def 		UpperCamelCase_(    snake_case__:						Optional[int]     ) ->				Union[str, Any]:
 # For xla_spawn (TPUs)
 main()


if __name__ == "__main__":
 main()



