

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




  """simple docstring"""




  def       SCREAMING_SNAKE_CASE   (   self     :  Dict    ):
   with tempfile.TemporaryDirectory() as tmpdirname:
    # pipeline has Flax weights
    __lowercase													=				FlaxDiffusionPipeline.from_pretrained(
        '''hf-internal-testing/tiny-stable-diffusion-pipe'''      ,safety_checker=lowercase__      ,cache_dir=lowercase__    )

    __lowercase													=				[t[-1] for t in os.walk(os.path.join(lowercase__      ,os.listdir(lowercase__    )[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     lowercase_			(unittest.TestCase   ):




  """simple docstring"""




  def       SCREAMING_SNAKE_CASE   (   self     :  List[str]    ):
   __lowercase						,			__lowercase													=				FlaxStableDiffusionPipeline.from_pretrained(
       '''hf-internal-testing/tiny-stable-diffusion-pipe'''      ,safety_checker=lowercase__    )

   __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(lowercase__    )

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

   __lowercase													=				pipeline(lowercase__      ,lowercase__      ,lowercase__      ,lowercase__      ,jit=lowercase__    ).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_5_1_4_7_4_5    ) < 1e-3
    assert np.abs(np.abs(lowercase__      ,dtype=np.floataa    ).sum() - 4_9_9_4_7.8_7_5    ) < 5e-1

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






  def       SCREAMING_SNAKE_CASE   (   self     :  Any    ):
   __lowercase						,			__lowercase													=				FlaxStableDiffusionPipeline.from_pretrained(
       '''CompVis/stable-diffusion-v1-4'''      ,revision='''flax'''      ,safety_checker=lowercase__    )

   __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(lowercase__    )

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

   __lowercase													=				pipeline(lowercase__      ,lowercase__      ,lowercase__      ,lowercase__      ,jit=lowercase__    ).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_5_6_5_2_4_0_1)    ) < 1e-3
    assert np.abs((np.abs(lowercase__      ,dtype=np.floataa    ).sum() - 2_3_8_3_8_0_8.2)    ) < 5e-1






  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   __lowercase						,			__lowercase													=				FlaxStableDiffusionPipeline.from_pretrained(
       '''CompVis/stable-diffusion-v1-4'''      ,revision='''bf16'''      ,dtype=jnp.bfloataa      ,safety_checker=lowercase__    )

   __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(lowercase__    )

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

   __lowercase													=				pipeline(lowercase__      ,lowercase__      ,lowercase__      ,lowercase__      ,jit=lowercase__    ).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_4_0_0_3_9_0_6)    ) < 1e-3
    assert np.abs((np.abs(lowercase__      ,dtype=np.floataa    ).sum() - 2_3_7_3_5_1_6.7_5)    ) < 5e-1






  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[Any]    ):
   __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(lowercase__    )

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

   __lowercase													=				pipeline(lowercase__      ,lowercase__      ,lowercase__      ,lowercase__      ,jit=lowercase__    ).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_4_0_0_3_9_0_6)    ) < 1e-3
    assert np.abs((np.abs(lowercase__      ,dtype=np.floataa    ).sum() - 2_3_7_3_5_1_6.7_5)    ) < 5e-1






  def       SCREAMING_SNAKE_CASE   (   self     :  Dict    ):
   __lowercase													=				FlaxDDIMScheduler(
       beta_start=0.0_0_0_8_5      ,beta_end=0.0_1_2      ,beta_schedule='''scaled_linear'''      ,set_alpha_to_one=lowercase__      ,steps_offset=1      ,)

   __lowercase						,			__lowercase													=				FlaxStableDiffusionPipeline.from_pretrained(
       '''CompVis/stable-diffusion-v1-4'''      ,revision='''bf16'''      ,dtype=jnp.bfloataa      ,scheduler=lowercase__      ,safety_checker=lowercase__      ,)
   __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(lowercase__    )

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

   __lowercase													=				pipeline(lowercase__      ,lowercase__      ,lowercase__      ,lowercase__      ,jit=lowercase__    ).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_4_5_0_4_3_9_4_5)    ) < 1e-3
    assert np.abs((np.abs(lowercase__      ,dtype=np.floataa    ).sum() - 2_3_4_7_6_9_3.5)    ) < 5e-1






  def       SCREAMING_SNAKE_CASE   (   self     :  Union[str, Any]    ):
   __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    )      ,lowercase__    )

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

   __lowercase													=				replicate(lowercase__    )
   __lowercase													=				pipeline.prepare_inputs(lowercase__    )
   __lowercase													=				shard(lowercase__    )
   __lowercase													=				pipeline(lowercase__      ,lowercase__      ,lowercase__      ,jit=lowercase__    ).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=lowercase__      ,use_memory_efficient_attention=lowercase__      ,)

   __lowercase													=				replicate(lowercase__    )
   __lowercase													=				pipeline.prepare_inputs(lowercase__    )
   __lowercase													=				shard(lowercase__    )
   __lowercase													=				pipeline(lowercase__      ,lowercase__      ,lowercase__      ,jit=lowercase__    ).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 hashlib
