
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_image_inputs


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import ViltImageProcessor

class 		__magic_name__				( unittest.TestCase					):


  """simple docstring"""





  def __init__(					self	,		a__	,		a__=7	,		a__=3	,		a__=18	,		a__=30	,		a__=4_00	,		a__=True	,		a__=None	,		a__=2	,		a__=True	,		a__=[0.5, 0.5, 0.5]	,		a__=[0.5, 0.5, 0.5]	,		):
    _lowerCamelCase      =						size if size is not None else {'''shortest_edge''': 30}
    _lowerCamelCase      =						parent
    _lowerCamelCase      =						batch_size
    _lowerCamelCase      =						num_channels
    _lowerCamelCase      =						image_size
    _lowerCamelCase      =						min_resolution
    _lowerCamelCase      =						max_resolution
    _lowerCamelCase      =						do_resize
    _lowerCamelCase      =						size
    _lowerCamelCase      =						size_divisor
    _lowerCamelCase      =						do_normalize
    _lowerCamelCase      =						image_mean
    _lowerCamelCase      =						image_std


  def     _UpperCAmelCase  (					self		):
    return {
        "image_mean": self.image_mean,
        "image_std": self.image_std,
        "do_normalize": self.do_normalize,
        "do_resize": self.do_resize,
        "size": self.size,
        "size_divisor": self.size_divisor,
    }


  def     _UpperCAmelCase  (					self	,		a__	,		a__=False		):
    if not batched:
      _lowerCamelCase      =						self.size['''shortest_edge''']
      _lowerCamelCase      =						image_inputs[0]
      if isinstance(a__	,		Image.Image		):
        _lowerCamelCase    ,    _lowerCamelCase      =						image.size
      else:
        _lowerCamelCase    ,    _lowerCamelCase      =						image.shape[1], image.shape[2]
      _lowerCamelCase      =						size / min(a__	,		a__		)
      if h < w:
        _lowerCamelCase    ,    _lowerCamelCase      =						size, scale * w
      else:
        _lowerCamelCase    ,    _lowerCamelCase      =						scale * h, size

      _lowerCamelCase      =						int((13_33 / 8_00) * size		)
      if max(a__	,		a__		) > max_size:
        _lowerCamelCase      =						max_size / max(a__	,		a__		)
        _lowerCamelCase      =						newh * scale
        _lowerCamelCase      =						neww * scale

      _lowerCamelCase    ,    _lowerCamelCase      =						int(newh + 0.5		), int(neww + 0.5		)
      _lowerCamelCase    ,    _lowerCamelCase      =						(
          newh // self.size_divisor * self.size_divisor,
          neww // self.size_divisor * self.size_divisor,
      )

    else:
      _lowerCamelCase      =						[]
      for image in image_inputs:
        _lowerCamelCase    ,    _lowerCamelCase      =						self.get_expected_values([image]		)
        expected_values.append((expected_height, expected_width)		)
      _lowerCamelCase      =						max(a__	,		key=lambda a__		: item[0]		)[0]
      _lowerCamelCase      =						max(a__	,		key=lambda a__		: item[1]		)[1]

    return expected_height, expected_width







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


  """simple docstring"""





  _UpperCamelCase						 = ViltImageProcessor if is_vision_available() else None


  def     _UpperCAmelCase  (					self		):
    _lowerCamelCase      =						ViltImageProcessingTester(self		)


  @property
  def     _UpperCAmelCase  (					self		):
    return self.image_processor_tester.prepare_image_processor_dict()


  def     _UpperCAmelCase  (					self		):
    _lowerCamelCase      =						self.image_processing_class(**self.image_processor_dict		)
    self.assertTrue(hasattr(a__	,		'''image_mean'''		)		)
    self.assertTrue(hasattr(a__	,		'''image_std'''		)		)
    self.assertTrue(hasattr(a__	,		'''do_normalize'''		)		)
    self.assertTrue(hasattr(a__	,		'''do_resize'''		)		)
    self.assertTrue(hasattr(a__	,		'''size'''		)		)
    self.assertTrue(hasattr(a__	,		'''size_divisor'''		)		)


  def     _UpperCAmelCase  (					self		):
    _lowerCamelCase      =						self.image_processing_class.from_dict(self.image_processor_dict		)
    self.assertEqual(image_processor.size	,		{'''shortest_edge''': 30}		)

    _lowerCamelCase      =						self.image_processing_class.from_dict(self.image_processor_dict	,		size=42		)
    self.assertEqual(image_processor.size	,		{'''shortest_edge''': 42}		)


  def     _UpperCAmelCase  (					self		):
    pass


  def     _UpperCAmelCase  (					self		):
    # Initialize image_processing
    _lowerCamelCase      =						self.image_processing_class(**self.image_processor_dict		)
    # create random PIL images
    _lowerCamelCase      =						prepare_image_inputs(self.image_processor_tester	,		equal_resolution=a__		)
    for image in image_inputs:
      self.assertIsInstance(a__	,		Image.Image		)

    # Test not batched input
    _lowerCamelCase      =						image_processing(image_inputs[0]	,		return_tensors='''pt'''		).pixel_values

    _lowerCamelCase    ,    _lowerCamelCase      =						self.image_processor_tester.get_expected_values(a__		)
    self.assertEqual(
        encoded_images.shape	,		(1, self.image_processor_tester.num_channels, expected_height, expected_width)	,		)

    # Test batched
    _lowerCamelCase      =						image_processing(a__	,		return_tensors='''pt'''		).pixel_values

    _lowerCamelCase    ,    _lowerCamelCase      =						self.image_processor_tester.get_expected_values(a__	,		batched=a__		)
    self.assertEqual(
        encoded_images.shape	,		(
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            expected_height,
            expected_width,
        )	,		)


  def     _UpperCAmelCase  (					self		):
    # Initialize image_processing
    _lowerCamelCase      =						self.image_processing_class(**self.image_processor_dict		)
    # create random numpy tensors
    _lowerCamelCase      =						prepare_image_inputs(self.image_processor_tester	,		equal_resolution=a__	,		numpify=a__		)
    for image in image_inputs:
      self.assertIsInstance(a__	,		np.ndarray		)

    # Test not batched input
    _lowerCamelCase      =						image_processing(image_inputs[0]	,		return_tensors='''pt'''		).pixel_values

    _lowerCamelCase    ,    _lowerCamelCase      =						self.image_processor_tester.get_expected_values(a__		)
    self.assertEqual(
        encoded_images.shape	,		(1, self.image_processor_tester.num_channels, expected_height, expected_width)	,		)

    # Test batched
    _lowerCamelCase      =						image_processing(a__	,		return_tensors='''pt'''		).pixel_values

    _lowerCamelCase    ,    _lowerCamelCase      =						self.image_processor_tester.get_expected_values(a__	,		batched=a__		)
    self.assertEqual(
        encoded_images.shape	,		(
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            expected_height,
            expected_width,
        )	,		)


  def     _UpperCAmelCase  (					self		):
    # Initialize image_processing
    _lowerCamelCase      =						self.image_processing_class(**self.image_processor_dict		)
    # create random PyTorch tensors
    _lowerCamelCase      =						prepare_image_inputs(self.image_processor_tester	,		equal_resolution=a__	,		torchify=a__		)
    for image in image_inputs:
      self.assertIsInstance(a__	,		torch.Tensor		)

    # Test not batched input
    _lowerCamelCase      =						image_processing(image_inputs[0]	,		return_tensors='''pt'''		).pixel_values

    _lowerCamelCase    ,    _lowerCamelCase      =						self.image_processor_tester.get_expected_values(a__		)
    self.assertEqual(
        encoded_images.shape	,		(1, self.image_processor_tester.num_channels, expected_height, expected_width)	,		)

    # Test batched
    _lowerCamelCase      =						image_processing(a__	,		return_tensors='''pt'''		).pixel_values

    _lowerCamelCase    ,    _lowerCamelCase      =						self.image_processor_tester.get_expected_values(a__	,		batched=a__		)
    self.assertEqual(
        encoded_images.shape	,		(
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            expected_height,
            expected_width,
        )	,		)






