



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

SCREAMING_SNAKE_CASE__   			=   logging.get_logger(__name__)


def A    (							__UpperCamelCase       )    ->   List[List[ImageInput]]:
			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   __lowerCAmelCase  (		UpperCAmelCase_   ):
					"""simple docstring"""






					A__					:		Any      							=     ["pixel_values"]



					def __init__(  self       :							int					,       _snake_case       :							bool = True					,       _snake_case       :							Dict[str, int] = None					,       _snake_case       :							PILImageResampling = PILImageResampling.BILINEAR					,       _snake_case       :							bool = True					,       _snake_case       :							Dict[str, int] = None					,       _snake_case       :							bool = True					,       _snake_case       :							Union[int, float] = 1 / 2_55					,       _snake_case       :							bool = True					,       _snake_case       :							bool = True					,       _snake_case       :							Optional[Union[float, List[float]]] = None					,       _snake_case       :							Optional[Union[float, List[float]]] = None					,       **_snake_case       :							Tuple					,       ):






								"""simple docstring"""


								super().__init__(**_snake_case       )
								A__	  =     size if size is not None else {'shortest_edge': 2_56}
								A__	  =     get_size_dict(_snake_case					,       default_to_square=_snake_case       )
								A__	  =     crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24}
								A__	  =     get_size_dict(_snake_case					,       param_name='crop_size'       )

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



					def      _a				(  self       :							Dict					,       _snake_case       :							np.ndarray					,       _snake_case       :							Dict[str, int]					,       _snake_case       :							PILImageResampling = PILImageResampling.BILINEAR					,       _snake_case       :							Optional[Union[str, ChannelDimension]] = None					,       **_snake_case       :							int					,       ):






								"""simple docstring"""


								A__	  =     get_size_dict(_snake_case					,       default_to_square=_snake_case       )
								if "shortest_edge" in size:
											A__	  =     get_resize_output_image_size(_snake_case					,       size['shortest_edge']					,       default_to_square=_snake_case       )
								elif "height" in size and "width" in size:
											A__	  =     (size['height'], size['width'])
								else:
											raise ValueError(F'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'''       )
								return resize(_snake_case					,       size=_snake_case					,       resample=_snake_case					,       data_format=_snake_case					,       **_snake_case       )



					def      _a				(  self       :							Any					,       _snake_case       :							np.ndarray					,       _snake_case       :							Dict[str, int]					,       _snake_case       :							Optional[Union[str, ChannelDimension]] = None					,       **_snake_case       :							str					,       ):






								"""simple docstring"""


								A__	  =     get_size_dict(_snake_case       )
								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(_snake_case					,       size=(size['height'], size['width'])					,       data_format=_snake_case					,       **_snake_case       )



					def      _a				(  self       :							Optional[Any]					,       _snake_case       :							np.ndarray					,       _snake_case       :							Union[int, float]					,       _snake_case       :							bool = True					,       _snake_case       :							Optional[Union[str, ChannelDimension]] = None					,       **_snake_case       :							str					,       ):






								"""simple docstring"""


								A__	  =     image.astype(np.floataa       )
								if offset:
											A__	  =     image - (scale / 2)
								return rescale(_snake_case					,       scale=_snake_case					,       data_format=_snake_case					,       **_snake_case       )



					def      _a				(  self       :							Optional[int]					,       _snake_case       :							np.ndarray					,       _snake_case       :							Union[float, List[float]]					,       _snake_case       :							Union[float, List[float]]					,       _snake_case       :							Optional[Union[str, ChannelDimension]] = None					,       **_snake_case       :							Tuple					,       ):






								"""simple docstring"""


								return normalize(_snake_case					,       mean=_snake_case					,       std=_snake_case					,       data_format=_snake_case					,       **_snake_case       )



					def      _a				(  self       :							List[Any]					,       _snake_case       :							ImageInput					,       _snake_case       :							bool = None					,       _snake_case       :							Dict[str, int] = None					,       _snake_case       :							PILImageResampling = None					,       _snake_case       :							bool = None					,       _snake_case       :							Dict[str, int] = None					,       _snake_case       :							bool = None					,       _snake_case       :							float = None					,       _snake_case       :							bool = None					,       _snake_case       :							bool = None					,       _snake_case       :							Optional[Union[float, List[float]]] = None					,       _snake_case       :							Optional[Union[float, List[float]]] = None					,       _snake_case       :							Optional[ChannelDimension] = ChannelDimension.FIRST					,       ):






								"""simple docstring"""


								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.
								A__	  =     to_numpy_array(_snake_case       )

								if do_resize:
											A__	  =     self.resize(image=_snake_case					,       size=_snake_case					,       resample=_snake_case       )

								if do_center_crop:
											A__	  =     self.center_crop(_snake_case					,       size=_snake_case       )

								if do_rescale:
											A__	  =     self.rescale(image=_snake_case					,       scale=_snake_case					,       offset=_snake_case       )

								if do_normalize:
											A__	  =     self.normalize(image=_snake_case					,       mean=_snake_case					,       std=_snake_case       )

								A__	  =     to_channel_dimension_format(_snake_case					,       _snake_case       )
								return image



					def      _a				(  self       :							Union[str, Any]					,       _snake_case       :							ImageInput					,       _snake_case       :							bool = None					,       _snake_case       :							Dict[str, int] = None					,       _snake_case       :							PILImageResampling = None					,       _snake_case       :							bool = None					,       _snake_case       :							Dict[str, int] = None					,       _snake_case       :							bool = None					,       _snake_case       :							float = None					,       _snake_case       :							bool = None					,       _snake_case       :							bool = None					,       _snake_case       :							Optional[Union[float, List[float]]] = None					,       _snake_case       :							Optional[Union[float, List[float]]] = None					,       _snake_case       :							Optional[Union[str, TensorType]] = None					,       _snake_case       :							ChannelDimension = ChannelDimension.FIRST					,       **_snake_case       :							str					,       ):






								"""simple docstring"""


								A__	  =     do_resize if do_resize is not None else self.do_resize
								A__	  =     resample if resample is not None else self.resample
								A__	  =     do_center_crop if do_center_crop is not None else self.do_center_crop
								A__	  =     do_rescale if do_rescale is not None else self.do_rescale
								A__	  =     rescale_factor if rescale_factor is not None else self.rescale_factor
								A__	  =     offset if offset is not None else self.offset
								A__	  =     do_normalize if do_normalize is not None else self.do_normalize
								A__	  =     image_mean if image_mean is not None else self.image_mean
								A__	  =     image_std if image_std is not None else self.image_std

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

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

								A__	  =     make_batched(_snake_case       )

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

								A__	  =     {'pixel_values': videos}
								return BatchFeature(data=_snake_case					,       tensor_type=_snake_case       )









