




"""simple docstring"""


import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


A_									=       False






class       lowercase(  unittest.TestCase				):







 '''simple docstring'''





 pass







@nightly
@require_torch_gpu
class       lowercase(  unittest.TestCase				):







 '''simple docstring'''





 def 				UpperCamelCase_     (       self:	Union[str, Any]	):




   '''simple docstring'''



   super().tearDown()
   gc.collect()
   torch.cuda.empty_cache()


 def 				UpperCamelCase_     (       self:	Dict	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						VersatileDiffusionPipeline.from_pretrained("""shi-labs/versatile-diffusion""",   torch_dtype=torch.floataa	)
   pipe.to(a_	)
   pipe.set_progress_bar_config(disable=a_	)

   _snake_case							:	Union[str, Any]			=						load_image(
       """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"""	)

   _snake_case							:	Tuple			=						torch.manual_seed(0	)
   _snake_case							:	Dict			=						pipe.dual_guided(
       prompt="""first prompt""",   image=a_,   text_to_image_strength=0.75,   generator=a_,   guidance_scale=7.5,   num_inference_steps=2,   output_type="""numpy""",   ).images

   with tempfile.TemporaryDirectory() as tmpdirname:
     pipe.save_pretrained(a_	)
     _snake_case							:	str			=						VersatileDiffusionPipeline.from_pretrained(a_,   torch_dtype=torch.floataa	)
   pipe.to(a_	)
   pipe.set_progress_bar_config(disable=a_	)

   _snake_case							:	int			=						generator.manual_seed(0	)
   _snake_case							:	int			=						pipe.dual_guided(
       prompt="""first prompt""",   image=a_,   text_to_image_strength=0.75,   generator=a_,   guidance_scale=7.5,   num_inference_steps=2,   output_type="""numpy""",   ).images

   assert np.abs(image - new_image	).sum() < 1E-5, "Models don't have the same forward pass"


 def 				UpperCamelCase_     (       self:	Any	):




   '''simple docstring'''



   _snake_case							:	List[str]			=						VersatileDiffusionPipeline.from_pretrained("""shi-labs/versatile-diffusion""",   torch_dtype=torch.floataa	)
   pipe.to(a_	)
   pipe.set_progress_bar_config(disable=a_	)

   _snake_case							:	Optional[Any]			=						"""cyberpunk 2077"""
   _snake_case							:	List[Any]			=						load_image(
       """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"""	)
   _snake_case							:	str			=						torch.manual_seed(0	)
   _snake_case							:	Tuple			=						pipe.dual_guided(
       prompt=a_,   image=a_,   text_to_image_strength=0.75,   generator=a_,   guidance_scale=7.5,   num_inference_steps=50,   output_type="""numpy""",   ).images

   _snake_case							:	Tuple			=						image[0, 253:256, 253:256, -1]

   assert image.shape == (1, 512, 512, 3)
   _snake_case							:	Dict			=						np.array([0.1_448, 0.1_619, 0.1_741, 0.1_086, 0.1_147, 0.1_128, 0.1_199, 0.1_165, 0.1_001]	)

   assert np.abs(image_slice.flatten() - expected_slice	).max() < 1E-1

   _snake_case							:	Optional[int]			=						"""A painting of a squirrel eating a burger """
   _snake_case							:	Tuple			=						torch.manual_seed(0	)
   _snake_case							:	Dict			=						pipe.text_to_image(
       prompt=a_,   generator=a_,   guidance_scale=7.5,   num_inference_steps=50,   output_type="""numpy"""	).images

   _snake_case							:	Dict			=						image[0, 253:256, 253:256, -1]

   assert image.shape == (1, 512, 512, 3)
   _snake_case							:	str			=						np.array([0.3_367, 0.3_169, 0.2_656, 0.3_870, 0.4_790, 0.3_796, 0.4_009, 0.4_878, 0.4_778]	)

   assert np.abs(image_slice.flatten() - expected_slice	).max() < 1E-1

   _snake_case							:	List[Any]			=						pipe.image_variation(a_,   generator=a_,   output_type="""numpy"""	).images

   _snake_case							:	Optional[int]			=						image[0, 253:256, 253:256, -1]

   assert image.shape == (1, 512, 512, 3)
   _snake_case							:	Any			=						np.array([0.3_076, 0.3_123, 0.3_284, 0.3_782, 0.3_770, 0.3_894, 0.4_297, 0.4_331, 0.4_456]	)

   assert np.abs(image_slice.flatten() - expected_slice	).max() < 1E-1








"""simple docstring"""


import os
import sys
import unittest


A_      			=       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_      			=       os.path.join(git_repo_path, '''src''', '''diffusers''')






class       lowercase(  unittest.TestCase				):







 '''simple docstring'''





 def 				UpperCamelCase_     (       self:	Tuple	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						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")

   _snake_case							:	Any			=						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")

   _snake_case							:	Union[str, Any]			=						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[Any]	):




   '''simple docstring'''



   _snake_case							:	Dict			=						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:	List[str]	):




   '''simple docstring'''



   _snake_case							:	Optional[Any]			=						create_dummy_object("""CONSTANT""",   """'torch'"""	)
   self.assertEqual(a_,   """\nCONSTANT = None\n"""	)

   _snake_case							:	Optional[int]			=						create_dummy_object("""function""",   """'torch'"""	)
   self.assertEqual(
       a_,   """\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""	)

   _snake_case							:	List[Any]			=						"""
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')
"""
   _snake_case							:	Union[str, Any]			=						create_dummy_object("""FakeClass""",   """'torch'"""	)
   self.assertEqual(a_,   a_	)


 def 				UpperCamelCase_     (       self:	Union[str, Any]	):




   '''simple docstring'''



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


