
'''simple docstring'''
import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available


if is_torch_available():
						import numpy as np
						import torch

if is_vision_available():
						from PIL import Image







def 						A_(			A		:						int						,			A		:						Dict=False						,			A		:						List[Any]=False						,			A		:						List[str]=False):
							assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

							UpperCamelCase					       =			[]
							for i in range(image_processor_tester.batch_size):
														if equal_resolution:
																					UpperCamelCase					       =			UpperCamelCase					       =			image_processor_tester.max_resolution
														else:
																					# To avoid getting image width/height 0
																					UpperCamelCase					       =			image_processor_tester.min_resolution
																					if getattr(A						,			'size_divisor'						,			A):
																												# If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
																												UpperCamelCase					       =			max(image_processor_tester.size_divisor						,			A)
																					UpperCamelCase       ,     UpperCamelCase					       =			np.random.choice(np.arange(A						,			image_processor_tester.max_resolution)						,			2)
														image_inputs.append(
														    np.random.randint(255						,			size=(image_processor_tester.num_channels, width, height)						,			dtype=np.uinta))

							if not numpify and not torchify:
														# PIL expects the channel dimension as last dimension
														UpperCamelCase					       =			[Image.fromarray(np.moveaxis(A						,			0						,			-1)) for image in image_inputs]

							if torchify:
														UpperCamelCase					       =			[torch.from_numpy(A) for image in image_inputs]

							return image_inputs







def 						A_(			A		:						Optional[Any]						,			A		:						Optional[int]=10						,			A		:						List[Any]=10						,			A		:						Optional[Any]=False						,			A		:						List[str]=False):
							UpperCamelCase					       =			[]
							for i in range(image_processor_tester.num_frames):
														video.append(np.random.randint(255						,			size=(image_processor_tester.num_channels, width, height)						,			dtype=np.uinta))

							if not numpify and not torchify:
														# PIL expects the channel dimension as last dimension
														UpperCamelCase					       =			[Image.fromarray(np.moveaxis(A						,			0						,			-1)) for frame in video]

							if torchify:
														UpperCamelCase					       =			[torch.from_numpy(A) for frame in video]

							return video







def 						A_(			A		:						str						,			A		:						Optional[int]=False						,			A		:						Tuple=False						,			A		:						List[str]=False):
							assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

							UpperCamelCase					       =			[]
							for i in range(image_processor_tester.batch_size):
														if equal_resolution:
																					UpperCamelCase					       =			UpperCamelCase					       =			image_processor_tester.max_resolution
														else:
																					UpperCamelCase       ,     UpperCamelCase					       =			np.random.choice(
																					    np.arange(image_processor_tester.min_resolution						,			image_processor_tester.max_resolution)						,			2)
																					UpperCamelCase					       =			prepare_video(
																					    image_processor_tester=A						,			width=A						,			height=A						,			numpify=A						,			torchify=A						,			)
														video_inputs.append(A)

							return video_inputs





class        SCREAMING_SNAKE_CASE__	:
				lowerCAmelCase_			       =				None







				def 		UpperCAmelCase_  (    self			)->						Tuple:







											'''simple docstring'''






											UpperCamelCase					       =			self.image_processing_class(**self.image_processor_dict			)
											UpperCamelCase					       =			json.loads(image_processor.to_json_string()			)
											for key, value in self.image_processor_dict.items():
																		self.assertEqual(obj[key]		,							A_			)







				def 		UpperCAmelCase_  (    self			)->						List[Any]:







											'''simple docstring'''






											UpperCamelCase					       =			self.image_processing_class(**self.image_processor_dict			)

											with tempfile.TemporaryDirectory() as tmpdirname:
																		UpperCamelCase					       =			os.path.join(A_		,							'image_processor.json'			)
																		image_processor_first.to_json_file(A_			)
																		UpperCamelCase					       =			self.image_processing_class.from_json_file(A_			)

											self.assertEqual(image_processor_second.to_dict()		,							image_processor_first.to_dict()			)







				def 		UpperCAmelCase_  (    self			)->						Dict:







											'''simple docstring'''






											UpperCamelCase					       =			self.image_processing_class(**self.image_processor_dict			)

											with tempfile.TemporaryDirectory() as tmpdirname:
																		UpperCamelCase					       =			image_processor_first.save_pretrained(A_			)[0]
																		check_json_file_has_correct_format(A_			)
																		UpperCamelCase					       =			self.image_processing_class.from_pretrained(A_			)

											self.assertEqual(image_processor_second.to_dict()		,							image_processor_first.to_dict()			)







				def 		UpperCAmelCase_  (    self			)->						str:







											'''simple docstring'''






											UpperCamelCase					       =			self.image_processing_class()
											self.assertIsNotNone(A_			)







				@require_torch
				@require_vision
				def 		UpperCAmelCase_  (    self			)->						Any:







											'''simple docstring'''






											if self.test_cast_dtype is not None:
																		# Initialize image_processor
																		UpperCamelCase					       =			self.image_processing_class(**self.image_processor_dict			)

																		# create random PyTorch tensors
																		UpperCamelCase					       =			prepare_image_inputs(self.image_processor_tester		,							equal_resolution=A_		,							torchify=A_			)

																		UpperCamelCase					       =			image_processor(A_		,							return_tensors='pt'			)
																		# for layoutLM compatiblity
																		self.assertEqual(encoding.pixel_values.device		,							torch.device('cpu'			)			)
																		self.assertEqual(encoding.pixel_values.dtype		,							torch.floataa			)

																		UpperCamelCase					       =			image_processor(A_		,							return_tensors='pt'			).to(torch.floataa			)
																		self.assertEqual(encoding.pixel_values.device		,							torch.device('cpu'			)			)
																		self.assertEqual(encoding.pixel_values.dtype		,							torch.floataa			)

																		UpperCamelCase					       =			image_processor(A_		,							return_tensors='pt'			).to('cpu'		,							torch.bfloataa			)
																		self.assertEqual(encoding.pixel_values.device		,							torch.device('cpu'			)			)
																		self.assertEqual(encoding.pixel_values.dtype		,							torch.bfloataa			)

																		with self.assertRaises(A_			):
																									UpperCamelCase					       =			image_processor(A_		,							return_tensors='pt'			).to(torch.bfloataa		,							'cpu'			)

																		# Try with text + image feature
																		UpperCamelCase					       =			image_processor(A_		,							return_tensors='pt'			)
																		encoding.update({'input_ids': torch.LongTensor([[1, 2, 3], [4, 5, 6]]			)}			)
																		UpperCamelCase					       =			encoding.to(torch.floataa			)

																		self.assertEqual(encoding.pixel_values.device		,							torch.device('cpu'			)			)
																		self.assertEqual(encoding.pixel_values.dtype		,							torch.floataa			)
																		self.assertEqual(encoding.input_ids.dtype		,							torch.long			)






