


import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO
)
snake_case    :   List[str]	    =					logging.getLogger(__name__)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[Any]			,  UpperCAmelCase_						:		Any						):




      """simple docstring"""





      a						:Optional[Any]										=	np.argmax(UpperCAmelCase_			,  axis=1						)
      return np.sum(outputs == labels						)
def     __lowerCamelCase						(			UpperCAmelCase_						:		List[str]						):




      """simple docstring"""





      with open(UpperCAmelCase_			,  encoding='''utf_8'''						) as f:
            a						:List[str]										=	csv.reader(UpperCAmelCase_						)
            a						:Tuple										=	[]
            next(UpperCAmelCase_						)  # skip the first line
            for line in tqdm(UpperCAmelCase_						):
                  output.append((''' '''.join(line[1:5]						), line[5], line[6], int(line[-1]						) - 1)						)
      return output
def     __lowerCamelCase						(			UpperCAmelCase_						:		List[Any]			,  UpperCAmelCase_						:		Dict			,  UpperCAmelCase_						:		str			,  UpperCAmelCase_						:		Optional[Any]			,  UpperCAmelCase_						:		Union[str, Any]			,  UpperCAmelCase_						:		Tuple						):




      """simple docstring"""





      a						:Optional[int]										=	[]
      for dataset in encoded_datasets:
            a						:Union[str, Any]										=	len(UpperCAmelCase_						)
            a						:Tuple										=	np.zeros((n_batch, 2, input_len)			,  dtype=np.intaa						)
            a						:Optional[Any]										=	np.zeros((n_batch, 2)			,  dtype=np.intaa						)
            a						:int										=	np.full((n_batch, 2, input_len)			,  fill_value=-100			,  dtype=np.intaa						)
            a						:Union[str, Any]										=	np.zeros((n_batch,)			,  dtype=np.intaa						)
            for (
                i,
                (story, conta, conta, mc_label),
            ) in enumerate(UpperCAmelCase_						):
                  a						:Optional[int]										=	[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                  a						:Optional[Any]										=	[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
                  a						:Union[str, Any]										=	with_conta
                  a						:List[Any]										=	with_conta
                  a						:Dict										=	len(UpperCAmelCase_						) - 1
                  a						:Tuple										=	len(UpperCAmelCase_						) - 1
                  a						:Dict										=	with_conta
                  a						:List[str]										=	with_conta
                  a						:Any										=	mc_label
            a						:str										=	(input_ids, mc_token_ids, lm_labels, mc_labels)
            tensor_datasets.append(tuple(torch.tensor(UpperCAmelCase_						) for t in all_inputs						)						)
      return tensor_datasets
def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:int										=	argparse.ArgumentParser()
      parser.add_argument('''--model_name'''			,  type=UpperCAmelCase_			,  default='''openai-gpt'''			,  help='''pretrained model name'''						)
      parser.add_argument('''--do_train'''			,  action='''store_true'''			,  help='''Whether to run training.'''						)
      parser.add_argument('''--do_eval'''			,  action='''store_true'''			,  help='''Whether to run eval on the dev set.'''						)
      parser.add_argument(
          '''--output_dir'''			,  default=UpperCAmelCase_			,  type=UpperCAmelCase_			,  required=UpperCAmelCase_			,  help='''The output directory where the model predictions and checkpoints will be written.'''			,  )
      parser.add_argument('''--train_dataset'''			,  type=UpperCAmelCase_			,  default=''''''						)
      parser.add_argument('''--eval_dataset'''			,  type=UpperCAmelCase_			,  default=''''''						)
      parser.add_argument('''--seed'''			,  type=UpperCAmelCase_			,  default=42						)
      parser.add_argument('''--num_train_epochs'''			,  type=UpperCAmelCase_			,  default=3						)
      parser.add_argument('''--train_batch_size'''			,  type=UpperCAmelCase_			,  default=8						)
      parser.add_argument('''--eval_batch_size'''			,  type=UpperCAmelCase_			,  default=16						)
      parser.add_argument('''--adam_epsilon'''			,  default=1E-8			,  type=UpperCAmelCase_			,  help='''Epsilon for Adam optimizer.'''						)
      parser.add_argument('''--max_grad_norm'''			,  type=UpperCAmelCase_			,  default=1						)
      parser.add_argument(
          '''--max_steps'''			,  default=-1			,  type=UpperCAmelCase_			,  help=(
              '''If > 0: set total number of training                         steps to perform. Override num_train_epochs.'''
          )			,  )
      parser.add_argument(
          '''--gradient_accumulation_steps'''			,  type=UpperCAmelCase_			,  default=1			,  help='''Number of updates steps to accumulate before                        performing a backward/update pass.'''			,  )
      parser.add_argument('''--learning_rate'''			,  type=UpperCAmelCase_			,  default=6.25E-5						)
      parser.add_argument('''--warmup_steps'''			,  default=0			,  type=UpperCAmelCase_			,  help='''Linear warmup over warmup_steps.'''						)
      parser.add_argument('''--lr_schedule'''			,  type=UpperCAmelCase_			,  default='''warmup_linear'''						)
      parser.add_argument('''--weight_decay'''			,  type=UpperCAmelCase_			,  default=0.01						)
      parser.add_argument('''--lm_coef'''			,  type=UpperCAmelCase_			,  default=0.9						)
      parser.add_argument('''--n_valid'''			,  type=UpperCAmelCase_			,  default=374						)

      parser.add_argument('''--server_ip'''			,  type=UpperCAmelCase_			,  default=''''''			,  help='''Can be used for distant debugging.'''						)
      parser.add_argument('''--server_port'''			,  type=UpperCAmelCase_			,  default=''''''			,  help='''Can be used for distant debugging.'''						)
      a						:int										=	parser.parse_args()
      print(UpperCAmelCase_						)

      if args.server_ip and args.server_port:
            # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
            import ptvsd

            print('''Waiting for debugger attach'''						)
            ptvsd.enable_attach(address=(args.server_ip, args.server_port)			,  redirect_output=UpperCAmelCase_						)
            ptvsd.wait_for_attach()

      random.seed(args.seed						)
      np.random.seed(args.seed						)
      torch.manual_seed(args.seed						)
      torch.cuda.manual_seed_all(args.seed						)

      a						:Dict										=	torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''						)
      a						:str										=	torch.cuda.device_count()
      logger.info('''device: {}, n_gpu {}'''.format(UpperCAmelCase_			,  UpperCAmelCase_						)						)

      if not args.do_train and not args.do_eval:
            raise ValueError('''At least one of `do_train` or `do_eval` must be True.'''						)

      if not os.path.exists(args.output_dir						):
            os.makedirs(args.output_dir						)

      # Load tokenizer and model
      # This loading functions also add new tokens and embeddings called `special tokens`
      # These new embeddings will be fine-tuned on the RocStories dataset
      a						:List[str]										=	['''_start_''', '''_delimiter_''', '''_classify_''']
      a						:Dict										=	OpenAIGPTTokenizer.from_pretrained(args.model_name						)
      tokenizer.add_tokens(UpperCAmelCase_						)
      a						:Tuple										=	tokenizer.convert_tokens_to_ids(UpperCAmelCase_						)
      a						:Tuple										=	OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name						)
      model.resize_token_embeddings(len(UpperCAmelCase_						)						)
      model.to(UpperCAmelCase_						)

      # Load and encode the datasets
      def tokenize_and_encode(UpperCAmelCase_						:		Optional[int]						):
            if isinstance(UpperCAmelCase_			,  UpperCAmelCase_						):
                  return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(UpperCAmelCase_						)						)
            elif isinstance(UpperCAmelCase_			,  UpperCAmelCase_						):
                  return obj
            return [tokenize_and_encode(UpperCAmelCase_						) for o in obj]

      logger.info('''Encoding dataset...'''						)
      a						:Dict										=	load_rocstories_dataset(args.train_dataset						)
      a						:Optional[Any]										=	load_rocstories_dataset(args.eval_dataset						)
      a						:str										=	(train_dataset, eval_dataset)
      a						:Union[str, Any]										=	tokenize_and_encode(UpperCAmelCase_						)

      # Compute the max input length for the Transformer
      a						:List[Any]										=	model.config.n_positions // 2 - 2
      a						:List[str]										=	max(
          len(story[:max_length]						) + max(len(conta[:max_length]						)			,  len(conta[:max_length]						)						) + 3
          for dataset in encoded_datasets
          for story, conta, conta, _ in dataset						)
      a						:List[Any]										=	min(UpperCAmelCase_			,  model.config.n_positions						)  # Max size of input for the pre-trained model

      # Prepare inputs tensors and dataloaders
      a						:Union[str, Any]										=	pre_process_datasets(UpperCAmelCase_			,  UpperCAmelCase_			,  UpperCAmelCase_			,  *UpperCAmelCase_						)
      a						:Any										=	tensor_datasets[0], tensor_datasets[1]

      a						:int										=	TensorDataset(*UpperCAmelCase_						)
      a						:Tuple										=	RandomSampler(UpperCAmelCase_						)
      a						:Union[str, Any]										=	DataLoader(UpperCAmelCase_			,  sampler=UpperCAmelCase_			,  batch_size=args.train_batch_size						)

      a						:int										=	TensorDataset(*UpperCAmelCase_						)
      a						:Dict										=	SequentialSampler(UpperCAmelCase_						)
      a						:str										=	DataLoader(UpperCAmelCase_			,  sampler=UpperCAmelCase_			,  batch_size=args.eval_batch_size						)

      # Prepare optimizer
      if args.do_train:
            if args.max_steps > 0:
                  a						:List[Any]										=	args.max_steps
                  a						:List[str]										=	args.max_steps // (len(UpperCAmelCase_						) // args.gradient_accumulation_steps) + 1
            else:
                  a						:Dict										=	len(UpperCAmelCase_						) // args.gradient_accumulation_steps * args.num_train_epochs

            a						:Optional[Any]										=	list(model.named_parameters()						)
            a						:List[Any]										=	['''bias''', '''LayerNorm.bias''', '''LayerNorm.weight''']
            a						:int										=	[
                {
                    '''params''': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay						)],
                    '''weight_decay''': args.weight_decay,
                },
                {'''params''': [p for n, p in param_optimizer if any(nd in n for nd in no_decay						)], '''weight_decay''': 0.0},
            ]
            a						:Any										=	AdamW(UpperCAmelCase_			,  lr=args.learning_rate			,  eps=args.adam_epsilon						)
            a						:List[Any]										=	get_linear_schedule_with_warmup(
                UpperCAmelCase_			,  num_warmup_steps=args.warmup_steps			,  num_training_steps=UpperCAmelCase_						)

      if args.do_train:
            a						:List[Any]										=	0, 0, None
            model.train()
            for _ in trange(int(args.num_train_epochs						)			,  desc='''Epoch'''						):
                  a						:List[str]										=	0
                  a						:Any										=	0
                  a						:Optional[int]										=	tqdm(UpperCAmelCase_			,  desc='''Training'''						)
                  for step, batch in enumerate(UpperCAmelCase_						):
                        a						:Optional[Any]										=	tuple(t.to(UpperCAmelCase_						) for t in batch						)
                        a						:Optional[Any]										=	batch
                        a						:int										=	model(UpperCAmelCase_			,  mc_token_ids=UpperCAmelCase_			,  lm_labels=UpperCAmelCase_			,  mc_labels=UpperCAmelCase_						)
                        a						:List[Any]										=	args.lm_coef * losses[0] + losses[1]
                        loss.backward()
                        optimizer.step()
                        scheduler.step()
                        optimizer.zero_grad()
                        tr_loss += loss.item()
                        a						:Any										=	(
                            loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
                        )
                        nb_tr_steps += 1
                        a						:Union[str, Any]										=	'''Training loss: {:.2e} lr: {:.2e}'''.format(UpperCAmelCase_			,  scheduler.get_lr()[0]						)

    # Save a trained model
      if args.do_train:
            # Save a trained model, configuration and tokenizer
            a						:List[Any]										=	model.module if hasattr(UpperCAmelCase_			,  '''module'''						) else model  # Only save the model itself

            # If we save using the predefined names, we can load using `from_pretrained`
            a						:Any										=	os.path.join(args.output_dir			,  UpperCAmelCase_						)
            a						:List[Any]										=	os.path.join(args.output_dir			,  UpperCAmelCase_						)

            torch.save(model_to_save.state_dict()			,  UpperCAmelCase_						)
            model_to_save.config.to_json_file(UpperCAmelCase_						)
            tokenizer.save_vocabulary(args.output_dir						)

            # Load a trained model and vocabulary that you have fine-tuned
            a						:Tuple										=	OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir						)
            a						:Union[str, Any]										=	OpenAIGPTTokenizer.from_pretrained(args.output_dir						)
            model.to(UpperCAmelCase_						)

      if args.do_eval:
            model.eval()
            a						:List[str]										=	0, 0
            a						:Dict										=	0, 0
            for batch in tqdm(UpperCAmelCase_			,  desc='''Evaluating'''						):
                  a						:Union[str, Any]										=	tuple(t.to(UpperCAmelCase_						) for t in batch						)
                  a						:List[Any]										=	batch
                  with torch.no_grad():
                        a						:List[str]										=	model(
                            UpperCAmelCase_			,  mc_token_ids=UpperCAmelCase_			,  lm_labels=UpperCAmelCase_			,  mc_labels=UpperCAmelCase_						)

                  a						:Dict										=	mc_logits.detach().cpu().numpy()
                  a						:Dict										=	mc_labels.to('''cpu'''						).numpy()
                  a						:Union[str, Any]										=	accuracy(UpperCAmelCase_			,  UpperCAmelCase_						)

                  eval_loss += mc_loss.mean().item()
                  eval_accuracy += tmp_eval_accuracy

                  nb_eval_examples += input_ids.size(0						)
                  nb_eval_steps += 1

            a						:List[Any]										=	eval_loss / nb_eval_steps
            a						:Any										=	eval_accuracy / nb_eval_examples
            a						:str										=	tr_loss / nb_tr_steps if args.do_train else None
            a						:Optional[int]										=	{'''eval_loss''': eval_loss, '''eval_accuracy''': eval_accuracy, '''train_loss''': train_loss}

            a						:int										=	os.path.join(args.output_dir			,  '''eval_results.txt'''						)
            with open(UpperCAmelCase_			,  '''w'''						) as writer:
                  logger.info('''***** Eval results *****'''						)
                  for key in sorted(result.keys()						):
                        logger.info('''  %s = %s'''			,  UpperCAmelCase_			,  str(result[key]						)						)
                        writer.write('''%s = %s\n''' % (key, str(result[key]						))						)


