


'''simple docstring'''

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


lowerCamelCase				:  Tuple    		=      logging.get_logger(__name__)

def _SCREAMING_SNAKE_CASE (A			)			->			List[List[ImageInput]]:






       """simple docstring"""







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

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

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

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

class     __lowerCAmelCase		(lowercase_	):





      '''simple docstring'''






      lowerCAmelCase__   :	int       =				["""pixel_values"""]



      def __init__(self       :       Any  ,		UpperCamelCase       :       bool = True  ,		UpperCamelCase       :       Dict[str, int] = None  ,		UpperCamelCase       :       PILImageResampling = PILImageResampling.BILINEAR  ,		UpperCamelCase       :       bool = True  ,		UpperCamelCase       :       Dict[str, int] = None  ,		UpperCamelCase       :       bool = True  ,		UpperCamelCase       :       Union[int, float] = 1 / 255  ,		UpperCamelCase       :       bool = True  ,		UpperCamelCase       :       Optional[Union[float, List[float]]] = None  ,		UpperCamelCase       :       Optional[Union[float, List[float]]] = None  ,		**UpperCamelCase       :       List[str]  ,		):

             '''simple docstring'''







             super().__init__(**UpperCamelCase					)
             lowercase__      =					size if size is not None else {'''shortest_edge''': 224}
             lowercase__      =					get_size_dict(UpperCamelCase  ,		default_to_square=UpperCamelCase					)
             lowercase__      =					crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
             lowercase__      =					get_size_dict(UpperCamelCase  ,		param_name='''crop_size'''					)

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



      def  UpperCamelCase__						(self       :       List[Any]  ,		UpperCamelCase       :       np.ndarray  ,		UpperCamelCase       :       Dict[str, int]  ,		UpperCamelCase       :       PILImageResampling = PILImageResampling.BILINEAR  ,		UpperCamelCase       :       Optional[Union[str, ChannelDimension]] = None  ,		**UpperCamelCase       :       Dict  ,		):

             '''simple docstring'''







             lowercase__      =					get_size_dict(UpperCamelCase  ,		default_to_square=UpperCamelCase					)
             if "shortest_edge" in size:
                    lowercase__      =					get_resize_output_image_size(UpperCamelCase  ,		size['''shortest_edge''']  ,		default_to_square=UpperCamelCase					)
             elif "height" in size and "width" in size:
                    lowercase__      =					(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       :       Union[str, Any]  ,		UpperCamelCase       :       np.ndarray  ,		UpperCamelCase       :       Dict[str, int]  ,		UpperCamelCase       :       Optional[Union[str, ChannelDimension]] = None  ,		**UpperCamelCase       :       int  ,		):

             '''simple docstring'''







             lowercase__      =					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       :       Any  ,		UpperCamelCase       :       np.ndarray  ,		UpperCamelCase       :       Union[int, float]  ,		UpperCamelCase       :       Optional[Union[str, ChannelDimension]] = None  ,		**UpperCamelCase       :       str  ,		):

             '''simple docstring'''







             return rescale(UpperCamelCase  ,		scale=UpperCamelCase  ,		data_format=UpperCamelCase  ,		**UpperCamelCase					)



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

             '''simple docstring'''







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



      def  UpperCamelCase__						(self       :       Any  ,		UpperCamelCase       :       ImageInput  ,		UpperCamelCase       :       bool = None  ,		UpperCamelCase       :       Dict[str, int] = None  ,		UpperCamelCase       :       PILImageResampling = None  ,		UpperCamelCase       :       bool = None  ,		UpperCamelCase       :       Dict[str, int] = None  ,		UpperCamelCase       :       bool = None  ,		UpperCamelCase       :       float = None  ,		UpperCamelCase       :       bool = None  ,		UpperCamelCase       :       Optional[Union[float, List[float]]] = None  ,		UpperCamelCase       :       Optional[Union[float, List[float]]] = None  ,		UpperCamelCase       :       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.'''					)

             # All transformations expect numpy arrays.
             lowercase__      =					to_numpy_array(UpperCamelCase					)

             if do_resize:
                    lowercase__      =					self.resize(image=UpperCamelCase  ,		size=UpperCamelCase  ,		resample=UpperCamelCase					)

             if do_center_crop:
                    lowercase__      =					self.center_crop(UpperCamelCase  ,		size=UpperCamelCase					)

             if do_rescale:
                    lowercase__      =					self.rescale(image=UpperCamelCase  ,		scale=UpperCamelCase					)

             if do_normalize:
                    lowercase__      =					self.normalize(image=UpperCamelCase  ,		mean=UpperCamelCase  ,		std=UpperCamelCase					)

             lowercase__      =					to_channel_dimension_format(UpperCamelCase  ,		UpperCamelCase					)
             return image






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

             '''simple docstring'''







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

             lowercase__      =					size if size is not None else self.size
             lowercase__      =					get_size_dict(UpperCamelCase  ,		default_to_square=UpperCamelCase					)
             lowercase__      =					crop_size if crop_size is not None else self.crop_size
             lowercase__      =					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.'''					)

             lowercase__      =					make_batched(UpperCamelCase					)

             lowercase__      =					[
                 [
                     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
             ]

             lowercase__      =					{'''pixel_values''': videos}
             return BatchFeature(data=UpperCamelCase  ,		tensor_type=UpperCamelCase					)








'''simple docstring'''

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  UpperCamelCase__						(*UpperCamelCase       :       Optional[Any]  ,		**UpperCamelCase       :       Tuple					):

              '''simple docstring'''







              pass
@is_pipeline_test
@require_vision
@require_torch
class     __lowerCAmelCase		(unittest.TestCase	):





      '''simple docstring'''






      lowerCAmelCase__   :	Optional[int]       =				MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING



      def  UpperCamelCase__						(self       :       int  ,		UpperCamelCase       :       List[str]  ,		UpperCamelCase       :       List[str]  ,		UpperCamelCase       :       str					):

             '''simple docstring'''







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

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



      def  UpperCamelCase__						(self       :       Optional[Any]  ,		UpperCamelCase       :       Tuple  ,		UpperCamelCase       :       Optional[int]					):

             '''simple docstring'''







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

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



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

             '''simple docstring'''







             pass



      @require_torch
      def  UpperCamelCase__						(self       :       Any					):

             '''simple docstring'''







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

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

             self.assertEqual(
                 nested_simplify(UpperCamelCase  ,		decimals=4					)  ,		[
                     {'''score''': 0.72_35, '''label''': '''cat''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                     {'''score''': 0.72_18, '''label''': '''remote''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                     {'''score''': 0.71_84, '''label''': '''couch''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                     {'''score''': 0.67_48, '''label''': '''remote''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                     {'''score''': 0.66_56, '''label''': '''cat''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                     {'''score''': 0.66_14, '''label''': '''couch''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                     {'''score''': 0.64_56, '''label''': '''remote''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                     {'''score''': 0.6_42, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 274, '''xmax''': 93, '''ymax''': 297}},
                     {'''score''': 0.64_19, '''label''': '''cat''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                 ]  ,		)

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

             self.assertEqual(
                 nested_simplify(UpperCamelCase  ,		decimals=4					)  ,		[
                     [
                         {'''score''': 0.72_35, '''label''': '''cat''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                         {'''score''': 0.72_18, '''label''': '''remote''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                         {'''score''': 0.71_84, '''label''': '''couch''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                         {'''score''': 0.67_48, '''label''': '''remote''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                         {'''score''': 0.66_56, '''label''': '''cat''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                         {'''score''': 0.66_14, '''label''': '''couch''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                         {'''score''': 0.64_56, '''label''': '''remote''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                         {'''score''': 0.6_42, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 274, '''xmax''': 93, '''ymax''': 297}},
                         {'''score''': 0.64_19, '''label''': '''cat''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                     ]
                 ]  ,		)



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

             '''simple docstring'''







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

             lowercase__      =					object_detector(
                 '''http://images.cocodataset.org/val2017/000000039769.jpg'''  ,		candidate_labels=['''cat''', '''remote''', '''couch''']  ,		)
             self.assertEqual(
                 nested_simplify(UpperCamelCase  ,		decimals=4					)  ,		[
                     {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                     {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                     {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                     {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 335, '''ymin''': 74, '''xmax''': 371, '''ymax''': 187}},
                     {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 642, '''ymax''': 476}},
                 ]  ,		)

             lowercase__      =					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(UpperCamelCase  ,		decimals=4					)  ,		[
                     [
                         {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                         {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                         {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                         {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 335, '''ymin''': 74, '''xmax''': 371, '''ymax''': 187}},
                         {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 642, '''ymax''': 476}},
                     ],
                     [
                         {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                         {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                         {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                         {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 335, '''ymin''': 74, '''xmax''': 371, '''ymax''': 187}},
                         {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 642, '''ymax''': 476}},
                     ],
                 ]  ,		)



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

             '''simple docstring'''







             pass



      @require_torch
      @slow
      def  UpperCamelCase__						(self       :       Tuple					):

             '''simple docstring'''







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

             lowercase__      =					object_detector(
                 '''http://images.cocodataset.org/val2017/000000039769.jpg'''  ,		candidate_labels=['''cat''', '''remote''', '''couch''']  ,		threshold=UpperCamelCase  ,		)
             self.assertEqual(
                 nested_simplify(UpperCamelCase  ,		decimals=4					)  ,		[
                     {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                     {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                     {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                 ]  ,		)






      @require_torch
      @slow
      def  UpperCamelCase__						(self       :       Dict					):

             '''simple docstring'''







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

             lowercase__      =					object_detector(
                 '''http://images.cocodataset.org/val2017/000000039769.jpg'''  ,		candidate_labels=['''cat''', '''remote''', '''couch''']  ,		top_k=UpperCamelCase  ,		)
             self.assertEqual(
                 nested_simplify(UpperCamelCase  ,		decimals=4					)  ,		[
                     {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                     {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                 ]  ,		)




