
"""simple docstring"""




# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


A__   :					str							=   'Create a default config file for Accelerate with only a few flags set.'




def  _lowerCAmelCase		(		_UpperCamelCase="no" ,				_UpperCamelCase = default_json_config_file ,				_UpperCamelCase = False						):






  """simple docstring"""



  _lowercase:			int       =     Path(_UpperCamelCase						)
  path.parent.mkdir(parents=_UpperCamelCase ,				exist_ok=_UpperCamelCase						)
  if path.exists():
    print(
        f'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'''						)
    return False
  _lowercase:			Dict       =     mixed_precision.lower()
  if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
    raise ValueError(
        f'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'''						)
  _lowercase:			List[Any]       =     {
      '''compute_environment''': '''LOCAL_MACHINE''',
      '''mixed_precision''': mixed_precision,
  }
  if torch.cuda.is_available():
    _lowercase:			List[str]       =     torch.cuda.device_count()
    _lowercase:			Union[str, Any]       =     num_gpus
    _lowercase:			str       =     False
    if num_gpus > 1:
      _lowercase:			Optional[Any]       =     '''MULTI_GPU'''
    else:
      _lowercase:			Any       =     '''NO'''
  elif is_xpu_available() and use_xpu:
    _lowercase:			Union[str, Any]       =     torch.xpu.device_count()
    _lowercase:			Union[str, Any]       =     num_xpus
    _lowercase:			Optional[Any]       =     False
    if num_xpus > 1:
      _lowercase:			List[Any]       =     '''MULTI_XPU'''
    else:
      _lowercase:			int       =     '''NO'''
  elif is_npu_available():
    _lowercase:			Tuple       =     torch.npu.device_count()
    _lowercase:			str       =     num_npus
    _lowercase:			Optional[int]       =     False
    if num_npus > 1:
      _lowercase:			List[str]       =     '''MULTI_NPU'''
    else:
      _lowercase:			Dict       =     '''NO'''
  else:
    _lowercase:			int       =     0
    _lowercase:			Union[str, Any]       =     True
    _lowercase:			Dict       =     1
    _lowercase:			List[str]       =     '''NO'''
  _lowercase:			Optional[Any]       =     ClusterConfig(**_UpperCamelCase						)
  config.to_json_file(_UpperCamelCase						)
  return path




def  _lowerCAmelCase		(		_UpperCamelCase ,				_UpperCamelCase						):






  """simple docstring"""



  _lowercase:			Optional[Any]       =     parser.add_parser('''default''' ,				parents=_UpperCamelCase ,				help=_UpperCamelCase ,				formatter_class=_UpperCamelCase						)
  parser.add_argument(
      '''--config_file''' ,				default=_UpperCamelCase ,				help=(
          '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
          '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
          '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
          '''with \'huggingface\'.'''
      ) ,				dest='''save_location''' ,				)

  parser.add_argument(
      '''--mixed_precision''' ,				choices=['''no''', '''fp16''', '''bf16'''] ,				type=_UpperCamelCase ,				help='''Whether or not to use mixed precision training. '''
      '''Choose between FP16 and BF16 (bfloat16) training. '''
      '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.''' ,				default='''no''' ,				)
  parser.set_defaults(func=_UpperCamelCase						)
  return parser







def  _lowerCAmelCase		(		_UpperCamelCase						):






  """simple docstring"""



  _lowercase:			Any       =     write_basic_config(args.mixed_precision ,				args.save_location						)
  if config_file:
    print(f'''accelerate configuration saved at {config_file}'''						)


