





import gc
import unittest

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

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference

class 		SCREAMING_SNAKE_CASE__    (	_UpperCAmelCase						,				unittest.TestCase  ):
      A_						:    Union[str, Any]							=   ShapEPipeline
      A_						:    List[str]							=   ['prompt']
      A_						:    Optional[Any]							=   ['prompt']
      A_						:    List[Any]							=   [
          'num_images_per_prompt',
          'num_inference_steps',
          'generator',
          'latents',
          'guidance_scale',
          'frame_size',
          'output_type',
          'return_dict',
      ]
      A_						:    Any							=   False


      @property
      def        a			(self	:				Optional[int]				):





         """simple docstring"""



         return 32


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





         """simple docstring"""



         return 32


      @property
      def        a			(self	:				Tuple				):





         """simple docstring"""



         return self.time_input_dim * 4


      @property
      def        a			(self	:				int				):





         """simple docstring"""



         return 8


      @property
      def        a			(self	:				Dict				):





         """simple docstring"""



         __snake_case								=       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)
         return tokenizer


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





         """simple docstring"""



         torch.manual_seed(0				)
         __snake_case								=       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=37    ,      layer_norm_eps=1E-05    ,      num_attention_heads=4    ,      num_hidden_layers=5    ,      pad_token_id=1    ,      vocab_size=1000    ,      )
         return CLIPTextModelWithProjection(a__				)


      @property
      def        a			(self	:				Tuple				):





         """simple docstring"""



         torch.manual_seed(0				)

         __snake_case								=       {
             '''num_attention_heads''': 2,
             '''attention_head_dim''': 16,
             '''embedding_dim''': self.time_input_dim,
             '''num_embeddings''': 32,
             '''embedding_proj_dim''': self.text_embedder_hidden_size,
             '''time_embed_dim''': self.time_embed_dim,
             '''num_layers''': 1,
             '''clip_embed_dim''': self.time_input_dim * 2,
             '''additional_embeddings''': 0,
             '''time_embed_act_fn''': '''gelu''',
             '''norm_in_type''': '''layer''',
             '''encoder_hid_proj_type''': None,
             '''added_emb_type''': None,
         }

         __snake_case								=       PriorTransformer(**a__				)
         return model


      @property
      def        a			(self	:				int				):





         """simple docstring"""



         torch.manual_seed(0				)

         __snake_case								=       {
             '''param_shapes''': (
                 (self.renderer_dim, 93),
                 (self.renderer_dim, 8),
                 (self.renderer_dim, 8),
                 (self.renderer_dim, 8),
             ),
             '''d_latent''': self.time_input_dim,
             '''d_hidden''': self.renderer_dim,
             '''n_output''': 12,
             '''background''': (
                 0.1,
                 0.1,
                 0.1,
             ),
         }
         __snake_case								=       ShapERenderer(**a__				)
         return model


      def        a			(self	:				Optional[int]				):





         """simple docstring"""



         __snake_case								=       self.dummy_prior
         __snake_case								=       self.dummy_text_encoder
         __snake_case								=       self.dummy_tokenizer
         __snake_case								=       self.dummy_renderer

         __snake_case								=       HeunDiscreteScheduler(
             beta_schedule='''exp'''    ,      num_train_timesteps=1024    ,      prediction_type='''sample'''    ,      use_karras_sigmas=a__    ,      clip_sample=a__    ,      clip_sample_range=1.0    ,      )
         __snake_case								=       {
             '''prior''': prior,
             '''text_encoder''': text_encoder,
             '''tokenizer''': tokenizer,
             '''renderer''': renderer,
             '''scheduler''': scheduler,
         }

         return components


      def        a			(self	:				Dict    ,      a__	:				Optional[Any]    ,      a__	:				Union[str, Any]=0				):





         """simple docstring"""



         if str(a__				).startswith('''mps'''				):
            __snake_case								=       torch.manual_seed(a__				)
         else:
            __snake_case								=       torch.Generator(device=a__				).manual_seed(a__				)
         __snake_case								=       {
             '''prompt''': '''horse''',
             '''generator''': generator,
             '''num_inference_steps''': 1,
             '''frame_size''': 32,
             '''output_type''': '''np''',
         }
         return inputs


      def        a			(self	:				Optional[int]				):





         """simple docstring"""



         __snake_case								=       '''cpu'''

         __snake_case								=       self.get_dummy_components()

         __snake_case								=       self.pipeline_class(**a__				)
         __snake_case								=       pipe.to(a__				)

         pipe.set_progress_bar_config(disable=a__				)

         __snake_case								=       pipe(**self.get_dummy_inputs(a__				)				)
         __snake_case								=       output.images[0]
         __snake_case								=       image[0, -3:, -3:, -1]

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

         __snake_case								=       np.array(
             [
                 0.0_0_0_3_9_2_1_6,
                 0.0_0_0_3_9_2_1_6,
                 0.0_0_0_3_9_2_1_6,
                 0.0_0_0_3_9_2_1_6,
                 0.0_0_0_3_9_2_1_6,
                 0.0_0_0_3_9_2_1_6,
                 0.0_0_0_3_9_2_1_6,
                 0.0_0_0_3_9_2_1_6,
                 0.0_0_0_3_9_2_1_6,
             ]				)

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


      def        a			(self	:				List[str]				):





         """simple docstring"""



         self._test_inference_batch_consistent(batch_sizes=[1, 2]				)


      def        a			(self	:				Dict				):





         """simple docstring"""



         __snake_case								=       torch_device == '''cpu'''
         __snake_case								=       True

         self._test_inference_batch_single_identical(
             batch_size=2    ,      test_max_difference=a__    ,      relax_max_difference=a__    ,      )


      def        a			(self	:				List[str]				):





         """simple docstring"""



         __snake_case								=       self.get_dummy_components()
         __snake_case								=       self.pipeline_class(**a__				)
         __snake_case								=       pipe.to(a__				)
         pipe.set_progress_bar_config(disable=a__				)

         __snake_case								=       1
         __snake_case								=       2

         __snake_case								=       self.get_dummy_inputs(a__				)

         for key in inputs.keys():
            if key in self.batch_params:
               __snake_case								=       batch_size * [inputs[key]]

         __snake_case								=       pipe(**a__    ,      num_images_per_prompt=a__				)[0]

         assert images.shape[0] == batch_size * num_images_per_prompt






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


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





         """simple docstring"""



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


      def        a			(self	:				Tuple				):





         """simple docstring"""



         __snake_case								=       load_numpy(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/shap_e/test_shap_e_np_out.npy'''				)
         __snake_case								=       ShapEPipeline.from_pretrained('''openai/shap-e'''				)
         __snake_case								=       pipe.to(a__				)
         pipe.set_progress_bar_config(disable=a__				)

         __snake_case								=       torch.Generator(device=a__				).manual_seed(0				)

         __snake_case								=       pipe(
             '''a shark'''    ,      generator=a__    ,      guidance_scale=1_5.0    ,      num_inference_steps=64    ,      frame_size=64    ,      output_type='''np'''    ,      ).images[0]

         assert images.shape == (20, 64, 64, 3)

         assert_mean_pixel_difference(a__    ,      a__				)








from __future__ import annotations

snake_case_           =      'Muhammad Umer Farooq'
snake_case_           =      'MIT'
snake_case_           =      '1.0.0'
snake_case_           =      'Muhammad Umer Farooq'
snake_case_           =      'contact@muhammadumerfarooq.me'
snake_case_           =      'Alpha'

import re
from html.parser import HTMLParser
from urllib import parse

import requests

class 		SCREAMING_SNAKE_CASE__    (	_UpperCAmelCase  ):


      def __init__(self	:				Dict    ,      a__	:				str				):





         """simple docstring"""



         super().__init__()
         __snake_case								=       []
         __snake_case								=       domain


      def        a			(self	:				Tuple    ,      a__	:				str    ,      a__	:				list[tuple[str, str | None]]				):





         """simple docstring"""



         if tag == "a":
            # Check the list of defined attributes.
            for name, value in attrs:
               # If href is defined, and not empty nor # print it.
               if name == "href" and value != "#" and value != "":
                  # If not already in urls.
                  if value not in self.urls:
                     __snake_case								=       parse.urljoin(self.domain    ,      a__				)
                     self.urls.append(a__				)






def lowerCamelCase__   (							snake_case_     :  str	)				->    str:
   return ".".join(get_sub_domain_name(snake_case_	).split('''.'''	)[-2:]	)






def lowerCamelCase__   (							snake_case_     :  str	)				->    str:
   return parse.urlparse(snake_case_	).netloc






def lowerCamelCase__   (							snake_case_     :  str = "https://github.com"	)				->    list[str]:
   __snake_case								=       get_domain_name(snake_case_	)

   # Initialize the parser
   __snake_case								=       Parser(snake_case_	)

   try:
      # Open URL
      __snake_case								=       requests.get(snake_case_	)

      # pass the raw HTML to the parser to get links
      parser.feed(r.text	)

      # Get links and loop through
      __snake_case								=       set()
      for link in parser.urls:
         # open URL.
         # read = requests.get(link)
         try:
            __snake_case								=       requests.get(snake_case_	)
            # Get the valid email.
            __snake_case								=       re.findall('''[a-zA-Z0-9]+@''' + domain	,				read.text	)
            # If not in list then append it.
            for email in emails:
               valid_emails.add(snake_case_	)
         except ValueError:
            pass
   except ValueError:
      raise SystemExit(1	)

   # Finally return a sorted list of email addresses with no duplicates.
   return sorted(snake_case_	)


if __name__ == "__main__":
    snake_case_           =      emails_from_url('https://github.com')
    print(F'{len(emails)} emails found:')
    print('\n'.join(sorted(emails)))

