



"""simple docstring"""


import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
    from apex import amp

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


snake_case_         = logging.getLogger(__name__)







@dataclass
class    A_    :



      """simple docstring"""
      __UpperCamelCase	       =							field(
          metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}       )
      __UpperCamelCase	       =							field(
          default=A_			,     metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}			,     )
      __UpperCamelCase	       =							field(
          default=A_			,     metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}       )
      __UpperCamelCase	       =							field(
          default=A_			,     metadata={"""help""": """Whether to log verbose messages or not."""}			,     )


def 				_lowerCAmelCase   (     lowercase_	,			lowercase_		):
      logging.basicConfig(
          format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'	,			datefmt='%m/%d/%Y %H:%M:%S'	,			handlers=[logging.StreamHandler(sys.stdout		)]	,			)
      UpperCAmelCase    =				logging.WARNING
      if model_args.verbose_logging:
            UpperCAmelCase    =				logging.DEBUG
      elif trainer_utils.is_main_process(training_args.local_rank		):
            UpperCAmelCase    =				logging.INFO
      logger.setLevel(lowercase__		)







@dataclass
class    A_    :



      """simple docstring"""
      __UpperCamelCase	       =							field(
          default=A_			,     metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}       )
      __UpperCamelCase	       =							field(
          default=A_			,     metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}       )
      __UpperCamelCase	       =							field(
          default="""train"""			,     metadata={
              """help""": """The name of the training data set split to use (via the datasets library). Defaults to \'train\'"""
          }			,     )
      __UpperCamelCase	       =							field(
          default="""validation"""			,     metadata={
              """help""": (
                  """The name of the validation data set split to use (via the datasets library). Defaults to \'validation\'"""
              )
          }			,     )
      __UpperCamelCase	       =							field(
          default="""text"""			,     metadata={"""help""": """Column in the dataset that contains label (target text). Defaults to \'text\'"""}			,     )
      __UpperCamelCase	       =							field(
          default="""file"""			,     metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to \'file\'"""}			,     )
      __UpperCamelCase	       =							field(
          default=A_			,     metadata={"""help""": """Resample loaded audio to target feature extractor\'s sampling rate or not."""}			,     )
      __UpperCamelCase	       =							field(
          default=A_			,     metadata={"""help""": """Filters out examples longer than specified. Defaults to no filtering."""}			,     )
      __UpperCamelCase	       =							field(
          default="""librispeech"""			,     metadata={
              """help""": (
                  """Orthography used for normalization and tokenization: \'librispeech\' (default), \'timit\', or"""
                  """ \'buckwalter\'."""
              )
          }			,     )
      __UpperCamelCase	       =							field(
          default=A_			,     metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}       )
      __UpperCamelCase	       =							field(
          default=A_			,     metadata={"""help""": """The number of processes to use for the preprocessing."""}			,     )







