



import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
      from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Any     ):



 """simple docstring"""





 if is_torch_version("<"		,	"2.0.0"     ) or not hasattr(__lowerCamelCase		,	"_dynamo"     ):
  return False
 return isinstance(__lowerCamelCase		,	torch._dynamo.eval_frame.OptimizedModule     )






def 	_lowerCAmelCase						(				__lowerCamelCase   :     List[str]		,	__lowerCamelCase   :     bool = True     ):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    List[Any]       =	(torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

 __SCREAMING_SNAKE_CASE       :    List[Any]       =	is_compiled_module(__lowerCamelCase     )
 if is_compiled:
  __SCREAMING_SNAKE_CASE       :    int       =	model
  __SCREAMING_SNAKE_CASE       :    str       =	model._orig_mod

 if is_deepspeed_available():
  options += (DeepSpeedEngine,)

 while isinstance(__lowerCamelCase		,	__lowerCamelCase     ):
  __SCREAMING_SNAKE_CASE       :    Tuple       =	model.module

 if not keep_fpaa_wrapper:
  __SCREAMING_SNAKE_CASE       :    Any       =	getattr(__lowerCamelCase		,	"forward"     )
  __SCREAMING_SNAKE_CASE       :    List[Any]       =	model.__dict__.pop("_original_forward"		,	__lowerCamelCase     )
  if original_forward is not None:
   while hasattr(__lowerCamelCase		,	"__wrapped__"     ):
    __SCREAMING_SNAKE_CASE       :    int       =	forward.__wrapped__
    if forward == original_forward:
     break
   __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	forward
  if getattr(__lowerCamelCase		,	"_converted_to_transformer_engine"		,	__lowerCamelCase     ):
   convert_model(__lowerCamelCase		,	to_transformer_engine=__lowerCamelCase     )

 if is_compiled:
  __SCREAMING_SNAKE_CASE       :    List[Any]       =	model
  __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	compiled_model

 return model






def 	_lowerCAmelCase						(				):



 """simple docstring"""





 PartialState().wait_for_everyone()






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Optional[Any]		,	__lowerCamelCase   :     Tuple     ):



 """simple docstring"""





 if PartialState().distributed_type == DistributedType.TPU:
  xm.save(__lowerCamelCase		,	__lowerCamelCase     )
 elif PartialState().local_process_index == 0:
  torch.save(__lowerCamelCase		,	__lowerCamelCase     )






@contextmanager
def 	_lowerCAmelCase						(				**__lowerCamelCase   :     Optional[Any]     ):



 """simple docstring"""





 for key, value in kwargs.items():
  __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	str(__lowerCamelCase     )

 yield

 for key in kwargs:
  if key.upper() in os.environ:
   del os.environ[key.upper()]






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Tuple     ):



 """simple docstring"""





 if not hasattr(__lowerCamelCase		,	"__qualname__"     ) and not hasattr(__lowerCamelCase		,	"__name__"     ):
  __SCREAMING_SNAKE_CASE       :    Optional[int]       =	getattr(__lowerCamelCase		,	"__class__"		,	__lowerCamelCase     )
 if hasattr(__lowerCamelCase		,	"__qualname__"     ):
  return obj.__qualname__
 if hasattr(__lowerCamelCase		,	"__name__"     ):
  return obj.__name__
 return str(__lowerCamelCase     )






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Any		,	__lowerCamelCase   :     List[str]     ):



 """simple docstring"""





 for key, value in source.items():
  if isinstance(__lowerCamelCase		,	__lowerCamelCase     ):
   __SCREAMING_SNAKE_CASE       :    Optional[int]       =	destination.setdefault(__lowerCamelCase		,	{}     )
   merge_dicts(__lowerCamelCase		,	__lowerCamelCase     )
  else:
   __SCREAMING_SNAKE_CASE       :    str       =	value

 return destination






def 	_lowerCAmelCase						(				__lowerCamelCase   :     int = None     ):



 """simple docstring"""





 if port is None:
  __SCREAMING_SNAKE_CASE       :    Dict       =	29500
 with socket.socket(socket.AF_INET		,	socket.SOCK_STREAM     ) as s:
  return s.connect_ex(("localhost", port)     ) == 0











import unittest
from typing import Dict, List, Optional, Union

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():
      from PIL import Image

      from transformers import BridgeTowerImageProcessor

