


'''simple docstring'''



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

_lowercase    :    List[Any]			     =  logging.get_logger(__name__)






@add_end_docstrings(SCREAMING_SNAKE_CASE__ )
class  UpperCamelCase__(     SCREAMING_SNAKE_CASE__ ):




				def __init__(	self    :				str   ,					**lowerCAmelCase    :				Optional[int]   )->  int:

										"""simple docstring"""




										super().__init__(**snake_case__   )

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

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




				def __call__(	self    :				Tuple   ,					lowerCAmelCase    :				int   ,					lowerCAmelCase    :				Optional[int] = None   ,					**lowerCAmelCase    :				Dict   ,					)->  str:

										"""simple docstring"""




										if "text_queries" in kwargs:
																UpperCAmelCase         =			kwargs.pop('''text_queries'''   )

										if isinstance(snake_case__   ,					(str, Image.Image)   ):
																UpperCAmelCase         =			{"image": image, "candidate_labels": candidate_labels}
										else:
																UpperCAmelCase         =			image
										UpperCAmelCase         =			super().__call__(snake_case__   ,					**snake_case__   )
										return results




				def   a__(	self    :				Any   ,					**lowerCAmelCase    :				Dict   )->  Tuple:

										"""simple docstring"""




										UpperCAmelCase         =			{}
										if "threshold" in kwargs:
																UpperCAmelCase         =			kwargs["threshold"]
										if "top_k" in kwargs:
																UpperCAmelCase         =			kwargs["top_k"]
										return {}, {}, postprocess_params




				def   a__(	self    :				Tuple   ,					lowerCAmelCase    :				int   )->  Any:

										"""simple docstring"""




										UpperCAmelCase         =			load_image(inputs['''image''']   )
										UpperCAmelCase         =			inputs["candidate_labels"]
										if isinstance(snake_case__   ,					snake_case__   ):
																UpperCAmelCase         =			candidate_labels.split(''','''   )

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




				def   a__(	self    :				Any   ,					lowerCAmelCase    :				Dict   )->  Dict:

										"""simple docstring"""




										UpperCAmelCase         =			model_inputs.pop('''target_size'''   )
										UpperCAmelCase         =			model_inputs.pop('''candidate_label'''   )
										UpperCAmelCase         =			model_inputs.pop('''is_last'''   )

										UpperCAmelCase         =			self.model(**snake_case__   )

										UpperCAmelCase         =			{"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs}
										return model_outputs




				def   a__(	self    :				int   ,					lowerCAmelCase    :				Optional[int]   ,					lowerCAmelCase    :				Tuple=0.1   ,					lowerCAmelCase    :				List[Any]=None   )->  Union[str, Any]:

										"""simple docstring"""




										UpperCAmelCase         =			[]
										for model_output in model_outputs:
																UpperCAmelCase         =			model_output["candidate_label"]
																UpperCAmelCase         =			BaseModelOutput(snake_case__   )
																UpperCAmelCase         =			self.image_processor.post_process_object_detection(
																    outputs=snake_case__   ,					threshold=snake_case__   ,					target_sizes=model_output['''target_size''']   )[0]

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

																						UpperCAmelCase         =			{"score": score, "label": label, "box": box}
																						results.append(snake_case__   )

										UpperCAmelCase         =			sorted(snake_case__   ,					key=lambda lowerCAmelCase   : x["score"]   ,					reverse=snake_case__   )
										if top_k:
																UpperCAmelCase         =			results[:top_k]

										return results





				def   a__(	self    :				Optional[Any]   ,					lowerCAmelCase    :				Optional[Any]   )->  Optional[Any]:

										"""simple docstring"""




										if self.framework != "pt":
																raise ValueError('''The ZeroShotObjectDetectionPipeline is only available in PyTorch.'''   )
										UpperCAmelCase         =			box.int().tolist()
										UpperCAmelCase         =			{
										    "xmin": xmin,
										    "ymin": ymin,
										    "xmax": xmax,
										    "ymax": ymax,
										}
										return bbox









'''simple docstring'''



import argparse

from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird
from transformers.utils import logging


logging.set_verbosity_info()


def    lowerCamelCase__   ( A     :    List[Any]   ,     A     :    int   ,     A     :    List[str]   ,     A     :    Optional[int]  ):




						'''simple docstring'''






						UpperCAmelCase         =			BigBirdConfig.from_json_file(A  )
						print(f"""Building PyTorch model from configuration: {config}"""  )

						if is_trivia_qa:
												UpperCAmelCase         =			BigBirdForQuestionAnswering(A  )
						else:
												UpperCAmelCase         =			BigBirdForPreTraining(A  )

						# Load weights from tf checkpoint
						load_tf_weights_in_big_bird(A   ,     A   ,     is_trivia_qa=A  )

						# Save pytorch-model
						print(f"""Save PyTorch model to {pytorch_dump_path}"""  )
						model.save_pretrained(A  )


if __name__ == "__main__":
	_lowercase    :    List[str]			     =  argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
	)
	parser.add_argument(
	    """--big_bird_config_file""",
	    default=None,
	    type=str,
	    required=True,
	    help=(
	        """The config json file corresponding to the pre-trained BERT model. \n"""
	        """This specifies the model architecture."""
	    ),
	)
	parser.add_argument(
	    """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
	)
	parser.add_argument(
	    """--is_trivia_qa""", action="""store_true""", help="""Whether to convert a model with a trivia_qa head."""
	)
	_lowercase    :    Any			     =  parser.parse_args()
	convert_tf_checkpoint_to_pytorch(
	    args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa
	)





