






"""simple docstring"""


import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)


def        UpperCAmelCase      (					a__     ,      a__=False ):





						'''simple docstring'''






						try:
												lowerCAmelCase   :Tuple						=			os.environ[key]
						except KeyError:
												# KEY isn't set, default to `default`.
												lowerCAmelCase   :Optional[Any]						=			default
						else:
												# KEY is set, convert it to True or False.
												try:
																		lowerCAmelCase   :List[Any]						=			strtobool(a__ )
												except ValueError:
																		# More values are supported, but let's keep the message simple.
																		raise ValueError(F"""If set, {key} must be yes or no.""" )
						return _value


__SCREAMING_SNAKE_CASE   =   parse_flag_from_env('RUN_SLOW', default=False)


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skip('Test was skipped' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(_run_slow_tests     ,      'test is slow' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(not torch.cuda.is_available()     ,      'test requires only a CPU' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(torch.cuda.is_available()     ,      'test requires a GPU' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(is_xpu_available()     ,      'test requires a XPU' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(is_mps_available()     ,      'test requires a `mps` backend support in `torch`' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(
						    is_transformers_available() and is_datasets_available()     ,      'test requires the Hugging Face suite' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(is_bnb_available()     ,      'test requires the bitsandbytes library' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(is_tpu_available()     ,      'test requires TPU' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(torch.cuda.device_count() == 1     ,      'test requires a GPU' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(torch.xpu.device_count() == 1     ,      'test requires a XPU' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(torch.cuda.device_count() > 1     ,      'test requires multiple GPUs' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(torch.xpu.device_count() > 1     ,      'test requires multiple XPUs' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(is_safetensors_available()     ,      'test requires safetensors' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(is_deepspeed_available()     ,      'test requires DeepSpeed' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(is_torch_version('>='     ,      '1.12.0' )     ,      'test requires torch version >= 1.12.0' )(a__ )


def        UpperCAmelCase      (					a__=None     ,      a__=None ):





						'''simple docstring'''






						if test_case is None:
												return partial(a__     ,      version=a__ )
						return unittest.skipUnless(is_torch_version('>='     ,      a__ )     ,      F"""test requires torch version >= {version}""" )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(is_tensorboard_available()     ,      'test requires Tensorboard' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(is_wandb_available()     ,      'test requires wandb' )(a__ )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(is_comet_ml_available()     ,      'test requires comet_ml' )(a__ )


__SCREAMING_SNAKE_CASE   =   (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						return unittest.skipUnless(
						    _atleast_one_tracker_available     ,      'test requires at least one tracker to be available and for `comet_ml` to not be installed'     ,      )(a__ )




class 						__UpperCamelCase     (     unittest.TestCase						):
					lowercase_    :				str      =  True
					@classmethod
					def        UpperCAmelCase__ (							cls							:	Union[str, Any]   )	->       int:
											lowerCAmelCase   :List[Any]						=			tempfile.mkdtemp()
					@classmethod
					def        UpperCAmelCase__ (							cls							:	Union[str, Any]   )	->       Optional[Any]:
											if os.path.exists(cls.tmpdir   ):
																	shutil.rmtree(cls.tmpdir   )
					def        UpperCAmelCase__ (							self							:	Optional[int]   )	->       Union[str, Any]:
											if self.clear_on_setup:
																	for path in Path(self.tmpdir   ).glob('**/*'   ):
																							if path.is_file():
																													path.unlink()
																							elif path.is_dir():
																													shutil.rmtree(UpperCAmelCase   )




class 						__UpperCamelCase     (     unittest.TestCase						):
					def        UpperCAmelCase__ (							self							:	str   )	->       Optional[int]:
											super().tearDown()
											# Reset the state of the AcceleratorState singleton.
											AcceleratorState._reset_state()
											PartialState._reset_state()




class 						__UpperCamelCase     (     unittest.TestCase						):
					def        UpperCAmelCase__ (							self							:	str     , UpperCAmelCase							:	Union[mock.Mock, List[mock.Mock]]   )	->       int:
											lowerCAmelCase   :Any						=			mocks if isinstance(UpperCAmelCase     , (tuple, list)   ) else [mocks]
											for m in self.mocks:
																	m.start()
																	self.addCleanup(m.stop   )


def        UpperCAmelCase      (					a__ ):





						'''simple docstring'''






						lowerCAmelCase   :int						=			AcceleratorState()
						lowerCAmelCase   :List[str]						=			tensor[None].clone().to(state.device )
						lowerCAmelCase   :Optional[Any]						=			gather(a__ ).cpu()
						lowerCAmelCase   :Dict						=			tensor[0].cpu()
						for i in range(tensors.shape[0] ):
												if not torch.equal(tensors[i]     ,      a__ ):
																		return False
						return True




class 						__UpperCamelCase     :
					def __init__(							self							:	Optional[Any]     , UpperCAmelCase							:	str     , UpperCAmelCase							:	int     , UpperCAmelCase							:	str   )	->       Any:
											lowerCAmelCase   :List[str]						=			returncode
											lowerCAmelCase   :List[Any]						=			stdout
											lowerCAmelCase   :Tuple						=			stderr


async def        UpperCAmelCase      (					a__     ,      a__ ):





						'''simple docstring'''






						while True:
												lowerCAmelCase   :Union[str, Any]						=			await stream.readline()
												if line:
																		callback(a__ )
												else:
																		break


async def        UpperCAmelCase      (					a__     ,      a__=None     ,      a__=None     ,      a__=None     ,      a__=False     ,      a__=False ):





						'''simple docstring'''






						if echo:
												print('\nRunning: '     ,      ' '.join(a__ ) )

						lowerCAmelCase   :Optional[int]						=			await asyncio.create_subprocess_exec(
						    cmd[0]     ,      *cmd[1:]     ,      stdin=a__     ,      stdout=asyncio.subprocess.PIPE     ,      stderr=asyncio.subprocess.PIPE     ,      env=a__     ,      )

						# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
						# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
						#
						# If it starts hanging, will need to switch to the following code. The problem is that no data
						# will be seen until it's done and if it hangs for example there will be no debug info.
						# out, err = await p.communicate()
						# return _RunOutput(p.returncode, out, err)

						lowerCAmelCase   :Optional[int]						=			[]
						lowerCAmelCase   :List[Any]						=			[]

						def tee(a__     ,      a__     ,      a__     ,      a__="" ):
												lowerCAmelCase   :Union[str, Any]						=			line.decode('utf-8' ).rstrip()
												sink.append(a__ )
												if not quiet:
																		print(a__     ,      a__     ,      file=a__ )

    # XXX: the timeout doesn't seem to make any difference here
						await asyncio.wait(
						    [
						        asyncio.create_task(_read_stream(p.stdout     ,      lambda a__ : tee(a__     ,      a__     ,      sys.stdout     ,      label='stdout:' ) ) ),
						        asyncio.create_task(_read_stream(p.stderr     ,      lambda a__ : tee(a__     ,      a__     ,      sys.stderr     ,      label='stderr:' ) ) ),
						    ]     ,      timeout=a__     ,      )
						return _RunOutput(await p.wait()     ,      a__     ,      a__ )


def        UpperCAmelCase      (					a__     ,      a__=None     ,      a__=None     ,      a__=1_80     ,      a__=False     ,      a__=True ):





						'''simple docstring'''






						lowerCAmelCase   :str						=			asyncio.get_event_loop()
						lowerCAmelCase   :List[str]						=			loop.run_until_complete(
						    _stream_subprocess(a__     ,      env=a__     ,      stdin=a__     ,      timeout=a__     ,      quiet=a__     ,      echo=a__ ) )

						lowerCAmelCase   :Dict						=			' '.join(a__ )
						if result.returncode > 0:
												lowerCAmelCase   :str						=			'\n'.join(result.stderr )
												raise RuntimeError(
												    F"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
												    F"""The combined stderr from workers follows:\n{stderr}""" )

						return result




class 						__UpperCamelCase     (     UpperCamelCase						):
					pass


def        UpperCAmelCase      (					a__     ,      a__=False ):





						'''simple docstring'''






						try:
												lowerCAmelCase   :int						=			subprocess.check_output(a__     ,      stderr=subprocess.STDOUT )
												if return_stdout:
																		if hasattr(a__     ,      'decode' ):
																								lowerCAmelCase   :Any						=			output.decode('utf-8' )
																		return output
						except subprocess.CalledProcessError as e:
												raise SubprocessCallException(
												    F"""Command `{" ".join(a__ )}` failed with the following error:\n\n{e.output.decode()}""" ) from e







"""simple docstring"""


import numpy as np
from cva import destroyAllWindows, imread, imshow, waitKey




class 						__UpperCamelCase     :
					def __init__(							self							:	Union[str, Any]     , UpperCAmelCase							:	Union[str, Any]     , UpperCAmelCase							:	int     , UpperCAmelCase							:	int   )	->       Tuple:
											if dst_width < 0 or dst_height < 0:
																	raise ValueError('Destination width/height should be > 0'   )

											lowerCAmelCase   :List[Any]						=			img
											lowerCAmelCase   :Optional[int]						=			img.shape[1]
											lowerCAmelCase   :Union[str, Any]						=			img.shape[0]
											lowerCAmelCase   :Optional[int]						=			dst_width
											lowerCAmelCase   :Optional[int]						=			dst_height

											lowerCAmelCase   :Any						=			self.src_w / self.dst_w
											lowerCAmelCase   :Dict						=			self.src_h / self.dst_h

											lowerCAmelCase   :int						=			(
											    np.ones((self.dst_h, self.dst_w, 3)     , np.uinta   ) * 255
											)
					def        UpperCAmelCase__ (							self							:	Union[str, Any]   )	->       List[str]:
											for i in range(self.dst_h   ):
																	for j in range(self.dst_w   ):
																							lowerCAmelCase   :Optional[Any]						=			self.img[self.get_y(UpperCAmelCase   )][self.get_x(UpperCAmelCase   )]
					def        UpperCAmelCase__ (							self							:	Optional[int]     , UpperCAmelCase							:	int   )	->       int:
											return int(self.ratio_x * x   )
					def        UpperCAmelCase__ (							self							:	List[str]     , UpperCAmelCase							:	int   )	->       int:
											return int(self.ratio_y * y   )


if __name__ == "__main__":
		__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE   =   8_00, 6_00
		__SCREAMING_SNAKE_CASE   =   imread('image_data/lena.jpg', 1)
		__SCREAMING_SNAKE_CASE   =   NearestNeighbour(im, dst_w, dst_h)
		n.process()

		imshow(
		    F"""Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}""", n.output
		)
		waitKey(0)
		destroyAllWindows()