@dataclass
class    A_    :



      """simple docstring"""
      __UpperCamelCase	       =							False
      __UpperCamelCase	       =							None
      __UpperCamelCase	       =							"|"
      __UpperCamelCase	       =							field(default_factory=A_       )
      __UpperCamelCase	       =							field(default_factory=A_       )
      __UpperCamelCase	       =							None






      @classmethod
      def 			UpperCAmelCase__  (      cls				:Union[str, Any]     ,						lowercase_				:List[str]      )       ->    Any:
            if name == "librispeech":
                  return cls()
            if name == "timit":
                  return cls(
                      do_lower_case=lowercase_     ,						translation_table=str.maketrans({'-': ' '}      )     ,						)
            if name == "buckwalter":
                  UpperCAmelCase    =				{
                      '-': ' ',  # sometimes used to represent pauses
                      '^': 'v',  # fixing "tha" in arabic_speech_corpus dataset
                  }
                  return cls(
                      vocab_file=pathlib.Path(lowercase_      ).parent.joinpath('vocab/buckwalter.json'      )     ,						word_delimiter_token='/'     ,						translation_table=str.maketrans(lowercase_      )     ,						words_to_remove={'sil'}     ,						untransliterator=arabic.buckwalter.untransliterate     ,						)
            raise ValueError(f"""Unsupported orthography: \'{name}\'."""      )






      def 			UpperCAmelCase__  (      self				:Tuple     ,						lowercase_				:Union[str, Any]      )       ->    int:
            # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
            if len(self.translation_table      ) > 0:
                  UpperCAmelCase    =				text.translate(self.translation_table      )
            if len(self.words_to_remove      ) == 0:
                  UpperCAmelCase    =				' '.join(text.split()      )  # clean up whitespaces
            else:
                  UpperCAmelCase    =				' '.join(w for w in text.split() if w not in self.words_to_remove      )  # and clean up whilespaces
            return text






      def 			UpperCAmelCase__  (      self				:int     ,						lowercase_				:Optional[int]      )       ->    Tuple:
            UpperCAmelCase    =				WavaVecaFeatureExtractor.from_pretrained(
                model_args.model_name_or_path     ,						cache_dir=model_args.cache_dir      )
            if self.vocab_file:
                  UpperCAmelCase    =				WavaVecaCTCTokenizer(
                      self.vocab_file     ,						cache_dir=model_args.cache_dir     ,						do_lower_case=self.do_lower_case     ,						word_delimiter_token=self.word_delimiter_token     ,						)
            else:
                  UpperCAmelCase    =				WavaVecaCTCTokenizer.from_pretrained(
                      model_args.model_name_or_path     ,						cache_dir=model_args.cache_dir     ,						do_lower_case=self.do_lower_case     ,						word_delimiter_token=self.word_delimiter_token     ,						)
            return WavaVecaProcessor(lowercase_     ,						lowercase_      )







@dataclass
class    A_    :



      """simple docstring"""
      __UpperCamelCase	       =							42
      __UpperCamelCase	       =							True
      __UpperCamelCase	       =							None
      __UpperCamelCase	       =							None
      __UpperCamelCase	       =							None
      __UpperCamelCase	       =							None






      def __call__(      self				:List[Any]     ,						lowercase_				:Any      )       ->    Optional[Any]:
            # split inputs and labels since they have to be of different lenghts and need
            # different padding methods
            UpperCAmelCase    =				[{'input_values': feature['input_values']} for feature in features]
            UpperCAmelCase    =				[{'input_ids': feature['labels']} for feature in features]

            UpperCAmelCase    =				self.processor.pad(
                lowercase_     ,						padding=self.padding     ,						max_length=self.max_length     ,						pad_to_multiple_of=self.pad_to_multiple_of     ,						return_tensors='pt'     ,						)
            UpperCAmelCase    =				self.processor.pad(
                labels=lowercase_     ,						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
            UpperCAmelCase    =				labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1      )     ,						-1_00      )

            UpperCAmelCase    =				labels

            return batch







class    A_    (  A_       ):



      """simple docstring"""






      def 			UpperCAmelCase__  (      self				:Optional[int]     ,						lowercase_				:Dict     ,						lowercase_				:Any      )       ->    Dict:
            model.train()
            UpperCAmelCase    =				self._prepare_inputs(lowercase_      )

            if self.use_amp:
                  with autocast():
                        UpperCAmelCase    =				self.compute_loss(lowercase_     ,						lowercase_      )
            else:
                  UpperCAmelCase    =				self.compute_loss(lowercase_     ,						lowercase_      )

            if self.args.n_gpu > 1:
                  if model.module.config.ctc_loss_reduction == "mean":
                        UpperCAmelCase    =				loss.mean()
                  elif model.module.config.ctc_loss_reduction == "sum":
                        UpperCAmelCase    =				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:
                  UpperCAmelCase    =				loss / self.args.gradient_accumulation_steps

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

            return loss.detach()


