


"""simple docstring"""

import os
import tempfile
import unittest

import numpy as np

from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax, slow


if is_flax_available():
       import jax
       import jax.numpy as jnp
       from flax.jax_utils import replicate
       from flax.training.common_utils import shard

       from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline





@require_flax
class    lowerCamelCase__						(		unittest.TestCase    ):
      def SCREAMING_SNAKE_CASE_	(		self	:	Tuple							):






       '''simple docstring'''


       with tempfile.TemporaryDirectory() as tmpdirname:
        # pipeline has Flax weights
        __lowercase									=	FlaxDiffusionPipeline.from_pretrained(
            """hf-internal-testing/tiny-stable-diffusion-pipe"""      ,       safety_checker=A_      ,       cache_dir=A_							)

        __lowercase									=	[t[-1] for t in os.walk(os.path.join(A_      ,       os.listdir(A_							)[0]      ,       """snapshots"""							)							)]
        __lowercase									=	[item for sublist in all_root_files for item in sublist]

        # None of the downloaded files should be a PyTorch file even if we have some here:
        # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin
        assert not any(f.endswith(""".bin"""							) for f in files							)






@slow
@require_flax
class    lowerCamelCase__						(		unittest.TestCase    ):
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]							):






       '''simple docstring'''


       __lowercase							,		__lowercase									=	FlaxStableDiffusionPipeline.from_pretrained(
           """hf-internal-testing/tiny-stable-diffusion-pipe"""      ,       safety_checker=A_							)

       __lowercase									=	(
           """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
           """ field, close up, split lighting, cinematic"""
       )

       __lowercase									=	jax.random.PRNGKey(0							)
       __lowercase									=	4

       __lowercase									=	jax.device_count()
       __lowercase									=	num_samples * [prompt]
       __lowercase									=	pipeline.prepare_inputs(A_							)

       # shard inputs and rng
       __lowercase									=	replicate(A_							)
       __lowercase									=	jax.random.split(A_      ,       A_							)
       __lowercase									=	shard(A_							)

       __lowercase									=	pipeline(A_      ,       A_      ,       A_      ,       A_      ,       jit=A_							).images

       assert images.shape == (num_samples, 1, 6_4, 6_4, 3)
       if jax.device_count() == 8:
        assert np.abs(np.abs(images[0, 0, :2, :2, -2:]      ,       dtype=np.floataa							).sum() - 4.1_51_47_45							) < 1e-3
        assert np.abs(np.abs(A_      ,       dtype=np.floataa							).sum() - 4_99_47.8_75							) < 5e-1

       __lowercase									=	pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]							)							)							)
       assert len(A_							) == num_samples
      def SCREAMING_SNAKE_CASE_	(		self	:	Union[str, Any]							):






       '''simple docstring'''


       __lowercase							,		__lowercase									=	FlaxStableDiffusionPipeline.from_pretrained(
           """CompVis/stable-diffusion-v1-4"""      ,       revision="""flax"""      ,       safety_checker=A_							)

       __lowercase									=	(
           """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
           """ field, close up, split lighting, cinematic"""
       )

       __lowercase									=	jax.random.PRNGKey(0							)
       __lowercase									=	5_0

       __lowercase									=	jax.device_count()
       __lowercase									=	num_samples * [prompt]
       __lowercase									=	pipeline.prepare_inputs(A_							)

       # shard inputs and rng
       __lowercase									=	replicate(A_							)
       __lowercase									=	jax.random.split(A_      ,       A_							)
       __lowercase									=	shard(A_							)

       __lowercase									=	pipeline(A_      ,       A_      ,       A_      ,       A_      ,       jit=A_							).images

       assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       if jax.device_count() == 8:
        assert np.abs((np.abs(images[0, 0, :2, :2, -2:]      ,       dtype=np.floataa							).sum() - 0.05_65_24_01)							) < 1e-3
        assert np.abs((np.abs(A_      ,       dtype=np.floataa							).sum() - 2_38_38_08.2)							) < 5e-1
      def SCREAMING_SNAKE_CASE_	(		self	:	Any							):






       '''simple docstring'''


       __lowercase							,		__lowercase									=	FlaxStableDiffusionPipeline.from_pretrained(
           """CompVis/stable-diffusion-v1-4"""      ,       revision="""bf16"""      ,       dtype=jnp.bfloataa      ,       safety_checker=A_							)

       __lowercase									=	(
           """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
           """ field, close up, split lighting, cinematic"""
       )

       __lowercase									=	jax.random.PRNGKey(0							)
       __lowercase									=	5_0

       __lowercase									=	jax.device_count()
       __lowercase									=	num_samples * [prompt]
       __lowercase									=	pipeline.prepare_inputs(A_							)

       # shard inputs and rng
       __lowercase									=	replicate(A_							)
       __lowercase									=	jax.random.split(A_      ,       A_							)
       __lowercase									=	shard(A_							)

       __lowercase									=	pipeline(A_      ,       A_      ,       A_      ,       A_      ,       jit=A_							).images

       assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       if jax.device_count() == 8:
        assert np.abs((np.abs(images[0, 0, :2, :2, -2:]      ,       dtype=np.floataa							).sum() - 0.04_00_39_06)							) < 1e-3
        assert np.abs((np.abs(A_      ,       dtype=np.floataa							).sum() - 2_37_35_16.75)							) < 5e-1
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[int]							):






       '''simple docstring'''


       __lowercase							,		__lowercase									=	FlaxStableDiffusionPipeline.from_pretrained(
           """CompVis/stable-diffusion-v1-4"""      ,       revision="""bf16"""      ,       dtype=jnp.bfloataa							)

       __lowercase									=	(
           """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
           """ field, close up, split lighting, cinematic"""
       )

       __lowercase									=	jax.random.PRNGKey(0							)
       __lowercase									=	5_0

       __lowercase									=	jax.device_count()
       __lowercase									=	num_samples * [prompt]
       __lowercase									=	pipeline.prepare_inputs(A_							)

       # shard inputs and rng
       __lowercase									=	replicate(A_							)
       __lowercase									=	jax.random.split(A_      ,       A_							)
       __lowercase									=	shard(A_							)

       __lowercase									=	pipeline(A_      ,       A_      ,       A_      ,       A_      ,       jit=A_							).images

       assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       if jax.device_count() == 8:
        assert np.abs((np.abs(images[0, 0, :2, :2, -2:]      ,       dtype=np.floataa							).sum() - 0.04_00_39_06)							) < 1e-3
        assert np.abs((np.abs(A_      ,       dtype=np.floataa							).sum() - 2_37_35_16.75)							) < 5e-1
      def SCREAMING_SNAKE_CASE_	(		self	:	str							):






       '''simple docstring'''


       __lowercase									=	FlaxDDIMScheduler(
           beta_start=0.0_00_85      ,       beta_end=0.0_12      ,       beta_schedule="""scaled_linear"""      ,       set_alpha_to_one=A_      ,       steps_offset=1      ,       )

       __lowercase							,		__lowercase									=	FlaxStableDiffusionPipeline.from_pretrained(
           """CompVis/stable-diffusion-v1-4"""      ,       revision="""bf16"""      ,       dtype=jnp.bfloataa      ,       scheduler=A_      ,       safety_checker=A_      ,       )
       __lowercase									=	scheduler.create_state()

       __lowercase									=	scheduler_state

       __lowercase									=	(
           """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
           """ field, close up, split lighting, cinematic"""
       )

       __lowercase									=	jax.random.PRNGKey(0							)
       __lowercase									=	5_0

       __lowercase									=	jax.device_count()
       __lowercase									=	num_samples * [prompt]
       __lowercase									=	pipeline.prepare_inputs(A_							)

       # shard inputs and rng
       __lowercase									=	replicate(A_							)
       __lowercase									=	jax.random.split(A_      ,       A_							)
       __lowercase									=	shard(A_							)

       __lowercase									=	pipeline(A_      ,       A_      ,       A_      ,       A_      ,       jit=A_							).images

       assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       if jax.device_count() == 8:
        assert np.abs((np.abs(images[0, 0, :2, :2, -2:]      ,       dtype=np.floataa							).sum() - 0.0_45_04_39_45)							) < 1e-3
        assert np.abs((np.abs(A_      ,       dtype=np.floataa							).sum() - 2_34_76_93.5)							) < 5e-1






      def SCREAMING_SNAKE_CASE_	(		self	:	List[str]							):






       '''simple docstring'''


       __lowercase									=	(
           """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
           """ field, close up, split lighting, cinematic"""
       )

       __lowercase									=	jax.device_count()
       __lowercase									=	num_samples * [prompt]
       __lowercase									=	jax.random.split(jax.random.PRNGKey(0							)      ,       A_							)

       __lowercase							,		__lowercase									=	FlaxStableDiffusionPipeline.from_pretrained(
           """CompVis/stable-diffusion-v1-4"""      ,       revision="""bf16"""      ,       dtype=jnp.bfloataa      ,       safety_checker=A_      ,       )

       __lowercase									=	replicate(A_							)
       __lowercase									=	pipeline.prepare_inputs(A_							)
       __lowercase									=	shard(A_							)
       __lowercase									=	pipeline(A_      ,       A_      ,       A_      ,       jit=A_							).images
       assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       __lowercase									=	images[2, 0, 2_5_6, 1_0:1_7, 1]

       # With memory efficient attention
       __lowercase							,		__lowercase									=	FlaxStableDiffusionPipeline.from_pretrained(
           """CompVis/stable-diffusion-v1-4"""      ,       revision="""bf16"""      ,       dtype=jnp.bfloataa      ,       safety_checker=A_      ,       use_memory_efficient_attention=A_      ,       )

       __lowercase									=	replicate(A_							)
       __lowercase									=	pipeline.prepare_inputs(A_							)
       __lowercase									=	shard(A_							)
       __lowercase									=	pipeline(A_      ,       A_      ,       A_      ,       jit=A_							).images
       assert images_eff.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
       __lowercase									=	images[2, 0, 2_5_6, 1_0:1_7, 1]

       # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum`
       # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now.
       assert abs(slice_eff - slice							).max() < 1e-2




