






import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
     from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse("1.6"):
     UpperCAmelCase__							  =						True
     from torch.cuda.amp import autocast

UpperCAmelCase__							  =						logging.getLogger(__name__)
def 		_a       ( a					:Optional[int]=None      ,				a					:int=None					)				->     Optional[Any]:
 return field(default_factory=lambda: default      ,				metadata=a					)






@dataclass
class 						lowercase_   :






      '''simple docstring'''




      __snake_case	    =    field(
          metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}  )
      __snake_case	    =    field(
          default=lowercase					,    metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}					,    )
      __snake_case	    =    field(
          default=lowercase					,    metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}  )
      __snake_case	    =    field(
          default=0.1					,    metadata={'''help''': '''The dropout ratio for the attention probabilities.'''}  )
      __snake_case	    =    field(
          default=0.1					,    metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''}  )
      __snake_case	    =    field(
          default=0.1					,    metadata={
              '''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
          }					,    )
      __snake_case	    =    field(
          default=0.1					,    metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''}					,    )
      __snake_case	    =    field(
          default=0.0_5					,    metadata={
              '''help''': (
                  '''Propability of each feature vector along the time axis to be chosen as the start of the vector'''
                  '''span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'''
                  '''vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'''
              )
          }					,    )
      __snake_case	    =    field(default=0.0					,    metadata={'''help''': '''The LayerDrop probability.'''}  )






@dataclass
class 						lowercase_   :






      '''simple docstring'''




      __snake_case	    =    field(
          default=lowercase					,    metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}  )
      __snake_case	    =    field(
          default='''train+validation'''					,    metadata={
              '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
          }					,    )
      __snake_case	    =    field(
          default=lowercase					,    metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}  )
      __snake_case	    =    field(
          default=lowercase					,    metadata={'''help''': '''The number of processes to use for the preprocessing.'''}					,    )
      __snake_case	    =    field(
          default=lowercase					,    metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of training examples to this '''
                  '''value if set.'''
              )
          }					,    )
      __snake_case	    =    field(
          default=lowercase					,    metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of validation examples to this '''
                  '''value if set.'''
              )
          }					,    )
      __snake_case	    =    list_field(
          default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�''']					,    metadata={'''help''': '''A list of characters to remove from the transcripts.'''}					,    )






@dataclass
class 						lowercase_   :






      '''simple docstring'''




      __snake_case	    =    42
      __snake_case	    =    True
      __snake_case	    =    None
      __snake_case	    =    None
      __snake_case	    =    None
      __snake_case	    =    None







      def __call__( self :		Any					,   __UpperCAmelCase :		List[Dict[str, Union[List[int], torch.Tensor]]]    )       ->Dict[str, torch.Tensor]:




       """simple docstring"""


       a						    = [{'''input_values''': feature['''input_values''']} for feature in features]
       a						    = [{'''input_ids''': feature['''labels''']} for feature in features]

       a						    = self.processor.pad(
           __UpperCAmelCase					,   padding=self.padding					,   max_length=self.max_length					,   pad_to_multiple_of=self.pad_to_multiple_of					,   return_tensors='''pt'''					,   )
       a						    = self.processor.pad(
           labels=__UpperCAmelCase					,   padding=self.padding					,   max_length=self.max_length_labels					,   pad_to_multiple_of=self.pad_to_multiple_of_labels					,   return_tensors='''pt'''					,   )

       # replace padding with -100 to ignore loss correctly
       a						    = labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1    )					,   -100    )

       a						    = labels

       return batch






