'''simple docstring'''

import unittest

import numpy as np

from transformers.testing_utils import is_flaky, 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 DonutImageProcessor



class       UpperCAmelCase  (						unittest.TestCase ):





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase=7     ,       __lowerCAmelCase=3     ,       __lowerCAmelCase=18     ,       __lowerCAmelCase=30     ,       __lowerCAmelCase=400     ,       __lowerCAmelCase=True     ,       __lowerCAmelCase=None     ,       __lowerCAmelCase=True     ,       __lowerCAmelCase=False     ,       __lowerCAmelCase=True     ,       __lowerCAmelCase=True     ,       __lowerCAmelCase=[0.5, 0.5, 0.5]     ,       __lowerCAmelCase=[0.5, 0.5, 0.5]     ,       )  ->  Union[str, Any]:
        lowercase__    :   str						= parent
        lowercase__    :   Union[str, Any]						= batch_size
        lowercase__    :   List[str]						= num_channels
        lowercase__    :   Dict						= image_size
        lowercase__    :   int						= min_resolution
        lowercase__    :   int						= max_resolution
        lowercase__    :   str						= do_resize
        lowercase__    :   List[Any]						= size if size is not None else {'''height''': 18, '''width''': 20}
        lowercase__    :   Tuple						= do_thumbnail
        lowercase__    :   Dict						= do_align_axis
        lowercase__    :   str						= do_pad
        lowercase__    :   str						= do_normalize
        lowercase__    :   Any						= image_mean
        lowercase__    :   str						= image_std


       def _lowerCAmelCase(						self			)  ->  List[Any]:
        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_thumbnail": self.do_thumbnail,
            "do_align_long_axis": self.do_align_axis,
            "do_pad": self.do_pad,
            "do_normalize": self.do_normalize,
            "image_mean": self.image_mean,
            "image_std": self.image_std,
        }



