"""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						):
    print(f"""Reading saved model from {model_file}"""						)
    __a			      =						torch.load(_lowerCAmelCase				, map_location=lambda _lowerCAmelCase				, _lowerCAmelCase						: default_restore_location(_lowerCAmelCase				, """cpu"""						)						)
    return CheckpointState(**_lowerCAmelCase						)






class 					a					:



  def __init__(		self   :    Tuple						,  lowerCamelCase_   :    Path     )      -> Tuple:
      __a			      =						src_file



  def        lowerCAmelCase_				(		self   :    str     )      -> List[Any]:
      raise NotImplementedError



  @staticmethod
  def        lowerCAmelCase_				(		lowerCamelCase_   :    str						,  *lowerCamelCase_   :    Dict						,  **lowerCamelCase_   :    Tuple     )      -> "DPRState":
      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					(				A_							):



  def        lowerCAmelCase_				(		self   :    str     )      -> Union[str, Any]:
      __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(lowerCamelCase_     ):
              __a			      =						key[len(lowerCamelCase_     ) :]
              if not key.startswith("""encode_proj."""     ):
                  __a			      =						"""bert_model.""" + key
              __a			      =						value
      encoder.load_state_dict(lowerCamelCase_     )
      return model






class 					a					(				A_							):



  def        lowerCAmelCase_				(		self   :    int     )      -> List[Any]:
      __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(lowerCamelCase_     ):
              __a			      =						key[len(lowerCamelCase_     ) :]
              if not key.startswith("""encode_proj."""     ):
                  __a			      =						"""bert_model.""" + key
              __a			      =						value
      encoder.load_state_dict(lowerCamelCase_     )
      return model






class 					a					(				A_							):



  def        lowerCAmelCase_				(		self   :    List[str]     )      -> int:
      __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(lowerCamelCase_     )
      return model

def 						UpperCamelCase				(	_lowerCAmelCase   :							str				, _lowerCAmelCase   :							Path				, _lowerCAmelCase   :							Path						):
    __a			      =						Path(_lowerCAmelCase						)
    dest_dir.mkdir(exist_ok=_lowerCAmelCase						)

    __a			      =						DPRState.from_type(_lowerCAmelCase				, src_file=_lowerCAmelCase						)
    __a			      =						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)

"""simple docstring"""


from doctest import testmod
from math import sqrt

def 						UpperCamelCase				(	_lowerCAmelCase   :							int						):
    __a			      =						[]
    if num < 1:
        return facs
    facs.append(1						)
    if num == 1:
        return facs
    facs.append(_lowerCAmelCase						)
    for i in range(2				, int(sqrt(_lowerCAmelCase						)						) + 1						):
        if num % i == 0:  # If i is a factor of num
            facs.append(_lowerCAmelCase						)
            __a			      =						num // i  # num//i is the other factor of num
            if d != i:  # If d and i are distinct
                facs.append(_lowerCAmelCase						)  # we have found another factor
    facs.sort()
    return facs


if __name__ == "__main__":
 testmod(name="""factors_of_a_number""", verbose=True)
