




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

a_      :		Tuple							      =       logging.get_logger(__name__)


@add_end_docstrings(lowerCamelCase__				)
class   __UpperCamelCase       ( lowerCamelCase__				):






       def __init__(							self,		**lowerCAmelCase  ):



              """simple docstring"""







              super().__init__(**lowerCAmelCase  )

              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,		lowerCAmelCase,		**lowerCAmelCase  ):



              """simple docstring"""







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






       def      lowercase__     (							self,		**lowerCAmelCase  ):



              """simple docstring"""







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

              return preprocess_params, {}, {}






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase=None,		lowerCAmelCase="This is a photo of {}."  ):



              """simple docstring"""







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






       def      lowercase__     (							self,		lowerCAmelCase  ):



              """simple docstring"""







              lowerCamelCase_							=model_inputs.pop('''candidate_labels'''  )
              lowerCamelCase_							=model_inputs.pop('''text_inputs'''  )
              if isinstance(text_inputs[0],		lowerCAmelCase  ):
                     lowerCamelCase_							=text_inputs[0]
              else:
                     # Batching case.
                     lowerCamelCase_							=text_inputs[0][0]

              lowerCamelCase_							=self.model(**lowerCAmelCase,		**lowerCAmelCase  )

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






       def      lowercase__     (							self,		lowerCAmelCase  ):



              """simple docstring"""







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

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





'''simple docstring'''




from urllib.parse import quote

import pytest

from datasets.utils.hub import hf_hub_url




@pytest.mark.parametrize("""repo_id"""      ,      ["""canonical_dataset_name""", """org-name/dataset-name"""] )
@pytest.mark.parametrize("""path"""      ,      ["""filename.csv""", """filename with blanks.csv"""] )
@pytest.mark.parametrize("""revision"""      ,      [None, """v2"""] )
def 							lowerCamelCase	(      UpperCAmelCase__       :					int      ,      UpperCAmelCase__       :					Optional[int]      ,      UpperCAmelCase__       :					Optional[int] )			->      Optional[int]:
							lowercase_					:			Union[str, Any]										=       hf_hub_url(repo_id=UpperCAmelCase__      ,      path=UpperCAmelCase__      ,      revision=UpperCAmelCase__ )
							assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(UpperCAmelCase__ )}'''





