
import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class UpperCAmelCase  (		SCREAMING_SNAKE_CASE__				,				unittest.TestCase  ):





   '''simple docstring'''
   __UpperCamelCase						:       Any												=       KandinskyVaaPriorEmbaEmbPipeline
   __UpperCamelCase						:       int												=       ['''prompt''', '''image''']
   __UpperCamelCase						:       Optional[int]												=       ['''prompt''', '''image''']
   __UpperCamelCase						:       Optional[Any]												=       [
       '''num_images_per_prompt''',
       '''strength''',
       '''generator''',
       '''num_inference_steps''',
       '''latents''',
       '''negative_prompt''',
       '''guidance_scale''',
       '''output_type''',
       '''return_dict''',
   ]
   __UpperCamelCase						:       Dict												=       False


   @property
   def 					__magic_name__							(   self	:				Optional[Any]	):

      """simple docstring"""
      return 3_2


   @property
   def 					__magic_name__							(   self	:				Dict	):

      """simple docstring"""
      return 3_2


   @property
   def 					__magic_name__							(   self	:				Union[str, Any]	):

      """simple docstring"""
      return self.time_input_dim


   @property
   def 					__magic_name__							(   self	:				Any	):

      """simple docstring"""
      return self.time_input_dim * 4


   @property
   def 					__magic_name__							(   self	:				int	):

      """simple docstring"""
      return 1_0_0


   @property
   def 					__magic_name__							(   self	:				int	):

      """simple docstring"""
      _A:    int						     =			CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''	)
      return tokenizer


   @property
   def 					__magic_name__							(   self	:				Any	):

      """simple docstring"""
      torch.manual_seed(0	)
      _A:    Optional[Any]						     =			CLIPTextConfig(
          bos_token_id=0     ,     eos_token_id=2     ,     hidden_size=self.text_embedder_hidden_size     ,     projection_dim=self.text_embedder_hidden_size     ,     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 CLIPTextModelWithProjection(lowerCAmelCase_	)


   @property
   def 					__magic_name__							(   self	:				Tuple	):

      """simple docstring"""
      torch.manual_seed(0	)

      _A:    int						     =			{
          '''num_attention_heads''': 2,
          '''attention_head_dim''': 1_2,
          '''embedding_dim''': self.text_embedder_hidden_size,
          '''num_layers''': 1,
      }

      _A:    List[str]						     =			PriorTransformer(**lowerCAmelCase_	)
      # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
      _A:    Optional[int]						     =			nn.Parameter(torch.ones(model.clip_std.shape	)	)
      return model


   @property
   def 					__magic_name__							(   self	:				Dict	):

      """simple docstring"""
      torch.manual_seed(0	)
      _A:    List[str]						     =			CLIPVisionConfig(
          hidden_size=self.text_embedder_hidden_size     ,     image_size=2_2_4     ,     projection_dim=self.text_embedder_hidden_size     ,     intermediate_size=3_7     ,     num_attention_heads=4     ,     num_channels=3     ,     num_hidden_layers=5     ,     patch_size=1_4     ,     )

      _A:    int						     =			CLIPVisionModelWithProjection(lowerCAmelCase_	)
      return model


   @property
   def 					__magic_name__							(   self	:				Optional[Any]	):

      """simple docstring"""
      _A:    int						     =			CLIPImageProcessor(
          crop_size=2_2_4     ,     do_center_crop=lowerCAmelCase_     ,     do_normalize=lowerCAmelCase_     ,     do_resize=lowerCAmelCase_     ,     image_mean=[0.48145466, 0.4578275, 0.40821073]     ,     image_std=[0.26862954, 0.26130258, 0.27577711]     ,     resample=3     ,     size=2_2_4     ,     )

      return image_processor


   def 					__magic_name__							(   self	:				Dict	):

      """simple docstring"""
      _A:    Tuple						     =			self.dummy_prior
      _A:    str						     =			self.dummy_image_encoder
      _A:    Optional[Any]						     =			self.dummy_text_encoder
      _A:    Optional[int]						     =			self.dummy_tokenizer
      _A:    List[str]						     =			self.dummy_image_processor

      _A:    List[str]						     =			UnCLIPScheduler(
          variance_type='''fixed_small_log'''     ,     prediction_type='''sample'''     ,     num_train_timesteps=1_0_0_0     ,     clip_sample=lowerCAmelCase_     ,     clip_sample_range=10.0     ,     )

      _A:    Optional[Any]						     =			{
          '''prior''': prior,
          '''image_encoder''': image_encoder,
          '''text_encoder''': text_encoder,
          '''tokenizer''': tokenizer,
          '''scheduler''': scheduler,
          '''image_processor''': image_processor,
      }

      return components


   def 					__magic_name__							(   self	:				int     ,     lowerCAmelCase_	:				Tuple     ,     lowerCAmelCase_	:				List[Any]=0	):

      """simple docstring"""
      if str(lowerCAmelCase_	).startswith('''mps'''	):
         _A:    Optional[Any]						     =			torch.manual_seed(lowerCAmelCase_	)
      else:
         _A:    Union[str, Any]						     =			torch.Generator(device=lowerCAmelCase_	).manual_seed(lowerCAmelCase_	)

      _A:    Tuple						     =			floats_tensor((1, 3, 6_4, 6_4)     ,     rng=random.Random(lowerCAmelCase_	)	).to(lowerCAmelCase_	)
      _A:    Optional[Any]						     =			image.cpu().permute(0     ,     2     ,     3     ,     1	)[0]
      _A:    Optional[int]						     =			Image.fromarray(np.uinta(lowerCAmelCase_	)	).convert('''RGB'''	).resize((2_5_6, 2_5_6)	)

      _A:    Union[str, Any]						     =			{
          '''prompt''': '''horse''',
          '''image''': init_image,
          '''strength''': 0.5,
          '''generator''': generator,
          '''guidance_scale''': 4.0,
          '''num_inference_steps''': 2,
          '''output_type''': '''np''',
      }
      return inputs


   def 					__magic_name__							(   self	:				Tuple	):

      """simple docstring"""
      _A:    str						     =			'''cpu'''

      _A:    Optional[Any]						     =			self.get_dummy_components()

      _A:    str						     =			self.pipeline_class(**lowerCAmelCase_	)
      _A:    Dict						     =			pipe.to(lowerCAmelCase_	)

      pipe.set_progress_bar_config(disable=lowerCAmelCase_	)

      _A:    Tuple						     =			pipe(**self.get_dummy_inputs(lowerCAmelCase_	)	)
      _A:    Tuple						     =			output.image_embeds

      _A:    List[Any]						     =			pipe(
          **self.get_dummy_inputs(lowerCAmelCase_	)     ,     return_dict=lowerCAmelCase_     ,     )[0]

      _A:    Any						     =			image[0, -1_0:]
      _A:    int						     =			image_from_tuple[0, -1_0:]

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

      _A:    Union[str, Any]						     =			np.array(
          [
              0.1071284,
              1.3330271,
              0.61260223,
              -0.6691065,
              -0.3846852,
              -1.0303661,
              0.22716111,
              0.03348901,
              0.30040675,
              -0.24805029,
          ]	)

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


   @skip_mps
   def 					__magic_name__							(   self	:				List[str]	):

      """simple docstring"""
      _A:    str						     =			torch_device == '''cpu'''
      _A:    str						     =			True
      _A:    List[Any]						     =			False

      self._test_inference_batch_single_identical(
          test_max_difference=lowerCAmelCase_     ,     relax_max_difference=lowerCAmelCase_     ,     test_mean_pixel_difference=lowerCAmelCase_     ,     )


   @skip_mps
   def 					__magic_name__							(   self	:				Union[str, Any]	):

      """simple docstring"""
      _A:    Union[str, Any]						     =			torch_device == '''cpu'''
      _A:    Tuple						     =			False

      self._test_attention_slicing_forward_pass(
          test_max_difference=lowerCAmelCase_     ,     test_mean_pixel_difference=lowerCAmelCase_     ,     )





from __future__ import annotations






def     lowerCamelCase__				(   a ) ->  Union[str, Any]:
   global graph, reversed_graph, scc, component, visit, stack
   if visit[u]:
      return
   _A:    Optional[Any]						     =			True
   for v in graph[u]:
      dfs(a )
   stack.append(a )






def     lowerCamelCase__				(   a ) ->  List[Any]:
   global graph, reversed_graph, scc, component, visit, stack
   if visit[u]:
      return
   _A:    str						     =			True
   component.append(a )
   for v in reversed_graph[u]:
      dfsa(a )






def     lowerCamelCase__				(   ) ->  str:
   global graph, reversed_graph, scc, component, visit, stack
   for i in range(a ):
      dfs(a )
   _A:    Optional[Any]						     =			[False] * n
   for i in stack[::-1]:
      if visit[i]:
         continue
      _A:    Optional[Any]						     =			[]
      dfsa(a )
      scc.append(a )
   return scc


if __name__ == "__main__":
   # n - no of nodes, m - no of edges
   UpperCAmelCase__     ,UpperCAmelCase__						:	Any	     = list(map(int, input().strip().split()))

   UpperCAmelCase__						:	list[list[int]]	     = [[] for _ in range(n)]  # graph
   UpperCAmelCase__						:	list[list[int]]	     = [[] for i in range(n)]  # reversed graph
   # input graph data (edges)
   for _ in range(m):
      UpperCAmelCase__     ,UpperCAmelCase__						:	str	     = list(map(int, input().strip().split()))
      graph[u].append(v)
      reversed_graph[v].append(u)

   UpperCAmelCase__						:	list[int]	     = []
   UpperCAmelCase__						:	list[bool]	     = [False] * n
   UpperCAmelCase__						:	list[int]	     = []
   UpperCAmelCase__						:	list[int]	     = []
   print(kosaraju())



