"""simple docstring"""


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    UpperCAmelCase       (						UpperCAmelCase   )							-> Tuple:
     # Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
     snake_case_   			=   importlib.util.find_spec(SCREAMING_SNAKE_CASE__   ) is not None
     if package_exists:
          try:
               snake_case_   			=   importlib.metadata.metadata(SCREAMING_SNAKE_CASE__   )
               return True
          except importlib.metadata.PackageNotFoundError:
               return False







def    UpperCAmelCase       (						)							-> bool:
     return _torch_distributed_available







def    UpperCAmelCase       (						)							-> Any:
     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    UpperCAmelCase       (						)							-> Tuple:
     return importlib.metadata.version('oneccl_bind_pt'   )







def    UpperCAmelCase       (						)							-> int:
     return _is_package_available('transformer_engine'   )







@lru_cache
def    UpperCAmelCase       (						UpperCAmelCase=True   )							-> Dict:
     # Due to bugs on the amp series GPUs, we disable torch-xla on them
     if torch.cuda.is_available():
          return False
     if _tpu_available and check_device:
          try:
               # Will raise a RuntimeError if no XLA configuration is found
               snake_case_   			=   xm.xla_device()
               return True
          except RuntimeError:
               return False
     return _tpu_available







def    UpperCAmelCase       (						)							-> List[Any]:
     return _is_package_available('deepspeed'   )







def    UpperCAmelCase       (						UpperCAmelCase=False   )							-> Union[str, Any]:
     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    UpperCAmelCase       (						)							-> Tuple:
     snake_case_   			=   _is_package_available('bitsandbytes'   )
     if package_exists:
          snake_case_   			=   version.parse(importlib.metadata.version('bitsandbytes'   )   )
          return compare_versions(SCREAMING_SNAKE_CASE__		,   '>='		,   '0.39.0'   )
     return False







def    UpperCAmelCase       (						)							-> Union[str, Any]:
     snake_case_   			=   _is_package_available('bitsandbytes'   )
     if package_exists:
          snake_case_   			=   version.parse(importlib.metadata.version('bitsandbytes'   )   )
          return compare_versions(SCREAMING_SNAKE_CASE__		,   '>='		,   '0.37.2'   )
     return False







def    UpperCAmelCase       (						)							-> int:
     return _is_package_available('bitsandbytes'   )







def    UpperCAmelCase       (						)							-> Optional[int]:
     if strtobool(os.environ.get('ACCELERATE_USE_MEGATRON_LM'		,   'False'   )   ) == 1:
          snake_case_   			=   importlib.util.find_spec('megatron'   ) is not None
          if package_exists:
               try:
                    snake_case_   			=   parse(importlib.metadata.version('megatron-lm'   )   )
                    return compare_versions(SCREAMING_SNAKE_CASE__		,   '>='		,   '2.2.0'   )
               except Exception as e:
                    warnings.warn(f'Parse Megatron version failed. Exception:{e}'   )
                    return False







def    UpperCAmelCase       (						)							-> Dict:
     return _is_package_available('safetensors'   )







def    UpperCAmelCase       (						)							-> List[str]:
     return _is_package_available('transformers'   )







def    UpperCAmelCase       (						)							-> str:
     return _is_package_available('datasets'   )







def    UpperCAmelCase       (						)							-> Any:
     return _is_package_available('aim'   )







def    UpperCAmelCase       (						)							-> List[Any]:
     return _is_package_available('tensorboard'   ) or _is_package_available('tensorboardX'   )







def    UpperCAmelCase       (						)							-> Tuple:
     return _is_package_available('wandb'   )







def    UpperCAmelCase       (						)							-> Any:
     return _is_package_available('comet_ml'   )







def    UpperCAmelCase       (						)							-> List[Any]:
     return _is_package_available('boto3'   )







def    UpperCAmelCase       (						)							-> Union[str, Any]:
     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'		,   SCREAMING_SNAKE_CASE__   )
          return parse_flag_from_env('ACCELERATE_ENABLE_RICH'		,   SCREAMING_SNAKE_CASE__   )
     return False







def    UpperCAmelCase       (						)							-> Union[str, Any]:
     return _is_package_available('sagemaker'   )







def    UpperCAmelCase       (						)							-> List[Any]:
     return _is_package_available('tqdm'   )







def    UpperCAmelCase       (						)							-> List[Any]:
     return _is_package_available('mlflow'   )







def    UpperCAmelCase       (						)							-> Union[str, Any]:
     return is_torch_version('>='		,   '1.12'   ) and torch.backends.mps.is_available() and torch.backends.mps.is_built()







