code: 
  
  '''simple docstring'''
  
  
  
  
  
  import json
  import os
  import tempfile
  
  from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_vision
  from transformers.utils import is_torch_available, is_vision_available
  
  
  if is_torch_available():
         import numpy as np
         import torch
  
  if is_vision_available():
         from PIL import Image
  
  def 			snake_case__    (					SCREAMING_SNAKE_CASE_	:					Optional[Any]			,  SCREAMING_SNAKE_CASE_	:					Optional[int]=False			,  SCREAMING_SNAKE_CASE_	:					List[Any]=False			,  SCREAMING_SNAKE_CASE_	:					Dict=False    ):
  
  
  
       '''simple docstring'''
  
  
  
  
  
       assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
  
       lowercase__					:     Any   = []
       for i in range(image_processor_tester.batch_size    ):
            if equal_resolution:
                 lowercase__					:     Optional[Any]   = image_processor_tester.max_resolution
            else:
                 # To avoid getting image width/height 0
                 lowercase__					:     Union[str, Any]   = image_processor_tester.min_resolution
                 if getattr(SCREAMING_SNAKE_CASE_			,  'size_divisor'			,  SCREAMING_SNAKE_CASE_    ):
                      # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
                      lowercase__					:     Any   = max(image_processor_tester.size_divisor			,  SCREAMING_SNAKE_CASE_    )
                 lowercase__					:     Union[str, Any]   = np.random.choice(np.arange(SCREAMING_SNAKE_CASE_			,  image_processor_tester.max_resolution    )			,  2    )
            image_inputs.append(
                np.random.randint(255			,  size=(image_processor_tester.num_channels, width, height)			,  dtype=np.uinta    )    )
  
       if not numpify and not torchify:
            # PIL expects the channel dimension as last dimension
            lowercase__					:     Optional[int]   = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_			,  0			,  -1    )    ) for image in image_inputs]
  
       if torchify:
            lowercase__					:     str   = [torch.from_numpy(SCREAMING_SNAKE_CASE_    ) for image in image_inputs]
  
       return image_inputs
  
  def 			snake_case__    (					SCREAMING_SNAKE_CASE_	:					int			,  SCREAMING_SNAKE_CASE_	:					int=10			,  SCREAMING_SNAKE_CASE_	:					Optional[Any]=10			,  SCREAMING_SNAKE_CASE_	:					Union[str, Any]=False			,  SCREAMING_SNAKE_CASE_	:					Tuple=False    ):
  
  
  
       '''simple docstring'''
  
  
  
  
  
       lowercase__					:     Union[str, Any]   = []
       for i in range(image_processor_tester.num_frames    ):
            video.append(np.random.randint(255			,  size=(image_processor_tester.num_channels, width, height)			,  dtype=np.uinta    )    )
  
       if not numpify and not torchify:
            # PIL expects the channel dimension as last dimension
            lowercase__					:     Optional[int]   = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_			,  0			,  -1    )    ) for frame in video]
  
       if torchify:
            lowercase__					:     Optional[int]   = [torch.from_numpy(SCREAMING_SNAKE_CASE_    ) for frame in video]
  
       return video
  
  def 			snake_case__    (					SCREAMING_SNAKE_CASE_	:					Optional[int]			,  SCREAMING_SNAKE_CASE_	:					Dict=False			,  SCREAMING_SNAKE_CASE_	:					Tuple=False			,  SCREAMING_SNAKE_CASE_	:					str=False    ):
  
  
  
       '''simple docstring'''
  
  
  
  
  
       assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
  
       lowercase__					:     int   = []
       for i in range(image_processor_tester.batch_size    ):
            if equal_resolution:
                 lowercase__					:     int   = image_processor_tester.max_resolution
            else:
                 lowercase__					:     Union[str, Any]   = np.random.choice(
                     np.arange(image_processor_tester.min_resolution			,  image_processor_tester.max_resolution    )			,  2    )
                 lowercase__					:     Tuple   = prepare_video(
                     image_processor_tester=SCREAMING_SNAKE_CASE_			,  width=SCREAMING_SNAKE_CASE_			,  height=SCREAMING_SNAKE_CASE_			,  numpify=SCREAMING_SNAKE_CASE_			,  torchify=SCREAMING_SNAKE_CASE_			,  )
            video_inputs.append(SCREAMING_SNAKE_CASE_    )
  
       return video_inputs
  
  
  class    SCREAMING_SNAKE_CASE__      :
      __lowerCamelCase		: List[str]														=  None
  
  
  
  
  
      def    snake_case_       (   self):
           lowercase__					:     int   = self.image_processing_class(**self.image_processor_dict)
           lowercase__					:     List[str]   = json.loads(image_processor.to_json_string())
           for key, value in self.image_processor_dict.items():
                self.assertEqual(obj[key]		,     _A)
  
  
  
  
  
      def    snake_case_       (   self):
           lowercase__					:     str   = self.image_processing_class(**self.image_processor_dict)
  
           with tempfile.TemporaryDirectory() as tmpdirname:
                lowercase__					:     Optional[Any]   = os.path.join(_A		,     'image_processor.json')
                image_processor_first.to_json_file(_A)
                lowercase__					:     Union[str, Any]   = self.image_processing_class.from_json_file(_A)
  
           self.assertEqual(image_processor_second.to_dict()		,     image_processor_first.to_dict())
  
  
  
  
  
      def    snake_case_       (   self):
           lowercase__					:     Dict   = self.image_processing_class(**self.image_processor_dict)
  
           with tempfile.TemporaryDirectory() as tmpdirname:
                lowercase__					:     List[Any]   = image_processor_first.save_pretrained(_A)[0]
                check_json_file_has_correct_format(_A)
                lowercase__					:     Dict   = self.image_processing_class.from_pretrained(_A)
  
           self.assertEqual(image_processor_second.to_dict()		,     image_processor_first.to_dict())
  
  
  
  
  
      def    snake_case_       (   self):
           lowercase__					:     Optional[int]   = self.image_processing_class()
           self.assertIsNotNone(_A)
  
  
  
  
  
      @require_torch
      @require_vision
      def    snake_case_       (   self):
           if self.test_cast_dtype is not None:
                # Initialize image_processor
                lowercase__					:     Optional[Any]   = self.image_processing_class(**self.image_processor_dict)
  
                # create random PyTorch tensors
                lowercase__					:     str   = prepare_image_inputs(self.image_processor_tester		,     equal_resolution=_A		,     torchify=_A)
  
                lowercase__					:     Dict   = image_processor(_A		,     return_tensors='pt')
                # for layoutLM compatiblity
                self.assertEqual(encoding.pixel_values.device		,     torch.device('cpu'))
                self.assertEqual(encoding.pixel_values.dtype		,     torch.floataa)
  
                lowercase__					:     str   = image_processor(_A		,     return_tensors='pt').to(torch.floataa)
                self.assertEqual(encoding.pixel_values.device		,     torch.device('cpu'))
                self.assertEqual(encoding.pixel_values.dtype		,     torch.floataa)
  
                lowercase__					:     int   = image_processor(_A		,     return_tensors='pt').to('cpu'		,     torch.bfloataa)
                self.assertEqual(encoding.pixel_values.device		,     torch.device('cpu'))
                self.assertEqual(encoding.pixel_values.dtype		,     torch.bfloataa)
  
                with self.assertRaises(_A):
                     lowercase__					:     Any   = image_processor(_A		,     return_tensors='pt').to(torch.bfloataa		,     'cpu')
  
                # Try with text + image feature
                lowercase__					:     Union[str, Any]   = image_processor(_A		,     return_tensors='pt')
                encoding.update({'input_ids': torch.LongTensor([[1, 2, 3], [4, 5, 6]])})
                lowercase__					:     List[Any]   = encoding.to(torch.floataa)
  
                self.assertEqual(encoding.pixel_values.device		,     torch.device('cpu'))
                self.assertEqual(encoding.pixel_values.dtype		,     torch.floataa)
                self.assertEqual(encoding.input_ids.dtype		,     torch.long)
  
  
