






"""simple docstring"""


import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    PNDMScheduler,
    StableDiffusionLDMaDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS


enable_full_determinism()






class 						snake_case  (  unittest.TestCase	):
    __magic_name__   					=					StableDiffusionLDMaDPipeline
    __magic_name__   					=					TEXT_TO_IMAGE_PARAMS
    __magic_name__   					=					TEXT_TO_IMAGE_BATCH_PARAMS
    __magic_name__   					=					TEXT_TO_IMAGE_IMAGE_PARAMS





    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      torch.manual_seed(0      )
      a					:      str    =       UNetaDConditionModel(
          block_out_channels=(3_2, 6_4)    ,		layers_per_block=2    ,		sample_size=3_2    ,		in_channels=4    ,		out_channels=4    ,		down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')    ,		up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')    ,		cross_attention_dim=3_2    ,		)
      a					:      Tuple    =       DDIMScheduler(
          beta_start=0.0_00_85    ,		beta_end=0.0_12    ,		beta_schedule='scaled_linear'    ,		clip_sample=A    ,		set_alpha_to_one=A    ,		)
      torch.manual_seed(0      )
      a					:      Dict    =       AutoencoderKL(
          block_out_channels=[3_2, 6_4]    ,		in_channels=6    ,		out_channels=6    ,		down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']    ,		up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']    ,		latent_channels=4    ,		)
      torch.manual_seed(0      )
      a					:      Tuple    =       CLIPTextConfig(
          bos_token_id=0    ,		eos_token_id=2    ,		hidden_size=3_2    ,		intermediate_size=3_7    ,		layer_norm_eps=1E-05    ,		num_attention_heads=4    ,		num_hidden_layers=5    ,		pad_token_id=1    ,		vocab_size=1_0_0_0    ,		)
      a					:      Optional[int]    =       CLIPTextModel(A      )
      a					:      List[str]    =       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

      a					:      Optional[Any]    =       {
          'unet': unet,
          'scheduler': scheduler,
          'vae': vae,
          'text_encoder': text_encoder,
          'tokenizer': tokenizer,
          'safety_checker': None,
          'feature_extractor': None,
      }
      return components





    def     lowerCamelCase__				(							self     : Tuple    ,		A     : int    ,		A     : int=0      ):


      '''simple docstring'''




      if str(A      ).startswith('mps'      ):
        a					:      Optional[int]    =       torch.manual_seed(A      )
      else:
        a					:      Optional[int]    =       torch.Generator(device=A      ).manual_seed(A      )
      a					:      Optional[Any]    =       {
          'prompt': 'A painting of a squirrel eating a burger',
          'generator': generator,
          'num_inference_steps': 2,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs





    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      a					:      Tuple    =       'cpu'  # ensure determinism for the device-dependent torch.Generator

      a					:      Optional[Any]    =       self.get_dummy_components()
      a					:      List[Any]    =       StableDiffusionLDMaDPipeline(**A      )
      a					:      List[Any]    =       ldmad_pipe.to(A      )
      ldmad_pipe.set_progress_bar_config(disable=A      )

      a					:      Optional[int]    =       self.get_dummy_inputs(A      )
      a					:      Union[str, Any]    =       ldmad_pipe(**A      )
      a,					a					:      int    =       output.rgb, output.depth

      a					:      Any    =       rgb[0, -3:, -3:, -1]
      a					:      List[Any]    =       depth[0, -3:, -1]

      assert rgb.shape == (1, 6_4, 6_4, 3)
      assert depth.shape == (1, 6_4, 6_4)

      a					:      Union[str, Any]    =       np.array(
          [0.37_33_81_76, 0.7_02_47, 0.74_20_31_93, 0.51_64_36_04, 0.58_25_67_93, 0.60_93_21_36, 0.4_18_10_95, 0.48_35_58_77, 0.46_53_52_62]      )
      a					:      Union[str, Any]    =       np.array([1_03.4_67_27, 85.81_20_04, 87.84_92_36]      )

      assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb      ).max() < 1E-2
      assert np.abs(image_slice_depth.flatten() - expected_slice_depth      ).max() < 1E-2





    def     lowerCamelCase__				(							self     : Tuple      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       self.get_dummy_components()
      a					:      Dict    =       StableDiffusionLDMaDPipeline(**A      )
      a					:      Dict    =       ldmad_pipe.to(A      )
      ldmad_pipe.set_progress_bar_config(disable=A      )

      a					:      Dict    =       self.get_dummy_inputs(A      )
      a					:      Tuple    =       3 * [inputs['prompt']]

      # forward
      a					:      Dict    =       ldmad_pipe(**A      )
      a,					a					:      Optional[int]    =       output.rgb, output.depth
      a					:      Tuple    =       rgb_slice_a[0, -3:, -3:, -1]
      a					:      Dict    =       depth_slice_a[0, -3:, -1]

      a					:      str    =       self.get_dummy_inputs(A      )
      a					:      str    =       3 * [inputs.pop('prompt'      )]

      a					:      Any    =       ldmad_pipe.tokenizer(
          A    ,		padding='max_length'    ,		max_length=ldmad_pipe.tokenizer.model_max_length    ,		truncation=A    ,		return_tensors='pt'    ,		)
      a					:      str    =       text_inputs['input_ids'].to(A      )

      a					:      Any    =       ldmad_pipe.text_encoder(A      )[0]

      a					:      List[str]    =       prompt_embeds

      # forward
      a					:      Optional[Any]    =       ldmad_pipe(**A      )
      a,					a					:      int    =       output.rgb, output.depth
      a					:      Any    =       rgb_slice_a[0, -3:, -3:, -1]
      a					:      Dict    =       depth_slice_a[0, -3:, -1]

      assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten()      ).max() < 1E-4
      assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten()      ).max() < 1E-4





    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       'cpu'  # ensure determinism for the device-dependent torch.Generator
      a					:      Union[str, Any]    =       self.get_dummy_components()
      a					:      Optional[Any]    =       PNDMScheduler(skip_prk_steps=A      )
      a					:      Tuple    =       StableDiffusionLDMaDPipeline(**A      )
      a					:      Optional[int]    =       ldmad_pipe.to(A      )
      ldmad_pipe.set_progress_bar_config(disable=A      )

      a					:      Union[str, Any]    =       self.get_dummy_inputs(A      )
      a					:      int    =       'french fries'
      a					:      Union[str, Any]    =       ldmad_pipe(**A    ,		negative_prompt=A      )

      a,					a					:      int    =       output.rgb, output.depth
      a					:      Optional[Any]    =       rgb[0, -3:, -3:, -1]
      a					:      str    =       depth[0, -3:, -1]

      assert rgb.shape == (1, 6_4, 6_4, 3)
      assert depth.shape == (1, 6_4, 6_4)

      a					:      Tuple    =       np.array(
          [0.3_70_44, 0.71_81_15_03, 0.7_22_32_51, 0.48_60_36_75, 0.5_63_83_91, 0.6_36_49_48, 0.42_83_37_04, 0.4_90_13_15, 0.47_92_62_17]      )
      a					:      int    =       np.array([1_07.8_47_38, 84.6_28_02, 89.96_21_35]      )
      assert np.abs(rgb_slice.flatten() - expected_slice_rgb      ).max() < 1E-2
      assert np.abs(depth_slice.flatten() - expected_slice_depth      ).max() < 1E-2






