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


UpperCamelCase__  :						int					=      logging.get_logger(__name__)


if is_vision_available():
  import PIL


class 					_lowercase						(   lowerCAmelCase ):
      '''simple docstring'''


      UpperCAmelCase_   :   Union[str, Any]   				= ['''pixel_values''']




      def __init__(					self       ,lowerCamelCase_ = True       ,lowerCamelCase_ = None       ,lowerCamelCase_ = PILImageResampling.BICUBIC       ,lowerCamelCase_ = True       ,lowerCamelCase_ = None       ,lowerCamelCase_ = True       ,lowerCamelCase_ = 1 / 255       ,lowerCamelCase_ = True       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = True       ,**lowerCamelCase_       ,)      ->      None:



         '''simple docstring'''



         super().__init__(**lowerCamelCase_				)
         UpperCAmelCase__				:					str 					=	size if size is not None else {'''shortest_edge''': 224}
         UpperCAmelCase__				:					Dict 					=	get_size_dict(lowerCamelCase_       ,default_to_square=lowerCamelCase_				)
         UpperCAmelCase__				:					Dict 					=	crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
         UpperCAmelCase__				:					Optional[int] 					=	get_size_dict(lowerCamelCase_       ,default_to_square=lowerCamelCase_       ,param_name='''crop_size'''				)

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




      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_       ,lowerCamelCase_ = PILImageResampling.BICUBIC       ,lowerCamelCase_ = None       ,**lowerCamelCase_       ,)      ->      np.ndarray:



         '''simple docstring'''



         UpperCAmelCase__				:					Tuple 					=	get_size_dict(lowerCamelCase_       ,default_to_square=lowerCamelCase_				)
         if "shortest_edge" not in size:
            raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''				)
         UpperCAmelCase__				:					Tuple 					=	get_resize_output_image_size(lowerCamelCase_       ,size=size['''shortest_edge''']       ,default_to_square=lowerCamelCase_				)
         return resize(lowerCamelCase_       ,size=lowerCamelCase_       ,resample=lowerCamelCase_       ,data_format=lowerCamelCase_       ,**lowerCamelCase_				)




      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_       ,lowerCamelCase_ = None       ,**lowerCamelCase_       ,)      ->      np.ndarray:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[int] 					=	get_size_dict(lowerCamelCase_				)
         if "height" not in size or "width" not in size:
            raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''				)
         return center_crop(lowerCamelCase_       ,size=(size['''height'''], size['''width'''])       ,data_format=lowerCamelCase_       ,**lowerCamelCase_				)




      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_       ,lowerCamelCase_ = None       ,**lowerCamelCase_       ,)      ->      Union[str, Any]:



         '''simple docstring'''



         return rescale(lowerCamelCase_       ,scale=lowerCamelCase_       ,data_format=lowerCamelCase_       ,**lowerCamelCase_				)




      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_       ,lowerCamelCase_       ,lowerCamelCase_ = None       ,**lowerCamelCase_       ,)      ->      np.ndarray:



         '''simple docstring'''



         return normalize(lowerCamelCase_       ,mean=lowerCamelCase_       ,std=lowerCamelCase_       ,data_format=lowerCamelCase_       ,**lowerCamelCase_				)




      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = None       ,lowerCamelCase_ = ChannelDimension.FIRST       ,**lowerCamelCase_       ,)      ->      PIL.Image.Image:



         '''simple docstring'''



         UpperCAmelCase__				:					Any 					=	do_resize if do_resize is not None else self.do_resize
         UpperCAmelCase__				:					Any 					=	size if size is not None else self.size
         UpperCAmelCase__				:					int 					=	get_size_dict(lowerCamelCase_       ,param_name='''size'''       ,default_to_square=lowerCamelCase_				)
         UpperCAmelCase__				:					Tuple 					=	resample if resample is not None else self.resample
         UpperCAmelCase__				:					str 					=	do_center_crop if do_center_crop is not None else self.do_center_crop
         UpperCAmelCase__				:					Any 					=	crop_size if crop_size is not None else self.crop_size
         UpperCAmelCase__				:					Optional[int] 					=	get_size_dict(lowerCamelCase_       ,param_name='''crop_size'''       ,default_to_square=lowerCamelCase_				)
         UpperCAmelCase__				:					List[str] 					=	do_rescale if do_rescale is not None else self.do_rescale
         UpperCAmelCase__				:					str 					=	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__				:					Dict 					=	image_std if image_std is not None else self.image_std
         UpperCAmelCase__				:					int 					=	do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

         UpperCAmelCase__				:					Optional[Any] 					=	make_list_of_images(lowerCamelCase_				)

         if not valid_images(lowerCamelCase_				):
            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__				:					Union[str, Any] 					=	[convert_to_rgb(lowerCamelCase_				) for image in images]

         # All transformations expect numpy arrays.
         UpperCAmelCase__				:					Optional[int] 					=	[to_numpy_array(lowerCamelCase_				) for image in images]

         if do_resize:
            UpperCAmelCase__				:					List[Any] 					=	[self.resize(image=lowerCamelCase_       ,size=lowerCamelCase_       ,resample=lowerCamelCase_				) for image in images]

         if do_center_crop:
            UpperCAmelCase__				:					Any 					=	[self.center_crop(image=lowerCamelCase_       ,size=lowerCamelCase_				) for image in images]

         if do_rescale:
            UpperCAmelCase__				:					List[Any] 					=	[self.rescale(image=lowerCamelCase_       ,scale=lowerCamelCase_				) for image in images]

         if do_normalize:
            UpperCAmelCase__				:					int 					=	[self.normalize(image=lowerCamelCase_       ,mean=lowerCamelCase_       ,std=lowerCamelCase_				) for image in images]

         UpperCAmelCase__				:					Optional[int] 					=	[to_channel_dimension_format(lowerCamelCase_       ,lowerCamelCase_				) for image in images]

         UpperCAmelCase__				:					Any 					=	{'''pixel_values''': images}
         return BatchFeature(data=lowerCamelCase_       ,tensor_type=lowerCamelCase_				)





