






"""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

lowercase_				     =     logging.get_logger(__name__)


@add_end_docstrings(UpperCAmelCase__						)
class 					snake_case		(							UpperCAmelCase__						):


   '''simple docstring'''

   def __init__(	self :     Dict,       **_lowerCamelCase :     int  ):

     '''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 :     int,       _lowerCamelCase :     Dict,       **_lowerCamelCase :     str  ):

     '''simple docstring'''
     return super().__call__(_a,       **_a  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     List[Any],       **_lowerCamelCase :     Tuple  ):

     '''simple docstring'''
     __A									= {}
     if "candidate_labels" in kwargs:
       __A									= kwargs['''candidate_labels''']
     if "hypothesis_template" in kwargs:
       __A									= kwargs['''hypothesis_template''']

     return preprocess_params, {}, {}


   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict,       _lowerCamelCase :     int,       _lowerCamelCase :     Optional[int]=None,       _lowerCamelCase :     Optional[Any]="This is a photo of {}."  ):

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


   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any],       _lowerCamelCase :     Tuple  ):

     '''simple docstring'''
     __A									= model_inputs.pop('''candidate_labels'''  )
     __A									= model_inputs.pop('''text_inputs'''  )
     if isinstance(text_inputs[0],       _a  ):
       __A									= text_inputs[0]
     else:
       # Batching case.
       __A									= text_inputs[0][0]

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

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






   def 				_SCREAMING_SNAKE_CASE				(	self :     str,       _lowerCamelCase :     Optional[Any]  ):

     '''simple docstring'''
     __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(_a,       _a  ):
         __A									= [scores]
     elif self.framework == "tf":
       __A									= stable_softmax(_a,       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(_a,       _a  ),       key=lambda _lowerCamelCase  : -x[0]  )
     ]
     return result










"""simple docstring"""




import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path

import torch_xla.distributed.xla_multiprocessing as xmp



def     a__ (				)						->					Union[str, Any]:
			lowerCamelCase			      =					ArgumentParser(
			    description=(
			        """PyTorch TPU distributed training launch """
			        """helper utility that will spawn up """
			        """multiple distributed processes"""
			    )				)

			# Optional arguments for the launch helper
			parser.add_argument("""--num_cores"""       , type=snake_case__       , default=1       , help="""Number of TPU cores to use (1 or 8)."""				)

			# positional
			parser.add_argument(
			    """training_script"""       , type=snake_case__       , help=(
			        """The full path to the single TPU training """
			        """program/script to be launched in parallel, """
			        """followed by all the arguments for the """
			        """training script"""
			    )       , )

			# rest from the training program
			parser.add_argument("""training_script_args"""       , nargs=snake_case__				)

			return parser.parse_args()



def     a__ (				)						->					List[str]:
			lowerCamelCase			      =					parse_args()

			# Import training_script as a module.
			lowerCamelCase			      =					Path(args.training_script				)
			sys.path.append(str(script_fpath.parent.resolve()				)				)
			lowerCamelCase			      =					script_fpath.stem
			lowerCamelCase			      =					importlib.import_module(snake_case__				)

			# Patch sys.argv
			lowerCamelCase			      =					[args.training_script] + args.training_script_args + ["""--tpu_num_cores""", str(args.num_cores				)]
			xmp.spawn(mod._mp_fn       , args=()       , nprocs=args.num_cores				)


if __name__ == "__main__":
					main()



