






import argparse
import os
import pickle
import sys

import torch

from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
A        =			data_utils.TransfoXLTokenizer
A        =			data_utils.TransfoXLCorpus
A        =			data_utils
A        =			data_utils



def 					_lowerCamelCase(			lowerCAmelCase__				:		Union[str, Any]    ,    lowerCAmelCase__				:		List[Any]    ,    lowerCAmelCase__				:		Dict    ,    lowerCAmelCase__				:		Dict      ):





				'''simple docstring'''







				if transfo_xl_dataset_file:
								# Convert a pre-processed corpus (see original TensorFlow repo)
								with open(_SCREAMING_SNAKE_CASE    ,    'rb'      ) as fp:
												SCREAMING_SNAKE_CASE_   :	Optional[int]													=   pickle.load(_SCREAMING_SNAKE_CASE    ,    encoding='latin1'      )
								# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
								SCREAMING_SNAKE_CASE_   :	Tuple													=   pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file']
								print(F'''Save vocabulary to {pytorch_vocab_dump_path}'''      )
								SCREAMING_SNAKE_CASE_   :	int													=   corpus.vocab.__dict__
								torch.save(_SCREAMING_SNAKE_CASE    ,    _SCREAMING_SNAKE_CASE      )

								SCREAMING_SNAKE_CASE_   :	Any													=   corpus.__dict__
								corpus_dict_no_vocab.pop('vocab'    ,    _SCREAMING_SNAKE_CASE      )
								SCREAMING_SNAKE_CASE_   :	List[str]													=   pytorch_dump_folder_path + '/' + CORPUS_NAME
								print(F'''Save dataset to {pytorch_dataset_dump_path}'''      )
								torch.save(_SCREAMING_SNAKE_CASE    ,    _SCREAMING_SNAKE_CASE      )

				if tf_checkpoint_path:
								# Convert a pre-trained TensorFlow model
								SCREAMING_SNAKE_CASE_   :	str													=   os.path.abspath(_SCREAMING_SNAKE_CASE      )
								SCREAMING_SNAKE_CASE_   :	List[str]													=   os.path.abspath(_SCREAMING_SNAKE_CASE      )

								print(F'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.'''      )
								# Initialise PyTorch model
								if transfo_xl_config_file == "":
												SCREAMING_SNAKE_CASE_   :	Optional[int]													=   TransfoXLConfig()
								else:
												SCREAMING_SNAKE_CASE_   :	List[Any]													=   TransfoXLConfig.from_json_file(_SCREAMING_SNAKE_CASE      )
								print(F'''Building PyTorch model from configuration: {config}'''      )
								SCREAMING_SNAKE_CASE_   :	List[Any]													=   TransfoXLLMHeadModel(_SCREAMING_SNAKE_CASE      )

								SCREAMING_SNAKE_CASE_   :	Optional[int]													=   load_tf_weights_in_transfo_xl(_SCREAMING_SNAKE_CASE    ,    _SCREAMING_SNAKE_CASE    ,    _SCREAMING_SNAKE_CASE      )
								# Save pytorch-model
								SCREAMING_SNAKE_CASE_   :	List[str]													=   os.path.join(_SCREAMING_SNAKE_CASE    ,    _SCREAMING_SNAKE_CASE      )
								SCREAMING_SNAKE_CASE_   :	int													=   os.path.join(_SCREAMING_SNAKE_CASE    ,    _SCREAMING_SNAKE_CASE      )
								print(F'''Save PyTorch model to {os.path.abspath(_SCREAMING_SNAKE_CASE      )}'''      )
								torch.save(model.state_dict()    ,    _SCREAMING_SNAKE_CASE      )
								print(F'''Save configuration file to {os.path.abspath(_SCREAMING_SNAKE_CASE      )}'''      )
								with open(_SCREAMING_SNAKE_CASE    ,    'w'    ,    encoding='utf-8'      ) as f:
												f.write(config.to_json_string()      )


if __name__ == "__main__":
				A        =			argparse.ArgumentParser()
				parser.add_argument(
				    '--pytorch_dump_folder_path',
				    default=None,
				    type=str,
				    required=True,
				    help='Path to the folder to store the PyTorch model or dataset/vocab.',
				)
				parser.add_argument(
				    '--tf_checkpoint_path',
				    default='',
				    type=str,
				    help='An optional path to a TensorFlow checkpoint path to be converted.',
				)
				parser.add_argument(
				    '--transfo_xl_config_file',
				    default='',
				    type=str,
				    help=(
				        'An optional config json file corresponding to the pre-trained BERT model. \n'
				        'This specifies the model architecture.'
				    ),
				)
				parser.add_argument(
				    '--transfo_xl_dataset_file',
				    default='',
				    type=str,
				    help='An optional dataset file to be converted in a vocabulary.',
				)
				A        =			parser.parse_args()
				convert_transfo_xl_checkpoint_to_pytorch(
				    args.tf_checkpoint_path,
				    args.transfo_xl_config_file,
				    args.pytorch_dump_folder_path,
				    args.transfo_xl_dataset_file,
				)