"""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 ChineseCLIPImageProcessor





class    lowerCamelCase__						(		unittest.TestCase    ):
      def __init__(		self	:	List[Any]      ,       A_	:	List[str]      ,       A_	:	str=7      ,       A_	:	Optional[int]=3      ,       A_	:	str=1_8      ,       A_	:	Tuple=3_0      ,       A_	:	Optional[Any]=4_0_0      ,       A_	:	Union[str, Any]=True      ,       A_	:	str=None      ,       A_	:	str=True      ,       A_	:	Optional[Any]=None      ,       A_	:	List[Any]=True      ,       A_	:	Union[str, Any]=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]      ,       A_	:	str=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]      ,       A_	:	List[str]=True      ,       ):






       '''simple docstring'''


       __lowercase									=	size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4}
       __lowercase									=	crop_size if crop_size is not None else {"""height""": 1_8, """width""": 1_8}
       __lowercase									=	parent
       __lowercase									=	batch_size
       __lowercase									=	num_channels
       __lowercase									=	image_size
       __lowercase									=	min_resolution
       __lowercase									=	max_resolution
       __lowercase									=	do_resize
       __lowercase									=	size
       __lowercase									=	do_center_crop
       __lowercase									=	crop_size
       __lowercase									=	do_normalize
       __lowercase									=	image_mean
       __lowercase									=	image_std
       __lowercase									=	do_convert_rgb
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]							):






       '''simple docstring'''


       return {
           "do_resize": self.do_resize,
           "size": self.size,
           "do_center_crop": self.do_center_crop,
           "crop_size": self.crop_size,
           "do_normalize": self.do_normalize,
           "image_mean": self.image_mean,
           "image_std": self.image_std,
           "do_convert_rgb": self.do_convert_rgb,
       }






      def SCREAMING_SNAKE_CASE_	(		self	:	str      ,       A_	:	List[Any]=False      ,       A_	:	List[Any]=False      ,       A_	:	Optional[Any]=False							):






       '''simple docstring'''


       assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

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

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

       if torchify:
        __lowercase									=	[torch.from_numpy(A_							) for x in image_inputs]

       return image_inputs






@require_torch
@require_vision
class    lowerCamelCase__						(		_a			,   unittest.TestCase    ):
      a :     Union[str, Any]											=		ChineseCLIPImageProcessor if is_vision_available() else None
      def SCREAMING_SNAKE_CASE_	(		self	:	Tuple							):






       '''simple docstring'''


       __lowercase									=	ChineseCLIPImageProcessingTester(self      ,       do_center_crop=A_							)
      @property
      def SCREAMING_SNAKE_CASE_	(		self	:	Union[str, Any]							):






       '''simple docstring'''


       return self.image_processor_tester.prepare_image_processor_dict()
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]							):






       '''simple docstring'''


       __lowercase									=	self.image_processing_class(**self.image_processor_dict							)
       self.assertTrue(hasattr(A_      ,       """do_resize"""							)							)
       self.assertTrue(hasattr(A_      ,       """size"""							)							)
       self.assertTrue(hasattr(A_      ,       """do_center_crop"""							)							)
       self.assertTrue(hasattr(A_      ,       """center_crop"""							)							)
       self.assertTrue(hasattr(A_      ,       """do_normalize"""							)							)
       self.assertTrue(hasattr(A_      ,       """image_mean"""							)							)
       self.assertTrue(hasattr(A_      ,       """image_std"""							)							)
       self.assertTrue(hasattr(A_      ,       """do_convert_rgb"""							)							)
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]							):






       '''simple docstring'''


       __lowercase									=	self.image_processing_class.from_dict(self.image_processor_dict							)
       self.assertEqual(image_processor.size      ,       {"""height""": 2_2_4, """width""": 2_2_4}							)
       self.assertEqual(image_processor.crop_size      ,       {"""height""": 1_8, """width""": 1_8}							)

       __lowercase									=	self.image_processing_class.from_dict(self.image_processor_dict      ,       size=4_2      ,       crop_size=8_4							)
       self.assertEqual(image_processor.size      ,       {"""shortest_edge""": 4_2}							)
       self.assertEqual(image_processor.crop_size      ,       {"""height""": 8_4, """width""": 8_4}							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[Any]							):






       '''simple docstring'''


       pass
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[int]							):






       '''simple docstring'''


       __lowercase									=	self.image_processing_class(**self.image_processor_dict							)
       # create random PIL images
       __lowercase									=	self.image_processor_tester.prepare_inputs(equal_resolution=A_							)
       for image in image_inputs:
        self.assertIsInstance(A_      ,       Image.Image							)

       # Test not batched input
       __lowercase									=	image_processing(image_inputs[0]      ,       return_tensors="""pt"""							).pixel_values
       self.assertEqual(
           encoded_images.shape      ,       (
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["""height"""],
               self.image_processor_tester.crop_size["""width"""],
           )      ,       )

       # Test batched
       __lowercase									=	image_processing(A_      ,       return_tensors="""pt"""							).pixel_values
       self.assertEqual(
           encoded_images.shape      ,       (
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["""height"""],
               self.image_processor_tester.crop_size["""width"""],
           )      ,       )
      def SCREAMING_SNAKE_CASE_	(		self	:	Any							):






       '''simple docstring'''


       __lowercase									=	self.image_processing_class(**self.image_processor_dict							)
       # create random numpy tensors
       __lowercase									=	self.image_processor_tester.prepare_inputs(equal_resolution=A_      ,       numpify=A_							)
       for image in image_inputs:
        self.assertIsInstance(A_      ,       np.ndarray							)

       # Test not batched input
       __lowercase									=	image_processing(image_inputs[0]      ,       return_tensors="""pt"""							).pixel_values
       self.assertEqual(
           encoded_images.shape      ,       (
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["""height"""],
               self.image_processor_tester.crop_size["""width"""],
           )      ,       )

       # Test batched
       __lowercase									=	image_processing(A_      ,       return_tensors="""pt"""							).pixel_values
       self.assertEqual(
           encoded_images.shape      ,       (
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["""height"""],
               self.image_processor_tester.crop_size["""width"""],
           )      ,       )






      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       __lowercase									=	self.image_processing_class(**self.image_processor_dict							)
       # create random PyTorch tensors
       __lowercase									=	self.image_processor_tester.prepare_inputs(equal_resolution=A_      ,       torchify=A_							)
       for image in image_inputs:
        self.assertIsInstance(A_      ,       torch.Tensor							)

       # Test not batched input
       __lowercase									=	image_processing(image_inputs[0]      ,       return_tensors="""pt"""							).pixel_values
       self.assertEqual(
           encoded_images.shape      ,       (
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["""height"""],
               self.image_processor_tester.crop_size["""width"""],
           )      ,       )

       # Test batched
       __lowercase									=	image_processing(A_      ,       return_tensors="""pt"""							).pixel_values
       self.assertEqual(
           encoded_images.shape      ,       (
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["""height"""],
               self.image_processor_tester.crop_size["""width"""],
           )      ,       )






@require_torch
@require_vision
class    lowerCamelCase__						(		_a			,   unittest.TestCase    ):
      a :     Optional[Any]											=		ChineseCLIPImageProcessor if is_vision_available() else None
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[Any]							):






       '''simple docstring'''


       __lowercase									=	ChineseCLIPImageProcessingTester(self      ,       num_channels=4      ,       do_center_crop=A_							)
       __lowercase									=	3
      @property
      def SCREAMING_SNAKE_CASE_	(		self	:	str							):






       '''simple docstring'''


       return self.image_processor_tester.prepare_image_processor_dict()
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[int]							):






       '''simple docstring'''


       __lowercase									=	self.image_processing_class(**self.image_processor_dict							)
       self.assertTrue(hasattr(A_      ,       """do_resize"""							)							)
       self.assertTrue(hasattr(A_      ,       """size"""							)							)
       self.assertTrue(hasattr(A_      ,       """do_center_crop"""							)							)
       self.assertTrue(hasattr(A_      ,       """center_crop"""							)							)
       self.assertTrue(hasattr(A_      ,       """do_normalize"""							)							)
       self.assertTrue(hasattr(A_      ,       """image_mean"""							)							)
       self.assertTrue(hasattr(A_      ,       """image_std"""							)							)
       self.assertTrue(hasattr(A_      ,       """do_convert_rgb"""							)							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Union[str, Any]							):






       '''simple docstring'''


       pass






      def SCREAMING_SNAKE_CASE_	(		self	:	str							):






       '''simple docstring'''


       __lowercase									=	self.image_processing_class(**self.image_processor_dict							)
       # create random PIL images
       __lowercase									=	self.image_processor_tester.prepare_inputs(equal_resolution=A_							)
       for image in image_inputs:
        self.assertIsInstance(A_      ,       Image.Image							)

       # Test not batched input
       __lowercase									=	image_processing(image_inputs[0]      ,       return_tensors="""pt"""							).pixel_values
       self.assertEqual(
           encoded_images.shape      ,       (
               1,
               self.expected_encoded_image_num_channels,
               self.image_processor_tester.crop_size["""height"""],
               self.image_processor_tester.crop_size["""width"""],
           )      ,       )

       # Test batched
       __lowercase									=	image_processing(A_      ,       return_tensors="""pt"""							).pixel_values
       self.assertEqual(
           encoded_images.shape      ,       (
               self.image_processor_tester.batch_size,
               self.expected_encoded_image_num_channels,
               self.image_processor_tester.crop_size["""height"""],
               self.image_processor_tester.crop_size["""width"""],
           )      ,       )
