
'''simple docstring'''





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 snake_case_    (				lowercase__      ,					lowercase__      ,					lowercase__		):






  if not inplace:
    UpperCAmelCase__			:				Dict												=       ma + ma
  else:
    ma += ma

  return ma







def snake_case_    (				lowercase__      ,					lowercase__		):
  UpperCAmelCase__			:				Dict												=       -1 * len(UpperCamelCase__		)
  UpperCAmelCase__			:				Union[str, Any]												=       list(range(len(tensor.shape[:zero_index]		)		)		)
  return tensor.permute(first_inds + [zero_index + i for i in inds]		)







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







def snake_case_    (				lowercase__      ,					lowercase__      ,					lowercase__      ,					lowercase__ = 1E-4		):
  UpperCAmelCase__			:				List[str]												=       mask.expand(*value.shape		)
  return torch.sum(mask * value      ,					dim=UpperCamelCase__		) / (eps + torch.sum(UpperCamelCase__      ,					dim=UpperCamelCase__		))







def snake_case_    (				lowercase__      ,					lowercase__ = 2.3125      ,					lowercase__ = 21.6875      ,					lowercase__ = 6_4		):
  UpperCAmelCase__			:				List[str]												=       torch.linspace(UpperCamelCase__      ,					UpperCamelCase__      ,					no_bins - 1      ,					device=pts.device		)
  UpperCAmelCase__			:				Optional[Any]												=       torch.sqrt(torch.sum((pts.unsqueeze(-2		) - pts.unsqueeze(-3		)) ** 2      ,					dim=-1		)		)
  return torch.bucketize(UpperCamelCase__      ,					UpperCamelCase__		)







def snake_case_    (				lowercase__      ,					lowercase__		):
  UpperCAmelCase__			:				int												=       dicts[0]
  UpperCAmelCase__			:				List[str]												=       {}
  for k, v in first.items():
    UpperCAmelCase__			:				Union[str, Any]												=       [d[k] for d in dicts]
    if isinstance(UpperCamelCase__      ,					UpperCamelCase__		):
      UpperCAmelCase__			:				int												=       dict_multimap(UpperCamelCase__      ,					UpperCamelCase__		)
    else:
      UpperCAmelCase__			:				str												=       fn(UpperCamelCase__		)

  return new_dict







def snake_case_    (				lowercase__      ,					lowercase__		):
  UpperCAmelCase__			:				Tuple												=       v_bins.view(((1,) * len(x.shape		)) + (len(UpperCamelCase__		),)		)
  UpperCAmelCase__			:				Optional[Any]												=       x[..., None] - reshaped_bins
  UpperCAmelCase__			:				Dict												=       torch.argmin(torch.abs(UpperCamelCase__		)      ,					dim=-1		)
  return nn.functional.one_hot(UpperCamelCase__      ,					num_classes=len(UpperCamelCase__		)		).float()







def snake_case_    (				lowercase__      ,					lowercase__      ,					lowercase__ = 0      ,					lowercase__ = 0		):
  UpperCAmelCase__			:				Optional[Any]												=       []
  for i, s in enumerate(data.shape[:no_batch_dims]		):
    UpperCAmelCase__			:				Optional[int]												=       torch.arange(UpperCamelCase__		)
    UpperCAmelCase__			:				int												=       r.view(*(*((1,) * i), -1, *((1,) * (len(inds.shape		) - i - 1)))		)
    ranges.append(UpperCamelCase__		)

  UpperCAmelCase__			:				List[Any]												=       [slice(UpperCamelCase__		) for _ in range(len(data.shape		) - no_batch_dims		)]
  UpperCAmelCase__			:				Any												=       inds
  ranges.extend(UpperCamelCase__		)
  # 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(UpperCamelCase__		)]


SCREAMING_SNAKE_CASE    =					TypeVar("""T""")







def snake_case_    (				lowercase__      ,					lowercase__      ,					lowercase__		):
  UpperCAmelCase__			:				str												=       {}
  for k, v in dic.items():
    if isinstance(UpperCamelCase__      ,					UpperCamelCase__		):
      UpperCAmelCase__			:				int												=       dict_map(UpperCamelCase__      ,					UpperCamelCase__      ,					UpperCamelCase__		)
    else:
      UpperCAmelCase__			:				int												=       tree_map(UpperCamelCase__      ,					UpperCamelCase__      ,					UpperCamelCase__		)

  return new_dict







