




'''simple docstring'''
from argparse import ArgumentParser

from . import BaseTransformersCLICommand





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		str:
			return DownloadCommand(args.model       ,args.cache_dir       ,args.force       ,args.trust_remote_code     )






class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					@staticmethod
					def     __snake_case						(	_lowercase     :						ArgumentParser)    ->							Optional[Any]:
								A_									= parser.add_parser('download')
								download_parser.add_argument(
								    '--cache-dir'      ,       type=_lowercase      ,       default=_lowercase      ,       help='Path to location to store the models')
								download_parser.add_argument(
								    '--force'      ,       action='store_true'      ,       help='Force the model to be download even if already in cache-dir')
								download_parser.add_argument(
								    '--trust-remote-code'      ,       action='store_true'      ,       help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine'      ,       )
								download_parser.add_argument('model'      ,       type=_lowercase      ,       help='Name of the model to download')
								download_parser.set_defaults(func=_lowercase)



					def __init__(	self     :						Dict      ,       _lowercase     :						str      ,       _lowercase     :						str      ,       _lowercase     :						bool      ,       _lowercase     :						bool)    ->							Any:
								A_									= model
								A_									= cache
								A_									= force
								A_									= trust_remote_code



					def     __snake_case						(	self     :						str)    ->							List[str]:
								from ..models.auto import AutoModel, AutoTokenizer

								AutoModel.from_pretrained(
								    self._model      ,       cache_dir=self._cache      ,       force_download=self._force      ,       trust_remote_code=self._trust_remote_code)
								AutoTokenizer.from_pretrained(
								    self._model      ,       cache_dir=self._cache      ,       force_download=self._force      ,       trust_remote_code=self._trust_remote_code)










'''simple docstring'''
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

_SCREAMING_SNAKE_CASE			=						logging.get_logger(__name__)
@add_end_docstrings(lowerCAmelCase				)
class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					def __init__(	self     :						int      ,       **_lowercase     :						List[Any])    ->							Union[str, Any]:
								super().__init__(**_lowercase)

								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]      ,       _lowercase     :						Union[str, List[str], "Image", List["Image"]]      ,       **_lowercase     :						List[Any])    ->							Any:
								return super().__call__(_lowercase      ,       **_lowercase)



					def     __snake_case						(	self     :						int      ,       **_lowercase     :						Union[str, Any])    ->							Any:
								A_									= {}
								if "candidate_labels" in kwargs:
											A_									= kwargs['candidate_labels']
								if "hypothesis_template" in kwargs:
											A_									= kwargs['hypothesis_template']

								return preprocess_params, {}, {}



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



					def     __snake_case						(	self     :						Optional[int]      ,       _lowercase     :						Tuple)    ->							Optional[int]:
								A_									= model_inputs.pop('candidate_labels')
								A_									= model_inputs.pop('text_inputs')
								if isinstance(text_inputs[0]      ,       _lowercase):
											A_									= text_inputs[0]
								else:
											# Batching case.
											A_									= text_inputs[0][0]

								A_									= self.model(**_lowercase      ,       **_lowercase)

								A_									= {
								    'candidate_labels': candidate_labels,
								    'logits': outputs.logits_per_image,
								}
								return model_outputs



					def     __snake_case						(	self     :						List[str]      ,       _lowercase     :						int)    ->							Optional[int]:
								A_									= model_outputs.pop('candidate_labels')
								A_									= model_outputs['logits'][0]
								if self.framework == "pt":
											A_									= logits.softmax(dim=-1).squeeze(-1)
											A_									= probs.tolist()
											if not isinstance(_lowercase      ,       _lowercase):
														A_									= [scores]
								elif self.framework == "tf":
											A_									= stable_softmax(_lowercase      ,       axis=-1)
											A_									= probs.numpy().tolist()
								else:
											raise ValueError(F'Unsupported framework: {self.framework}')

								A_									= [
								    {'score': score, 'label': candidate_label}
								    for score, candidate_label in sorted(zip(_lowercase      ,       _lowercase)      ,       key=lambda _lowercase: -x[0])
								]
								return result




