



"""simple docstring"""






import random
import unittest

import numpy as np

from transformers.testing_utils import 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():
		import PIL

		from transformers import FlavaImageProcessor
		from transformers.image_utils import PILImageResampling
		from transformers.models.flava.image_processing_flava import (
		    FLAVA_CODEBOOK_MEAN,
		    FLAVA_CODEBOOK_STD,
		    FLAVA_IMAGE_MEAN,
		    FLAVA_IMAGE_STD,
		)
else:
		_lowercase					:					Tuple 		=		None

class 			__SCREAMING_SNAKE_CASE      ( unittest.TestCase  ):


					'''simple docstring'''





					def __init__(			self				:    List[str],    lowerCamelCase				:    Optional[Any],    lowerCamelCase				:    Optional[Any]=7,    lowerCamelCase				:    Tuple=3,    lowerCamelCase				:    List[Any]=30,    lowerCamelCase				:    Any=400,    lowerCamelCase				:    List[str]=True,    lowerCamelCase				:    Tuple=None,    lowerCamelCase				:    Optional[Any]=True,    lowerCamelCase				:    Any=None,    lowerCamelCase				:    str=None,    lowerCamelCase				:    Tuple=True,    lowerCamelCase				:    int=1 / 255,    lowerCamelCase				:    Optional[int]=True,    lowerCamelCase				:    List[str]=FLAVA_IMAGE_MEAN,    lowerCamelCase				:    Optional[Any]=FLAVA_IMAGE_STD,    lowerCamelCase				:    List[str]=14,    lowerCamelCase				:    str=75,    lowerCamelCase				:    Optional[int]=None,    lowerCamelCase				:    Union[str, Any]=16,    lowerCamelCase				:    List[Any]=0.3,    lowerCamelCase				:    List[Any]=None,    lowerCamelCase				:    int=True,    lowerCamelCase				:    Any=None,    lowerCamelCase				:    Tuple=None,    lowerCamelCase				:    int=True,    lowerCamelCase				:    str=None,    lowerCamelCase				:    Tuple=True,    lowerCamelCase				:    Any=True,    lowerCamelCase				:    List[Any]=FLAVA_CODEBOOK_MEAN,    lowerCamelCase				:    str=FLAVA_CODEBOOK_STD,    )->   Optional[Any]:
								lowerCamelCase__						:						Any						      =size if size is not None else {'''height''': 224, '''width''': 224}
								lowerCamelCase__						:						Optional[Any]						      =crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
								lowerCamelCase__						:						str						      =codebook_size if codebook_size is not None else {'''height''': 112, '''width''': 112}
								lowerCamelCase__						:						Optional[Any]						      =codebook_crop_size if codebook_crop_size is not None else {'''height''': 112, '''width''': 112}

								lowerCamelCase__						:						Any						      =parent
								lowerCamelCase__						:						Union[str, Any]						      =batch_size
								lowerCamelCase__						:						Tuple						      =num_channels
								lowerCamelCase__						:						Optional[int]						      =do_resize
								lowerCamelCase__						:						Union[str, Any]						      =do_rescale
								lowerCamelCase__						:						Dict						      =rescale_factor
								lowerCamelCase__						:						Optional[int]						      =min_resolution
								lowerCamelCase__						:						Optional[Any]						      =max_resolution
								lowerCamelCase__						:						Dict						      =size
								lowerCamelCase__						:						int						      =resample if resample is not None else PILImageResampling.BICUBIC
								lowerCamelCase__						:						Any						      =do_normalize
								lowerCamelCase__						:						Optional[int]						      =image_mean
								lowerCamelCase__						:						str						      =image_std
								lowerCamelCase__						:						Union[str, Any]						      =do_center_crop
								lowerCamelCase__						:						List[Any]						      =crop_size

								lowerCamelCase__						:						List[str]						      =input_size_patches
								lowerCamelCase__						:						int						      =total_mask_patches
								lowerCamelCase__						:						List[str]						      =mask_group_max_patches
								lowerCamelCase__						:						Any						      =mask_group_min_patches
								lowerCamelCase__						:						int						      =mask_group_min_aspect_ratio
								lowerCamelCase__						:						Any						      =mask_group_max_aspect_ratio

								lowerCamelCase__						:						Union[str, Any]						      =codebook_do_resize
								lowerCamelCase__						:						Any						      =codebook_size
								lowerCamelCase__						:						str						      =codebook_resample if codebook_resample is not None else PILImageResampling.LANCZOS
								lowerCamelCase__						:						Optional[Any]						      =codebook_do_center_crop
								lowerCamelCase__						:						Any						      =codebook_crop_size
								lowerCamelCase__						:						int						      =codebook_do_map_pixels
								lowerCamelCase__						:						Optional[int]						      =codebook_do_normalize
								lowerCamelCase__						:						Union[str, Any]						      =codebook_image_mean
								lowerCamelCase__						:						int						      =codebook_image_std



					def 						snake_case			(			self				:    Optional[int]	)->   int:
								return {
								    "image_mean": self.image_mean,
								    "image_std": self.image_std,
								    "do_normalize": self.do_normalize,
								    "do_resize": self.do_resize,
								    "size": self.size,
								    "resample": self.resample,
								    "do_rescale": self.do_rescale,
								    "rescale_factor": self.rescale_factor,
								    "do_center_crop": self.do_center_crop,
								    "crop_size": self.crop_size,
								    "input_size_patches": self.input_size_patches,
								    "total_mask_patches": self.total_mask_patches,
								    "mask_group_max_patches": self.mask_group_max_patches,
								    "mask_group_min_patches": self.mask_group_min_patches,
								    "mask_group_min_aspect_ratio": self.mask_group_min_aspect_ratio,
								    "mask_group_max_aspect_ratio": self.mask_group_min_aspect_ratio,
								    "codebook_do_resize": self.codebook_do_resize,
								    "codebook_size": self.codebook_size,
								    "codebook_resample": self.codebook_resample,
								    "codebook_do_center_crop": self.codebook_do_center_crop,
								    "codebook_crop_size": self.codebook_crop_size,
								    "codebook_do_map_pixels": self.codebook_do_map_pixels,
								    "codebook_do_normalize": self.codebook_do_normalize,
								    "codebook_image_mean": self.codebook_image_mean,
								    "codebook_image_std": self.codebook_image_std,
								}



					def 						snake_case			(			self				:    int	)->   Optional[int]:
								return (self.size["height"], self.size["width"])



					def 						snake_case			(			self				:    Optional[Any]	)->   Tuple:
								return (
								    (self.input_size_patches, self.input_size_patches)
								    if not isinstance(self.input_size_patches,    lowerCamelCase	)
								    else self.input_size_patches
								)




					def 						snake_case			(			self				:    Union[str, Any]	)->   Union[str, Any]:
								return (self.codebook_size["height"], self.codebook_size["width"])





