






"""simple docstring"""


import argparse
import collections

import jax
import jax.numpy as jnp
import torch
import torch.nn as nn
from clip.model import CLIP
from flax.training import checkpoints
from huggingface_hub import Repository

from transformers import (
    CLIPTokenizer,
    OwlViTConfig,
    OwlViTForObjectDetection,
    OwlViTImageProcessor,
    OwlViTModel,
    OwlViTProcessor,
)


__SCREAMING_SNAKE_CASE      =      {
    'vit_b32': {
        'embed_dim': 5_12,
        'image_resolution': 7_68,
        'context_length': 16,
        'vocab_size': 4_94_08,
        'vision_layers': 12,
        'vision_width': 7_68,
        'vision_patch_size': 32,
        'transformer_width': 5_12,
        'transformer_heads': 8,
        'transformer_layers': 12,
    },
    'vit_b16': {
        'embed_dim': 5_12,
        'image_resolution': 7_68,
        'context_length': 16,
        'vocab_size': 4_94_08,
        'vision_layers': 12,
        'vision_width': 7_68,
        'vision_patch_size': 16,
        'transformer_width': 5_12,
        'transformer_heads': 8,
        'transformer_layers': 12,
    },
    'vit_l14': {
        'embed_dim': 7_68,
        'image_resolution': 8_40,
        'context_length': 16,
        'vocab_size': 4_94_08,
        'vision_layers': 24,
        'vision_width': 10_24,
        'vision_patch_size': 14,
        'transformer_width': 7_68,
        'transformer_heads': 12,
        'transformer_layers': 12,
    },
}


