


'''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 _SCREAMING_SNAKE_CASE				(A  ,			A=False  ,			A=False  ,			A=False	)	->	Union[str, Any]:






							"""simple docstring"""







							assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

							lowercase__				      =			[]
							for i in range(image_processor_tester.batch_size	):
														if equal_resolution:
																					lowercase__				      =			lowercase__				      =			image_processor_tester.max_resolution
														else:
																					# To avoid getting image width/height 0
																					lowercase__				      =			image_processor_tester.min_resolution
																					if getattr(__lowercase  ,			'''size_divisor'''  ,			__lowercase	):
																												# If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
																												lowercase__				      =			max(image_processor_tester.size_divisor  ,			__lowercase	)
																					lowercase__      ,lowercase__				      =			np.random.choice(np.arange(__lowercase  ,			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
														lowercase__				      =			[Image.fromarray(np.moveaxis(__lowercase  ,			0  ,			-1	)	) for image in image_inputs]

							if torchify:
														lowercase__				      =			[torch.from_numpy(__lowercase	) for image in image_inputs]

							return image_inputs

def _SCREAMING_SNAKE_CASE				(A  ,			A=10  ,			A=10  ,			A=False  ,			A=False	)	->	List[str]:






							"""simple docstring"""







							lowercase__				      =			[]
							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
														lowercase__				      =			[Image.fromarray(np.moveaxis(__lowercase  ,			0  ,			-1	)	) for frame in video]

							if torchify:
														lowercase__				      =			[torch.from_numpy(__lowercase	) for frame in video]

							return video

def _SCREAMING_SNAKE_CASE				(A  ,			A=False  ,			A=False  ,			A=False	)	->	List[Any]:






							"""simple docstring"""







							assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

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

							return video_inputs

class   __lowerCAmelCase						:





						'''simple docstring'''






						lowerCAmelCase__ :					Union[str, Any]   =							None



						def 				UpperCamelCase__		(self   :   List[Any]			):

													'''simple docstring'''







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



						def 				UpperCamelCase__		(self   :   Optional[int]			):

													'''simple docstring'''







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

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

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



						def 				UpperCamelCase__		(self   :   Optional[int]			):

													'''simple docstring'''







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

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

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



						def 				UpperCamelCase__		(self   :   int			):

													'''simple docstring'''







													lowercase__				      =			self.image_processing_class()
													self.assertIsNotNone(UpperCamelCase_			)






						@require_torch
						@require_vision
						def 				UpperCamelCase__		(self   :   List[Any]			):

													'''simple docstring'''







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

																				# create random PyTorch tensors
																				lowercase__				      =			prepare_image_inputs(self.image_processor_tester       ,						equal_resolution=UpperCamelCase_       ,						torchify=UpperCamelCase_			)

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

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

																				lowercase__				      =			image_processor(UpperCamelCase_       ,						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(UpperCamelCase_			):
																											lowercase__				      =			image_processor(UpperCamelCase_       ,						return_tensors='''pt'''			).to(torch.bfloataa       ,						'''cpu'''			)

																				# Try with text + image feature
																				lowercase__				      =			image_processor(UpperCamelCase_       ,						return_tensors='''pt'''			)
																				encoding.update({'''input_ids''': torch.LongTensor([[1, 2, 3], [4, 5, 6]]			)}			)
																				lowercase__				      =			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 _SCREAMING_SNAKE_CASE				(A  ,			A = False	)	->	Tuple:






       """simple docstring"""







       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 _SCREAMING_SNAKE_CASE				(A = None  ,			A = None	)	->	Tuple:






       """simple docstring"""







       if rng_type == RNGType.TORCH:
              lowercase__				      =			torch.get_rng_state()
       elif rng_type == RNGType.CUDA:
              lowercase__				      =			torch.cuda.get_rng_state()
       elif rng_type == RNGType.XLA:
              assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
              lowercase__				      =			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."
              lowercase__				      =			torch.npu.get_rng_state()
       elif rng_type == RNGType.XPU:
              assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
              lowercase__				      =			torch.xpu.get_rng_state()
       elif rng_type == RNGType.GENERATOR:
              assert generator is not None, "Need a generator to synchronize its seed."
              lowercase__				      =			generator.get_state()

       # Broadcast the rng state from device 0 to other devices
       lowercase__				      =			AcceleratorState()
       if state.distributed_type == DistributedType.TPU:
              lowercase__				      =			rng_state.to(xm.xla_device()	)
              xm.collective_broadcast([rng_state]	)
              xm.mark_step()
              lowercase__				      =			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
       ):
              lowercase__				      =			rng_state.to(state.device	)
              torch.distributed.broadcast(A  ,			0	)
              lowercase__				      =			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 _SCREAMING_SNAKE_CASE				(A  ,			A = None	)	->	int:






       """simple docstring"""







       for rng_type in rng_types:
              synchronize_rng_state(RNGType(A	)  ,			generator=A	)




