





'''simple docstring'''






import importlib.util
import os
import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import (
    is_accelerate_available,
    is_flax_available,
    is_safetensors_available,
    is_tf_available,
    is_torch_available,
)
from . import BaseTransformersCLICommand
def    UpperCamelCase__      (		lowerCAmelCase  ):





      """simple docstring"""


      return EnvironmentCommand()
def    UpperCamelCase__      (		lowerCAmelCase  ):





      """simple docstring"""


      return EnvironmentCommand(args.accelerate_config_file  )





class  UpperCAmelCase     (			snake_case_   ):




      @staticmethod
      def 				lowercase__    (			__snake_case			: ArgumentParser  )				->      Optional[Any]:
            _lowerCAmelCase							     =							parser.add_parser("""env"""  )
            download_parser.set_defaults(func=__snake_case  )
            download_parser.add_argument(
                """--accelerate-config_file"""			,			default=__snake_case			,			help="""The accelerate config file to use for the default values in the launching script."""			,			)
            download_parser.set_defaults(func=__snake_case  )




      def __init__(			self			: Dict			,			__snake_case			: Optional[Any]			,			*__snake_case			: Dict  )				->      None:
            _lowerCAmelCase							     =							accelerate_config_file




      def 				lowercase__    (			self			: Optional[int]  )				->      Dict:
            _lowerCAmelCase							     =							"""not installed"""
            if is_safetensors_available():
                  import safetensors

                  _lowerCAmelCase							     =							safetensors.__version__
            elif importlib.util.find_spec("""safetensors"""  ) is not None:
                  import safetensors

                  _lowerCAmelCase							     =							f"{safetensors.__version__} but is ignored because of PyTorch version too old."

            _lowerCAmelCase							     =							"""not installed"""
            _lowerCAmelCase							     =							_lowerCAmelCase							     =							"""not found"""
            if is_accelerate_available():
                  import accelerate
                  from accelerate.commands.config import default_config_file, load_config_from_file

                  _lowerCAmelCase							     =							accelerate.__version__
                  # Get the default from the config file.
                  if self._accelerate_config_file is not None or os.path.isfile(__snake_case  ):
                        _lowerCAmelCase							     =							load_config_from_file(self._accelerate_config_file  ).to_dict()

                  _lowerCAmelCase							     =							(
                      """\n""".join([f"\t- {prop}: {val}" for prop, val in accelerate_config.items()]  )
                      if isinstance(__snake_case			,			__snake_case  )
                      else f"\t{accelerate_config}"
                  )

            _lowerCAmelCase							     =							"""not installed"""
            _lowerCAmelCase							     =							"""NA"""
            if is_torch_available():
                  import torch

                  _lowerCAmelCase							     =							torch.__version__
                  _lowerCAmelCase							     =							torch.cuda.is_available()

            _lowerCAmelCase							     =							"""not installed"""
            _lowerCAmelCase							     =							"""NA"""
            if is_tf_available():
                  import tensorflow as tf

                  _lowerCAmelCase							     =							tf.__version__
                  try:
                        # deprecated in v2.1
                        _lowerCAmelCase							     =							tf.test.is_gpu_available()
                  except AttributeError:
                        # returns list of devices, convert to bool
                        _lowerCAmelCase							     =							bool(tf.config.list_physical_devices("""GPU"""  )  )

            _lowerCAmelCase							     =							"""not installed"""
            _lowerCAmelCase							     =							"""not installed"""
            _lowerCAmelCase							     =							"""not installed"""
            _lowerCAmelCase							     =							"""NA"""
            if is_flax_available():
                  import flax
                  import jax
                  import jaxlib

                  _lowerCAmelCase							     =							flax.__version__
                  _lowerCAmelCase							     =							jax.__version__
                  _lowerCAmelCase							     =							jaxlib.__version__
                  _lowerCAmelCase							     =							jax.lib.xla_bridge.get_backend().platform

            _lowerCAmelCase							     =							{
                """`transformers` version""": version,
                """Platform""": platform.platform(),
                """Python version""": platform.python_version(),
                """Huggingface_hub version""": huggingface_hub.__version__,
                """Safetensors version""": f"{safetensors_version}",
                """Accelerate version""": f"{accelerate_version}",
                """Accelerate config""": f"{accelerate_config_str}",
                """PyTorch version (GPU?)""": f"{pt_version} ({pt_cuda_available})",
                """Tensorflow version (GPU?)""": f"{tf_version} ({tf_cuda_available})",
                """Flax version (CPU?/GPU?/TPU?)""": f"{flax_version} ({jax_backend})",
                """Jax version""": f"{jax_version}",
                """JaxLib version""": f"{jaxlib_version}",
                """Using GPU in script?""": """<fill in>""",
                """Using distributed or parallel set-up in script?""": """<fill in>""",
            }

            print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n"""  )
            print(self.format_dict(__snake_case  )  )

            return info




      @staticmethod
      def 				lowercase__    (			__snake_case			: str  )				->      Dict:
            return "\n".join([f"- {prop}: {val}" for prop, val in d.items()]  ) + "\n"














'''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:				str			,							UpperCamelCase__:				Optional[Any]			,							UpperCamelCase__:				Any=7			,							UpperCamelCase__:				Optional[int]=3			,							UpperCamelCase__:				List[str]=18			,							UpperCamelCase__:				Union[str, Any]=30			,							UpperCamelCase__:				List[str]=400			,							UpperCamelCase__:				Any=True			,							UpperCamelCase__:				Union[str, Any]=None			,							UpperCamelCase__:				List[Any]=True			,							UpperCamelCase__:				List[Any]=False			,							UpperCamelCase__:				Tuple=True			,							UpperCamelCase__:				Tuple=True			,							UpperCamelCase__:				Any=[0.5, 0.5, 0.5]			,							UpperCamelCase__:				Optional[Any]=[0.5, 0.5, 0.5]			,							):
														lowerCamelCase__					:	int         =       parent
														lowerCamelCase__					:	Any         =       batch_size
														lowerCamelCase__					:	Optional[int]         =       num_channels
														lowerCamelCase__					:	Union[str, Any]         =       image_size
														lowerCamelCase__					:	Optional[int]         =       min_resolution
														lowerCamelCase__					:	Optional[Any]         =       max_resolution
														lowerCamelCase__					:	Union[str, Any]         =       do_resize
														lowerCamelCase__					:	Optional[Any]         =       size if size is not None else {"""height""": 18, """width""": 20}
														lowerCamelCase__					:	Dict         =       do_thumbnail
														lowerCamelCase__					:	Optional[int]         =       do_align_axis
														lowerCamelCase__					:	Any         =       do_pad
														lowerCamelCase__					:	Optional[Any]         =       do_normalize
														lowerCamelCase__					:	Union[str, Any]         =       image_mean
														lowerCamelCase__					:	Union[str, Any]         =       image_std




							def 		lowerCamelCase_				(							self:				str     ):
														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	(				_lowercase				,      unittest.TestCase		):
							a				      =       DonutImageProcessor if is_vision_available() else None




							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														lowerCamelCase__					:	Any         =       DonutImageProcessingTester(self     )




							@property
							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														return self.image_processor_tester.prepare_image_processor_dict()




							def 		lowerCamelCase_				(							self:				Tuple     ):
														lowerCamelCase__					:	Dict         =       self.image_processing_class(**self.image_processor_dict     )
														self.assertTrue(hasattr(UpperCamelCase__			,							"""do_resize"""     )     )
														self.assertTrue(hasattr(UpperCamelCase__			,							"""size"""     )     )
														self.assertTrue(hasattr(UpperCamelCase__			,							"""do_thumbnail"""     )     )
														self.assertTrue(hasattr(UpperCamelCase__			,							"""do_align_long_axis"""     )     )
														self.assertTrue(hasattr(UpperCamelCase__			,							"""do_pad"""     )     )
														self.assertTrue(hasattr(UpperCamelCase__			,							"""do_normalize"""     )     )
														self.assertTrue(hasattr(UpperCamelCase__			,							"""image_mean"""     )     )
														self.assertTrue(hasattr(UpperCamelCase__			,							"""image_std"""     )     )




							def 		lowerCamelCase_				(							self:				Optional[Any]     ):
														lowerCamelCase__					:	Optional[int]         =       self.image_processing_class.from_dict(self.image_processor_dict     )
														self.assertEqual(image_processor.size			,							{"""height""": 18, """width""": 20}     )

														lowerCamelCase__					:	Optional[int]         =       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
														lowerCamelCase__					:	List[str]         =       self.image_processing_class.from_dict(self.image_processor_dict			,							size=(42, 84)     )
														self.assertEqual(image_processor.size			,							{"""height""": 84, """width""": 42}     )




							def 		lowerCamelCase_				(							self:				List[str]     ):
														pass




							@is_flaky()
							def 		lowerCamelCase_				(							self:				Union[str, Any]     ):
														# Initialize image_processing
														lowerCamelCase__					:	str         =       self.image_processing_class(**self.image_processor_dict     )
														# create random PIL images
														lowerCamelCase__					:	Dict         =       prepare_image_inputs(self.image_processor_tester			,							equal_resolution=UpperCamelCase__     )
														for image in image_inputs:
																					self.assertIsInstance(UpperCamelCase__			,							Image.Image     )

														# Test not batched input
														lowerCamelCase__					:	Union[str, 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
														lowerCamelCase__					:	List[str]         =       image_processing(UpperCamelCase__			,							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 		lowerCamelCase_				(							self:				Optional[int]     ):
														# Initialize image_processing
														lowerCamelCase__					:	Dict         =       self.image_processing_class(**self.image_processor_dict     )
														# create random numpy tensors
														lowerCamelCase__					:	Dict         =       prepare_image_inputs(self.image_processor_tester			,							equal_resolution=UpperCamelCase__			,							numpify=UpperCamelCase__     )
														for image in image_inputs:
																					self.assertIsInstance(UpperCamelCase__			,							np.ndarray     )

														# Test not batched input
														lowerCamelCase__					:	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
														lowerCamelCase__					:	Optional[Any]         =       image_processing(UpperCamelCase__			,							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 		lowerCamelCase_				(							self:				Dict     ):
														# Initialize image_processing
														lowerCamelCase__					:	int         =       self.image_processing_class(**self.image_processor_dict     )
														# create random PyTorch tensors
														lowerCamelCase__					:	Optional[int]         =       prepare_image_inputs(self.image_processor_tester			,							equal_resolution=UpperCamelCase__			,							torchify=UpperCamelCase__     )
														for image in image_inputs:
																					self.assertIsInstance(UpperCamelCase__			,							torch.Tensor     )

														# Test not batched input
														lowerCamelCase__					:	Union[str, 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
														lowerCamelCase__					:	Tuple         =       image_processing(UpperCamelCase__			,							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"""],
														    )			,							)

