


'''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


if is_torch_available():
	import torch

if is_vision_available():
	from PIL import Image

	from transformers import SwinaSRImageProcessor
	from transformers.image_transforms import get_image_size
class   __lowerCAmelCase						(unittest.TestCase					):





						'''simple docstring'''






						def __init__(self   :   List[Any]       ,						UpperCamelCase   :   Optional[Any]       ,						UpperCamelCase   :   Any=7       ,						UpperCamelCase   :   Union[str, Any]=3       ,						UpperCamelCase   :   Dict=18       ,						UpperCamelCase   :   Any=30       ,						UpperCamelCase   :   Any=400       ,						UpperCamelCase   :   Optional[Any]=True       ,						UpperCamelCase   :   List[str]=1 / 255       ,						UpperCamelCase   :   Any=True       ,						UpperCamelCase   :   Tuple=8       ,						):

													'''simple docstring'''







													lowercase__				      =			parent
													lowercase__				      =			batch_size
													lowercase__				      =			num_channels
													lowercase__				      =			image_size
													lowercase__				      =			min_resolution
													lowercase__				      =			max_resolution
													lowercase__				      =			do_rescale
													lowercase__				      =			rescale_factor
													lowercase__				      =			do_pad
													lowercase__				      =			pad_size



						def 				UpperCamelCase__		(self   :   Any			):

													'''simple docstring'''







													return {
													    "do_rescale": self.do_rescale,
													    "rescale_factor": self.rescale_factor,
													    "do_pad": self.do_pad,
													    "pad_size": self.pad_size,
													}






						def 				UpperCamelCase__		(self   :   Optional[int]       ,						UpperCamelCase   :   int=False       ,						UpperCamelCase   :   Optional[int]=False       ,						UpperCamelCase   :   Union[str, Any]=False			):

													'''simple docstring'''







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

													if equal_resolution:
																				lowercase__				      =			[]
																				for i in range(self.batch_size			):
																											image_inputs.append(
																											    np.random.randint(
																											        255       ,						size=(self.num_channels, self.max_resolution, self.max_resolution)       ,						dtype=np.uinta			)			)
													else:
																				lowercase__				      =			[]
																				for i in range(self.batch_size			):
																											lowercase__      ,lowercase__				      =			np.random.choice(np.arange(self.min_resolution       ,						self.max_resolution			)       ,						2			)
																											image_inputs.append(np.random.randint(255       ,						size=(self.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(UpperCamelCase       ,						0       ,						-1			)			) for x in image_inputs]

													if torchify:
																				lowercase__				      =			[torch.from_numpy(UpperCamelCase			) for x in image_inputs]

													return image_inputs






@require_torch
@require_vision
class   __lowerCAmelCase						(lowercase_  ,					unittest.TestCase					):





						'''simple docstring'''






						lowerCAmelCase__ :					Tuple   =							SwinaSRImageProcessor if is_vision_available() else None



						def 				UpperCamelCase__		(self   :   Dict			):

													'''simple docstring'''







													lowercase__				      =			SwinaSRImageProcessingTester(self			)



						@property
						def 				UpperCamelCase__		(self   :   Dict			):

													'''simple docstring'''







													return self.image_processor_tester.prepare_image_processor_dict()



						def 				UpperCamelCase__		(self   :   Any			):

													'''simple docstring'''







													lowercase__				      =			self.image_processing_class(**self.image_processor_dict			)
													self.assertTrue(hasattr(UpperCamelCase       ,						'''do_rescale'''			)			)
													self.assertTrue(hasattr(UpperCamelCase       ,						'''rescale_factor'''			)			)
													self.assertTrue(hasattr(UpperCamelCase       ,						'''do_pad'''			)			)
													self.assertTrue(hasattr(UpperCamelCase       ,						'''pad_size'''			)			)



						def 				UpperCamelCase__		(self   :   Optional[int]			):

													'''simple docstring'''







													pass



						def 				UpperCamelCase__		(self   :   List[Any]       ,						UpperCamelCase   :   str			):

													'''simple docstring'''







													lowercase__      ,lowercase__				      =			get_image_size(UpperCamelCase			)
													lowercase__				      =			self.image_processor_tester.pad_size

													lowercase__				      =			(old_height // size + 1) * size - old_height
													lowercase__				      =			(old_width // size + 1) * size - old_width
													return old_height + pad_height, old_width + pad_width



						def 				UpperCamelCase__		(self   :   Optional[Any]			):

													'''simple docstring'''







													lowercase__				      =			self.image_processing_class(**self.image_processor_dict			)
													# create random PIL images
													lowercase__				      =			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase			)
													for image in image_inputs:
																				self.assertIsInstance(UpperCamelCase       ,						Image.Image			)

													# Test not batched input
													lowercase__				      =			image_processor(image_inputs[0]       ,						return_tensors='''pt'''			).pixel_values
													lowercase__      ,lowercase__				      =			self.calculate_expected_size(np.array(image_inputs[0]			)			)
													self.assertEqual(
													    encoded_images.shape       ,						(
													        1,
													        self.image_processor_tester.num_channels,
													        expected_height,
													        expected_width,
													    )       ,						)



						def 				UpperCamelCase__		(self   :   str			):

													'''simple docstring'''







													lowercase__				      =			self.image_processing_class(**self.image_processor_dict			)
													# create random numpy tensors
													lowercase__				      =			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase       ,						numpify=UpperCamelCase			)
													for image in image_inputs:
																				self.assertIsInstance(UpperCamelCase       ,						np.ndarray			)

													# Test not batched input
													lowercase__				      =			image_processor(image_inputs[0]       ,						return_tensors='''pt'''			).pixel_values
													lowercase__      ,lowercase__				      =			self.calculate_expected_size(image_inputs[0]			)
													self.assertEqual(
													    encoded_images.shape       ,						(
													        1,
													        self.image_processor_tester.num_channels,
													        expected_height,
													        expected_width,
													    )       ,						)






						def 				UpperCamelCase__		(self   :   Optional[Any]			):

													'''simple docstring'''







													lowercase__				      =			self.image_processing_class(**self.image_processor_dict			)
													# create random PyTorch tensors
													lowercase__				      =			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase       ,						torchify=UpperCamelCase			)
													for image in image_inputs:
																				self.assertIsInstance(UpperCamelCase       ,						torch.Tensor			)

													# Test not batched input
													lowercase__				      =			image_processor(image_inputs[0]       ,						return_tensors='''pt'''			).pixel_values
													lowercase__      ,lowercase__				      =			self.calculate_expected_size(image_inputs[0]			)
													self.assertEqual(
													    encoded_images.shape       ,						(
													        1,
													        self.image_processor_tester.num_channels,
													        expected_height,
													        expected_width,
													    )       ,						)








'''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	)




