



import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
_lowercase				:					int     					="""src/transformers"""

# Matches is_xxx_available()
_lowercase				:					List[Any]     					=re.compile(R"""is\_([a-z_]*)_available()""")
# Matches from xxx import bla
_lowercase				:					int     					=re.compile(R"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""")
_lowercase				:					List[str]     					=re.compile(R"""^\s+if\s+not\s+\(?is\_[a-z_]*\_available\(\)""")


_lowercase				:					Optional[Any]     					="""\n{0} = None\n"""

_lowercase				:					Optional[int]     					="""\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n"""


_lowercase				:					List[str]     					="""\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n"""




def    UpperCAmelCase					(  lowercase__						:					Optional[Any]	):



			'''simple docstring'''





			if _re_test_backend.search(_lowerCAmelCase	) is None:
						return None
			a__					=  [b[0] for b in _re_backend.findall(_lowerCAmelCase	)]
			backends.sort()
			return "_and_".join(_lowerCAmelCase	)




def    UpperCAmelCase					(  ):



			'''simple docstring'''





			with open(os.path.join(_lowerCAmelCase				,					"""__init__.py"""	)				,					"""r"""				,					encoding="""utf-8"""				,					newline="""\n"""	) as f:
						a__					=  f.readlines()

			# Get to the point we do the actual imports for type checking
			a__					=  0
			while not lines[line_index].startswith("""if TYPE_CHECKING"""	):
						line_index += 1

			a__					=  {}
			# Go through the end of the file
			while line_index < len(_lowerCAmelCase	):
						# If the line is an if is_backend_available, we grab all objects associated.
						a__					=  find_backend(lines[line_index]	)
						if backend is not None:
									while not lines[line_index].startswith("""    else:"""	):
												line_index += 1
									line_index += 1

									a__					=  []
									# Until we unindent, add backend objects to the list
									while len(lines[line_index]	) <= 1 or lines[line_index].startswith(""" """ * 8	):
												a__					=  lines[line_index]
												a__					=  _re_single_line_import.search(_lowerCAmelCase	)
												if single_line_import_search is not None:
															objects.extend(single_line_import_search.groups()[0].split(""", """	)	)
												elif line.startswith(""" """ * 12	):
															objects.append(line[12:-2]	)
												line_index += 1

									a__					=  objects
						else:
									line_index += 1

			return backend_specific_objects




def    UpperCAmelCase					(  lowercase__						:					Optional[Any]				,					lowercase__						:					Any	):



			'''simple docstring'''





			if name.isupper():
						return DUMMY_CONSTANT.format(_lowerCAmelCase	)
			elif name.islower():
						return DUMMY_FUNCTION.format(_lowerCAmelCase				,					_lowerCAmelCase	)
			else:
						return DUMMY_CLASS.format(_lowerCAmelCase				,					_lowerCAmelCase	)




def    UpperCAmelCase					(  lowercase__						:					int=None	):



			'''simple docstring'''





			if backend_specific_objects is None:
						a__					=  read_init()
			# For special correspondence backend to module name as used in the function requires_modulename
			a__					=  {}

			for backend, objects in backend_specific_objects.items():
						a__					=  "[" + ", ".join(f'\"{b}\"' for b in backend.split("""_and_"""	)	) + "]"
						a__					=  "# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
						dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
						dummy_file += "\n".join([create_dummy_object(_lowerCAmelCase				,					_lowerCAmelCase	) for o in objects]	)
						a__					=  dummy_file

			return dummy_files




def    UpperCAmelCase					(  lowercase__						:					List[str]=False	):



			'''simple docstring'''





			a__					=  create_dummy_files()
			# For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
			a__					=  {"torch": "pt"}

			# Locate actual dummy modules and read their content.
			a__					=  os.path.join(_lowerCAmelCase				,					"""utils"""	)
			a__					=  {
			    backend: os.path.join(_lowerCAmelCase				,					f'dummy_{short_names.get(_lowerCAmelCase				,					_lowerCAmelCase	)}_objects.py'	)
			    for backend in dummy_files.keys()
			}

			a__					=  {}
			for backend, file_path in dummy_file_paths.items():
						if os.path.isfile(_lowerCAmelCase	):
									with open(_lowerCAmelCase				,					"""r"""				,					encoding="""utf-8"""				,					newline="""\n"""	) as f:
												a__					=  f.read()
						else:
									a__					=  ""

			for backend in dummy_files.keys():
						if dummy_files[backend] != actual_dummies[backend]:
									if overwrite:
												print(
												    f'Updating transformers.utils.dummy_{short_names.get(_lowerCAmelCase				,					_lowerCAmelCase	)}_objects.py as the main '
												    """__init__ has new objects."""	)
												with open(dummy_file_paths[backend]				,					"""w"""				,					encoding="""utf-8"""				,					newline="""\n"""	) as f:
															f.write(dummy_files[backend]	)
									else:
												raise ValueError(
												    """The main __init__ has objects that are not present in """
												    f'transformers.utils.dummy_{short_names.get(_lowerCAmelCase				,					_lowerCAmelCase	)}_objects.py. Run `make fix-copies` '
												    """to fix this."""	)


