






"""simple docstring"""


import random
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, prepare_image_inputs


if is_torch_available():
   import torch

if is_vision_available():
   import PIL

   from transformers import FlavaImageProcessor
   from transformers.image_utils import PILImageResampling
   from transformers.models.flava.image_processing_flava import (
       FLAVA_CODEBOOK_MEAN,
       FLAVA_CODEBOOK_STD,
       FLAVA_IMAGE_MEAN,
       FLAVA_IMAGE_STD,
   )
else:
   _UpperCamelCase							:       Tuple       					=		None






class 		snake_case    (    unittest.TestCase			):





    def __init__(				self      :   Dict							,						A      :   Tuple							,						A      :   str=7							,						A      :   Dict=3							,						A      :   Dict=3_0							,						A      :   Optional[Any]=4_0_0							,						A      :   Dict=True							,						A      :   str=None							,						A      :   List[Any]=True							,						A      :   Union[str, Any]=None							,						A      :   Union[str, Any]=None							,						A      :   Any=True							,						A      :   List[str]=1 / 2_5_5							,						A      :   Tuple=True							,						A      :   Union[str, Any]=FLAVA_IMAGE_MEAN							,						A      :   str=FLAVA_IMAGE_STD							,						A      :   List[Any]=1_4							,						A      :   List[str]=7_5							,						A      :   Optional[int]=None							,						A      :   List[Any]=1_6							,						A      :   Tuple=0.3							,						A      :   str=None							,						A      :   Dict=True							,						A      :   List[Any]=None							,						A      :   int=None							,						A      :   Optional[int]=True							,						A      :   Optional[Any]=None							,						A      :   Dict=True							,						A      :   List[str]=True							,						A      :   Union[str, Any]=FLAVA_CODEBOOK_MEAN							,						A      :   List[Any]=FLAVA_CODEBOOK_STD							,						):


      '''simple docstring'''




      a	:     Tuple							=  size if size is not None else {'height': 2_2_4, 'width': 2_2_4}
      a	:     List[Any]							=  crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
      a	:     Optional[int]							=  codebook_size if codebook_size is not None else {'height': 1_1_2, 'width': 1_1_2}
      a	:     Optional[int]							=  codebook_crop_size if codebook_crop_size is not None else {'height': 1_1_2, 'width': 1_1_2}

      a	:     Union[str, Any]							=  parent
      a	:     Union[str, Any]							=  batch_size
      a	:     Optional[int]							=  num_channels
      a	:     int							=  do_resize
      a	:     int							=  do_rescale
      a	:     Dict							=  rescale_factor
      a	:     Tuple							=  min_resolution
      a	:     Optional[Any]							=  max_resolution
      a	:     Optional[Any]							=  size
      a	:     Optional[Any]							=  resample if resample is not None else PILImageResampling.BICUBIC
      a	:     Dict							=  do_normalize
      a	:     Tuple							=  image_mean
      a	:     Tuple							=  image_std
      a	:     Tuple							=  do_center_crop
      a	:     List[str]							=  crop_size

      a	:     Dict							=  input_size_patches
      a	:     Optional[Any]							=  total_mask_patches
      a	:     Optional[int]							=  mask_group_max_patches
      a	:     Any							=  mask_group_min_patches
      a	:     str							=  mask_group_min_aspect_ratio
      a	:     int							=  mask_group_max_aspect_ratio

      a	:     str							=  codebook_do_resize
      a	:     int							=  codebook_size
      a	:     Optional[Any]							=  codebook_resample if codebook_resample is not None else PILImageResampling.LANCZOS
      a	:     str							=  codebook_do_center_crop
      a	:     List[str]							=  codebook_crop_size
      a	:     Optional[int]							=  codebook_do_map_pixels
      a	:     Dict							=  codebook_do_normalize
      a	:     Optional[int]							=  codebook_image_mean
      a	:     Union[str, Any]							=  codebook_image_std





    def 							lowerCamelCase__ (				self      :   List[Any]     ):


      '''simple docstring'''




      return {
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_normalize": self.do_normalize,
          "do_resize": self.do_resize,
          "size": self.size,
          "resample": self.resample,
          "do_rescale": self.do_rescale,
          "rescale_factor": self.rescale_factor,
          "do_center_crop": self.do_center_crop,
          "crop_size": self.crop_size,
          "input_size_patches": self.input_size_patches,
          "total_mask_patches": self.total_mask_patches,
          "mask_group_max_patches": self.mask_group_max_patches,
          "mask_group_min_patches": self.mask_group_min_patches,
          "mask_group_min_aspect_ratio": self.mask_group_min_aspect_ratio,
          "mask_group_max_aspect_ratio": self.mask_group_min_aspect_ratio,
          "codebook_do_resize": self.codebook_do_resize,
          "codebook_size": self.codebook_size,
          "codebook_resample": self.codebook_resample,
          "codebook_do_center_crop": self.codebook_do_center_crop,
          "codebook_crop_size": self.codebook_crop_size,
          "codebook_do_map_pixels": self.codebook_do_map_pixels,
          "codebook_do_normalize": self.codebook_do_normalize,
          "codebook_image_mean": self.codebook_image_mean,
          "codebook_image_std": self.codebook_image_std,
      }





    def 							lowerCamelCase__ (				self      :   Any     ):


      '''simple docstring'''




      return (self.size["height"], self.size["width"])





    def 							lowerCamelCase__ (				self      :   List[str]     ):


      '''simple docstring'''




      return (
          (self.input_size_patches, self.input_size_patches)
          if not isinstance(self.input_size_patches							,						A     )
          else self.input_size_patches
      )





    def 							lowerCamelCase__ (				self      :   str     ):


      '''simple docstring'''




      return (self.codebook_size["height"], self.codebook_size["width"])