def 				_lowerCAmelCase   (     ):
      UpperCAmelCase    =				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)

      UpperCAmelCase   ,					UpperCAmelCase   ,					UpperCAmelCase    =				parser.parse_args_into_dataclasses()
      configure_logger(lowercase__	,			lowercase__		)

      UpperCAmelCase    =				Orthography.from_name(data_args.orthography.lower()		)
      UpperCAmelCase    =				orthography.create_processor(lowercase__		)
      UpperCAmelCase    =				WavaVecaForCTC.from_pretrained(
          model_args.model_name_or_path	,			cache_dir=model_args.cache_dir	,			gradient_checkpointing=training_args.gradient_checkpointing	,			vocab_size=len(processor.tokenizer		)	,			)

      UpperCAmelCase    =				datasets.load_dataset(
          data_args.dataset_name	,			data_args.dataset_config_name	,			split=data_args.train_split_name		)
      UpperCAmelCase    =				datasets.load_dataset(
          data_args.dataset_name	,			data_args.dataset_config_name	,			split=data_args.validation_split_name		)

      UpperCAmelCase    =				datasets.load_metric('wer'		)
      UpperCAmelCase    =				processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
      UpperCAmelCase    =				''.join(t for t in processor.tokenizer.get_vocab().keys() if len(lowercase__		) == 1		)
      UpperCAmelCase    =				re.compile(  # remove characters not in vocabulary
          RF"""[^\s{re.escape(lowercase__		)}]"""	,			flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0	,			)
      UpperCAmelCase    =				[]

      def prepare_example(lowercase_		):  # TODO(elgeish) make use of multiprocessing?
            UpperCAmelCase   ,					UpperCAmelCase    =				librosa.load(example[data_args.speech_file_column]	,			sr=lowercase__		)
            if data_args.max_duration_in_seconds is not None:
                  UpperCAmelCase    =				len(example['speech']		) / example['sampling_rate']
            # Normalize and clean up text; order matters!
            UpperCAmelCase    =				orthography.preprocess_for_training(example[data_args.target_text_column]		)
            UpperCAmelCase    =				vocabulary_text_cleaner.sub(''	,			lowercase__		)
            if updated_text != example[data_args.target_text_column]:
                  text_updates.append((example[data_args.target_text_column], updated_text)		)
                  UpperCAmelCase    =				updated_text
            return example

      UpperCAmelCase    =				train_dataset.map(lowercase__	,			remove_columns=[data_args.speech_file_column]		)
      UpperCAmelCase    =				val_dataset.map(lowercase__	,			remove_columns=[data_args.speech_file_column]		)

      if data_args.max_duration_in_seconds is not None:

            def filter_by_max_duration(lowercase_		):
                  return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

            UpperCAmelCase    =				len(lowercase__		)
            UpperCAmelCase    =				len(lowercase__		)
            UpperCAmelCase    =				train_dataset.filter(lowercase__	,			remove_columns=['duration_in_seconds']		)
            UpperCAmelCase    =				val_dataset.filter(lowercase__	,			remove_columns=['duration_in_seconds']		)
            if len(lowercase__		) > old_train_size:
                  logger.warning(
                      F"""Filtered out {len(lowercase__		) - old_train_size} train example(s) longer than"""
                      F""" {data_args.max_duration_in_seconds} second(s)."""		)
            if len(lowercase__		) > old_val_size:
                  logger.warning(
                      F"""Filtered out {len(lowercase__		) - old_val_size} validation example(s) longer than"""
                      F""" {data_args.max_duration_in_seconds} second(s)."""		)
      logger.info(F"""Split sizes: {len(lowercase__		)} train and {len(lowercase__		)} validation."""		)

      logger.warning(F"""Updated {len(lowercase__		)} transcript(s) using \'{data_args.orthography}\' orthography rules."""		)
      if logger.isEnabledFor(logging.DEBUG		):
            for original_text, updated_text in text_updates:
                  logger.debug(F"""Updated text: \"{original_text}\" -> \"{updated_text}\""""		)
      UpperCAmelCase    =				None

      def prepare_dataset(lowercase_		):
            # 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}."""

            UpperCAmelCase    =				processor(
                audio=batch['speech']	,			text=batch[data_args.target_text_column]	,			sampling_rate=batch['sampling_rate'][0]		)
            batch.update(lowercase__		)
            return batch

      UpperCAmelCase    =				train_dataset.map(
          lowercase__	,			batch_size=training_args.per_device_train_batch_size	,			batched=lowercase__	,			num_proc=data_args.preprocessing_num_workers	,			)
      UpperCAmelCase    =				val_dataset.map(
          lowercase__	,			batch_size=training_args.per_device_train_batch_size	,			batched=lowercase__	,			num_proc=data_args.preprocessing_num_workers	,			)

      UpperCAmelCase    =				DataCollatorCTCWithPadding(processor=lowercase__	,			padding=lowercase__		)

      def compute_metrics(lowercase_		):
            UpperCAmelCase    =				pred.predictions
            UpperCAmelCase    =				np.argmax(lowercase__	,			axis=-1		)

            UpperCAmelCase    =				processor.tokenizer.pad_token_id

            UpperCAmelCase    =				processor.batch_decode(lowercase__		)
            # we do not want to group tokens when computing the metrics
            UpperCAmelCase    =				processor.batch_decode(pred.label_ids	,			group_tokens=lowercase__		)
            if logger.isEnabledFor(logging.DEBUG		):
                  for reference, predicted in zip(lowercase__	,			lowercase__		):
                        logger.debug(F"""reference: \"{reference}\""""		)
                        logger.debug(F"""predicted: \"{predicted}\""""		)
                        if orthography.untransliterator is not None:
                              logger.debug(F"""reference (untransliterated): \"{orthography.untransliterator(lowercase__		)}\""""		)
                              logger.debug(F"""predicted (untransliterated): \"{orthography.untransliterator(lowercase__		)}\""""		)

            UpperCAmelCase    =				wer_metric.compute(predictions=lowercase__	,			references=lowercase__		)

            return {"wer": wer}

      if model_args.freeze_feature_extractor:
            model.freeze_feature_extractor()

      UpperCAmelCase    =				CTCTrainer(
          model=lowercase__	,			data_collator=lowercase__	,			args=lowercase__	,			compute_metrics=lowercase__	,			train_dataset=lowercase__	,			eval_dataset=lowercase__	,			tokenizer=processor.feature_extractor	,			)

      trainer.train()


