






"""simple docstring"""


import gc
import random
import tempfile
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu






class 						snake_case  (  unittest.TestCase	):





    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




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





    @property
    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      a					:      str    =       1
      a					:      List[Any]    =       3
      a					:      int    =       (3_2, 3_2)

      a					:      Any    =       floats_tensor((batch_size, num_channels) + sizes    ,		rng=random.Random(0      )      ).to(A      )
      return image





    @property
    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      torch.manual_seed(0      )
      a					:      Optional[Any]    =       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    ,		)
      return model





    @property
    def     lowerCamelCase__				(							self     : int      ):


      '''simple docstring'''




      torch.manual_seed(0      )
      a					:      Dict    =       AutoencoderKL(
          block_out_channels=[3_2, 6_4]    ,		in_channels=3    ,		out_channels=3    ,		down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']    ,		up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']    ,		latent_channels=4    ,		)
      return model





    @property
    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      torch.manual_seed(0      )
      a					:      List[Any]    =       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    ,		)
      return CLIPTextModel(A      )





    @property
    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      def extract(*A     : Union[str, Any]    ,		**A     : Optional[int]      ):






        class 						snake_case  :





            def __init__(							self     : List[str]      ):


              '''simple docstring'''




              a					:      Union[str, Any]    =       torch.ones([0]      )





            def     lowerCamelCase__				(							self     : List[Any]    ,		A     : str      ):


              '''simple docstring'''




              self.pixel_values.to(A      )
              return self




        return Out()

      return extract





    def     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       'cpu'  # ensure determinism for the device-dependent torch.Generator
      a					:      Any    =       self.dummy_cond_unet
      a					:      Union[str, Any]    =       DDIMScheduler(
          beta_start=0.0_00_85    ,		beta_end=0.0_12    ,		beta_schedule='scaled_linear'    ,		clip_sample=A    ,		set_alpha_to_one=A    ,		)

      a					:      List[Any]    =       self.dummy_vae
      a					:      Tuple    =       self.dummy_text_encoder
      a					:      Union[str, Any]    =       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

      # make sure here that pndm scheduler skips prk
      a					:      str    =       StableDiffusionPipeline(
          unet=A    ,		scheduler=A    ,		vae=A    ,		text_encoder=A    ,		tokenizer=A    ,		safety_checker=A    ,		feature_extractor=self.dummy_extractor    ,		)
      a					:      List[Any]    =       sd_pipe.to(A      )
      sd_pipe.set_progress_bar_config(disable=A      )

      a					:      List[str]    =       'A painting of a squirrel eating a burger'

      a					:      Optional[int]    =       torch.Generator(device=A      ).manual_seed(0      )
      a					:      Optional[Any]    =       sd_pipe([prompt]    ,		generator=A    ,		guidance_scale=6.0    ,		num_inference_steps=2    ,		output_type='np'      )
      a					:      Optional[int]    =       output.images

      a					:      List[Any]    =       torch.Generator(device=A      ).manual_seed(0      )
      a					:      int    =       sd_pipe(
          [prompt]    ,		generator=A    ,		guidance_scale=6.0    ,		num_inference_steps=2    ,		output_type='np'    ,		return_dict=A    ,		)[0]

      a					:      Union[str, Any]    =       image[0, -3:, -3:, -1]
      a					:      int    =       image_from_tuple[0, -3:, -3:, -1]

      assert image.shape == (1, 6_4, 6_4, 3)
      a					:      List[str]    =       np.array([0.57_56, 0.61_18, 0.50_05, 0.50_41, 0.54_71, 0.47_26, 0.49_76, 0.48_65, 0.48_64]      )

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





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


      '''simple docstring'''




      a					:      Any    =       'cpu'  # ensure determinism for the device-dependent torch.Generator
      a					:      List[str]    =       self.dummy_cond_unet
      a					:      int    =       PNDMScheduler(skip_prk_steps=A      )
      a					:      Optional[Any]    =       self.dummy_vae
      a					:      str    =       self.dummy_text_encoder
      a					:      List[str]    =       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

      # make sure here that pndm scheduler skips prk
      a					:      int    =       StableDiffusionPipeline(
          unet=A    ,		scheduler=A    ,		vae=A    ,		text_encoder=A    ,		tokenizer=A    ,		safety_checker=A    ,		feature_extractor=self.dummy_extractor    ,		)
      a					:      str    =       sd_pipe.to(A      )
      sd_pipe.set_progress_bar_config(disable=A      )

      a					:      Union[str, Any]    =       'A painting of a squirrel eating a burger'
      a					:      List[str]    =       torch.Generator(device=A      ).manual_seed(0      )
      a					:      List[str]    =       sd_pipe([prompt]    ,		generator=A    ,		guidance_scale=6.0    ,		num_inference_steps=2    ,		output_type='np'      )

      a					:      List[Any]    =       output.images

      a					:      Optional[Any]    =       torch.Generator(device=A      ).manual_seed(0      )
      a					:      int    =       sd_pipe(
          [prompt]    ,		generator=A    ,		guidance_scale=6.0    ,		num_inference_steps=2    ,		output_type='np'    ,		return_dict=A    ,		)[0]

      a					:      Optional[int]    =       image[0, -3:, -3:, -1]
      a					:      Optional[int]    =       image_from_tuple[0, -3:, -3:, -1]

      assert image.shape == (1, 6_4, 6_4, 3)
      a					:      List[Any]    =       np.array([0.51_25, 0.57_16, 0.48_28, 0.50_60, 0.56_50, 0.47_68, 0.51_85, 0.48_95, 0.49_93]      )

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





    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      a					:      str    =       StableDiffusionPipeline.from_pretrained(
          'hf-internal-testing/tiny-stable-diffusion-lms-pipe'    ,		safety_checker=A      )
      assert isinstance(A    ,		A      )
      assert isinstance(pipe.scheduler    ,		A      )
      assert pipe.safety_checker is None

      a					:      Any    =       pipe('example prompt'    ,		num_inference_steps=2      ).images[0]
      assert image is not None

      # check that there's no error when saving a pipeline with one of the models being None
      with tempfile.TemporaryDirectory() as tmpdirname:
        pipe.save_pretrained(A      )
        a					:      List[Any]    =       StableDiffusionPipeline.from_pretrained(A      )

      # sanity check that the pipeline still works
      assert pipe.safety_checker is None
      a					:      str    =       pipe('example prompt'    ,		num_inference_steps=2      ).images[0]
      assert image is not None





    @unittest.skipIf(torch_device != 'cuda'    ,		'This test requires a GPU'      )
    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      a					:      str    =       self.dummy_cond_unet
      a					:      Optional[Any]    =       PNDMScheduler(skip_prk_steps=A      )
      a					:      Tuple    =       self.dummy_vae
      a					:      List[str]    =       self.dummy_text_encoder
      a					:      Optional[int]    =       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

      # put models in fp16
      a					:      int    =       unet.half()
      a					:      Tuple    =       vae.half()
      a					:      Any    =       bert.half()

      # make sure here that pndm scheduler skips prk
      a					:      Any    =       StableDiffusionPipeline(
          unet=A    ,		scheduler=A    ,		vae=A    ,		text_encoder=A    ,		tokenizer=A    ,		safety_checker=A    ,		feature_extractor=self.dummy_extractor    ,		)
      a					:      Optional[int]    =       sd_pipe.to(A      )
      sd_pipe.set_progress_bar_config(disable=A      )

      a					:      Tuple    =       'A painting of a squirrel eating a burger'
      a					:      Optional[int]    =       sd_pipe([prompt]    ,		num_inference_steps=2    ,		output_type='np'      ).images

      assert image.shape == (1, 6_4, 6_4, 3)






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





    def     lowerCamelCase__				(							self     : Optional[Any]      ):


      '''simple docstring'''




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





    def     lowerCamelCase__				(							self     : Optional[Any]      ):


      '''simple docstring'''




      a					:      Optional[Any]    =       StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5'    ,		safety_checker=A      )
      a					:      str    =       LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config      )
      a					:      Any    =       sd_pipe.to(A      )
      sd_pipe.set_progress_bar_config(disable=A      )

      a					:      Union[str, Any]    =       (
          'portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle'
          ' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with'
          ' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and'
          ' children from bahnhof zoo, detailed '
      )
      a					:      Tuple    =       4_0_0_3_6_6_0_3_4_6
      a					:      Tuple    =       7

      # without safety guidance (sld_guidance_scale = 0)
      a					:      Any    =       torch.manual_seed(A      )
      a					:      Dict    =       sd_pipe(
          [prompt]    ,		generator=A    ,		guidance_scale=A    ,		num_inference_steps=5_0    ,		output_type='np'    ,		width=5_1_2    ,		height=5_1_2    ,		sld_guidance_scale=0    ,		)

      a					:      Optional[int]    =       output.images
      a					:      Optional[int]    =       image[0, -3:, -3:, -1]
      a					:      Dict    =       [0.22_78, 0.22_31, 0.22_49, 0.23_33, 0.23_03, 0.18_85, 0.22_73, 0.21_44, 0.21_76]

      assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

      # without safety guidance (strong configuration)
      a					:      Union[str, Any]    =       torch.manual_seed(A      )
      a					:      Optional[int]    =       sd_pipe(
          [prompt]    ,		generator=A    ,		guidance_scale=A    ,		num_inference_steps=5_0    ,		output_type='np'    ,		width=5_1_2    ,		height=5_1_2    ,		sld_guidance_scale=2_0_0_0    ,		sld_warmup_steps=7    ,		sld_threshold=0.0_25    ,		sld_momentum_scale=0.5    ,		sld_mom_beta=0.7    ,		)

      a					:      Any    =       output.images
      a					:      Optional[int]    =       image[0, -3:, -3:, -1]
      a					:      Union[str, Any]    =       [0.23_83, 0.22_76, 0.2_36, 0.21_92, 0.21_86, 0.20_53, 0.19_71, 0.19_01, 0.17_19]

      assert image.shape == (1, 5_1_2, 5_1_2, 3)

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





    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      a					:      Optional[Any]    =       StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5'    ,		safety_checker=A      )
      a					:      str    =       LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config      )
      a					:      Dict    =       sd_pipe.to(A      )
      sd_pipe.set_progress_bar_config(disable=A      )

      a					:      Any    =       'padme amidala taking a bath artwork, safe for work, no nudity'
      a					:      Optional[Any]    =       2_7_3_4_9_7_1_7_5_5
      a					:      Optional[int]    =       7

      a					:      Dict    =       torch.manual_seed(A      )
      a					:      Any    =       sd_pipe(
          [prompt]    ,		generator=A    ,		guidance_scale=A    ,		num_inference_steps=5_0    ,		output_type='np'    ,		width=5_1_2    ,		height=5_1_2    ,		sld_guidance_scale=0    ,		)

      a					:      Any    =       output.images
      a					:      Union[str, Any]    =       image[0, -3:, -3:, -1]
      a					:      Union[str, Any]    =       [0.35_02, 0.36_22, 0.33_96, 0.36_42, 0.34_78, 0.33_18, 0.35, 0.33_48, 0.32_97]

      assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

      a					:      int    =       torch.manual_seed(A      )
      a					:      List[Any]    =       sd_pipe(
          [prompt]    ,		generator=A    ,		guidance_scale=A    ,		num_inference_steps=5_0    ,		output_type='np'    ,		width=5_1_2    ,		height=5_1_2    ,		sld_guidance_scale=2_0_0_0    ,		sld_warmup_steps=7    ,		sld_threshold=0.0_25    ,		sld_momentum_scale=0.5    ,		sld_mom_beta=0.7    ,		)

      a					:      str    =       output.images
      a					:      Dict    =       image[0, -3:, -3:, -1]
      a					:      Union[str, Any]    =       [0.55_31, 0.52_06, 0.48_95, 0.51_56, 0.51_82, 0.47_51, 0.48_02, 0.48_03, 0.44_43]

      assert image.shape == (1, 5_1_2, 5_1_2, 3)

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





    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




      a					:      str    =       StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5'      )
      a					:      str    =       sd_pipe.to(A      )
      sd_pipe.set_progress_bar_config(disable=A      )

      a					:      List[str]    =       (
          'the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.'
          ' leyendecker'
      )
      a					:      List[Any]    =       1_0_4_4_3_5_5_2_3_4
      a					:      Dict    =       1_2

      a					:      Optional[Any]    =       torch.manual_seed(A      )
      a					:      Optional[Any]    =       sd_pipe(
          [prompt]    ,		generator=A    ,		guidance_scale=A    ,		num_inference_steps=5_0    ,		output_type='np'    ,		width=5_1_2    ,		height=5_1_2    ,		sld_guidance_scale=0    ,		)

      a					:      List[str]    =       output.images
      a					:      Tuple    =       image[0, -3:, -3:, -1]
      a					:      Any    =       np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]      )

      assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

      a					:      List[Any]    =       torch.manual_seed(A      )
      a					:      Any    =       sd_pipe(
          [prompt]    ,		generator=A    ,		guidance_scale=A    ,		num_inference_steps=5_0    ,		output_type='np'    ,		width=5_1_2    ,		height=5_1_2    ,		sld_guidance_scale=2_0_0_0    ,		sld_warmup_steps=7    ,		sld_threshold=0.0_25    ,		sld_momentum_scale=0.5    ,		sld_mom_beta=0.7    ,		)

      a					:      List[str]    =       output.images
      a					:      Tuple    =       image[0, -3:, -3:, -1]
      a					:      Optional[Any]    =       np.array([0.58_18, 0.62_85, 0.68_35, 0.60_19, 0.6_25, 0.67_54, 0.60_96, 0.63_34, 0.65_61]      )
      assert image.shape == (1, 5_1_2, 5_1_2, 3)

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