@require_torch
@require_vision
class 		snake_case    (    UpperCAmelCase  ,					unittest.TestCase			):
    __magic_name__       	=	FlavaImageProcessor if is_vision_available() else None
    __magic_name__       	=	None





    def 							lowerCamelCase__ (				self      :   Optional[int]     ):


      '''simple docstring'''




      a	:     Tuple							=  FlavaImageProcessingTester(self     )





    @property
    def 							lowerCamelCase__ (				self      :   int     ):


      '''simple docstring'''




      return self.image_processor_tester.prepare_image_processor_dict()





    def 							lowerCamelCase__ (				self      :   Tuple     ):


      '''simple docstring'''




      a	:     str							=  self.image_processing_class(**self.image_processor_dict     )
      self.assertTrue(hasattr(A							,						'image_mean'     )     )
      self.assertTrue(hasattr(A							,						'image_std'     )     )
      self.assertTrue(hasattr(A							,						'do_normalize'     )     )
      self.assertTrue(hasattr(A							,						'do_resize'     )     )
      self.assertTrue(hasattr(A							,						'resample'     )     )
      self.assertTrue(hasattr(A							,						'crop_size'     )     )
      self.assertTrue(hasattr(A							,						'do_center_crop'     )     )
      self.assertTrue(hasattr(A							,						'do_rescale'     )     )
      self.assertTrue(hasattr(A							,						'rescale_factor'     )     )
      self.assertTrue(hasattr(A							,						'masking_generator'     )     )
      self.assertTrue(hasattr(A							,						'codebook_do_resize'     )     )
      self.assertTrue(hasattr(A							,						'codebook_size'     )     )
      self.assertTrue(hasattr(A							,						'codebook_resample'     )     )
      self.assertTrue(hasattr(A							,						'codebook_do_center_crop'     )     )
      self.assertTrue(hasattr(A							,						'codebook_crop_size'     )     )
      self.assertTrue(hasattr(A							,						'codebook_do_map_pixels'     )     )
      self.assertTrue(hasattr(A							,						'codebook_do_normalize'     )     )
      self.assertTrue(hasattr(A							,						'codebook_image_mean'     )     )
      self.assertTrue(hasattr(A							,						'codebook_image_std'     )     )





    def 							lowerCamelCase__ (				self      :   Optional[int]     ):


      '''simple docstring'''




      a	:     Optional[Any]							=  self.image_processing_class.from_dict(self.image_processor_dict     )
      self.assertEqual(image_processor.size							,						{'height': 2_2_4, 'width': 2_2_4}     )
      self.assertEqual(image_processor.crop_size							,						{'height': 2_2_4, 'width': 2_2_4}     )
      self.assertEqual(image_processor.codebook_size							,						{'height': 1_1_2, 'width': 1_1_2}     )
      self.assertEqual(image_processor.codebook_crop_size							,						{'height': 1_1_2, 'width': 1_1_2}     )

      a	:     int							=  self.image_processing_class.from_dict(
          self.image_processor_dict							,						size=4_2							,						crop_size=8_4							,						codebook_size=3_3							,						codebook_crop_size=6_6     )
      self.assertEqual(image_processor.size							,						{'height': 4_2, 'width': 4_2}     )
      self.assertEqual(image_processor.crop_size							,						{'height': 8_4, 'width': 8_4}     )
      self.assertEqual(image_processor.codebook_size							,						{'height': 3_3, 'width': 3_3}     )
      self.assertEqual(image_processor.codebook_crop_size							,						{'height': 6_6, 'width': 6_6}     )





    def 							lowerCamelCase__ (				self      :   List[Any]     ):


      '''simple docstring'''




      pass





    def 							lowerCamelCase__ (				self      :   Union[str, Any]     ):


      '''simple docstring'''




      a	:     int							=  self.image_processing_class(**self.image_processor_dict     )
      # create random PIL images
      a	:     List[str]							=  prepare_image_inputs(self.image_processor_tester							,						equal_resolution=A     )
      for image in image_inputs:
        self.assertIsInstance(A							,						PIL.Image.Image     )

      # Test not batched input
      a	:     Optional[Any]							=  image_processing(image_inputs[0]							,						return_tensors='pt'     )

      # Test no bool masked pos
      self.assertFalse('bool_masked_pos' in encoded_images     )

      a,	a	:     Any							=  self.image_processor_tester.get_expected_image_size()

      self.assertEqual(
          encoded_images.pixel_values.shape							,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)							,						)

      # Test batched
      a	:     Optional[Any]							=  image_processing(A							,						return_tensors='pt'     )
      a,	a	:     Dict							=  self.image_processor_tester.get_expected_image_size()

      # Test no bool masked pos
      self.assertFalse('bool_masked_pos' in encoded_images     )

      self.assertEqual(
          encoded_images.pixel_values.shape							,						(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )							,						)





    def 							lowerCamelCase__ (				self      :   List[str]							,						A      :   Optional[int]							,						A      :   Union[str, Any]     ):


      '''simple docstring'''




      a	:     List[str]							=  self.image_processing_class(**self.image_processor_dict     )
      # create random tensors
      a	:     List[Any]							=  prepare_image_inputs(self.image_processor_tester							,						equal_resolution=A							,						**A     )
      for image in image_inputs:
        self.assertIsInstance(A							,						A     )

      # Test not batched input
      a	:     Tuple							=  image_processing(image_inputs[0]							,						return_tensors='pt'     )

      a,	a	:     List[str]							=  self.image_processor_tester.get_expected_image_size()
      self.assertEqual(
          encoded_images.pixel_values.shape							,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)							,						)

      a	:     Union[str, Any]							=  image_processing(A							,						return_image_mask=A							,						return_tensors='pt'     )

      a,	a	:     List[str]							=  self.image_processor_tester.get_expected_image_size()
      self.assertEqual(
          encoded_images.pixel_values.shape							,						(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )							,						)

      a,	a	:     Optional[int]							=  self.image_processor_tester.get_expected_mask_size()
      self.assertEqual(
          encoded_images.bool_masked_pos.shape							,						(
              self.image_processor_tester.batch_size,
              expected_height,
              expected_width,
          )							,						)

      # Test batched
      a	:     Optional[Any]							=  image_processing(A							,						return_tensors='pt'     ).pixel_values

      a,	a	:     Union[str, Any]							=  self.image_processor_tester.get_expected_image_size()
      self.assertEqual(
          encoded_images.shape							,						(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )							,						)

      # Test masking
      a	:     Optional[Any]							=  image_processing(A							,						return_image_mask=A							,						return_tensors='pt'     )

      a,	a	:     Any							=  self.image_processor_tester.get_expected_image_size()
      self.assertEqual(
          encoded_images.pixel_values.shape							,						(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )							,						)

      a,	a	:     Union[str, Any]							=  self.image_processor_tester.get_expected_mask_size()
      self.assertEqual(
          encoded_images.bool_masked_pos.shape							,						(
              self.image_processor_tester.batch_size,
              expected_height,
              expected_width,
          )							,						)





    def 							lowerCamelCase__ (				self      :   List[Any]     ):


      '''simple docstring'''




      self._test_call_framework(np.ndarray							,						prepare_kwargs={'numpify': True}     )





    def 							lowerCamelCase__ (				self      :   Optional[int]     ):


      '''simple docstring'''




      self._test_call_framework(torch.Tensor							,						prepare_kwargs={'torchify': True}     )





    def 							lowerCamelCase__ (				self      :   Any     ):


      '''simple docstring'''




      random.seed(1_2_3_4     )
      a	:     Optional[Any]							=  self.image_processing_class(**self.image_processor_dict     )
      a	:     Optional[int]							=  prepare_image_inputs(self.image_processor_tester							,						equal_resolution=A							,						torchify=A     )

      # Test not batched input
      a	:     Dict							=  image_processing(image_inputs[0]							,						return_image_mask=A							,						return_tensors='pt'     )
      self.assertEqual(encoded_images.bool_masked_pos.sum().item()							,						7_5     )





    def 							lowerCamelCase__ (				self      :   Dict     ):


      '''simple docstring'''




      a	:     Tuple							=  self.image_processing_class(**self.image_processor_dict     )
      # create random PIL images
      a	:     Optional[Any]							=  prepare_image_inputs(self.image_processor_tester							,						equal_resolution=A     )
      for image in image_inputs:
        self.assertIsInstance(A							,						PIL.Image.Image     )

      # Test not batched input
      a	:     Tuple							=  image_processing(image_inputs[0]							,						return_codebook_pixels=A							,						return_tensors='pt'     )
      a,	a	:     Optional[Any]							=  self.image_processor_tester.get_expected_codebook_image_size()
      self.assertEqual(
          encoded_images.codebook_pixel_values.shape							,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)							,						)

      # Test batched
      a	:     Dict							=  image_processing(A							,						return_codebook_pixels=A							,						return_tensors='pt'     )
      a,	a	:     Optional[int]							=  self.image_processor_tester.get_expected_codebook_image_size()
      self.assertEqual(
          encoded_images.codebook_pixel_values.shape							,						(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )							,						)












