





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

_lowerCamelCase 					=      logging.get_logger(__name__)




@add_end_docstrings(UpperCamelCase__     )
class 	UpperCamelCase_							(  UpperCamelCase__     ):


							def __init__(				self     :List[str]				,					**__A     :Optional[int]		) -> Tuple:



									"""simple docstring"""



									super().__init__(**__A		)

									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     :Optional[Any]				,					__A     :Union[str, List[str], "Image", List["Image"]]				,					**__A     :Any		) -> Tuple:



									"""simple docstring"""



									return super().__call__(__A				,					**__A		)


							def   _snake_case	(				self     :Tuple				,					**__A     :List[Any]		) -> int:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   {}
									if "candidate_labels" in kwargs:
											SCREAMING_SNAKE_CASE__								=   kwargs["""candidate_labels"""]
									if "hypothesis_template" in kwargs:
											SCREAMING_SNAKE_CASE__								=   kwargs["""hypothesis_template"""]

									return preprocess_params, {}, {}


							def   _snake_case	(				self     :List[Any]				,					__A     :Optional[Any]				,					__A     :str=None				,					__A     :Dict="This is a photo of {}."		) -> List[str]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   load_image(__A		)
									SCREAMING_SNAKE_CASE__								=   self.image_processor(images=[image]				,					return_tensors=self.framework		)
									SCREAMING_SNAKE_CASE__								=   candidate_labels
									SCREAMING_SNAKE_CASE__								=   [hypothesis_template.format(__A		) for x in candidate_labels]
									SCREAMING_SNAKE_CASE__								=   self.tokenizer(__A				,					return_tensors=self.framework				,					padding=__A		)
									SCREAMING_SNAKE_CASE__								=   [text_inputs]
									return inputs


							def   _snake_case	(				self     :str				,					__A     :Dict		) -> Union[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   model_inputs.pop("""candidate_labels"""		)
									SCREAMING_SNAKE_CASE__								=   model_inputs.pop("""text_inputs"""		)
									if isinstance(text_inputs[0]				,					__A		):
											SCREAMING_SNAKE_CASE__								=   text_inputs[0]
									else:
											# Batching case.
											SCREAMING_SNAKE_CASE__								=   text_inputs[0][0]

									SCREAMING_SNAKE_CASE__								=   self.model(**__A				,					**__A		)

									SCREAMING_SNAKE_CASE__								=   {
									    """candidate_labels""": candidate_labels,
									    """logits""": outputs.logits_per_image,
									}
									return model_outputs


							def   _snake_case	(				self     :Dict				,					__A     :Union[str, Any]		) -> List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   model_outputs.pop("""candidate_labels"""		)
									SCREAMING_SNAKE_CASE__								=   model_outputs["""logits"""][0]
									if self.framework == "pt":
											SCREAMING_SNAKE_CASE__								=   logits.softmax(dim=-1		).squeeze(-1		)
											SCREAMING_SNAKE_CASE__								=   probs.tolist()
											if not isinstance(__A				,					__A		):
													SCREAMING_SNAKE_CASE__								=   [scores]
									elif self.framework == "tf":
											SCREAMING_SNAKE_CASE__								=   stable_softmax(__A				,					axis=-1		)
											SCREAMING_SNAKE_CASE__								=   probs.numpy().tolist()
									else:
											raise ValueError(f'''Unsupported framework: {self.framework}'''		)

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



# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

from .config import config_command_parser
from .config_args import default_config_file, load_config_from_file  # noqa: F401
from .default import default_command_parser
from .update import update_command_parser






def 	__lowerCamelCase						(							lowerCamelCase__		:						Any=None      ):





			'''simple docstring'''




			lowerCamelCase    		=  argparse.ArgumentParser(add_help=lowerCamelCase__  ,							allow_abbrev=lowerCamelCase__      )
			# The main config parser
			lowerCamelCase    		=  config_command_parser(lowerCamelCase__      )
			# The subparser to add commands to
			lowerCamelCase    		=  config_parser.add_subparsers(title="""subcommands"""  ,							dest="""subcommand"""      )

			# Then add other parsers with the parent parser
			default_command_parser(lowerCamelCase__  ,							parents=[parent_parser]      )
			update_command_parser(lowerCamelCase__  ,							parents=[parent_parser]      )

			return config_parser






def 	__lowerCamelCase						(							):





			'''simple docstring'''




			lowerCamelCase    		=  get_config_parser()
			lowerCamelCase    		=  config_parser.parse_args()

			if not hasattr(lowerCamelCase__  ,							"""func"""      ):
						config_parser.print_help()
						exit(1      )

			# Run
			args.func(lowerCamelCase__      )


if __name__ == "__main__":
		main()