@overload
def snake_case_    (				lowercase__      ,					lowercase__      ,					lowercase__		):
  ...







@overload
def snake_case_    (				lowercase__      ,					lowercase__      ,					lowercase__		):
  ...







@overload
def snake_case_    (				lowercase__      ,					lowercase__      ,					lowercase__		):
  ...







@overload
def snake_case_    (				lowercase__      ,					lowercase__      ,					lowercase__		):
  ...







def snake_case_    (				lowercase__      ,					lowercase__      ,					lowercase__		):






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






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





'''simple docstring'''





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_video_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import VideoMAEImageProcessor






class        UpperCAmelCase_       (						unittest.TestCase							):

 '''simple docstring'''







 def __init__(				self		:     str ,							snake_case__		:     Optional[int] ,							snake_case__		:     Union[str, Any]=7 ,							snake_case__		:     Any=3 ,							snake_case__		:     Tuple=10 ,							snake_case__		:     Dict=18 ,							snake_case__		:     Dict=30 ,							snake_case__		:     Tuple=4_00 ,							snake_case__		:     str=True ,							snake_case__		:     Optional[Any]=None ,							snake_case__		:     Union[str, Any]=True ,							snake_case__		:     List[Any]=[0.5, 0.5, 0.5] ,							snake_case__		:     Dict=[0.5, 0.5, 0.5] ,							snake_case__		:     Tuple=None ,							):



   '''simple docstring'''




   UpperCAmelCase__			:				List[str]												=       size if size is not None else {"shortest_edge": 18}
   UpperCAmelCase__			:				Optional[int]												=       crop_size if crop_size is not None else {"height": 18, "width": 18}

   UpperCAmelCase__			:				List[Any]												=       parent
   UpperCAmelCase__			:				Optional[Any]												=       batch_size
   UpperCAmelCase__			:				int												=       num_channels
   UpperCAmelCase__			:				str												=       num_frames
   UpperCAmelCase__			:				List[Any]												=       image_size
   UpperCAmelCase__			:				Optional[int]												=       min_resolution
   UpperCAmelCase__			:				int												=       max_resolution
   UpperCAmelCase__			:				Optional[int]												=       do_resize
   UpperCAmelCase__			:				List[str]												=       size
   UpperCAmelCase__			:				Optional[int]												=       do_normalize
   UpperCAmelCase__			:				int												=       image_mean
   UpperCAmelCase__			:				Any												=       image_std
   UpperCAmelCase__			:				Optional[int]												=       crop_size







 def        UpperCamelCase     (				self		:     Union[str, Any]   ):



   '''simple docstring'''




   return {
       "image_mean": self.image_mean,
       "image_std": self.image_std,
       "do_normalize": self.do_normalize,
       "do_resize": self.do_resize,
       "size": self.size,
       "crop_size": self.crop_size,
   }