class       _SCREAMING_SNAKE_CASE	(unittest.TestCase ):





     def __init__(       self :							Union[str, Any]     ,  UpperCamelCase :							List[Any]     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Dict[str, int] = None     ,  UpperCamelCase :							int = 3_2     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Union[int, float] = 1 / 2_5_5     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Optional[Union[float, List[float]]] = [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]     ,  UpperCamelCase :							Optional[Union[float, List[float]]] = [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Dict=7     ,  UpperCamelCase :							Dict=3_0     ,  UpperCamelCase :							Tuple=4_0_0     ,  UpperCamelCase :							Union[str, Any]=3     ,  )->Optional[int]:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	parent
      __SCREAMING_SNAKE_CASE       :    str       =	do_resize
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	size if size is not None else {"shortest_edge": 2_8_8}
      __SCREAMING_SNAKE_CASE       :    List[str]       =	size_divisor
      __SCREAMING_SNAKE_CASE       :    str       =	do_rescale
      __SCREAMING_SNAKE_CASE       :    int       =	rescale_factor
      __SCREAMING_SNAKE_CASE       :    Tuple       =	do_normalize
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	do_center_crop
      __SCREAMING_SNAKE_CASE       :    List[str]       =	image_mean
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	image_std
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	do_pad
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	batch_size
      __SCREAMING_SNAKE_CASE       :    str       =	num_channels
      __SCREAMING_SNAKE_CASE       :    List[str]       =	min_resolution
      __SCREAMING_SNAKE_CASE       :    Tuple       =	max_resolution





     def 	__snake_case    (       self :							Optional[Any]				)->List[str]:
      return {
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_normalize": self.do_normalize,
          "do_resize": self.do_resize,
          "size": self.size,
          "size_divisor": self.size_divisor,
      }






     def 	__snake_case    (       self :							Optional[Any]     ,  UpperCamelCase :							Optional[int]     ,  UpperCamelCase :							Dict=False				)->Optional[Any]:
      if not batched:
       __SCREAMING_SNAKE_CASE       :    Optional[int]       =	self.size["shortest_edge"]
       __SCREAMING_SNAKE_CASE       :    List[Any]       =	image_inputs[0]
       if isinstance(UpperCamelCase     ,  Image.Image				):
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[Any]       =	image.size
       else:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	image.shape[1], image.shape[2]
       __SCREAMING_SNAKE_CASE       :    Tuple       =	size / min(UpperCamelCase     ,  UpperCamelCase				)
       if h < w:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    int       =	size, scale * w
       else:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[str]       =	scale * h, size

       __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	int((1_3_3_3 / 8_0_0) * size				)
       if max(UpperCamelCase     ,  UpperCamelCase				) > max_size:
        __SCREAMING_SNAKE_CASE       :    Any       =	max_size / max(UpperCamelCase     ,  UpperCamelCase				)
        __SCREAMING_SNAKE_CASE       :    List[Any]       =	newh * scale
        __SCREAMING_SNAKE_CASE       :    Optional[int]       =	neww * scale

       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[Any]       =	int(newh + 0.5				), int(neww + 0.5				)
       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Optional[Any]       =	(
           newh // self.size_divisor * self.size_divisor,
           neww // self.size_divisor * self.size_divisor,
       )

      else:
       __SCREAMING_SNAKE_CASE       :    Optional[int]       =	[]
       for image in image_inputs:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Optional[Any]       =	self.get_expected_values([image]				)
        expected_values.append((expected_height, expected_width)				)
       __SCREAMING_SNAKE_CASE       :    int       =	max(UpperCamelCase     ,  key=lambda UpperCamelCase				: item[0]				)[0]
       __SCREAMING_SNAKE_CASE       :    List[str]       =	max(UpperCamelCase     ,  key=lambda UpperCamelCase				: item[1]				)[1]

      return expected_height, expected_width






@require_torch
@require_vision
class       _SCREAMING_SNAKE_CASE	(UpperCamelCase			,    unittest.TestCase ):
     lowerCAmelCase					=			BridgeTowerImageProcessor if is_vision_available() else None





     def 	__snake_case    (       self :							str				)->int:
      __SCREAMING_SNAKE_CASE       :    str       =	BridgeTowerImageProcessingTester(self				)





     @property
     def 	__snake_case    (       self :							str				)->Any:
      return self.image_processor_tester.prepare_image_processor_dict()





     def 	__snake_case    (       self :							Optional[int]				)->Dict:
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	self.image_processing_class(**self.image_processor_dict				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "image_mean"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "image_std"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "do_normalize"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "do_resize"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "size"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "size_divisor"				)				)





     def 	__snake_case    (       self :							Optional[int]				)->int:
      pass





     def 	__snake_case    (       self :							str				)->Union[str, Any]:
      # Initialize image processor
      __SCREAMING_SNAKE_CASE       :    Any       =	self.image_processing_class(**self.image_processor_dict				)
      # create random PIL images
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=UpperCamelCase				)
      for image in image_inputs:
       self.assertIsInstance(UpperCamelCase     ,  Image.Image				)

      # Test not batched input
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	image_processing(image_inputs[0]     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Tuple       =	self.image_processor_tester.get_expected_values(UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,  )

      # Test batched
      __SCREAMING_SNAKE_CASE       :    Any       =	image_processing(UpperCamelCase     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	self.image_processor_tester.get_expected_values(UpperCamelCase     ,  batched=UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )     ,  )





     def 	__snake_case    (       self :							List[str]				)->Optional[int]:
      # Initialize image processor
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	self.image_processing_class(**self.image_processor_dict				)
      # create random numpy tensors
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=UpperCamelCase     ,  numpify=UpperCamelCase				)
      for image in image_inputs:
       self.assertIsInstance(UpperCamelCase     ,  np.ndarray				)

      # Test not batched input
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	image_processing(image_inputs[0]     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Optional[int]       =	self.image_processor_tester.get_expected_values(UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,  )

      # Test batched
      __SCREAMING_SNAKE_CASE       :    str       =	image_processing(UpperCamelCase     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[Any]       =	self.image_processor_tester.get_expected_values(UpperCamelCase     ,  batched=UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )     ,  )






     def 	__snake_case    (       self :							Optional[Any]				)->Union[str, Any]:
      # Initialize image processor
      __SCREAMING_SNAKE_CASE       :    Dict       =	self.image_processing_class(**self.image_processor_dict				)
      # create random PyTorch tensors
      __SCREAMING_SNAKE_CASE       :    List[str]       =	prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=UpperCamelCase     ,  torchify=UpperCamelCase				)
      for image in image_inputs:
       self.assertIsInstance(UpperCamelCase     ,  torch.Tensor				)

      # Test not batched input
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	image_processing(image_inputs[0]     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Dict       =	self.image_processor_tester.get_expected_values(UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,  )

      # Test batched
      __SCREAMING_SNAKE_CASE       :    str       =	image_processing(UpperCamelCase     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Any       =	self.image_processor_tester.get_expected_values(UpperCamelCase     ,  batched=UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )     ,  )






