



"""simple docstring"""





import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()
class  lowercase__  (       unittest.TestCase ):







       '''simple docstring'''


       def 	lowercase__							(				self     :    List[str]       )					->		Any:


             '''simple docstring'''




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



       @property
       def 	lowercase__							(				self     :    int       )					->		str:


             '''simple docstring'''




             UpperCAmelCase_     					=				1
             UpperCAmelCase_     					=				3
             UpperCAmelCase_     					=				(32, 32)

             UpperCAmelCase_     					=				floats_tensor((batch_size, num_channels) + sizes						,							rng=random.Random(0       )       ).to(_UpperCAmelCase       )
             return image



       @property
       def 	lowercase__							(				self     :    int       )					->		Tuple:


             '''simple docstring'''




             torch.manual_seed(0       )
             UpperCAmelCase_     					=				UNetaDConditionModel(
                 block_out_channels=(32, 64)						,							layers_per_block=2						,							sample_size=32						,							in_channels=4						,							out_channels=4						,							down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")						,							up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")						,							cross_attention_dim=32						,							)
             return model



       @property
       def 	lowercase__							(				self     :    Dict       )					->		Any:


             '''simple docstring'''




             torch.manual_seed(0       )
             UpperCAmelCase_     					=				AutoencoderKL(
                 block_out_channels=[32, 64]						,							in_channels=3						,							out_channels=3						,							down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]						,							up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]						,							latent_channels=4						,							)
             return model



       @property
       def 	lowercase__							(				self     :    str       )					->		Optional[Any]:


             '''simple docstring'''




             torch.manual_seed(0       )
             UpperCAmelCase_     					=				RobertaSeriesConfig(
                 hidden_size=32						,							project_dim=32						,							intermediate_size=37						,							layer_norm_eps=1e-05						,							num_attention_heads=4						,							num_hidden_layers=5						,							pad_token_id=1						,							vocab_size=5006						,							)
             return RobertaSeriesModelWithTransformation(_UpperCAmelCase       )



       @property
       def 	lowercase__							(				self     :    Optional[Any]       )					->		Dict:


             '''simple docstring'''




             def extract(*_UpperCAmelCase     :    Union[str, Any]						,							**_UpperCAmelCase     :    Union[str, Any]       ):
                   class  lowercase__  :







                          '''simple docstring'''


                          def __init__(				self     :    Tuple       )					->		Optional[int]:


                                '''simple docstring'''




                                UpperCAmelCase_     					=				torch.ones([0]       )







                          def 	lowercase__							(				self     :    Dict						,							_UpperCAmelCase     :    Union[str, Any]       )					->		str:


                                '''simple docstring'''




                                self.pixel_values.to(_UpperCAmelCase       )
                                return self



                   return Out()

             return extract



       def 	lowercase__							(				self     :    List[str]       )					->		Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				"cpu"  # ensure determinism for the device-dependent torch.Generator
             UpperCAmelCase_     					=				self.dummy_cond_unet
             UpperCAmelCase_     					=				PNDMScheduler(skip_prk_steps=_UpperCAmelCase       )
             UpperCAmelCase_     					=				self.dummy_vae
             UpperCAmelCase_     					=				self.dummy_text_encoder
             UpperCAmelCase_     					=				XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"       )
             UpperCAmelCase_     					=				77

             UpperCAmelCase_     					=				self.dummy_image.to(_UpperCAmelCase       )
             UpperCAmelCase_     					=				init_image / 2 + 0.5

             # make sure here that pndm scheduler skips prk
             UpperCAmelCase_     					=				AltDiffusionImgaImgPipeline(
                 unet=_UpperCAmelCase						,							scheduler=_UpperCAmelCase						,							vae=_UpperCAmelCase						,							text_encoder=_UpperCAmelCase						,							tokenizer=_UpperCAmelCase						,							safety_checker=_UpperCAmelCase						,							feature_extractor=self.dummy_extractor						,							)
             UpperCAmelCase_     					=				VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor						,							do_normalize=_UpperCAmelCase       )
             UpperCAmelCase_     					=				alt_pipe.to(_UpperCAmelCase       )
             alt_pipe.set_progress_bar_config(disable=_UpperCAmelCase       )

             UpperCAmelCase_     					=				"A painting of a squirrel eating a burger"
             UpperCAmelCase_     					=				torch.Generator(device=_UpperCAmelCase       ).manual_seed(0       )
             UpperCAmelCase_     					=				alt_pipe(
                 [prompt]						,							generator=_UpperCAmelCase						,							guidance_scale=6.0						,							num_inference_steps=2						,							output_type="np"						,							image=_UpperCAmelCase						,							)

             UpperCAmelCase_     					=				output.images

             UpperCAmelCase_     					=				torch.Generator(device=_UpperCAmelCase       ).manual_seed(0       )
             UpperCAmelCase_     					=				alt_pipe(
                 [prompt]						,							generator=_UpperCAmelCase						,							guidance_scale=6.0						,							num_inference_steps=2						,							output_type="np"						,							image=_UpperCAmelCase						,							return_dict=_UpperCAmelCase						,							)[0]

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

             assert image.shape == (1, 32, 32, 3)
             UpperCAmelCase_     					=				np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]       )

             assert np.abs(image_slice.flatten() - expected_slice       ).max() < 5e-3
             assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < 5e-3



       @unittest.skipIf(torch_device != "cuda"						,							"This test requires a GPU"       )
       def 	lowercase__							(				self     :    int       )					->		List[str]:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.dummy_cond_unet
             UpperCAmelCase_     					=				PNDMScheduler(skip_prk_steps=_UpperCAmelCase       )
             UpperCAmelCase_     					=				self.dummy_vae
             UpperCAmelCase_     					=				self.dummy_text_encoder
             UpperCAmelCase_     					=				XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"       )
             UpperCAmelCase_     					=				77

             UpperCAmelCase_     					=				self.dummy_image.to(_UpperCAmelCase       )

             # put models in fp16
             UpperCAmelCase_     					=				unet.half()
             UpperCAmelCase_     					=				vae.half()
             UpperCAmelCase_     					=				bert.half()

             # make sure here that pndm scheduler skips prk
             UpperCAmelCase_     					=				AltDiffusionImgaImgPipeline(
                 unet=_UpperCAmelCase						,							scheduler=_UpperCAmelCase						,							vae=_UpperCAmelCase						,							text_encoder=_UpperCAmelCase						,							tokenizer=_UpperCAmelCase						,							safety_checker=_UpperCAmelCase						,							feature_extractor=self.dummy_extractor						,							)
             UpperCAmelCase_     					=				VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor						,							do_normalize=_UpperCAmelCase       )
             UpperCAmelCase_     					=				alt_pipe.to(_UpperCAmelCase       )
             alt_pipe.set_progress_bar_config(disable=_UpperCAmelCase       )

             UpperCAmelCase_     					=				"A painting of a squirrel eating a burger"
             UpperCAmelCase_     					=				torch.manual_seed(0       )
             UpperCAmelCase_     					=				alt_pipe(
                 [prompt]						,							generator=_UpperCAmelCase						,							num_inference_steps=2						,							output_type="np"						,							image=_UpperCAmelCase						,							).images

             assert image.shape == (1, 32, 32, 3)







       @unittest.skipIf(torch_device != "cuda"						,							"This test requires a GPU"       )
       def 	lowercase__							(				self     :    Tuple       )					->		Any:


             '''simple docstring'''




             UpperCAmelCase_     					=				load_image(
                 "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                 "/img2img/sketch-mountains-input.jpg"       )
             # resize to resolution that is divisible by 8 but not 16 or 32
             UpperCAmelCase_     					=				init_image.resize((760, 504)       )

             UpperCAmelCase_     					=				"BAAI/AltDiffusion"
             UpperCAmelCase_     					=				AltDiffusionImgaImgPipeline.from_pretrained(
                 _UpperCAmelCase						,							safety_checker=_UpperCAmelCase						,							)
             pipe.to(_UpperCAmelCase       )
             pipe.set_progress_bar_config(disable=_UpperCAmelCase       )
             pipe.enable_attention_slicing()

             UpperCAmelCase_     					=				"A fantasy landscape, trending on artstation"

             UpperCAmelCase_     					=				torch.manual_seed(0       )
             UpperCAmelCase_     					=				pipe(
                 prompt=_UpperCAmelCase						,							image=_UpperCAmelCase						,							strength=0.75						,							guidance_scale=7.5						,							generator=_UpperCAmelCase						,							output_type="np"						,							)
             UpperCAmelCase_     					=				output.images[0]

             UpperCAmelCase_     					=				image[255:258, 383:386, -1]

             assert image.shape == (504, 760, 3)
             UpperCAmelCase_     					=				np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]       )

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



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







       '''simple docstring'''


       def 	lowercase__							(				self     :    Optional[Any]       )					->		Optional[Any]:


             '''simple docstring'''




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







       def 	lowercase__							(				self     :    Dict       )					->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_     					=				load_image(
                 "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                 "/img2img/sketch-mountains-input.jpg"       )
             UpperCAmelCase_     					=				init_image.resize((768, 512)       )
             UpperCAmelCase_     					=				load_numpy(
                 "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"       )

             UpperCAmelCase_     					=				"BAAI/AltDiffusion"
             UpperCAmelCase_     					=				AltDiffusionImgaImgPipeline.from_pretrained(
                 _UpperCAmelCase						,							safety_checker=_UpperCAmelCase						,							)
             pipe.to(_UpperCAmelCase       )
             pipe.set_progress_bar_config(disable=_UpperCAmelCase       )
             pipe.enable_attention_slicing()

             UpperCAmelCase_     					=				"A fantasy landscape, trending on artstation"

             UpperCAmelCase_     					=				torch.manual_seed(0       )
             UpperCAmelCase_     					=				pipe(
                 prompt=_UpperCAmelCase						,							image=_UpperCAmelCase						,							strength=0.75						,							guidance_scale=7.5						,							generator=_UpperCAmelCase						,							output_type="np"						,							)
             UpperCAmelCase_     					=				output.images[0]

             assert image.shape == (512, 768, 3)
             # img2img is flaky across GPUs even in fp32, so using MAE here
             assert np.abs(expected_image - image       ).max() < 1e-2








def    a__    (		snake_case__					:							Tuple     ):  # noqa: E741
  _UpperCAmelCase		:							Dict							=     len(snake_case__     )
  _UpperCAmelCase		:							Tuple							=     0
  _UpperCAmelCase		:							Union[str, Any]							=     [0] * n
  _UpperCAmelCase		:							Union[str, Any]							=     [False] * n
  _UpperCAmelCase		:							Tuple							=     [False] * n

  def dfs(snake_case__					:							List[str]						,   snake_case__					:							int						,   snake_case__					:							str						,   snake_case__					:							int     ):
    if parent == root:
      out_edge_count += 1
    _UpperCAmelCase		:							List[Any]							=     True
    _UpperCAmelCase		:							List[str]							=     at

    for to in l[at]:
      if to == parent:
        pass
      elif not visited[to]:
        _UpperCAmelCase		:							Optional[Any]							=     dfs(snake_case__						,   snake_case__						,   snake_case__						,   snake_case__     )
        _UpperCAmelCase		:							Optional[Any]							=     min(low[at]						,   low[to]     )

        # AP found via bridge
        if at < low[to]:
          _UpperCAmelCase		:							List[str]							=     True
        # AP found via cycle
        if at == low[to]:
          _UpperCAmelCase		:							Optional[Any]							=     True
      else:
        _UpperCAmelCase		:							str							=     min(low[at]						,   snake_case__     )
    return out_edge_count

  for i in range(snake_case__     ):
    if not visited[i]:
      _UpperCAmelCase		:							List[Any]							=     0
      _UpperCAmelCase		:							List[str]							=     dfs(snake_case__						,   snake_case__						,   -1						,   snake_case__     )
      _UpperCAmelCase		:							Optional[Any]							=     out_edge_count > 1

  for x in range(len(snake_case__     )     ):
    if is_art[x] is True:
      print(snake_case__     )


# Adjacency list of graph
SCREAMING_SNAKE_CASE__					:     Optional[Any]       =     {
    0: [1, 2],
    1: [0, 2],
    2: [0, 1, 3, 5],
    3: [2, 4],
    4: [3],
    5: [2, 6, 8],
    6: [5, 7],
    7: [6, 8],
    8: [5, 7],
}





compute_ap(data)





