'''simple docstring'''





import argparse
import json

import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download

from transformers import (
    VideoMAEConfig,
    VideoMAEForPreTraining,
    VideoMAEForVideoClassification,
    VideoMAEImageProcessor,
)
def 						__A							(     UpperCAmelCase					)     ->			Union[str, Any]:




						'''simple docstring'''
						_UpperCamelCase			:			List[str]   			=						VideoMAEConfig()

						set_architecture_configs(UpperCAmelCase     ,UpperCAmelCase					)

						if "finetuned" not in model_name:
												_UpperCamelCase			:			Optional[Any]   			=						False

						if "finetuned" in model_name:
												_UpperCamelCase			:			Any   			=						"huggingface/label-files"
												if "kinetics" in model_name:
																		_UpperCamelCase			:			List[str]   			=						4_0_0
																		_UpperCamelCase			:			Union[str, Any]   			=						"kinetics400-id2label.json"
												elif "ssv2" in model_name:
																		_UpperCamelCase			:			Optional[int]   			=						1_7_4
																		_UpperCamelCase			:			Optional[int]   			=						"something-something-v2-id2label.json"
												else:
																		raise ValueError("Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned."					)
												_UpperCamelCase			:			Optional[Any]   			=						json.load(open(hf_hub_download(UpperCAmelCase     ,UpperCAmelCase     ,repo_type="dataset"					)     ,"r"					)					)
												_UpperCamelCase			:			Optional[int]   			=						{int(UpperCAmelCase					): v for k, v in idalabel.items()}
												_UpperCamelCase			:			Any   			=						idalabel
												_UpperCamelCase			:			int   			=						{v: k for k, v in idalabel.items()}

						return config
def 						__A							(     UpperCAmelCase     ,UpperCAmelCase					)     ->			Optional[int]:




						'''simple docstring'''
						if "small" in model_name:
												_UpperCamelCase			:			List[Any]   			=						3_8_4
												_UpperCamelCase			:			List[str]   			=						1_5_3_6
												_UpperCamelCase			:			Dict   			=						1_2
												_UpperCamelCase			:			Optional[int]   			=						1_6
												_UpperCamelCase			:			Optional[Any]   			=						1_2
												_UpperCamelCase			:			Dict   			=						3
												_UpperCamelCase			:			Dict   			=						1_9_2
												_UpperCamelCase			:			Optional[int]   			=						7_6_8
						elif "large" in model_name:
												_UpperCamelCase			:			str   			=						1_0_2_4
												_UpperCamelCase			:			Dict   			=						4_0_9_6
												_UpperCamelCase			:			Optional[int]   			=						2_4
												_UpperCamelCase			:			int   			=						1_6
												_UpperCamelCase			:			List[Any]   			=						1_2
												_UpperCamelCase			:			Union[str, Any]   			=						8
												_UpperCamelCase			:			Dict   			=						5_1_2
												_UpperCamelCase			:			Dict   			=						2_0_4_8
						elif "huge" in model_name:
												_UpperCamelCase			:			int   			=						1_2_8_0
												_UpperCamelCase			:			int   			=						5_1_2_0
												_UpperCamelCase			:			List[Any]   			=						3_2
												_UpperCamelCase			:			Tuple   			=						1_6
												_UpperCamelCase			:			Tuple   			=						1_2
												_UpperCamelCase			:			Optional[int]   			=						8
												_UpperCamelCase			:			str   			=						6_4_0
												_UpperCamelCase			:			List[str]   			=						2_5_6_0
						elif "base" not in model_name:
												raise ValueError("Model name should include either \"small\", \"base\", \"large\", or \"huge\""					)