@require_torch
@require_vision
class 			__SCREAMING_SNAKE_CASE      ( lowerCAmelCase_						,  unittest.TestCase  ):


					'''simple docstring'''





					_a       =				FlavaImageProcessor if is_vision_available() else None
					_a       =				None



					def 						snake_case			(			self				:    List[Any]	)->   str:
								lowerCamelCase__						:						str						      =FlavaImageProcessingTester(self	)



					@property
					def 						snake_case			(			self				:    Dict	)->   Dict:
								return self.image_processor_tester.prepare_image_processor_dict()



					def 						snake_case			(			self				:    Tuple	)->   Optional[int]:
								lowerCamelCase__						:						Tuple						      =self.image_processing_class(**self.image_processor_dict	)
								self.assertTrue(hasattr(lowerCamelCase,    '''image_mean'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''image_std'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''do_normalize'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''do_resize'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''resample'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''crop_size'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''do_center_crop'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''do_rescale'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''rescale_factor'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''masking_generator'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''codebook_do_resize'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''codebook_size'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''codebook_resample'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''codebook_do_center_crop'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''codebook_crop_size'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''codebook_do_map_pixels'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''codebook_do_normalize'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''codebook_image_mean'''	)	)
								self.assertTrue(hasattr(lowerCamelCase,    '''codebook_image_std'''	)	)



					def 						snake_case			(			self				:    Any	)->   Union[str, Any]:
								lowerCamelCase__						:						str						      =self.image_processing_class.from_dict(self.image_processor_dict	)
								self.assertEqual(image_processor.size,    {'''height''': 224, '''width''': 224}	)
								self.assertEqual(image_processor.crop_size,    {'''height''': 224, '''width''': 224}	)
								self.assertEqual(image_processor.codebook_size,    {'''height''': 112, '''width''': 112}	)
								self.assertEqual(image_processor.codebook_crop_size,    {'''height''': 112, '''width''': 112}	)

								lowerCamelCase__						:						List[str]						      =self.image_processing_class.from_dict(
								    self.image_processor_dict,    size=42,    crop_size=84,    codebook_size=33,    codebook_crop_size=66	)
								self.assertEqual(image_processor.size,    {'''height''': 42, '''width''': 42}	)
								self.assertEqual(image_processor.crop_size,    {'''height''': 84, '''width''': 84}	)
								self.assertEqual(image_processor.codebook_size,    {'''height''': 33, '''width''': 33}	)
								self.assertEqual(image_processor.codebook_crop_size,    {'''height''': 66, '''width''': 66}	)



					def 						snake_case			(			self				:    Optional[Any]	)->   Dict:
								pass



					def 						snake_case			(			self				:    int	)->   Optional[Any]:
								# Initialize image_processing
								lowerCamelCase__						:						Optional[int]						      =self.image_processing_class(**self.image_processor_dict	)
								# create random PIL images
								lowerCamelCase__						:						int						      =prepare_image_inputs(self.image_processor_tester,    equal_resolution=lowerCamelCase	)
								for image in image_inputs:
											self.assertIsInstance(lowerCamelCase,    PIL.Image.Image	)

								# Test not batched input
								lowerCamelCase__						:						List[Any]						      =image_processing(image_inputs[0],    return_tensors='''pt'''	)

								# Test no bool masked pos
								self.assertFalse('''bool_masked_pos''' in encoded_images	)

								lowerCamelCase__      ,  lowerCamelCase__						:						Union[str, Any]						      =self.image_processor_tester.get_expected_image_size()

								self.assertEqual(
								    encoded_images.pixel_values.shape,    (1, self.image_processor_tester.num_channels, expected_height, expected_width),    )

								# Test batched
								lowerCamelCase__						:						Dict						      =image_processing(lowerCamelCase,    return_tensors='''pt'''	)
								lowerCamelCase__      ,  lowerCamelCase__						:						int						      =self.image_processor_tester.get_expected_image_size()

								# Test no bool masked pos
								self.assertFalse('''bool_masked_pos''' in encoded_images	)

								self.assertEqual(
								    encoded_images.pixel_values.shape,    (
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        expected_height,
								        expected_width,
								    ),    )



					def 						snake_case			(			self				:    Union[str, Any],    lowerCamelCase				:    str,    lowerCamelCase				:    Tuple	)->   Optional[int]:
								# Initialize image_processing
								lowerCamelCase__						:						Tuple						      =self.image_processing_class(**self.image_processor_dict	)
								# create random tensors
								lowerCamelCase__						:						Union[str, Any]						      =prepare_image_inputs(self.image_processor_tester,    equal_resolution=lowerCamelCase,    **lowerCamelCase	)
								for image in image_inputs:
											self.assertIsInstance(lowerCamelCase,    lowerCamelCase	)

								# Test not batched input
								lowerCamelCase__						:						List[str]						      =image_processing(image_inputs[0],    return_tensors='''pt'''	)

								lowerCamelCase__      ,  lowerCamelCase__						:						int						      =self.image_processor_tester.get_expected_image_size()
								self.assertEqual(
								    encoded_images.pixel_values.shape,    (1, self.image_processor_tester.num_channels, expected_height, expected_width),    )

								lowerCamelCase__						:						List[str]						      =image_processing(lowerCamelCase,    return_image_mask=lowerCamelCase,    return_tensors='''pt'''	)

								lowerCamelCase__      ,  lowerCamelCase__						:						int						      =self.image_processor_tester.get_expected_image_size()
								self.assertEqual(
								    encoded_images.pixel_values.shape,    (
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        expected_height,
								        expected_width,
								    ),    )

								lowerCamelCase__      ,  lowerCamelCase__						:						Tuple						      =self.image_processor_tester.get_expected_mask_size()
								self.assertEqual(
								    encoded_images.bool_masked_pos.shape,    (
								        self.image_processor_tester.batch_size,
								        expected_height,
								        expected_width,
								    ),    )

								# Test batched
								lowerCamelCase__						:						int						      =image_processing(lowerCamelCase,    return_tensors='''pt'''	).pixel_values

								lowerCamelCase__      ,  lowerCamelCase__						:						int						      =self.image_processor_tester.get_expected_image_size()
								self.assertEqual(
								    encoded_images.shape,    (
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        expected_height,
								        expected_width,
								    ),    )

								# Test masking
								lowerCamelCase__						:						List[str]						      =image_processing(lowerCamelCase,    return_image_mask=lowerCamelCase,    return_tensors='''pt'''	)

								lowerCamelCase__      ,  lowerCamelCase__						:						Any						      =self.image_processor_tester.get_expected_image_size()
								self.assertEqual(
								    encoded_images.pixel_values.shape,    (
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        expected_height,
								        expected_width,
								    ),    )

								lowerCamelCase__      ,  lowerCamelCase__						:						str						      =self.image_processor_tester.get_expected_mask_size()
								self.assertEqual(
								    encoded_images.bool_masked_pos.shape,    (
								        self.image_processor_tester.batch_size,
								        expected_height,
								        expected_width,
								    ),    )



					def 						snake_case			(			self				:    Optional[int]	)->   Tuple:
								self._test_call_framework(np.ndarray,    prepare_kwargs={'''numpify''': True}	)



					def 						snake_case			(			self				:    Optional[Any]	)->   Dict:
								self._test_call_framework(torch.Tensor,    prepare_kwargs={'''torchify''': True}	)



					def 						snake_case			(			self				:    Dict	)->   int:
								# Initialize image_processing
								random.seed(1234	)
								lowerCamelCase__						:						Optional[int]						      =self.image_processing_class(**self.image_processor_dict	)
								lowerCamelCase__						:						Any						      =prepare_image_inputs(self.image_processor_tester,    equal_resolution=lowerCamelCase,    torchify=lowerCamelCase	)

								# Test not batched input
								lowerCamelCase__						:						List[str]						      =image_processing(image_inputs[0],    return_image_mask=lowerCamelCase,    return_tensors='''pt'''	)
								self.assertEqual(encoded_images.bool_masked_pos.sum().item(),    75	)




					def 						snake_case			(			self				:    List[Any]	)->   str:
								# Initialize image_processing
								lowerCamelCase__						:						List[Any]						      =self.image_processing_class(**self.image_processor_dict	)
								# create random PIL images
								lowerCamelCase__						:						List[Any]						      =prepare_image_inputs(self.image_processor_tester,    equal_resolution=lowerCamelCase	)
								for image in image_inputs:
											self.assertIsInstance(lowerCamelCase,    PIL.Image.Image	)

								# Test not batched input
								lowerCamelCase__						:						Optional[Any]						      =image_processing(image_inputs[0],    return_codebook_pixels=lowerCamelCase,    return_tensors='''pt'''	)
								lowerCamelCase__      ,  lowerCamelCase__						:						Dict						      =self.image_processor_tester.get_expected_codebook_image_size()
								self.assertEqual(
								    encoded_images.codebook_pixel_values.shape,    (1, self.image_processor_tester.num_channels, expected_height, expected_width),    )

								# Test batched
								lowerCamelCase__						:						List[Any]						      =image_processing(lowerCamelCase,    return_codebook_pixels=lowerCamelCase,    return_tensors='''pt'''	)
								lowerCamelCase__      ,  lowerCamelCase__						:						int						      =self.image_processor_tester.get_expected_codebook_image_size()
								self.assertEqual(
								    encoded_images.codebook_pixel_values.shape,    (
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        expected_height,
								        expected_width,
								    ),    )










