





'''simple docstring'''






import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
     from PIL import Image

     from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
     import torch

if is_tf_available():
     import tensorflow as tf


@require_vision
@require_torchvision
class   _lowercase						(							unittest.TestCase				):


   def 					snake_case				( self					):
       A       :       Optional[int]							=						tempfile.mkdtemp()
       A       :       Optional[Any]							=						SamImageProcessor()
       A       :       List[str]							=						SamProcessor(_UpperCAmelCase					)
       processor.save_pretrained(self.tmpdirname					)


   def 					snake_case				( self    ,   **_UpperCAmelCase					):
       return AutoProcessor.from_pretrained(self.tmpdirname    ,   **_UpperCAmelCase					).image_processor


   def 					snake_case				( self					):
       shutil.rmtree(self.tmpdirname					)


   def 					snake_case				( self					):
       A       :       List[Any]							=						[np.random.randint(255    ,   size=(3, 30, 400)    ,   dtype=np.uinta					)]

       A       :       Any							=						[Image.fromarray(np.moveaxis(_UpperCAmelCase    ,   0    ,   -1					)					) for x in image_inputs]

       return image_inputs


   def 					snake_case				( self					):
       A       :       Tuple							=						SamProcessor(image_processor=self.get_image_processor()					)
       processor.save_pretrained(self.tmpdirname					)

       A       :       List[str]							=						self.get_image_processor(do_normalize=_UpperCAmelCase    ,   padding_value=1.0					)

       A       :       List[str]							=						SamProcessor.from_pretrained(self.tmpdirname    ,   do_normalize=_UpperCAmelCase    ,   padding_value=1.0					)

       self.assertEqual(processor.image_processor.to_json_string()    ,   image_processor_add_kwargs.to_json_string()					)
       self.assertIsInstance(processor.image_processor    ,   _UpperCAmelCase					)


   def 					snake_case				( self					):
       A       :       Union[str, Any]							=						self.get_image_processor()

       A       :       Optional[Any]							=						SamProcessor(image_processor=_UpperCAmelCase					)

       A       :       List[str]							=						self.prepare_image_inputs()

       A       :       Optional[Any]							=						image_processor(_UpperCAmelCase    ,   return_tensors='''np'''					)
       A       :       Tuple							=						processor(images=_UpperCAmelCase    ,   return_tensors='''np'''					)

       input_feat_extract.pop('''original_sizes'''					)  # pop original_sizes as it is popped in the processor
       input_feat_extract.pop('''reshaped_input_sizes'''					)  # pop original_sizes as it is popped in the processor

       for key in input_feat_extract.keys():
           self.assertAlmostEqual(input_feat_extract[key].sum()    ,   input_processor[key].sum()    ,   delta=1E-2					)


   @require_torch
   def 					snake_case				( self					):
       A       :       int							=						self.get_image_processor()

       A       :       int							=						SamProcessor(image_processor=_UpperCAmelCase					)
       A       :       str							=						[torch.ones((1, 3, 5, 5)					)]

       A       :       str							=						[[1_764, 2_646]]

       A       :       Optional[Any]							=						[[683, 1_024]]
       A       :       Dict							=						processor.post_process_masks(_UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase					)
       self.assertEqual(masks[0].shape    ,   (1, 3, 1_764, 2_646)					)

       A       :       int							=						processor.post_process_masks(
           _UpperCAmelCase    ,   torch.tensor(_UpperCAmelCase					)    ,   torch.tensor(_UpperCAmelCase					)					)
       self.assertEqual(masks[0].shape    ,   (1, 3, 1_764, 2_646)					)

       # should also work with np
       A       :       Optional[Any]							=						[np.ones((1, 3, 5, 5)					)]
       A       :       Any							=						processor.post_process_masks(_UpperCAmelCase    ,   np.array(_UpperCAmelCase					)    ,   np.array(_UpperCAmelCase					)					)

       self.assertEqual(masks[0].shape    ,   (1, 3, 1_764, 2_646)					)

       A       :       Dict							=						[[1, 0], [0, 1]]
       with self.assertRaises(_UpperCAmelCase					):
           A       :       Optional[Any]							=						processor.post_process_masks(_UpperCAmelCase    ,   np.array(_UpperCAmelCase					)    ,   np.array(_UpperCAmelCase					)					)







