





from typing import Optional, Tuple, Union

import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from flax.core.frozen_dict import FrozenDict

from ..configuration_utils import ConfigMixin, flax_register_to_config
from ..utils import BaseOutput
from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
from .modeling_flax_utils import FlaxModelMixin
from .unet_ad_blocks_flax import (
    FlaxCrossAttnDownBlockaD,
    FlaxDownBlockaD,
    FlaxUNetMidBlockaDCrossAttn,
)



@flax.struct.dataclass
class       A__     ( __snake_case    ):
      _UpperCAmelCase			:jnp.ndarray
      _UpperCAmelCase			:jnp.ndarray



class       A__     ( nn.Module    ):
      _UpperCAmelCase			:int
      _UpperCAmelCase			:Tuple[int]							=     (1_6, 3_2, 9_6, 2_5_6)
      _UpperCAmelCase			:jnp.dtype							=     jnp.floataa





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     nn.Conv(
           self.block_out_channels[0] ,							kernel_size=(3, 3) ,							padding=((1, 1), (1, 1)) ,							dtype=self.dtype ,							)

       UpperCamelCase			:      Optional[int] 			=     []
       for i in range(len(self.block_out_channels     ) - 1     ):
        UpperCamelCase			:      List[Any] 			=     self.block_out_channels[i]
        UpperCamelCase			:      Tuple 			=     self.block_out_channels[i + 1]
        UpperCamelCase			:      List[str] 			=     nn.Conv(
            A_ ,							kernel_size=(3, 3) ,							padding=((1, 1), (1, 1)) ,							dtype=self.dtype ,							)
        blocks.append(A_     )
        UpperCamelCase			:      List[str] 			=     nn.Conv(
            A_ ,							kernel_size=(3, 3) ,							strides=(2, 2) ,							padding=((1, 1), (1, 1)) ,							dtype=self.dtype ,							)
        blocks.append(A_     )
       UpperCamelCase			:      List[Any] 			=     blocks

       UpperCamelCase			:      Dict 			=     nn.Conv(
           self.conditioning_embedding_channels ,							kernel_size=(3, 3) ,							padding=((1, 1), (1, 1)) ,							kernel_init=nn.initializers.zeros_init() ,							bias_init=nn.initializers.zeros_init() ,							dtype=self.dtype ,							)





      def __call__(				self ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     self.conv_in(A_     )
       UpperCamelCase			:      Any 			=     nn.silu(A_     )

       for block in self.blocks:
        UpperCamelCase			:      int 			=     block(A_     )
        UpperCamelCase			:      Any 			=     nn.silu(A_     )

       UpperCamelCase			:      List[Any] 			=     self.conv_out(A_     )

       return embedding



@flax_register_to_config
class       A__     ( nn.Module ,     __snake_case ,     __snake_case    ):
      _UpperCAmelCase			:int							=     3_2
      _UpperCAmelCase			:int							=     4
      _UpperCAmelCase			:Tuple[str]							=     (
          "CrossAttnDownBlock2D",
          "CrossAttnDownBlock2D",
          "CrossAttnDownBlock2D",
          "DownBlock2D",
      )
      _UpperCAmelCase			:Union[bool, Tuple[bool]]							=     False
      _UpperCAmelCase			:Tuple[int]							=     (3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0)
      _UpperCAmelCase			:int							=     2
      _UpperCAmelCase			:Union[int, Tuple[int]]							=     8
      _UpperCAmelCase			:Optional[Union[int, Tuple[int]]]							=     None
      _UpperCAmelCase			:int							=     1_2_8_0
      _UpperCAmelCase			:float							=     0.0
      _UpperCAmelCase			:bool							=     False
      _UpperCAmelCase			:jnp.dtype							=     jnp.floataa
      _UpperCAmelCase			:bool							=     True
      _UpperCAmelCase			:int							=     0
      _UpperCAmelCase			:str							=     "rgb"
      _UpperCAmelCase			:Tuple[int]							=     (1_6, 3_2, 9_6, 2_5_6)





      def  __UpperCamelCase(				self ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     (1, self.in_channels, self.sample_size, self.sample_size)
       UpperCamelCase			:      Any 			=     jnp.zeros(A_ ,							dtype=jnp.floataa     )
       UpperCamelCase			:      Union[str, Any] 			=     jnp.ones((1,) ,							dtype=jnp.intaa     )
       UpperCamelCase			:      Dict 			=     jnp.zeros((1, 1, self.cross_attention_dim) ,							dtype=jnp.floataa     )
       UpperCamelCase			:      List[str] 			=     (1, 3, self.sample_size * 8, self.sample_size * 8)
       UpperCamelCase			:      Optional[Any] 			=     jnp.zeros(A_ ,							dtype=jnp.floataa     )

       UpperCamelCase			,					UpperCamelCase			:      Union[str, Any] 			=     jax.random.split(A_     )
       UpperCamelCase			:      List[str] 			=     {"params": params_rng, "dropout": dropout_rng}

       return self.init(A_ ,							A_ ,							A_ ,							A_ ,							A_     )["params"]





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     self.block_out_channels
       UpperCamelCase			:      Optional[Any] 			=     block_out_channels[0] * 4

       # If `num_attention_heads` is not defined (which is the case for most models)
       # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
       # The reason for this behavior is to correct for incorrectly named variables that were introduced
       # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
       # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
       # which is why we correct for the naming here.
       UpperCamelCase			:      Dict 			=     self.num_attention_heads or self.attention_head_dim

       # input
       UpperCamelCase			:      int 			=     nn.Conv(
           block_out_channels[0] ,							kernel_size=(3, 3) ,							strides=(1, 1) ,							padding=((1, 1), (1, 1)) ,							dtype=self.dtype ,							)

       # time
       UpperCamelCase			:      Optional[Any] 			=     FlaxTimesteps(
           block_out_channels[0] ,							flip_sin_to_cos=self.flip_sin_to_cos ,							freq_shift=self.config.freq_shift     )
       UpperCamelCase			:      int 			=     FlaxTimestepEmbedding(A_ ,							dtype=self.dtype     )

       UpperCamelCase			:      int 			=     FlaxControlNetConditioningEmbedding(
           conditioning_embedding_channels=block_out_channels[0] ,							block_out_channels=self.conditioning_embedding_out_channels ,							)

       UpperCamelCase			:      Tuple 			=     self.only_cross_attention
       if isinstance(A_ ,							A_     ):
        UpperCamelCase			:      Dict 			=     (only_cross_attention,) * len(self.down_block_types     )

       if isinstance(A_ ,							A_     ):
        UpperCamelCase			:      Any 			=     (num_attention_heads,) * len(self.down_block_types     )

       # down
       UpperCamelCase			:      str 			=     []
       UpperCamelCase			:      Optional[Any] 			=     []

       UpperCamelCase			:      int 			=     block_out_channels[0]

       UpperCamelCase			:      str 			=     nn.Conv(
           A_ ,							kernel_size=(1, 1) ,							padding="VALID" ,							kernel_init=nn.initializers.zeros_init() ,							bias_init=nn.initializers.zeros_init() ,							dtype=self.dtype ,							)
       controlnet_down_blocks.append(A_     )

       for i, down_block_type in enumerate(self.down_block_types     ):
        UpperCamelCase			:      Union[str, Any] 			=     output_channel
        UpperCamelCase			:      Optional[Any] 			=     block_out_channels[i]
        UpperCamelCase			:      int 			=     i == len(A_     ) - 1

        if down_block_type == "CrossAttnDownBlock2D":
         UpperCamelCase			:      List[Any] 			=     FlaxCrossAttnDownBlockaD(
             in_channels=A_ ,							out_channels=A_ ,							dropout=self.dropout ,							num_layers=self.layers_per_block ,							num_attention_heads=num_attention_heads[i] ,							add_downsample=not is_final_block ,							use_linear_projection=self.use_linear_projection ,							only_cross_attention=only_cross_attention[i] ,							dtype=self.dtype ,							)
        else:
         UpperCamelCase			:      Any 			=     FlaxDownBlockaD(
             in_channels=A_ ,							out_channels=A_ ,							dropout=self.dropout ,							num_layers=self.layers_per_block ,							add_downsample=not is_final_block ,							dtype=self.dtype ,							)

        down_blocks.append(A_     )

        for _ in range(self.layers_per_block     ):
         UpperCamelCase			:      List[Any] 			=     nn.Conv(
             A_ ,							kernel_size=(1, 1) ,							padding="VALID" ,							kernel_init=nn.initializers.zeros_init() ,							bias_init=nn.initializers.zeros_init() ,							dtype=self.dtype ,							)
         controlnet_down_blocks.append(A_     )

        if not is_final_block:
         UpperCamelCase			:      int 			=     nn.Conv(
             A_ ,							kernel_size=(1, 1) ,							padding="VALID" ,							kernel_init=nn.initializers.zeros_init() ,							bias_init=nn.initializers.zeros_init() ,							dtype=self.dtype ,							)
         controlnet_down_blocks.append(A_     )

       UpperCamelCase			:      List[str] 			=     down_blocks
       UpperCamelCase			:      List[str] 			=     controlnet_down_blocks

       # mid
       UpperCamelCase			:      int 			=     block_out_channels[-1]
       UpperCamelCase			:      Any 			=     FlaxUNetMidBlockaDCrossAttn(
           in_channels=A_ ,							dropout=self.dropout ,							num_attention_heads=num_attention_heads[-1] ,							use_linear_projection=self.use_linear_projection ,							dtype=self.dtype ,							)

       UpperCamelCase			:      Dict 			=     nn.Conv(
           A_ ,							kernel_size=(1, 1) ,							padding="VALID" ,							kernel_init=nn.initializers.zeros_init() ,							bias_init=nn.initializers.zeros_init() ,							dtype=self.dtype ,							)





      def __call__(				self ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ = 1.0 ,							A_ = True ,							A_ = False ,							):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     self.controlnet_conditioning_channel_order
       if channel_order == "bgr":
        UpperCamelCase			:      str 			=     jnp.flip(A_ ,							axis=1     )

       # 1. time
       if not isinstance(A_ ,							jnp.ndarray     ):
        UpperCamelCase			:      Tuple 			=     jnp.array([timesteps] ,							dtype=jnp.intaa     )
       elif isinstance(A_ ,							jnp.ndarray     ) and len(timesteps.shape     ) == 0:
        UpperCamelCase			:      Optional[Any] 			=     timesteps.astype(dtype=jnp.floataa     )
        UpperCamelCase			:      List[Any] 			=     jnp.expand_dims(A_ ,							0     )

       UpperCamelCase			:      int 			=     self.time_proj(A_     )
       UpperCamelCase			:      List[Any] 			=     self.time_embedding(A_     )

       # 2. pre-process
       UpperCamelCase			:      int 			=     jnp.transpose(A_ ,							(0, 2, 3, 1)     )
       UpperCamelCase			:      Dict 			=     self.conv_in(A_     )

       UpperCamelCase			:      List[Any] 			=     jnp.transpose(A_ ,							(0, 2, 3, 1)     )
       UpperCamelCase			:      Optional[int] 			=     self.controlnet_cond_embedding(A_     )
       sample += controlnet_cond

       # 3. down
       UpperCamelCase			:      Any 			=     (sample,)
       for down_block in self.down_blocks:
        if isinstance(A_ ,							A_     ):
         UpperCamelCase			,					UpperCamelCase			:      Union[str, Any] 			=     down_block(A_ ,							A_ ,							A_ ,							deterministic=not train     )
        else:
         UpperCamelCase			,					UpperCamelCase			:      Any 			=     down_block(A_ ,							A_ ,							deterministic=not train     )
        down_block_res_samples += res_samples

       # 4. mid
       UpperCamelCase			:      Any 			=     self.mid_block(A_ ,							A_ ,							A_ ,							deterministic=not train     )

       # 5. contronet blocks
       UpperCamelCase			:      List[Any] 			=     ()
       for down_block_res_sample, controlnet_block in zip(A_ ,							self.controlnet_down_blocks     ):
        UpperCamelCase			:      Tuple 			=     controlnet_block(A_     )
        controlnet_down_block_res_samples += (down_block_res_sample,)

       UpperCamelCase			:      int 			=     controlnet_down_block_res_samples

       UpperCamelCase			:      Optional[int] 			=     self.controlnet_mid_block(A_     )

       # 6. scaling
       UpperCamelCase			:      str 			=     [sample * conditioning_scale for sample in down_block_res_samples]
       mid_block_res_sample *= conditioning_scale

       if not return_dict:
        return (down_block_res_samples, mid_block_res_sample)

       return FlaxControlNetOutput(
           down_block_res_samples=A_ ,							mid_block_res_sample=A_     )







from __future__ import annotations

__lowerCamelCase :  Optional[int]										=  """Muhammad Umer Farooq"""
__lowerCamelCase :  Tuple										=  """MIT"""
__lowerCamelCase :  Optional[int]										=  """1.0.0"""
__lowerCamelCase :  int										=  """Muhammad Umer Farooq"""
__lowerCamelCase :  Optional[int]										=  """contact@muhammadumerfarooq.me"""
__lowerCamelCase :  Dict										=  """Alpha"""

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

import requests



class       A__     ( __snake_case    ):





      def __init__(				self ,							A_     ):
       '''simple docstring'''




       super().__init__()
       UpperCamelCase			:      list[str] 			=     []
       UpperCamelCase			:      str 			=     domain





      def  __UpperCamelCase(				self ,							A_ ,							A_     ):
       '''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:
           UpperCamelCase			:      Any 			=     parse.urljoin(self.domain ,							A_     )
           self.urls.append(A_     )



def 	A_       (  _lowerCAmelCase  )		->				str:
 return ".".join(get_sub_domain_name(_lowerCAmelCase  ).split("."  )[-2:]  )



def 	A_       (  _lowerCAmelCase  )		->				str:
 return parse.urlparse(_lowerCAmelCase  ).netloc



def 	A_       (  _lowerCAmelCase = "https://github.com"  )		->				list[str]:
 UpperCamelCase			:      int 			=     get_domain_name(_lowerCAmelCase  )

 # Initialize the parser
 UpperCamelCase			:      str 			=     Parser(_lowerCAmelCase  )

 try:
  # Open URL
  UpperCamelCase			:      int 			=     requests.get(_lowerCAmelCase  )

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

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

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


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