from functools import partial
from typing import Any, Callable, Dict, List, Type, TypeVar, Union, overload

import torch
import torch.nn as nn
import torch.types




def    lowerCamelCase__			(		A__			:   torch.Tensor    ,     A__			:   torch.Tensor    ,     A__			:   bool      ):





       '''simple docstring'''



       if not inplace:
              __lowerCamelCase  =		ma + ma
       else:
              ma += ma

       return ma




def    lowerCamelCase__			(		A__			:   torch.Tensor    ,     A__			:   List[int]      ):





       '''simple docstring'''



       __lowerCamelCase  =		-1 * len(A__      )
       __lowerCamelCase  =		list(range(len(tensor.shape[:zero_index]      )      )      )
       return tensor.permute(first_inds + [zero_index + i for i in inds]      )




def    lowerCamelCase__			(		A__			:   torch.Tensor    ,     A__			:   int      ):





       '''simple docstring'''



       return t.reshape(t.shape[:-no_dims] + (-1,)      )




def    lowerCamelCase__			(		A__			:   torch.Tensor    ,     A__			:   torch.Tensor    ,     A__			:   int    ,     A__			:   float = 1E-4      ):





       '''simple docstring'''



       __lowerCamelCase  =		mask.expand(*value.shape      )
       return torch.sum(mask * value    ,     dim=A__      ) / (eps + torch.sum(A__    ,     dim=A__      ))




