




from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
		import PIL


__A						:							Tuple							=  logging.get_logger(__name__)




class 			UpperCAmelCase_      (   _A       ):




							'''simple docstring'''



							a__						  =     ['''pixel_values''']





							def __init__(					self       :	int       ,     a       :	Union[str, Any] = True       ,     a       :	Optional[int] = None       ,     a       :	List[str] = PILImageResampling.BICUBIC       ,     a       :	Optional[Any] = True       ,     a       :	int = 1 / 255       ,     a       :	Optional[int] = True       ,     a       :	List[Any] = None       ,     a       :	List[Any] = None       ,     a       :	Optional[int] = True       ,     **a       :	Any       ,     )			->					None:
										super().__init__(**a			)
										SCREAMING_SNAKE_CASE           =					size if size is not None else {"height": 384, "width": 384}
										SCREAMING_SNAKE_CASE           =					get_size_dict(a       ,     default_to_square=a			)

										SCREAMING_SNAKE_CASE           =					do_resize
										SCREAMING_SNAKE_CASE           =					size
										SCREAMING_SNAKE_CASE           =					resample
										SCREAMING_SNAKE_CASE           =					do_rescale
										SCREAMING_SNAKE_CASE           =					rescale_factor
										SCREAMING_SNAKE_CASE           =					do_normalize
										SCREAMING_SNAKE_CASE           =					image_mean if image_mean is not None else OPENAI_CLIP_MEAN
										SCREAMING_SNAKE_CASE           =					image_std if image_std is not None else OPENAI_CLIP_STD
										SCREAMING_SNAKE_CASE           =					do_convert_rgb





							def    _UpperCAmelCase     (					self       :	int       ,     a       :	List[Any]       ,     a       :	str       ,     a       :	List[Any] = PILImageResampling.BICUBIC       ,     a       :	List[str] = None       ,     **a       :	Dict       ,     )			->					np.ndarray:
										SCREAMING_SNAKE_CASE           =					get_size_dict(a       ,     default_to_square=a			)
										if "height" not in size or "width" not in size:
													raise ValueError(f"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}"""			)
										SCREAMING_SNAKE_CASE           =					(size["height"], size["width"])
										return resize(a       ,     size=a       ,     resample=a       ,     data_format=a       ,     **a			)





							def    _UpperCAmelCase     (					self       :	Any       ,     a       :	int       ,     a       :	Tuple       ,     a       :	Optional[int] = None       ,     **a       :	Optional[Any]       ,     )			->					str:
										return rescale(a       ,     scale=a       ,     data_format=a       ,     **a			)





							def    _UpperCAmelCase     (					self       :	str       ,     a       :	Optional[int]       ,     a       :	Union[str, Any]       ,     a       :	str       ,     a       :	str = None       ,     **a       :	Union[str, Any]       ,     )			->					np.ndarray:
										return normalize(a       ,     mean=a       ,     std=a       ,     data_format=a       ,     **a			)







							def    _UpperCAmelCase     (					self       :	Any       ,     a       :	Dict       ,     a       :	Tuple = None       ,     a       :	List[Any] = None       ,     a       :	Dict = None       ,     a       :	Union[str, Any] = None       ,     a       :	Union[str, Any] = None       ,     a       :	Any = None       ,     a       :	str = None       ,     a       :	Dict = None       ,     a       :	Optional[int] = None       ,     a       :	Tuple = None       ,     a       :	Optional[int] = ChannelDimension.FIRST       ,     **a       :	Optional[int]       ,     )			->					PIL.Image.Image:
										SCREAMING_SNAKE_CASE           =					do_resize if do_resize is not None else self.do_resize
										SCREAMING_SNAKE_CASE           =					resample if resample is not None else self.resample
										SCREAMING_SNAKE_CASE           =					do_rescale if do_rescale is not None else self.do_rescale
										SCREAMING_SNAKE_CASE           =					rescale_factor if rescale_factor is not None else self.rescale_factor
										SCREAMING_SNAKE_CASE           =					do_normalize if do_normalize is not None else self.do_normalize
										SCREAMING_SNAKE_CASE           =					image_mean if image_mean is not None else self.image_mean
										SCREAMING_SNAKE_CASE           =					image_std if image_std is not None else self.image_std
										SCREAMING_SNAKE_CASE           =					do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

										SCREAMING_SNAKE_CASE           =					size if size is not None else self.size
										SCREAMING_SNAKE_CASE           =					get_size_dict(a       ,     default_to_square=a			)

										SCREAMING_SNAKE_CASE           =					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 or resample is None:
													raise ValueError("""Size and resample must be specified if do_resize 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."""			)

										# PIL RGBA images are converted to RGB
										if do_convert_rgb:
													SCREAMING_SNAKE_CASE           =					[convert_to_rgb(a			) for image in images]

										# All transformations expect numpy arrays.
										SCREAMING_SNAKE_CASE           =					[to_numpy_array(a			) for image in images]

										if do_resize:
													SCREAMING_SNAKE_CASE           =					[self.resize(image=a       ,     size=a       ,     resample=a			) for image in images]

										if do_rescale:
													SCREAMING_SNAKE_CASE           =					[self.rescale(image=a       ,     scale=a			) for image in images]

										if do_normalize:
													SCREAMING_SNAKE_CASE           =					[self.normalize(image=a       ,     mean=a       ,     std=a			) for image in images]

										SCREAMING_SNAKE_CASE           =					[to_channel_dimension_format(a       ,     a			) for image in images]

										SCREAMING_SNAKE_CASE           =					BatchFeature(data={"""pixel_values""": images}       ,     tensor_type=a			)

										return encoded_outputs









import os
import sys
import unittest


__A						:							Any							=  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						:							List[Any]							=  os.path.join(git_repo_path, """src""", """diffusers""")




class 			UpperCAmelCase_      (   unittest.TestCase       ):




							'''simple docstring'''



							def    _UpperCAmelCase     (					self       :	Any			)			->					Optional[Any]:
										SCREAMING_SNAKE_CASE           =					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")

										SCREAMING_SNAKE_CASE           =					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")

										SCREAMING_SNAKE_CASE           =					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[str]			)			->					int:
										SCREAMING_SNAKE_CASE           =					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       :	Any			)			->					int:
										SCREAMING_SNAKE_CASE           =					create_dummy_object("""CONSTANT"""       ,     """'torch'"""			)
										self.assertEqual(a       ,     """\nCONSTANT = None\n"""			)

										SCREAMING_SNAKE_CASE           =					create_dummy_object("""function"""       ,     """'torch'"""			)
										self.assertEqual(
										    a       ,     """\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""			)

										SCREAMING_SNAKE_CASE           =					"""
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')
"""
										SCREAMING_SNAKE_CASE           =					create_dummy_object("""FakeClass"""       ,     """'torch'"""			)
										self.assertEqual(a       ,     a			)







							def    _UpperCAmelCase     (					self       :	Union[str, Any]			)			->					Union[str, Any]:
										SCREAMING_SNAKE_CASE           =					"""# 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\"])
"""
										SCREAMING_SNAKE_CASE           =					create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}			)
										self.assertEqual(dummy_files["""torch"""]       ,     a			)