@require_torch
@require_vision
class       UpperCAmelCase  (						a__   ,						unittest.TestCase ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   DonutImageProcessor if is_vision_available() else None

       def _lowerCAmelCase(						self			)  ->  List[str]:
        lowercase__    :   List[Any]						= DonutImageProcessingTester(self			)

       @property
       def _lowerCAmelCase(						self			)  ->  List[Any]:
        return self.image_processor_tester.prepare_image_processor_dict()

       def _lowerCAmelCase(						self			)  ->  Dict:
        lowercase__    :   Optional[int]						= self.image_processing_class(**self.image_processor_dict			)
        self.assertTrue(hasattr(__lowerCAmelCase     ,       '''do_resize'''			)			)
        self.assertTrue(hasattr(__lowerCAmelCase     ,       '''size'''			)			)
        self.assertTrue(hasattr(__lowerCAmelCase     ,       '''do_thumbnail'''			)			)
        self.assertTrue(hasattr(__lowerCAmelCase     ,       '''do_align_long_axis'''			)			)
        self.assertTrue(hasattr(__lowerCAmelCase     ,       '''do_pad'''			)			)
        self.assertTrue(hasattr(__lowerCAmelCase     ,       '''do_normalize'''			)			)
        self.assertTrue(hasattr(__lowerCAmelCase     ,       '''image_mean'''			)			)
        self.assertTrue(hasattr(__lowerCAmelCase     ,       '''image_std'''			)			)

       def _lowerCAmelCase(						self			)  ->  Any:
        lowercase__    :   Dict						= self.image_processing_class.from_dict(self.image_processor_dict			)
        self.assertEqual(image_processor.size     ,       {'''height''': 18, '''width''': 20}			)

        lowercase__    :   Dict						= self.image_processing_class.from_dict(self.image_processor_dict     ,       size=42			)
        self.assertEqual(image_processor.size     ,       {'''height''': 42, '''width''': 42}			)

        # Previous config had dimensions in (width, height) order
        lowercase__    :   Optional[int]						= self.image_processing_class.from_dict(self.image_processor_dict     ,       size=(42, 84)			)
        self.assertEqual(image_processor.size     ,       {'''height''': 84, '''width''': 42}			)

       def _lowerCAmelCase(						self			)  ->  Optional[int]:
        pass

       @is_flaky()
       def _lowerCAmelCase(						self			)  ->  Tuple:
        # Initialize image_processing
        lowercase__    :   Optional[int]						= self.image_processing_class(**self.image_processor_dict			)
        # create random PIL images
        lowercase__    :   Optional[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
        lowercase__    :   Dict						= image_processing(image_inputs[0]     ,       return_tensors='''pt'''			).pixel_values
        self.assertEqual(
            encoded_images.shape     ,       (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size['''height'''],
                self.image_processor_tester.size['''width'''],
            )     ,       )

        # Test batched
        lowercase__    :   List[Any]						= image_processing(__lowerCAmelCase     ,       return_tensors='''pt'''			).pixel_values
        self.assertEqual(
            encoded_images.shape     ,       (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size['''height'''],
                self.image_processor_tester.size['''width'''],
            )     ,       )

       @is_flaky()
       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        # Initialize image_processing
        lowercase__    :   Tuple						= self.image_processing_class(**self.image_processor_dict			)
        # create random numpy tensors
        lowercase__    :   Optional[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
        lowercase__    :   List[Any]						= image_processing(image_inputs[0]     ,       return_tensors='''pt'''			).pixel_values
        self.assertEqual(
            encoded_images.shape     ,       (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size['''height'''],
                self.image_processor_tester.size['''width'''],
            )     ,       )

        # Test batched
        lowercase__    :   Dict						= image_processing(__lowerCAmelCase     ,       return_tensors='''pt'''			).pixel_values
        self.assertEqual(
            encoded_images.shape     ,       (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size['''height'''],
                self.image_processor_tester.size['''width'''],
            )     ,       )


       @is_flaky()
       def _lowerCAmelCase(						self			)  ->  str:
        # Initialize image_processing
        lowercase__    :   Union[str, Any]						= self.image_processing_class(**self.image_processor_dict			)
        # create random PyTorch tensors
        lowercase__    :   Dict						= 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
        lowercase__    :   List[Any]						= image_processing(image_inputs[0]     ,       return_tensors='''pt'''			).pixel_values
        self.assertEqual(
            encoded_images.shape     ,       (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size['''height'''],
                self.image_processor_tester.size['''width'''],
            )     ,       )

        # Test batched
        lowercase__    :   int						= image_processing(__lowerCAmelCase     ,       return_tensors='''pt'''			).pixel_values
        self.assertEqual(
            encoded_images.shape     ,       (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size['''height'''],
                self.image_processor_tester.size['''width'''],
            )     ,       )


'''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:			Optional[Any]	       =       logging.get_logger(__name__)



@add_end_docstrings(a__ )
class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       def __init__(						self     ,       **__lowerCAmelCase			)  ->  int:
        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			)  ->  List[str]:
        return super().__call__(__lowerCAmelCase     ,       **__lowerCAmelCase			)

       def _lowerCAmelCase(						self     ,       **__lowerCAmelCase			)  ->  Optional[Any]:
        lowercase__    :   str						= {}
        if "candidate_labels" in kwargs:
         lowercase__    :   str						= kwargs['''candidate_labels''']
        if "hypothesis_template" in kwargs:
         lowercase__    :   str						= kwargs['''hypothesis_template''']

        return preprocess_params, {}, {}

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

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Optional[Any]:
        lowercase__    :   Any						= model_inputs.pop('''candidate_labels'''			)
        lowercase__    :   int						= model_inputs.pop('''text_inputs'''			)
        if isinstance(text_inputs[0]     ,       __lowerCAmelCase			):
         lowercase__    :   Union[str, Any]						= text_inputs[0]
        else:
         # Batching case.
         lowercase__    :   Optional[Any]						= text_inputs[0][0]

        lowercase__    :   Any						= self.model(**__lowerCAmelCase     ,       **__lowerCAmelCase			)

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


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

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

