
from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
		from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
		from ..tf_utils import stable_softmax

lowercase						:      Tuple									= logging.get_logger(__name__)




@add_end_docstrings(__UpperCAmelCase)
class 				lowerCamelCase__							(       __UpperCAmelCase):




	'''simple docstring'''




	def __init__(      self	:Tuple  ,     **a	:Any		)	->				Dict:
								super().__init__(**__SCREAMING_SNAKE_CASE		)

								requires_backends(self  ,     "vision"		)
								self.check_model_type(
								    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
								    if self.framework == "tf"
								    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING		)







	def __call__(      self	:Union[str, Any]  ,     a	:Union[str, List[str], "Image", List["Image"]]  ,     **a	:Optional[Any]		)	->				int:
								return super().__call__(__SCREAMING_SNAKE_CASE  ,     **__SCREAMING_SNAKE_CASE		)







	def      _lowerCamelCase       (      self	:Union[str, Any]  ,     **a	:Any		)	->				Tuple:
								__UpperCamelCase			:     List[str]         =      {}
								if "candidate_labels" in kwargs:
															__UpperCamelCase			:     int         =      kwargs["candidate_labels"]
								if "hypothesis_template" in kwargs:
															__UpperCamelCase			:     str         =      kwargs["hypothesis_template"]

								return preprocess_params, {}, {}







	def      _lowerCamelCase       (      self	:Tuple  ,     a	:int  ,     a	:str=None  ,     a	:Optional[int]="This is a photo of {}."		)	->				str:
								__UpperCamelCase			:     str         =      load_image(__SCREAMING_SNAKE_CASE		)
								__UpperCamelCase			:     int         =      self.image_processor(images=[image]  ,     return_tensors=self.framework		)
								__UpperCamelCase			:     Dict         =      candidate_labels
								__UpperCamelCase			:     Dict         =      [hypothesis_template.format(__SCREAMING_SNAKE_CASE		) for x in candidate_labels]
								__UpperCamelCase			:     Union[str, Any]         =      self.tokenizer(__SCREAMING_SNAKE_CASE  ,     return_tensors=self.framework  ,     padding=__SCREAMING_SNAKE_CASE		)
								__UpperCamelCase			:     Union[str, Any]         =      [text_inputs]
								return inputs







	def      _lowerCamelCase       (      self	:Optional[int]  ,     a	:Dict		)	->				List[Any]:
								__UpperCamelCase			:     Tuple         =      model_inputs.pop("candidate_labels"		)
								__UpperCamelCase			:     int         =      model_inputs.pop("text_inputs"		)
								if isinstance(text_inputs[0]  ,     __SCREAMING_SNAKE_CASE		):
															__UpperCamelCase			:     List[Any]         =      text_inputs[0]
								else:
															# Batching case.
															__UpperCamelCase			:     str         =      text_inputs[0][0]

								__UpperCamelCase			:     Tuple         =      self.model(**__SCREAMING_SNAKE_CASE  ,     **__SCREAMING_SNAKE_CASE		)

								__UpperCamelCase			:     List[Any]         =      {
								    "candidate_labels": candidate_labels,
								    "logits": outputs.logits_per_image,
								}
								return model_outputs







	def      _lowerCamelCase       (      self	:Union[str, Any]  ,     a	:Union[str, Any]		)	->				List[str]:
								__UpperCamelCase			:     Optional[int]         =      model_outputs.pop("candidate_labels"		)
								__UpperCamelCase			:     Dict         =      model_outputs["logits"][0]
								if self.framework == "pt":
															__UpperCamelCase			:     str         =      logits.softmax(dim=-1		).squeeze(-1		)
															__UpperCamelCase			:     Optional[int]         =      probs.tolist()
															if not isinstance(__SCREAMING_SNAKE_CASE  ,     __SCREAMING_SNAKE_CASE		):
																						__UpperCamelCase			:     Optional[Any]         =      [scores]
								elif self.framework == "tf":
															__UpperCamelCase			:     List[str]         =      stable_softmax(__SCREAMING_SNAKE_CASE  ,     axis=-1		)
															__UpperCamelCase			:     Optional[Any]         =      probs.numpy().tolist()
								else:
															raise ValueError(f'Unsupported framework: {self.framework}'		)

								__UpperCamelCase			:     Dict         =      [
								    {"score": score, "label": candidate_label}
								    for score, candidate_label in sorted(zip(__SCREAMING_SNAKE_CASE  ,     __SCREAMING_SNAKE_CASE		)  ,     key=lambda a		: -x[0]		)
								]
								return result

import argparse

import torch

from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging


logging.set_verbosity_info()




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    Dict		,						_lowerCamelCase				:    Tuple		,						_lowerCamelCase				:    Union[str, Any])      ->					List[Any]:






							'''simple docstring'''





							__UpperCamelCase			:     Tuple         =      BertConfig.from_json_file(_lowerCamelCase)
							print(F'Building PyTorch model from configuration: {config}')
							__UpperCamelCase			:     List[Any]         =      BertForPreTraining(_lowerCamelCase)

							# Load weights from tf checkpoint
							load_tf_weights_in_bert(_lowerCamelCase		,						_lowerCamelCase		,						_lowerCamelCase)

							# Save pytorch-model
							print(F'Save PyTorch model to {pytorch_dump_path}')
							torch.save(model.state_dict()		,						_lowerCamelCase)


if __name__ == "__main__":
		lowercase						:      Any									= 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(
		    '--bert_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.'
		)
		lowercase						:      Tuple									= parser.parse_args()
		convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)