class 						lowercase_   (      lowercase  ):






      '''simple docstring'''




      def  __lowerCAmelCase   ( self :		Optional[Any]					,   __UpperCAmelCase :		nn.Module					,   __UpperCAmelCase :		Dict[str, Union[torch.Tensor, Any]]    )       ->torch.Tensor:




       """simple docstring"""


       model.train()
       a						    = self._prepare_inputs(__UpperCAmelCase    )

       if self.use_amp:
        with autocast():
         a						    = self.compute_loss(__UpperCAmelCase					,   __UpperCAmelCase    )
       else:
        a						    = self.compute_loss(__UpperCAmelCase					,   __UpperCAmelCase    )

       if self.args.n_gpu > 1:
        if model.module.config.ctc_loss_reduction == "mean":
         a						    = loss.mean()
        elif model.module.config.ctc_loss_reduction == "sum":
         a						    = loss.sum() / (inputs['''labels'''] >= 0).sum()
        else:
         raise ValueError(F"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']"""    )

       if self.args.gradient_accumulation_steps > 1:
        a						    = loss / self.args.gradient_accumulation_steps

       if self.use_amp:
        self.scaler.scale(__UpperCAmelCase    ).backward()
       elif self.use_apex:
        with amp.scale_loss(__UpperCAmelCase					,   self.optimizer    ) as scaled_loss:
         scaled_loss.backward()
       elif self.deepspeed:
        self.deepspeed.backward(__UpperCAmelCase    )
       else:
        loss.backward()

       return loss.detach()