@require_torch
@require_vision
class        UpperCAmelCase_       (						A				,							unittest.TestCase							):

 '''simple docstring'''
 lowercase_				:						Any				=       VideoMAEImageProcessor if is_vision_available() else None







 def        UpperCamelCase     (				self		:     List[str]   ):



   '''simple docstring'''




   UpperCAmelCase__			:				Optional[int]												=       VideoMAEImageProcessingTester(self   )







 @property
 def        UpperCamelCase     (				self		:     Any   ):



   '''simple docstring'''




   return self.image_processor_tester.prepare_image_processor_dict()







 def        UpperCamelCase     (				self		:     Any   ):



   '''simple docstring'''




   UpperCAmelCase__			:				str												=       self.image_processing_class(**self.image_processor_dict   )
   self.assertTrue(hasattr(snake_case__ ,							"image_mean"   )   )
   self.assertTrue(hasattr(snake_case__ ,							"image_std"   )   )
   self.assertTrue(hasattr(snake_case__ ,							"do_normalize"   )   )
   self.assertTrue(hasattr(snake_case__ ,							"do_resize"   )   )
   self.assertTrue(hasattr(snake_case__ ,							"do_center_crop"   )   )
   self.assertTrue(hasattr(snake_case__ ,							"size"   )   )







 def        UpperCamelCase     (				self		:     Tuple   ):



   '''simple docstring'''




   UpperCAmelCase__			:				int												=       self.image_processing_class.from_dict(self.image_processor_dict   )
   self.assertEqual(image_processor.size ,							{"shortest_edge": 18}   )
   self.assertEqual(image_processor.crop_size ,							{"height": 18, "width": 18}   )

   UpperCAmelCase__			:				Union[str, Any]												=       self.image_processing_class.from_dict(self.image_processor_dict ,							size=42 ,							crop_size=84   )
   self.assertEqual(image_processor.size ,							{"shortest_edge": 42}   )
   self.assertEqual(image_processor.crop_size ,							{"height": 84, "width": 84}   )







 def        UpperCamelCase     (				self		:     Optional[int]   ):



   '''simple docstring'''




   pass







 def        UpperCamelCase     (				self		:     Union[str, Any]   ):



   '''simple docstring'''




   UpperCAmelCase__			:				List[str]												=       self.image_processing_class(**self.image_processor_dict   )
   # create random PIL videos
   UpperCAmelCase__			:				Optional[int]												=       prepare_video_inputs(self.image_processor_tester ,							equal_resolution=snake_case__   )
   for video in video_inputs:
     self.assertIsInstance(snake_case__ ,							snake_case__   )
     self.assertIsInstance(video[0] ,							Image.Image   )

   # Test not batched input
   UpperCAmelCase__			:				Dict												=       image_processing(video_inputs[0] ,							return_tensors="pt"   ).pixel_values
   self.assertEqual(
       encoded_videos.shape ,							(
           1,
           self.image_processor_tester.num_frames,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       ) ,							)

   # Test batched
   UpperCAmelCase__			:				Tuple												=       image_processing(snake_case__ ,							return_tensors="pt"   ).pixel_values
   self.assertEqual(
       encoded_videos.shape ,							(
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_frames,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       ) ,							)







 def        UpperCamelCase     (				self		:     Union[str, Any]   ):



   '''simple docstring'''




   UpperCAmelCase__			:				Dict												=       self.image_processing_class(**self.image_processor_dict   )
   # create random numpy tensors
   UpperCAmelCase__			:				List[Any]												=       prepare_video_inputs(self.image_processor_tester ,							equal_resolution=snake_case__ ,							numpify=snake_case__   )
   for video in video_inputs:
     self.assertIsInstance(snake_case__ ,							snake_case__   )
     self.assertIsInstance(video[0] ,							np.ndarray   )

   # Test not batched input
   UpperCAmelCase__			:				Dict												=       image_processing(video_inputs[0] ,							return_tensors="pt"   ).pixel_values
   self.assertEqual(
       encoded_videos.shape ,							(
           1,
           self.image_processor_tester.num_frames,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       ) ,							)

   # Test batched
   UpperCAmelCase__			:				Optional[int]												=       image_processing(snake_case__ ,							return_tensors="pt"   ).pixel_values
   self.assertEqual(
       encoded_videos.shape ,							(
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_frames,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       ) ,							)







 def        UpperCamelCase     (				self		:     Dict   ):



   '''simple docstring'''




   UpperCAmelCase__			:				int												=       self.image_processing_class(**self.image_processor_dict   )
   # create random PyTorch tensors
   UpperCAmelCase__			:				Dict												=       prepare_video_inputs(self.image_processor_tester ,							equal_resolution=snake_case__ ,							torchify=snake_case__   )
   for video in video_inputs:
     self.assertIsInstance(snake_case__ ,							snake_case__   )
     self.assertIsInstance(video[0] ,							torch.Tensor   )

   # Test not batched input
   UpperCAmelCase__			:				int												=       image_processing(video_inputs[0] ,							return_tensors="pt"   ).pixel_values
   self.assertEqual(
       encoded_videos.shape ,							(
           1,
           self.image_processor_tester.num_frames,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       ) ,							)

   # Test batched
   UpperCAmelCase__			:				Optional[Any]												=       image_processing(snake_case__ ,							return_tensors="pt"   ).pixel_values
   self.assertEqual(
       encoded_videos.shape ,							(
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_frames,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       ) ,							)