if __name__ == "__main__":
    main()










"""simple docstring"""


import json
import os
import re
import unicodedata
from typing import Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
from ...utils import logging


snake_case_         = logging.get_logger(__name__)

snake_case_         = {
    """vocab_file""": """vocab.json""",
    """merges_file""": """merges.txt""",
}

snake_case_         = {
    """vocab_file""": {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/vocab.json"""},
    """merges_file""": {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/merges.txt"""},
}

snake_case_         = {
    """openai-gpt""": 512,
}

def 				_lowerCAmelCase   (     lowercase_		):
						UpperCAmelCase    =				text.strip()
						if not text:
												return []
						UpperCAmelCase    =				text.split()
						return tokens







class    A_    (  SCREAMING_SNAKE_CASE_       ):



						"""simple docstring"""






						def __init__(      self				:Dict     ,						lowercase_				:int=True     ,						lowercase_				:Union[str, Any]=None     ,						lowercase_				:List[Any]=True     ,						lowercase_				:List[str]=None     ,						lowercase_				:Optional[int]=True     ,						)       ->    Any:
												if never_split is None:
																		UpperCAmelCase    =				[]
												UpperCAmelCase    =				do_lower_case
												UpperCAmelCase    =				set(lowercase_      )
												UpperCAmelCase    =				tokenize_chinese_chars
												UpperCAmelCase    =				strip_accents
												UpperCAmelCase    =				do_split_on_punc






						def 			UpperCAmelCase__  (      self				:List[str]     ,						lowercase_				:Optional[int]     ,						lowercase_				:int=None      )       ->    List[Any]:
												UpperCAmelCase    =				self.never_split.union(set(lowercase_      )      ) if never_split else self.never_split
												UpperCAmelCase    =				self._clean_text(lowercase_      )

												# This was added on November 1st, 2018 for the multilingual and Chinese
												# models. This is also applied to the English models now, but it doesn't
												# matter since the English models were not trained on any Chinese data
												# and generally don't have any Chinese data in them (there are Chinese
												# characters in the vocabulary because Wikipedia does have some Chinese
												# words in the English Wikipedia.).
												if self.tokenize_chinese_chars:
																		UpperCAmelCase    =				self._tokenize_chinese_chars(lowercase_      )
												# prevents treating the same character with different unicode codepoints as different characters
												UpperCAmelCase    =				unicodedata.normalize('NFC'     ,						lowercase_      )
												UpperCAmelCase    =				whitespace_tokenize(lowercase_      )
												UpperCAmelCase    =				[]
												for token in orig_tokens:
																		if token not in never_split:
																								if self.do_lower_case:
																														UpperCAmelCase    =				token.lower()
																														if self.strip_accents is not False:
																																				UpperCAmelCase    =				self._run_strip_accents(lowercase_      )
																								elif self.strip_accents:
																														UpperCAmelCase    =				self._run_strip_accents(lowercase_      )
																		split_tokens.extend(self._run_split_on_punc(lowercase_     ,						lowercase_      )      )

												UpperCAmelCase    =				whitespace_tokenize(' '.join(lowercase_      )      )
												return output_tokens






						def 			UpperCAmelCase__  (      self				:Tuple     ,						lowercase_				:int      )       ->    Tuple:
												UpperCAmelCase    =				unicodedata.normalize('NFD'     ,						lowercase_      )
												UpperCAmelCase    =				[]
												for char in text:
																		UpperCAmelCase    =				unicodedata.category(lowercase_      )
																		if cat == "Mn":
																								continue
																		output.append(lowercase_      )
												return "".join(lowercase_      )






						def 			UpperCAmelCase__  (      self				:Optional[Any]     ,						lowercase_				:Tuple     ,						lowercase_				:Optional[Any]=None      )       ->    Optional[int]:
												if not self.do_split_on_punc or (never_split is not None and text in never_split):
																		return [text]
												UpperCAmelCase    =				list(lowercase_      )
												UpperCAmelCase    =				0
												UpperCAmelCase    =				True
												UpperCAmelCase    =				[]
												while i < len(lowercase_      ):
																		UpperCAmelCase    =				chars[i]
																		if _is_punctuation(lowercase_      ):
																								output.append([char]      )
																								UpperCAmelCase    =				True
																		else:
																								if start_new_word:
																														output.append([]      )
																								UpperCAmelCase    =				False
																								output[-1].append(lowercase_      )
																		i += 1

												return ["".join(lowercase_      ) for x in output]






						def 			UpperCAmelCase__  (      self				:Optional[int]     ,						lowercase_				:str      )       ->    int:
												UpperCAmelCase    =				[]
												for char in text:
																		UpperCAmelCase    =				ord(lowercase_      )
																		if self._is_chinese_char(lowercase_      ):
																								output.append(' '      )
																								output.append(lowercase_      )
																								output.append(' '      )
																		else:
																								output.append(lowercase_      )
												return "".join(lowercase_      )






						def 			UpperCAmelCase__  (      self				:List[Any]     ,						lowercase_				:int      )       ->    Optional[Any]:
												# This defines a "chinese character" as anything in the CJK Unicode block:
												#   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
												#
												# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
												# despite its name. The modern Korean Hangul alphabet is a different block,
												# as is Japanese Hiragana and Katakana. Those alphabets are used to write
												# space-separated words, so they are not treated specially and handled
												# like the all of the other languages.
												if (
												    (cp >= 0x4E00 and cp <= 0x9FFF)
												    or (cp >= 0x3400 and cp <= 0x4DBF)  #
												    or (cp >= 0x20000 and cp <= 0x2A6DF)  #
												    or (cp >= 0x2A700 and cp <= 0x2B73F)  #
												    or (cp >= 0x2B740 and cp <= 0x2B81F)  #
												    or (cp >= 0x2B820 and cp <= 0x2CEAF)  #
												    or (cp >= 0xF900 and cp <= 0xFAFF)
												    or (cp >= 0x2F800 and cp <= 0x2FA1F)  #
												):  #
																		return True

												return False






						def 			UpperCAmelCase__  (      self				:Optional[Any]     ,						lowercase_				:int      )       ->    List[Any]:
												UpperCAmelCase    =				[]
												for char in text:
																		UpperCAmelCase    =				ord(lowercase_      )
																		if cp == 0 or cp == 0xFFFD or _is_control(lowercase_      ):
																								continue
																		if _is_whitespace(lowercase_      ):
																								output.append(' '      )
																		else:
																								output.append(lowercase_      )
												return "".join(lowercase_      )