def 		_a       ( )				->     int:
 # 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.

 a						    = 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.
  a    ,	a    ,	a						    = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]					)					)
 else:
  a    ,	a    ,	a						    = parser.parse_args_into_dataclasses()

 # Detecting last checkpoint.
 a						    = None
 if os.path.isdir(training_args.output_dir					) and training_args.do_train and not training_args.overwrite_output_dir:
  a						    = get_last_checkpoint(training_args.output_dir					)
  if last_checkpoint is None and len(os.listdir(training_args.output_dir					)					) > 0:
   raise ValueError(
       F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
       '''Use --overwrite_output_dir to overcome.'''					)
  elif last_checkpoint is not None:
   logger.info(
       F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
       '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''					)

    # Setup logging
 logging.basicConfig(
     format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''      ,				datefmt='''%m/%d/%Y %H:%M:%S'''      ,				handlers=[logging.StreamHandler(sys.stdout					)]      ,				)
 logger.setLevel(logging.INFO if is_main_process(training_args.local_rank					) else logging.WARN					)

 # Log on each process the small summary:
 logger.warning(
     F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
     + F"""distributed training: {bool(training_args.local_rank != -1					)}, 16-bits training: {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()
 logger.info('''Training/evaluation parameters %s'''      ,				a					)

 # Set seed before initializing model.
 set_seed(training_args.seed					)

 # Get the datasets:
 a						    = datasets.load_dataset(
     '''common_voice'''      ,				data_args.dataset_config_name      ,				split=data_args.train_split_name					)
 a						    = datasets.load_dataset('''common_voice'''      ,				data_args.dataset_config_name      ,				split='''test'''					)

 # Create and save tokenizer
 a						    = F"""[{''.join(data_args.chars_to_ignore					)}]"""

 def remove_special_characters(a					:List[Any]					):
  a						    = re.sub(a      ,				''''''      ,				batch['''sentence''']					).lower() + ''' '''
  return batch

 a						    = train_dataset.map(a      ,				remove_columns=['''sentence''']					)
 a						    = eval_dataset.map(a      ,				remove_columns=['''sentence''']					)

 def extract_all_chars(a					:Dict					):
  a						    = ''' '''.join(batch['''text''']					)
  a						    = list(set(a					)					)
  return {"vocab": [vocab], "all_text": [all_text]}

 a						    = train_dataset.map(
     a      ,				batched=a      ,				batch_size=-1      ,				keep_in_memory=a      ,				remove_columns=train_dataset.column_names      ,				)
 a						    = train_dataset.map(
     a      ,				batched=a      ,				batch_size=-1      ,				keep_in_memory=a      ,				remove_columns=eval_dataset.column_names      ,				)

 a						    = list(set(vocab_train['''vocab'''][0]					) | set(vocab_test['''vocab'''][0]					)					)
 a						    = {v: k for k, v in enumerate(a					)}
 a						    = vocab_dict[''' ''']
 del vocab_dict[" "]
 a						    = len(a					)
 a						    = len(a					)

 with open('''vocab.json'''      ,				'''w'''					) as vocab_file:
  json.dump(a      ,				a					)

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.
 a						    = WavaVecaCTCTokenizer(
     '''vocab.json'''      ,				unk_token='''[UNK]'''      ,				pad_token='''[PAD]'''      ,				word_delimiter_token='''|'''      ,				)
 a						    = WavaVecaFeatureExtractor(
     feature_size=1      ,				sampling_rate=16_000      ,				padding_value=0.0      ,				do_normalize=a      ,				return_attention_mask=a					)
 a						    = WavaVecaProcessor(feature_extractor=a      ,				tokenizer=a					)
 a						    = WavaVecaForCTC.from_pretrained(
     model_args.model_name_or_path      ,				cache_dir=model_args.cache_dir      ,				activation_dropout=model_args.activation_dropout      ,				attention_dropout=model_args.attention_dropout      ,				hidden_dropout=model_args.hidden_dropout      ,				feat_proj_dropout=model_args.feat_proj_dropout      ,				mask_time_prob=model_args.mask_time_prob      ,				gradient_checkpointing=training_args.gradient_checkpointing      ,				layerdrop=model_args.layerdrop      ,				ctc_loss_reduction='''mean'''      ,				pad_token_id=processor.tokenizer.pad_token_id      ,				vocab_size=len(processor.tokenizer					)      ,				)

 if data_args.max_train_samples is not None:
  a						    = min(len(a					)      ,				data_args.max_train_samples					)
  a						    = train_dataset.select(range(a					)					)

 if data_args.max_val_samples is not None:
  a						    = eval_dataset.select(range(data_args.max_val_samples					)					)

 a						    = torchaudio.transforms.Resample(48_000      ,				16_000					)

 # Preprocessing the datasets.
 # We need to read the aduio files as arrays and tokenize the targets.
 def speech_file_to_array_fn(a					:Optional[Any]					):
  a    ,	a						    = torchaudio.load(batch['''path''']					)
  a						    = resampler(a					).squeeze().numpy()
  a						    = 16_000
  a						    = batch['''text''']
  return batch

 a						    = train_dataset.map(
     a      ,				remove_columns=train_dataset.column_names      ,				num_proc=data_args.preprocessing_num_workers      ,				)
 a						    = eval_dataset.map(
     a      ,				remove_columns=eval_dataset.column_names      ,				num_proc=data_args.preprocessing_num_workers      ,				)

 def prepare_dataset(a					:Dict					):
  # check that all files have the correct sampling rate
  assert (
      len(set(batch['''sampling_rate''']					)					) == 1
  ), F"""Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}."""

  a						    = processor(
      audio=batch['''speech''']      ,				text=batch['''target_text''']      ,				sampling_rate=batch['''sampling_rate'''][0]					)
  batch.update(a					)
  return batch

 a						    = train_dataset.map(
     a      ,				remove_columns=train_dataset.column_names      ,				batch_size=training_args.per_device_train_batch_size      ,				batched=a      ,				num_proc=data_args.preprocessing_num_workers      ,				)
 a						    = eval_dataset.map(
     a      ,				remove_columns=eval_dataset.column_names      ,				batch_size=training_args.per_device_train_batch_size      ,				batched=a      ,				num_proc=data_args.preprocessing_num_workers      ,				)

 # Metric
 a						    = datasets.load_metric('''wer'''					)

 def compute_metrics(a					:Union[str, Any]					):
  a						    = pred.predictions
  a						    = np.argmax(a      ,				axis=-1					)

  a						    = processor.tokenizer.pad_token_id

  a						    = processor.batch_decode(a					)
  # we do not want to group tokens when computing the metrics
  a						    = processor.batch_decode(pred.label_ids      ,				group_tokens=a					)

  a						    = wer_metric.compute(predictions=a      ,				references=a					)

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

 # Data collator
 a						    = DataCollatorCTCWithPadding(processor=a      ,				padding=a					)

 # Initialize our Trainer
 a						    = CTCTrainer(
     model=a      ,				data_collator=a      ,				args=a      ,				compute_metrics=a      ,				train_dataset=train_dataset if training_args.do_train else None      ,				eval_dataset=eval_dataset if training_args.do_eval else None      ,				tokenizer=processor.feature_extractor      ,				)

 # Training
 if training_args.do_train:
  if last_checkpoint is not None:
   a						    = last_checkpoint
  elif os.path.isdir(model_args.model_name_or_path					):
   a						    = model_args.model_name_or_path
  else:
   a						    = None

  # Save the feature_extractor and the tokenizer
  if is_main_process(training_args.local_rank					):
   processor.save_pretrained(training_args.output_dir					)

  a						    = trainer.train(resume_from_checkpoint=a					)
  trainer.save_model()

  a						    = train_result.metrics
  a						    = (
      data_args.max_train_samples if data_args.max_train_samples is not None else len(a					)
  )
  a						    = min(a      ,				len(a					)					)

  trainer.log_metrics('''train'''      ,				a					)
  trainer.save_metrics('''train'''      ,				a					)
  trainer.save_state()

 # Evaluation
 a						    = {}
 if training_args.do_eval:
  logger.info('''*** Evaluate ***'''					)
  a						    = trainer.evaluate()
  a						    = data_args.max_val_samples if data_args.max_val_samples is not None else len(a					)
  a						    = min(a      ,				len(a					)					)

  trainer.log_metrics('''eval'''      ,				a					)
  trainer.save_metrics('''eval'''      ,				a					)

 return results


if __name__ == "__main__":
     main()










import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_realm import RealmTokenizer


UpperCAmelCase__							  =						logging.get_logger(__name__)

UpperCAmelCase__							  =						{"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

UpperCAmelCase__							  =						{
    "vocab_file": {
        "google/realm-cc-news-pretrained-embedder": (
            "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt"
        ),
        "google/realm-cc-news-pretrained-encoder": (
            "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt"
        ),
        "google/realm-cc-news-pretrained-scorer": (
            "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt"
        ),
        "google/realm-cc-news-pretrained-openqa": (
            "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt"
        ),
        "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt",
        "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt",
        "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt",
        "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt",
    },
    "tokenizer_file": {
        "google/realm-cc-news-pretrained-embedder": (
            "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont"
        ),
        "google/realm-cc-news-pretrained-encoder": (
            "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json"
        ),
        "google/realm-cc-news-pretrained-scorer": (
            "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json"
        ),
        "google/realm-cc-news-pretrained-openqa": (
            "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json"
        ),
        "google/realm-orqa-nq-openqa": (
            "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json"
        ),
        "google/realm-orqa-nq-reader": (
            "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json"
        ),
        "google/realm-orqa-wq-openqa": (
            "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json"
        ),
        "google/realm-orqa-wq-reader": (
            "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json"
        ),
    },
}

UpperCAmelCase__							  =						{
    "google/realm-cc-news-pretrained-embedder": 512,
    "google/realm-cc-news-pretrained-encoder": 512,
    "google/realm-cc-news-pretrained-scorer": 512,
    "google/realm-cc-news-pretrained-openqa": 512,
    "google/realm-orqa-nq-openqa": 512,
    "google/realm-orqa-nq-reader": 512,
    "google/realm-orqa-wq-openqa": 512,
    "google/realm-orqa-wq-reader": 512,
}

UpperCAmelCase__							  =						{
    "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True},
    "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True},
    "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True},
    "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True},
    "google/realm-orqa-nq-openqa": {"do_lower_case": True},
    "google/realm-orqa-nq-reader": {"do_lower_case": True},
    "google/realm-orqa-wq-openqa": {"do_lower_case": True},
    "google/realm-orqa-wq-reader": {"do_lower_case": True},
}






class 						lowercase_   (      lowercase  ):






      '''simple docstring'''




      __snake_case	    =    VOCAB_FILES_NAMES
      __snake_case	    =    PRETRAINED_VOCAB_FILES_MAP
      __snake_case	    =    PRETRAINED_INIT_CONFIGURATION
      __snake_case	    =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      __snake_case	    =    RealmTokenizer







      def __init__( self :		List[Any]					,   __UpperCAmelCase :		Union[str, Any]=None					,   __UpperCAmelCase :		Tuple=None					,   __UpperCAmelCase :		List[Any]=True					,   __UpperCAmelCase :		Any="[UNK]"					,   __UpperCAmelCase :		Dict="[SEP]"					,   __UpperCAmelCase :		List[str]="[PAD]"					,   __UpperCAmelCase :		str="[CLS]"					,   __UpperCAmelCase :		Optional[int]="[MASK]"					,   __UpperCAmelCase :		str=True					,   __UpperCAmelCase :		List[str]=None					,   **__UpperCAmelCase :		str					,   )       ->Optional[int]:




       """simple docstring"""


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

       a						    = json.loads(self.backend_tokenizer.normalizer.__getstate__()    )
       if (
           normalizer_state.get('''lowercase'''					,   __UpperCAmelCase    ) != do_lower_case
           or normalizer_state.get('''strip_accents'''					,   __UpperCAmelCase    ) != strip_accents
           or normalizer_state.get('''handle_chinese_chars'''					,   __UpperCAmelCase    ) != tokenize_chinese_chars
       ):
        a						    = getattr(__UpperCAmelCase					,   normalizer_state.pop('''type'''    )    )
        a						    = do_lower_case
        a						    = strip_accents
        a						    = tokenize_chinese_chars
        a						    = normalizer_class(**__UpperCAmelCase    )

       a						    = do_lower_case







      def  __lowerCAmelCase   ( self :		str					,   __UpperCAmelCase :		List[Any]					,   **__UpperCAmelCase :		List[str]    )       ->List[Any]:




       """simple docstring"""


       a						    = PaddingStrategy.MAX_LENGTH

       a						    = text
       a						    = kwargs.pop('''text_pair'''					,   __UpperCAmelCase    )
       a						    = kwargs.pop('''return_tensors'''					,   __UpperCAmelCase    )

       a						    = {
           '''input_ids''': [],
           '''attention_mask''': [],
           '''token_type_ids''': [],
       }

       for idx, candidate_text in enumerate(__UpperCAmelCase    ):
        if batch_text_pair is not None:
         a						    = batch_text_pair[idx]
        else:
         a						    = None

        a						    = super().__call__(__UpperCAmelCase					,   __UpperCAmelCase					,   return_tensors=__UpperCAmelCase					,   **__UpperCAmelCase    )

        a						    = encoded_candidates.get('''input_ids'''    )
        a						    = encoded_candidates.get('''attention_mask'''    )
        a						    = encoded_candidates.get('''token_type_ids'''    )

        if encoded_input_ids is not None:
         output_data["input_ids"].append(__UpperCAmelCase    )
        if encoded_attention_mask is not None:
         output_data["attention_mask"].append(__UpperCAmelCase    )
        if encoded_token_type_ids is not None:
         output_data["token_type_ids"].append(__UpperCAmelCase    )

       a						    = {key: item for key, item in output_data.items() if len(__UpperCAmelCase    ) != 0}

       return BatchEncoding(__UpperCAmelCase					,   tensor_type=__UpperCAmelCase    )







      def  __lowerCAmelCase   ( self :		Tuple					,   __UpperCAmelCase :		Optional[int]					,   __UpperCAmelCase :		Dict=None    )       ->str:




       """simple docstring"""


       a						    = [self.cls_token_id] + token_ids_a + [self.sep_token_id]

       if token_ids_a:
        output += token_ids_a + [self.sep_token_id]

       return output







      def  __lowerCAmelCase   ( self :		str					,   __UpperCAmelCase :		List[int]					,   __UpperCAmelCase :		Optional[List[int]] = None    )       ->List[int]:




       """simple docstring"""


       a						    = [self.sep_token_id]
       a						    = [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    ) * [0] + len(token_ids_a + sep    ) * [1]







      def  __lowerCAmelCase   ( self :		Dict					,   __UpperCAmelCase :		str					,   __UpperCAmelCase :		Optional[str] = None    )       ->Tuple[str]:




       """simple docstring"""


       a						    = self._tokenizer.model.save(__UpperCAmelCase					,   name=__UpperCAmelCase    )
       return tuple(__UpperCAmelCase    )


