






'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


a_      = {
    'configuration_mobilenet_v1': [
        'MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'MobileNetV1Config',
        'MobileNetV1OnnxConfig',
    ],
}

try:
							if not is_vision_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							a_      = ['MobileNetV1FeatureExtractor']
							a_      = ['MobileNetV1ImageProcessor']

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							a_      = [
							    'MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST',
							    'MobileNetV1ForImageClassification',
							    'MobileNetV1Model',
							    'MobileNetV1PreTrainedModel',
							    'load_tf_weights_in_mobilenet_v1',
							]


if TYPE_CHECKING:
							from .configuration_mobilenet_va import (
							    MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP,
							    MobileNetVaConfig,
							    MobileNetVaOnnxConfig,
							)

							try:
														if not is_vision_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor
														from .image_processing_mobilenet_va import MobileNetVaImageProcessor

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_mobilenet_va import (
														    MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST,
														    MobileNetVaForImageClassification,
														    MobileNetVaModel,
														    MobileNetVaPreTrainedModel,
														    load_tf_weights_in_mobilenet_va,
														)


else:
							import sys

							a_      = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)











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



