






'''simple docstring'''





from typing import Dict, List, Optional, Tuple

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


a_      = logging.get_logger(__name__)





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):
		_UpperCAmelCase         =['''input_ids''', '''attention_mask''']



		def __init__(    self:    Optional[Any]				,   a:    Union[str, Any]="[PAD]"				,   a:    Any="[BOS]"				,   a:    List[str]="[EOS]"				,   a:    List[str]="[MASK]"				,   a:    Dict="[CLS]"				,   a:    Tuple="[SEP]"				,   a:    Union[str, Any]=20_48				,   **a:    Optional[int]				,   )  ->None:






								'''simple docstring'''


								a_				     =   AddedToken(a				,   lstrip=a				,   rstrip=a) if isinstance(a				,   a) else pad_token
								a_				     =   AddedToken(a				,   lstrip=a				,   rstrip=a) if isinstance(a				,   a) else bos_token
								a_				     =   AddedToken(a				,   lstrip=a				,   rstrip=a) if isinstance(a				,   a) else eos_token
								a_				     =   AddedToken(a				,   lstrip=a				,   rstrip=a) if isinstance(a				,   a) else mask_token
								a_				     =   AddedToken(a				,   lstrip=a				,   rstrip=a) if isinstance(a				,   a) else cls_token
								a_				     =   AddedToken(a				,   lstrip=a				,   rstrip=a) if isinstance(a				,   a) else sep_token

								super().__init__(
								    pad_token=a				,   bos_token=a				,   eos_token=a				,   mask_token=a				,   cls_token=a				,   sep_token=a				,   model_max_length=a				,   **a				,   )

								a_				     =   2**8  # utf is 8 bits

								# define special tokens dict
								a_				     =   {
								    self.pad_token: 0,
								    self.bos_token: 1,
								    self.eos_token: 2,
								    self.mask_token: 3,
								    self.cls_token: 4,
								    self.sep_token: 5,
								}
								a_				     =   len(self.special_tokens_encoder)
								a_				     =   {v: k for k, v in self.special_tokens_encoder.items()}



		def _lowerCAmelCase     (    self:    Optional[Any])  ->Dict[str, int]:






								'''simple docstring'''


								a_				     =   self.special_tokens_encoder.copy()
								vocab.update(self.added_tokens_encoder)
								for i in range(self._utf_vocab_size):
														a_				     =   chr(a)
														a_				     =   i + len(self.special_tokens_encoder)
								return vocab



		@property
		def _lowerCAmelCase     (    self:    int)  ->List[Any]:






								'''simple docstring'''


								return self._utf_vocab_size + self._num_special_tokens



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






								'''simple docstring'''


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

								# normal case: some special tokens
								if token_ids_a is None:
														return [1] + [0] * len(a) + [1]
								return [1] + ([0] * len(a)) + [1] + ([0] * len(a)) + [1]



		def _lowerCAmelCase     (    self:    Tuple				,   a:    List[int]				,   a:    Optional[List[int]] = None)  ->List[int]:






								'''simple docstring'''


								if token_ids_a is None:
														return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
								else:
														return [self.cls_token_id] + token_ids_a + [self.sep_token_id] + token_ids_a + [self.sep_token_id]



		def _lowerCAmelCase     (    self:    List[Any]				,   a:    str)  ->List[str]:






								'''simple docstring'''


								a_				     =   [chr(a) for i in text.encode("utf-8")]
								return tokens



		def _lowerCAmelCase     (    self:    Any				,   a:    Union[str, Any])  ->List[Any]:






								'''simple docstring'''


								if token in self.special_tokens_encoder:
														a_				     =   self.special_tokens_encoder[token]
								elif token in self.added_tokens_encoder:
														a_				     =   self.added_tokens_encoder[token]
								elif len(a) != 1:
														a_				     =   self.unk_token_id
								else:
														a_				     =   ord(a) + self._num_special_tokens
								return token_id



		def _lowerCAmelCase     (    self:    int				,   a:    List[Any])  ->List[str]:






								'''simple docstring'''


								if index in self.special_tokens_decoder:
														a_				     =   self.special_tokens_decoder[index]
								elif index in self.added_tokens_decoder:
														a_				     =   self.added_tokens_decoder[index]
								else:
														a_				     =   chr(index - self._num_special_tokens)
								return token



		def _lowerCAmelCase     (    self:    Optional[int]				,   a:    Optional[int])  ->Optional[int]:






								'''simple docstring'''


								a_				     =   b""
								for token in tokens:
														if token in self.special_tokens_decoder:
																				a_				     =   self.special_tokens_decoder[token].encode("utf-8")
														elif token in self.added_tokens_decoder:
																				a_				     =   self.special_tokens_decoder[token].encode("utf-8")
														elif token in self.special_tokens_encoder:
																				a_				     =   token.encode("utf-8")
														elif token in self.added_tokens_encoder:
																				a_				     =   token.encode("utf-8")
														else:
																				a_				     =   bytes([ord(a)])
														bstring += tok_string
								a_				     =   bstring.decode("utf-8"				,   errors="replace")
								return string




		def _lowerCAmelCase     (    self:    Optional[Any]				,   a:    str				,   a:    Optional[str] = None)  ->Tuple[str]:






								'''simple docstring'''


								return ()











'''simple docstring'''





import argparse
import collections
from pathlib import Path

import torch
from torch.serialization import default_restore_location

from transformers import BertConfig, DPRConfig, DPRContextEncoder, DPRQuestionEncoder, DPRReader


