






'''simple docstring'''
from typing import Dict, List, Optional, Union

import numpy as np

from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import logging


if is_vision_available():
     import PIL

a_					= logging.get_logger(__name__)





def  _a(  UpperCamelCase__				:						List[Any]							):




      '''simple docstring'''






      if isinstance(UpperCamelCase__,	(list, tuple)							) and isinstance(videos[0],	(list, tuple)							) and is_valid_image(videos[0][0]							):
            return videos

      elif isinstance(UpperCamelCase__,	(list, tuple)							) and is_valid_image(videos[0]							):
            return [videos]

      elif is_valid_image(UpperCamelCase__							):
            return [[videos]]

      raise ValueError(f"Could not make batched video from {videos}"							)







class      __SCREAMING_SNAKE_CASE      (			lowerCamelCase				):
 snake_case_  							=							["""pixel_values"""]




 def __init__(      self	:							int					,      __lowercase	:							bool = True					,      __lowercase	:							Dict[str, int] = None					,      __lowercase	:							PILImageResampling = PILImageResampling.BILINEAR					,      __lowercase	:							bool = True					,      __lowercase	:							Dict[str, int] = None					,      __lowercase	:							bool = True					,      __lowercase	:							Union[int, float] = 1 / 2_55					,      __lowercase	:							bool = True					,      __lowercase	:							bool = True					,      __lowercase	:							Optional[Union[float, List[float]]] = None					,      __lowercase	:							Optional[Union[float, List[float]]] = None					,      **__lowercase	:							Optional[int]					,      )	->						None:
       super().__init__(**__lowercase      )
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=size if size is not None else {'''shortest_edge''': 2_56}
       SCREAMING_SNAKE_CASE__     :				str									=get_size_dict(__lowercase					,      default_to_square=__lowercase      )
       SCREAMING_SNAKE_CASE__     :				str									=crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
       SCREAMING_SNAKE_CASE__     :				str									=get_size_dict(__lowercase					,      param_name='''crop_size'''      )

       SCREAMING_SNAKE_CASE__     :				int									=do_resize
       SCREAMING_SNAKE_CASE__     :				Tuple									=size
       SCREAMING_SNAKE_CASE__     :				int									=do_center_crop
       SCREAMING_SNAKE_CASE__     :				Dict									=crop_size
       SCREAMING_SNAKE_CASE__     :				Tuple									=resample
       SCREAMING_SNAKE_CASE__     :				List[Any]									=do_rescale
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=rescale_factor
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=offset
       SCREAMING_SNAKE_CASE__     :				Tuple									=do_normalize
       SCREAMING_SNAKE_CASE__     :				List[str]									=image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       SCREAMING_SNAKE_CASE__     :				List[Any]									=image_std if image_std is not None else IMAGENET_STANDARD_STD




 def      __magic_name__	(      self	:							Optional[Any]					,      __lowercase	:							np.ndarray					,      __lowercase	:							Dict[str, int]					,      __lowercase	:							PILImageResampling = PILImageResampling.BILINEAR					,      __lowercase	:							Optional[Union[str, ChannelDimension]] = None					,      **__lowercase	:							str					,      )	->						np.ndarray:
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=get_size_dict(__lowercase					,      default_to_square=__lowercase      )
       if "shortest_edge" in size:
             SCREAMING_SNAKE_CASE__     :				Optional[int]									=get_resize_output_image_size(__lowercase					,      size['''shortest_edge''']					,      default_to_square=__lowercase      )
       elif "height" in size and "width" in size:
             SCREAMING_SNAKE_CASE__     :				Any									=(size['''height'''], size['''width'''])
       else:
             raise ValueError(F"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}"      )
       return resize(__lowercase					,      size=__lowercase					,      resample=__lowercase					,      data_format=__lowercase					,      **__lowercase      )




 def      __magic_name__	(      self	:							Optional[Any]					,      __lowercase	:							np.ndarray					,      __lowercase	:							Dict[str, int]					,      __lowercase	:							Optional[Union[str, ChannelDimension]] = None					,      **__lowercase	:							List[Any]					,      )	->						np.ndarray:
       SCREAMING_SNAKE_CASE__     :				Any									=get_size_dict(__lowercase      )
       if "height" not in size or "width" not in size:
             raise ValueError(F"Size must have 'height' and 'width' as keys. Got {size.keys()}"      )
       return center_crop(__lowercase					,      size=(size['''height'''], size['''width'''])					,      data_format=__lowercase					,      **__lowercase      )




 def      __magic_name__	(      self	:							Tuple					,      __lowercase	:							np.ndarray					,      __lowercase	:							Union[int, float]					,      __lowercase	:							bool = True					,      __lowercase	:							Optional[Union[str, ChannelDimension]] = None					,      **__lowercase	:							Optional[int]					,      )	->						List[Any]:
       SCREAMING_SNAKE_CASE__     :				str									=image.astype(np.floataa      )
       if offset:
             SCREAMING_SNAKE_CASE__     :				int									=image - (scale / 2)
       return rescale(__lowercase					,      scale=__lowercase					,      data_format=__lowercase					,      **__lowercase      )




 def      __magic_name__	(      self	:							Optional[Any]					,      __lowercase	:							np.ndarray					,      __lowercase	:							Union[float, List[float]]					,      __lowercase	:							Union[float, List[float]]					,      __lowercase	:							Optional[Union[str, ChannelDimension]] = None					,      **__lowercase	:							Any					,      )	->						np.ndarray:
       return normalize(__lowercase					,      mean=__lowercase					,      std=__lowercase					,      data_format=__lowercase					,      **__lowercase      )




 def      __magic_name__	(      self	:							Dict					,      __lowercase	:							ImageInput					,      __lowercase	:							bool = None					,      __lowercase	:							Dict[str, int] = None					,      __lowercase	:							PILImageResampling = None					,      __lowercase	:							bool = None					,      __lowercase	:							Dict[str, int] = None					,      __lowercase	:							bool = None					,      __lowercase	:							float = None					,      __lowercase	:							bool = None					,      __lowercase	:							bool = None					,      __lowercase	:							Optional[Union[float, List[float]]] = None					,      __lowercase	:							Optional[Union[float, List[float]]] = None					,      __lowercase	:							Optional[ChannelDimension] = ChannelDimension.FIRST					,      )	->						np.ndarray:
       if do_resize and size is None or resample is None:
             raise ValueError('''Size and resample must be specified if do_resize is True.'''      )

       if do_center_crop and crop_size is None:
             raise ValueError('''Crop size must be specified if do_center_crop is True.'''      )

       if do_rescale and rescale_factor is None:
             raise ValueError('''Rescale factor must be specified if do_rescale is True.'''      )

       if do_normalize and (image_mean is None or image_std is None):
             raise ValueError('''Image mean and std must be specified if do_normalize is True.'''      )

       if offset and not do_rescale:
             raise ValueError('''For offset, do_rescale must also be set to True.'''      )

       # All transformations expect numpy arrays.
       SCREAMING_SNAKE_CASE__     :				List[str]									=to_numpy_array(__lowercase      )

       if do_resize:
             SCREAMING_SNAKE_CASE__     :				str									=self.resize(image=__lowercase					,      size=__lowercase					,      resample=__lowercase      )

       if do_center_crop:
             SCREAMING_SNAKE_CASE__     :				Optional[Any]									=self.center_crop(__lowercase					,      size=__lowercase      )

       if do_rescale:
             SCREAMING_SNAKE_CASE__     :				List[str]									=self.rescale(image=__lowercase					,      scale=__lowercase					,      offset=__lowercase      )

       if do_normalize:
             SCREAMING_SNAKE_CASE__     :				int									=self.normalize(image=__lowercase					,      mean=__lowercase					,      std=__lowercase      )

       SCREAMING_SNAKE_CASE__     :				Dict									=to_channel_dimension_format(__lowercase					,      __lowercase      )
       return image




 def      __magic_name__	(      self	:							Any					,      __lowercase	:							ImageInput					,      __lowercase	:							bool = None					,      __lowercase	:							Dict[str, int] = None					,      __lowercase	:							PILImageResampling = None					,      __lowercase	:							bool = None					,      __lowercase	:							Dict[str, int] = None					,      __lowercase	:							bool = None					,      __lowercase	:							float = None					,      __lowercase	:							bool = None					,      __lowercase	:							bool = None					,      __lowercase	:							Optional[Union[float, List[float]]] = None					,      __lowercase	:							Optional[Union[float, List[float]]] = None					,      __lowercase	:							Optional[Union[str, TensorType]] = None					,      __lowercase	:							ChannelDimension = ChannelDimension.FIRST					,      **__lowercase	:							Dict					,      )	->						PIL.Image.Image:
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=do_resize if do_resize is not None else self.do_resize
       SCREAMING_SNAKE_CASE__     :				List[str]									=resample if resample is not None else self.resample
       SCREAMING_SNAKE_CASE__     :				str									=do_center_crop if do_center_crop is not None else self.do_center_crop
       SCREAMING_SNAKE_CASE__     :				Dict									=do_rescale if do_rescale is not None else self.do_rescale
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=rescale_factor if rescale_factor is not None else self.rescale_factor
       SCREAMING_SNAKE_CASE__     :				Any									=offset if offset is not None else self.offset
       SCREAMING_SNAKE_CASE__     :				List[Any]									=do_normalize if do_normalize is not None else self.do_normalize
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=image_mean if image_mean is not None else self.image_mean
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=image_std if image_std is not None else self.image_std

       SCREAMING_SNAKE_CASE__     :				Optional[int]									=size if size is not None else self.size
       SCREAMING_SNAKE_CASE__     :				str									=get_size_dict(__lowercase					,      default_to_square=__lowercase      )
       SCREAMING_SNAKE_CASE__     :				str									=crop_size if crop_size is not None else self.crop_size
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=get_size_dict(__lowercase					,      param_name='''crop_size'''      )

       if not valid_images(__lowercase      ):
             raise ValueError(
                 '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                 '''torch.Tensor, tf.Tensor or jax.ndarray.'''      )

       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=make_batched(__lowercase      )

       SCREAMING_SNAKE_CASE__     :				int									=[
           [
               self._preprocess_image(
                   image=__lowercase					,      do_resize=__lowercase					,      size=__lowercase					,      resample=__lowercase					,      do_center_crop=__lowercase					,      crop_size=__lowercase					,      do_rescale=__lowercase					,      rescale_factor=__lowercase					,      offset=__lowercase					,      do_normalize=__lowercase					,      image_mean=__lowercase					,      image_std=__lowercase					,      data_format=__lowercase					,      )
               for img in video
           ]
           for video in videos
       ]

       SCREAMING_SNAKE_CASE__     :				Tuple									={'''pixel_values''': videos}
       return BatchFeature(data=__lowercase					,      tensor_type=__lowercase      )







'''simple docstring'''
import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
  from PIL import Image
else:






  class      __SCREAMING_SNAKE_CASE      :




   @staticmethod
   def      __magic_name__	(      *__lowercase	:							int					,      **__lowercase	:							Optional[Any]      )	->						Optional[Any]:
         pass






@is_pipeline_test
@require_vision
class      __SCREAMING_SNAKE_CASE      (			unittest.TestCase				):




 @require_torch
 def      __magic_name__	(      self	:							Optional[int]      )	->						Tuple:
       SCREAMING_SNAKE_CASE__     :				List[Any]									=pipeline(
           model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification'''					,      )
       SCREAMING_SNAKE_CASE__     :				List[str]									=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
       SCREAMING_SNAKE_CASE__     :				Any									=image_classifier(__lowercase					,      candidate_labels=['''a''', '''b''', '''c''']      )

       # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
       # python and torch versions.
       self.assertIn(
           nested_simplify(__lowercase      )					,      [
               [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}],
               [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''c'''}, {'''score''': 0.333, '''label''': '''b'''}],
           ]					,      )

       SCREAMING_SNAKE_CASE__     :				int									=image_classifier([image] * 5					,      candidate_labels=['''A''', '''B''', '''C''']					,      batch_size=2      )
       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
           ]					,      )




 @require_tf
 def      __magic_name__	(      self	:							Union[str, Any]      )	->						Optional[int]:
       SCREAMING_SNAKE_CASE__     :				List[Any]									=pipeline(
           model='''hf-internal-testing/tiny-random-clip-zero-shot-image-classification'''					,      framework='''tf'''      )
       SCREAMING_SNAKE_CASE__     :				Dict									=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
       SCREAMING_SNAKE_CASE__     :				Tuple									=image_classifier(__lowercase					,      candidate_labels=['''a''', '''b''', '''c''']      )

       self.assertEqual(
           nested_simplify(__lowercase      )					,      [{'''score''': 0.333, '''label''': '''a'''}, {'''score''': 0.333, '''label''': '''b'''}, {'''score''': 0.333, '''label''': '''c'''}]					,      )

       SCREAMING_SNAKE_CASE__     :				List[Any]									=image_classifier([image] * 5					,      candidate_labels=['''A''', '''B''', '''C''']					,      batch_size=2      )
       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
               [
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
                   {'''score''': 0.333, '''label''': ANY(__lowercase      )},
               ],
           ]					,      )




 @slow
 @require_torch
 def      __magic_name__	(      self	:							List[Any]      )	->						Dict:
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=pipeline(
           task='''zero-shot-image-classification'''					,      model='''openai/clip-vit-base-patch32'''					,      )
       # This is an image of 2 cats with remotes and no planes
       SCREAMING_SNAKE_CASE__     :				Any									=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
       SCREAMING_SNAKE_CASE__     :				List[str]									=image_classifier(__lowercase					,      candidate_labels=['''cat''', '''plane''', '''remote''']      )

       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               {'''score''': 0.511, '''label''': '''remote'''},
               {'''score''': 0.485, '''label''': '''cat'''},
               {'''score''': 0.004, '''label''': '''plane'''},
           ]					,      )

       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=image_classifier([image] * 5					,      candidate_labels=['''cat''', '''plane''', '''remote''']					,      batch_size=2      )
       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               [
                   {'''score''': 0.511, '''label''': '''remote'''},
                   {'''score''': 0.485, '''label''': '''cat'''},
                   {'''score''': 0.004, '''label''': '''plane'''},
               ],
           ]
           * 5					,      )




 @slow
 @require_tf
 def      __magic_name__	(      self	:							Union[str, Any]      )	->						int:
       SCREAMING_SNAKE_CASE__     :				str									=pipeline(
           task='''zero-shot-image-classification'''					,      model='''openai/clip-vit-base-patch32'''					,      framework='''tf'''      )
       # This is an image of 2 cats with remotes and no planes
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
       SCREAMING_SNAKE_CASE__     :				Any									=image_classifier(__lowercase					,      candidate_labels=['''cat''', '''plane''', '''remote''']      )
       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               {'''score''': 0.511, '''label''': '''remote'''},
               {'''score''': 0.485, '''label''': '''cat'''},
               {'''score''': 0.004, '''label''': '''plane'''},
           ]					,      )

       SCREAMING_SNAKE_CASE__     :				List[Any]									=image_classifier([image] * 5					,      candidate_labels=['''cat''', '''plane''', '''remote''']					,      batch_size=2      )
       self.assertEqual(
           nested_simplify(__lowercase      )					,      [
               [
                   {'''score''': 0.511, '''label''': '''remote'''},
                   {'''score''': 0.485, '''label''': '''cat'''},
                   {'''score''': 0.004, '''label''': '''plane'''},
               ],
           ]
           * 5					,      )