'''simple docstring'''





import importlib
import inspect
import json
import os
import re
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional, Union
from urllib import request

from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
from packaging import version

from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging


SCREAMING_SNAKE_CASE :	Dict							     =		(
    'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py'
)


SCREAMING_SNAKE_CASE :	Any							     =		logging.get_logger(__name__)  # pylint: disable=invalid-name



def   __A		(			):



 """simple docstring"""


 __a       =  '''https://pypi.org/pypi/diffusers/json'''
 __a       =  json.loads(request.urlopen(__UpperCamelCase					).read()					)['''releases'''].keys()
 return sorted(__UpperCamelCase							,				key=lambda _A					: version.Version(__UpperCamelCase					)					)



def   __A		(			):



 """simple docstring"""


 if HF_MODULES_CACHE in sys.path:
  return

 sys.path.append(__UpperCamelCase					)
 os.makedirs(__UpperCamelCase							,				exist_ok=__UpperCamelCase					)
 __a       =  Path(__UpperCamelCase					) / '''__init__.py'''
 if not init_path.exists():
  init_path.touch()



def   __A		(			_A					):



 """simple docstring"""


 init_hf_modules()
 __a       =  Path(__UpperCamelCase					) / name
 # If the parent module does not exist yet, recursively create it.
 if not dynamic_module_path.parent.exists():
  create_dynamic_module(dynamic_module_path.parent					)
 os.makedirs(__UpperCamelCase							,				exist_ok=__UpperCamelCase					)
 __a       =  dynamic_module_path / '''__init__.py'''
 if not init_path.exists():
  init_path.touch()



def   __A		(			_A					):



 """simple docstring"""


 with open(__UpperCamelCase							,				"r"							,				encoding="utf-8"					) as f:
  __a       =  f.read()

 # Imports of the form `import .xxx`
 __a       =  re.findall("^\s*import\s+\.(\S+)\s*$"							,				__UpperCamelCase							,				flags=re.MULTILINE					)
 # Imports of the form `from .xxx import yyy`
 relative_imports += re.findall("^\s*from\s+\.(\S+)\s+import"							,				__UpperCamelCase							,				flags=re.MULTILINE					)
 # Unique-ify
 return list(set(__UpperCamelCase					)					)



def   __A		(			_A					):



 """simple docstring"""


 __a       =  False
 __a       =  [module_file]
 __a       =  []

 # Let's recurse through all relative imports
 while not no_change:
  __a       =  []
  for f in files_to_check:
   new_imports.extend(get_relative_imports(__UpperCamelCase					)					)

  __a       =  Path(__UpperCamelCase					).parent
  __a       =  [str(module_path / m					) for m in new_imports]
  __a       =  [f for f in new_import_files if f not in all_relative_imports]
  __a       =  [f"""{f}.py""" for f in new_import_files]

  __a       =  len(__UpperCamelCase					) == 0
  all_relative_imports.extend(__UpperCamelCase					)

 return all_relative_imports



def   __A		(			_A					):



 """simple docstring"""


 with open(__UpperCamelCase							,				"r"							,				encoding="utf-8"					) as f:
  __a       =  f.read()

 # Imports of the form `import xxx`
 __a       =  re.findall("^\s*import\s+(\S+)\s*$"							,				__UpperCamelCase							,				flags=re.MULTILINE					)
 # Imports of the form `from xxx import yyy`
 imports += re.findall("^\s*from\s+(\S+)\s+import"							,				__UpperCamelCase							,				flags=re.MULTILINE					)
 # Only keep the top-level module
 __a       =  [imp.split("."					)[0] for imp in imports if not imp.startswith("."					)]

 # Unique-ify and test we got them all
 __a       =  list(set(__UpperCamelCase					)					)
 __a       =  []
 for imp in imports:
  try:
   importlib.import_module(__UpperCamelCase					)
  except ImportError:
   missing_packages.append(__UpperCamelCase					)

 if len(__UpperCamelCase					) > 0:
  raise ImportError(
      "This modeling file requires the following packages that were not found in your environment: "
      f"""{", ".join(__UpperCamelCase					)}. Run `pip install {" ".join(__UpperCamelCase					)}`"""					)

 return get_relative_imports(__UpperCamelCase					)



def   __A		(			_A							,				_A					):



 """simple docstring"""


 __a       =  module_path.replace(os.path.sep							,				"."					)
 __a       =  importlib.import_module(__UpperCamelCase					)

 if class_name is None:
  return find_pipeline_class(__UpperCamelCase					)
 return getattr(__UpperCamelCase							,				__UpperCamelCase					)