@slow
@require_torch_gpu
class 						snake_case  (  unittest.TestCase	):





    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




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





    def     lowerCamelCase__				(							self     : Tuple    ,		A     : List[str]    ,		A     : List[str]="cpu"    ,		A     : Optional[Any]=torch.floataa    ,		A     : Tuple=0      ):


      '''simple docstring'''




      a					:      Tuple    =       torch.Generator(device=A      ).manual_seed(A      )
      a					:      Any    =       np.random.RandomState(A      ).standard_normal((1, 4, 6_4, 6_4)      )
      a					:      List[str]    =       torch.from_numpy(A      ).to(device=A    ,		dtype=A      )
      a					:      str    =       {
          'prompt': 'a photograph of an astronaut riding a horse',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 3,
          'guidance_scale': 7.5,
          'output_type': 'numpy',
      }
      return inputs





    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      a					:      List[str]    =       StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d'      )
      a					:      int    =       ldmad_pipe.to(A      )
      ldmad_pipe.set_progress_bar_config(disable=A      )

      a					:      Tuple    =       self.get_inputs(A      )
      a					:      Tuple    =       ldmad_pipe(**A      )
      a,					a					:      Optional[Any]    =       output.rgb, output.depth
      a					:      int    =       rgb[0, -3:, -3:, -1].flatten()
      a					:      str    =       rgb[0, -3:, -1].flatten()

      assert rgb.shape == (1, 5_1_2, 5_1_2, 3)
      assert depth.shape == (1, 5_1_2, 5_1_2)

      a					:      int    =       np.array(
          [0.53_80_54_65, 0.56_70_73_05, 0.5_48_65_15, 0.57_01_22_36, 0.5_81_45_11, 0.56_25_34_87, 0.54_84_30_14, 0.55_09_22_63, 0.6_45_97_06]      )
      a					:      Tuple    =       np.array(
          [0.9_26_37_81, 0.6_67_86_72, 0.5_48_65_15, 0.92_20_21_45, 0.67_83_11_35, 0.56_25_34_87, 0.9_24_16_94, 0.7_55_14_78, 0.6_45_97_06]      )
      assert np.abs(rgb_slice - expected_slice_rgb      ).max() < 3E-3
      assert np.abs(depth_slice - expected_slice_depth      ).max() < 3E-3






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





    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




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





    def     lowerCamelCase__				(							self     : List[str]    ,		A     : List[str]    ,		A     : Tuple="cpu"    ,		A     : Optional[Any]=torch.floataa    ,		A     : int=0      ):


      '''simple docstring'''




      a					:      str    =       torch.Generator(device=A      ).manual_seed(A      )
      a					:      Optional[int]    =       np.random.RandomState(A      ).standard_normal((1, 4, 6_4, 6_4)      )
      a					:      Optional[Any]    =       torch.from_numpy(A      ).to(device=A    ,		dtype=A      )
      a					:      List[Any]    =       {
          'prompt': 'a photograph of an astronaut riding a horse',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 5_0,
          'guidance_scale': 7.5,
          'output_type': 'numpy',
      }
      return inputs





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


      '''simple docstring'''




      a					:      List[str]    =       StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d'      ).to(A      )
      ldmad_pipe.set_progress_bar_config(disable=A      )

      a					:      Union[str, Any]    =       self.get_inputs(A      )
      a					:      Optional[int]    =       ldmad_pipe(**A      )
      a,					a					:      Union[str, Any]    =       output.rgb, output.depth

      a					:      str    =       0.49_55_86
      a					:      Optional[Any]    =       0.33_79_55_15
      a					:      List[str]    =       1_12.4_85_18
      a					:      str    =       98.48_97_46
      assert np.abs(expected_rgb_mean - rgb.mean()      ) < 1E-3
      assert np.abs(expected_rgb_std - rgb.std()      ) < 1E-3
      assert np.abs(expected_depth_mean - depth.mean()      ) < 1E-3
      assert np.abs(expected_depth_std - depth.std()      ) < 1E-3





    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      a					:      Optional[int]    =       StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d-4c'      ).to(A      )
      ldmad_pipe.set_progress_bar_config(disable=A      )

      a					:      List[Any]    =       self.get_inputs(A      )
      a					:      Optional[Any]    =       ldmad_pipe(**A      )
      a,					a					:      Dict    =       output.rgb, output.depth

      a					:      str    =       0.4_19_41_27
      a					:      Optional[int]    =       0.35_37_55_86
      a					:      Tuple    =       0.5_63_85_02
      a					:      Any    =       0.34_68_61_03

      assert rgb.shape == (1, 5_1_2, 5_1_2, 3)
      assert depth.shape == (1, 5_1_2, 5_1_2, 1)
      assert np.abs(expected_rgb_mean - rgb.mean()      ) < 1E-3
      assert np.abs(expected_rgb_std - rgb.std()      ) < 1E-3
      assert np.abs(expected_depth_mean - depth.mean()      ) < 1E-3
      assert np.abs(expected_depth_std - depth.std()      ) < 1E-3