import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, 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   __lowerCAmelCase  :
												"""simple docstring"""






												@staticmethod
												def      _a				(  *_snake_case       :							int					,       **_snake_case       :							List[str]       ):






															"""simple docstring"""


															pass


@is_pipeline_test
@require_vision
@require_torch
class   __lowerCAmelCase  (		unittest.TestCase   ):
					"""simple docstring"""






					A__					:		List[str]      							=     MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING



					def      _a				(  self       :							Any					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							Tuple					,       _snake_case       :							Optional[Any]       ):






								"""simple docstring"""


								A__	  =     pipeline(
								    'zero-shot-object-detection'					,       model='hf-internal-testing/tiny-random-owlvit-object-detection'       )

								A__	  =     [
								    {
								        'image': './tests/fixtures/tests_samples/COCO/000000039769.png',
								        'candidate_labels': ['cat', 'remote', 'couch'],
								    }
								]
								return object_detector, examples



					def      _a				(  self       :							int					,       _snake_case       :							int					,       _snake_case       :							List[str]       ):






								"""simple docstring"""


								A__	  =     object_detector(examples[0]					,       threshold=0.0       )

								A__	  =     len(_snake_case       )
								self.assertGreater(_snake_case					,       0       )
								self.assertEqual(
								    _snake_case					,       [
								        {
								            'score': ANY(_snake_case       ),
								            'label': ANY(_snake_case       ),
								            'box': {'xmin': ANY(_snake_case       ), 'ymin': ANY(_snake_case       ), 'xmax': ANY(_snake_case       ), 'ymax': ANY(_snake_case       )},
								        }
								        for i in range(_snake_case       )
								    ]					,       )



					@require_tf
					@unittest.skip('Zero Shot Object Detection not implemented in TF'       )
					def      _a				(  self       :							List[str]       ):






								"""simple docstring"""


								pass



					@require_torch
					def      _a				(  self       :							Optional[int]       ):






								"""simple docstring"""


								A__	  =     pipeline(
								    'zero-shot-object-detection'					,       model='hf-internal-testing/tiny-random-owlvit-object-detection'       )

								A__	  =     object_detector(
								    './tests/fixtures/tests_samples/COCO/000000039769.png'					,       candidate_labels=['cat', 'remote', 'couch']					,       threshold=0.64					,       )

								self.assertEqual(
								    nested_simplify(_snake_case					,       decimals=4       )					,       [
								        {'score': 0.7235, 'label': 'cat', 'box': {'xmin': 2_04, 'ymin': 1_67, 'xmax': 2_32, 'ymax': 1_90}},
								        {'score': 0.7218, 'label': 'remote', 'box': {'xmin': 2_04, 'ymin': 1_67, 'xmax': 2_32, 'ymax': 1_90}},
								        {'score': 0.7184, 'label': 'couch', 'box': {'xmin': 2_04, 'ymin': 1_67, 'xmax': 2_32, 'ymax': 1_90}},
								        {'score': 0.6748, 'label': 'remote', 'box': {'xmin': 5_71, 'ymin': 83, 'xmax': 5_98, 'ymax': 1_03}},
								        {'score': 0.6656, 'label': 'cat', 'box': {'xmin': 5_71, 'ymin': 83, 'xmax': 5_98, 'ymax': 1_03}},
								        {'score': 0.6614, 'label': 'couch', 'box': {'xmin': 5_71, 'ymin': 83, 'xmax': 5_98, 'ymax': 1_03}},
								        {'score': 0.6456, 'label': 'remote', 'box': {'xmin': 4_94, 'ymin': 1_05, 'xmax': 5_21, 'ymax': 1_27}},
								        {'score': 0.642, 'label': 'remote', 'box': {'xmin': 67, 'ymin': 2_74, 'xmax': 93, 'ymax': 2_97}},
								        {'score': 0.6419, 'label': 'cat', 'box': {'xmin': 4_94, 'ymin': 1_05, 'xmax': 5_21, 'ymax': 1_27}},
								    ]					,       )

								A__	  =     object_detector(
								    [
								        {
								            'image': './tests/fixtures/tests_samples/COCO/000000039769.png',
								            'candidate_labels': ['cat', 'remote', 'couch'],
								        }
								    ]					,       threshold=0.64					,       )

								self.assertEqual(
								    nested_simplify(_snake_case					,       decimals=4       )					,       [
								        [
								            {'score': 0.7235, 'label': 'cat', 'box': {'xmin': 2_04, 'ymin': 1_67, 'xmax': 2_32, 'ymax': 1_90}},
								            {'score': 0.7218, 'label': 'remote', 'box': {'xmin': 2_04, 'ymin': 1_67, 'xmax': 2_32, 'ymax': 1_90}},
								            {'score': 0.7184, 'label': 'couch', 'box': {'xmin': 2_04, 'ymin': 1_67, 'xmax': 2_32, 'ymax': 1_90}},
								            {'score': 0.6748, 'label': 'remote', 'box': {'xmin': 5_71, 'ymin': 83, 'xmax': 5_98, 'ymax': 1_03}},
								            {'score': 0.6656, 'label': 'cat', 'box': {'xmin': 5_71, 'ymin': 83, 'xmax': 5_98, 'ymax': 1_03}},
								            {'score': 0.6614, 'label': 'couch', 'box': {'xmin': 5_71, 'ymin': 83, 'xmax': 5_98, 'ymax': 1_03}},
								            {'score': 0.6456, 'label': 'remote', 'box': {'xmin': 4_94, 'ymin': 1_05, 'xmax': 5_21, 'ymax': 1_27}},
								            {'score': 0.642, 'label': 'remote', 'box': {'xmin': 67, 'ymin': 2_74, 'xmax': 93, 'ymax': 2_97}},
								            {'score': 0.6419, 'label': 'cat', 'box': {'xmin': 4_94, 'ymin': 1_05, 'xmax': 5_21, 'ymax': 1_27}},
								        ]
								    ]					,       )



					@require_torch
					@slow
					def      _a				(  self       :							int       ):






								"""simple docstring"""


								A__	  =     pipeline('zero-shot-object-detection'       )

								A__	  =     object_detector(
								    'http://images.cocodataset.org/val2017/000000039769.jpg'					,       candidate_labels=['cat', 'remote', 'couch']					,       )
								self.assertEqual(
								    nested_simplify(_snake_case					,       decimals=4       )					,       [
								        {'score': 0.2868, 'label': 'cat', 'box': {'xmin': 3_24, 'ymin': 20, 'xmax': 6_40, 'ymax': 3_73}},
								        {'score': 0.277, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 1_77, 'ymax': 1_15}},
								        {'score': 0.2537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 3_15, 'ymax': 4_72}},
								        {'score': 0.1474, 'label': 'remote', 'box': {'xmin': 3_35, 'ymin': 74, 'xmax': 3_71, 'ymax': 1_87}},
								        {'score': 0.1208, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 6_42, 'ymax': 4_76}},
								    ]					,       )

								A__	  =     object_detector(
								    [
								        {
								            'image': 'http://images.cocodataset.org/val2017/000000039769.jpg',
								            'candidate_labels': ['cat', 'remote', 'couch'],
								        },
								        {
								            'image': 'http://images.cocodataset.org/val2017/000000039769.jpg',
								            'candidate_labels': ['cat', 'remote', 'couch'],
								        },
								    ]					,       )
								self.assertEqual(
								    nested_simplify(_snake_case					,       decimals=4       )					,       [
								        [
								            {'score': 0.2868, 'label': 'cat', 'box': {'xmin': 3_24, 'ymin': 20, 'xmax': 6_40, 'ymax': 3_73}},
								            {'score': 0.277, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 1_77, 'ymax': 1_15}},
								            {'score': 0.2537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 3_15, 'ymax': 4_72}},
								            {'score': 0.1474, 'label': 'remote', 'box': {'xmin': 3_35, 'ymin': 74, 'xmax': 3_71, 'ymax': 1_87}},
								            {'score': 0.1208, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 6_42, 'ymax': 4_76}},
								        ],
								        [
								            {'score': 0.2868, 'label': 'cat', 'box': {'xmin': 3_24, 'ymin': 20, 'xmax': 6_40, 'ymax': 3_73}},
								            {'score': 0.277, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 1_77, 'ymax': 1_15}},
								            {'score': 0.2537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 3_15, 'ymax': 4_72}},
								            {'score': 0.1474, 'label': 'remote', 'box': {'xmin': 3_35, 'ymin': 74, 'xmax': 3_71, 'ymax': 1_87}},
								            {'score': 0.1208, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 6_42, 'ymax': 4_76}},
								        ],
								    ]					,       )



					@require_tf
					@unittest.skip('Zero Shot Object Detection not implemented in TF'       )
					def      _a				(  self       :							int       ):






								"""simple docstring"""


								pass



					@require_torch
					@slow
					def      _a				(  self       :							str       ):






								"""simple docstring"""


								A__	  =     0.2
								A__	  =     pipeline('zero-shot-object-detection'       )

								A__	  =     object_detector(
								    'http://images.cocodataset.org/val2017/000000039769.jpg'					,       candidate_labels=['cat', 'remote', 'couch']					,       threshold=_snake_case					,       )
								self.assertEqual(
								    nested_simplify(_snake_case					,       decimals=4       )					,       [
								        {'score': 0.2868, 'label': 'cat', 'box': {'xmin': 3_24, 'ymin': 20, 'xmax': 6_40, 'ymax': 3_73}},
								        {'score': 0.277, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 1_77, 'ymax': 1_15}},
								        {'score': 0.2537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 3_15, 'ymax': 4_72}},
								    ]					,       )



					@require_torch
					@slow
					def      _a				(  self       :							Any       ):






								"""simple docstring"""


								A__	  =     2
								A__	  =     pipeline('zero-shot-object-detection'       )

								A__	  =     object_detector(
								    'http://images.cocodataset.org/val2017/000000039769.jpg'					,       candidate_labels=['cat', 'remote', 'couch']					,       top_k=_snake_case					,       )
								self.assertEqual(
								    nested_simplify(_snake_case					,       decimals=4       )					,       [
								        {'score': 0.2868, 'label': 'cat', 'box': {'xmin': 3_24, 'ymin': 20, 'xmax': 6_40, 'ymax': 3_73}},
								        {'score': 0.277, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 1_77, 'ymax': 1_15}},
								    ]					,       )