def    UpperCAmelCase       (						)							-> Union[str, Any]:
     def get_major_and_minor_from_version(UpperCAmelCase   ):
          return str(version.parse(SCREAMING_SNAKE_CASE__   ).major   ) + "." + str(version.parse(SCREAMING_SNAKE_CASE__   ).minor   )

     snake_case_   			=   importlib.metadata.version('torch'   )
     if importlib.util.find_spec('intel_extension_for_pytorch'   ) is None:
          return False
     snake_case_   			=   '''N/A'''
     try:
          snake_case_   			=   importlib.metadata.version('intel_extension_for_pytorch'   )
     except importlib.metadata.PackageNotFoundError:
          return False
     snake_case_   			=   get_major_and_minor_from_version(_torch_version   )
     snake_case_   			=   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    UpperCAmelCase       (						UpperCAmelCase=False   )							-> Any:
     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
               snake_case_   			=   torch.npu.device_count()
               return torch.npu.is_available()
          except RuntimeError:
               return False
     return hasattr(SCREAMING_SNAKE_CASE__		,   'npu'   ) and torch.npu.is_available()







@lru_cache
def    UpperCAmelCase       (						UpperCAmelCase=False   )							-> int:
     if not parse_flag_from_env('ACCELERATE_USE_XPU'		,   default=SCREAMING_SNAKE_CASE__   ):
          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
               snake_case_   			=   torch.xpu.device_count()
               return torch.xpu.is_available()
          except RuntimeError:
               return False
     return hasattr(SCREAMING_SNAKE_CASE__		,   'xpu'   ) and torch.xpu.is_available()








'''simple docstring'''







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


snake_case_  :							Any            =	logging.get_logger(__name__)


if is_vision_available():
					import PIL