@require_vision
@require_tf
class   _lowercase						(							unittest.TestCase				):


   def 					snake_case				( self					):
       A       :       List[Any]							=						tempfile.mkdtemp()
       A       :       str							=						SamImageProcessor()
       A       :       Optional[Any]							=						SamProcessor(_UpperCAmelCase					)
       processor.save_pretrained(self.tmpdirname					)


   def 					snake_case				( self    ,   **_UpperCAmelCase					):
       return AutoProcessor.from_pretrained(self.tmpdirname    ,   **_UpperCAmelCase					).image_processor


   def 					snake_case				( self					):
       shutil.rmtree(self.tmpdirname					)


   def 					snake_case				( self					):
       A       :       int							=						[np.random.randint(255    ,   size=(3, 30, 400)    ,   dtype=np.uinta					)]

       A       :       Union[str, Any]							=						[Image.fromarray(np.moveaxis(_UpperCAmelCase    ,   0    ,   -1					)					) for x in image_inputs]

       return image_inputs


   def 					snake_case				( self					):
       A       :       Dict							=						SamProcessor(image_processor=self.get_image_processor()					)
       processor.save_pretrained(self.tmpdirname					)

       A       :       Dict							=						self.get_image_processor(do_normalize=_UpperCAmelCase    ,   padding_value=1.0					)

       A       :       List[str]							=						SamProcessor.from_pretrained(self.tmpdirname    ,   do_normalize=_UpperCAmelCase    ,   padding_value=1.0					)

       self.assertEqual(processor.image_processor.to_json_string()    ,   image_processor_add_kwargs.to_json_string()					)
       self.assertIsInstance(processor.image_processor    ,   _UpperCAmelCase					)


   def 					snake_case				( self					):
       A       :       Any							=						self.get_image_processor()

       A       :       str							=						SamProcessor(image_processor=_UpperCAmelCase					)

       A       :       Any							=						self.prepare_image_inputs()

       A       :       Optional[int]							=						image_processor(_UpperCAmelCase    ,   return_tensors='''np'''					)
       A       :       Tuple							=						processor(images=_UpperCAmelCase    ,   return_tensors='''np'''					)

       input_feat_extract.pop('''original_sizes'''					)  # pop original_sizes as it is popped in the processor
       input_feat_extract.pop('''reshaped_input_sizes'''					)  # pop reshaped_input_sizes as it is popped in the processor

       for key in input_feat_extract.keys():
           self.assertAlmostEqual(input_feat_extract[key].sum()    ,   input_processor[key].sum()    ,   delta=1E-2					)


   @require_tf
   def 					snake_case				( self					):
       A       :       Any							=						self.get_image_processor()

       A       :       Any							=						SamProcessor(image_processor=_UpperCAmelCase					)
       A       :       str							=						[tf.ones((1, 3, 5, 5)					)]

       A       :       Dict							=						[[1_764, 2_646]]

       A       :       str							=						[[683, 1_024]]
       A       :       Union[str, Any]							=						processor.post_process_masks(_UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   return_tensors='''tf'''					)
       self.assertEqual(masks[0].shape    ,   (1, 3, 1_764, 2_646)					)

       A       :       Optional[Any]							=						processor.post_process_masks(
           _UpperCAmelCase    ,   tf.convert_to_tensor(_UpperCAmelCase					)    ,   tf.convert_to_tensor(_UpperCAmelCase					)    ,   return_tensors='''tf'''    ,   )
       self.assertEqual(masks[0].shape    ,   (1, 3, 1_764, 2_646)					)

       # should also work with np
       A       :       int							=						[np.ones((1, 3, 5, 5)					)]
       A       :       Union[str, Any]							=						processor.post_process_masks(
           _UpperCAmelCase    ,   np.array(_UpperCAmelCase					)    ,   np.array(_UpperCAmelCase					)    ,   return_tensors='''tf'''					)

       self.assertEqual(masks[0].shape    ,   (1, 3, 1_764, 2_646)					)

       A       :       Optional[int]							=						[[1, 0], [0, 1]]
       with self.assertRaises(tf.errors.InvalidArgumentError					):
           A       :       List[str]							=						processor.post_process_masks(
               _UpperCAmelCase    ,   np.array(_UpperCAmelCase					)    ,   np.array(_UpperCAmelCase					)    ,   return_tensors='''tf'''					)