style_context: 
  
  # as due to their complexity multi-gpu tests could impact other tests, and to aid debug we have those in a separate module.
  
  import os
  import sys
  
  from transformers.testing_utils import TestCasePlus, execute_subprocess_async, get_gpu_count, require_torch_gpu, slow
  
  from .utils import load_json
  
  
  class    SCREAMING_SNAKE_CASE__      (__snake_case  ):
  
  
  
  
  
      @classmethod
      def    snake_case_       (   cls):
           return cls
  
  
  
  
  
      @slow
      @require_torch_gpu
      def    snake_case_       (   self):
           lowercase__					:     List[Any]   = self.get_auto_remove_tmp_dir()
           lowercase__					:     List[str]   = f"""
              --model_name Helsinki-NLP/opus-mt-en-ro
              --save_dir {output_dir}
              --data_dir {self.test_file_dir_str}/test_data/wmt_en_ro
              --num_beams 2
              --task translation
          """.split()
  
           # we want this test to run even if there is only one GPU, but if there are more we use them all
           lowercase__					:     int   = get_gpu_count()
           lowercase__					:     Tuple   = f"""
              -m torch.distributed.launch
              --nproc_per_node={n_gpu}
              {self.test_file_dir}/run_distributed_eval.py
          """.split()
           lowercase__					:     Optional[Any]   = [sys.executable] + distributed_args + args
           execute_subprocess_async(a		,     env=self.get_env())
  
           lowercase__					:     str   = os.path.join(a		,     'test_bleu.json')
           lowercase__					:     List[str]   = load_json(a)
           # print(metrics)
           self.assertGreaterEqual(metrics['bleu']		,     25)
  
  