if __name__ == "__main__":
     main()









import os
import re
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


snake_case    :   List[str]	    =					logging.get_logger(__name__)

snake_case    :   Optional[Any]	    =					{
    '''vocab_file''': '''vocab.txt''',
    '''merges_file''': '''bpe.codes''',
}

snake_case    :   str	    =					{
    '''vocab_file''': {
        '''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt''',
        '''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt''',
    },
    '''merges_file''': {
        '''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes''',
        '''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes''',
    },
}

snake_case    :   List[Any]	    =					{
    '''vinai/phobert-base''': 2_56,
    '''vinai/phobert-large''': 2_56,
}
def     __lowerCamelCase						(			UpperCAmelCase_						:		List[str]						):




      """simple docstring"""





      a						:Union[str, Any]										=	set()
      a						:str										=	word[0]
      for char in word[1:]:
            pairs.add((prev_char, char)						)
            a						:Optional[int]										=	char

      a						:Optional[int]										=	set(UpperCAmelCase_						)
      return pairs







class 		_snake_case  (				_snake_case							):
 SCREAMING_SNAKE_CASE__				=	VOCAB_FILES_NAMES
 SCREAMING_SNAKE_CASE__				=	PRETRAINED_VOCAB_FILES_MAP
 SCREAMING_SNAKE_CASE__				=	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES




 def __init__(		self ,  _lowerCamelCase ,  _lowerCamelCase ,  _lowerCamelCase="<s>" ,  _lowerCamelCase="</s>" ,  _lowerCamelCase="</s>" ,  _lowerCamelCase="<s>" ,  _lowerCamelCase="<unk>" ,  _lowerCamelCase="<pad>" ,  _lowerCamelCase="<mask>" ,  **_lowerCamelCase ,  ):
       super().__init__(
           bos_token=_lowerCamelCase ,  eos_token=_lowerCamelCase ,  unk_token=_lowerCamelCase ,  sep_token=_lowerCamelCase ,  cls_token=_lowerCamelCase ,  pad_token=_lowerCamelCase ,  mask_token=_lowerCamelCase ,  **_lowerCamelCase ,  )

       a						:Optional[Any]										=	vocab_file
       a						:Optional[Any]										=	merges_file

       a						:Any										=	{}
       a						:Any										=	0
       a						:int										=	1
       a						:Union[str, Any]										=	2
       a						:List[Any]										=	3

       self.add_from_file(_lowerCamelCase   )

       a						:List[str]										=	{v: k for k, v in self.encoder.items()}

       with open(_lowerCamelCase ,  encoding='''utf-8'''   ) as merges_handle:
             a						:List[str]										=	merges_handle.read().split('''\n'''   )[:-1]
       a						:Any										=	[tuple(merge.split()[:-1]   ) for merge in merges]
       a						:str										=	dict(zip(_lowerCamelCase ,  range(len(_lowerCamelCase   )   )   )   )
       a						:str										=	{}




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase = None   ):

       if token_ids_a is None:
             return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
       a						:Union[str, Any]										=	[self.cls_token_id]
       a						:Tuple										=	[self.sep_token_id]
       return cls + token_ids_a + sep + sep + token_ids_a + sep




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase = None ,  _lowerCamelCase = False   ):

       if already_has_special_tokens:
             return super().get_special_tokens_mask(
                 token_ids_a=_lowerCamelCase ,  token_ids_a=_lowerCamelCase ,  already_has_special_tokens=_lowerCamelCase   )

       if token_ids_a is None:
             return [1] + ([0] * len(_lowerCamelCase   )) + [1]
       return [1] + ([0] * len(_lowerCamelCase   )) + [1, 1] + ([0] * len(_lowerCamelCase   )) + [1]




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase = None   ):
       a						:Optional[int]										=	[self.sep_token_id]
       a						:Optional[Any]										=	[self.cls_token_id]

       if token_ids_a is None:
             return len(cls + token_ids_a + sep   ) * [0]
       return len(cls + token_ids_a + sep + sep + token_ids_a + sep   ) * [0]




 @property
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return len(self.encoder   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return dict(self.encoder ,  **self.added_tokens_encoder   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       if token in self.cache:
             return self.cache[token]
       a						:Optional[int]										=	tuple(_lowerCamelCase   )
       a						:List[str]										=	tuple(list(word[:-1]   ) + [word[-1] + '''</w>''']   )
       a						:Union[str, Any]										=	get_pairs(_lowerCamelCase   )

       if not pairs:
             return token

       while True:
             a						:Optional[Any]										=	min(_lowerCamelCase ,  key=lambda _lowerCamelCase   : self.bpe_ranks.get(_lowerCamelCase ,  float('''inf'''   )   )   )
             if bigram not in self.bpe_ranks:
                   break
             a							,    a						:Dict										=	bigram
             a						:Union[str, Any]										=	[]
             a						:int										=	0
             while i < len(_lowerCamelCase   ):
                   try:
                         a						:Optional[Any]										=	word.index(_lowerCamelCase ,  _lowerCamelCase   )
                   except ValueError:
                         new_word.extend(word[i:]   )
                         break
                   else:
                         new_word.extend(word[i:j]   )
                         a						:Union[str, Any]										=	j

                   if word[i] == first and i < len(_lowerCamelCase   ) - 1 and word[i + 1] == second:
                         new_word.append(first + second   )
                         i += 2
                   else:
                         new_word.append(word[i]   )
                         i += 1
             a						:Union[str, Any]										=	tuple(_lowerCamelCase   )
             a						:int										=	new_word
             if len(_lowerCamelCase   ) == 1:
                   break
             else:
                   a						:List[str]										=	get_pairs(_lowerCamelCase   )
       a						:Union[str, Any]										=	'''@@ '''.join(_lowerCamelCase   )
       a						:Dict										=	word[:-4]
       a						:Any										=	word
       return word




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       a						:Union[str, Any]										=	[]

       a						:str										=	re.findall(R'''\S+\n?''' ,  _lowerCamelCase   )

       for token in words:
             split_tokens.extend(list(self.bpe(_lowerCamelCase   ).split(''' '''   )   )   )
       return split_tokens




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       return self.encoder.get(_lowerCamelCase ,  self.encoder.get(self.unk_token   )   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       return self.decoder.get(_lowerCamelCase ,  self.unk_token   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       a						:Optional[int]										=	''' '''.join(_lowerCamelCase   ).replace('''@@ ''' ,  ''''''   ).strip()
       return out_string




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase = None   ):
       if not os.path.isdir(_lowerCamelCase   ):
             logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''   )
             return
       a						:Tuple										=	os.path.join(
           _lowerCamelCase ,  (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']   )
       a						:Optional[int]										=	os.path.join(
           _lowerCamelCase ,  (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']   )

       if os.path.abspath(self.vocab_file   ) != os.path.abspath(_lowerCamelCase   ):
             copyfile(self.vocab_file ,  _lowerCamelCase   )

       if os.path.abspath(self.merges_file   ) != os.path.abspath(_lowerCamelCase   ):
             copyfile(self.merges_file ,  _lowerCamelCase   )

       return out_vocab_file, out_merge_file




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       if isinstance(_lowerCamelCase ,  _lowerCamelCase   ):
             try:
                   with open(_lowerCamelCase ,  '''r''' ,  encoding='''utf-8'''   ) as fd:
                         self.add_from_file(_lowerCamelCase   )
             except FileNotFoundError as fnfe:
                   raise fnfe
             except UnicodeError:
                   raise Exception(F'''Incorrect encoding detected in {f}, please rebuild the dataset'''   )
             return

       a						:str										=	f.readlines()
       for lineTmp in lines:
             a						:Tuple										=	lineTmp.strip()
             a						:int										=	line.rfind(''' '''   )
             if idx == -1:
                   raise ValueError('''Incorrect dictionary format, expected \'<token> <cnt>\''''   )
             a						:Tuple										=	line[:idx]
             a						:Tuple										=	len(self.encoder   )