def 						__A							(     UpperCAmelCase					)     ->			Tuple:




						'''simple docstring'''
						if "encoder." in name:
												_UpperCamelCase			:			int   			=						name.replace("encoder."     ,""					)
						if "cls_token" in name:
												_UpperCamelCase			:			Dict   			=						name.replace("cls_token"     ,"videomae.embeddings.cls_token"					)
						if "decoder_pos_embed" in name:
												_UpperCamelCase			:			Optional[Any]   			=						name.replace("decoder_pos_embed"     ,"decoder.decoder_pos_embed"					)
						if "pos_embed" in name and "decoder" not in name:
												_UpperCamelCase			:			List[Any]   			=						name.replace("pos_embed"     ,"videomae.embeddings.position_embeddings"					)
						if "patch_embed.proj" in name:
												_UpperCamelCase			:			List[Any]   			=						name.replace("patch_embed.proj"     ,"videomae.embeddings.patch_embeddings.projection"					)
						if "patch_embed.norm" in name:
												_UpperCamelCase			:			List[Any]   			=						name.replace("patch_embed.norm"     ,"videomae.embeddings.norm"					)
						if "decoder.blocks" in name:
												_UpperCamelCase			:			List[Any]   			=						name.replace("decoder.blocks"     ,"decoder.decoder_layers"					)
						if "blocks" in name:
												_UpperCamelCase			:			List[str]   			=						name.replace("blocks"     ,"videomae.encoder.layer"					)
						if "attn.proj" in name:
												_UpperCamelCase			:			Optional[int]   			=						name.replace("attn.proj"     ,"attention.output.dense"					)
						if "attn" in name and "bias" not in name:
												_UpperCamelCase			:			List[Any]   			=						name.replace("attn"     ,"attention.self"					)
						if "attn" in name:
												_UpperCamelCase			:			str   			=						name.replace("attn"     ,"attention.attention"					)
						if "norm1" in name:
												_UpperCamelCase			:			Tuple   			=						name.replace("norm1"     ,"layernorm_before"					)
						if "norm2" in name:
												_UpperCamelCase			:			Tuple   			=						name.replace("norm2"     ,"layernorm_after"					)
						if "mlp.fc1" in name:
												_UpperCamelCase			:			Optional[Any]   			=						name.replace("mlp.fc1"     ,"intermediate.dense"					)
						if "mlp.fc2" in name:
												_UpperCamelCase			:			List[Any]   			=						name.replace("mlp.fc2"     ,"output.dense"					)
						if "decoder_embed" in name:
												_UpperCamelCase			:			Dict   			=						name.replace("decoder_embed"     ,"decoder.decoder_embed"					)
						if "decoder_norm" in name:
												_UpperCamelCase			:			List[Any]   			=						name.replace("decoder_norm"     ,"decoder.decoder_norm"					)
						if "decoder_pred" in name:
												_UpperCamelCase			:			Tuple   			=						name.replace("decoder_pred"     ,"decoder.decoder_pred"					)
						if "norm.weight" in name and "decoder" not in name and "fc" not in name:
												_UpperCamelCase			:			Dict   			=						name.replace("norm.weight"     ,"videomae.layernorm.weight"					)
						if "norm.bias" in name and "decoder" not in name and "fc" not in name:
												_UpperCamelCase			:			Optional[int]   			=						name.replace("norm.bias"     ,"videomae.layernorm.bias"					)
						if "head" in name and "decoder" not in name:
												_UpperCamelCase			:			Dict   			=						name.replace("head"     ,"classifier"					)

						return name
