



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      ):





   def        _snake_case    (self				):
      with tempfile.TemporaryDirectory() as tmpdirname:
         # pipeline has Flax weights
         lowerCamelCase__ :      List[Any]								=		FlaxDiffusionPipeline.from_pretrained(
             """hf-internal-testing/tiny-stable-diffusion-pipe"""							,    safety_checker=__magic_name__							,    cache_dir=__magic_name__				)

         lowerCamelCase__ :      Tuple								=		[t[-1] for t in os.walk(os.path.join(__magic_name__							,    os.listdir(__magic_name__				)[0]							,    """snapshots"""				)				)]
         lowerCamelCase__ :      Union[str, Any]								=		[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      ):





   def        _snake_case    (self				):
      lowerCamelCase__ :      Optional[int]								=		FlaxStableDiffusionPipeline.from_pretrained(
          """hf-internal-testing/tiny-stable-diffusion-pipe"""							,    safety_checker=__magic_name__				)

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

      lowerCamelCase__ :      Union[str, Any]								=		jax.random.PRNGKey(0				)
      lowerCamelCase__ :      str								=		4

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

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

      lowerCamelCase__ :      List[Any]								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).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_51_47_45				) < 1E-3
         assert np.abs(np.abs(__magic_name__							,    dtype=np.floataa				).sum() - 49947.875				) < 5E-1

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





   def        _snake_case    (self				):
      lowerCamelCase__ :      Union[str, Any]								=		FlaxStableDiffusionPipeline.from_pretrained(
          """CompVis/stable-diffusion-v1-4"""							,    revision="""flax"""							,    safety_checker=__magic_name__				)

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

      lowerCamelCase__ :      Dict								=		jax.random.PRNGKey(0				)
      lowerCamelCase__ :      List[str]								=		50

      lowerCamelCase__ :      str								=		jax.device_count()
      lowerCamelCase__ :      str								=		num_samples * [prompt]
      lowerCamelCase__ :      List[str]								=		pipeline.prepare_inputs(__magic_name__				)

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

      lowerCamelCase__ :      Optional[int]								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).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.05_65_24_01)				) < 1E-3
         assert np.abs((np.abs(__magic_name__							,    dtype=np.floataa				).sum() - 2383808.2)				) < 5E-1





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

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

      lowerCamelCase__ :      int								=		jax.random.PRNGKey(0				)
      lowerCamelCase__ :      List[Any]								=		50

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

      # shard inputs and rng
      lowerCamelCase__ :      Dict								=		replicate(__magic_name__				)
      lowerCamelCase__ :      str								=		jax.random.split(__magic_name__							,    __magic_name__				)
      lowerCamelCase__ :      Union[str, Any]								=		shard(__magic_name__				)

      lowerCamelCase__ :      int								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).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.04_00_39_06)				) < 1E-3
         assert np.abs((np.abs(__magic_name__							,    dtype=np.floataa				).sum() - 2373516.75)				) < 5E-1





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

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

      lowerCamelCase__ :      Union[str, Any]								=		jax.random.PRNGKey(0				)
      lowerCamelCase__ :      Union[str, Any]								=		50

      lowerCamelCase__ :      List[str]								=		jax.device_count()
      lowerCamelCase__ :      List[Any]								=		num_samples * [prompt]
      lowerCamelCase__ :      int								=		pipeline.prepare_inputs(__magic_name__				)

      # shard inputs and rng
      lowerCamelCase__ :      Dict								=		replicate(__magic_name__				)
      lowerCamelCase__ :      str								=		jax.random.split(__magic_name__							,    __magic_name__				)
      lowerCamelCase__ :      Any								=		shard(__magic_name__				)

      lowerCamelCase__ :      Optional[Any]								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).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.04_00_39_06)				) < 1E-3
         assert np.abs((np.abs(__magic_name__							,    dtype=np.floataa				).sum() - 2373516.75)				) < 5E-1





   def        _snake_case    (self				):
      lowerCamelCase__ :      str								=		FlaxDDIMScheduler(
          beta_start=0.0_00_85							,    beta_end=0.0_12							,    beta_schedule="""scaled_linear"""							,    set_alpha_to_one=__magic_name__							,    steps_offset=1							,    )

      lowerCamelCase__ :      Optional[int]								=		FlaxStableDiffusionPipeline.from_pretrained(
          """CompVis/stable-diffusion-v1-4"""							,    revision="""bf16"""							,    dtype=jnp.bfloataa							,    scheduler=__magic_name__							,    safety_checker=__magic_name__							,    )
      lowerCamelCase__ :      str								=		scheduler.create_state()

      lowerCamelCase__ :      Union[str, Any]								=		scheduler_state

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

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

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

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

      lowerCamelCase__ :      List[Any]								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).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_45_04_39_45)				) < 1E-3
         assert np.abs((np.abs(__magic_name__							,    dtype=np.floataa				).sum() - 2347693.5)				) < 5E-1





   def        _snake_case    (self				):
      lowerCamelCase__ :      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"""
      )

      lowerCamelCase__ :      Tuple								=		jax.device_count()
      lowerCamelCase__ :      Optional[int]								=		num_samples * [prompt]
      lowerCamelCase__ :      List[str]								=		jax.random.split(jax.random.PRNGKey(0				)							,    __magic_name__				)

      lowerCamelCase__ :      Dict								=		FlaxStableDiffusionPipeline.from_pretrained(
          """CompVis/stable-diffusion-v1-4"""							,    revision="""bf16"""							,    dtype=jnp.bfloataa							,    safety_checker=__magic_name__							,    )

      lowerCamelCase__ :      Union[str, Any]								=		replicate(__magic_name__				)
      lowerCamelCase__ :      int								=		pipeline.prepare_inputs(__magic_name__				)
      lowerCamelCase__ :      Optional[int]								=		shard(__magic_name__				)
      lowerCamelCase__ :      Optional[Any]								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).images
      assert images.shape == (num_samples, 1, 512, 512, 3)
      lowerCamelCase__ :      List[str]								=		images[2, 0, 256, 10:17, 1]

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

      lowerCamelCase__ :      int								=		replicate(__magic_name__				)
      lowerCamelCase__ :      int								=		pipeline.prepare_inputs(__magic_name__				)
      lowerCamelCase__ :      str								=		shard(__magic_name__				)
      lowerCamelCase__ :      Optional[Any]								=		pipeline(__magic_name__							,    __magic_name__							,    __magic_name__							,    jit=__magic_name__				).images
      assert images_eff.shape == (num_samples, 1, 512, 512, 3)
      lowerCamelCase__ :      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








from __future__ import annotations

import string
from itertools import cycle, product
from pathlib import Path

_lowercase     							=						(
    string.ascii_letters + string.digits + string.punctuation + string.whitespace
)
_lowercase     							=						[ord(letter) for letter in string.ascii_lowercase]
_lowercase     							=						{ord(char) for char in VALID_CHARS}

_lowercase     							=						["the", "be", "to", "of", "and", "in", "that", "have"]






def      _A				(UpperCamelCase		:      list[int]      ,			UpperCamelCase		:      tuple[int, ...] )  ->str | None:



			'''simple docstring'''







			lowerCamelCase__ :      str								=		""
			lowerCamelCase__ :      int
			lowerCamelCase__ :      int
			lowerCamelCase__ :      int

			for keychar, cipherchar in zip(cycle(UpperCamelCase )      ,			UpperCamelCase ):
						lowerCamelCase__ :      str								=		cipherchar ^ keychar
						if decodedchar not in VALID_INTS:
									return None
						decoded += chr(UpperCamelCase )

			return decoded






def      _A				(UpperCamelCase		:      list[int] )  ->list[str]:



			'''simple docstring'''







			lowerCamelCase__ :      list[str]								=		[]
			for key in product(UpperCamelCase      ,			repeat=3 ):
						lowerCamelCase__ :      Union[str, Any]								=		try_key(UpperCamelCase      ,			UpperCamelCase )
						if encoded is not None:
									possibles.append(UpperCamelCase )
			return possibles






def      _A				(UpperCamelCase		:      list[str]      ,			UpperCamelCase		:      str )  ->list[str]:



			'''simple docstring'''







			return [possible for possible in possibles if common_word in possible.lower()]






def      _A				(UpperCamelCase		:      str = "p059_cipher.txt" )  ->int:



			'''simple docstring'''







			lowerCamelCase__ :      list[int]
			lowerCamelCase__ :      list[str]
			lowerCamelCase__ :      str
			lowerCamelCase__ :      str
			lowerCamelCase__ :      str								=		Path(UpperCamelCase ).parent.joinpath(UpperCamelCase ).read_text(encoding="""utf-8""" )

			lowerCamelCase__ :      str								=		[int(UpperCamelCase ) for number in data.strip().split(""",""" )]

			lowerCamelCase__ :      Optional[Any]								=		filter_valid_chars(UpperCamelCase )
			for common_word in COMMON_WORDS:
						lowerCamelCase__ :      Optional[int]								=		filter_common_word(UpperCamelCase      ,			UpperCamelCase )
						if len(UpperCamelCase ) == 1:
									break

			lowerCamelCase__ :      Union[str, Any]								=		possibles[0]
			return sum(ord(UpperCamelCase ) for char in decoded_text )


if __name__ == "__main__":
				print(F'''{solution() = }''')



