

'''simple docstring'''



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       SCREAMING_SNAKE_CASE       (				UpperCAmelCase__       ):






      '''simple docstring'''






      SCREAMING_SNAKE_CASE__			:					Union[str, Any]     =					42
      SCREAMING_SNAKE_CASE__			:					Any     =					42



class       SCREAMING_SNAKE_CASE       (				nn.Module       ):






      '''simple docstring'''






      SCREAMING_SNAKE_CASE__			:					Any     =					42
      SCREAMING_SNAKE_CASE__			:					Any     =					(16, 32, 96, 256)
      SCREAMING_SNAKE_CASE__			:					Optional[int]     =					jnp.floataa




      def 						__UpperCAmelCase      (       self			:		List[str] ):



          """simple docstring"""





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

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

          _snake_case			:			Tuple				       =		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			:		int  ,       snake_case			:		str ):



          """simple docstring"""





          _snake_case			:			Any				       =		self.conv_in(UpperCAmelCase__ )
          _snake_case			:			List[str]				       =		nn.silu(UpperCAmelCase__ )

          for block in self.blocks:
              _snake_case			:			Optional[int]				       =		block(UpperCAmelCase__ )
              _snake_case			:			List[str]				       =		nn.silu(UpperCAmelCase__ )

          _snake_case			:			str				       =		self.conv_out(UpperCAmelCase__ )

          return embedding