class        __a   (lowerCamelCase  ):
							__a       : Any          =							["pixel_values"]

							def __init__(				self				:  Optional[int]							,  __magic_name__				:  bool = True							,  __magic_name__				:  Dict[str, int] = None							,  __magic_name__				:  PILImageResampling = PILImageResampling.BICUBIC							,  __magic_name__				:  bool = True							,  __magic_name__				:  Dict[str, int] = None							,  __magic_name__				:  bool = True							,  __magic_name__				:  Union[int, float] = 1 / 2_55							,  __magic_name__				:  bool = True							,  __magic_name__				:  Optional[Union[float, List[float]]] = None							,  __magic_name__				:  Optional[Union[float, List[float]]] = None							,  __magic_name__				:  bool = True							,  **__magic_name__				:  Union[str, Any]							,  )       ->							None:







													"""simple docstring"""
													super().__init__(**__magic_name__ )
													UpperCAmelCase_      :   List[Any]      =	size if size is not None else {'''shortest_edge''': 2_24}
													UpperCAmelCase_      :   List[str]      =	get_size_dict(__magic_name__							,  default_to_square=__magic_name__ )
													UpperCAmelCase_      :   int      =	crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
													UpperCAmelCase_      :   Union[str, Any]      =	get_size_dict(__magic_name__ )

													UpperCAmelCase_      :   str      =	do_resize
													UpperCAmelCase_      :   Optional[Any]      =	size
													UpperCAmelCase_      :   int      =	resample
													UpperCAmelCase_      :   List[str]      =	do_center_crop
													UpperCAmelCase_      :   Optional[Any]      =	crop_size
													UpperCAmelCase_      :   List[str]      =	do_rescale
													UpperCAmelCase_      :   Union[str, Any]      =	rescale_factor
													UpperCAmelCase_      :   int      =	do_normalize
													UpperCAmelCase_      :   Any      =	image_mean if image_mean is not None else OPENAI_CLIP_MEAN
													UpperCAmelCase_      :   Optional[Any]      =	image_std if image_std is not None else OPENAI_CLIP_STD
													UpperCAmelCase_      :   int      =	do_convert_rgb

							def      UpperCAmelCase__						(				self				:  int							,  __magic_name__				:  np.ndarray							,  __magic_name__				:  Dict[str, int]							,  __magic_name__				:  PILImageResampling = PILImageResampling.BICUBIC							,  __magic_name__				:  Optional[Union[str, ChannelDimension]] = None							,  **__magic_name__				:  Optional[int]							,  )       ->							np.ndarray:







													"""simple docstring"""
													UpperCAmelCase_      :   Optional[Any]      =	get_size_dict(__magic_name__							,  default_to_square=__magic_name__ )
													UpperCAmelCase_      :   Any      =	get_resize_output_image_size(
													    __magic_name__							,  size=(size['''height'''], size['''width'''])							,  default_to_square=__magic_name__ )
													return resize(__magic_name__							,  size=__magic_name__							,  resample=__magic_name__							,  data_format=__magic_name__							,  **__magic_name__ )

							def      UpperCAmelCase__						(				self				:  List[Any]							,  __magic_name__				:  np.ndarray							,  __magic_name__				:  Dict[str, int]							,  __magic_name__				:  Optional[Union[str, ChannelDimension]] = None							,  **__magic_name__				:  Any							,  )       ->							np.ndarray:







													"""simple docstring"""
													UpperCAmelCase_      :   List[Any]      =	get_size_dict(__magic_name__ )
													return center_crop(__magic_name__							,  size=(size['''height'''], size['''width'''])							,  data_format=__magic_name__							,  **__magic_name__ )

							def      UpperCAmelCase__						(				self				:  str							,  __magic_name__				:  np.ndarray							,  __magic_name__				:  Union[int, float]							,  __magic_name__				:  Optional[Union[str, ChannelDimension]] = None							,  **__magic_name__				:  Any							,  )       ->							Union[str, Any]:







													"""simple docstring"""
													return rescale(__magic_name__							,  scale=__magic_name__							,  data_format=__magic_name__							,  **__magic_name__ )

							def      UpperCAmelCase__						(				self				:  str							,  __magic_name__				:  np.ndarray							,  __magic_name__				:  Union[float, List[float]]							,  __magic_name__				:  Union[float, List[float]]							,  __magic_name__				:  Optional[Union[str, ChannelDimension]] = None							,  **__magic_name__				:  Optional[int]							,  )       ->							np.ndarray:







													"""simple docstring"""
													return normalize(__magic_name__							,  mean=__magic_name__							,  std=__magic_name__							,  data_format=__magic_name__							,  **__magic_name__ )



							def      UpperCAmelCase__						(				self				:  Dict							,  __magic_name__				:  ImageInput							,  __magic_name__				:  bool = None							,  __magic_name__				:  Dict[str, int] = None							,  __magic_name__				:  PILImageResampling = None							,  __magic_name__				:  bool = None							,  __magic_name__				:  int = None							,  __magic_name__				:  bool = None							,  __magic_name__				:  float = None							,  __magic_name__				:  bool = None							,  __magic_name__				:  Optional[Union[float, List[float]]] = None							,  __magic_name__				:  Optional[Union[float, List[float]]] = None							,  __magic_name__				:  bool = None							,  __magic_name__				:  Optional[Union[str, TensorType]] = None							,  __magic_name__				:  Optional[ChannelDimension] = ChannelDimension.FIRST							,  **__magic_name__				:  Union[str, Any]							,  )       ->							PIL.Image.Image:







													"""simple docstring"""
													UpperCAmelCase_      :   int      =	do_resize if do_resize is not None else self.do_resize
													UpperCAmelCase_      :   Dict      =	size if size is not None else self.size
													UpperCAmelCase_      :   Union[str, Any]      =	get_size_dict(__magic_name__							,  default_to_square=__magic_name__ )
													UpperCAmelCase_      :   str      =	resample if resample is not None else self.resample
													UpperCAmelCase_      :   Tuple      =	do_center_crop if do_center_crop is not None else self.do_center_crop
													UpperCAmelCase_      :   List[str]      =	crop_size if crop_size is not None else self.crop_size
													UpperCAmelCase_      :   Optional[Any]      =	get_size_dict(__magic_name__ )
													UpperCAmelCase_      :   str      =	do_rescale if do_rescale is not None else self.do_rescale
													UpperCAmelCase_      :   Tuple      =	rescale_factor if rescale_factor is not None else self.rescale_factor
													UpperCAmelCase_      :   List[Any]      =	do_normalize if do_normalize is not None else self.do_normalize
													UpperCAmelCase_      :   Tuple      =	image_mean if image_mean is not None else self.image_mean
													UpperCAmelCase_      :   int      =	image_std if image_std is not None else self.image_std
													UpperCAmelCase_      :   Optional[Any]      =	do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

													UpperCAmelCase_      :   Any      =	make_list_of_images(__magic_name__ )

													if not valid_images(__magic_name__ ):
																			raise ValueError(
																			    '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
																			    '''torch.Tensor, tf.Tensor or jax.ndarray.''' )

													if do_resize and size is None:
																			raise ValueError('''Size must be specified if do_resize is True.''' )

													if do_center_crop and crop_size is None:
																			raise ValueError('''Crop size must be specified if do_center_crop is True.''' )

													if do_rescale and rescale_factor is None:
																			raise ValueError('''Rescale factor must be specified if do_rescale is True.''' )

													if do_normalize and (image_mean is None or image_std is None):
																			raise ValueError('''Image mean and std must be specified if do_normalize is True.''' )

													# PIL RGBA images are converted to RGB
													if do_convert_rgb:
																			UpperCAmelCase_      :   Optional[int]      =	[convert_to_rgb(__magic_name__ ) for image in images]

													# All transformations expect numpy arrays.
													UpperCAmelCase_      :   Optional[Any]      =	[to_numpy_array(__magic_name__ ) for image in images]

													if do_resize:
																			UpperCAmelCase_      :   Dict      =	[self.resize(image=__magic_name__							,  size=__magic_name__							,  resample=__magic_name__ ) for image in images]

													if do_center_crop:
																			UpperCAmelCase_      :   Union[str, Any]      =	[self.center_crop(image=__magic_name__							,  size=__magic_name__ ) for image in images]

													if do_rescale:
																			UpperCAmelCase_      :   Dict      =	[self.rescale(image=__magic_name__							,  scale=__magic_name__ ) for image in images]

													if do_normalize:
																			UpperCAmelCase_      :   Optional[int]      =	[self.normalize(image=__magic_name__							,  mean=__magic_name__							,  std=__magic_name__ ) for image in images]

													UpperCAmelCase_      :   Optional[Any]      =	[to_channel_dimension_format(__magic_name__							,  __magic_name__ ) for image in images]

													UpperCAmelCase_      :   int      =	{'''pixel_values''': images}
													return BatchFeature(data=__magic_name__							,  tensor_type=__magic_name__ )