"""simple docstring"""


import argparse
from collections import defaultdict

import yaml


_UpperCamelCase    :   int   			=						'docs/source/en/_toctree.yml'




def       snake_case  (A_				:Optional[Any]				):







  '''simple docstring'''

  a					:      List[Any]    =       defaultdict(A_				)
  for doc in model_doc:
    counts[doc["local"]] += 1
  a					:      Optional[Any]    =       [key for key, value in counts.items() if value > 1]

  a					:      List[str]    =       []
  for duplicate_key in duplicates:
    a					:      int    =       list({doc['title'] for doc in model_doc if doc['local'] == duplicate_key}				)
    if len(A_				) > 1:
      raise ValueError(
          f'''{duplicate_key} is present several times in the documentation table of content at '''
          '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '
          'others.'				)
    # Only add this once
    new_doc.append({'local': duplicate_key, 'title': titles[0]}				)

  # Add none duplicate-keys
  new_doc.extend([doc for doc in model_doc if counts[doc['local']] == 1]				)

  # Sort
  return sorted(A_     ,      key=lambda A_				: s["title"].lower()				)




def       snake_case  (A_				:List[str]=False				):







  '''simple docstring'''

  with open(A_     ,      encoding='utf-8'				) as f:
    a					:      Dict    =       yaml.safe_load(f.read()				)

  # Get to the API doc
  a					:      Optional[Any]    =       0
  while content[api_idx]["title"] != "API":
    api_idx += 1
  a					:      List[str]    =       content[api_idx]['sections']

  # Then to the model doc
  a					:      Optional[int]    =       0
  while api_doc[model_idx]["title"] != "Models":
    model_idx += 1

  a					:      Optional[Any]    =       api_doc[model_idx]['sections']

  a					:      Dict    =       [(idx, section) for idx, section in enumerate(A_				) if 'sections' in section]
  a					:      List[str]    =       False
  for idx, modality_doc in modalities_docs:
    a					:      str    =       modality_doc['sections']
    a					:      str    =       clean_model_doc_toc(A_				)

    if old_modality_doc != new_modality_doc:
      a					:      str    =       True
      if overwrite:
        a					:      Any    =       new_modality_doc

  if diff:
    if overwrite:
      a					:      Any    =       model_doc
      a					:      str    =       api_doc
      with open(A_     ,      'w'     ,      encoding='utf-8'				) as f:
        f.write(yaml.dump(A_     ,      allow_unicode=A_				)				)
    else:
      raise ValueError(
          'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'				)


if __name__ == "__main__":
   _UpperCamelCase    :   Optional[int]   			=						argparse.ArgumentParser()
   parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
   _UpperCamelCase    :   Any   			=						parser.parse_args()

   check_model_doc(args.fix_and_overwrite)