@require_vision
@require_torchvision
class   _lowercase						(							unittest.TestCase				):


   def 					snake_case				( self					):
       A       :       Tuple							=						tempfile.mkdtemp()
       A       :       Optional[Any]							=						SamImageProcessor()
       A       :       Optional[int]							=						SamProcessor(_UpperCAmelCase					)
       processor.save_pretrained(self.tmpdirname					)


   def 					snake_case				( self    ,   **_UpperCAmelCase					):
       return AutoProcessor.from_pretrained(self.tmpdirname    ,   **_UpperCAmelCase					).image_processor


   def 					snake_case				( self					):
       shutil.rmtree(self.tmpdirname					)


   def 					snake_case				( self					):
       A       :       Optional[Any]							=						[np.random.randint(255    ,   size=(3, 30, 400)    ,   dtype=np.uinta					)]

       A       :       int							=						[Image.fromarray(np.moveaxis(_UpperCAmelCase    ,   0    ,   -1					)					) for x in image_inputs]

       return image_inputs


   @is_pt_tf_cross_test
   def 					snake_case				( self					):
       A       :       str							=						self.get_image_processor()

       A       :       Optional[Any]							=						SamProcessor(image_processor=_UpperCAmelCase					)
       A       :       List[str]							=						np.random.randint(0    ,   2    ,   size=(1, 3, 5, 5)					).astype(np.floataa					)
       A       :       List[str]							=						[tf.convert_to_tensor(_UpperCAmelCase					)]
       A       :       Union[str, Any]							=						[torch.tensor(_UpperCAmelCase					)]

       A       :       Optional[int]							=						[[1_764, 2_646]]

       A       :       List[str]							=						[[683, 1_024]]
       A       :       Optional[Any]							=						processor.post_process_masks(
           _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   return_tensors='''tf'''					)
       A       :       str							=						processor.post_process_masks(
           _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   return_tensors='''pt'''					)

       self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()					)					)


   @is_pt_tf_cross_test
   def 					snake_case				( self					):
       A       :       int							=						self.get_image_processor()

       A       :       Dict							=						SamProcessor(image_processor=_UpperCAmelCase					)

       A       :       Optional[int]							=						self.prepare_image_inputs()

       A       :       List[Any]							=						image_processor(_UpperCAmelCase    ,   return_tensors='''pt'''					)['''pixel_values'''].numpy()
       A       :       List[str]							=						processor(images=_UpperCAmelCase    ,   return_tensors='''pt'''					)['''pixel_values'''].numpy()

       A       :       Optional[Any]							=						image_processor(_UpperCAmelCase    ,   return_tensors='''tf'''					)['''pixel_values'''].numpy()
       A       :       List[str]							=						processor(images=_UpperCAmelCase    ,   return_tensors='''tf'''					)['''pixel_values'''].numpy()

       self.assertTrue(np.allclose(_UpperCAmelCase    ,   _UpperCAmelCase					)					)
       self.assertTrue(np.allclose(_UpperCAmelCase    ,   _UpperCAmelCase					)					)
       self.assertTrue(np.allclose(_UpperCAmelCase    ,   _UpperCAmelCase					)					)







'''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 							_lowerCamelCase(  UpperCamelCase__    : Optional[int]		)		->  List[str]:
    return EnvironmentCommand()
def 							_lowerCamelCase(  UpperCamelCase__    : List[Any]		)		->  Tuple:
    return EnvironmentCommand(args.accelerate_config_file		)





class   _lowercase						(							a				):


   @staticmethod
   def 					snake_case				( _UpperCAmelCase					):
       A       :       Optional[Any]							=						parser.add_parser('''env'''					)
       download_parser.set_defaults(func=_UpperCAmelCase					)
       download_parser.add_argument(
           '''--accelerate-config_file'''    ,   default=_UpperCAmelCase    ,   help='''The accelerate config file to use for the default values in the launching script.'''    ,   )
       download_parser.set_defaults(func=_UpperCAmelCase					)


   def __init__( self    ,   _UpperCAmelCase    ,   *_UpperCAmelCase					):
       A       :       Any							=						accelerate_config_file


   def 					snake_case				( self					):
       A       :       Any							=						'''not installed'''
       if is_safetensors_available():
           import safetensors

           A       :       Dict							=						safetensors.__version__
       elif importlib.util.find_spec('''safetensors'''					) is not None:
           import safetensors

           A       :       int							=						f'''{safetensors.__version__} but is ignored because of PyTorch version too old.'''

       A       :       Tuple							=						'''not installed'''
       A       :       Tuple							=						'''not found'''
       if is_accelerate_available():
           import accelerate
           from accelerate.commands.config import default_config_file, load_config_from_file

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

           A       :       Tuple							=						(
               '''\n'''.join([f'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]					)
               if isinstance(_UpperCAmelCase    ,   _UpperCAmelCase					)
               else f'''\t{accelerate_config}'''
           )

       A       :       str							=						'''not installed'''
       A       :       Optional[Any]							=						'''NA'''
       if is_torch_available():
           import torch

           A       :       Optional[int]							=						torch.__version__
           A       :       List[Any]							=						torch.cuda.is_available()

       A       :       Dict							=						'''not installed'''
       A       :       Any							=						'''NA'''
       if is_tf_available():
           import tensorflow as tf

           A       :       Optional[int]							=						tf.__version__
           try:
               # deprecated in v2.1
               A       :       int							=						tf.test.is_gpu_available()
           except AttributeError:
               # returns list of devices, convert to bool
               A       :       Optional[int]							=						bool(tf.config.list_physical_devices('''GPU'''					)					)

       A       :       str							=						'''not installed'''
       A       :       Dict							=						'''not installed'''
       A       :       int							=						'''not installed'''
       A       :       Tuple							=						'''NA'''
       if is_flax_available():
           import flax
           import jax
           import jaxlib

           A       :       Any							=						flax.__version__
           A       :       Tuple							=						jax.__version__
           A       :       int							=						jaxlib.__version__
           A       :       List[Any]							=						jax.lib.xla_bridge.get_backend().platform

       A       :       Union[str, Any]							=						{
           '''`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(_UpperCAmelCase					)					)

       return info


   @staticmethod
   def 					snake_case				( _UpperCAmelCase					):
       return "\n".join([f'''- {prop}: {val}''' for prop, val in d.items()]					) + "\n"
