




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 VivitImageProcessor


class    SCREAMING_SNAKE_CASE_				(       unittest.TestCase   ):



	"""simple docstring"""


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







						"""simple docstring"""







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

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






	def 					lowerCamelCase__     (					self		:						Optional[int]	)	->       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    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase	,  unittest.TestCase   ):



	"""simple docstring"""


	__magic_name__   :       Dict      	=		VivitImageProcessor if is_vision_available() else None






	def 					lowerCamelCase__     (					self		:						int	)	->       Tuple:







						"""simple docstring"""







						__UpperCamelCase					:	List[Any]             =      VivitImageProcessingTester(self	)






	@property
	def 					lowerCamelCase__     (					self		:						Union[str, Any]	)	->       Any:







						"""simple docstring"""







						return self.image_processor_tester.prepare_image_processor_dict()






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







						"""simple docstring"""







						__UpperCamelCase					:	int             =      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					,     """do_center_crop"""	)	)
						self.assertTrue(hasattr(lowerCAmelCase					,     """size"""	)	)






	def 					lowerCamelCase__     (					self		:						Any	)	->       str:







						"""simple docstring"""







						__UpperCamelCase					:	Dict             =      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					:	str             =      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		:						List[Any]	)	->       List[Any]:







						"""simple docstring"""







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

						# Test not batched input
						__UpperCamelCase					:	str             =      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					:	Dict             =      image_processing(lowerCAmelCase					,     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[str]	)	->       List[str]:







						"""simple docstring"""







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

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







						"""simple docstring"""







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

						# Test not batched input
						__UpperCamelCase					:	Optional[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
						__UpperCamelCase					:	Any             =      image_processing(lowerCAmelCase					,     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"""],
						    )					,     )












# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import torch

from accelerate import PartialState
from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce





def 				A__ (snake_case   :		List[Any]				)     ->						Optional[Any]:
					return (torch.arange(state.num_processes				) + 1.0 + (state.num_processes * state.process_index)).to(state.device				)





def 				A__ (snake_case   :		int				)     ->						Any:
					__UpperCamelCase					:	List[str]             =      create_tensor(snake_case				)
					__UpperCamelCase					:	List[Any]             =      gather(snake_case				)
					assert gathered_tensor.tolist() == list(range(1		,	state.num_processes**2 + 1				)				)





def 				A__ (snake_case   :		Optional[Any]				)     ->						Dict:
					__UpperCamelCase					:	Any             =      [state.process_index]
					__UpperCamelCase					:	int             =      gather_object(snake_case				)
					assert len(snake_case				) == state.num_processes, F'''{gathered_obj}, {len(snake_case				)} != {state.num_processes}'''
					assert gathered_obj == list(range(state.num_processes				)				), F'''{gathered_obj} != {list(range(state.num_processes				)				)}'''





def 				A__ (snake_case   :		Any				)     ->						Optional[Any]:
					__UpperCamelCase					:	Optional[Any]             =      create_tensor(snake_case				)
					__UpperCamelCase					:	Any             =      broadcast(snake_case				)
					assert broadcasted_tensor.shape == torch.Size([state.num_processes]				)
					assert broadcasted_tensor.tolist() == list(range(1		,	state.num_processes + 1				)				)





def 				A__ (snake_case   :		Tuple				)     ->						Dict:
					# We need to pad the tensor with one more element if we are the main process
					# to ensure that we can pad
					if state.is_main_process:
										__UpperCamelCase					:	List[Any]             =      torch.arange(state.num_processes + 1				).to(state.device				)
					else:
										__UpperCamelCase					:	List[str]             =      torch.arange(state.num_processes				).to(state.device				)
					__UpperCamelCase					:	List[str]             =      pad_across_processes(snake_case				)
					assert padded_tensor.shape == torch.Size([state.num_processes + 1]				)
					if not state.is_main_process:
										assert padded_tensor.tolist() == list(range(0		,	state.num_processes				)				) + [0]





def 				A__ (snake_case   :		Tuple				)     ->						Dict:
					# For now runs on only two processes
					if state.num_processes != 2:
										return
					__UpperCamelCase					:	Optional[int]             =      create_tensor(snake_case				)
					__UpperCamelCase					:	str             =      reduce(snake_case		,	"""sum"""				)
					__UpperCamelCase					:	Optional[int]             =      torch.tensor([4.0, 6]				).to(state.device				)
					assert torch.allclose(snake_case		,	snake_case				), F'''{reduced_tensor} != {truth_tensor}'''





def 				A__ (snake_case   :		Optional[Any]				)     ->						Optional[Any]:
					# For now runs on only two processes
					if state.num_processes != 2:
										return
					__UpperCamelCase					:	List[Any]             =      create_tensor(snake_case				)
					__UpperCamelCase					:	str             =      reduce(snake_case		,	"""mean"""				)
					__UpperCamelCase					:	Union[str, Any]             =      torch.tensor([2.0, 3]				).to(state.device				)
					assert torch.allclose(snake_case		,	snake_case				), F'''{reduced_tensor} != {truth_tensor}'''





def 				A__ (snake_case   :		Tuple				)     ->						int:
					# For xla_spawn (TPUs)
					main()





def 				A__ ()     ->						List[Any]:
					__UpperCamelCase					:	List[Any]             =      PartialState()
					state.print(F'''State: {state}'''				)
					state.print("""testing gather"""				)
					test_gather(snake_case				)
					state.print("""testing gather_object"""				)
					test_gather_object(snake_case				)
					state.print("""testing broadcast"""				)
					test_broadcast(snake_case				)
					state.print("""testing pad_across_processes"""				)
					test_pad_across_processes(snake_case				)
					state.print("""testing reduce_sum"""				)
					test_reduce_sum(snake_case				)
					state.print("""testing reduce_mean"""				)
					test_reduce_mean(snake_case				)


if __name__ == "__main__":
	main()