def 						__A							(     UpperCAmelCase     ,UpperCAmelCase					)     ->			Dict:




						'''simple docstring'''
						for key in orig_state_dict.copy().keys():
												_UpperCamelCase			:			List[Any]   			=						orig_state_dict.pop(UpperCAmelCase					)

												if key.startswith("encoder."					):
																		_UpperCamelCase			:			str   			=						key.replace("encoder."     ,""					)

												if "qkv" in key:
																		_UpperCamelCase			:			Tuple   			=						key.split("."					)
																		if key.startswith("decoder.blocks"					):
																								_UpperCamelCase			:			int   			=						config.decoder_hidden_size
																								_UpperCamelCase			:			Any   			=						int(key_split[2]					)
																								_UpperCamelCase			:			Optional[int]   			=						"decoder.decoder_layers."
																								if "weight" in key:
																														_UpperCamelCase			:			Dict   			=						val[:dim, :]
																														_UpperCamelCase			:			Union[str, Any]   			=						val[dim : dim * 2, :]
																														_UpperCamelCase			:			str   			=						val[-dim:, :]
																		else:
																								_UpperCamelCase			:			Union[str, Any]   			=						config.hidden_size
																								_UpperCamelCase			:			Dict   			=						int(key_split[1]					)
																								_UpperCamelCase			:			List[str]   			=						"videomae.encoder.layer."
																								if "weight" in key:
																														_UpperCamelCase			:			List[Any]   			=						val[:dim, :]
																														_UpperCamelCase			:			Any   			=						val[dim : dim * 2, :]
																														_UpperCamelCase			:			List[Any]   			=						val[-dim:, :]
												else:
																		_UpperCamelCase			:			str   			=						val

						return orig_state_dict
def 						__A							(     )     ->			List[str]:




						'''simple docstring'''
						_UpperCamelCase			:			int   			=						hf_hub_download(
						    repo_id="hf-internal-testing/spaghetti-video"     ,filename="eating_spaghetti.npy"     ,repo_type="dataset"					)
						_UpperCamelCase			:			Tuple   			=						np.load(UpperCAmelCase					)
						return list(UpperCAmelCase					)