if __name__ == "__main__":
	_lowercase				:					Dict     					=argparse.ArgumentParser()
	parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
	_lowercase				:					Any     					=parser.parse_args()

	check_dummies(args.fix_and_overwrite)


'''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__   (				_lowerCAmelCase    :			str)    ->		CheckpointState:



						"""simple docstring"""

						print(f"""Reading saved model from {model_file}""")
						snake_case :       Optional[Any]				=    torch.load(_lowerCAmelCase,      map_location=lambda _lowerCAmelCase,      _lowerCAmelCase: default_restore_location(_lowerCAmelCase,      "cpu"))
						return CheckpointState(**_lowerCAmelCase)




class 		SCREAMING_SNAKE_CASE_					:



			"""simple docstring"""






			def __init__(							self				,			snake_case_					):
									snake_case :       Union[str, Any]				=    src_file



			def   lowerCamelCase (							self					):
									raise NotImplementedError






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







class 		SCREAMING_SNAKE_CASE_					(_UpperCAmelCase      ):



			"""simple docstring"""






			def   lowerCamelCase (							self					):
									snake_case :       List[Any]				=    DPRContextEncoder(DPRConfig(**BertConfig.get_config_dict("bert-base-uncased"					)[0]					)					)
									print(F"""Loading DPR biencoder from {self.src_file}"""					)
									snake_case :       List[Any]				=    load_states_from_checkpoint(self.src_file					)
									snake_case				,					snake_case :       List[str]				=    model.ctx_encoder, "ctx_model."
									# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
									snake_case :       List[str]				=    {"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(snake_case_					):
																					snake_case :       str				=    key[len(snake_case_					) :]
																					if not key.startswith("encode_proj."					):
																											snake_case :       int				=    "bert_model." + key
																					snake_case :       Union[str, Any]				=    value
									encoder.load_state_dict(snake_case_					)
									return model







class 		SCREAMING_SNAKE_CASE_					(_UpperCAmelCase      ):



			"""simple docstring"""






			def   lowerCamelCase (							self					):
									snake_case :       Any				=    DPRQuestionEncoder(DPRConfig(**BertConfig.get_config_dict("bert-base-uncased"					)[0]					)					)
									print(F"""Loading DPR biencoder from {self.src_file}"""					)
									snake_case :       Dict				=    load_states_from_checkpoint(self.src_file					)
									snake_case				,					snake_case :       Tuple				=    model.question_encoder, "question_model."
									# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
									snake_case :       Dict				=    {"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(snake_case_					):
																					snake_case :       Optional[int]				=    key[len(snake_case_					) :]
																					if not key.startswith("encode_proj."					):
																											snake_case :       List[str]				=    "bert_model." + key
																					snake_case :       Union[str, Any]				=    value
									encoder.load_state_dict(snake_case_					)
									return model







class 		SCREAMING_SNAKE_CASE_					(_UpperCAmelCase      ):



			"""simple docstring"""






			def   lowerCamelCase (							self					):
									snake_case :       List[Any]				=    DPRReader(DPRConfig(**BertConfig.get_config_dict("bert-base-uncased"					)[0]					)					)
									print(F"""Loading DPR reader from {self.src_file}"""					)
									snake_case :       List[str]				=    load_states_from_checkpoint(self.src_file					)
									# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
									snake_case :       List[str]				=    {
									    "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"					):
																					snake_case :       List[Any]				=    "encoder.bert_model." + key[len("encoder."					) :]
															snake_case :       Union[str, Any]				=    value
									model.span_predictor.load_state_dict(snake_case_					)
									return model







def        UpperCAmelCase__   (				_lowerCAmelCase    :			str,      _lowerCAmelCase    :			Path,      _lowerCAmelCase    :			Path)    ->		List[Any]:



						"""simple docstring"""

						snake_case :       Any				=    Path(_lowerCAmelCase)
						dest_dir.mkdir(exist_ok=_lowerCAmelCase)

						snake_case :       Tuple				=    DPRState.from_type(_lowerCAmelCase,      src_file=_lowerCAmelCase)
						snake_case :       Optional[int]				=    dpr_state.load_dpr_model()
						model.save_pretrained(_lowerCAmelCase)
						model.from_pretrained(_lowerCAmelCase)  # 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)





