






from typing import Dict, List, Optional, Union

import numpy as np

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 TensorType, is_vision_available, logging


if is_vision_available():
 import PIL


snake_case__   :						str													=   logging.get_logger(__name__)






def      _snake_case     (__lowercase):
   if isinstance(__lowercase     ,   (list, tuple)) and isinstance(videos[0]     ,   (list, tuple)) and is_valid_image(videos[0][0]):
      return videos

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

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

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


class     _a							(	UpperCAmelCase__     ):






  """simple docstring"""





  A_						       = ["""pixel_values"""]




  def __init__(  self		,		_UpperCAmelCase = True		,		_UpperCAmelCase = None		,		_UpperCAmelCase = PILImageResampling.BILINEAR		,		_UpperCAmelCase = True		,		_UpperCAmelCase = None		,		_UpperCAmelCase = True		,		_UpperCAmelCase = 1 / 255		,		_UpperCAmelCase = True		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		**_UpperCAmelCase		,		)      ->			None:
     super().__init__(**_UpperCAmelCase			)
     UpperCamelCase_						=  size if size is not None else {'shortest_edge': 224}
     UpperCamelCase_						=  get_size_dict(_UpperCAmelCase		,		default_to_square=_UpperCAmelCase			)
     UpperCamelCase_						=  crop_size if crop_size is not None else {'height': 224, 'width': 224}
     UpperCamelCase_						=  get_size_dict(_UpperCAmelCase		,		param_name='crop_size'			)

     UpperCamelCase_						=  do_resize
     UpperCamelCase_						=  size
     UpperCamelCase_						=  do_center_crop
     UpperCamelCase_						=  crop_size
     UpperCamelCase_						=  resample
     UpperCamelCase_						=  do_rescale
     UpperCamelCase_						=  rescale_factor
     UpperCamelCase_						=  do_normalize
     UpperCamelCase_						=  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
     UpperCamelCase_						=  image_std if image_std is not None else IMAGENET_STANDARD_STD




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = PILImageResampling.BILINEAR		,		_UpperCAmelCase = None		,		**_UpperCAmelCase		,		)      ->			np.ndarray:
     UpperCamelCase_						=  get_size_dict(_UpperCAmelCase		,		default_to_square=_UpperCAmelCase			)
     if "shortest_edge" in size:
        UpperCamelCase_						=  get_resize_output_image_size(_UpperCAmelCase		,		size['shortest_edge']		,		default_to_square=_UpperCAmelCase			)
     elif "height" in size and "width" in size:
        UpperCamelCase_						=  (size['height'], size['width'])
     else:
        raise ValueError(f"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}"""			)
     return resize(_UpperCAmelCase		,		size=_UpperCAmelCase		,		resample=_UpperCAmelCase		,		data_format=_UpperCAmelCase		,		**_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		**_UpperCAmelCase		,		)      ->			np.ndarray:
     UpperCamelCase_						=  get_size_dict(_UpperCAmelCase			)
     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(_UpperCAmelCase		,		size=(size['height'], size['width'])		,		data_format=_UpperCAmelCase		,		**_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		**_UpperCAmelCase		,		)      ->			int:
     return rescale(_UpperCAmelCase		,		scale=_UpperCAmelCase		,		data_format=_UpperCAmelCase		,		**_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		**_UpperCAmelCase		,		)      ->			np.ndarray:
     return normalize(_UpperCAmelCase		,		mean=_UpperCAmelCase		,		std=_UpperCAmelCase		,		data_format=_UpperCAmelCase		,		**_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = 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.'			)

     # All transformations expect numpy arrays.
     UpperCamelCase_						=  to_numpy_array(_UpperCAmelCase			)

     if do_resize:
        UpperCamelCase_						=  self.resize(image=_UpperCAmelCase		,		size=_UpperCAmelCase		,		resample=_UpperCAmelCase			)

     if do_center_crop:
        UpperCamelCase_						=  self.center_crop(_UpperCAmelCase		,		size=_UpperCAmelCase			)

     if do_rescale:
        UpperCamelCase_						=  self.rescale(image=_UpperCAmelCase		,		scale=_UpperCAmelCase			)

     if do_normalize:
        UpperCamelCase_						=  self.normalize(image=_UpperCAmelCase		,		mean=_UpperCAmelCase		,		std=_UpperCAmelCase			)

     UpperCamelCase_						=  to_channel_dimension_format(_UpperCAmelCase		,		_UpperCAmelCase			)
     return image




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = None		,		_UpperCAmelCase = ChannelDimension.FIRST		,		**_UpperCAmelCase		,		)      ->			PIL.Image.Image:
     UpperCamelCase_						=  do_resize if do_resize is not None else self.do_resize
     UpperCamelCase_						=  resample if resample is not None else self.resample
     UpperCamelCase_						=  do_center_crop if do_center_crop is not None else self.do_center_crop
     UpperCamelCase_						=  do_rescale if do_rescale is not None else self.do_rescale
     UpperCamelCase_						=  rescale_factor if rescale_factor is not None else self.rescale_factor
     UpperCamelCase_						=  do_normalize if do_normalize is not None else self.do_normalize
     UpperCamelCase_						=  image_mean if image_mean is not None else self.image_mean
     UpperCamelCase_						=  image_std if image_std is not None else self.image_std

     UpperCamelCase_						=  size if size is not None else self.size
     UpperCamelCase_						=  get_size_dict(_UpperCAmelCase		,		default_to_square=_UpperCAmelCase			)
     UpperCamelCase_						=  crop_size if crop_size is not None else self.crop_size
     UpperCamelCase_						=  get_size_dict(_UpperCAmelCase		,		param_name='crop_size'			)

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

     UpperCamelCase_						=  make_batched(_UpperCAmelCase			)

     UpperCamelCase_						=  [
         [
             self._preprocess_image(
                 image=_UpperCAmelCase		,		do_resize=_UpperCAmelCase		,		size=_UpperCAmelCase		,		resample=_UpperCAmelCase		,		do_center_crop=_UpperCAmelCase		,		crop_size=_UpperCAmelCase		,		do_rescale=_UpperCAmelCase		,		rescale_factor=_UpperCAmelCase		,		do_normalize=_UpperCAmelCase		,		image_mean=_UpperCAmelCase		,		image_std=_UpperCAmelCase		,		data_format=_UpperCAmelCase		,		)
             for img in video
         ]
         for video in videos
     ]

     UpperCamelCase_						=  {'pixel_values': videos}
     return BatchFeature(data=_UpperCAmelCase		,		tensor_type=_UpperCAmelCase			)










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     __a			:



					@staticmethod
					def 		UpperCamelCase				(    *snake_case_				:     Any					,						**snake_case_				:     str)->				int:
										pass






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



	@require_torch
	def 		UpperCamelCase				(    self				:     Dict)->				List[str]:
						__lowerCAmelCase						 =pipeline(
						    model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""					,						)
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						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(snake_case_)					,						[
						        [{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """b"""}, {"""score""": 0.3_3_3, """label""": """c"""}],
						        [{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """c"""}, {"""score""": 0.3_3_3, """label""": """b"""}],
						    ]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""A""", """B""", """C"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						    ]					,						)



	@require_tf
	def 		UpperCamelCase				(    self				:     Dict)->				Optional[Any]:
						__lowerCAmelCase						 =pipeline(
						    model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""					,						framework="""tf""")
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""a""", """b""", """c"""])

						self.assertEqual(
						    nested_simplify(snake_case_)					,						[{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """b"""}, {"""score""": 0.3_3_3, """label""": """c"""}]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""A""", """B""", """C"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						    ]					,						)



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

						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        {"""score""": 0.5_1_1, """label""": """remote"""},
						        {"""score""": 0.4_8_5, """label""": """cat"""},
						        {"""score""": 0.0_0_4, """label""": """plane"""},
						    ]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""cat""", """plane""", """remote"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.5_1_1, """label""": """remote"""},
						            {"""score""": 0.4_8_5, """label""": """cat"""},
						            {"""score""": 0.0_0_4, """label""": """plane"""},
						        ],
						    ]
						    * 5					,						)



	@slow
	@require_tf
	def 		UpperCamelCase				(    self				:     Optional[int])->				int:
						__lowerCAmelCase						 =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
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""cat""", """plane""", """remote"""])
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        {"""score""": 0.5_1_1, """label""": """remote"""},
						        {"""score""": 0.4_8_5, """label""": """cat"""},
						        {"""score""": 0.0_0_4, """label""": """plane"""},
						    ]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""cat""", """plane""", """remote"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.5_1_1, """label""": """remote"""},
						            {"""score""": 0.4_8_5, """label""": """cat"""},
						            {"""score""": 0.0_0_4, """label""": """plane"""},
						        ],
						    ]
						    * 5					,						)