import unittest

from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available
from transformers.pipelines import DepthEstimationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image
else:






 class     lowercase_			:




   """simple docstring"""




   @staticmethod
   def       SCREAMING_SNAKE_CASE   (   *lowercase__     :  Union[str, Any]      ,**lowercase__     :  Tuple    ):
    pass


def 	_A  (					A__   ):






 """simple docstring"""



 __lowercase													=				hashlib.mda(image.tobytes()   )
 return m.hexdigest()






@is_pipeline_test
@require_vision
@require_timm
@require_torch
class     lowercase_			(unittest.TestCase   ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE					:						Optional[Any]           =    MODEL_FOR_DEPTH_ESTIMATION_MAPPING






  def       SCREAMING_SNAKE_CASE   (   self     :  List[Any]      ,lowercase__     :  int      ,lowercase__     :  List[str]      ,lowercase__     :  int    ):
   __lowercase													=				DepthEstimationPipeline(model=lowercase__      ,image_processor=lowercase__    )
   return depth_estimator, [
       "./tests/fixtures/tests_samples/COCO/000000039769.png",
       "./tests/fixtures/tests_samples/COCO/000000039769.png",
   ]






  def       SCREAMING_SNAKE_CASE   (   self     :  List[Any]      ,lowercase__     :  List[str]      ,lowercase__     :  List[str]    ):
   __lowercase													=				depth_estimator('''./tests/fixtures/tests_samples/COCO/000000039769.png'''    )
   self.assertEqual({'''predicted_depth''': ANY(torch.Tensor    ), '''depth''': ANY(Image.Image    )}      ,lowercase__    )
   import datasets

   __lowercase													=				datasets.load_dataset('''hf-internal-testing/fixtures_image_utils'''      ,'''image'''      ,split='''test'''    )
   __lowercase													=				depth_estimator(
       [
           Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''    ),
           '''http://images.cocodataset.org/val2017/000000039769.jpg''',
           # RGBA
           dataset[0]['''file'''],
           # LA
           dataset[1]['''file'''],
           # L
           dataset[2]['''file'''],
       ]    )
   self.assertEqual(
       [
           {'''predicted_depth''': ANY(torch.Tensor    ), '''depth''': ANY(Image.Image    )},
           {'''predicted_depth''': ANY(torch.Tensor    ), '''depth''': ANY(Image.Image    )},
           {'''predicted_depth''': ANY(torch.Tensor    ), '''depth''': ANY(Image.Image    )},
           {'''predicted_depth''': ANY(torch.Tensor    ), '''depth''': ANY(Image.Image    )},
           {'''predicted_depth''': ANY(torch.Tensor    ), '''depth''': ANY(Image.Image    )},
       ]      ,lowercase__      ,)






  @require_tf
  @unittest.skip('''Depth estimation is not implemented in TF'''    )
  def       SCREAMING_SNAKE_CASE   (   self     :  Dict    ):
   pass






  @slow
  @require_torch
  def       SCREAMING_SNAKE_CASE   (   self     :  List[str]    ):
   __lowercase													=				'''Intel/dpt-large'''
   __lowercase													=				pipeline('''depth-estimation'''      ,model=lowercase__    )
   __lowercase													=				depth_estimator('''http://images.cocodataset.org/val2017/000000039769.jpg'''    )
   __lowercase													=				hashimage(outputs['''depth''']    )

   # This seems flaky.
   # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977")
   self.assertEqual(nested_simplify(outputs['''predicted_depth'''].max().item()    )      ,2_9.3_0_4    )
   self.assertEqual(nested_simplify(outputs['''predicted_depth'''].min().item()    )      ,2.6_6_2    )






  @require_torch
  def       SCREAMING_SNAKE_CASE   (   self     :  List[Any]    ):
   # This is highly irregular to have no small tests.
   self.skipTest('''There is not hf-internal-testing tiny model for either GLPN nor DPT'''    )

