




"""simple docstring"""

import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import ChineseCLIPImageProcessor





class     lowercase_	(					unittest.TestCase							):



 '''simple docstring'''

 def __init__(			self	:	Dict   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	Optional[int]=7   ,							_UpperCAmelCase	:	int=3   ,							_UpperCAmelCase	:	Optional[Any]=18   ,							_UpperCAmelCase	:	Dict=30   ,							_UpperCAmelCase	:	List[str]=400   ,							_UpperCAmelCase	:	Any=True   ,							_UpperCAmelCase	:	Optional[Any]=None   ,							_UpperCAmelCase	:	Union[str, Any]=True   ,							_UpperCAmelCase	:	Any=None   ,							_UpperCAmelCase	:	List[str]=True   ,							_UpperCAmelCase	:	Any=[0.4814_5466, 0.457_8275, 0.4082_1073]   ,							_UpperCAmelCase	:	int=[0.2686_2954, 0.2613_0258, 0.2757_7711]   ,							_UpperCAmelCase	:	Union[str, Any]=True   ,							):
       _A        =       size if size is not None else {'height': 224, 'width': 224}
       _A        =       crop_size if crop_size is not None else {'height': 18, 'width': 18}
       _A        =       parent
       _A        =       batch_size
       _A        =       num_channels
       _A        =       image_size
       _A        =       min_resolution
       _A        =       max_resolution
       _A        =       do_resize
       _A        =       size
       _A        =       do_center_crop
       _A        =       crop_size
       _A        =       do_normalize
       _A        =       image_mean
       _A        =       image_std
       _A        =       do_convert_rgb

 def       lowerCAmelCase_							(			self	:	Optional[Any]		):
       return {
           "do_resize": self.do_resize,
           "size": self.size,
           "do_center_crop": self.do_center_crop,
           "crop_size": self.crop_size,
           "do_normalize": self.do_normalize,
           "image_mean": self.image_mean,
           "image_std": self.image_std,
           "do_convert_rgb": self.do_convert_rgb,
       }



 def       lowerCAmelCase_							(			self	:	Union[str, Any]   ,							_UpperCAmelCase	:	List[str]=False   ,							_UpperCAmelCase	:	Optional[Any]=False   ,							_UpperCAmelCase	:	List[Any]=False		):
       assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

       if equal_resolution:
             _A        =       []
             for i in range(self.batch_size		):
                   image_inputs.append(
                       np.random.randint(
                           255   ,							size=(self.num_channels, self.max_resolution, self.max_resolution)   ,							dtype=np.uinta		)		)
       else:
             _A        =       []
             for i in range(self.batch_size		):
                   _A       ,   _A        =       np.random.choice(np.arange(self.min_resolution   ,							self.max_resolution		)   ,							2		)
                   image_inputs.append(np.random.randint(255   ,							size=(self.num_channels, width, height)   ,							dtype=np.uinta		)		)

       if not numpify and not torchify:
             # PIL expects the channel dimension as last dimension
             _A        =       [Image.fromarray(np.moveaxis(_UpperCAmelCase   ,							0   ,							-1		)		) for x in image_inputs]

       if torchify:
             _A        =       [torch.from_numpy(_UpperCAmelCase		) for x in image_inputs]

       return image_inputs