def    lowerCamelCase__			(		A__			:   torch.Tensor    ,     A__			:   torch.types.Number = 2.3_125    ,     A__			:   torch.types.Number = 21.6_875    ,     A__			:   int = 64      ):





       '''simple docstring'''



       __lowerCamelCase  =		torch.linspace(A__    ,     A__    ,     no_bins - 1    ,     device=pts.device      )
       __lowerCamelCase  =		torch.sqrt(torch.sum((pts.unsqueeze(-2      ) - pts.unsqueeze(-3      )) ** 2    ,     dim=-1      )      )
       return torch.bucketize(A__    ,     A__      )




def    lowerCamelCase__			(		A__			:   Callable[[list], Any]    ,     A__			:   List[dict]      ):





       '''simple docstring'''



       __lowerCamelCase  =		dicts[0]
       __lowerCamelCase  =		{}
       for k, v in first.items():
              __lowerCamelCase  =		[d[k] for d in dicts]
              if isinstance(A__    ,     A__      ):
                     __lowerCamelCase  =		dict_multimap(A__    ,     A__      )
              else:
                     __lowerCamelCase  =		fn(A__      )

       return new_dict




def    lowerCamelCase__			(		A__			:   torch.Tensor    ,     A__			:   torch.Tensor      ):





       '''simple docstring'''



       __lowerCamelCase  =		v_bins.view(((1,) * len(x.shape      )) + (len(A__      ),)      )
       __lowerCamelCase  =		x[..., None] - reshaped_bins
       __lowerCamelCase  =		torch.argmin(torch.abs(A__      )    ,     dim=-1      )
       return nn.functional.one_hot(A__    ,     num_classes=len(A__      )      ).float()




