

"""simple docstring"""




import unittest

import numpy as np

from transformers.testing_utils import is_flaky, 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 DonutImageProcessor







class   __lowercase      (     unittest.TestCase       ):

  def __init__(	self		:      Union[str, Any]       ,A		:      Union[str, Any]       ,A		:      Dict=7       ,A		:      Optional[int]=3       ,A		:      List[str]=18       ,A		:      Union[str, Any]=30       ,A		:      Tuple=400       ,A		:      Dict=True       ,A		:      List[str]=None       ,A		:      str=True       ,A		:      Optional[Any]=False       ,A		:      Optional[Any]=True       ,A		:      List[str]=True       ,A		:      Optional[int]=[0.5, 0.5, 0.5]       ,A		:      List[str]=[0.5, 0.5, 0.5]       ,):






   '''simple docstring'''
   UpperCAmelCase__       :	str        =       parent
   UpperCAmelCase__       :	List[str]        =       batch_size
   UpperCAmelCase__       :	List[str]        =       num_channels
   UpperCAmelCase__       :	Union[str, Any]        =       image_size
   UpperCAmelCase__       :	List[Any]        =       min_resolution
   UpperCAmelCase__       :	Optional[int]        =       max_resolution
   UpperCAmelCase__       :	str        =       do_resize
   UpperCAmelCase__       :	Tuple        =       size if size is not None else {"""height""": 18, """width""": 20}
   UpperCAmelCase__       :	List[str]        =       do_thumbnail
   UpperCAmelCase__       :	Optional[int]        =       do_align_axis
   UpperCAmelCase__       :	Union[str, Any]        =       do_pad
   UpperCAmelCase__       :	Tuple        =       do_normalize
   UpperCAmelCase__       :	Optional[Any]        =       image_mean
   UpperCAmelCase__       :	List[Any]        =       image_std




  def  __lowercase							(	self		:      Optional[int]     ):






   '''simple docstring'''
   return {
       "do_resize": self.do_resize,
       "size": self.size,
       "do_thumbnail": self.do_thumbnail,
       "do_align_long_axis": self.do_align_axis,
       "do_pad": self.do_pad,
       "do_normalize": self.do_normalize,
       "image_mean": self.image_mean,
       "image_std": self.image_std,
   }







