






'''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 					__UpperCAmelCase (		unittest.TestCase	):

      '''simple docstring'''





      def __init__(					self  ,		_UpperCAmelCase  ,		_UpperCAmelCase=7  ,		_UpperCAmelCase=3  ,		_UpperCAmelCase=18  ,		_UpperCAmelCase=30  ,		_UpperCAmelCase=400  ,		_UpperCAmelCase=True  ,		_UpperCAmelCase=1 / 255  ,		_UpperCAmelCase=True  ,		_UpperCAmelCase=8  ,		):
             UpperCAmelCase__	:   Tuple												=	parent
             UpperCAmelCase__	:   Any												=	batch_size
             UpperCAmelCase__	:   Any												=	num_channels
             UpperCAmelCase__	:   int												=	image_size
             UpperCAmelCase__	:   List[Any]												=	min_resolution
             UpperCAmelCase__	:   Dict												=	max_resolution
             UpperCAmelCase__	:   Optional[Any]												=	do_rescale
             UpperCAmelCase__	:   Optional[int]												=	rescale_factor
             UpperCAmelCase__	:   Tuple												=	do_pad
             UpperCAmelCase__	:   str												=	pad_size




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




      def 							lowerCamelCase     (					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:
                    UpperCAmelCase__	:   List[Any]												=	[]
                    for i in range(self.batch_size						):
                           image_inputs.append(
                               np.random.randint(
                                   255  ,		size=(self.num_channels, self.max_resolution, self.max_resolution)  ,		dtype=np.uinta						)						)
             else:
                    UpperCAmelCase__	:   str												=	[]
                    for i in range(self.batch_size						):
                           UpperCAmelCase__							,							UpperCAmelCase__	:   Any												=	np.random.choice(np.arange(self.min_resolution  ,		self.max_resolution						)  ,		2						)
                           image_inputs.append(np.random.randint(255  ,		size=(self.num_channels, width, height)  ,		dtype=np.uinta						)						)

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

             if torchify:
                    UpperCAmelCase__	:   List[str]												=	[torch.from_numpy(_UpperCAmelCase						) for x in image_inputs]

             return image_inputs




@require_torch
@require_vision
class 					__UpperCAmelCase (		UpperCamelCase__      ,				unittest.TestCase	):

      '''simple docstring'''





      SCREAMING_SNAKE_CASE				:    List[str]				       =					SwinaSRImageProcessor if is_vision_available() else None




      def 							lowerCamelCase     (					self						):
             UpperCAmelCase__	:   str												=	SwinaSRImageProcessingTester(self						)




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




      def 							lowerCamelCase     (					self						):
             UpperCAmelCase__	:   str												=	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 							lowerCamelCase     (					self						):
             pass




      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase						):
             UpperCAmelCase__							,							UpperCAmelCase__	:   List[Any]												=	get_image_size(_UpperCAmelCase						)
             UpperCAmelCase__	:   List[str]												=	self.image_processor_tester.pad_size

             UpperCAmelCase__	:   Union[str, Any]												=	(old_height // size + 1) * size - old_height
             UpperCAmelCase__	:   Any												=	(old_width // size + 1) * size - old_width
             return old_height + pad_height, old_width + pad_width




      def 							lowerCamelCase     (					self						):
             # Initialize image_processor
             UpperCAmelCase__	:   List[Any]												=	self.image_processing_class(**self.image_processor_dict						)
             # create random PIL images
             UpperCAmelCase__	:   List[Any]												=	self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase						)
             for image in image_inputs:
                    self.assertIsInstance(_UpperCAmelCase  ,		Image.Image						)

             # Test not batched input
             UpperCAmelCase__	:   str												=	image_processor(image_inputs[0]  ,		return_tensors='''pt'''						).pixel_values
             UpperCAmelCase__							,							UpperCAmelCase__	:   List[Any]												=	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 							lowerCamelCase     (					self						):
             # Initialize image_processor
             UpperCAmelCase__	:   str												=	self.image_processing_class(**self.image_processor_dict						)
             # create random numpy tensors
             UpperCAmelCase__	:   Tuple												=	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
             UpperCAmelCase__	:   Optional[int]												=	image_processor(image_inputs[0]  ,		return_tensors='''pt'''						).pixel_values
             UpperCAmelCase__							,							UpperCAmelCase__	:   Any												=	self.calculate_expected_size(image_inputs[0]						)
             self.assertEqual(
                 encoded_images.shape  ,		(
                     1,
                     self.image_processor_tester.num_channels,
                     expected_height,
                     expected_width,
                 )  ,		)




      def 							lowerCamelCase     (					self						):
             # Initialize image_processor
             UpperCAmelCase__	:   Optional[Any]												=	self.image_processing_class(**self.image_processor_dict						)
             # create random PyTorch tensors
             UpperCAmelCase__	:   List[str]												=	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
             UpperCAmelCase__	:   List[Any]												=	image_processor(image_inputs[0]  ,		return_tensors='''pt'''						).pixel_values
             UpperCAmelCase__							,							UpperCAmelCase__	:   int												=	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 ctypes import c_float, sizeof
from enum import Enum
from typing import TYPE_CHECKING, Optional, Union


if TYPE_CHECKING:
  from .. import AutoFeatureExtractor, AutoProcessor, AutoTokenizer  # tests_ignore




class 					__UpperCAmelCase (		UpperCamelCase__	):

      '''simple docstring'''





      SCREAMING_SNAKE_CASE				:    Dict				       =					c_float




      @property
      def 							lowerCamelCase     (					self						):
             return sizeof(self.value						)






def  lowerCAmelCase__		(					a_  :     int			,						a_  :     int			,						a_  :     int = 0			)   -> int:
       # < 0 is possible if using a dynamic axis
       if dimension <= 0:
              UpperCAmelCase__	:   List[Any]												=	fixed_dimension

       dimension -= num_token_to_add
       return dimension






def  lowerCAmelCase__		(					a_  :     int			,						a_  :     ParameterFormat			)   -> int:
       return num_parameters * dtype.size






def  lowerCAmelCase__		(					a_  :     str			)   -> Optional[Union["AutoTokenizer", "AutoFeatureExtractor", "AutoProcessor"]]:
       from .. import AutoFeatureExtractor, AutoProcessor, AutoTokenizer  # tests_ignore

       try:
              return AutoProcessor.from_pretrained(a_			)
       except (ValueError, OSError, KeyError):
              UpperCAmelCase__							,							UpperCAmelCase__	:   Dict												=	None, None
              try:
                     UpperCAmelCase__	:   Union[str, Any]												=	AutoTokenizer.from_pretrained(a_			)
              except (OSError, KeyError):
                     pass
              try:
                     UpperCAmelCase__	:   List[str]												=	AutoFeatureExtractor.from_pretrained(a_			)
              except (OSError, KeyError):
                     pass

              if tokenizer is not None and feature_extractor is not None:
                     raise ValueError(
                         f"""Couldn't auto-detect preprocessor for {model_name}. Found both a tokenizer and a feature extractor."""			)
              elif tokenizer is None and feature_extractor is None:
                     return None
              elif tokenizer is not None:
                     return tokenizer
              else:
                     return feature_extractor