import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


A        =			logging.get_logger(__name__)

A        =			{'vocab_file': 'spm_char.model'}

A        =			{
    'vocab_file': {
        'microsoft/speecht5_asr': 'https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model',
        'microsoft/speecht5_tts': 'https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model',
        'microsoft/speecht5_vc': 'https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model',
    }
}

A        =			{
    'microsoft/speecht5_asr': 1024,
    'microsoft/speecht5_tts': 1024,
    'microsoft/speecht5_vc': 1024,
}


class 							__a							(  __A						):





		'''simple docstring'''



		UpperCAmelCase__      :				str				    =						VOCAB_FILES_NAMES
		UpperCAmelCase__      :				List[str]				    =						PRETRAINED_VOCAB_FILES_MAP
		UpperCAmelCase__      :				Optional[int]				    =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		UpperCAmelCase__      :				Dict				    =						["""input_ids""", """attention_mask"""]


		def __init__(						self ,    UpperCamelCase__ ,    UpperCamelCase__="<s>" ,    UpperCamelCase__="</s>" ,    UpperCamelCase__="<unk>" ,    UpperCamelCase__="<pad>" ,    UpperCamelCase__ = None ,    **UpperCamelCase__ ,    ):
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   {} if sp_model_kwargs is None else sp_model_kwargs

						super().__init__(
						    bos_token=UpperCamelCase__ ,    eos_token=UpperCamelCase__ ,    unk_token=UpperCamelCase__ ,    pad_token=UpperCamelCase__ ,    sp_model_kwargs=self.sp_model_kwargs ,    **UpperCamelCase__ ,    )

						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   vocab_file

						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   spm.SentencePieceProcessor(**self.sp_model_kwargs       )
						self.sp_model.Load(UpperCamelCase__       )


		@property
		def   __snake_case			(						self       ):
						return self.sp_model.get_piece_size()


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	List[str]													=   {self.convert_ids_to_tokens(UpperCamelCase__       ): i for i in range(self.vocab_size       )}
						vocab.update(self.added_tokens_encoder       )
						return vocab


		def __getstate__(						self       ):
						SCREAMING_SNAKE_CASE_   :	str													=   self.__dict__.copy()
						SCREAMING_SNAKE_CASE_   :	List[str]													=   None
						return state


		def __setstate__(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   d

						# for backward compatibility
						if not hasattr(self ,    'sp_model_kwargs'       ):
										SCREAMING_SNAKE_CASE_   :	Any													=   {}

						SCREAMING_SNAKE_CASE_   :	List[Any]													=   spm.SentencePieceProcessor(**self.sp_model_kwargs       )
						self.sp_model.Load(self.vocab_file       )


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						return self.sp_model.encode(UpperCamelCase__ ,    out_type=UpperCamelCase__       )


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						return self.sp_model.piece_to_id(UpperCamelCase__       )


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   self.sp_model.IdToPiece(UpperCamelCase__       )
						return token


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	int													=   []
						SCREAMING_SNAKE_CASE_   :	int													=   ''
						for token in tokens:
										# make sure that special tokens are not decoded using sentencepiece model
										if token in self.all_special_tokens:
														out_string += self.sp_model.decode(UpperCamelCase__       ) + token
														SCREAMING_SNAKE_CASE_   :	Any													=   []
										else:
														current_sub_tokens.append(UpperCamelCase__       )
						out_string += self.sp_model.decode(UpperCamelCase__       )
						return out_string.strip()


		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__=None       ):
						if token_ids_a is None:
										return token_ids_a + [self.eos_token_id]
						# We don't expect to process pairs, but leave the pair logic for API consistency
						return token_ids_a + token_ids_a + [self.eos_token_id]


		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__ = None ,    UpperCamelCase__ = False       ):
						if already_has_special_tokens:
										return super().get_special_tokens_mask(
										    token_ids_a=UpperCamelCase__ ,    token_ids_a=UpperCamelCase__ ,    already_has_special_tokens=UpperCamelCase__       )

						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   [1]
						if token_ids_a is None:
										return ([0] * len(UpperCamelCase__       )) + suffix_ones
						return ([0] * len(UpperCamelCase__       )) + ([0] * len(UpperCamelCase__       )) + suffix_ones






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

						if os.path.abspath(self.vocab_file       ) != os.path.abspath(UpperCamelCase__       ) and os.path.isfile(self.vocab_file       ):
										copyfile(self.vocab_file ,    UpperCamelCase__       )
						elif not os.path.isfile(self.vocab_file       ):
										with open(UpperCamelCase__ ,    'wb'       ) as fi:
														SCREAMING_SNAKE_CASE_   :	Tuple													=   self.sp_model.serialized_model_proto()
														fi.write(UpperCamelCase__       )

						return (out_vocab_file,)