@require_torch
@require_vision
class     lowercase_	(					__lowerCAmelCase      ,     unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					int				  =     ChineseCLIPImageProcessor if is_vision_available() else None

 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       ChineseCLIPImageProcessingTester(self   ,							do_center_crop=_UpperCAmelCase		)

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

 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       self.image_processing_class(**self.image_processor_dict		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'do_resize'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'size'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'do_center_crop'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'center_crop'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'do_normalize'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'image_mean'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'image_std'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'do_convert_rgb'		)		)

 def       lowerCAmelCase_							(			self	:	Optional[Any]		):
       _A        =       self.image_processing_class.from_dict(self.image_processor_dict		)
       self.assertEqual(image_processor.size   ,							{'height': 224, 'width': 224}		)
       self.assertEqual(image_processor.crop_size   ,							{'height': 18, 'width': 18}		)

       _A        =       self.image_processing_class.from_dict(self.image_processor_dict   ,							size=42   ,							crop_size=84		)
       self.assertEqual(image_processor.size   ,							{'shortest_edge': 42}		)
       self.assertEqual(image_processor.crop_size   ,							{'height': 84, 'width': 84}		)

 def       lowerCAmelCase_							(			self	:	str		):
       pass

 def       lowerCAmelCase_							(			self	:	Union[str, Any]		):
       # Initialize image_processing
       _A        =       self.image_processing_class(**self.image_processor_dict		)
       # create random PIL images
       _A        =       self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase		)
       for image in image_inputs:
             self.assertIsInstance(_UpperCAmelCase   ,							Image.Image		)

       # Test not batched input
       _A        =       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.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )   ,							)

       # Test batched
       _A        =       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.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )   ,							)

 def       lowerCAmelCase_							(			self	:	Dict		):
       # Initialize image_processing
       _A        =       self.image_processing_class(**self.image_processor_dict		)
       # create random numpy tensors
       _A        =       self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase   ,							numpify=_UpperCAmelCase		)
       for image in image_inputs:
             self.assertIsInstance(_UpperCAmelCase   ,							np.ndarray		)

       # Test not batched input
       _A        =       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.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )   ,							)

       # Test batched
       _A        =       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.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )   ,							)



 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       # Initialize image_processing
       _A        =       self.image_processing_class(**self.image_processor_dict		)
       # create random PyTorch tensors
       _A        =       self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase   ,							torchify=_UpperCAmelCase		)
       for image in image_inputs:
             self.assertIsInstance(_UpperCAmelCase   ,							torch.Tensor		)

       # Test not batched input
       _A        =       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.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )   ,							)

       # Test batched
       _A        =       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.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )   ,							)





@require_torch
@require_vision
class     lowercase_	(					__lowerCAmelCase      ,     unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					Any				  =     ChineseCLIPImageProcessor if is_vision_available() else None

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       _A        =       ChineseCLIPImageProcessingTester(self   ,							num_channels=4   ,							do_center_crop=_UpperCAmelCase		)
       _A        =       3

 @property
 def       lowerCAmelCase_							(			self	:	List[str]		):
       return self.image_processor_tester.prepare_image_processor_dict()

 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       self.image_processing_class(**self.image_processor_dict		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'do_resize'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'size'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'do_center_crop'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'center_crop'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'do_normalize'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'image_mean'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'image_std'		)		)
       self.assertTrue(hasattr(_UpperCAmelCase   ,							'do_convert_rgb'		)		)

 def       lowerCAmelCase_							(			self	:	str		):
       pass



 def       lowerCAmelCase_							(			self	:	Dict		):
       # Initialize image_processing
       _A        =       self.image_processing_class(**self.image_processor_dict		)
       # create random PIL images
       _A        =       self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase		)
       for image in image_inputs:
             self.assertIsInstance(_UpperCAmelCase   ,							Image.Image		)

       # Test not batched input
       _A        =       image_processing(image_inputs[0]   ,							return_tensors='pt'		).pixel_values
       self.assertEqual(
           encoded_images.shape   ,							(
               1,
               self.expected_encoded_image_num_channels,
               self.image_processor_tester.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )   ,							)

       # Test batched
       _A        =       image_processing(_UpperCAmelCase   ,							return_tensors='pt'		).pixel_values
       self.assertEqual(
           encoded_images.shape   ,							(
               self.image_processor_tester.batch_size,
               self.expected_encoded_image_num_channels,
               self.image_processor_tester.crop_size['height'],
               self.image_processor_tester.crop_size['width'],
           )   ,							)







"""simple docstring"""

import inspect
import os
import unittest
from pathlib import Path

import torch

import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command





