
'''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      snake_case__    (	unittest.TestCase ):







		"""simple docstring"""

		def __init__(	self							:       Dict   ,     UpperCamelCase__							:       str   ,     UpperCamelCase__							:       Optional[Any]=7   ,     UpperCamelCase__							:       Union[str, Any]=3   ,     UpperCamelCase__							:       str=10   ,     UpperCamelCase__							:       List[Any]=18   ,     UpperCamelCase__							:       Optional[Any]=30   ,     UpperCamelCase__							:       Optional[Any]=400   ,     UpperCamelCase__							:       List[Any]=True   ,     UpperCamelCase__							:       Union[str, Any]=None   ,     UpperCamelCase__							:       int=True   ,     UpperCamelCase__							:       int=[0.5, 0.5, 0.5]   ,     UpperCamelCase__							:       Optional[Any]=[0.5, 0.5, 0.5]   ,     UpperCamelCase__							:       List[Any]=None   ,     )		->       Optional[int]:






				"""simple docstring"""







				snake_case   :    Dict			       =		size if size is not None else {'''shortest_edge''': 18}
				snake_case   :    Union[str, Any]			       =		crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

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



		def 	lowerCAmelCase							(	self							:       Union[str, Any]	)		->       Optional[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      snake_case__    (	__SCREAMING_SNAKE_CASE  , unittest.TestCase ):







		"""simple docstring"""

		lowerCamelCase							=		VideoMAEImageProcessor if is_vision_available() else None



		def 	lowerCAmelCase							(	self							:       Union[str, Any]	)		->       Optional[int]:






				"""simple docstring"""







				snake_case   :    str			       =		VideoMAEImageProcessingTester(self	)



		@property
		def 	lowerCAmelCase							(	self							:       List[Any]	)		->       int:






				"""simple docstring"""







				return self.image_processor_tester.prepare_image_processor_dict()



		def 	lowerCAmelCase							(	self							:       Optional[Any]	)		->       Tuple:






				"""simple docstring"""







				snake_case   :    int			       =		self.image_processing_class(**self.image_processor_dict	)
				self.assertTrue(hasattr(UpperCamelCase__   ,     '''image_mean'''	)	)
				self.assertTrue(hasattr(UpperCamelCase__   ,     '''image_std'''	)	)
				self.assertTrue(hasattr(UpperCamelCase__   ,     '''do_normalize'''	)	)
				self.assertTrue(hasattr(UpperCamelCase__   ,     '''do_resize'''	)	)
				self.assertTrue(hasattr(UpperCamelCase__   ,     '''do_center_crop'''	)	)
				self.assertTrue(hasattr(UpperCamelCase__   ,     '''size'''	)	)



		def 	lowerCAmelCase							(	self							:       List[Any]	)		->       Optional[Any]:






				"""simple docstring"""







				snake_case   :    Any			       =		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}	)

				snake_case   :    Optional[int]			       =		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 	lowerCAmelCase							(	self							:       Tuple	)		->       Optional[Any]:






				"""simple docstring"""







				pass



		def 	lowerCAmelCase							(	self							:       Optional[Any]	)		->       Tuple:






				"""simple docstring"""







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

				# Test not batched input
				snake_case   :    Union[str, Any]			       =		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
				snake_case   :    Optional[int]			       =		image_processing(UpperCamelCase__   ,     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 	lowerCAmelCase							(	self							:       List[Any]	)		->       Union[str, Any]:






				"""simple docstring"""







				snake_case   :    Optional[int]			       =		self.image_processing_class(**self.image_processor_dict	)
				# create random numpy tensors
				snake_case   :    Optional[Any]			       =		prepare_video_inputs(self.image_processor_tester   ,     equal_resolution=UpperCamelCase__   ,     numpify=UpperCamelCase__	)
				for video in video_inputs:
						self.assertIsInstance(UpperCamelCase__   ,     UpperCamelCase__	)
						self.assertIsInstance(video[0]   ,     np.ndarray	)

				# Test not batched input
				snake_case   :    Optional[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
				snake_case   :    int			       =		image_processing(UpperCamelCase__   ,     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 	lowerCAmelCase							(	self							:       Any	)		->       List[Any]:






				"""simple docstring"""







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

				# Test not batched input
				snake_case   :    Union[str, Any]			       =		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
				snake_case   :    Dict			       =		image_processing(UpperCamelCase__   ,     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'''],
				    )   ,     )




'''simple docstring'''
from typing import SupportsIndex

import numpy as np
from scipy.ndimage import convolve







def 						A_(			A		:						np.ndarray						,			A		:						np.ndarray						,			A		:						np.ndarray):
							UpperCamelCase					       =			np.stack((horizontal_flow, vertical_flow)						,			2)

							# Create a grid of all pixel coordinates and subtract the flow to get the
							# target pixels coordinates
							UpperCamelCase					       =			np.stack(
							    np.meshgrid(np.arange(0						,			image.shape[1])						,			np.arange(0						,			image.shape[0]))						,			2)
							UpperCamelCase					       =			np.round(grid - flow).astype(np.intaa)

							# Find the locations outside of the original image
							UpperCamelCase					       =			(grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]]))
							UpperCamelCase					       =			0

							UpperCamelCase					       =			image[grid[:, :, 1], grid[:, :, 0]]

							# Set pixels at invalid locations to 0
							UpperCamelCase					       =			0

							return warped







def 						A_(			A		:						np.ndarray						,			A		:						np.ndarray						,			A		:						SupportsIndex						,			A		:						float | None = None						,			):
							if alpha is None:
														UpperCamelCase					       =			0.1

							# Initialize flow
							UpperCamelCase					       =			np.zeros_like(A)
							UpperCamelCase					       =			np.zeros_like(A)

							# Prepare kernels for the calculation of the derivatives and the average velocity
							UpperCamelCase					       =			np.array([[-1, 1], [-1, 1]]) * 0.25
							UpperCamelCase					       =			np.array([[-1, -1], [1, 1]]) * 0.25
							UpperCamelCase					       =			np.array([[1, 1], [1, 1]]) * 0.25
							UpperCamelCase					       =			np.array(
							    [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]])

							# Iteratively refine the flow
							for _ in range(A):
														UpperCamelCase					       =			warp(A						,			A						,			A)
														UpperCamelCase					       =			convolve(A						,			A) + convolve(A						,			A)
														UpperCamelCase					       =			convolve(A						,			A) + convolve(A						,			A)
														UpperCamelCase					       =			convolve(A						,			A) + convolve(A						,			-kernel_t)

														UpperCamelCase					       =			convolve(A						,			A)
														UpperCamelCase					       =			convolve(A						,			A)

														# This updates the flow as proposed in the paper (Step 12)
														UpperCamelCase					       =			(
														    derivative_x * avg_horizontal_velocity
														    + derivative_y * avg_vertical_velocity
														    + derivative_t
														)
														UpperCamelCase					       =			update / (alpha**2 + derivative_x**2 + derivative_y**2)

														UpperCamelCase					       =			avg_horizontal_velocity - derivative_x * update
														UpperCamelCase					       =			avg_vertical_velocity - derivative_y * update

							return horizontal_flow, vertical_flow


if __name__ == "__main__":
						import doctest

						doctest.testmod()