def 				_lowerCAmelCase   (     lowercase_		):
						UpperCAmelCase    =				set()
						UpperCAmelCase    =				word[0]
						for char in word[1:]:
												pairs.add((prev_char, char)		)
												UpperCAmelCase    =				char
						return pairs

def 				_lowerCAmelCase   (     lowercase_		):
						UpperCAmelCase    =				text.replace('—'	,			'-'		)
						UpperCAmelCase    =				text.replace('–'	,			'-'		)
						UpperCAmelCase    =				text.replace('―'	,			'-'		)
						UpperCAmelCase    =				text.replace('…'	,			'...'		)
						UpperCAmelCase    =				text.replace('´'	,			'\''		)
						UpperCAmelCase    =				re.sub(R'(-+|~+|!+|"+|;+|\?+|\++|,+|\)+|\(+|\\+|\/+|\*+|\[+|\]+|}+|{+|\|+|_+)'	,			R' \1 '	,			lowercase_		)
						UpperCAmelCase    =				re.sub(R'\s*\n\s*'	,			' \n '	,			lowercase_		)
						UpperCAmelCase    =				re.sub(R'[^\S\n]+'	,			' '	,			lowercase_		)
						return text.strip()







class    A_    (  SCREAMING_SNAKE_CASE_       ):



						"""simple docstring"""
						__UpperCamelCase	       =							VOCAB_FILES_NAMES
						__UpperCamelCase	       =							PRETRAINED_VOCAB_FILES_MAP
						__UpperCamelCase	       =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						__UpperCamelCase	       =							["""input_ids""", """attention_mask"""]






						def __init__(      self				:Dict     ,						lowercase_				:Optional[int]     ,						lowercase_				:Dict     ,						lowercase_				:List[str]="<unk>"     ,						**lowercase_				:Tuple      )       ->    Dict:
												super().__init__(unk_token=lowercase_     ,						**lowercase_      )

												try:
																		import ftfy
																		from spacy.lang.en import English

																		UpperCAmelCase    =				English()
																		UpperCAmelCase    =				_nlp.tokenizer
																		UpperCAmelCase    =				ftfy.fix_text
												except ImportError:
																		logger.warning('ftfy or spacy is not installed using BERT BasicTokenizer instead of SpaCy & ftfy.'      )
																		UpperCAmelCase    =				BasicTokenizer(do_lower_case=lowercase_      )
																		UpperCAmelCase    =				None

												with open(lowercase_     ,						encoding='utf-8'      ) as vocab_handle:
																		UpperCAmelCase    =				json.load(lowercase_      )
												UpperCAmelCase    =				{v: k for k, v in self.encoder.items()}
												with open(lowercase_     ,						encoding='utf-8'      ) as merges_handle:
																		UpperCAmelCase    =				merges_handle.read().split('\n'      )[1:-1]
												UpperCAmelCase    =				[tuple(merge.split()      ) for merge in merges]
												UpperCAmelCase    =				dict(zip(lowercase_     ,						range(len(lowercase_      )      )      )      )
												UpperCAmelCase    =				{}






						@property
						def 			UpperCAmelCase__  (      self				:Union[str, Any]      )       ->    List[Any]:
												return True






						@property
						def 			UpperCAmelCase__  (      self				:str      )       ->    str:
												return len(self.encoder      )






						def 			UpperCAmelCase__  (      self				:Optional[int]      )       ->    Optional[Any]:
												return dict(self.encoder     ,						**self.added_tokens_encoder      )






						def 			UpperCAmelCase__  (      self				:Union[str, Any]     ,						lowercase_				:List[Any]      )       ->    int:
												UpperCAmelCase    =				tuple(token[:-1]      ) + (token[-1] + '</w>',)
												if token in self.cache:
																		return self.cache[token]
												UpperCAmelCase    =				get_pairs(lowercase_      )

												if not pairs:
																		return token + "</w>"

												while True:
																		UpperCAmelCase    =				min(lowercase_     ,						key=lambda lowercase_      : self.bpe_ranks.get(lowercase_     ,						float('inf'      )      )      )
																		if bigram not in self.bpe_ranks:
																								break
																		UpperCAmelCase   ,					UpperCAmelCase    =				bigram
																		UpperCAmelCase    =				[]
																		UpperCAmelCase    =				0
																		while i < len(lowercase_      ):
																								try:
																														UpperCAmelCase    =				word.index(lowercase_     ,						lowercase_      )
																								except ValueError:
																														new_word.extend(word[i:]      )
																														break
																								else:
																														new_word.extend(word[i:j]      )
																														UpperCAmelCase    =				j

																								if word[i] == first and i < len(lowercase_      ) - 1 and word[i + 1] == second:
																														new_word.append(first + second      )
																														i += 2
																								else:
																														new_word.append(word[i]      )
																														i += 1
																		UpperCAmelCase    =				tuple(lowercase_      )
																		UpperCAmelCase    =				new_word
																		if len(lowercase_      ) == 1:
																								break
																		else:
																								UpperCAmelCase    =				get_pairs(lowercase_      )
												UpperCAmelCase    =				' '.join(lowercase_      )
												if word == "\n  </w>":
																		UpperCAmelCase    =				'\n</w>'
												UpperCAmelCase    =				word
												return word






						def 			UpperCAmelCase__  (      self				:List[str]     ,						lowercase_				:Union[str, Any]      )       ->    str:
												UpperCAmelCase    =				[]
												if self.fix_text is None:
																		# Using BERT's BasicTokenizer
																		UpperCAmelCase    =				self.nlp.tokenize(lowercase_      )
																		for token in text:
																								split_tokens.extend(list(self.bpe(lowercase_      ).split(' '      )      )      )
												else:
																		# Using SpaCy & ftfy (original tokenization process of OpenAI GPT)
																		UpperCAmelCase    =				self.nlp(text_standardize(self.fix_text(lowercase_      )      )      )
																		for token in text:
																								split_tokens.extend(list(self.bpe(token.text.lower()      ).split(' '      )      )      )
												return split_tokens






						def 			UpperCAmelCase__  (      self				:Tuple     ,						lowercase_				:Optional[Any]      )       ->    Tuple:
												return self.encoder.get(lowercase_     ,						self.encoder.get(self.unk_token      )      )






						def 			UpperCAmelCase__  (      self				:List[Any]     ,						lowercase_				:str      )       ->    Union[str, Any]:
												return self.decoder.get(lowercase_     ,						self.unk_token      )






						def 			UpperCAmelCase__  (      self				:Tuple     ,						lowercase_				:Optional[Any]      )       ->    Tuple:
												UpperCAmelCase    =				''.join(lowercase_      ).replace('</w>'     ,						' '      ).strip()
												return out_string






						def 			UpperCAmelCase__  (      self				:List[str]     ,						lowercase_				:str     ,						lowercase_				:Optional[str] = None      )       ->    Tuple[str]:
												if not os.path.isdir(lowercase_      ):
																		logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""      )
																		return
												UpperCAmelCase    =				os.path.join(
												    lowercase_     ,						(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']      )
												UpperCAmelCase    =				os.path.join(
												    lowercase_     ,						(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']      )

												with open(lowercase_     ,						'w'     ,						encoding='utf-8'      ) as f:
																		f.write(json.dumps(self.encoder     ,						indent=2     ,						sort_keys=lowercase_     ,						ensure_ascii=lowercase_      ) + '\n'      )

												UpperCAmelCase    =				0
												with open(lowercase_     ,						'w'     ,						encoding='utf-8'      ) as writer:
																		writer.write('#version: 0.2\n'      )
																		for bpe_tokens, token_index in sorted(self.bpe_ranks.items()     ,						key=lambda lowercase_      : kv[1]      ):
																								if index != token_index:
																														logger.warning(
																														    f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
																														    ' Please check that the tokenizer is not corrupted!'      )
																														UpperCAmelCase    =				token_index
																								writer.write(' '.join(lowercase_      ) + '\n'      )
																								index += 1

												return vocab_file, merge_file





