






"""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        lowercase__      (							snake_case__       ):
			_UpperCAmelCase		:jnp.ndarray
			_UpperCAmelCase		:jnp.ndarray







class        lowercase__      (							nn.Module       ):
			_UpperCAmelCase		:int
			_UpperCAmelCase		:Tuple[int]             =			(16, 32, 96, 256)
			_UpperCAmelCase		:jnp.dtype             =			jnp.floataa


			def      UpperCAmelCase__						(				self					:  int ):
										lowerCamelCase_	:							Optional[Any]									=nn.Conv(
										    self.block_out_channels[0]       ,	kernel_size=(3, 3)       ,	padding=((1, 1), (1, 1))       ,	dtype=self.dtype       ,	)

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

										lowerCamelCase_	:							List[str]									=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__					:  List[str] ):
										lowerCamelCase_	:							Union[str, Any]									=self.conv_in(snake_case__ )
										lowerCamelCase_	:							Tuple									=nn.silu(snake_case__ )

										for block in self.blocks:
																	lowerCamelCase_	:							int									=block(snake_case__ )
																	lowerCamelCase_	:							str									=nn.silu(snake_case__ )

										lowerCamelCase_	:							str									=self.conv_out(snake_case__ )

										return embedding







@flax_register_to_config
class        lowercase__      (							nn.Module,       snake_case__,       snake_case__       ):
			_UpperCAmelCase		:int             =			32
			_UpperCAmelCase		:int             =			4
			_UpperCAmelCase		:Tuple[str]             =			(
			    "CrossAttnDownBlock2D",
			    "CrossAttnDownBlock2D",
			    "CrossAttnDownBlock2D",
			    "DownBlock2D",
			)
			_UpperCAmelCase		:Union[bool, Tuple[bool]]             =			False
			_UpperCAmelCase		:Tuple[int]             =			(320, 640, 1280, 1280)
			_UpperCAmelCase		:int             =			2
			_UpperCAmelCase		:Union[int, Tuple[int]]             =			8
			_UpperCAmelCase		:Optional[Union[int, Tuple[int]]]             =			None
			_UpperCAmelCase		:int             =			1280
			_UpperCAmelCase		:float             =			0.0
			_UpperCAmelCase		:bool             =			False
			_UpperCAmelCase		:jnp.dtype             =			jnp.floataa
			_UpperCAmelCase		:bool             =			True
			_UpperCAmelCase		:int             =			0
			_UpperCAmelCase		:str             =			"rgb"
			_UpperCAmelCase		:Tuple[int]             =			(16, 32, 96, 256)


			def      UpperCAmelCase__						(				self					:  int       ,	snake_case__					:  jax.random.KeyArray ):
										# init input tensors
										lowerCamelCase_	:							Tuple									=(1, self.in_channels, self.sample_size, self.sample_size)
										lowerCamelCase_	:							Optional[Any]									=jnp.zeros(snake_case__       ,	dtype=jnp.floataa )
										lowerCamelCase_	:							Any									=jnp.ones((1,)       ,	dtype=jnp.intaa )
										lowerCamelCase_	:							int									=jnp.zeros((1, 1, self.cross_attention_dim)       ,	dtype=jnp.floataa )
										lowerCamelCase_	:							Any									=(1, 3, self.sample_size * 8, self.sample_size * 8)
										lowerCamelCase_	:							str									=jnp.zeros(snake_case__       ,	dtype=jnp.floataa )

										lowerCamelCase_							,						lowerCamelCase_	:							Optional[Any]									=jax.random.split(snake_case__ )
										lowerCamelCase_	:							Any									={"params": params_rng, "dropout": dropout_rng}

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


			def      UpperCAmelCase__						(				self					:  Union[str, Any] ):
										lowerCamelCase_	:							Optional[Any]									=self.block_out_channels
										lowerCamelCase_	:							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.
										lowerCamelCase_	:							Union[str, Any]									=self.num_attention_heads or self.attention_head_dim

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

										# time
										lowerCamelCase_	:							Tuple									=FlaxTimesteps(
										    block_out_channels[0]       ,	flip_sin_to_cos=self.flip_sin_to_cos       ,	freq_shift=self.config.freq_shift )
										lowerCamelCase_	:							Any									=FlaxTimestepEmbedding(snake_case__       ,	dtype=self.dtype )

										lowerCamelCase_	:							List[Any]									=FlaxControlNetConditioningEmbedding(
										    conditioning_embedding_channels=block_out_channels[0]       ,	block_out_channels=self.conditioning_embedding_out_channels       ,	)

										lowerCamelCase_	:							Tuple									=self.only_cross_attention
										if isinstance(snake_case__       ,	snake_case__ ):
																	lowerCamelCase_	:							Dict									=(only_cross_attention,) * len(self.down_block_types )

										if isinstance(snake_case__       ,	snake_case__ ):
																	lowerCamelCase_	:							str									=(num_attention_heads,) * len(self.down_block_types )

										# down
										lowerCamelCase_	:							List[Any]									=[]
										lowerCamelCase_	:							List[str]									=[]

										lowerCamelCase_	:							Optional[int]									=block_out_channels[0]

										lowerCamelCase_	:							Tuple									=nn.Conv(
										    snake_case__       ,	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(snake_case__ )

										for i, down_block_type in enumerate(self.down_block_types ):
																	lowerCamelCase_	:							Optional[Any]									=output_channel
																	lowerCamelCase_	:							List[str]									=block_out_channels[i]
																	lowerCamelCase_	:							List[Any]									=i == len(snake_case__ ) - 1

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

																	down_blocks.append(snake_case__ )

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

																	if not is_final_block:
																								lowerCamelCase_	:							List[Any]									=nn.Conv(
																								    snake_case__       ,	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(snake_case__ )

										lowerCamelCase_	:							str									=down_blocks
										lowerCamelCase_	:							List[Any]									=controlnet_down_blocks

										# mid
										lowerCamelCase_	:							Dict									=block_out_channels[-1]
										lowerCamelCase_	:							str									=FlaxUNetMidBlockaDCrossAttn(
										    in_channels=snake_case__       ,	dropout=self.dropout       ,	num_attention_heads=num_attention_heads[-1]       ,	use_linear_projection=self.use_linear_projection       ,	dtype=self.dtype       ,	)

										lowerCamelCase_	:							List[str]									=nn.Conv(
										    snake_case__       ,	kernel_size=(1, 1)       ,	padding="VALID"       ,	kernel_init=nn.initializers.zeros_init()       ,	bias_init=nn.initializers.zeros_init()       ,	dtype=self.dtype       ,	)


			def __call__(				self					:  Optional[Any]       ,	snake_case__					:  Tuple       ,	snake_case__					:  Optional[Any]       ,	snake_case__					:  Any       ,	snake_case__					:  List[Any]       ,	snake_case__					:  float = 1.0       ,	snake_case__					:  bool = True       ,	snake_case__					:  bool = False       ,	):
										lowerCamelCase_	:							Any									=self.controlnet_conditioning_channel_order
										if channel_order == "bgr":
																	lowerCamelCase_	:							List[Any]									=jnp.flip(snake_case__       ,	axis=1 )

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

										lowerCamelCase_	:							Optional[Any]									=self.time_proj(snake_case__ )
										lowerCamelCase_	:							Optional[int]									=self.time_embedding(snake_case__ )

										# 2. pre-process
										lowerCamelCase_	:							Optional[Any]									=jnp.transpose(snake_case__       ,	(0, 2, 3, 1) )
										lowerCamelCase_	:							str									=self.conv_in(snake_case__ )

										lowerCamelCase_	:							Any									=jnp.transpose(snake_case__       ,	(0, 2, 3, 1) )
										lowerCamelCase_	:							Any									=self.controlnet_cond_embedding(snake_case__ )
										sample += controlnet_cond

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

										# 4. mid
										lowerCamelCase_	:							Any									=self.mid_block(snake_case__       ,	snake_case__       ,	snake_case__       ,	deterministic=not train )

										# 5. contronet blocks
										lowerCamelCase_	:							Dict									=()
										for down_block_res_sample, controlnet_block in zip(snake_case__       ,	self.controlnet_down_blocks ):
																	lowerCamelCase_	:							Optional[Any]									=controlnet_block(snake_case__ )
																	controlnet_down_block_res_samples += (down_block_res_sample,)

										lowerCamelCase_	:							Any									=controlnet_down_block_res_samples

										lowerCamelCase_	:							List[str]									=self.controlnet_mid_block(snake_case__ )

										# 6. scaling
										lowerCamelCase_	:							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=snake_case__       ,	mid_block_res_sample=snake_case__ )











"""simple docstring"""



import itertools
from dataclasses import dataclass
from typing import List, Optional

import pyarrow as pa
import pyarrow.parquet as pq

import datasets
from datasets.table import table_cast


A__	:    List[str]			 = datasets.utils.logging.get_logger(__name__)







@dataclass
class        lowercase__      (							datasets.BuilderConfig       ):
			_UpperCAmelCase		:int             =			10000
			_UpperCAmelCase		:Optional[List[str]]             =			None
			_UpperCAmelCase		:Optional[datasets.Features]             =			None







class        lowercase__      (							datasets.ArrowBasedBuilder       ):
			_UpperCAmelCase		:Optional[int]             =			ParquetConfig


			def      UpperCAmelCase__						(				self					:  Optional[int] ):
										return datasets.DatasetInfo(features=self.config.features )


			def      UpperCAmelCase__						(				self					:  List[Any]       ,	snake_case__					:  List[Any] ):
										if not self.config.data_files:
																	raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" )
										lowerCamelCase_	:							str									=dl_manager.download_and_extract(self.config.data_files )
										if isinstance(snake_case__       ,	(str, list, tuple) ):
																	lowerCamelCase_	:							Dict									=data_files
																	if isinstance(snake_case__       ,	snake_case__ ):
																								lowerCamelCase_	:							List[Any]									=[files]
																	# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
																	lowerCamelCase_	:							Any									=[dl_manager.iter_files(snake_case__ ) for file in files]
																	return [datasets.SplitGenerator(name=datasets.Split.TRAIN       ,	gen_kwargs={"files": files} )]
										lowerCamelCase_	:							Optional[int]									=[]
										for split_name, files in data_files.items():
																	if isinstance(snake_case__       ,	snake_case__ ):
																								lowerCamelCase_	:							Optional[int]									=[files]
																	# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
																	lowerCamelCase_	:							int									=[dl_manager.iter_files(snake_case__ ) for file in files]
																	# Infer features is they are stoed in the arrow schema
																	if self.info.features is None:
																								for file in itertools.chain.from_iterable(snake_case__ ):
																															with open(snake_case__       ,	"rb" ) as f:
																																						lowerCamelCase_	:							List[Any]									=datasets.Features.from_arrow_schema(pq.read_schema(snake_case__ ) )
																															break
																	splits.append(datasets.SplitGenerator(name=snake_case__       ,	gen_kwargs={"files": files} ) )
										return splits


			def      UpperCAmelCase__						(				self					:  int       ,	snake_case__					:  pa.Table ):
										if self.info.features is not None:
																	# more expensive cast to support nested features with keys in a different order
																	# allows str <-> int/float or str to Audio for example
																	lowerCamelCase_	:							List[str]									=table_cast(snake_case__       ,	self.info.features.arrow_schema )
										return pa_table


			def      UpperCAmelCase__						(				self					:  int       ,	snake_case__					:  Optional[Any] ):
										lowerCamelCase_	:							Tuple									=self.info.features.arrow_schema if self.info.features is not None else None
										if self.info.features is not None and self.config.columns is not None:
																	if sorted(field.name for field in schema ) != sorted(self.config.columns ):
																								raise ValueError(
																								    F"""Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'""" )
										for file_idx, file in enumerate(itertools.chain.from_iterable(snake_case__ ) ):
																	with open(snake_case__       ,	"rb" ) as f:
																								lowerCamelCase_	:							List[str]									=pq.ParquetFile(snake_case__ )
																								try:
																															for batch_idx, record_batch in enumerate(
																															    parquet_file.iter_batches(batch_size=self.config.batch_size       ,	columns=self.config.columns ) ):
																																						lowerCamelCase_	:							Union[str, Any]									=pa.Table.from_batches([record_batch] )
																																						# Uncomment for debugging (will print the Arrow table size and elements)
																																						# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																																						# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																																						yield F"""{file_idx}_{batch_idx}""", self._cast_table(snake_case__ )
																								except ValueError as e:
																															logger.error(F"""Failed to read file '{file}' with error {type(snake_case__ )}: {e}""" )
																															raise