@require_torch
@require_vision
class   __lowercase      (     __lowerCamelCase						,      unittest.TestCase       ):
  snake_case_												=							DonutImageProcessor if is_vision_available() else None

  def  __lowercase							(	self		:      str     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Tuple        =       DonutImageProcessingTester(self     )

  @property
  def  __lowercase							(	self		:      Dict     ):






   '''simple docstring'''
   return self.image_processor_tester.prepare_image_processor_dict()

  def  __lowercase							(	self		:      Any     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Any        =       self.image_processing_class(**self.image_processor_dict     )
   self.assertTrue(hasattr(A       ,"""do_resize"""     )     )
   self.assertTrue(hasattr(A       ,"""size"""     )     )
   self.assertTrue(hasattr(A       ,"""do_thumbnail"""     )     )
   self.assertTrue(hasattr(A       ,"""do_align_long_axis"""     )     )
   self.assertTrue(hasattr(A       ,"""do_pad"""     )     )
   self.assertTrue(hasattr(A       ,"""do_normalize"""     )     )
   self.assertTrue(hasattr(A       ,"""image_mean"""     )     )
   self.assertTrue(hasattr(A       ,"""image_std"""     )     )

  def  __lowercase							(	self		:      Optional[Any]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	List[Any]        =       self.image_processing_class.from_dict(self.image_processor_dict     )
   self.assertEqual(image_processor.size       ,{"""height""": 18, """width""": 20}     )

   UpperCAmelCase__       :	str        =       self.image_processing_class.from_dict(self.image_processor_dict       ,size=42     )
   self.assertEqual(image_processor.size       ,{"""height""": 42, """width""": 42}     )

   # Previous config had dimensions in (width, height) order
   UpperCAmelCase__       :	str        =       self.image_processing_class.from_dict(self.image_processor_dict       ,size=(42, 84)     )
   self.assertEqual(image_processor.size       ,{"""height""": 84, """width""": 42}     )

  def  __lowercase							(	self		:      Dict     ):






   '''simple docstring'''
   pass

  @is_flaky()
  def  __lowercase							(	self		:      int     ):






   '''simple docstring'''
   # Initialize image_processing
   UpperCAmelCase__       :	Optional[int]        =       self.image_processing_class(**self.image_processor_dict     )
   # create random PIL images
   UpperCAmelCase__       :	Dict        =       prepare_image_inputs(self.image_processor_tester       ,equal_resolution=A     )
   for image in image_inputs:
    self.assertIsInstance(A       ,Image.Image     )

   # Test not batched input
   UpperCAmelCase__       :	int        =       image_processing(image_inputs[0]       ,return_tensors="""pt"""     ).pixel_values
   self.assertEqual(
       encoded_images.shape       ,(
           1,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.size["""height"""],
           self.image_processor_tester.size["""width"""],
       )       ,)

   # Test batched
   UpperCAmelCase__       :	Tuple        =       image_processing(A       ,return_tensors="""pt"""     ).pixel_values
   self.assertEqual(
       encoded_images.shape       ,(
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.size["""height"""],
           self.image_processor_tester.size["""width"""],
       )       ,)

  @is_flaky()
  def  __lowercase							(	self		:      List[str]     ):






   '''simple docstring'''
   # Initialize image_processing
   UpperCAmelCase__       :	Union[str, Any]        =       self.image_processing_class(**self.image_processor_dict     )
   # create random numpy tensors
   UpperCAmelCase__       :	Dict        =       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
   UpperCAmelCase__       :	List[str]        =       image_processing(image_inputs[0]       ,return_tensors="""pt"""     ).pixel_values
   self.assertEqual(
       encoded_images.shape       ,(
           1,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.size["""height"""],
           self.image_processor_tester.size["""width"""],
       )       ,)

   # Test batched
   UpperCAmelCase__       :	Optional[int]        =       image_processing(A       ,return_tensors="""pt"""     ).pixel_values
   self.assertEqual(
       encoded_images.shape       ,(
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.size["""height"""],
           self.image_processor_tester.size["""width"""],
       )       ,)




  @is_flaky()
  def  __lowercase							(	self		:      Any     ):






   '''simple docstring'''
   # Initialize image_processing
   UpperCAmelCase__       :	int        =       self.image_processing_class(**self.image_processor_dict     )
   # create random PyTorch tensors
   UpperCAmelCase__       :	int        =       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
   UpperCAmelCase__       :	List[Any]        =       image_processing(image_inputs[0]       ,return_tensors="""pt"""     ).pixel_values
   self.assertEqual(
       encoded_images.shape       ,(
           1,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.size["""height"""],
           self.image_processor_tester.size["""width"""],
       )       ,)

   # Test batched
   UpperCAmelCase__       :	List[Any]        =       image_processing(A       ,return_tensors="""pt"""     ).pixel_values
   self.assertEqual(
       encoded_images.shape       ,(
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.size["""height"""],
           self.image_processor_tester.size["""width"""],
       )       ,)







# 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


lowerCamelCase__     :		Any        = """Create a default config file for Accelerate with only a few flags set."""

def 		UpperCamelCase						(   lowercase_="no"			,			lowercase_ = default_json_config_file			,			lowercase_ = False )		->						Any:


  '''simple docstring'''






  lowercase__	: Any     		=   Path(lowercase_ )
  path.parent.mkdir(parents=lowercase_			,			exist_ok=lowercase_ )
  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__	: int     		=   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__	: Dict     		=   {
      """compute_environment""": """LOCAL_MACHINE""",
      """mixed_precision""": mixed_precision,
  }
  if torch.cuda.is_available():
    lowercase__	: Any     		=   torch.cuda.device_count()
    lowercase__	: Any     		=   num_gpus
    lowercase__	: Optional[int]     		=   False
    if num_gpus > 1:
      lowercase__	: Tuple     		=   """MULTI_GPU"""
    else:
      lowercase__	: Optional[Any]     		=   """NO"""
  elif is_xpu_available() and use_xpu:
    lowercase__	: Union[str, Any]     		=   torch.xpu.device_count()
    lowercase__	: str     		=   num_xpus
    lowercase__	: List[Any]     		=   False
    if num_xpus > 1:
      lowercase__	: str     		=   """MULTI_XPU"""
    else:
      lowercase__	: Optional[Any]     		=   """NO"""
  elif is_npu_available():
    lowercase__	: Tuple     		=   torch.npu.device_count()
    lowercase__	: Union[str, Any]     		=   num_npus
    lowercase__	: Union[str, Any]     		=   False
    if num_npus > 1:
      lowercase__	: List[Any]     		=   """MULTI_NPU"""
    else:
      lowercase__	: int     		=   """NO"""
  else:
    lowercase__	: Union[str, Any]     		=   0
    lowercase__	: str     		=   True
    lowercase__	: Union[str, Any]     		=   1
    lowercase__	: int     		=   """NO"""
  lowercase__	: Tuple     		=   ClusterConfig(**lowercase_ )
  config.to_json_file(lowercase_ )
  return path

def 		UpperCamelCase						(   lowercase_			,			lowercase_ )		->						Optional[Any]:


  '''simple docstring'''






  lowercase__	: List[str]     		=   parser.add_parser("""default"""			,			parents=lowercase_			,			help=lowercase_			,			formatter_class=lowercase_ )
  parser.add_argument(
      """--config_file"""			,			default=lowercase_			,			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=lowercase_			,			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=lowercase_ )
  return parser



def 		UpperCamelCase						(   lowercase_ )		->						Any:


  '''simple docstring'''






  lowercase__	: Optional[Any]     		=   write_basic_config(args.mixed_precision			,			args.save_location )
  if config_file:
    print(F'accelerate configuration saved at {config_file}' )






