






from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
							from PIL import Image

							from ..image_utils import load_image

if is_torch_available():
							import torch

							from transformers.modeling_outputs import BaseModelOutput

							from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

UpperCamelCase								=		logging.get_logger(__name__)

@add_end_docstrings(__snake_case			)
class 				lowerCAmelCase_	(		__snake_case			):


				def __init__(					self ,						**_lowerCAmelCase      ):
											super().__init__(**_lowerCAmelCase      )

											if self.framework == "tf":
																		raise ValueError(F"""The {self.__class__} is only available in PyTorch."""      )

											requires_backends(self ,						'vision'      )
											self.check_model_type(_lowerCAmelCase      )


				def __call__(					self ,						_lowerCAmelCase ,						_lowerCAmelCase = None ,						**_lowerCAmelCase ,						):
											if "text_queries" in kwargs:
																		_lowercase							:   Union[str, Any] 							=   kwargs.pop('text_queries'      )

											if isinstance(_lowerCAmelCase ,						(str, Image.Image)      ):
																		_lowercase							:   List[Any] 							=   {'image': image, 'candidate_labels': candidate_labels}
											else:
																		_lowercase							:   Union[str, Any] 							=   image
											_lowercase							:   Dict 							=   super().__call__(_lowerCAmelCase ,						**_lowerCAmelCase      )
											return results


				def 						__a					(					self ,						**_lowerCAmelCase      ):
											_lowercase							:   Optional[int] 							=   {}
											if "threshold" in kwargs:
																		_lowercase							:   Dict 							=   kwargs['threshold']
											if "top_k" in kwargs:
																		_lowercase							:   int 							=   kwargs['top_k']
											return {}, {}, postprocess_params


				def 						__a					(					self ,						_lowerCAmelCase      ):
											_lowercase							:   Dict 							=   load_image(inputs['image']      )
											_lowercase							:   Any 							=   inputs['candidate_labels']
											if isinstance(_lowerCAmelCase ,						_lowerCAmelCase      ):
																		_lowercase							:   Tuple 							=   candidate_labels.split(','      )

											_lowercase							:   int 							=   torch.tensor([[image.height, image.width]] ,						dtype=torch.intaa      )
											for i, candidate_label in enumerate(_lowerCAmelCase      ):
																		_lowercase							:   Union[str, Any] 							=   self.tokenizer(_lowerCAmelCase ,						return_tensors=self.framework      )
																		_lowercase							:   Union[str, Any] 							=   self.image_processor(_lowerCAmelCase ,						return_tensors=self.framework      )
																		yield {
																		    "is_last": i == len(_lowerCAmelCase      ) - 1,
																		    "target_size": target_size,
																		    "candidate_label": candidate_label,
																		    **text_inputs,
																		    **image_features,
																		}


				def 						__a					(					self ,						_lowerCAmelCase      ):
											_lowercase							:   Dict 							=   model_inputs.pop('target_size'      )
											_lowercase							:   Optional[Any] 							=   model_inputs.pop('candidate_label'      )
											_lowercase							:   int 							=   model_inputs.pop('is_last'      )

											_lowercase							:   Dict 							=   self.model(**_lowerCAmelCase      )

											_lowercase							:   Dict 							=   {'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs}
											return model_outputs


				def 						__a					(					self ,						_lowerCAmelCase ,						_lowerCAmelCase=0.1 ,						_lowerCAmelCase=None      ):
											_lowercase							:   List[Any] 							=   []
											for model_output in model_outputs:
																		_lowercase							:   List[str] 							=   model_output['candidate_label']
																		_lowercase							:   Optional[int] 							=   BaseModelOutput(_lowerCAmelCase      )
																		_lowercase							:   List[str] 							=   self.image_processor.post_process_object_detection(
																		    outputs=_lowerCAmelCase ,						threshold=_lowerCAmelCase ,						target_sizes=model_output['target_size']      )[0]

																		for index in outputs["scores"].nonzero():
																									_lowercase							:   Tuple 							=   outputs['scores'][index].item()
																									_lowercase							:   Any 							=   self._get_bounding_box(outputs['boxes'][index][0]      )

																									_lowercase							:   Dict 							=   {'score': score, 'label': label, 'box': box}
																									results.append(_lowerCAmelCase      )

											_lowercase							:   List[str] 							=   sorted(_lowerCAmelCase ,						key=lambda _lowerCAmelCase      : x["score"] ,						reverse=_lowerCAmelCase      )
											if top_k:
																		_lowercase							:   List[Any] 							=   results[:top_k]

											return results


				def 						__a					(					self ,						_lowerCAmelCase      ):
											if self.framework != "pt":
																		raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.'      )
											_lowercase							,							_lowercase							,							_lowercase							,							_lowercase							:   Optional[Any] 							=   box.int().tolist()
											_lowercase							:   Dict 							=   {
											    'xmin': xmin,
											    'ymin': ymin,
											    'xmax': xmax,
											    'ymax': ymax,
											}
											return bbox





import argparse
import json

import numpy
import torch

from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()



def 	__A		(      _A				,					_A       ):



 """simple docstring"""


 __a							=	torch.load(_A				,					map_location="cpu"       )

 __a							=	chkpt["model"]

 # We have the base model one level deeper than the original XLM repository
 __a							=	{}
 for k, v in state_dict.items():
  if "pred_layer" in k:
   __a							=	v
  else:
   __a							=	v

 __a							=	chkpt["params"]
 __a							=	{n: v for n, v in config.items() if not isinstance(_A				,					(torch.FloatTensor, numpy.ndarray)       )}

 __a							=	chkpt["dico_word2id"]
 __a							=	{s + "</w>" if s.find("@@"       ) == -1 and i > 13 else s.replace("@@"				,					""       ): i for s, i in vocab.items()}

 # Save pytorch-model
 __a							=	pytorch_dump_folder_path + "/" + WEIGHTS_NAME
 __a							=	pytorch_dump_folder_path + "/" + CONFIG_NAME
 __a							=	pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"]

 print(f"""Save PyTorch model to {pytorch_weights_dump_path}"""       )
 torch.save(_A				,					_A       )

 print(f"""Save configuration file to {pytorch_config_dump_path}"""       )
 with open(_A				,					"w"				,					encoding="utf-8"       ) as f:
  f.write(json.dumps(_A				,					indent=2       ) + "\n"       )

 print(f"""Save vocab file to {pytorch_config_dump_path}"""       )
 with open(_A				,					"w"				,					encoding="utf-8"       ) as f:
  f.write(json.dumps(_A				,					indent=2       ) + "\n"       )


if __name__ == "__main__":
  SCREAMING_SNAKE_CASE			:						Union[str, Any]				  =		argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      """--xlm_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump."""
  )
  parser.add_argument(
      """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
  )
  SCREAMING_SNAKE_CASE			:						Any				  =		parser.parse_args()
  convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)