"""simple docstring"""


# Copyright 2022 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

from .config_args import default_config_file, load_config_from_file
from .config_utils import SubcommandHelpFormatter


_UpperCamelCase							:       int       					=		'Update an existing config file with the latest defaults while maintaining the old configuration.'




def      snake_case    (A_ :str ):







  '''simple docstring'''

  a	:     int							=  args.config_file
  if config_file is None and Path(A_ ).exists():
    a	:     List[Any]							=  default_config_file
  elif not Path(A_ ).exists():
    raise ValueError(f'''The passed config file located at {config_file} doesn\'t exist.''' )
  a	:     Dict							=  load_config_from_file(A_ )

  if config_file.endswith('.json' ):
    config.to_json_file(A_ )
  else:
    config.to_yaml_file(A_ )
  return config_file




def      snake_case    (A_ :List[str]      ,     A_ :Union[str, Any] ):







  '''simple docstring'''

  a	:     int							=  parser.add_parser('update'      ,     parents=A_      ,     help=A_      ,     formatter_class=A_ )
  parser.add_argument(
      '--config_file'      ,     default=A_      ,     help=(
          'The path to the config file to update. 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\'.'
      )      ,     )

  parser.set_defaults(func=A_ )
  return parser






def      snake_case    (A_ :List[str] ):







  '''simple docstring'''

  a	:     List[str]							=  update_config(A_ )
  print(f'''Sucessfully updated the configuration file at {config_file}.''' )




