






import inspect
import re
from hashlib import shaaaa
from typing import Dict, List

from .arrow import arrow
from .audiofolder import audiofolder
from .csv import csv
from .imagefolder import imagefolder
from .json import json
from .pandas import pandas
from .parquet import parquet
from .sql import sql  # noqa F401
from .text import text

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:Union[str, Any]   =   []
				for line in lines:
								__magic_name__		:Dict   =   re.sub(R'''#.*''',	'''''',	snake_case			)  # remove comments
								if line:
												filtered_lines.append(snake_case			)
				__magic_name__		:int   =   '''\n'''.join(snake_case			)

				# Make a hash from all this code
				__magic_name__		:Optional[int]   =   full_str.encode('''utf-8'''			)
				return shaaaa(snake_case			).hexdigest()


# get importable module names and hash for caching
SCREAMING_SNAKE_CASE__   :      Optional[int]				=		{
    """csv""": (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())),
    """json""": (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())),
    """pandas""": (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())),
    """parquet""": (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())),
    """arrow""": (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())),
    """text""": (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())),
    """imagefolder""": (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())),
    """audiofolder""": (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())),
}

# Used to infer the module to use based on the data files extensions
SCREAMING_SNAKE_CASE__   :      Dict				=		{
    """.csv""": ("""csv""", {}),
    """.tsv""": ("""csv""", {"""sep""": """\t"""}),
    """.json""": ("""json""", {}),
    """.jsonl""": ("""json""", {}),
    """.parquet""": ("""parquet""", {}),
    """.arrow""": ("""arrow""", {}),
    """.txt""": ("""text""", {}),
}
_EXTENSION_TO_MODULE.update({ext: ("""imagefolder""", {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ("""imagefolder""", {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext: ("""audiofolder""", {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ("""audiofolder""", {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		{"""imagefolder""", """audiofolder"""}

# Used to filter data files based on extensions given a module name
SCREAMING_SNAKE_CASE__   :      Dict[str, List[str]]				=		{}
for _ext, (_module, _) in _EXTENSION_TO_MODULE.items():
					_MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext)

_MODULE_TO_EXTENSIONS["imagefolder"].append(""".zip""")

_MODULE_TO_EXTENSIONS["audiofolder"].append(""".zip""")









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


					'''simple docstring'''






					def     __A     (					self     ):
						with tempfile.TemporaryDirectory() as tmpdirname:
							# pipeline has Flax weights
							A__				:       Optional[int]	  =						FlaxDiffusionPipeline.from_pretrained(
							    """hf-internal-testing/tiny-stable-diffusion-pipe"""       ,			safety_checker=A__       ,			cache_dir=A__     )

							A__				:       int	  =						[t[-1] for t in os.walk(os.path.join(A__       ,			os.listdir(A__     )[0]       ,			"""snapshots"""     )     )]
							A__				:       str	  =						[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        _a		(unittest.TestCase							):


					'''simple docstring'''






					def     __A     (					self     ):
						A__  ,  A__				:       Any	  =						FlaxStableDiffusionPipeline.from_pretrained(
						    """hf-internal-testing/tiny-stable-diffusion-pipe"""       ,			safety_checker=A__     )

						A__				:       Optional[int]	  =						(
						    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
						    """ field, close up, split lighting, cinematic"""
						)

						A__				:       Tuple	  =						jax.random.PRNGKey(0     )
						A__				:       int	  =						4

						A__				:       Optional[Any]	  =						jax.device_count()
						A__				:       Union[str, Any]	  =						num_samples * [prompt]
						A__				:       str	  =						pipeline.prepare_inputs(A__     )

						# shard inputs and rng
						A__				:       str	  =						replicate(A__     )
						A__				:       Any	  =						jax.random.split(A__       ,			A__     )
						A__				:       Optional[Any]	  =						shard(A__     )

						A__				:       int	  =						pipeline(A__       ,			A__       ,			A__       ,			A__       ,			jit=A__     ).images

						assert images.shape == (num_samples, 1, 64, 64, 3)
						if jax.device_count() == 8:
							assert np.abs(np.abs(images[0, 0, :2, :2, -2:]       ,			dtype=np.floataa     ).sum() - 4.1_5_1_4_7_4_5     ) < 1e-3
							assert np.abs(np.abs(A__       ,			dtype=np.floataa     ).sum() - 4_9_9_4_7.8_7_5     ) < 5e-1

						A__				:       str	  =						pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]     )     )     )
						assert len(A__     ) == num_samples






					def     __A     (					self     ):
						A__  ,  A__				:       Any	  =						FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4"""       ,			revision="""flax"""       ,			safety_checker=A__     )

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

						A__				:       Tuple	  =						jax.random.PRNGKey(0     )
						A__				:       Optional[Any]	  =						50

						A__				:       List[str]	  =						jax.device_count()
						A__				:       Dict	  =						num_samples * [prompt]
						A__				:       Union[str, Any]	  =						pipeline.prepare_inputs(A__     )

						# shard inputs and rng
						A__				:       int	  =						replicate(A__     )
						A__				:       List[str]	  =						jax.random.split(A__       ,			A__     )
						A__				:       Optional[Any]	  =						shard(A__     )

						A__				:       Optional[Any]	  =						pipeline(A__       ,			A__       ,			A__       ,			A__       ,			jit=A__     ).images

						assert images.shape == (num_samples, 1, 512, 512, 3)
						if jax.device_count() == 8:
							assert np.abs((np.abs(images[0, 0, :2, :2, -2:]       ,			dtype=np.floataa     ).sum() - 0.0_5_6_5_2_4_0_1)     ) < 1e-3
							assert np.abs((np.abs(A__       ,			dtype=np.floataa     ).sum() - 2_3_8_3_8_0_8.2)     ) < 5e-1






					def     __A     (					self     ):
						A__  ,  A__				:       int	  =						FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4"""       ,			revision="""bf16"""       ,			dtype=jnp.bfloataa       ,			safety_checker=A__     )

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

						A__				:       Dict	  =						jax.random.PRNGKey(0     )
						A__				:       str	  =						50

						A__				:       Any	  =						jax.device_count()
						A__				:       List[Any]	  =						num_samples * [prompt]
						A__				:       Any	  =						pipeline.prepare_inputs(A__     )

						# shard inputs and rng
						A__				:       Any	  =						replicate(A__     )
						A__				:       str	  =						jax.random.split(A__       ,			A__     )
						A__				:       Optional[Any]	  =						shard(A__     )

						A__				:       Dict	  =						pipeline(A__       ,			A__       ,			A__       ,			A__       ,			jit=A__     ).images

						assert images.shape == (num_samples, 1, 512, 512, 3)
						if jax.device_count() == 8:
							assert np.abs((np.abs(images[0, 0, :2, :2, -2:]       ,			dtype=np.floataa     ).sum() - 0.0_4_0_0_3_9_0_6)     ) < 1e-3
							assert np.abs((np.abs(A__       ,			dtype=np.floataa     ).sum() - 2_3_7_3_5_1_6.7_5)     ) < 5e-1






					def     __A     (					self     ):
						A__  ,  A__				:       Tuple	  =						FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4"""       ,			revision="""bf16"""       ,			dtype=jnp.bfloataa     )

						A__				:       List[str]	  =						(
						    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
						    """ field, close up, split lighting, cinematic"""
						)

						A__				:       int	  =						jax.random.PRNGKey(0     )
						A__				:       Optional[int]	  =						50

						A__				:       Optional[Any]	  =						jax.device_count()
						A__				:       Optional[int]	  =						num_samples * [prompt]
						A__				:       Optional[int]	  =						pipeline.prepare_inputs(A__     )

						# shard inputs and rng
						A__				:       Optional[int]	  =						replicate(A__     )
						A__				:       Tuple	  =						jax.random.split(A__       ,			A__     )
						A__				:       Optional[int]	  =						shard(A__     )

						A__				:       Optional[int]	  =						pipeline(A__       ,			A__       ,			A__       ,			A__       ,			jit=A__     ).images

						assert images.shape == (num_samples, 1, 512, 512, 3)
						if jax.device_count() == 8:
							assert np.abs((np.abs(images[0, 0, :2, :2, -2:]       ,			dtype=np.floataa     ).sum() - 0.0_4_0_0_3_9_0_6)     ) < 1e-3
							assert np.abs((np.abs(A__       ,			dtype=np.floataa     ).sum() - 2_3_7_3_5_1_6.7_5)     ) < 5e-1






					def     __A     (					self     ):
						A__				:       int	  =						FlaxDDIMScheduler(
						    beta_start=0.0_0_0_8_5       ,			beta_end=0.0_1_2       ,			beta_schedule="""scaled_linear"""       ,			set_alpha_to_one=A__       ,			steps_offset=1       ,			)

						A__  ,  A__				:       Tuple	  =						FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4"""       ,			revision="""bf16"""       ,			dtype=jnp.bfloataa       ,			scheduler=A__       ,			safety_checker=A__       ,			)
						A__				:       Union[str, Any]	  =						scheduler.create_state()

						A__				:       Optional[Any]	  =						scheduler_state

						A__				:       Union[str, Any]	  =						(
						    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
						    """ field, close up, split lighting, cinematic"""
						)

						A__				:       Tuple	  =						jax.random.PRNGKey(0     )
						A__				:       List[Any]	  =						50

						A__				:       Optional[int]	  =						jax.device_count()
						A__				:       Dict	  =						num_samples * [prompt]
						A__				:       List[Any]	  =						pipeline.prepare_inputs(A__     )

						# shard inputs and rng
						A__				:       Tuple	  =						replicate(A__     )
						A__				:       Dict	  =						jax.random.split(A__       ,			A__     )
						A__				:       Dict	  =						shard(A__     )

						A__				:       int	  =						pipeline(A__       ,			A__       ,			A__       ,			A__       ,			jit=A__     ).images

						assert images.shape == (num_samples, 1, 512, 512, 3)
						if jax.device_count() == 8:
							assert np.abs((np.abs(images[0, 0, :2, :2, -2:]       ,			dtype=np.floataa     ).sum() - 0.0_4_5_0_4_3_9_4_5)     ) < 1e-3
							assert np.abs((np.abs(A__       ,			dtype=np.floataa     ).sum() - 2_3_4_7_6_9_3.5)     ) < 5e-1






					def     __A     (					self     ):
						A__				:       Optional[int]	  =						(
						    """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"""
						    """ field, close up, split lighting, cinematic"""
						)

						A__				:       Optional[int]	  =						jax.device_count()
						A__				:       str	  =						num_samples * [prompt]
						A__				:       Any	  =						jax.random.split(jax.random.PRNGKey(0     )       ,			A__     )

						A__  ,  A__				:       Optional[Any]	  =						FlaxStableDiffusionPipeline.from_pretrained(
						    """CompVis/stable-diffusion-v1-4"""       ,			revision="""bf16"""       ,			dtype=jnp.bfloataa       ,			safety_checker=A__       ,			)

						A__				:       Tuple	  =						replicate(A__     )
						A__				:       Dict	  =						pipeline.prepare_inputs(A__     )
						A__				:       str	  =						shard(A__     )
						A__				:       Tuple	  =						pipeline(A__       ,			A__       ,			A__       ,			jit=A__     ).images
						assert images.shape == (num_samples, 1, 512, 512, 3)
						A__				:       Optional[Any]	  =						images[2, 0, 256, 10:17, 1]

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

						A__				:       Any	  =						replicate(A__     )
						A__				:       Optional[int]	  =						pipeline.prepare_inputs(A__     )
						A__				:       Dict	  =						shard(A__     )
						A__				:       Tuple	  =						pipeline(A__       ,			A__       ,			A__       ,			jit=A__     ).images
						assert images_eff.shape == (num_samples, 1, 512, 512, 3)
						A__				:       Union[str, Any]	  =						images[2, 0, 256, 10:17, 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



