


import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import GLPNImageProcessor





class   __a			(    unittest.TestCase      ):
 def __init__(   self				, lowerCAmelCase__				, lowerCAmelCase__=7				, lowerCAmelCase__=3				, lowerCAmelCase__=18				, lowerCAmelCase__=30				, lowerCAmelCase__=400				, lowerCAmelCase__=True				, lowerCAmelCase__=32				, lowerCAmelCase__=True				, )					->				Dict:




        '''simple docstring'''
        lowercase__:   Tuple  			=   parent
        lowercase__:   int  			=   batch_size
        lowercase__:   Optional[int]  			=   num_channels
        lowercase__:   List[str]  			=   image_size
        lowercase__:   List[Any]  			=   min_resolution
        lowercase__:   List[str]  			=   max_resolution
        lowercase__:   List[Any]  			=   do_resize
        lowercase__:   List[Any]  			=   size_divisor
        lowercase__:   Dict  			=   do_rescale
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Dict:




        '''simple docstring'''
        return {
            "do_resize": self.do_resize,
            "size_divisor": self.size_divisor,
            "do_rescale": self.do_rescale,
        }





@require_torch
@require_vision
class   __a			(    __UpperCamelCase       ,       unittest.TestCase      ):
 __lowercase :							Optional[Any]        = GLPNImageProcessor if is_vision_available() else None
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Tuple:




        '''simple docstring'''
        lowercase__:   List[Any]  			=   GLPNImageProcessingTester(self )
 @property
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				int:




        '''simple docstring'''
        return self.image_processor_tester.prepare_image_processor_dict()
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				List[Any]:




        '''simple docstring'''
        lowercase__:   List[Any]  			=   self.image_processing_class(**self.image_processor_dict )
        self.assertTrue(hasattr(lowerCAmelCase__				, 'do_resize' ) )
        self.assertTrue(hasattr(lowerCAmelCase__				, 'size_divisor' ) )
        self.assertTrue(hasattr(lowerCAmelCase__				, 'resample' ) )
        self.assertTrue(hasattr(lowerCAmelCase__				, 'do_rescale' ) )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Tuple:




        '''simple docstring'''
        pass
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Optional[Any]:




        '''simple docstring'''
        # Initialize image_processing
        lowercase__:   Optional[int]  			=   self.image_processing_class(**self.image_processor_dict )
        # create random PIL images
        lowercase__:   List[Any]  			=   prepare_image_inputs(self.image_processor_tester				, equal_resolution=lowerCAmelCase__ )
        for image in image_inputs:
               self.assertIsInstance(lowerCAmelCase__				, Image.Image )

        # Test not batched input (GLPNImageProcessor doesn't support batching)
        lowercase__:   Union[str, Any]  			=   image_processing(image_inputs[0]				, return_tensors='pt' ).pixel_values
        self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
        self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Dict:




        '''simple docstring'''
        # Initialize image_processing
        lowercase__:   List[str]  			=   self.image_processing_class(**self.image_processor_dict )
        # create random numpy tensors
        lowercase__:   List[Any]  			=   prepare_image_inputs(self.image_processor_tester				, equal_resolution=lowerCAmelCase__				, numpify=lowerCAmelCase__ )
        for image in image_inputs:
               self.assertIsInstance(lowerCAmelCase__				, np.ndarray )

        # Test not batched input (GLPNImageProcessor doesn't support batching)
        lowercase__:   Tuple  			=   image_processing(image_inputs[0]				, return_tensors='pt' ).pixel_values
        self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
        self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Dict:




        '''simple docstring'''
        # Initialize image_processing
        lowercase__:   int  			=   self.image_processing_class(**self.image_processor_dict )
        # create random PyTorch tensors
        lowercase__:   List[Any]  			=   prepare_image_inputs(self.image_processor_tester				, equal_resolution=lowerCAmelCase__				, torchify=lowerCAmelCase__ )
        for image in image_inputs:
               self.assertIsInstance(lowerCAmelCase__				, torch.Tensor )

        # Test not batched input (GLPNImageProcessor doesn't support batching)
        lowercase__:   Tuple  			=   image_processing(image_inputs[0]				, return_tensors='pt' ).pixel_values
        self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
        self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )






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   __a			(    __UpperCamelCase      ):
 def __init__(   self				, **lowerCAmelCase__ )					->				List[str]:




        '''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__ )					->				Optional[Any]:




        '''simple docstring'''
        return super().__call__(lowerCAmelCase__				, **lowerCAmelCase__ )
 def 		SCREAMING_SNAKE_CASE__   (   self				, **lowerCAmelCase__ )					->				Dict:




        '''simple docstring'''
        lowercase__:   int  			=   {}
        if "candidate_labels" in kwargs:
               lowercase__:   Dict  			=   kwargs['candidate_labels']
        if "hypothesis_template" in kwargs:
               lowercase__:   List[Any]  			=   kwargs['hypothesis_template']

        return preprocess_params, {}, {}
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__=None				, lowerCAmelCase__="This is a photo of {}." )					->				int:




        '''simple docstring'''
        lowercase__:   Optional[int]  			=   load_image(lowerCAmelCase__ )
        lowercase__:   Dict  			=   self.image_processor(images=[image]				, return_tensors=self.framework )
        lowercase__:   Tuple  			=   candidate_labels
        lowercase__:   List[str]  			=   [hypothesis_template.format(lowerCAmelCase__ ) for x in candidate_labels]
        lowercase__:   Optional[Any]  			=   self.tokenizer(lowerCAmelCase__				, return_tensors=self.framework				, padding=lowerCAmelCase__ )
        lowercase__:   str  			=   [text_inputs]
        return inputs
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				int:




        '''simple docstring'''
        lowercase__:   str  			=   model_inputs.pop('candidate_labels' )
        lowercase__:   List[str]  			=   model_inputs.pop('text_inputs' )
        if isinstance(text_inputs[0]				, lowerCAmelCase__ ):
               lowercase__:   Any  			=   text_inputs[0]
        else:
               # Batching case.
               lowercase__:   Optional[int]  			=   text_inputs[0][0]

        lowercase__:   Tuple  			=   self.model(**lowerCAmelCase__				, **lowerCAmelCase__ )

        lowercase__:   Any  			=   {
            'candidate_labels': candidate_labels,
            'logits': outputs.logits_per_image,
        }
        return model_outputs
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				Union[str, Any]:




        '''simple docstring'''
        lowercase__:   Tuple  			=   model_outputs.pop('candidate_labels' )
        lowercase__:   Dict  			=   model_outputs['logits'][0]
        if self.framework == "pt":
               lowercase__:   Optional[int]  			=   logits.softmax(dim=-1 ).squeeze(-1 )
               lowercase__:   Dict  			=   probs.tolist()
               if not isinstance(lowerCAmelCase__				, lowerCAmelCase__ ):
                      lowercase__:   Dict  			=   [scores]
        elif self.framework == "tf":
               lowercase__:   Optional[int]  			=   stable_softmax(lowerCAmelCase__				, axis=-1 )
               lowercase__:   Union[str, Any]  			=   probs.numpy().tolist()
        else:
               raise ValueError(F'Unsupported framework: {self.framework}' )

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


