




"""simple docstring"""


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

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


A_									=       logging.get_logger(__name__)






class       lowercase(  __a				):







 '''simple docstring'''





 lowercase__				      =      ["pixel_values"]


 def __init__(       self:	str,   a_:	bool = True,   a_:	Dict[str, int] = None,   a_:	PILImageResampling = PILImageResampling.BICUBIC,   a_:	bool = True,   a_:	Dict[str, int] = None,   a_:	bool = True,   a_:	Union[int, float] = 1 / 255,   a_:	bool = True,   a_:	Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN,   a_:	Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD,   **a_:	str,   ):




   '''simple docstring'''



   super().__init__(**a_	)
   _snake_case							:	Union[str, Any]			=						size if size is not None else {"""shortest_edge""": 224}
   _snake_case							:	str			=						get_size_dict(a_,   default_to_square=a_	)
   _snake_case							:	Optional[int]			=						crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
   _snake_case							:	List[str]			=						get_size_dict(a_,   param_name="""crop_size"""	)

   _snake_case							:	int			=						do_resize
   _snake_case							:	str			=						size
   _snake_case							:	List[Any]			=						resample
   _snake_case							:	List[Any]			=						do_center_crop
   _snake_case							:	Any			=						crop_size
   _snake_case							:	Union[str, Any]			=						do_rescale
   _snake_case							:	str			=						rescale_factor
   _snake_case							:	Union[str, Any]			=						do_normalize
   _snake_case							:	Union[str, Any]			=						image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
   _snake_case							:	int			=						image_std if image_std is not None else IMAGENET_DEFAULT_STD


 def 				UpperCamelCase_     (       self:	Tuple,   a_:	np.ndarray,   a_:	Dict[str, int],   a_:	PILImageResampling = PILImageResampling.BICUBIC,   a_:	Optional[Union[str, ChannelDimension]] = None,   **a_:	List[Any],   ):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						get_size_dict(a_,   default_to_square=a_	)
   # size_dict is a dict with either keys "height" and "width" or "shortest_edge"
   if "shortest_edge" in size:
     _snake_case							:	List[str]			=						int((256 / 224) * size["""shortest_edge"""]	)
     _snake_case							:	Tuple			=						get_resize_output_image_size(a_,   size=a_,   default_to_square=a_	)
     _snake_case							:	Dict			=						{"""height""": output_size[0], """width""": output_size[1]}
   if "height" not in size_dict or "width" not in size_dict:
     raise ValueError(
         f"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}"	)
   return resize(
       a_,   size=(size_dict["""height"""], size_dict["""width"""]),   resample=a_,   data_format=a_,   **a_	)


 def 				UpperCamelCase_     (       self:	List[Any],   a_:	np.ndarray,   a_:	Dict[str, int],   a_:	Optional[Union[str, ChannelDimension]] = None,   **a_:	Any,   ):




   '''simple docstring'''



   _snake_case							:	Dict			=						get_size_dict(a_	)
   if "height" not in size or "width" not in size:
     raise ValueError(f"Size dict must have keys 'height' and 'width'. Got {size.keys()}"	)
   return center_crop(a_,   size=(size["""height"""], size["""width"""]),   data_format=a_,   **a_	)


 def 				UpperCamelCase_     (       self:	Dict,   a_:	np.ndarray,   a_:	Union[int, float],   a_:	Optional[Union[str, ChannelDimension]] = None,   **a_:	str,   ):




   '''simple docstring'''



   return rescale(a_,   scale=a_,   data_format=a_,   **a_	)


 def 				UpperCamelCase_     (       self:	Optional[int],   a_:	np.ndarray,   a_:	Union[float, List[float]],   a_:	Union[float, List[float]],   a_:	Optional[Union[str, ChannelDimension]] = None,   **a_:	Tuple,   ):




   '''simple docstring'''



   return normalize(a_,   mean=a_,   std=a_,   data_format=a_,   **a_	)


 def 				UpperCamelCase_     (       self:	Dict,   a_:	ImageInput,   a_:	Optional[bool] = None,   a_:	Optional[Dict[str, int]] = None,   a_:	PILImageResampling = None,   a_:	Optional[bool] = None,   a_:	Optional[Dict[str, int]] = None,   a_:	Optional[bool] = None,   a_:	Optional[float] = None,   a_:	Optional[bool] = None,   a_:	Optional[Union[float, Iterable[float]]] = None,   a_:	Optional[Union[float, Iterable[float]]] = None,   a_:	Optional[TensorType] = None,   a_:	ChannelDimension = ChannelDimension.FIRST,   **a_:	List[str],   ):




   '''simple docstring'''



   _snake_case							:	Any			=						do_resize if do_resize is not None else self.do_resize
   _snake_case							:	Union[str, Any]			=						resample if resample is not None else self.resample
   _snake_case							:	Tuple			=						do_center_crop if do_center_crop is not None else self.do_center_crop
   _snake_case							:	Dict			=						do_rescale if do_rescale is not None else self.do_rescale
   _snake_case							:	Tuple			=						rescale_factor if rescale_factor is not None else self.rescale_factor
   _snake_case							:	List[Any]			=						do_normalize if do_normalize is not None else self.do_normalize
   _snake_case							:	Tuple			=						image_mean if image_mean is not None else self.image_mean
   _snake_case							:	int			=						image_std if image_std is not None else self.image_std

   _snake_case							:	Union[str, Any]			=						size if size is not None else self.size
   _snake_case							:	Tuple			=						get_size_dict(a_,   default_to_square=a_	)
   _snake_case							:	str			=						crop_size if crop_size is not None else self.crop_size
   _snake_case							:	int			=						get_size_dict(a_,   param_name="""crop_size"""	)

   _snake_case							:	Optional[Any]			=						make_list_of_images(a_	)

   if not valid_images(a_	):
     raise ValueError(
         """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
         """torch.Tensor, tf.Tensor or jax.ndarray."""	)

   if do_resize and size is None:
     raise ValueError("""Size must be specified if do_resize is True."""	)

   if do_center_crop and crop_size is None:
     raise ValueError("""Crop size must be specified if do_center_crop is True."""	)

   if do_rescale and rescale_factor is None:
     raise ValueError("""Rescale factor must be specified if do_rescale is True."""	)

   if do_normalize and (image_mean is None or image_std is None):
     raise ValueError("""Image mean and std must be specified if do_normalize is True."""	)

   # All transformations expect numpy arrays.
   _snake_case							:	Any			=						[to_numpy_array(a_	) for image in images]

   if do_resize:
     _snake_case							:	List[Any]			=						[self.resize(a_,   a_,   a_	) for image in images]

   if do_center_crop:
     _snake_case							:	str			=						[self.center_crop(a_,   a_	) for image in images]

   if do_rescale:
     _snake_case							:	Optional[Any]			=						[self.rescale(a_,   a_	) for image in images]

   if do_normalize:
     _snake_case							:	Optional[int]			=						[self.normalize(a_,   a_,   a_	) for image in images]

   _snake_case							:	Tuple			=						[to_channel_dimension_format(a_,   a_	) for image in images]

   _snake_case							:	Tuple			=						{"""pixel_values""": images}
   return BatchFeature(data=a_,   tensor_type=a_	)








"""simple docstring"""


import os
import sys
import unittest


A_      			=       os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
A_      			=       os.path.join(git_repo_path, '''src''', '''diffusers''')






class       lowercase(  unittest.TestCase				):







 '''simple docstring'''





 def 				UpperCamelCase_     (       self:	Tuple	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						find_backend("""    if not is_torch_available():"""	)
   self.assertEqual(a_,   """torch"""	)

   # backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
   # self.assertEqual(backend_with_underscore, "tensorflow_text")

   _snake_case							:	Any			=						find_backend("""    if not (is_torch_available() and is_transformers_available()):"""	)
   self.assertEqual(a_,   """torch_and_transformers"""	)

   # double_backend_with_underscore = find_backend(
   #    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
   # )
   # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

   _snake_case							:	Union[str, Any]			=						find_backend(
       """    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):"""	)
   self.assertEqual(a_,   """torch_and_transformers_and_onnx"""	)


 def 				UpperCamelCase_     (       self:	List[Any]	):




   '''simple docstring'''



   _snake_case							:	Dict			=						read_init()
   # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
   self.assertIn("""torch""",   a_	)
   self.assertIn("""torch_and_transformers""",   a_	)
   self.assertIn("""flax_and_transformers""",   a_	)
   self.assertIn("""torch_and_transformers_and_onnx""",   a_	)

   # Likewise, we can't assert on the exact content of a key
   self.assertIn("""UNet2DModel""",   objects["""torch"""]	)
   self.assertIn("""FlaxUNet2DConditionModel""",   objects["""flax"""]	)
   self.assertIn("""StableDiffusionPipeline""",   objects["""torch_and_transformers"""]	)
   self.assertIn("""FlaxStableDiffusionPipeline""",   objects["""flax_and_transformers"""]	)
   self.assertIn("""LMSDiscreteScheduler""",   objects["""torch_and_scipy"""]	)
   self.assertIn("""OnnxStableDiffusionPipeline""",   objects["""torch_and_transformers_and_onnx"""]	)


 def 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   _snake_case							:	Optional[Any]			=						create_dummy_object("""CONSTANT""",   """'torch'"""	)
   self.assertEqual(a_,   """\nCONSTANT = None\n"""	)

   _snake_case							:	Optional[int]			=						create_dummy_object("""function""",   """'torch'"""	)
   self.assertEqual(
       a_,   """\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""	)

   _snake_case							:	List[Any]			=						"""
class FakeClass(metaclass=DummyObject):
    _backends = 'torch'

    def __init__(self, *args, **kwargs):
        requires_backends(self, 'torch')

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, 'torch')

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, 'torch')
"""
   _snake_case							:	Union[str, Any]			=						create_dummy_object("""FakeClass""",   """'torch'"""	)
   self.assertEqual(a_,   a_	)


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




   '''simple docstring'''



   _snake_case							:	Union[str, Any]			=						"""# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, [\"torch\"])


class FakeClass(metaclass=DummyObject):
    _backends = [\"torch\"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, [\"torch\"])

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, [\"torch\"])

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, [\"torch\"])
"""
   _snake_case							:	List[Any]			=						create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}	)
   self.assertEqual(dummy_files["""torch"""],   a_	)


