





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 							lowerCAmelCase_				(    A_  ,A_=10  ,A_=10  ,A_=False  ,A_=False):
    UpperCamelCase__:					List[str]												=      []
    for i in range(image_processor_tester.num_frames):
        video.append(np.random.randint(2_55  ,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
        UpperCamelCase__:					List[Any]												=      [Image.fromarray(np.moveaxis(A_  ,0  ,-1)) for frame in video]

    if torchify:
        UpperCamelCase__:					List[str]												=      [torch.from_numpy(A_) for frame in video]

    return video



def 							lowerCAmelCase_				(    A_  ,A_=False  ,A_=False  ,A_=False):
    assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

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

    return video_inputs




class    _a  (  unittest.TestCase):

      """simple docstring"""


      def __init__(						self:	Tuple					,  __lowerCamelCase:	str					,  __lowerCamelCase:	Optional[int]=7					,  __lowerCamelCase:	Tuple=3					,  __lowerCamelCase:	List[str]=4					,  __lowerCamelCase:	Union[str, Any]=18					,  __lowerCamelCase:	Any=30					,  __lowerCamelCase:	Dict=400					,  __lowerCamelCase:	Dict=True					,  __lowerCamelCase:	List[str]=None					,  __lowerCamelCase:	Optional[Any]=True					,  __lowerCamelCase:	List[Any]=[0.5, 0.5, 0.5]					,  __lowerCamelCase:	List[str]=[0.5, 0.5, 0.5]					,  __lowerCamelCase:	Optional[Any]=True					,  __lowerCamelCase:	int=None					,  ):
          '''simple docstring'''


          UpperCamelCase__:					Union[str, Any]												=      size if size is not None else {'''shortest_edge''': 18}
          UpperCamelCase__:					Union[str, Any]												=      crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

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






      def 	UpperCAmelCase_   (						self:	List[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    _a  (  lowerCAmelCase__		,	unittest.TestCase):

      """simple docstring"""


      UpperCamelCase__       						=   TvltImageProcessor if is_vision_available() else None






      def 	UpperCAmelCase_   (						self:	Any			):
          '''simple docstring'''


          UpperCamelCase__:					List[Any]												=      TvltImageProcessorTester(self			)






      @property
      def 	UpperCAmelCase_   (						self:	List[Any]			):
          '''simple docstring'''


          return self.image_processor_tester.prepare_image_processor_dict()






      def 	UpperCAmelCase_   (						self:	List[str]			):
          '''simple docstring'''


          UpperCamelCase__:					List[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 	UpperCAmelCase_   (						self:	Dict			):
          '''simple docstring'''


          UpperCamelCase__:					int												=      self.image_processing_class(**self.image_processor_dict			)
          # create random PIL videos
          UpperCamelCase__:					Tuple												=      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
          UpperCamelCase__:					Optional[Any]												=      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
          UpperCamelCase__:					List[str]												=      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 	UpperCAmelCase_   (						self:	List[str]			):
          '''simple docstring'''


          UpperCamelCase__:					int												=      self.image_processing_class(**self.image_processor_dict			)
          # create random numpy tensors
          UpperCamelCase__:					List[str]												=      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
          UpperCamelCase__:					Optional[Any]												=      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
          UpperCamelCase__:					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 	UpperCAmelCase_   (						self:	Tuple			):
          '''simple docstring'''


          UpperCamelCase__:					List[Any]												=      self.image_processing_class(**self.image_processor_dict			)
          # create random PyTorch tensors
          UpperCamelCase__:					Dict												=      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
          UpperCamelCase__:					Dict												=      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
          UpperCamelCase__:					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"],
              )					,  )








# Copyright 2021 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.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


A__:  Union[str, Any]       					=					os.path.expanduser(
    os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
)
A__:  int       					=					os.path.join(hf_cache_home, '''accelerate''')
A__:  Dict       					=					os.path.join(cache_dir, '''default_config.yaml''')
A__:  Union[str, Any]       					=					os.path.join(cache_dir, '''default_config.yaml''')

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
   A__:  Tuple       					=					default_yaml_config_file
else:
   A__:  int       					=					default_json_config_file



def 							lowerCAmelCase_				(    A_):
    if config_file is not None:
        if not os.path.isfile(A_):
            raise FileNotFoundError(
                F"The passed configuration file `{config_file}` does not exist. "
                "Please pass an existing file to `accelerate launch`, or use the the default one "
                "created through `accelerate config` and run `accelerate launch` "
                "without the `--config_file` argument.")
    else:
        UpperCamelCase__:					Optional[int]												=      default_config_file
    with open(A_  ,"r"  ,encoding="utf-8") as f:
        if config_file.endswith(".json"):
            if (
                json.load(A_).get("compute_environment"  ,ComputeEnvironment.LOCAL_MACHINE)
                == ComputeEnvironment.LOCAL_MACHINE
            ):
                UpperCamelCase__:					Union[str, Any]												=      ClusterConfig
            else:
                UpperCamelCase__:					int												=      SageMakerConfig
            return config_class.from_json_file(json_file=A_)
        else:
            if (
                yaml.safe_load(A_).get("compute_environment"  ,ComputeEnvironment.LOCAL_MACHINE)
                == ComputeEnvironment.LOCAL_MACHINE
            ):
                UpperCamelCase__:					Union[str, Any]												=      ClusterConfig
            else:
                UpperCamelCase__:					int												=      SageMakerConfig
            return config_class.from_yaml_file(yaml_file=A_)




@dataclass
class    _a  :

      """simple docstring"""


      UpperCamelCase__       						=   42
      UpperCamelCase__       						=   42
      UpperCamelCase__       						=   42
      UpperCamelCase__       						=   42






      def 	UpperCAmelCase_   (						self:	Union[str, Any]			):
          '''simple docstring'''


          UpperCamelCase__:					Tuple												=      self.__dict__
          # For serialization, it's best to convert Enums to strings (or their underlying value type).
          for key, value in result.items():
              if isinstance(__lowerCamelCase					,  __lowerCamelCase			):
                  UpperCamelCase__:					str												=      value.value
              if isinstance(__lowerCamelCase					,  __lowerCamelCase			) and not bool(__lowerCamelCase			):
                  UpperCamelCase__:					Tuple												=      None
          UpperCamelCase__:					List[Any]												=      {k: v for k, v in result.items() if v is not None}
          return result






      @classmethod
      def 	UpperCAmelCase_   (						cls:	str					,  __lowerCamelCase:	Any=None			):
          '''simple docstring'''


          UpperCamelCase__:					List[str]												=      default_json_config_file if json_file is None else json_file
          with open(__lowerCamelCase					,  "r"					,  encoding="utf-8"			) as f:
              UpperCamelCase__:					str												=      json.load(__lowerCamelCase			)
          if "compute_environment" not in config_dict:
              UpperCamelCase__:					List[str]												=      ComputeEnvironment.LOCAL_MACHINE
          if "mixed_precision" not in config_dict:
              UpperCamelCase__:					Optional[Any]												=      "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
          if "fp16" in config_dict:  # Convert the config to the new format.
              del config_dict["fp16"]
          if "dynamo_backend" in config_dict:  # Convert the config to the new format.
              UpperCamelCase__:					int												=      config_dict.pop("dynamo_backend"			)
              UpperCamelCase__:					Dict												=      {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
          if "use_cpu" not in config_dict:
              UpperCamelCase__:					str												=      False
          return cls(**__lowerCamelCase			)






      def 	UpperCAmelCase_   (						self:	Tuple					,  __lowerCamelCase:	List[Any]			):
          '''simple docstring'''


          with open(__lowerCamelCase					,  "w"					,  encoding="utf-8"			) as f:
              UpperCamelCase__:					Any												=      json.dumps(self.to_dict()					,  indent=2					,  sort_keys=__lowerCamelCase			) + "\n"
              f.write(__lowerCamelCase			)






      @classmethod
      def 	UpperCAmelCase_   (						cls:	Tuple					,  __lowerCamelCase:	Tuple=None			):
          '''simple docstring'''


          UpperCamelCase__:					Optional[Any]												=      default_yaml_config_file if yaml_file is None else yaml_file
          with open(__lowerCamelCase					,  "r"					,  encoding="utf-8"			) as f:
              UpperCamelCase__:					Union[str, Any]												=      yaml.safe_load(__lowerCamelCase			)
          if "compute_environment" not in config_dict:
              UpperCamelCase__:					List[Any]												=      ComputeEnvironment.LOCAL_MACHINE

          if "mixed_precision" not in config_dict:
              UpperCamelCase__:					Optional[int]												=      "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
          if isinstance(config_dict["mixed_precision"]					,  __lowerCamelCase			) and not config_dict["mixed_precision"]:
              UpperCamelCase__:					List[Any]												=      "no"
          if "fp16" in config_dict:  # Convert the config to the new format.
              del config_dict["fp16"]
          if "dynamo_backend" in config_dict:  # Convert the config to the new format.
              UpperCamelCase__:					List[str]												=      config_dict.pop("dynamo_backend"			)
              UpperCamelCase__:					Optional[Any]												=      {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
          if "use_cpu" not in config_dict:
              UpperCamelCase__:					int												=      False
          return cls(**__lowerCamelCase			)






      def 	UpperCAmelCase_   (						self:	Optional[int]					,  __lowerCamelCase:	Tuple			):
          '''simple docstring'''


          with open(__lowerCamelCase					,  "w"					,  encoding="utf-8"			) as f:
              yaml.safe_dump(self.to_dict()					,  __lowerCamelCase			)






      def 	UpperCAmelCase_   (						self:	Dict			):
          '''simple docstring'''


          if isinstance(self.compute_environment					,  __lowerCamelCase			):
              UpperCamelCase__:					Optional[int]												=      ComputeEnvironment(self.compute_environment			)
          if isinstance(self.distributed_type					,  __lowerCamelCase			):
              if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                  UpperCamelCase__:					str												=      SageMakerDistributedType(self.distributed_type			)
              else:
                  UpperCamelCase__:					Optional[int]												=      DistributedType(self.distributed_type			)
          if self.dynamo_config is None:
              UpperCamelCase__:					List[Any]												=      {}




@dataclass
class    _a  (  UpperCamelCase__):

      """simple docstring"""


      UpperCamelCase__       						=   42
      UpperCamelCase__       						=   0
      UpperCamelCase__       						=   1
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   "static"
      UpperCamelCase__       						=   False
      UpperCamelCase__       						=   "main"

      # args for deepspeed_plugin
      UpperCamelCase__       						=   None
      # args for fsdp
      UpperCamelCase__       						=   None
      # args for megatron_lm
      UpperCamelCase__       						=   None
      # args for ipex
      UpperCamelCase__       						=   None
      # args for TPU
      UpperCamelCase__       						=   False

      # args for TPU pods
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   False
      UpperCamelCase__       						=   False
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   None

      # args for dynamo
      UpperCamelCase__       						=   None






      def 	UpperCAmelCase_   (						self:	Optional[Any]			):
          '''simple docstring'''


          if self.deepspeed_config is None:
              UpperCamelCase__:					int												=      {}
          if self.fsdp_config is None:
              UpperCamelCase__:					List[Any]												=      {}
          if self.megatron_lm_config is None:
              UpperCamelCase__:					Union[str, Any]												=      {}
          if self.ipex_config is None:
              UpperCamelCase__:					List[str]												=      {}
          return super().__post_init__()




@dataclass
class    _a  (  UpperCamelCase__):

      """simple docstring"""


      UpperCamelCase__       						=   42
      UpperCamelCase__       						=   42
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   "us-east-1"
      UpperCamelCase__       						=   1
      UpperCamelCase__       						=   "all"
      UpperCamelCase__       						=   F'''accelerate-sagemaker-{num_machines}'''
      UpperCamelCase__       						=   SAGEMAKER_PYTORCH_VERSION
      UpperCamelCase__       						=   SAGEMAKER_TRANSFORMERS_VERSION
      UpperCamelCase__       						=   SAGEMAKER_PYTHON_VERSION
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   None
      UpperCamelCase__       						=   None