def 					UpperCAmelCase			(				a__    ,			a__=""    ,			a__="/"   ):





						'''simple docstring'''






						lowerCAmelCase      :Tuple				  = []

						for k, v in params.items():
												lowerCAmelCase      :Tuple				  = parent_key + sep + k if parent_key else k

												if isinstance(a__    ,			collections.MutableMapping   ):
																		items.extend(flatten_nested_dict(a__    ,			a__    ,			sep=a__   ).items()   )
												else:
																		items.append((new_key, v)   )
						return dict(a__   )


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






						return jax.tree_util.tree_map(lambda a__   : x.astype(jnp.floataa   ) if x.dtype == jnp.bfloataa else x    ,			a__   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :int				  = pt_attn_layer.in_proj_weight.chunk(3    ,			dim=0   )
						lowerCAmelCase      :Union[str, Any]				  = pt_attn_layer.in_proj_bias.chunk(3    ,			dim=0   )

						lowerCAmelCase      :int				  = pt_attn_layer.out_proj.weight
						lowerCAmelCase      :List[str]				  = pt_attn_layer.out_proj.bias

						lowerCAmelCase      :str				  = q_proj
						lowerCAmelCase      :Any				  = q_proj_bias

						lowerCAmelCase      :Tuple				  = k_proj
						lowerCAmelCase      :Any				  = k_proj_bias

						lowerCAmelCase      :Optional[int]				  = v_proj
						lowerCAmelCase      :Any				  = v_proj_bias

						lowerCAmelCase      :Optional[Any]				  = out_proj_weights
						lowerCAmelCase      :Optional[Any]				  = out_proj_bias


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						copy_linear(hf_mlp.fca    ,			pt_mlp.c_fc   )
						copy_linear(hf_mlp.fca    ,			pt_mlp.c_proj   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :List[Any]				  = pt_linear.weight
						lowerCAmelCase      :Any				  = pt_linear.bias


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						copy_linear(hf_layer.layer_norma    ,			pt_layer.ln_a   )
						copy_linear(hf_layer.layer_norma    ,			pt_layer.ln_a   )

						# copy MLP
						copy_mlp(hf_layer.mlp    ,			pt_layer.mlp   )

						# copy attn
						copy_attn_layer(hf_layer.self_attn    ,			pt_layer.attn   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						for hf_layer, pt_layer in zip(a__    ,			a__   ):
												copy_layer(a__    ,			a__   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Any				  = pt_model.token_embedding.weight
						lowerCAmelCase      :Any				  = pt_model.positional_embedding

						# copy layer norm
						copy_linear(hf_encoder.final_layer_norm    ,			pt_model.ln_final   )

						# copy hidden layers
						copy_layers(hf_encoder.encoder.layers    ,			pt_model.transformer.resblocks   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Tuple				  = pt_model.text_projection.data.T

						# copy text encoder
						copy_encoder(hf_model.text_model    ,			a__   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Optional[Any]				  = pt_model.visual.proj.data.T

						# copy layer norms
						copy_linear(hf_model.vision_model.pre_layernorm    ,			pt_model.visual.ln_pre   )
						copy_linear(hf_model.vision_model.post_layernorm    ,			pt_model.visual.ln_post   )

						# copy embeds
						lowerCAmelCase      :Optional[int]				  = pt_model.visual.conva.weight.data
						lowerCAmelCase      :Tuple				  = pt_model.visual.class_embedding
						lowerCAmelCase      :Union[str, Any]				  = pt_model.visual.positional_embedding.data

						# copy encoder
						copy_layers(hf_model.vision_model.encoder.layers    ,			pt_model.visual.transformer.resblocks   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :int				  = flatten_nested_dict(flax_params['backbone']['merged_class_token']   )

						lowerCAmelCase      :Tuple				  = torch.from_numpy(flax_class_token_params['scale']   )
						lowerCAmelCase      :Dict				  = torch.from_numpy(flax_class_token_params['bias']   )
						lowerCAmelCase      :Dict				  = nn.Parameter(a__   )
						lowerCAmelCase      :Tuple				  = nn.Parameter(a__   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :List[str]				  = hf_model.state_dict()
						lowerCAmelCase      :Union[str, Any]				  = {}

						# Rename class prediction head flax params to pytorch HF
						lowerCAmelCase      :Any				  = flatten_nested_dict(flax_params['class_head']   )

						for flax_key, v in flax_class_params.items():
												lowerCAmelCase      :Optional[Any]				  = flax_key.replace('/'    ,			'.'   )
												lowerCAmelCase      :Any				  = torch_key.replace('.kernel'    ,			'.weight'   )
												lowerCAmelCase      :List[Any]				  = torch_key.replace('Dense_0'    ,			'dense0'   )
												lowerCAmelCase      :Optional[Any]				  = 'class_head.' + torch_key

												if "weight" in torch_key and v.ndim == 2:
																		lowerCAmelCase      :Tuple				  = v.T

												lowerCAmelCase      :int				  = nn.Parameter(torch.from_numpy(a__   )   )

						# Rename box prediction box flax params to pytorch HF
						lowerCAmelCase      :str				  = flatten_nested_dict(flax_params['obj_box_head']   )

						for flax_key, v in flax_box_params.items():
												lowerCAmelCase      :List[str]				  = flax_key.replace('/'    ,			'.'   )
												lowerCAmelCase      :Optional[int]				  = torch_key.replace('.kernel'    ,			'.weight'   )
												lowerCAmelCase      :List[str]				  = torch_key.replace('_'    ,			''   ).lower()
												lowerCAmelCase      :Dict				  = 'box_head.' + torch_key

												if "weight" in torch_key and v.ndim == 2:
																		lowerCAmelCase      :Tuple				  = v.T

												lowerCAmelCase      :List[Any]				  = nn.Parameter(torch.from_numpy(a__   )   )

						# Copy flax params to PyTorch params
						for name, param in new_params.items():
												if name in pt_params.keys():
																		pt_params[name].copy_(a__   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						for k, v in flax_attn_params.items():
												if k.startswith('transformer'   ):
																		lowerCAmelCase      :Union[str, Any]				  = k.replace('transformer.resblocks'    ,			'text_model.encoder.layers'   )
												else:
																		lowerCAmelCase      :Any				  = k.replace('visual.transformer.resblocks'    ,			'vision_model.encoder.layers'   )

												lowerCAmelCase      :str				  = torch_key.replace('attn'    ,			'self_attn'   )
												lowerCAmelCase      :Optional[Any]				  = torch_key.replace('key'    ,			'k_proj'   )
												lowerCAmelCase      :int				  = torch_key.replace('value'    ,			'v_proj'   )
												lowerCAmelCase      :List[str]				  = torch_key.replace('query'    ,			'q_proj'   )
												lowerCAmelCase      :List[str]				  = torch_key.replace('out'    ,			'out_proj'   )

												if "bias" in torch_key and v.ndim == 2:
																		lowerCAmelCase      :List[Any]				  = v.shape[0] * v.shape[1]
																		lowerCAmelCase      :str				  = v.reshape(a__   )

												if "weight" in torch_key and "out" in torch_key:
																		lowerCAmelCase      :Tuple				  = (v.shape[0] * v.shape[1], v.shape[2])
																		lowerCAmelCase      :int				  = v.reshape(a__   ).T

												if "weight" in torch_key and "out" not in torch_key:
																		lowerCAmelCase      :Optional[Any]				  = (v.shape[0], v.shape[1] * v.shape[2])
																		lowerCAmelCase      :Optional[Any]				  = v.reshape(a__   ).T

												# Copy flax CLIP attn params to HF PyTorch params
												lowerCAmelCase      :Any				  = torch.from_numpy(a__   )
												hf_backbone.state_dict()[torch_key].copy_(a__   )


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






						lowerCAmelCase      :List[Any]				  = {}
						lowerCAmelCase      :Union[str, Any]				  = []

						for k, v in params.items():
												if "attn." in k:
																		lowerCAmelCase      :Optional[Any]				  = k[: k.rindex('attn.'   ) + 5]
																		if base in processed_attn_layers:
																								continue

																		processed_attn_layers.append(a__   )
																		lowerCAmelCase      :Tuple				  = params[base + 'out.weight'].shape[-1]
																		lowerCAmelCase      :Tuple				  = params[base + 'out.weight'].reshape(a__    ,			a__   ).T
																		lowerCAmelCase      :Optional[Any]				  = params[base + 'out.bias']
												else:
																		lowerCAmelCase      :List[Any]				  = v
						return new_params


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :str				  = CLIP(**a__   )
						torch_model.eval()
						lowerCAmelCase      :str				  = torch_model.state_dict()

						lowerCAmelCase      :Optional[Any]				  = flatten_nested_dict(flax_params['backbone']['clip']   )
						lowerCAmelCase      :Any				  = {}

						for flax_key, v in flax_clip_params.items():
												lowerCAmelCase      :int				  = flax_key.replace('/'    ,			'.'   )
												lowerCAmelCase      :Any				  = torch_key.replace('text.token_embedding.embedding'    ,			'token_embedding.kernel'   )

												if (
												    torch_key.startswith('text.transformer'   )
												    or torch_key.startswith('text.text_projection'   )
												    or torch_key.startswith('text.ln_final'   )
												    or torch_key.startswith('text.positional_embedding'   )
												):
																		lowerCAmelCase      :Optional[Any]				  = torch_key[5:]

												lowerCAmelCase      :List[Any]				  = torch_key.replace('text_projection.kernel'    ,			'text_projection'   )
												lowerCAmelCase      :Union[str, Any]				  = torch_key.replace('visual.proj.kernel'    ,			'visual.proj'   )
												lowerCAmelCase      :Tuple				  = torch_key.replace('.scale'    ,			'.weight'   )
												lowerCAmelCase      :List[Any]				  = torch_key.replace('.kernel'    ,			'.weight'   )

												if "conv" in torch_key or "downsample.0.weight" in torch_key:
																		lowerCAmelCase      :Union[str, Any]				  = v.transpose(3    ,			2    ,			0    ,			1   )

												elif "weight" in torch_key and v.ndim == 2 and "embedding" not in torch_key:
																		# Fully connected layers are transposed, embeddings are not
																		lowerCAmelCase      :int				  = v.T

												lowerCAmelCase      :Optional[int]				  = v

						lowerCAmelCase      :Tuple				  = _convert_attn_layers(a__   )
						new_torch_params.update(a__   )
						lowerCAmelCase      :Union[str, Any]				  = {}

						# Copy flax CLIP backbone params to PyTorch params
						for name, param in new_torch_params.items():
												if name in torch_clip_params.keys():
																		lowerCAmelCase      :Tuple				  = torch.from_numpy(new_torch_params[name]   )
																		torch_clip_params[name].copy_(a__   )
												else:
																		lowerCAmelCase      :List[Any]				  = param

						return torch_clip_params, torch_model, attn_params


@torch.no_grad()
def 					UpperCAmelCase			(				a__    ,			a__    ,			a__    ,			a__    ,			a__=None   ):





						'''simple docstring'''






						lowerCAmelCase      :int				  = Repository(a__    ,			clone_from=F"""google/{pytorch_dump_folder_path}"""   )
						repo.git_pull()

						if config_path is not None:
												lowerCAmelCase      :Optional[int]				  = OwlViTConfig.from_pretrained(a__   )
						else:
												lowerCAmelCase      :Tuple				  = OwlViTConfig()

						lowerCAmelCase      :Any				  = OwlViTModel(a__   ).eval()
						lowerCAmelCase      :Dict				  = OwlViTForObjectDetection(a__   ).eval()

						copy_text_model_and_projection(a__    ,			a__   )
						copy_vision_model_and_projection(a__    ,			a__   )
						lowerCAmelCase      :Any				  = pt_backbone.logit_scale
						copy_flax_attn_params(a__    ,			a__   )

						lowerCAmelCase      :Optional[Any]				  = hf_backbone
						copy_class_merge_token(a__    ,			a__   )
						copy_class_box_heads(a__    ,			a__   )

						# Save HF model
						hf_model.save_pretrained(repo.local_dir   )

						# Initialize image processor
						lowerCAmelCase      :Union[str, Any]				  = OwlViTImageProcessor(
						    size=config.vision_config.image_size    ,			crop_size=config.vision_config.image_size   )
						# Initialize tokenizer
						lowerCAmelCase      :Optional[Any]				  = CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32'    ,			pad_token='!'    ,			model_max_length=16   )

						# Initialize processor
						lowerCAmelCase      :Dict				  = OwlViTProcessor(image_processor=a__    ,			tokenizer=a__   )
						image_processor.save_pretrained(repo.local_dir   )
						processor.save_pretrained(repo.local_dir   )

						repo.git_add()
						repo.git_commit('Upload model and processor'   )
						repo.git_push()


if __name__ == "__main__":
		__SCREAMING_SNAKE_CASE      =      argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    '--owlvit_version',
		    default=None,
		    type=str,
		    required=True,
		    help='OWL-ViT model name [clip_b16, clip_b32, clip_l14].',
		)
		parser.add_argument(
		    '--owlvit_checkpoint', default=None, type=str, required=True, help='Path to flax model checkpoint.'
		)
		parser.add_argument('--hf_config', default=None, type=str, required=True, help='Path to HF model config.')
		parser.add_argument(
		    '--pytorch_dump_folder_path', default='hf_model', type=str, help='Path to the output PyTorch model.'
		)
		__SCREAMING_SNAKE_CASE      =      parser.parse_args()

		# Initialize PyToch clip model
		__SCREAMING_SNAKE_CASE      =      args.owlvit_version
		if model_name == "clip_b16":
				__SCREAMING_SNAKE_CASE      =      CONFIGS['vit_b16']
		elif model_name == "clip_b32":
				__SCREAMING_SNAKE_CASE      =      CONFIGS['vit_b32']
		elif model_name == "clip_l14":
				__SCREAMING_SNAKE_CASE      =      CONFIGS['vit_l14']

		# Load from checkpoint and convert params to float-32
		__SCREAMING_SNAKE_CASE      =      checkpoints.restore_checkpoint(args.owlvit_checkpoint, target=None)['optimizer']['target']
		__SCREAMING_SNAKE_CASE      =      jax.tree_util.tree_map(lambda x: x.astype(jnp.floataa) if x.dtype == jnp.bfloataa else x, variables)
		del variables

		# Convert CLIP backbone
		__SCREAMING_SNAKE_CASE,	__SCREAMING_SNAKE_CASE,	__SCREAMING_SNAKE_CASE      =      convert_clip_backbone(flax_params, torch_config)

		convert_owlvit_checkpoint(clip_pt, flax_params, attn_params, args.pytorch_dump_folder_path, args.hf_config)







"""simple docstring"""


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

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


__SCREAMING_SNAKE_CASE      =      logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE      =      {
    'src_vocab_file': 'vocab-src.json',
    'tgt_vocab_file': 'vocab-tgt.json',
    'merges_file': 'merges.txt',
}

__SCREAMING_SNAKE_CASE      =      {
    'src_vocab_file': {
        'stas/tiny-wmt19-en-de': 'https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/vocab-src.json'
    },
    'tgt_vocab_file': {
        'stas/tiny-wmt19-en-de': 'https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/vocab-tgt.json'
    },
    'merges_file': {'stas/tiny-wmt19-en-de': 'https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/merges.txt'},
}

__SCREAMING_SNAKE_CASE      =      {'stas/tiny-wmt19-en-de': 10_24}
__SCREAMING_SNAKE_CASE      =      {
    'stas/tiny-wmt19-en-de': {
        'langs': ['en', 'de'],
        'model_max_length': 10_24,
        'special_tokens_map_file': None,
        'full_tokenizer_file': None,
    }
}


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






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


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






						lowerCAmelCase      :List[str]				  = text.replace('，'    ,			','   )
						lowerCAmelCase      :str				  = re.sub(R'。\s*'    ,			'. '    ,			a__   )
						lowerCAmelCase      :int				  = text.replace('、'    ,			','   )
						lowerCAmelCase      :str				  = text.replace('”'    ,			'"'   )
						lowerCAmelCase      :Union[str, Any]				  = text.replace('“'    ,			'"'   )
						lowerCAmelCase      :List[Any]				  = text.replace('∶'    ,			':'   )
						lowerCAmelCase      :List[Any]				  = text.replace('：'    ,			':'   )
						lowerCAmelCase      :Optional[Any]				  = text.replace('？'    ,			'?'   )
						lowerCAmelCase      :Tuple				  = text.replace('《'    ,			'"'   )
						lowerCAmelCase      :Dict				  = text.replace('》'    ,			'"'   )
						lowerCAmelCase      :List[str]				  = text.replace('）'    ,			')'   )
						lowerCAmelCase      :Dict				  = text.replace('！'    ,			'!'   )
						lowerCAmelCase      :Optional[Any]				  = text.replace('（'    ,			'('   )
						lowerCAmelCase      :Optional[Any]				  = text.replace('；'    ,			';'   )
						lowerCAmelCase      :Any				  = text.replace('１'    ,			'1'   )
						lowerCAmelCase      :Union[str, Any]				  = text.replace('」'    ,			'"'   )
						lowerCAmelCase      :Any				  = text.replace('「'    ,			'"'   )
						lowerCAmelCase      :str				  = text.replace('０'    ,			'0'   )
						lowerCAmelCase      :Dict				  = text.replace('３'    ,			'3'   )
						lowerCAmelCase      :Union[str, Any]				  = text.replace('２'    ,			'2'   )
						lowerCAmelCase      :str				  = text.replace('５'    ,			'5'   )
						lowerCAmelCase      :Tuple				  = text.replace('６'    ,			'6'   )
						lowerCAmelCase      :Optional[int]				  = text.replace('９'    ,			'9'   )
						lowerCAmelCase      :Optional[Any]				  = text.replace('７'    ,			'7'   )
						lowerCAmelCase      :Union[str, Any]				  = text.replace('８'    ,			'8'   )
						lowerCAmelCase      :Optional[Any]				  = text.replace('４'    ,			'4'   )
						lowerCAmelCase      :int				  = re.sub(R'．\s*'    ,			'. '    ,			a__   )
						lowerCAmelCase      :List[Any]				  = text.replace('～'    ,			'~'   )
						lowerCAmelCase      :int				  = text.replace('’'    ,			'\''   )
						lowerCAmelCase      :Dict				  = text.replace('…'    ,			'...'   )
						lowerCAmelCase      :Any				  = text.replace('━'    ,			'-'   )
						lowerCAmelCase      :Union[str, Any]				  = text.replace('〈'    ,			'<'   )
						lowerCAmelCase      :Any				  = text.replace('〉'    ,			'>'   )
						lowerCAmelCase      :str				  = text.replace('【'    ,			'['   )
						lowerCAmelCase      :Any				  = text.replace('】'    ,			']'   )
						lowerCAmelCase      :int				  = text.replace('％'    ,			'%'   )
						return text


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Optional[int]				  = []
						for char in text:
												lowerCAmelCase      :Optional[Any]				  = unicodedata.category(a__   )
												if cat.startswith('C'   ):
																		continue
												output.append(a__   )
						return "".join(a__   )







class 	__UpperCamelCase    (    UpperCamelCase	):
					lowercase_						:							Dict			=     VOCAB_FILES_NAMES
					lowercase_						:							Any			=     PRETRAINED_VOCAB_FILES_MAP
					lowercase_						:							Dict			=     PRETRAINED_INIT_CONFIGURATION
					lowercase_						:							Optional[Any]			=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					lowercase_						:							Union[str, Any]			=     ["""input_ids""", """attention_mask"""]
					def __init__(       self       :  int    ,   UpperCAmelCase       :  Tuple=None    ,   UpperCAmelCase       :  Dict=None    ,   UpperCAmelCase       :  Dict=None    ,   UpperCAmelCase       :  Tuple=None    ,   UpperCAmelCase       :  str=False    ,   UpperCAmelCase       :  Optional[int]="<unk>"    ,   UpperCAmelCase       :  List[Any]="<s>"    ,   UpperCAmelCase       :  List[str]="</s>"    ,   UpperCAmelCase       :  Optional[int]="<pad>"    ,   **UpperCAmelCase       :  int    ,   )  ->					int:
											super().__init__(
											    langs=UpperCAmelCase    ,   src_vocab_file=UpperCAmelCase    ,   tgt_vocab_file=UpperCAmelCase    ,   merges_file=UpperCAmelCase    ,   do_lower_case=UpperCAmelCase    ,   unk_token=UpperCAmelCase    ,   bos_token=UpperCAmelCase    ,   sep_token=UpperCAmelCase    ,   pad_token=UpperCAmelCase    ,   **UpperCAmelCase    ,   )

											try:
																	import sacremoses
											except ImportError:
																	raise ImportError(
																	    'You need to install sacremoses to use XLMTokenizer. '
																	    'See https://pypi.org/project/sacremoses/ for installation.'      )

											lowerCAmelCase      :str				  = sacremoses

											lowerCAmelCase      :str				  = src_vocab_file
											lowerCAmelCase      :List[str]				  = tgt_vocab_file
											lowerCAmelCase      :str				  = merges_file
											lowerCAmelCase      :Optional[Any]				  = do_lower_case

											# cache of sm.MosesPunctNormalizer instance
											lowerCAmelCase      :str				  = {}
											# cache of sm.MosesTokenizer instance
											lowerCAmelCase      :Any				  = {}
											lowerCAmelCase      :List[str]				  = {}

											if langs and len(UpperCAmelCase      ) == 2:
																	lowerCAmelCase  ,   lowerCAmelCase      :List[Any]				  = langs
											else:
																	raise ValueError(
																	    f"""arg `langs` needs to be a list of 2 langs, e.g. ['en', 'ru'], but got {langs}. """
																	    'Usually that means that tokenizer can\'t find a mapping for the given model path '
																	    'in PRETRAINED_VOCAB_FILES_MAP, and other maps of this tokenizer.'      )

											with open(UpperCAmelCase    ,   encoding='utf-8'      ) as src_vocab_handle:
																	lowerCAmelCase      :Tuple				  = json.load(UpperCAmelCase      )
											with open(UpperCAmelCase    ,   encoding='utf-8'      ) as tgt_vocab_handle:
																	lowerCAmelCase      :str				  = json.load(UpperCAmelCase      )
																	lowerCAmelCase      :int				  = {v: k for k, v in tgt_vocab.items()}
											with open(UpperCAmelCase    ,   encoding='utf-8'      ) as merges_handle:
																	lowerCAmelCase      :Optional[int]				  = merges_handle.read().split('\n'      )[:-1]
											lowerCAmelCase      :List[Any]				  = [tuple(merge.split()[:2]      ) for merge in merges]
											lowerCAmelCase      :int				  = dict(zip(UpperCAmelCase    ,   range(len(UpperCAmelCase      )      )      )      )
											lowerCAmelCase      :str				  = {}
					def 					UpperCAmelCase__   (       self       :  Optional[Any]      )  ->					Dict[str, int]:
											return self.get_src_vocab()
					@property
					def 					UpperCAmelCase__   (       self       :  Dict      )  ->					int:
											return self.src_vocab_size
					def 					UpperCAmelCase__   (       self       :  int    ,   UpperCAmelCase       :  Tuple    ,   UpperCAmelCase       :  Tuple      )  ->					List[Any]:
											if lang not in self.cache_moses_punct_normalizer:
																	lowerCAmelCase      :str				  = self.sm.MosesPunctNormalizer(lang=UpperCAmelCase      )
																	lowerCAmelCase      :List[str]				  = punct_normalizer
											return self.cache_moses_punct_normalizer[lang].normalize(UpperCAmelCase      )
					def 					UpperCAmelCase__   (       self       :  Tuple    ,   UpperCAmelCase       :  str    ,   UpperCAmelCase       :  Optional[int]      )  ->					str:
											if lang not in self.cache_moses_tokenizer:
																	lowerCAmelCase      :Optional[int]				  = self.sm.MosesTokenizer(lang=UpperCAmelCase      )
																	lowerCAmelCase      :Any				  = moses_tokenizer
											return self.cache_moses_tokenizer[lang].tokenize(
											    UpperCAmelCase    ,   aggressive_dash_splits=UpperCAmelCase    ,   return_str=UpperCAmelCase    ,   escape=UpperCAmelCase      )
					def 					UpperCAmelCase__   (       self       :  Optional[Any]    ,   UpperCAmelCase       :  int    ,   UpperCAmelCase       :  str      )  ->					List[Any]:
											if lang not in self.cache_moses_detokenizer:
																	lowerCAmelCase      :Any				  = self.sm.MosesDetokenizer(lang=UpperCAmelCase      )
																	lowerCAmelCase      :str				  = moses_detokenizer
											return self.cache_moses_detokenizer[lang].detokenize(UpperCAmelCase      )
					def 					UpperCAmelCase__   (       self       :  Optional[int]    ,   UpperCAmelCase       :  str    ,   UpperCAmelCase       :  List[Any]      )  ->					int:
											lowerCAmelCase      :Dict				  = replace_unicode_punct(UpperCAmelCase      )
											lowerCAmelCase      :Union[str, Any]				  = self.moses_punct_norm(UpperCAmelCase    ,   UpperCAmelCase      )
											lowerCAmelCase      :Dict				  = remove_non_printing_char(UpperCAmelCase      )
											return text
					@property
					def 					UpperCAmelCase__   (       self       :  str      )  ->					Union[str, Any]:
											return len(self.encoder      )
					@property
					def 					UpperCAmelCase__   (       self       :  int      )  ->					Optional[int]:
											return len(self.decoder      )
					def 					UpperCAmelCase__   (       self       :  List[Any]      )  ->					Tuple:
											return dict(self.encoder    ,   **self.added_tokens_encoder      )
					def 					UpperCAmelCase__   (       self       :  Any      )  ->					str:
											return dict(self.decoder    ,   **self.added_tokens_decoder      )
					def 					UpperCAmelCase__   (       self       :  List[str]    ,   UpperCAmelCase       :  List[str]      )  ->					Tuple:
											lowerCAmelCase      :List[str]				  = tuple(token[:-1]      ) + (token[-1] + '</w>',)
											if token in self.cache:
																	return self.cache[token]
											lowerCAmelCase      :Dict				  = get_pairs(UpperCAmelCase      )

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

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

																							if word[i] == first and i < len(UpperCAmelCase      ) - 1 and word[i + 1] == second:
																													new_word.append(first + second      )
																													i += 2
																							else:
																													new_word.append(word[i]      )
																													i += 1
																	lowerCAmelCase      :Optional[Any]				  = tuple(UpperCAmelCase      )
																	lowerCAmelCase      :Dict				  = new_word
																	if len(UpperCAmelCase      ) == 1:
																							break
																	else:
																							lowerCAmelCase      :Any				  = get_pairs(UpperCAmelCase      )
											lowerCAmelCase      :Dict				  = ' '.join(UpperCAmelCase      )
											if word == "\n  </w>":
																	lowerCAmelCase      :List[Any]				  = '\n</w>'
											lowerCAmelCase      :Optional[Any]				  = word
											return word
					def 					UpperCAmelCase__   (       self       :  List[Any]    ,   UpperCAmelCase       :  int    ,   UpperCAmelCase       :  List[str]="en"    ,   UpperCAmelCase       :  int=False      )  ->					List[Any]:
											lowerCAmelCase      :Optional[Any]				  = self.src_lang

											if self.do_lower_case:
																	lowerCAmelCase      :Tuple				  = text.lower()

											if bypass_tokenizer:
																	lowerCAmelCase      :List[str]				  = text.split()
											else:
																	lowerCAmelCase      :Tuple				  = self.moses_pipeline(UpperCAmelCase    ,   lang=UpperCAmelCase      )
																	lowerCAmelCase      :Optional[int]				  = self.moses_tokenize(UpperCAmelCase    ,   lang=UpperCAmelCase      )

											lowerCAmelCase      :int				  = []
											for token in text:
																	if token:
																							split_tokens.extend(list(self.bpe(UpperCAmelCase      ).split(' '      )      )      )

											return split_tokens
					def 					UpperCAmelCase__   (       self       :  Dict    ,   UpperCAmelCase       :  Any      )  ->					List[Any]:
											return self.encoder.get(UpperCAmelCase    ,   self.encoder.get(self.unk_token      )      )
					def 					UpperCAmelCase__   (       self       :  Union[str, Any]    ,   UpperCAmelCase       :  Any      )  ->					Dict:
											return self.decoder.get(UpperCAmelCase    ,   self.unk_token      )
					def 					UpperCAmelCase__   (       self       :  List[str]    ,   UpperCAmelCase       :  Optional[Any]      )  ->					int:
											lowerCAmelCase      :Optional[int]				  = [t.replace(' '    ,   ''      ).replace('</w>'    ,   ' '      ) for t in tokens]
											lowerCAmelCase      :Optional[int]				  = ''.join(UpperCAmelCase      ).split()
											# detokenize
											lowerCAmelCase      :Dict				  = self.moses_detokenize(UpperCAmelCase    ,   self.tgt_lang      )
											return text
					def 					UpperCAmelCase__   (       self       :  str    ,   UpperCAmelCase       :  List[int]    ,   UpperCAmelCase       :  Optional[List[int]] = None      )  ->					List[int]:
											lowerCAmelCase      :Union[str, Any]				  = [self.sep_token_id]

											# no bos used in fairseq
											if token_ids_a is None:
																	return token_ids_a + sep
											return token_ids_a + sep + token_ids_a + sep
					def 					UpperCAmelCase__   (       self       :  Dict    ,   UpperCAmelCase       :  List[int]    ,   UpperCAmelCase       :  Optional[List[int]] = None    ,   UpperCAmelCase       :  bool = False      )  ->					List[int]:

											if already_has_special_tokens:
																	return super().get_special_tokens_mask(
																	    token_ids_a=UpperCAmelCase    ,   token_ids_a=UpperCAmelCase    ,   already_has_special_tokens=UpperCAmelCase      )
											# no bos used in fairseq
											if token_ids_a is not None:
																	return ([0] * len(UpperCAmelCase      )) + [1] + ([0] * len(UpperCAmelCase      )) + [1]
											return ([0] * len(UpperCAmelCase      )) + [1]
					def 					UpperCAmelCase__   (       self       :  str    ,   UpperCAmelCase       :  List[int]    ,   UpperCAmelCase       :  Optional[List[int]] = None      )  ->					List[int]:
											lowerCAmelCase      :Optional[Any]				  = [self.sep_token_id]

											# no bos used in fairseq
											if token_ids_a is None:
																	return len(token_ids_a + sep      ) * [0]
											return len(token_ids_a + sep      ) * [0] + len(token_ids_a + sep      ) * [1]
					def 					UpperCAmelCase__   (       self       :  Optional[int]    ,   UpperCAmelCase       :  str    ,   UpperCAmelCase       :  Optional[str] = None      )  ->					Tuple[str]:
											if not os.path.isdir(UpperCAmelCase      ):
																	logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""      )
																	return

											lowerCAmelCase      :Any				  = os.path.join(
											    UpperCAmelCase    ,   (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['src_vocab_file']      )
											lowerCAmelCase      :Tuple				  = os.path.join(
											    UpperCAmelCase    ,   (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['tgt_vocab_file']      )
											lowerCAmelCase      :Optional[int]				  = os.path.join(
											    UpperCAmelCase    ,   (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']      )

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

											with open(UpperCAmelCase    ,   'w'    ,   encoding='utf-8'      ) as f:
																	lowerCAmelCase      :int				  = {v: k for k, v in self.decoder.items()}
																	f.write(json.dumps(UpperCAmelCase    ,   indent=2    ,   sort_keys=UpperCAmelCase    ,   ensure_ascii=UpperCAmelCase      ) + '\n'      )

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

											return src_vocab_file, tgt_vocab_file, merges_file
					def __getstate__(       self       :  Union[str, Any]      )  ->					int:
											lowerCAmelCase      :Any				  = self.__dict__.copy()
											lowerCAmelCase      :Tuple				  = None
											return state
					def __setstate__(       self       :  Any    ,   UpperCAmelCase       :  Union[str, Any]      )  ->					List[Any]:
											lowerCAmelCase      :Tuple				  = d

											try:
																	import sacremoses
											except ImportError:
																	raise ImportError(
																	    'You need to install sacremoses to use XLMTokenizer. '
																	    'See https://pypi.org/project/sacremoses/ for installation.'      )

											lowerCAmelCase      :str				  = sacremoses