a_      = collections.namedtuple(
    'CheckpointState', ['model_dict', 'optimizer_dict', 'scheduler_dict', 'offset', 'epoch', 'encoder_params']
)



def 			__UpperCAmelCase				(lowercase__				)		->				CheckpointState:

						'''simple docstring'''


						print(F"""Reading saved model from {model_file}"""				)
						a_				     =   torch.load(lowercase__	,map_location=lambda lowercase__	,lowercase__				: default_restore_location(lowercase__	,"cpu"				)				)
						return CheckpointState(**lowercase__				)





class 		SCREAMING_SNAKE_CASE__   :



		def __init__(    self:    int				,   a:    Path)  ->str:






								'''simple docstring'''


								a_				     =   src_file



		def _lowerCAmelCase     (    self:    Dict)  ->Optional[Any]:






								'''simple docstring'''


								raise NotImplementedError




		@staticmethod
		def _lowerCAmelCase     (    a:    str				,   *a:    int				,   **a:    int)  ->"DPRState":






								'''simple docstring'''


								if comp_type.startswith("c"):
														return DPRContextEncoderState(*a				,   **a)
								if comp_type.startswith("q"):
														return DPRQuestionEncoderState(*a				,   **a)
								if comp_type.startswith("r"):
														return DPRReaderState(*a				,   **a)
								else:
														raise ValueError("Component type must be either 'ctx_encoder', 'question_encoder' or 'reader'.")





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



		def _lowerCAmelCase     (    self:    Union[str, Any])  ->Any:






								'''simple docstring'''


								a_				     =   DPRContextEncoder(DPRConfig(**BertConfig.get_config_dict("bert-base-uncased")[0]))
								print(f"""Loading DPR biencoder from {self.src_file}""")
								a_				     =   load_states_from_checkpoint(self.src_file)
								a_     ,       a_				     =   model.ctx_encoder, "ctx_model."
								# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
								a_				     =   {"bert_model.embeddings.position_ids": model.ctx_encoder.bert_model.embeddings.position_ids}
								for key, value in saved_state.model_dict.items():
														if key.startswith(a):
																				a_				     =   key[len(a) :]
																				if not key.startswith("encode_proj."):
																										a_				     =   "bert_model." + key
																				a_				     =   value
								encoder.load_state_dict(a)
								return model





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



		def _lowerCAmelCase     (    self:    Optional[int])  ->Optional[int]:






								'''simple docstring'''


								a_				     =   DPRQuestionEncoder(DPRConfig(**BertConfig.get_config_dict("bert-base-uncased")[0]))
								print(f"""Loading DPR biencoder from {self.src_file}""")
								a_				     =   load_states_from_checkpoint(self.src_file)
								a_     ,       a_				     =   model.question_encoder, "question_model."
								# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
								a_				     =   {"bert_model.embeddings.position_ids": model.question_encoder.bert_model.embeddings.position_ids}
								for key, value in saved_state.model_dict.items():
														if key.startswith(a):
																				a_				     =   key[len(a) :]
																				if not key.startswith("encode_proj."):
																										a_				     =   "bert_model." + key
																				a_				     =   value
								encoder.load_state_dict(a)
								return model





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



		def _lowerCAmelCase     (    self:    Tuple)  ->Optional[Any]:






								'''simple docstring'''


								a_				     =   DPRReader(DPRConfig(**BertConfig.get_config_dict("bert-base-uncased")[0]))
								print(f"""Loading DPR reader from {self.src_file}""")
								a_				     =   load_states_from_checkpoint(self.src_file)
								# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
								a_				     =   {
								    "encoder.bert_model.embeddings.position_ids": model.span_predictor.encoder.bert_model.embeddings.position_ids
								}
								for key, value in saved_state.model_dict.items():
														if key.startswith("encoder.") and not key.startswith("encoder.encode_proj"):
																				a_				     =   "encoder.bert_model." + key[len("encoder.") :]
														a_				     =   value
								model.span_predictor.load_state_dict(a)
								return model





def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				Any:

						'''simple docstring'''


						a_				     =   Path(lowercase__				)
						dest_dir.mkdir(exist_ok=lowercase__				)

						a_				     =   DPRState.from_type(lowercase__	,src_file=lowercase__				)
						a_				     =   dpr_state.load_dpr_model()
						model.save_pretrained(lowercase__				)
						model.from_pretrained(lowercase__				)  # sanity check


if __name__ == "__main__":
							a_      = argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    '--type', type=str, help='Type of the component to convert: \'ctx_encoder\', \'question_encoder\' or \'reader\'.'
							)
							parser.add_argument(
							    '--src',
							    type=str,
							    help=(
							        'Path to the dpr checkpoint file. They can be downloaded from the official DPR repo'
							        ' https://github.com/facebookresearch/DPR. Note that in the official repo, both encoders are stored in the'
							        ' \'retriever\' checkpoints.'
							    ),
							)
							parser.add_argument('--dest', type=str, default=None, help='Path to the output PyTorch model directory.')
							a_      = parser.parse_args()

							a_      = Path(args.src)
							a_      = F'converted-{src_file.name}' if args.dest is None else args.dest
							a_      = Path(dest_dir)
							assert src_file.exists()
							assert (
							    args.type is not None
							), "Please specify the component type of the DPR model to convert: 'ctx_encoder', 'question_encoder' or 'reader'."
							convert(args.type, src_file, dest_dir)