def 						__A							(     UpperCAmelCase     ,UpperCAmelCase     ,UpperCAmelCase     ,UpperCAmelCase					)     ->			int:




						'''simple docstring'''
						_UpperCamelCase			:			Optional[Any]   			=						get_videomae_config(UpperCAmelCase					)

						if "finetuned" in model_name:
												_UpperCamelCase			:			str   			=						VideoMAEForVideoClassification(UpperCAmelCase					)
						else:
												_UpperCamelCase			:			Any   			=						VideoMAEForPreTraining(UpperCAmelCase					)

						# download original checkpoint, hosted on Google Drive
						_UpperCamelCase			:			List[str]   			=						"pytorch_model.bin"
						gdown.cached_download(UpperCAmelCase     ,UpperCAmelCase     ,quiet=UpperCAmelCase					)
						_UpperCamelCase			:			str   			=						torch.load(UpperCAmelCase     ,map_location="cpu"					)
						if "model" in files:
												_UpperCamelCase			:			int   			=						files["model"]
						else:
												_UpperCamelCase			:			Dict   			=						files["module"]
						_UpperCamelCase			:			List[str]   			=						convert_state_dict(UpperCAmelCase     ,UpperCAmelCase					)

						model.load_state_dict(UpperCAmelCase					)
						model.eval()

						# verify model on basic input
						_UpperCamelCase			:			List[str]   			=						VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]     ,image_std=[0.5, 0.5, 0.5]					)
						_UpperCamelCase			:			List[str]   			=						prepare_video()
						_UpperCamelCase			:			Dict   			=						image_processor(UpperCAmelCase     ,return_tensors="pt"					)

						if "finetuned" not in model_name:
												_UpperCamelCase			:			List[Any]   			=						hf_hub_download(repo_id="hf-internal-testing/bool-masked-pos"     ,filename="bool_masked_pos.pt"					)
												_UpperCamelCase			:			Dict   			=						torch.load(UpperCAmelCase					)

						_UpperCamelCase			:			Optional[int]   			=						model(**UpperCAmelCase					)
						_UpperCamelCase			:			List[Any]   			=						outputs.logits

						_UpperCamelCase			:			Tuple   			=						[
						    "videomae-small-finetuned-kinetics",
						    "videomae-small-finetuned-ssv2",
						    # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600)
						    "videomae-base-short",
						    "videomae-base-short-finetuned-kinetics",
						    "videomae-base",
						    "videomae-base-finetuned-kinetics",
						    "videomae-large",
						    "videomae-large-finetuned-kinetics",
						    "videomae-huge-finetuned-kinetics",
						    # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400)
						    "videomae-base-short-ssv2",
						    "videomae-base-short-finetuned-ssv2",
						    "videomae-base-ssv2",
						    "videomae-base-finetuned-ssv2",
						]

						# NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5]
						if model_name == "videomae-small-finetuned-kinetics":
												_UpperCamelCase			:			List[str]   			=						torch.Size([1, 4_0_0]					)
												_UpperCamelCase			:			List[str]   			=						torch.tensor([-0.92_91, -0.40_61, -0.93_07]					)
						elif model_name == "videomae-small-finetuned-ssv2":
												_UpperCamelCase			:			Dict   			=						torch.Size([1, 1_7_4]					)
												_UpperCamelCase			:			Optional[Any]   			=						torch.tensor([0.26_71, -0.46_89, -0.82_35]					)
						elif model_name == "videomae-base":
												_UpperCamelCase			:			List[str]   			=						torch.Size([1, 1_4_0_8, 1_5_3_6]					)
												_UpperCamelCase			:			Optional[Any]   			=						torch.tensor([[0.77_39, 0.79_68, 0.70_89], [0.67_01, 0.74_87, 0.62_09], [0.42_87, 0.51_58, 0.47_73]]					)
						elif model_name == "videomae-base-short":
												_UpperCamelCase			:			str   			=						torch.Size([1, 1_4_0_8, 1_5_3_6]					)
												_UpperCamelCase			:			List[str]   			=						torch.tensor([[0.79_94, 0.96_12, 0.85_08], [0.74_01, 0.89_58, 0.83_02], [0.58_62, 0.74_68, 0.73_25]]					)
												# we verified the loss both for normalized and unnormalized targets for this one
												_UpperCamelCase			:			Dict   			=						torch.tensor([0.51_42]					) if config.norm_pix_loss else torch.tensor([0.64_69]					)
						elif model_name == "videomae-large":
												_UpperCamelCase			:			int   			=						torch.Size([1, 1_4_0_8, 1_5_3_6]					)
												_UpperCamelCase			:			int   			=						torch.tensor([[0.71_49, 0.79_97, 0.69_66], [0.67_68, 0.78_69, 0.69_48], [0.51_39, 0.62_21, 0.56_05]]					)
						elif model_name == "videomae-large-finetuned-kinetics":
												_UpperCamelCase			:			Any   			=						torch.Size([1, 4_0_0]					)
												_UpperCamelCase			:			int   			=						torch.tensor([0.07_71, 0.00_11, -0.36_25]					)
						elif model_name == "videomae-huge-finetuned-kinetics":
												_UpperCamelCase			:			Union[str, Any]   			=						torch.Size([1, 4_0_0]					)
												_UpperCamelCase			:			Dict   			=						torch.tensor([0.24_33, 0.16_32, -0.48_94]					)
						elif model_name == "videomae-base-short-finetuned-kinetics":
												_UpperCamelCase			:			List[str]   			=						torch.Size([1, 4_0_0]					)
												_UpperCamelCase			:			Optional[Any]   			=						torch.tensor([0.65_88, 0.09_90, -0.24_93]					)
						elif model_name == "videomae-base-finetuned-kinetics":
												_UpperCamelCase			:			List[Any]   			=						torch.Size([1, 4_0_0]					)
												_UpperCamelCase			:			int   			=						torch.tensor([0.36_69, -0.06_88, -0.24_21]					)
						elif model_name == "videomae-base-short-ssv2":
												_UpperCamelCase			:			int   			=						torch.Size([1, 1_4_0_8, 1_5_3_6]					)
												_UpperCamelCase			:			int   			=						torch.tensor([[0.47_12, 0.52_96, 0.57_86], [0.22_78, 0.27_29, 0.40_26], [0.03_52, 0.07_30, 0.25_06]]					)
						elif model_name == "videomae-base-short-finetuned-ssv2":
												_UpperCamelCase			:			List[Any]   			=						torch.Size([1, 1_7_4]					)
												_UpperCamelCase			:			int   			=						torch.tensor([-0.05_37, -0.15_39, -0.32_66]					)
						elif model_name == "videomae-base-ssv2":
												_UpperCamelCase			:			int   			=						torch.Size([1, 1_4_0_8, 1_5_3_6]					)
												_UpperCamelCase			:			Dict   			=						torch.tensor([[0.81_31, 0.87_27, 0.85_46], [0.73_66, 0.93_77, 0.88_70], [0.59_35, 0.88_74, 0.85_64]]					)
						elif model_name == "videomae-base-finetuned-ssv2":
												_UpperCamelCase			:			str   			=						torch.Size([1, 1_7_4]					)
												_UpperCamelCase			:			Any   			=						torch.tensor([0.19_61, -0.83_37, -0.63_89]					)
						else:
												raise ValueError(f'''Model name not supported. Should be one of {model_names}'''					)

						# verify logits
						assert logits.shape == expected_shape
						if "finetuned" in model_name:
												assert torch.allclose(logits[0, :3]     ,UpperCAmelCase     ,atol=1E-4					)
						else:
												print("Logits:"     ,logits[0, :3, :3]					)
												assert torch.allclose(logits[0, :3, :3]     ,UpperCAmelCase     ,atol=1E-4					)
						print("Logits ok!"					)

						# verify loss, if applicable
						if model_name == "videomae-base-short":
												_UpperCamelCase			:			Optional[int]   			=						outputs.loss
												assert torch.allclose(UpperCAmelCase     ,UpperCAmelCase     ,atol=1E-4					)
												print("Loss ok!"					)

						if pytorch_dump_folder_path is not None:
												print(f'''Saving model and image processor to {pytorch_dump_folder_path}'''					)
												image_processor.save_pretrained(UpperCAmelCase					)
												model.save_pretrained(UpperCAmelCase					)

						if push_to_hub:
												print("Pushing to the hub..."					)
												model.push_to_hub(UpperCAmelCase     ,organization="nielsr"					)