import importlib
import importlib.metadata
import os
import warnings
from distutils.util import strtobool
from functools import lru_cache

import torch
from packaging import version
from packaging.version import parse

from .environment import parse_flag_from_env
from .versions import compare_versions, is_torch_version


try:
  import torch_xla.core.xla_model as xm  # noqa: F401

  _UpperCAmelCase    			=					True
except ImportError:
  _UpperCAmelCase    			=					False


# Cache this result has it's a C FFI call which can be pretty time-consuming
_UpperCAmelCase    			=					torch.distributed.is_available()


def 		_lowerCamelCase       (   _a  ):
  """simple docstring"""




  _lowerCamelCase      =						importlib.util.find_spec(_a  ) is not None
  if package_exists:
    try:
      _lowerCamelCase      =						importlib.metadata.metadata(_a  )
      return True
    except importlib.metadata.PackageNotFoundError:
      return False


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _torch_distributed_available


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  try:
    pass
  except ImportError:
    print(
        '''Intel(R) oneCCL Bindings for PyTorch* is required to run DDP on Intel(R) GPUs, but it is not'''
        ''' detected. If you see \"ValueError: Invalid backend: \'ccl\'\" error, please install Intel(R) oneCCL'''
        ''' Bindings for PyTorch*.'''  )
  return (
      importlib.util.find_spec('''torch_ccl'''  ) is not None
      or importlib.util.find_spec('''oneccl_bindings_for_pytorch'''  ) is not None
  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return importlib.metadata.version('''oneccl_bind_pt'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''transformer_engine'''  )


@lru_cache
def 		_lowerCamelCase       (   _a=True  ):
  """simple docstring"""




  if torch.cuda.is_available():
    return False
  if _tpu_available and check_device:
    try:
      # Will raise a RuntimeError if no XLA configuration is found
      _lowerCamelCase      =						xm.xla_device()
      return True
    except RuntimeError:
      return False
  return _tpu_available


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''deepspeed'''  )


def 		_lowerCamelCase       (   _a=False  ):
  """simple docstring"""




  if is_tpu_available():
    return not ignore_tpu
  if torch.cuda.is_available():
    return torch.cuda.is_bfaa_supported()
  if is_npu_available():
    return False
  return True


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  _lowerCamelCase      =						_is_package_available('''bitsandbytes'''  )
  if package_exists:
    _lowerCamelCase      =						version.parse(importlib.metadata.version('''bitsandbytes'''  )  )
    return compare_versions(_a			,   '''>='''			,   '''0.39.0'''  )
  return False


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  _lowerCamelCase      =						_is_package_available('''bitsandbytes'''  )
  if package_exists:
    _lowerCamelCase      =						version.parse(importlib.metadata.version('''bitsandbytes'''  )  )
    return compare_versions(_a			,   '''>='''			,   '''0.37.2'''  )
  return False


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''bitsandbytes'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  if strtobool(os.environ.get('''ACCELERATE_USE_MEGATRON_LM'''			,   '''False'''  )  ) == 1:
    _lowerCamelCase      =						importlib.util.find_spec('''megatron'''  ) is not None
    if package_exists:
      try:
        _lowerCamelCase      =						parse(importlib.metadata.version('''megatron-lm'''  )  )
        return compare_versions(_a			,   '''>='''			,   '''2.2.0'''  )
      except Exception as e:
        warnings.warn(F'''Parse Megatron version failed. Exception:{e}'''  )
        return False


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''safetensors'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''transformers'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''datasets'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''aim'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''tensorboard'''  ) or _is_package_available('''tensorboardX'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''wandb'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''comet_ml'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''boto3'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  if _is_package_available('''rich'''  ):
    if "ACCELERATE_DISABLE_RICH" in os.environ:
      warnings.warn(
          '''`ACCELERATE_DISABLE_RICH` is deprecated and will be removed in v0.22.0 and deactivated by default. Please use `ACCELERATE_ENABLE_RICH` if you wish to use `rich`.'''  )
      return not parse_flag_from_env('''ACCELERATE_DISABLE_RICH'''			,   _a  )
    return parse_flag_from_env('''ACCELERATE_ENABLE_RICH'''			,   _a  )
  return False


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''sagemaker'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''tqdm'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return _is_package_available('''mlflow'''  )


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  return is_torch_version('''>='''			,   '''1.12'''  ) and torch.backends.mps.is_available() and torch.backends.mps.is_built()


def 		_lowerCamelCase       (   ):
  """simple docstring"""




  def get_major_and_minor_from_version(_a  ):
    return str(version.parse(_a  ).major  ) + "." + str(version.parse(_a  ).minor  )

  _lowerCamelCase      =						importlib.metadata.version('''torch'''  )
  if importlib.util.find_spec('''intel_extension_for_pytorch'''  ) is None:
    return False
  _lowerCamelCase      =						'''N/A'''
  try:
    _lowerCamelCase      =						importlib.metadata.version('''intel_extension_for_pytorch'''  )
  except importlib.metadata.PackageNotFoundError:
    return False
  _lowerCamelCase      =						get_major_and_minor_from_version(_torch_version  )
  _lowerCamelCase      =						get_major_and_minor_from_version(_ipex_version  )
  if torch_major_and_minor != ipex_major_and_minor:
    warnings.warn(
        F'''Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,'''
        F''' but PyTorch {_torch_version} is found. Please switch to the matching version and run again.'''  )
    return False
  return True


@lru_cache
def 		_lowerCamelCase       (   _a=False  ):
  """simple docstring"""




  if importlib.util.find_spec('''torch'''  ) is None or importlib.util.find_spec('''torch_npu'''  ) is None:
    return False

  import torch
  import torch_npu  # noqa: F401

  if check_device:
    try:
      # Will raise a RuntimeError if no NPU is found
      _lowerCamelCase      =						torch.npu.device_count()
      return torch.npu.is_available()
    except RuntimeError:
      return False
  return hasattr(_a			,   '''npu'''  ) and torch.npu.is_available()






@lru_cache
def 		_lowerCamelCase       (   _a=False  ):
  """simple docstring"""




  if not parse_flag_from_env('''ACCELERATE_USE_XPU'''			,   default=_a  ):
    return False
  if is_ipex_available():
    import torch

    if is_torch_version('''<='''			,   '''1.12'''  ):
      return False
  else:
    return False

  import intel_extension_for_pytorch  # noqa: F401

  if check_device:
    try:
      # Will raise a RuntimeError if no XPU  is found
      _lowerCamelCase      =						torch.xpu.device_count()
      return torch.xpu.is_available()
    except RuntimeError:
      return False
  return hasattr(_a			,   '''xpu'''  ) and torch.xpu.is_available()




