






"""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 TvltImageProcessor




def      snake_case    (A_ :List[str]      ,     A_ :List[str]=1_0      ,     A_ :Tuple=1_0      ,     A_ :Optional[Any]=False      ,     A_ :int=False ):







  '''simple docstring'''

  a	:     Union[str, Any]							=  []
  for i in range(image_processor_tester.num_frames ):
    video.append(np.random.randint(2_5_5      ,     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
    a	:     int							=  [Image.fromarray(np.moveaxis(A_      ,     0      ,     -1 ) ) for frame in video]

  if torchify:
    a	:     Any							=  [torch.from_numpy(A_ ) for frame in video]

  return video




def      snake_case    (A_ :int      ,     A_ :List[str]=False      ,     A_ :int=False      ,     A_ :int=False ):







  '''simple docstring'''

  assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

  a	:     List[str]							=  []
  for i in range(image_processor_tester.batch_size ):
    if equal_resolution:
      a	:     int							=  image_processor_tester.max_resolution
    else:
      a,	a	:     List[Any]							=  np.random.choice(
          np.arange(image_processor_tester.min_resolution      ,     image_processor_tester.max_resolution )      ,     2 )
      a	:     Optional[int]							=  prepare_video(
          image_processor_tester=A_      ,     width=A_      ,     height=A_      ,     numpify=A_      ,     torchify=A_      ,     )
    video_inputs.append(A_ )

  return video_inputs






class 		snake_case    (    unittest.TestCase			):





    def __init__(				self      :   Dict							,						A      :   int							,						A      :   Union[str, Any]=7							,						A      :   Any=3							,						A      :   Dict=4							,						A      :   Union[str, Any]=1_8							,						A      :   Tuple=3_0							,						A      :   List[str]=4_0_0							,						A      :   Dict=True							,						A      :   str=None							,						A      :   Dict=True							,						A      :   str=[0.5, 0.5, 0.5]							,						A      :   Any=[0.5, 0.5, 0.5]							,						A      :   Union[str, Any]=True							,						A      :   List[Any]=None							,						):


      '''simple docstring'''




      a	:     Optional[int]							=  size if size is not None else {'shortest_edge': 1_8}
      a	:     List[str]							=  crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}

      a	:     List[str]							=  parent
      a	:     Union[str, Any]							=  batch_size
      a	:     str							=  num_channels
      a	:     Optional[int]							=  num_frames
      a	:     Union[str, Any]							=  image_size
      a	:     Tuple							=  min_resolution
      a	:     Tuple							=  max_resolution
      a	:     Tuple							=  do_resize
      a	:     List[Any]							=  size
      a	:     str							=  do_normalize
      a	:     int							=  image_mean
      a	:     List[Any]							=  image_std
      a	:     str							=  do_center_crop
      a	:     Dict							=  crop_size





    def 							lowerCamelCase__ (				self      :   str     ):


      '''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,
          "do_center_crop": self.do_center_crop,
          "crop_size": self.crop_size,
      }






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





    def 							lowerCamelCase__ (				self      :   Tuple     ):


      '''simple docstring'''




      a	:     Dict							=  TvltImageProcessorTester(self     )





    @property
    def 							lowerCamelCase__ (				self      :   List[Any]     ):


      '''simple docstring'''




      return self.image_processor_tester.prepare_image_processor_dict()





    def 							lowerCamelCase__ (				self      :   Dict     ):


      '''simple docstring'''




      a	:     Union[str, Any]							=  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							,						'do_center_crop'     )     )
      self.assertTrue(hasattr(A							,						'size'     )     )





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


      '''simple docstring'''




      a	:     Optional[Any]							=  self.image_processing_class(**self.image_processor_dict     )
      # create random PIL videos
      a	:     Any							=  prepare_video_inputs(self.image_processor_tester							,						equal_resolution=A     )
      for video in video_inputs:
        self.assertIsInstance(A							,						A     )
        self.assertIsInstance(video[0]							,						Image.Image     )

      # Test not batched input
      a	:     int							=  image_processor(video_inputs[0]							,						return_tensors='pt'     ).pixel_values
      self.assertEqual(
          encoded_videos.shape							,						(
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )							,						)

      # Test batched
      a	:     Dict							=  image_processor(A							,						return_tensors='pt'     ).pixel_values
      self.assertEqual(
          encoded_videos.shape							,						(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              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]     ):


      '''simple docstring'''




      a	:     int							=  self.image_processing_class(**self.image_processor_dict     )
      # create random numpy tensors
      a	:     Any							=  prepare_video_inputs(self.image_processor_tester							,						equal_resolution=A							,						numpify=A     )
      for video in video_inputs:
        self.assertIsInstance(A							,						A     )
        self.assertIsInstance(video[0]							,						np.ndarray     )

      # Test not batched input
      a	:     Tuple							=  image_processor(video_inputs[0]							,						return_tensors='pt'     ).pixel_values
      self.assertEqual(
          encoded_videos.shape							,						(
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )							,						)

      # Test batched
      a	:     Union[str, Any]							=  image_processor(A							,						return_tensors='pt'     ).pixel_values
      self.assertEqual(
          encoded_videos.shape							,						(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )							,						)





    def 							lowerCamelCase__ (				self      :   List[str]     ):


      '''simple docstring'''




      a	:     Optional[int]							=  self.image_processing_class(**self.image_processor_dict     )
      # create random PyTorch tensors
      a	:     Tuple							=  prepare_video_inputs(self.image_processor_tester							,						equal_resolution=A							,						torchify=A     )
      for video in video_inputs:
        self.assertIsInstance(A							,						A     )
        self.assertIsInstance(video[0]							,						torch.Tensor     )

      # Test not batched input
      a	:     str							=  image_processor(video_inputs[0]							,						return_tensors='pt'     ).pixel_values
      self.assertEqual(
          encoded_videos.shape							,						(
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )							,						)

      # Test batched
      a	:     Optional[int]							=  image_processor(A							,						return_tensors='pt'     ).pixel_values
      self.assertEqual(
          encoded_videos.shape							,						(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['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}.''' )




