

"""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     a  (				_lowerCamelCase ):



    """simple docstring"""



    UpperCAmelCase         =    4_2
    UpperCAmelCase         =    4_2



class     a  (				nn.Module ):



    """simple docstring"""



    UpperCAmelCase         =    4_2
    UpperCAmelCase         =    (1_6, 3_2, 9_6, 2_5_6)
    UpperCAmelCase         =    jnp.floataa

    def  UpperCamelCase		(   self:       str				):






         """simple docstring"""


         A__								=     nn.Conv(
             self.block_out_channels[0]			,  kernel_size=(3, 3)			,  padding=((1, 1), (1, 1))			,  dtype=self.dtype			,  )

         A__								=     []
         for i in range(len(self.block_out_channels				) - 1				):
              A__								=     self.block_out_channels[i]
              A__								=     self.block_out_channels[i + 1]
              A__								=     nn.Conv(
                  UpperCamelCase			,  kernel_size=(3, 3)			,  padding=((1, 1), (1, 1))			,  dtype=self.dtype			,  )
              blocks.append(UpperCamelCase				)
              A__								=     nn.Conv(
                  UpperCamelCase			,  kernel_size=(3, 3)			,  strides=(2, 2)			,  padding=((1, 1), (1, 1))			,  dtype=self.dtype			,  )
              blocks.append(UpperCamelCase				)
         A__								=     blocks

         A__								=     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:       str			,  UpperCamelCase:       List[str]				):






         """simple docstring"""


         A__								=     self.conv_in(UpperCamelCase				)
         A__								=     nn.silu(UpperCamelCase				)

         for block in self.blocks:
              A__								=     block(UpperCamelCase				)
              A__								=     nn.silu(UpperCamelCase				)

         A__								=     self.conv_out(UpperCamelCase				)

         return embedding



@flax_register_to_config
class     a  (				nn.Module,		_lowerCamelCase,		_lowerCamelCase ):



    """simple docstring"""



    UpperCAmelCase         =    3_2
    UpperCAmelCase         =    4
    UpperCAmelCase         =    (
        "CrossAttnDownBlock2D",
        "CrossAttnDownBlock2D",
        "CrossAttnDownBlock2D",
        "DownBlock2D",
    )
    UpperCAmelCase         =    False
    UpperCAmelCase         =    (3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0)
    UpperCAmelCase         =    2
    UpperCAmelCase         =    8
    UpperCAmelCase         =    None
    UpperCAmelCase         =    1_2_8_0
    UpperCAmelCase         =    0.0
    UpperCAmelCase         =    False
    UpperCAmelCase         =    jnp.floataa
    UpperCAmelCase         =    True
    UpperCAmelCase         =    0
    UpperCAmelCase         =    "rgb"
    UpperCAmelCase         =    (1_6, 3_2, 9_6, 2_5_6)

    def  UpperCamelCase		(   self:       int			,  UpperCamelCase:       jax.random.KeyArray				):






         """simple docstring"""


         A__								=     (1, self.in_channels, self.sample_size, self.sample_size)
         A__								=     jnp.zeros(UpperCamelCase			,  dtype=jnp.floataa				)
         A__								=     jnp.ones((1,)			,  dtype=jnp.intaa				)
         A__								=     jnp.zeros((1, 1, self.cross_attention_dim)			,  dtype=jnp.floataa				)
         A__								=     (1, 3, self.sample_size * 8, self.sample_size * 8)
         A__								=     jnp.zeros(UpperCamelCase			,  dtype=jnp.floataa				)

         A__								=     jax.random.split(UpperCamelCase				)
         A__								=     {'params': params_rng, 'dropout': dropout_rng}

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

    def  UpperCamelCase		(   self:       Any				):






         """simple docstring"""


         A__								=     self.block_out_channels
         A__								=     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.
         A__								=     self.num_attention_heads or self.attention_head_dim

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

         # time
         A__								=     FlaxTimesteps(
             block_out_channels[0]			,  flip_sin_to_cos=self.flip_sin_to_cos			,  freq_shift=self.config.freq_shift				)
         A__								=     FlaxTimestepEmbedding(UpperCamelCase			,  dtype=self.dtype				)

         A__								=     FlaxControlNetConditioningEmbedding(
             conditioning_embedding_channels=block_out_channels[0]			,  block_out_channels=self.conditioning_embedding_out_channels			,  )

         A__								=     self.only_cross_attention
         if isinstance(UpperCamelCase			,  UpperCamelCase				):
              A__								=     (only_cross_attention,) * len(self.down_block_types				)

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

         # down
         A__								=     []
         A__								=     []

         A__								=     block_out_channels[0]

         A__								=     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				):
              A__								=     output_channel
              A__								=     block_out_channels[i]
              A__								=     i == len(UpperCamelCase				) - 1

              if down_block_type == "CrossAttnDownBlock2D":
                   A__								=     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:
                   A__								=     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				):
                   A__								=     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:
                   A__								=     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				)

         A__								=     down_blocks
         A__								=     controlnet_down_blocks

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

         A__								=     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:       Union[str, Any]			,  UpperCamelCase:       List[Any]			,  UpperCamelCase:       List[Any]			,  UpperCamelCase:       Optional[Any]			,  UpperCamelCase:       str			,  UpperCamelCase:       float = 1.0			,  UpperCamelCase:       bool = True			,  UpperCamelCase:       bool = False			,  ):






         """simple docstring"""


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

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

         A__								=     self.time_proj(UpperCamelCase				)
         A__								=     self.time_embedding(UpperCamelCase				)

         # 2. pre-process
         A__								=     jnp.transpose(UpperCamelCase			,  (0, 2, 3, 1)				)
         A__								=     self.conv_in(UpperCamelCase				)

         A__								=     jnp.transpose(UpperCamelCase			,  (0, 2, 3, 1)				)
         A__								=     self.controlnet_cond_embedding(UpperCamelCase				)
         sample += controlnet_cond

         # 3. down
         A__								=     (sample,)
         for down_block in self.down_blocks:
              if isinstance(UpperCamelCase			,  UpperCamelCase				):
                   A__								=     down_block(UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  deterministic=not train				)
              else:
                   A__								=     down_block(UpperCamelCase			,  UpperCamelCase			,  deterministic=not train				)
              down_block_res_samples += res_samples

         # 4. mid
         A__								=     self.mid_block(UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  deterministic=not train				)

         # 5. contronet blocks
         A__								=     ()
         for down_block_res_sample, controlnet_block in zip(UpperCamelCase			,  self.controlnet_down_blocks				):
              A__								=     controlnet_block(UpperCamelCase				)
              controlnet_down_block_res_samples += (down_block_res_sample,)

         A__								=     controlnet_down_block_res_samples

         A__								=     self.controlnet_mid_block(UpperCamelCase				)

         # 6. scaling
         A__								=     [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				)








import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict

from ..features import Audio, ClassLabel, Features
from .base import TaskTemplate







@dataclass(frozen=__magic_name__	)
class      A__							(     __magic_name__	):
				lowercase			    =  field(default='audio-classification'						,   metadata={'include_in_asdict_even_if_is_default': True}	)
				lowercase			    =  Features({'audio': Audio()}	)
				lowercase			    =  Features({'labels': ClassLabel}	)
				lowercase			    =  "audio"
				lowercase			    =  "labels"






				def 							_lowerCamelCase		(						self					:      Dict    ,     a					:      Tuple   ):






							'''simple docstring'''







							if self.label_column not in features:
										raise ValueError(f'''Column {self.label_column} is not present in features.'''   )
							if not isinstance(features[self.label_column]    ,     a   ):
										raise ValueError(f'''Column {self.label_column} is not a ClassLabel.'''   )
							lowerCAmelCase__      :      Tuple         =		copy.deepcopy(self   )
							lowerCAmelCase__      :      List[Any]         =		self.label_schema.copy()
							lowerCAmelCase__      :      List[Any]         =		features[self.label_column]
							lowerCAmelCase__      :      Optional[int]         =		label_schema
							return task_template






				@property
				def 							_lowerCamelCase		(						self					:      List[str]   ):






							'''simple docstring'''







							return {
							    self.audio_column: "audio",
							    self.label_column: "labels",
							}