






'''simple docstring'''





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_tf_available():
     import tensorflow as tf

     from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
     from ..tf_utils import stable_softmax

if is_torch_available():
     from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

lowerCamelCase__							=     logging.get_logger(__name__)




@add_end_docstrings(lowercase_)
class 			snake_case__   (							lowercase_):

       '''simple docstring'''



       def __init__(							self			,						*a__			,						**a__    ) ->      int:






            '''simple docstring'''





            super().__init__(*a__			,						**a__    )
            requires_backends(self			,						"""vision"""    )
            self.check_model_type(
                TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
                if self.framework == """tf"""
                else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING    )



       def 					__lowercase						(							self			,						a__=None    ) ->      Any:






            '''simple docstring'''





            __snake_case			:Dict          =						{}
            if top_k is not None:
                 __snake_case			:Tuple          =						top_k
            return {}, {}, postprocess_params



       def __call__(							self			,						a__			,						**a__    ) ->      int:






            '''simple docstring'''





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



       def 					__lowercase						(							self			,						a__    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:int          =						load_image(a__    )
            __snake_case			:Any          =						self.image_processor(images=a__			,						return_tensors=self.framework    )
            return model_inputs



       def 					__lowercase						(							self			,						a__    ) ->      Any:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						self.model(**a__    )
            return model_outputs



       def 					__lowercase						(							self			,						a__			,						a__=5    ) ->      Optional[Any]:






            '''simple docstring'''





            if top_k > self.model.config.num_labels:
                 __snake_case			:List[Any]          =						self.model.config.num_labels

            if self.framework == "pt":
                 __snake_case			:Optional[int]          =						model_outputs.logits.softmax(-1    )[0]
                 __snake_case			:List[str]          =						probs.topk(a__    )
            elif self.framework == "tf":
                 __snake_case			:Any          =						stable_softmax(model_outputs.logits			,						axis=-1    )[0]
                 __snake_case			:Dict          =						tf.math.top_k(a__			,						k=a__    )
                 __snake_case			:Dict          =						topk.values.numpy(), topk.indices.numpy()
            else:
                 raise ValueError(F'''Unsupported framework: {self.framework}'''    )

            __snake_case			:Dict          =						scores.tolist()
            __snake_case			:List[Any]          =						ids.tolist()
            return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(a__			,						a__    )]










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 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''



       def __init__(							self			,						a__			,						a__=7			,						a__=3			,						a__=18			,						a__=30			,						a__=4_00			,						a__=True			,						a__=32			,						a__=True			,						) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:List[Any]          =						parent
            __snake_case			:Dict          =						batch_size
            __snake_case			:Optional[Any]          =						num_channels
            __snake_case			:Dict          =						image_size
            __snake_case			:Dict          =						min_resolution
            __snake_case			:Dict          =						max_resolution
            __snake_case			:List[Any]          =						do_resize
            __snake_case			:Dict          =						size_divisor
            __snake_case			:Union[str, Any]          =						do_rescale



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            return {
                "do_resize": self.do_resize,
                "size_divisor": self.size_divisor,
                "do_rescale": self.do_rescale,
            }




@require_torch
@require_vision
class 			snake_case__   (							lowercase_	,    unittest.TestCase):

       '''simple docstring'''
       lowerCamelCase							:				Tuple 				= GLPNImageProcessor if is_vision_available() else None



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:Dict          =						GLPNImageProcessingTester(self    )



       @property
       def 					__lowercase						(							self    ) ->      Optional[int]:






            '''simple docstring'''





            return self.image_processor_tester.prepare_image_processor_dict()



       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:Optional[Any]          =						self.image_processing_class(**self.image_processor_dict    )
            self.assertTrue(hasattr(a__			,						"""do_resize"""    )    )
            self.assertTrue(hasattr(a__			,						"""size_divisor"""    )    )
            self.assertTrue(hasattr(a__			,						"""resample"""    )    )
            self.assertTrue(hasattr(a__			,						"""do_rescale"""    )    )



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            pass



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            __snake_case			:int          =						self.image_processing_class(**self.image_processor_dict    )
            # create random PIL images
            __snake_case			:Optional[Any]          =						prepare_image_inputs(self.image_processor_tester			,						equal_resolution=a__    )
            for image in image_inputs:
                 self.assertIsInstance(a__			,						Image.Image    )

            # Test not batched input (GLPNImageProcessor doesn't support batching)
            __snake_case			: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 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:int          =						self.image_processing_class(**self.image_processor_dict    )
            # create random numpy tensors
            __snake_case			:List[Any]          =						prepare_image_inputs(self.image_processor_tester			,						equal_resolution=a__			,						numpify=a__    )
            for image in image_inputs:
                 self.assertIsInstance(a__			,						np.ndarray    )

            # Test not batched input (GLPNImageProcessor doesn't support batching)
            __snake_case			:int          =						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 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            __snake_case			:Tuple          =						self.image_processing_class(**self.image_processor_dict    )
            # create random PyTorch tensors
            __snake_case			:Optional[int]          =						prepare_image_inputs(self.image_processor_tester			,						equal_resolution=a__			,						torchify=a__    )
            for image in image_inputs:
                 self.assertIsInstance(a__			,						torch.Tensor    )

            # Test not batched input (GLPNImageProcessor doesn't support batching)
            __snake_case			:List[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    )