"""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,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_batched,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


A__   :					Dict							=   logging.get_logger(__name__)


class 			__magic_name__       (       SCREAMING_SNAKE_CASE__ ):
       UpperCamelCase_   =		['''pixel_values''']
       def __init__(     self ,				A_ = True ,				A_ = None ,				A_ = PILImageResampling.BICUBIC ,				A_ = True ,				A_ = True ,				A_ = 1 / 255 ,				A_ = None ,				A_ = True ,				A_ = None ,				A_ = None ,				**A_ ,				)     ->	None:





         """simple docstring"""




         super().__init__(**A_       )
         _lowercase:			List[str]       =     size if size is not None else {'''height''': 224, '''width''': 224}
         _lowercase:			Dict       =     get_size_dict(A_       )
         _lowercase:			Any       =     crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
         _lowercase:			List[str]       =     get_size_dict(A_ ,				default_to_square=A_ ,				param_name='''crop_size'''       )

         _lowercase:			List[Any]       =     do_resize
         _lowercase:			Tuple       =     do_rescale
         _lowercase:			Union[str, Any]       =     do_normalize
         _lowercase:			Optional[int]       =     do_center_crop
         _lowercase:			List[str]       =     crop_size
         _lowercase:			int       =     size
         _lowercase:			List[Any]       =     resample
         _lowercase:			Optional[Any]       =     rescale_factor
         _lowercase:			str       =     image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
         _lowercase:			Dict       =     image_std if image_std is not None else IMAGENET_DEFAULT_STD
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ = PILImageResampling.BILINEAR ,				A_ = None ,				**A_ ,				)     ->	np.ndarray:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     get_size_dict(A_       )

         if "shortest_edge" in size:
           _lowercase:			Optional[int]       =     get_resize_output_image_size(A_ ,				size=size['''shortest_edge'''] ,				default_to_square=A_       )
           # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
         elif "height" in size and "width" in size:
           _lowercase:			Dict       =     (size['''height'''], size['''width'''])
         else:
           raise ValueError(f'''Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}'''       )
         return resize(A_ ,				size=A_ ,				resample=A_ ,				data_format=A_ ,				**A_       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ = None ,				**A_ ,				)     ->	np.ndarray:





         """simple docstring"""




         _lowercase:			Dict       =     get_size_dict(A_       )
         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(A_ ,				size=(size['''height'''], size['''width''']) ,				data_format=A_ ,				**A_       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ = None ,				**A_       )     ->	np.ndarray:





         """simple docstring"""




         return rescale(A_ ,				scale=A_ ,				data_format=A_ ,				**A_       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ = None ,				**A_ ,				)     ->	np.ndarray:





         """simple docstring"""




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



       def 							lowercase_							(     self ,				A_ ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = None ,				A_ = ChannelDimension.FIRST ,				**A_ ,				)     ->	BatchFeature:





         """simple docstring"""




         _lowercase:			List[Any]       =     do_resize if do_resize is not None else self.do_resize
         _lowercase:			Tuple       =     do_rescale if do_rescale is not None else self.do_rescale
         _lowercase:			Optional[Any]       =     do_normalize if do_normalize is not None else self.do_normalize
         _lowercase:			Optional[int]       =     do_center_crop if do_center_crop is not None else self.do_center_crop
         _lowercase:			Optional[int]       =     crop_size if crop_size is not None else self.crop_size
         _lowercase:			List[Any]       =     get_size_dict(A_ ,				param_name='''crop_size''' ,				default_to_square=A_       )
         _lowercase:			List[str]       =     resample if resample is not None else self.resample
         _lowercase:			List[str]       =     rescale_factor if rescale_factor is not None else self.rescale_factor
         _lowercase:			List[Any]       =     image_mean if image_mean is not None else self.image_mean
         _lowercase:			List[str]       =     image_std if image_std is not None else self.image_std

         _lowercase:			List[Any]       =     size if size is not None else self.size
         _lowercase:			List[str]       =     get_size_dict(A_       )

         if not is_batched(A_       ):
           _lowercase:			Optional[Any]       =     [images]

         if not valid_images(A_       ):
           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.'''       )

         # All transformations expect numpy arrays.
         _lowercase:			Dict       =     [to_numpy_array(A_       ) for image in images]

         if do_resize:
           _lowercase:			int       =     [self.resize(image=A_ ,				size=A_ ,				resample=A_       ) for image in images]

         if do_center_crop:
           _lowercase:			str       =     [self.center_crop(image=A_ ,				size=A_       ) for image in images]

         if do_rescale:
           _lowercase:			Optional[Any]       =     [self.rescale(image=A_ ,				scale=A_       ) for image in images]

         if do_normalize:
           _lowercase:			List[Any]       =     [self.normalize(image=A_ ,				mean=A_ ,				std=A_       ) for image in images]

         _lowercase:			Optional[Any]       =     [to_channel_dimension_format(A_ ,				A_       ) for image in images]

         _lowercase:			Any       =     {'''pixel_values''': images}
         return BatchFeature(data=A_ ,				tensor_type=A_       )