"""simple docstring"""


import argparse
import os
import re

import packaging.version


_UpperCamelCase    :   Optional[Any]   			=						'examples/'
_UpperCamelCase    :   Any   			=						{
    'examples': (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'),
    'init': (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),
    'setup': (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'),
    'doc': (re.compile(r'^(\s*)release\s*=\s*"[^"]+"$', re.MULTILINE), 'release = "VERSION"\n'),
}
_UpperCamelCase    :   List[str]   			=						{
    'init': 'src/diffusers/__init__.py',
    'setup': 'setup.py',
}
_UpperCamelCase    :   List[str]   			=						'README.md'




def       snake_case  (A_				:str     ,      A_				:Optional[Any]     ,      A_				:Any				):







  '''simple docstring'''

  with open(A_     ,      'r'     ,      encoding='utf-8'     ,      newline='\n'				) as f:
    a					:      Tuple    =       f.read()
  a,					a					:      Any    =       REPLACE_PATTERNS[pattern]
  a					:      Dict    =       replace.replace('VERSION'     ,      A_				)
  a					:      Union[str, Any]    =       re_pattern.sub(A_     ,      A_				)
  with open(A_     ,      'w'     ,      encoding='utf-8'     ,      newline='\n'				) as f:
    f.write(A_				)




def       snake_case  (A_				:List[Any]				):







  '''simple docstring'''

  for folder, directories, fnames in os.walk(A_				):
    # Removing some of the folders with non-actively maintained examples from the walk
    if "research_projects" in directories:
      directories.remove('research_projects'				)
    if "legacy" in directories:
      directories.remove('legacy'				)
    for fname in fnames:
      if fname.endswith('.py'				):
        update_version_in_file(os.path.join(A_     ,      A_				)     ,      A_     ,      pattern='examples'				)




def       snake_case  (A_				:Tuple     ,      A_				:Optional[Any]=False				):







  '''simple docstring'''

  for pattern, fname in REPLACE_FILES.items():
    update_version_in_file(A_     ,      A_     ,      A_				)
  if not patch:
    update_version_in_examples(A_				)




def       snake_case  ():







  '''simple docstring'''

  a					:      str    =       '🤗 Transformers currently provides the following architectures'
  a					:      Dict    =       '1. Want to contribute a new model?'
  with open(A_     ,      'r'     ,      encoding='utf-8'     ,      newline='\n'				) as f:
    a					:      Optional[Any]    =       f.readlines()

  # Find the start of the list.
  a					:      List[str]    =       0
  while not lines[start_index].startswith(_start_prompt				):
    start_index += 1
  start_index += 1

  a					:      Optional[Any]    =       start_index
  # Update the lines in the model list.
  while not lines[index].startswith(_end_prompt				):
    if lines[index].startswith('1.'				):
      a					:      int    =       lines[index].replace(
          'https://huggingface.co/docs/diffusers/main/model_doc'     ,      'https://huggingface.co/docs/diffusers/model_doc'     ,      )
    index += 1

  with open(A_     ,      'w'     ,      encoding='utf-8'     ,      newline='\n'				) as f:
    f.writelines(A_				)




def       snake_case  ():







  '''simple docstring'''

  with open(REPLACE_FILES['init']     ,      'r'				) as f:
    a					:      List[str]    =       f.read()
  a					:      str    =       REPLACE_PATTERNS['init'][0].search(A_				).groups()[0]
  return packaging.version.parse(A_				)




def       snake_case  (A_				:Optional[Any]=False				):







  '''simple docstring'''

  a					:      Optional[int]    =       get_version()
  if patch and default_version.is_devrelease:
    raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!'				)
  if default_version.is_devrelease:
    a					:      Tuple    =       default_version.base_version
  elif patch:
    a					:      Union[str, Any]    =       f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}'''
  else:
    a					:      Optional[Any]    =       f'''{default_version.major}.{default_version.minor + 1}.0'''

  # Now let's ask nicely if that's the right one.
  a					:      Union[str, Any]    =       input(f'''Which version are you releasing? [{default_version}]'''				)
  if len(A_				) == 0:
    a					:      int    =       default_version

  print(f'''Updating version to {version}.'''				)
  global_version_update(A_     ,      patch=A_				)




def       snake_case  ():







  '''simple docstring'''

  a					:      str    =       get_version()
  a					:      Optional[int]    =       f'''{current_version.major}.{current_version.minor + 1}.0.dev0'''
  a					:      Optional[int]    =       current_version.base_version

  # Check with the user we got that right.
  a					:      str    =       input(f'''Which version are we developing now? [{dev_version}]'''				)
  if len(A_				) == 0:
    a					:      Union[str, Any]    =       dev_version

  print(f'''Updating version to {version}.'''				)
  global_version_update(A_				)


#    print("Cleaning main README, don't forget to run `make fix-copies`.")
#    clean_main_ref_in_model_list()


if __name__ == "__main__":
   _UpperCamelCase    :   Dict   			=						argparse.ArgumentParser()
   parser.add_argument('--post_release', action='store_true', help='Whether this is pre or post release.')
   parser.add_argument('--patch', action='store_true', help='Whether or not this is a patch release.')
   _UpperCamelCase    :   Optional[Any]   			=						parser.parse_args()
   if not args.post_release:
      pre_release_work(patch=args.patch)
   elif args.patch:
      print('Nothing to do after a patch :-)')
   else:
      post_release_work()




