
'''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 SwinaSRImageProcessor
    from transformers.image_transforms import get_image_size







class 		snake_case_       (						unittest.TestCase						):



   """simple docstring"""





   def __init__( self			,   UpperCamelCase			,   UpperCamelCase=7			,   UpperCamelCase=3			,   UpperCamelCase=18			,   UpperCamelCase=30			,   UpperCamelCase=4_00			,   UpperCamelCase=True			,   UpperCamelCase=1 / 2_55			,   UpperCamelCase=True			,   UpperCamelCase=8			,   ):
          lowerCamelCase__				   =      parent
          lowerCamelCase__				   =      batch_size
          lowerCamelCase__				   =      num_channels
          lowerCamelCase__				   =      image_size
          lowerCamelCase__				   =      min_resolution
          lowerCamelCase__				   =      max_resolution
          lowerCamelCase__				   =      do_rescale
          lowerCamelCase__				   =      rescale_factor
          lowerCamelCase__				   =      do_pad
          lowerCamelCase__				   =      pad_size







   def     __UpperCAmelCase      ( self):
          return {
              "do_rescale": self.do_rescale,
              "rescale_factor": self.rescale_factor,
              "do_pad": self.do_pad,
              "pad_size": self.pad_size,
          }







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

          if equal_resolution:
                 lowerCamelCase__				   =      []
                 for i in range(self.batch_size):
                        image_inputs.append(
                            np.random.randint(
                                2_55			,   size=(self.num_channels, self.max_resolution, self.max_resolution)			,   dtype=np.uinta))
          else:
                 lowerCamelCase__				   =      []
                 for i in range(self.batch_size):
                        lowerCamelCase__   ,		lowerCamelCase__				   =      np.random.choice(np.arange(self.min_resolution			,   self.max_resolution)			,   2)
                        image_inputs.append(np.random.randint(2_55			,   size=(self.num_channels, width, height)			,   dtype=np.uinta))

          if not numpify and not torchify:
                 # PIL expects the channel dimension as last dimension
                 lowerCamelCase__				   =      [Image.fromarray(np.moveaxis(UpperCamelCase			,   0			,   -1)) for x in image_inputs]

          if torchify:
                 lowerCamelCase__				   =      [torch.from_numpy(UpperCamelCase) for x in image_inputs]

          return image_inputs







@require_torch
@require_vision
class 		snake_case_       (						A__		,	unittest.TestCase						):



   """simple docstring"""





   __lowerCAmelCase	:							Optional[Any]								=SwinaSRImageProcessor if is_vision_available() else None







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      SwinaSRImageProcessingTester(self)







   @property
   def     __UpperCAmelCase      ( self):
          return self.image_processor_tester.prepare_image_processor_dict()







   def     __UpperCAmelCase      ( self):
          lowerCamelCase__				   =      self.image_processing_class(**self.image_processor_dict)
          self.assertTrue(hasattr(UpperCamelCase			,   "do_rescale"))
          self.assertTrue(hasattr(UpperCamelCase			,   "rescale_factor"))
          self.assertTrue(hasattr(UpperCamelCase			,   "do_pad"))
          self.assertTrue(hasattr(UpperCamelCase			,   "pad_size"))







   def     __UpperCAmelCase      ( self):
          pass







   def     __UpperCAmelCase      ( self			,   UpperCamelCase):
          lowerCamelCase__   ,		lowerCamelCase__				   =      get_image_size(UpperCamelCase)
          lowerCamelCase__				   =      self.image_processor_tester.pad_size

          lowerCamelCase__				   =      (old_height // size + 1) * size - old_height
          lowerCamelCase__				   =      (old_width // size + 1) * size - old_width
          return old_height + pad_height, old_width + pad_width







   def     __UpperCAmelCase      ( self):
          # Initialize image_processor
          lowerCamelCase__				   =      self.image_processing_class(**self.image_processor_dict)
          # create random PIL images
          lowerCamelCase__				   =      self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase)
          for image in image_inputs:
                 self.assertIsInstance(UpperCamelCase			,   Image.Image)

          # Test not batched input
          lowerCamelCase__				   =      image_processor(image_inputs[0]			,   return_tensors="pt").pixel_values
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.calculate_expected_size(np.array(image_inputs[0]))
          self.assertEqual(
              encoded_images.shape			,   (
                  1,
                  self.image_processor_tester.num_channels,
                  expected_height,
                  expected_width,
              )			,   )







   def     __UpperCAmelCase      ( self):
          # Initialize image_processor
          lowerCamelCase__				   =      self.image_processing_class(**self.image_processor_dict)
          # create random numpy tensors
          lowerCamelCase__				   =      self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase			,   numpify=UpperCamelCase)
          for image in image_inputs:
                 self.assertIsInstance(UpperCamelCase			,   np.ndarray)

          # Test not batched input
          lowerCamelCase__				   =      image_processor(image_inputs[0]			,   return_tensors="pt").pixel_values
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.calculate_expected_size(image_inputs[0])
          self.assertEqual(
              encoded_images.shape			,   (
                  1,
                  self.image_processor_tester.num_channels,
                  expected_height,
                  expected_width,
              )			,   )







   def     __UpperCAmelCase      ( self):
          # Initialize image_processor
          lowerCamelCase__				   =      self.image_processing_class(**self.image_processor_dict)
          # create random PyTorch tensors
          lowerCamelCase__				   =      self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase			,   torchify=UpperCamelCase)
          for image in image_inputs:
                 self.assertIsInstance(UpperCamelCase			,   torch.Tensor)

          # Test not batched input
          lowerCamelCase__				   =      image_processor(image_inputs[0]			,   return_tensors="pt").pixel_values
          lowerCamelCase__   ,		lowerCamelCase__				   =      self.calculate_expected_size(image_inputs[0])
          self.assertEqual(
              encoded_images.shape			,   (
                  1,
                  self.image_processor_tester.num_channels,
                  expected_height,
                  expected_width,
              )			,   )



'''simple docstring'''







from typing import List, Optional, Tuple, Union

from . import logging
from .import_utils import is_torch_available, is_torch_version


if is_torch_available():
    import torch

lowerCAmelCase_      =   logging.get_logger(__name__)  # pylint: disable=invalid-name

try:
    from torch._dynamo import allow_in_graph as maybe_allow_in_graph
except (ImportError, ModuleNotFoundError):







    def   lowerCAmelCase(  cls    :  Dict      ):







           '''simple docstring'''






           return cls







def   lowerCAmelCase(  a__    :  Union[Tuple, List]      , a__    :  Optional[Union[List["torch.Generator"], "torch.Generator"]] = None      , a__    :  Optional["torch.device"] = None      , a__    :  Optional["torch.dtype"] = None      , a__    :  Optional["torch.layout"] = None      , ):







       '''simple docstring'''






       lowerCamelCase__				   =      device
       lowerCamelCase__				   =      shape[0]

       lowerCamelCase__				   =      layout or torch.strided
       lowerCamelCase__				   =      device or torch.device("cpu"      )

       if generator is not None:
              lowerCamelCase__				   =      generator.device.type if not isinstance(a__      , a__      ) else generator[0].device.type
              if gen_device_type != device.type and gen_device_type == "cpu":
                     lowerCamelCase__				   =      "cpu"
                     if device != "mps":
                            logger.info(
                                f"""The passed generator was created on 'cpu' even though a tensor on {device} was expected."""
                                f""" Tensors will be created on 'cpu' and then moved to {device}. Note that one can probably"""
                                f""" slighly speed up this function by passing a generator that was created on the {device} device."""      )
              elif gen_device_type != device.type and gen_device_type == "cuda":
                     raise ValueError(f"""Cannot generate a {device} tensor from a generator of type {gen_device_type}."""      )

       if isinstance(a__      , a__      ):
              lowerCamelCase__				   =      (1,) + shape[1:]
              lowerCamelCase__				   =      [
                  torch.randn(a__      , generator=generator[i]      , device=a__      , dtype=a__      , layout=a__      )
                  for i in range(a__      )
              ]
              lowerCamelCase__				   =      torch.cat(a__      , dim=0      ).to(a__      )
       else:
              lowerCamelCase__				   =      torch.randn(a__      , generator=a__      , device=a__      , dtype=a__      , layout=a__      ).to(a__      )

       return latents







def   lowerCAmelCase(  a__    :  Union[str, Any]      ):







       '''simple docstring'''






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