def   __A		(			_A					):



 """simple docstring"""


 from ..pipelines import DiffusionPipeline

 __a       =  dict(inspect.getmembers(__UpperCamelCase							,				inspect.isclass					)					)

 __a       =  None
 for cls_name, cls in cls_members.items():
  if (
      cls_name != DiffusionPipeline.__name__
      and issubclass(cls							,				__UpperCamelCase					)
      and cls.__module__.split("."					)[0] != "diffusers"
  ):
   if pipeline_class is not None:
    raise ValueError(
        f"""Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:"""
        f""" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in"""
        f""" {loaded_module}."""					)
   __a       =  cls

 return pipeline_class



def   __A		(			_A							,				_A							,				_A = None							,				_A = False							,				_A = False							,				_A = None							,				_A = None							,				_A = None							,				_A = False							,				):



 """simple docstring"""


 __a       =  str(__UpperCamelCase					)

 __a       =  os.path.join(__UpperCamelCase							,				__UpperCamelCase					)

 if os.path.isfile(__UpperCamelCase					):
  __a       =  module_file_or_url
  __a       =  '''local'''
 elif pretrained_model_name_or_path.count("/"					) == 0:
  __a       =  get_diffusers_versions()
  # cut ".dev0"
  __a       =  '''v''' + '''.'''.join(__version__.split("."					)[:3]					)

  # retrieve github version that matches
  if revision is None:
   __a       =  latest_version if latest_version[1:] in available_versions else '''main'''
   logger.info(f"""Defaulting to latest_version: {revision}."""					)
  elif revision in available_versions:
   __a       =  f"""v{revision}"""
  elif revision == "main":
   __a       =  revision
  else:
   raise ValueError(
       f"""`custom_revision`: {revision} does not exist. Please make sure to choose one of"""
       f""" {", ".join(available_versions + ["main"]					)}."""					)

  # community pipeline on GitHub
  __a       =  COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase							,				pipeline=__UpperCamelCase					)
  try:
   __a       =  cached_download(
       __UpperCamelCase							,				cache_dir=__UpperCamelCase							,				force_download=__UpperCamelCase							,				proxies=__UpperCamelCase							,				resume_download=__UpperCamelCase							,				local_files_only=__UpperCamelCase							,				use_auth_token=__UpperCamelCase							,				)
   __a       =  '''git'''
   __a       =  pretrained_model_name_or_path + '''.py'''
  except EnvironmentError:
   logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}."""					)
   raise
 else:
  try:
   # Load from URL or cache if already cached
   __a       =  hf_hub_download(
       __UpperCamelCase							,				__UpperCamelCase							,				cache_dir=__UpperCamelCase							,				force_download=__UpperCamelCase							,				proxies=__UpperCamelCase							,				resume_download=__UpperCamelCase							,				local_files_only=__UpperCamelCase							,				use_auth_token=__UpperCamelCase							,				)
   __a       =  os.path.join("local"							,				"--".join(pretrained_model_name_or_path.split("/"					)					)					)
  except EnvironmentError:
   logger.error(f"""Could not locate the {module_file} inside {pretrained_model_name_or_path}."""					)
   raise

    # Check we have all the requirements in our environment
 __a       =  check_imports(__UpperCamelCase					)

 # Now we move the module inside our cached dynamic modules.
 __a       =  DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
 create_dynamic_module(__UpperCamelCase					)
 __a       =  Path(__UpperCamelCase					) / full_submodule
 if submodule == "local" or submodule == "git":
  # We always copy local files (we could hash the file to see if there was a change, and give them the name of
  # that hash, to only copy when there is a modification but it seems overkill for now).
  # The only reason we do the copy is to avoid putting too many folders in sys.path.
  shutil.copy(__UpperCamelCase							,				submodule_path / module_file					)
  for module_needed in modules_needed:
   __a       =  f"""{module_needed}.py"""
   shutil.copy(os.path.join(__UpperCamelCase							,				__UpperCamelCase					)							,				submodule_path / module_needed					)
 else:
  # Get the commit hash
  # TODO: we will get this info in the etag soon, so retrieve it from there and not here.
  if isinstance(__UpperCamelCase							,				__UpperCamelCase					):
   __a       =  use_auth_token
  elif use_auth_token is True:
   __a       =  HfFolder.get_token()
  else:
   __a       =  None

  __a       =  model_info(__UpperCamelCase							,				revision=__UpperCamelCase							,				token=__UpperCamelCase					).sha

  # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
  # benefit of versioning.
  __a       =  submodule_path / commit_hash
  __a       =  full_submodule + os.path.sep + commit_hash
  create_dynamic_module(__UpperCamelCase					)

  if not (submodule_path / module_file).exists():
   shutil.copy(__UpperCamelCase							,				submodule_path / module_file					)
  # Make sure we also have every file with relative
  for module_needed in modules_needed:
   if not (submodule_path / module_needed).exists():
    get_cached_module_file(
        __UpperCamelCase							,				f"""{module_needed}.py"""							,				cache_dir=__UpperCamelCase							,				force_download=__UpperCamelCase							,				resume_download=__UpperCamelCase							,				proxies=__UpperCamelCase							,				use_auth_token=__UpperCamelCase							,				revision=__UpperCamelCase							,				local_files_only=__UpperCamelCase							,				)
 return os.path.join(__UpperCamelCase							,				__UpperCamelCase					)






def   __A		(			_A							,				_A							,				_A = None							,				_A = None							,				_A = False							,				_A = False							,				_A = None							,				_A = None							,				_A = None							,				_A = False							,				**_A							,				):



 """simple docstring"""


 __a       =  get_cached_module_file(
     __UpperCamelCase							,				__UpperCamelCase							,				cache_dir=__UpperCamelCase							,				force_download=__UpperCamelCase							,				resume_download=__UpperCamelCase							,				proxies=__UpperCamelCase							,				use_auth_token=__UpperCamelCase							,				revision=__UpperCamelCase							,				local_files_only=__UpperCamelCase							,				)
 return get_class_in_module(__UpperCamelCase							,				final_module.replace(".py"							,				""					)					)



import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()
class    A_ (       unittest.TestCase ):

  @property
  def 		_UpperCAmelCase   (		self :      str       ):
   torch.manual_seed(0       )
   __a       =  UNetaDModel(
       block_out_channels=(32, 64)     ,							layers_per_block=2     ,							sample_size=32     ,							in_channels=3     ,							out_channels=3     ,							down_block_types=("DownBlock2D", "AttnDownBlock2D")     ,							up_block_types=("AttnUpBlock2D", "UpBlock2D")     ,							)
   return model

  @property
  def 		_UpperCAmelCase   (		self :      Dict       ):
   torch.manual_seed(0       )
   __a       =  VQModel(
       block_out_channels=[32, 64]     ,							in_channels=3     ,							out_channels=3     ,							down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]     ,							up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]     ,							latent_channels=3     ,							)
   return model

  @property
  def 		_UpperCAmelCase   (		self :      Optional[Any]       ):
   torch.manual_seed(0       )
   __a       =  CLIPTextConfig(
       bos_token_id=0     ,							eos_token_id=2     ,							hidden_size=32     ,							intermediate_size=37     ,							layer_norm_eps=1E-05     ,							num_attention_heads=4     ,							num_hidden_layers=5     ,							pad_token_id=1     ,							vocab_size=10_00     ,							)
   return CLIPTextModel(__SCREAMING_SNAKE_CASE       )

  def 		_UpperCAmelCase   (		self :      Dict       ):
   __a       =  self.dummy_uncond_unet
   __a       =  DDIMScheduler()
   __a       =  self.dummy_vq_model

   __a       =  LDMPipeline(unet=__SCREAMING_SNAKE_CASE     ,							vqvae=__SCREAMING_SNAKE_CASE     ,							scheduler=__SCREAMING_SNAKE_CASE       )
   ldm.to(__SCREAMING_SNAKE_CASE       )
   ldm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE       )

   __a       =  torch.manual_seed(0       )
   __a       =  ldm(generator=__SCREAMING_SNAKE_CASE     ,							num_inference_steps=2     ,							output_type="numpy"       ).images

   __a       =  torch.manual_seed(0       )
   __a       =  ldm(generator=__SCREAMING_SNAKE_CASE     ,							num_inference_steps=2     ,							output_type="numpy"     ,							return_dict=__SCREAMING_SNAKE_CASE       )[0]

   __a       =  image[0, -3:, -3:, -1]
   __a       =  image_from_tuple[0, -3:, -3:, -1]

   assert image.shape == (1, 64, 64, 3)
   __a       =  np.array([0.85_12, 0.8_18, 0.64_11, 0.68_08, 0.44_65, 0.56_18, 0.46, 0.62_31, 0.51_72]       )
   __a       =  1E-2 if torch_device != "mps" else 3E-2

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance
   assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < tolerance
@slow
@require_torch
class    A_ (       unittest.TestCase ):

  def 		_UpperCAmelCase   (		self :      str       ):
   __a       =  LDMPipeline.from_pretrained("CompVis/ldm-celebahq-256"       )
   ldm.to(__SCREAMING_SNAKE_CASE       )
   ldm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE       )

   __a       =  torch.manual_seed(0       )
   __a       =  ldm(generator=__SCREAMING_SNAKE_CASE     ,							num_inference_steps=5     ,							output_type="numpy"       ).images

   __a       =  image[0, -3:, -3:, -1]

   assert image.shape == (1, 2_56, 2_56, 3)
   __a       =  np.array([0.43_99, 0.4_49_75, 0.4_68_25, 0.4_74, 0.43_59, 0.45_81, 0.4_50_95, 0.43_41, 0.44_47]       )
   __a       =  1E-2 if torch_device != "mps" else 3E-2

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