if __name__ == "__main__":
			lowerCAmelCase_	:		Any			=     argparse.ArgumentParser()
			# Required parameters
			parser.add_argument(
			    """--checkpoint_url""",
			    default="""https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4""",
			    type=str,
			    help=(
			        """URL of the original PyTorch checkpoint (on Google Drive) you'd like to convert. Should be a direct"""
			        """ download link."""
			    ),
			)
			parser.add_argument(
			    """--pytorch_dump_folder_path""",
			    default="""/Users/nielsrogge/Documents/VideoMAE/Test""",
			    type=str,
			    help="""Path to the output PyTorch model directory.""",
			)
			parser.add_argument("""--model_name""", default="""videomae-base""", type=str, help="""Name of the model.""")
			parser.add_argument(
			    """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
			)

			lowerCAmelCase_	:		List[str]			=     parser.parse_args()
			convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)



'''simple docstring'''





import collections
import os
from typing import List, Optional, Tuple

from transformers.utils import is_jieba_available, requires_backends


if is_jieba_available():
			import jieba

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


lowerCAmelCase_	:		int			=     logging.get_logger(__name__)

lowerCAmelCase_	:		List[str]			=     {"""vocab_file""": """vocab.txt"""}

lowerCAmelCase_	:		Optional[Any]			=     {
    """vocab_file""": {
        """openbmb/cpm-ant-10b""": """https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt""",
    },
}

lowerCAmelCase_	:		int			=     {
    """openbmb/cpm-ant-10b""": 1024,
}
def 						__A							(     UpperCAmelCase					)     ->			List[str]:




						'''simple docstring'''
						_UpperCamelCase			:			Optional[int]   			=						collections.OrderedDict()
						with open(UpperCAmelCase     ,"r"     ,encoding="utf-8"					) as reader:
												_UpperCamelCase			:			int   			=						reader.readlines()
						for index, token in enumerate(UpperCAmelCase					):
												_UpperCamelCase			:			Optional[int]   			=						token.rstrip("\n"					)
												_UpperCamelCase			:			List[str]   			=						index
						return vocab




class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def __init__(						self					:						Dict       ,		lowercase__					:						List[str]       ,		lowercase__					:						Any="<unk>"       ,		lowercase__					:						str=200					)							->Optional[int]:


										'''simple docstring'''




										_UpperCamelCase			:			Any   			=						vocab
										_UpperCamelCase			:			str   			=						unk_token
										_UpperCamelCase			:			List[Any]   			=						max_input_chars_per_word







				def  snake_case__				(						self					:						Union[str, Any]       ,		lowercase__					:						Any					)							->Dict:


										'''simple docstring'''




										_UpperCamelCase			:			int   			=						list(lowercase__					)
										if len(lowercase__					) > self.max_input_chars_per_word:
																return [self.unk_token]

										_UpperCamelCase			:			int   			=						0
										_UpperCamelCase			:			List[str]   			=						[]
										while start < len(lowercase__					):
																_UpperCamelCase			:			Union[str, Any]   			=						len(lowercase__					)
																_UpperCamelCase			:			Union[str, Any]   			=						None
																while start < end:
																						_UpperCamelCase			:			Dict   			=						"".join(chars[start:end]					)
																						if substr in self.vocab:
																												_UpperCamelCase			:			int   			=						substr
																												break
																						end -= 1
																if cur_substr is None:
																						sub_tokens.append(self.unk_token					)
																						start += 1
																else:
																						sub_tokens.append(lowercase__					)
																						_UpperCamelCase			:			List[str]   			=						end

										return sub_tokens





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''
				UpperCAmelCase__							=							VOCAB_FILES_NAMES
				UpperCAmelCase__							=							PRETRAINED_VOCAB_FILES_MAP
				UpperCAmelCase__							=							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				UpperCAmelCase__							=							['''input_ids''', '''attention_mask''']
				UpperCAmelCase__							=							False





				def __init__(						self					:						int       ,		lowercase__					:						str       ,		lowercase__					:						int="<d>"       ,		lowercase__					:						Tuple="</d>"       ,		lowercase__					:						Optional[int]="<s>"       ,		lowercase__					:						Optional[int]="</s>"       ,		lowercase__					:						List[str]="<pad>"       ,		lowercase__					:						Optional[int]="<unk>"       ,		lowercase__					:						int="</n>"       ,		lowercase__					:						Optional[Any]="</_>"       ,		lowercase__					:						int="left"       ,		**lowercase__					:						List[str]       ,		)							->Union[str, Any]:


										'''simple docstring'''




										requires_backends(self       ,		["jieba"]					)
										super().__init__(
										    bod_token=lowercase__       ,		eod_token=lowercase__       ,		bos_token=lowercase__       ,		eos_token=lowercase__       ,		pad_token=lowercase__       ,		unk_token=lowercase__       ,		line_token=lowercase__       ,		space_token=lowercase__       ,		padding_side=lowercase__       ,		**lowercase__       ,		)
										_UpperCamelCase			:			Union[str, Any]   			=						bod_token
										_UpperCamelCase			:			Union[str, Any]   			=						eod_token
										_UpperCamelCase			:			int   			=						load_vocab(lowercase__					)
										_UpperCamelCase			:			Any   			=						self.encoder[space_token]
										_UpperCamelCase			:			List[str]   			=						self.encoder[line_token]

										del self.encoder[space_token]
										del self.encoder[line_token]

										_UpperCamelCase			:			Dict   			=						collections.OrderedDict(sorted(self.encoder.items()       ,		key=lambda lowercase__					: x[1]					)					)
										_UpperCamelCase			:			Any   			=						{v: k for k, v in self.encoder.items()}

										_UpperCamelCase			:			Any   			=						WordpieceTokenizer(vocab=self.encoder       ,		unk_token=self.unk_token					)





				@property
				def  snake_case__				(						self					:						Tuple					)							->List[str]:


										'''simple docstring'''




										return self.encoder[self.bod_token]





				@property
				def  snake_case__				(						self					:						Tuple					)							->List[Any]:


										'''simple docstring'''




										return self.encoder[self.eod_token]





				@property
				def  snake_case__				(						self					:						List[str]					)							->int:


										'''simple docstring'''




										return self.encoder["\n"]





				@property
				def  snake_case__				(						self					:						List[str]					)							->int:


										'''simple docstring'''




										return len(self.encoder					)





				def  snake_case__				(						self					:						Dict					)							->Tuple:


										'''simple docstring'''




										return dict(self.encoder       ,		**self.added_tokens_encoder					)





				def  snake_case__				(						self					:						Optional[int]       ,		lowercase__					:						Tuple					)							->Tuple:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						[]
										for x in jieba.cut(lowercase__       ,		cut_all=lowercase__					):
																output_tokens.extend(self.wordpiece_tokenizer.tokenize(lowercase__					)					)
										return output_tokens





				def  snake_case__				(						self					:						Optional[Any]       ,		lowercase__					:						Any       ,		**lowercase__					:						Tuple					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			Optional[int]   			=						[i for i in token_ids if i >= 0]
										_UpperCamelCase			:			Union[str, Any]   			=						[
										    x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
										]
										return super()._decode(lowercase__       ,		**lowercase__					)





				def  snake_case__				(						self					:						Optional[Any]       ,		lowercase__					:						Tuple					)							->Union[str, Any]:


										'''simple docstring'''




										return token in self.encoder





				def  snake_case__				(						self					:						str       ,		lowercase__					:						List[str]					)							->str:


										'''simple docstring'''




										return "".join(lowercase__					)





				def  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						Optional[Any]					)							->int:


										'''simple docstring'''




										return self.encoder.get(lowercase__       ,		self.encoder.get(self.unk_token					)					)





				def  snake_case__				(						self					:						Any       ,		lowercase__					:						Dict					)							->Dict:


										'''simple docstring'''




										return self.decoder.get(lowercase__       ,		self.unk_token					)





				def  snake_case__				(						self					:						Tuple       ,		lowercase__					:						str       ,		lowercase__					:						Optional[str] = None					)							->Tuple[str]:


										'''simple docstring'''




										if os.path.isdir(lowercase__					):
																_UpperCamelCase			:			Tuple   			=						os.path.join(
																    lowercase__       ,		(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]					)
										else:
																_UpperCamelCase			:			Optional[int]   			=						(filename_prefix + "-" if filename_prefix else "") + save_directory
										_UpperCamelCase			:			List[str]   			=						0
										if " " in self.encoder:
																_UpperCamelCase			:			Dict   			=						self.encoder[" "]
																del self.encoder[" "]
										if "\n" in self.encoder:
																_UpperCamelCase			:			int   			=						self.encoder["\n"]
																del self.encoder["\n"]
										_UpperCamelCase			:			List[str]   			=						collections.OrderedDict(sorted(self.encoder.items()       ,		key=lambda lowercase__					: x[1]					)					)
										with open(lowercase__       ,		"w"       ,		encoding="utf-8"					) as writer:
																for token, token_index in self.encoder.items():
																						if index != token_index:
																												logger.warning(
																												    f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
																												    " Please check that the vocabulary is not corrupted!"					)
																												_UpperCamelCase			:			str   			=						token_index
																						writer.write(token + "\n"					)
																						index += 1
										return (vocab_file,)





				def  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						List[int]       ,		lowercase__					:						List[int] = None					)							->List[int]:


										'''simple docstring'''




										if token_ids_a is None:
																return [self.bos_token_id] + token_ids_a
										return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a







				def  snake_case__				(						self					:						Optional[int]       ,		lowercase__					:						List[int]       ,		lowercase__					:						Optional[List[int]] = None       ,		lowercase__					:						bool = False					)							->List[int]:


										'''simple docstring'''




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

										if token_ids_a is not None:
																return [1] + ([0] * len(lowercase__					)) + [1] + ([0] * len(lowercase__					))
										return [1] + ([0] * len(lowercase__					))