class     lowercase_	(					unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					str				  =     inspect.getfile(accelerate.test_utils							)
 UpperCAmelCase   :					Optional[Any]				  =     os.path.sep.join(mod_file.split(os.path.sep							)[:-1] + ['''scripts''', '''test_cli.py''']							)

 UpperCAmelCase   :					List[Any]				  =     ['''accelerate''', '''launch''']
 UpperCAmelCase   :					Dict				  =     Path.home() / '''.cache/huggingface/accelerate'''
 UpperCAmelCase   :					Union[str, Any]				  =     '''default_config.yaml'''
 UpperCAmelCase   :					Union[str, Any]				  =     config_folder / config_file
 UpperCAmelCase   :					Union[str, Any]				  =     config_folder / '''_default_config.yaml'''

 UpperCAmelCase   :					List[Any]				  =     Path('''tests/test_configs'''							)

 @classmethod
 def       lowerCAmelCase_							(			cls	:	List[Any]		):
       if cls.config_path.is_file():
             cls.config_path.rename(cls.changed_path		)

 @classmethod
 def       lowerCAmelCase_							(			cls	:	Tuple		):
       if cls.changed_path.is_file():
             cls.changed_path.rename(cls.config_path		)

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       _A        =       self.base_cmd
       if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
             cmd += ["--multi_gpu"]
       execute_subprocess_async(cmd + [self.test_file_path]   ,							env=os.environ.copy()		)

 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       for config in sorted(self.test_config_path.glob('**/*.yaml'		)		):
             with self.subTest(config_file=_UpperCAmelCase		):
                   execute_subprocess_async(
                       self.base_cmd + ['--config_file', str(_UpperCAmelCase		), self.test_file_path]   ,							env=os.environ.copy()		)



 def       lowerCAmelCase_							(			self	:	Any		):
       execute_subprocess_async(['accelerate', 'test']   ,							env=os.environ.copy()		)





class     lowercase_	(					unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					Dict				  =     '''test-tpu'''
 UpperCAmelCase   :					Optional[int]				  =     '''us-central1-a'''
 UpperCAmelCase   :					List[str]				  =     '''ls'''
 UpperCAmelCase   :					str				  =     ['''accelerate''', '''tpu-config''']
 UpperCAmelCase   :					Optional[Any]				  =     '''cd /usr/share'''
 UpperCAmelCase   :					Optional[Any]				  =     '''tests/test_samples/test_command_file.sh'''
 UpperCAmelCase   :					str				  =     '''Running gcloud compute tpus tpu-vm ssh'''

 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       run_command(
           self.cmd
           + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug']   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	Dict		):
       _A        =       run_command(
           self.cmd
           + [
               '--config_file',
               'tests/test_configs/0_12_0.yaml',
               '--command',
               self.command,
               '--tpu_zone',
               self.tpu_zone,
               '--tpu_name',
               self.tpu_name,
               '--debug',
           ]   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       _A        =       run_command(
           self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug']   ,							return_stdout=_UpperCAmelCase		)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	str		):
       _A        =       run_command(
           self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug']   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	List[str]		):
       _A        =       run_command(
           self.cmd
           + [
               '--config_file',
               'tests/test_configs/latest.yaml',
               '--command',
               self.command,
               '--command',
               'echo "Hello World"',
               '--debug',
           ]   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	str		):
       _A        =       run_command(
           self.cmd
           + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug']   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       _A        =       run_command(
           self.cmd
           + [
               '--config_file',
               'tests/test_configs/0_12_0.yaml',
               '--command_file',
               self.command_file,
               '--tpu_zone',
               self.tpu_zone,
               '--tpu_name',
               self.tpu_name,
               '--debug',
           ]   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''   ,							_UpperCAmelCase   ,							)

 def       lowerCAmelCase_							(			self	:	int		):
       _A        =       run_command(
           self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug']   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all'''   ,							_UpperCAmelCase   ,							)



 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       _A        =       run_command(
           self.cmd
           + [
               '--config_file',
               'tests/test_configs/latest.yaml',
               '--install_accelerate',
               '--accelerate_version',
               '12.0.0',
               '--debug',
           ]   ,							return_stdout=_UpperCAmelCase   ,							)
       self.assertIn(
           F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all'''   ,							_UpperCAmelCase   ,							)

