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


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

def 	__lowerCamelCase							(				__a    : str		)      ->       CheckpointState:
	print(f'''Reading saved model from {model_file}'''		)
	_lowercase   =torch.load(__a      ,							map_location=lambda __a      ,							__a		: default_restore_location(__a      ,							"cpu"		)		)
	return CheckpointState(**__a		)
class 	_a  :



	"""simple docstring"""



	def __init__(   self       ,  lowerCAmelCase_       ):
		_lowercase   =src_file


	def __lowerCAmelCase      (   self       ):
		raise NotImplementedError


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

class 	_a  (							lowerCamelCase_					):



	"""simple docstring"""



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

class 	_a  (							lowerCamelCase_					):



	"""simple docstring"""



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

class 	_a  (							lowerCamelCase_					):



	"""simple docstring"""



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

def 	__lowerCamelCase							(				__a    : str      ,							__a    : Path      ,							__a    : Path		)      ->       int:
	_lowercase   =Path(__a		)
	dest_dir.mkdir(exist_ok=__a		)

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


if __name__ == "__main__":
						lowerCAmelCase__  	=      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.")
						lowerCAmelCase__  	=      parser.parse_args()

						lowerCAmelCase__  	=      Path(args.src)
						lowerCAmelCase__  	=      F'''converted-{src_file.name}''' if args.dest is None else args.dest
						lowerCAmelCase__  	=      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)










import math
from itertools import permutations


def 				__SCREAMING_SNAKE_CASE    (     snake_case_		):

						'''simple docstring'''


						if 1 < number < 4:
												# 2 and 3 are primes
												return True
						elif number < 2 or number % 2 == 0 or number % 3 == 0:
												# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
												return False

						# All primes number are in format of 6k +/- 1
						for i in range(5      ,       int(math.sqrt(snake_case_		) + 1		)      ,       6		):
												if number % i == 0 or number % (i + 2) == 0:
																		return False
						return True


def 				__SCREAMING_SNAKE_CASE    (     snake_case_      ,       snake_case_		):

						'''simple docstring'''


						_UpperCAmelCase				,					_UpperCAmelCase						=	0, len(snake_case_		) - 1
						while left <= right:
												_UpperCAmelCase						=	(left + right) // 2
												if prime_list[middle] == target:
																		return True
												elif prime_list[middle] < target:
																		_UpperCAmelCase						=	middle + 1
												else:
																		_UpperCAmelCase						=	middle - 1

						return False


def 				__SCREAMING_SNAKE_CASE    (     ):

						'''simple docstring'''


						_UpperCAmelCase						=	[n for n in range(1001      ,       1_0000      ,       2		) if is_prime(snake_case_		)]
						_UpperCAmelCase						=	[]

						for number in prime_list:
												_UpperCAmelCase						=	[]

												for prime_member in permutations(list(str(snake_case_		)		)		):
																		_UpperCAmelCase						=	int("".join(snake_case_		)		)

																		if prime % 2 == 0:
																								continue

																		if search(snake_case_      ,       snake_case_		):
																								tmp_numbers.append(snake_case_		)

												tmp_numbers.sort()
												if len(snake_case_		) >= 3:
																		candidates.append(snake_case_		)

						_UpperCAmelCase						=	[]
						for candidate in candidates:
												_UpperCAmelCase						=	len(snake_case_		)
												_UpperCAmelCase						=	False

												for i in range(snake_case_		):
																		for j in range(i + 1      ,       snake_case_		):
																								for k in range(j + 1      ,       snake_case_		):
																														if (
																														    abs(candidate[i] - candidate[j]		)
																														    == abs(candidate[j] - candidate[k]		)
																														    and len({candidate[i], candidate[j], candidate[k]}		) == 3
																														):
																																				passed.append(
																																				    sorted([candidate[i], candidate[j], candidate[k]]		)		)
																																				_UpperCAmelCase						=	True

																														if found:
																																				break
																								if found:
																														break
																		if found:
																								break

						_UpperCAmelCase						=	set()
						for seq in passed:
												answer.add("".join([str(snake_case_		) for i in seq]		)		)

						return max(int(snake_case_		) for x in answer		)


if __name__ == "__main__":
				print(solution())