@flax_register_to_config
class       SCREAMING_SNAKE_CASE       (				nn.Module   ,UpperCAmelCase__   ,UpperCAmelCase__       ):






      '''simple docstring'''






      SCREAMING_SNAKE_CASE__			:					Optional[int]     =					32
      SCREAMING_SNAKE_CASE__			:					Optional[Any]     =					4
      SCREAMING_SNAKE_CASE__			:					Any     =					(
          '''CrossAttnDownBlock2D''',
          '''CrossAttnDownBlock2D''',
          '''CrossAttnDownBlock2D''',
          '''DownBlock2D''',
      )
      SCREAMING_SNAKE_CASE__			:					List[Any]     =					False
      SCREAMING_SNAKE_CASE__			:					List[str]     =					(320, 640, 1_280, 1_280)
      SCREAMING_SNAKE_CASE__			:					str     =					2
      SCREAMING_SNAKE_CASE__			:					List[str]     =					8
      SCREAMING_SNAKE_CASE__			:					Dict     =					None
      SCREAMING_SNAKE_CASE__			:					Optional[Any]     =					1_280
      SCREAMING_SNAKE_CASE__			:					int     =					0.0
      SCREAMING_SNAKE_CASE__			:					List[str]     =					False
      SCREAMING_SNAKE_CASE__			:					Any     =					jnp.floataa
      SCREAMING_SNAKE_CASE__			:					Tuple     =					True
      SCREAMING_SNAKE_CASE__			:					Dict     =					0
      SCREAMING_SNAKE_CASE__			:					Dict     =					'''rgb'''
      SCREAMING_SNAKE_CASE__			:					Optional[Any]     =					(16, 32, 96, 256)




      def 						__UpperCAmelCase      (       self			:		Optional[Any]  ,       snake_case			:		jax.random.KeyArray ):



          """simple docstring"""





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

          _snake_case       ,				_snake_case			:			Union[str, Any]				       =		jax.random.split(UpperCAmelCase__ )
          _snake_case			:			Optional[Any]				       =		{'params': params_rng, 'dropout': dropout_rng}

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




      def 						__UpperCAmelCase      (       self			:		Optional[int] ):



          """simple docstring"""





          _snake_case			:			Any				       =		self.block_out_channels
          _snake_case			:			Union[str, 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.
          _snake_case			:			int				       =		self.num_attention_heads or self.attention_head_dim

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

          # time
          _snake_case			:			Union[str, Any]				       =		FlaxTimesteps(
              block_out_channels[0]  ,       flip_sin_to_cos=self.flip_sin_to_cos  ,       freq_shift=self.config.freq_shift )
          _snake_case			:			List[str]				       =		FlaxTimestepEmbedding(UpperCAmelCase__  ,       dtype=self.dtype )

          _snake_case			:			List[str]				       =		FlaxControlNetConditioningEmbedding(
              conditioning_embedding_channels=block_out_channels[0]  ,       block_out_channels=self.conditioning_embedding_out_channels  ,       )

          _snake_case			:			List[str]				       =		self.only_cross_attention
          if isinstance(UpperCAmelCase__  ,       UpperCAmelCase__ ):
              _snake_case			:			Optional[int]				       =		(only_cross_attention,) * len(self.down_block_types )

          if isinstance(UpperCAmelCase__  ,       UpperCAmelCase__ ):
              _snake_case			:			List[Any]				       =		(num_attention_heads,) * len(self.down_block_types )

          # down
          _snake_case			:			Tuple				       =		[]
          _snake_case			:			str				       =		[]

          _snake_case			:			List[str]				       =		block_out_channels[0]

          _snake_case			:			Dict				       =		nn.Conv(
              UpperCAmelCase__  ,       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(UpperCAmelCase__ )

          for i, down_block_type in enumerate(self.down_block_types ):
              _snake_case			:			List[Any]				       =		output_channel
              _snake_case			:			Dict				       =		block_out_channels[i]
              _snake_case			:			Union[str, Any]				       =		i == len(UpperCAmelCase__ ) - 1

              if down_block_type == "CrossAttnDownBlock2D":
                  _snake_case			:			Any				       =		FlaxCrossAttnDownBlockaD(
                      in_channels=UpperCAmelCase__  ,       out_channels=UpperCAmelCase__  ,       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:
                  _snake_case			:			Dict				       =		FlaxDownBlockaD(
                      in_channels=UpperCAmelCase__  ,       out_channels=UpperCAmelCase__  ,       dropout=self.dropout  ,       num_layers=self.layers_per_block  ,       add_downsample=not is_final_block  ,       dtype=self.dtype  ,       )

              down_blocks.append(UpperCAmelCase__ )

              for _ in range(self.layers_per_block ):
                  _snake_case			:			Tuple				       =		nn.Conv(
                      UpperCAmelCase__  ,       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(UpperCAmelCase__ )

              if not is_final_block:
                  _snake_case			:			Optional[Any]				       =		nn.Conv(
                      UpperCAmelCase__  ,       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(UpperCAmelCase__ )

          _snake_case			:			Union[str, Any]				       =		down_blocks
          _snake_case			:			int				       =		controlnet_down_blocks

          # mid
          _snake_case			:			Union[str, Any]				       =		block_out_channels[-1]
          _snake_case			:			Optional[Any]				       =		FlaxUNetMidBlockaDCrossAttn(
              in_channels=UpperCAmelCase__  ,       dropout=self.dropout  ,       num_attention_heads=num_attention_heads[-1]  ,       use_linear_projection=self.use_linear_projection  ,       dtype=self.dtype  ,       )

          _snake_case			:			Any				       =		nn.Conv(
              UpperCAmelCase__  ,       kernel_size=(1, 1)  ,       padding='VALID'  ,       kernel_init=nn.initializers.zeros_init()  ,       bias_init=nn.initializers.zeros_init()  ,       dtype=self.dtype  ,       )




      def __call__(       self			:		List[str]  ,       snake_case			:		Tuple  ,       snake_case			:		Optional[int]  ,       snake_case			:		Any  ,       snake_case			:		int  ,       snake_case			:		float = 1.0  ,       snake_case			:		bool = True  ,       snake_case			:		bool = False  ,       ):



          """simple docstring"""





          _snake_case			:			str				       =		self.controlnet_conditioning_channel_order
          if channel_order == "bgr":
              _snake_case			:			Any				       =		jnp.flip(UpperCAmelCase__  ,       axis=1 )

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

          _snake_case			:			Any				       =		self.time_proj(UpperCAmelCase__ )
          _snake_case			:			str				       =		self.time_embedding(UpperCAmelCase__ )

          # 2. pre-process
          _snake_case			:			Tuple				       =		jnp.transpose(UpperCAmelCase__  ,       (0, 2, 3, 1) )
          _snake_case			:			int				       =		self.conv_in(UpperCAmelCase__ )

          _snake_case			:			Union[str, Any]				       =		jnp.transpose(UpperCAmelCase__  ,       (0, 2, 3, 1) )
          _snake_case			:			int				       =		self.controlnet_cond_embedding(UpperCAmelCase__ )
          sample += controlnet_cond

          # 3. down
          _snake_case			:			Any				       =		(sample,)
          for down_block in self.down_blocks:
              if isinstance(UpperCAmelCase__  ,       UpperCAmelCase__ ):
                  _snake_case       ,				_snake_case			:			List[Any]				       =		down_block(UpperCAmelCase__  ,       UpperCAmelCase__  ,       UpperCAmelCase__  ,       deterministic=not train )
              else:
                  _snake_case       ,				_snake_case			:			int				       =		down_block(UpperCAmelCase__  ,       UpperCAmelCase__  ,       deterministic=not train )
              down_block_res_samples += res_samples

          # 4. mid
          _snake_case			:			Union[str, Any]				       =		self.mid_block(UpperCAmelCase__  ,       UpperCAmelCase__  ,       UpperCAmelCase__  ,       deterministic=not train )

          # 5. contronet blocks
          _snake_case			:			Union[str, Any]				       =		()
          for down_block_res_sample, controlnet_block in zip(UpperCAmelCase__  ,       self.controlnet_down_blocks ):
              _snake_case			:			Dict				       =		controlnet_block(UpperCAmelCase__ )
              controlnet_down_block_res_samples += (down_block_res_sample,)

          _snake_case			:			Tuple				       =		controlnet_down_block_res_samples

          _snake_case			:			List[str]				       =		self.controlnet_mid_block(UpperCAmelCase__ )

          # 6. scaling
          _snake_case			:			List[Any]				       =		[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=UpperCAmelCase__  ,       mid_block_res_sample=UpperCAmelCase__ )









from __future__ import annotations

import requests







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			dict:



       """simple docstring"""

       A__ 					=       f"""https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty"""
       return requests.get(lowercase_		).json()







def SCREAMING_SNAKE_CASE							(			lowercase_ = 10		)  ->			list[dict]:



       """simple docstring"""

       A__ 					=       '''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'''
       A__ 					=       requests.get(lowercase_		).json()[:max_stories]
       return [get_hackernews_story(lowercase_		) for story_id in story_ids]







def SCREAMING_SNAKE_CASE							(			lowercase_ = 10		)  ->			str:



       """simple docstring"""

       A__ 					=       hackernews_top_stories(lowercase_		)
       return "\n".join('''* [{title}]({url})'''.format(**lowercase_		) for story in stories		)


if __name__ == "__main__":
  print(hackernews_top_stories_as_markdown())


