





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


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




def 			lowerCAmelCase_			(				UpperCamelCase_	)  ->		CheckpointState:
       print(F'''Reading saved model from {model_file}'''	)
       UpperCamelCase_ 							=	torch.load(UpperCamelCase_       ,		map_location=lambda UpperCamelCase_       ,		UpperCamelCase_	: default_restore_location(UpperCamelCase_       ,		"cpu"	)	)
       return CheckpointState(**UpperCamelCase_	)



class 				_UpperCamelCase       :

       def __init__(		self:			List[str]       , _SCREAMING_SNAKE_CASE:			List[Any]		)							->			Dict:




              """simple docstring"""


              UpperCamelCase_ 							=	src_file

       def lowercase			(		self:			List[str]		)							->			Any:




              """simple docstring"""


              raise NotImplementedError



       @staticmethod
       def lowercase			(		_SCREAMING_SNAKE_CASE:			Optional[Any]       , *_SCREAMING_SNAKE_CASE:			Optional[int]       , **_SCREAMING_SNAKE_CASE:			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 				_UpperCamelCase       (						_UpperCAmelCase  ):

       def lowercase			(		self:			Union[str, Any]		)							->			str:




              """simple docstring"""


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



class 				_UpperCamelCase       (						_UpperCAmelCase  ):

       def lowercase			(		self:			Tuple		)							->			Tuple:




              """simple docstring"""


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



class 				_UpperCamelCase       (						_UpperCAmelCase  ):

       def lowercase			(		self:			Tuple		)							->			Optional[Any]:




              """simple docstring"""


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




def 			lowerCAmelCase_			(				UpperCamelCase_       ,		UpperCamelCase_       ,		UpperCamelCase_	)  ->		Dict:
       UpperCamelCase_ 							=	Path(UpperCamelCase_	)
       dest_dir.mkdir(exist_ok=UpperCamelCase_	)

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


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

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




UpperCamelCase											=     [
    [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
    [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
]






def 							lowerCAmelCase			(   UpperCamelCase_:				int  ,			UpperCamelCase_:				int  ,			UpperCamelCase_:				int  ,			UpperCamelCase_:				int       )							->				bool:







  '''simple docstring'''







  return 0 <= row < rows and 0 <= col < cols






def 							lowerCAmelCase			(   UpperCamelCase_:				int  ,			UpperCamelCase_:				int  ,			UpperCamelCase_:				set  ,			UpperCamelCase_:				list[list[int]]       )							->				int:







  '''simple docstring'''







  _a					      =						len(UpperCamelCase_       )
  _a					      =						len(mat[0]       )
  if is_safe(UpperCamelCase_  ,			UpperCamelCase_  ,			UpperCamelCase_  ,			UpperCamelCase_       ) and (row, col) not in seen and mat[row][col] == 1:
    seen.add((row, col)       )
    return (
        1
        + depth_first_search(row + 1  ,			UpperCamelCase_  ,			UpperCamelCase_  ,			UpperCamelCase_       )
        + depth_first_search(row - 1  ,			UpperCamelCase_  ,			UpperCamelCase_  ,			UpperCamelCase_       )
        + depth_first_search(UpperCamelCase_  ,			col + 1  ,			UpperCamelCase_  ,			UpperCamelCase_       )
        + depth_first_search(UpperCamelCase_  ,			col - 1  ,			UpperCamelCase_  ,			UpperCamelCase_       )
    )
  else:
    return 0






def 							lowerCAmelCase			(   UpperCamelCase_:				list[list[int]]       )							->				int:







  '''simple docstring'''







  _a					      =						set()

  _a					      =						0
  for row, line in enumerate(UpperCamelCase_       ):
    for col, item in enumerate(UpperCamelCase_       ):
      if item == 1 and (row, col) not in seen:
        # Maximizing the area
        _a					      =						max(UpperCamelCase_  ,			depth_first_search(UpperCamelCase_  ,			UpperCamelCase_  ,			UpperCamelCase_  ,			UpperCamelCase_       )       )
  return max_area


if __name__ == "__main__":
     import doctest

     print(find_max_area(matrix))  # Output -> 6
     doctest.testmod()