'''simple docstring'''
import random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
						import torch_xla.core.xla_model as xm







def 						A_(			A		:						int						,			A		:						bool = False):
							if device_specific:
														seed += AcceleratorState().process_index
							random.seed(A)
							np.random.seed(A)
							torch.manual_seed(A)
							if is_xpu_available():
														torch.xpu.manual_seed_all(A)
							elif is_npu_available():
														torch.npu.manual_seed_all(A)
							else:
														torch.cuda.manual_seed_all(A)
							# ^^ safe to call this function even if cuda is not available
							if is_tpu_available():
														xm.set_rng_state(A)







def 						A_(			A		:						Optional[RNGType] = None						,			A		:						Optional[torch.Generator] = None):
							# Get the proper rng state
							if rng_type == RNGType.TORCH:
														UpperCamelCase					       =			torch.get_rng_state()
							elif rng_type == RNGType.CUDA:
														UpperCamelCase					       =			torch.cuda.get_rng_state()
							elif rng_type == RNGType.XLA:
														assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
														UpperCamelCase					       =			torch.tensor(xm.get_rng_state())
							elif rng_type == RNGType.NPU:
														assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
														UpperCamelCase					       =			torch.npu.get_rng_state()
							elif rng_type == RNGType.XPU:
														assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
														UpperCamelCase					       =			torch.xpu.get_rng_state()
							elif rng_type == RNGType.GENERATOR:
														assert generator is not None, "Need a generator to synchronize its seed."
														UpperCamelCase					       =			generator.get_state()

							# Broadcast the rng state from device 0 to other devices
							UpperCamelCase					       =			AcceleratorState()
							if state.distributed_type == DistributedType.TPU:
														UpperCamelCase					       =			rng_state.to(xm.xla_device())
														xm.collective_broadcast([rng_state])
														xm.mark_step()
														UpperCamelCase					       =			rng_state.cpu()
							elif (
							    state.distributed_type in CUDA_DISTRIBUTED_TYPES
							    or state.distributed_type == DistributedType.MULTI_NPU
							    or state.distributed_type == DistributedType.MULTI_XPU
							):
														UpperCamelCase					       =			rng_state.to(state.device)
														torch.distributed.broadcast(A						,			0)
														UpperCamelCase					       =			rng_state.cpu()
							elif state.distributed_type == DistributedType.MULTI_CPU:
														torch.distributed.broadcast(A						,			0)

							# Set the broadcast rng state
							if rng_type == RNGType.TORCH:
														torch.set_rng_state(A)
							elif rng_type == RNGType.CUDA:
														torch.cuda.set_rng_state(A)
							elif rng_type == RNGType.NPU:
														torch.npu.set_rng_state(A)
							elif rng_type == RNGType.XPU:
														torch.xpu.set_rng_state(A)
							elif rng_type == RNGType.XLA:
														xm.set_rng_state(rng_state.item())
							elif rng_type == RNGType.GENERATOR:
														generator.set_state(A)







def 						A_(			A		:						List[Union[str, RNGType]]						,			A		:						Optional[torch.Generator] = None):
							for rng_type in rng_types:
														synchronize_rng_state(RNGType(A)						,			generator=A)