'''simple docstring'''

import os
import sys
import tempfile

import torch

from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment







def __UpperCamelCase( _A       :					Any	,      _A       :					List[str]=()	,      _A       :					List[str]=None	,      _A       :					Dict="no"	,      _A       :					List[str]="29500"     ):
   '''simple docstring'''
   UpperCAmelCase__				:					int 					=	False
   UpperCAmelCase__				:					List[str] 					=	False
   if any(key.startswith('''KAGGLE'''     ) for key in os.environ.keys()     ):
      UpperCAmelCase__				:					List[str] 					=	True
   elif "IPython" in sys.modules:
      UpperCAmelCase__				:					List[Any] 					=	'''google.colab''' in str(sys.modules['''IPython'''].get_ipython()     )

   try:
      UpperCAmelCase__				:					Tuple 					=	PrecisionType(mixed_precision.lower()     )
   except ValueError:
      raise ValueError(
          F'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.'''     )

   if (in_colab or in_kaggle) and (os.environ.get('''TPU_NAME'''	,      _A     ) is not None):
      # TPU launch
      import torch_xla.distributed.xla_multiprocessing as xmp

      if len(AcceleratorState._shared_state     ) > 0:
         raise ValueError(
             '''To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside '''
             '''your training function. Restart your notebook and make sure no cells initializes an '''
             '''`Accelerator`.'''     )
      if num_processes is None:
         UpperCAmelCase__				:					Tuple 					=	8

      UpperCAmelCase__				:					Optional[Any] 					=	PrepareForLaunch(_A	,      distributed_type='''TPU'''     )
      print(F'''Launching a training on {num_processes} TPU cores.'''     )
      xmp.spawn(_A	,      args=_A	,      nprocs=_A	,      start_method='''fork'''     )
   elif in_colab:
      # No need for a distributed launch otherwise as it's either CPU or one GPU.
      if torch.cuda.is_available():
         print('''Launching training on one GPU.'''     )
      else:
         print('''Launching training on one CPU.'''     )
      function(*_A     )
   else:
      if num_processes is None:
         raise ValueError(
             '''You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.'''     )

      if num_processes > 1:
         # Multi-GPU launch
         from torch.multiprocessing import start_processes
         from torch.multiprocessing.spawn import ProcessRaisedException

         if len(AcceleratorState._shared_state     ) > 0:
            raise ValueError(
                '''To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized '''
                '''inside your training function. Restart your notebook and make sure no cells initializes an '''
                '''`Accelerator`.'''     )

         if torch.cuda.is_initialized():
            raise ValueError(
                '''To launch a multi-GPU training from your notebook, you need to avoid running any instruction '''
                '''using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA '''
                '''function.'''     )

         # torch.distributed will expect a few environment variable to be here. We set the ones common to each
         # process here (the other ones will be set be the launcher).
         with patch_environment(
             world_size=_A	,      master_addr='''127.0.01'''	,      master_port=_A	,      mixed_precision=_A     ):
            UpperCAmelCase__				:					str 					=	PrepareForLaunch(_A	,      distributed_type='''MULTI_GPU'''     )
            print(F'''Launching training on {num_processes} GPUs.'''     )
            try:
               start_processes(_A	,      args=_A	,      nprocs=_A	,      start_method='''fork'''     )
            except ProcessRaisedException as e:
               if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
                  raise RuntimeError(
                      '''CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. '''
                      '''This likely stems from an outside import causing issues once the `notebook_launcher()` is called. '''
                      '''Please review your imports and test them when running the `notebook_launcher()` to identify '''
                      '''which one is problematic.'''     ) from e

      else:
         # No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
         if is_mps_available():
            UpperCAmelCase__				:					Union[str, Any] 					=	'''1'''
            print('''Launching training on MPS.'''     )
         elif torch.cuda.is_available():
            print('''Launching training on one GPU.'''     )
         else:
            print('''Launching training on CPU.'''     )
         function(*_A     )







def __UpperCamelCase( _A       :					List[str]	,      _A       :					Optional[Any]=()	,      _A       :					str=2     ):
   '''simple docstring'''
   from torch.multiprocessing import start_processes

   with tempfile.NamedTemporaryFile() as tmp_file:
      # torch.distributed will expect a few environment variable to be here. We set the ones common to each
      # process here (the other ones will be set be the launcher).
      with patch_environment(
          world_size=_A	,      master_addr='''127.0.01'''	,      master_port='''29500'''	,      accelerate_mixed_precision='''no'''	,      accelerate_debug_rdv_file=tmp_file.name	,      accelerate_use_cpu='''yes'''	,      ):
         UpperCAmelCase__				:					Optional[int] 					=	PrepareForLaunch(_A	,      debug=_A     )
         start_processes(_A	,      args=_A	,      nprocs=_A	,      start_method='''fork'''     )




