






'''simple docstring'''





from typing import Optional, Union

from ...file_utils import TensorType
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, TruncationStrategy





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):
		_UpperCAmelCase         ='''MarkupLMFeatureExtractor'''
		_UpperCAmelCase         =('''MarkupLMTokenizer''', '''MarkupLMTokenizerFast''')
		_UpperCAmelCase         =True



		def __call__(    self:    List[Any]				,   a:    Optional[int]=None				,   a:    Tuple=None				,   a:    Any=None				,   a:    Optional[Any]=None				,   a:    Optional[int]=None				,   a:    bool = True				,   a:    Union[bool, str, PaddingStrategy] = False				,   a:    Union[bool, str, TruncationStrategy] = None				,   a:    Optional[int] = None				,   a:    int = 0				,   a:    Optional[int] = None				,   a:    Optional[bool] = None				,   a:    Optional[bool] = None				,   a:    bool = False				,   a:    bool = False				,   a:    bool = False				,   a:    bool = False				,   a:    bool = True				,   a:    Optional[Union[str, TensorType]] = None				,   **a:    Optional[int]				,   )  ->BatchEncoding:






								'''simple docstring'''


								if self.parse_html:
														if html_strings is None:
																				raise ValueError("Make sure to pass HTML strings in case `parse_html` is set to `True`")

														if nodes is not None or xpaths is not None or node_labels is not None:
																				raise ValueError(
																				    "Please don't pass nodes, xpaths nor node labels in case `parse_html` is set to `True`")

														a_				     =   self.feature_extractor(a)
														a_				     =   features["nodes"]
														a_				     =   features["xpaths"]
								else:
														if html_strings is not None:
																				raise ValueError("You have passed HTML strings but `parse_html` is set to `False`.")
														if nodes is None or xpaths is None:
																				raise ValueError("Make sure to pass nodes and xpaths in case `parse_html` is set to `False`")

        # # second, apply the tokenizer
								if questions is not None and self.parse_html:
														if isinstance(a				,   a):
																				a_				     =   [questions]  # add batch dimension (as the feature extractor always adds a batch dimension)

								a_				     =   self.tokenizer(
								    text=questions if questions is not None else nodes				,   text_pair=nodes if questions is not None else None				,   xpaths=a				,   node_labels=a				,   add_special_tokens=a				,   padding=a				,   truncation=a				,   max_length=a				,   stride=a				,   pad_to_multiple_of=a				,   return_token_type_ids=a				,   return_attention_mask=a				,   return_overflowing_tokens=a				,   return_special_tokens_mask=a				,   return_offsets_mapping=a				,   return_length=a				,   verbose=a				,   return_tensors=a				,   **a				,   )

								return encoded_inputs



		def _lowerCAmelCase     (    self:    str				,   *a:    Tuple				,   **a:    Dict)  ->str:






								'''simple docstring'''


								return self.tokenizer.batch_decode(*a				,   **a)



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






								'''simple docstring'''


								return self.tokenizer.decode(*a				,   **a)




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






								'''simple docstring'''


								a_				     =   self.tokenizer.model_input_names
								return tokenizer_input_names














'''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)