def    lowerCamelCase__			(		A__			:   torch.Tensor    ,     A__			:   torch.Tensor    ,     A__			:   int = 0    ,     A__			:   int = 0      ):





       '''simple docstring'''



       __lowerCamelCase  =		[]
       for i, s in enumerate(data.shape[:no_batch_dims]      ):
              __lowerCamelCase  =		torch.arange(A__      )
              __lowerCamelCase  =		r.view(*(*((1,) * i), -1, *((1,) * (len(inds.shape      ) - i - 1)))      )
              ranges.append(A__      )

       __lowerCamelCase  =		[slice(A__      ) for _ in range(len(data.shape      ) - no_batch_dims      )]
       __lowerCamelCase  =		inds
       ranges.extend(A__      )
       # Matt note: Editing this to get around the behaviour of using a list as an array index changing
       # in recent Numpy versions
       return data[tuple(A__      )]


UpperCAmelCase_   							=      TypeVar('T')




def    lowerCamelCase__			(		A__			:   Callable[[T], Any]    ,     A__			:   Dict[Any, Union[dict, list, tuple, T]]    ,     A__			:   Type[T]      ):





       '''simple docstring'''



       __lowerCamelCase  =		{}
       for k, v in dic.items():
              if isinstance(A__    ,     A__      ):
                     __lowerCamelCase  =		dict_map(A__    ,     A__    ,     A__      )
              else:
                     __lowerCamelCase  =		tree_map(A__    ,     A__    ,     A__      )

       return new_dict




@overload
def    lowerCamelCase__			(		A__			:   Callable[[T], Any]    ,     A__			:   T    ,     A__			:   Type[T]      ):





       '''simple docstring'''



       ...




@overload
def    lowerCamelCase__			(		A__			:   Callable[[T], Any]    ,     A__			:   dict    ,     A__			:   Type[T]      ):





       '''simple docstring'''



       ...




@overload
def    lowerCamelCase__			(		A__			:   Callable[[T], Any]    ,     A__			:   list    ,     A__			:   Type[T]      ):





       '''simple docstring'''



       ...




@overload
def    lowerCamelCase__			(		A__			:   Callable[[T], Any]    ,     A__			:   tuple    ,     A__			:   Type[T]      ):





       '''simple docstring'''



       ...




def    lowerCamelCase__			(		A__			:   Dict    ,     A__			:   List[str]    ,     A__			:   List[str]      ):





       '''simple docstring'''



       if isinstance(A__    ,     A__      ):
              return dict_map(A__    ,     A__    ,     A__      )
       elif isinstance(A__    ,     A__      ):
              return [tree_map(A__    ,     A__    ,     A__      ) for x in tree]
       elif isinstance(A__    ,     A__      ):
              return tuple(tree_map(A__    ,     A__    ,     A__      ) for x in tree      )
       elif isinstance(A__    ,     A__      ):
              return fn(A__      )
       else:
              print(type(A__      )      )
              raise ValueError("""Not supported"""      )




UpperCAmelCase_   							=      partial(tree_map, leaf_type=torch.Tensor)

