



'''simple docstring'''

from dataclasses import dataclass
from typing import Dict, Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .attention_processor import AttentionProcessor, AttnProcessor
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder


@dataclass
class 	a__     (				_lowercase	):
	__magic_name__		:    "DiagonalGaussianDistribution"



class 	a__     (				_lowercase,			_lowercase	):
	__magic_name__		:    Tuple	    =     True


	@register_to_config
	def __init__(self : Tuple,					__UpperCAmelCase : int = 3,					__UpperCAmelCase : int = 3,					__UpperCAmelCase : Tuple[str] = ("DownEncoderBlock2D",),					__UpperCAmelCase : Tuple[str] = ("UpDecoderBlock2D",),					__UpperCAmelCase : Tuple[int] = (64,),					__UpperCAmelCase : int = 1,					__UpperCAmelCase : str = "silu",					__UpperCAmelCase : int = 4,					__UpperCAmelCase : int = 32,					__UpperCAmelCase : int = 32,					__UpperCAmelCase : float = 0.1_8215,					)     ->			int:

					"""simple docstring"""

					super().__init__()

					# pass init params to Encoder
					SCREAMING_SNAKE_CASE  :						Tuple      					= Encoder(
					    in_channels=__UpperCAmelCase,					out_channels=__UpperCAmelCase,					down_block_types=__UpperCAmelCase,					block_out_channels=__UpperCAmelCase,					layers_per_block=__UpperCAmelCase,					act_fn=__UpperCAmelCase,					norm_num_groups=__UpperCAmelCase,					double_z=__UpperCAmelCase,					)

					# pass init params to Decoder
					SCREAMING_SNAKE_CASE  :						Optional[Any]      					= Decoder(
					    in_channels=__UpperCAmelCase,					out_channels=__UpperCAmelCase,					up_block_types=__UpperCAmelCase,					block_out_channels=__UpperCAmelCase,					layers_per_block=__UpperCAmelCase,					norm_num_groups=__UpperCAmelCase,					act_fn=__UpperCAmelCase,					)

					SCREAMING_SNAKE_CASE  :						Any      					= nn.Convad(2 * latent_channels,					2 * latent_channels,					1      )
					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= nn.Convad(__UpperCAmelCase,					__UpperCAmelCase,					1      )

					SCREAMING_SNAKE_CASE  :						Optional[int]      					= False
					SCREAMING_SNAKE_CASE  :						Any      					= False

					# only relevant if vae tiling is enabled
					SCREAMING_SNAKE_CASE  :						Any      					= self.config.sample_size
					SCREAMING_SNAKE_CASE  :						int      					= (
					    self.config.sample_size[0]
					    if isinstance(self.config.sample_size,					(list, tuple)      )
					    else self.config.sample_size
					)
					SCREAMING_SNAKE_CASE  :						List[str]      					= int(sample_size / (2 ** (len(self.config.block_out_channels      ) - 1))      )
					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= 0.25


	def 				lowercase__  (self : Tuple,					__UpperCAmelCase : str,					__UpperCAmelCase : Dict=False      )     ->			str:

					"""simple docstring"""

					if isinstance(__UpperCAmelCase,					(Encoder, Decoder)      ):
									SCREAMING_SNAKE_CASE  :						Tuple      					= value


	def 				lowercase__  (self : int,					__UpperCAmelCase : bool = True      )     ->			Tuple:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						Optional[int]      					= use_tiling


	def 				lowercase__  (self : Optional[Any]      )     ->			str:

					"""simple docstring"""

					self.enable_tiling(__UpperCAmelCase      )


	def 				lowercase__  (self : Tuple      )     ->			List[str]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						Tuple      					= True


	def 				lowercase__  (self : Tuple      )     ->			List[Any]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						int      					= False


	@property
	# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
	def 				lowercase__  (self : Any      )     ->			Dict[str, AttentionProcessor]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						Any      					= {}

					def fn_recursive_add_processors(__UpperCAmelCase : str,					__UpperCAmelCase : torch.nn.Module,					__UpperCAmelCase : Dict[str, AttentionProcessor]      ):
									if hasattr(__UpperCAmelCase,					'''set_processor'''      ):
													SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= module.processor

									for sub_name, child in module.named_children():
													fn_recursive_add_processors(F'''{name}.{sub_name}''',					__UpperCAmelCase,					__UpperCAmelCase      )

									return processors

					for name, module in self.named_children():
									fn_recursive_add_processors(__UpperCAmelCase,					__UpperCAmelCase,					__UpperCAmelCase      )

					return processors


	def 				lowercase__  (self : List[Any],					__UpperCAmelCase : Union[AttentionProcessor, Dict[str, AttentionProcessor]]      )     ->			Any:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						int      					= len(self.attn_processors.keys()      )

					if isinstance(__UpperCAmelCase,					__UpperCAmelCase      ) and len(__UpperCAmelCase      ) != count:
									raise ValueError(
									    F'''A dict of processors was passed, but the number of processors {len(__UpperCAmelCase      )} does not match the'''
									    F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.'''      )

					def fn_recursive_attn_processor(__UpperCAmelCase : str,					__UpperCAmelCase : torch.nn.Module,					__UpperCAmelCase : List[Any]      ):
									if hasattr(__UpperCAmelCase,					'''set_processor'''      ):
													if not isinstance(__UpperCAmelCase,					__UpperCAmelCase      ):
																	module.set_processor(__UpperCAmelCase      )
													else:
																	module.set_processor(processor.pop(F'''{name}.processor'''      )      )

									for sub_name, child in module.named_children():
													fn_recursive_attn_processor(F'''{name}.{sub_name}''',					__UpperCAmelCase,					__UpperCAmelCase      )

					for name, module in self.named_children():
									fn_recursive_attn_processor(__UpperCAmelCase,					__UpperCAmelCase,					__UpperCAmelCase      )


	def 				lowercase__  (self : Tuple      )     ->			Tuple:

					"""simple docstring"""

					self.set_attn_processor(AttnProcessor()      )


	@apply_forward_hook
	def 				lowercase__  (self : int,					__UpperCAmelCase : torch.FloatTensor,					__UpperCAmelCase : bool = True      )     ->			AutoencoderKLOutput:

					"""simple docstring"""

					if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
									return self.tiled_encode(__UpperCAmelCase,					return_dict=__UpperCAmelCase      )

					if self.use_slicing and x.shape[0] > 1:
									SCREAMING_SNAKE_CASE  :						Optional[int]      					= [self.encoder(__UpperCAmelCase      ) for x_slice in x.split(1      )]
									SCREAMING_SNAKE_CASE  :						List[Any]      					= torch.cat(__UpperCAmelCase      )
					else:
									SCREAMING_SNAKE_CASE  :						Optional[Any]      					= self.encoder(__UpperCAmelCase      )

					SCREAMING_SNAKE_CASE  :						List[str]      					= self.quant_conv(__UpperCAmelCase      )
					SCREAMING_SNAKE_CASE  :						Optional[int]      					= DiagonalGaussianDistribution(__UpperCAmelCase      )

					if not return_dict:
									return (posterior,)

					return AutoencoderKLOutput(latent_dist=__UpperCAmelCase      )


	def 				lowercase__  (self : str,					__UpperCAmelCase : torch.FloatTensor,					__UpperCAmelCase : bool = True      )     ->			Union[DecoderOutput, torch.FloatTensor]:

					"""simple docstring"""

					if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
									return self.tiled_decode(__UpperCAmelCase,					return_dict=__UpperCAmelCase      )

					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= self.post_quant_conv(__UpperCAmelCase      )
					SCREAMING_SNAKE_CASE  :						Tuple      					= self.decoder(__UpperCAmelCase      )

					if not return_dict:
									return (dec,)

					return DecoderOutput(sample=__UpperCAmelCase      )


	@apply_forward_hook
	def 				lowercase__  (self : Tuple,					__UpperCAmelCase : torch.FloatTensor,					__UpperCAmelCase : bool = True      )     ->			Union[DecoderOutput, torch.FloatTensor]:

					"""simple docstring"""

					if self.use_slicing and z.shape[0] > 1:
									SCREAMING_SNAKE_CASE  :						Dict      					= [self._decode(__UpperCAmelCase      ).sample for z_slice in z.split(1      )]
									SCREAMING_SNAKE_CASE  :						Tuple      					= torch.cat(__UpperCAmelCase      )
					else:
									SCREAMING_SNAKE_CASE  :						Optional[int]      					= self._decode(__UpperCAmelCase      ).sample

					if not return_dict:
									return (decoded,)

					return DecoderOutput(sample=__UpperCAmelCase      )


	def 				lowercase__  (self : Tuple,					__UpperCAmelCase : Optional[Any],					__UpperCAmelCase : List[str],					__UpperCAmelCase : Tuple      )     ->			Union[str, Any]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						Dict      					= min(a.shape[2],					b.shape[2],					__UpperCAmelCase      )
					for y in range(__UpperCAmelCase      ):
									SCREAMING_SNAKE_CASE  :						str      					= a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
					return b


	def 				lowercase__  (self : Tuple,					__UpperCAmelCase : Union[str, Any],					__UpperCAmelCase : str,					__UpperCAmelCase : Optional[int]      )     ->			str:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						Dict      					= min(a.shape[3],					b.shape[3],					__UpperCAmelCase      )
					for x in range(__UpperCAmelCase      ):
									SCREAMING_SNAKE_CASE  :						List[str]      					= a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
					return b


	def 				lowercase__  (self : List[str],					__UpperCAmelCase : torch.FloatTensor,					__UpperCAmelCase : bool = True      )     ->			AutoencoderKLOutput:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						int      					= int(self.tile_sample_min_size * (1 - self.tile_overlap_factor)      )
					SCREAMING_SNAKE_CASE  :						Optional[int]      					= int(self.tile_latent_min_size * self.tile_overlap_factor      )
					SCREAMING_SNAKE_CASE  :						List[str]      					= self.tile_latent_min_size - blend_extent

					# Split the image into 512x512 tiles and encode them separately.
					SCREAMING_SNAKE_CASE  :						Any      					= []
					for i in range(0,					x.shape[2],					__UpperCAmelCase      ):
									SCREAMING_SNAKE_CASE  :						List[Any]      					= []
									for j in range(0,					x.shape[3],					__UpperCAmelCase      ):
													SCREAMING_SNAKE_CASE  :						int      					= x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
													SCREAMING_SNAKE_CASE  :						Optional[int]      					= self.encoder(__UpperCAmelCase      )
													SCREAMING_SNAKE_CASE  :						int      					= self.quant_conv(__UpperCAmelCase      )
													row.append(__UpperCAmelCase      )
									rows.append(__UpperCAmelCase      )
					SCREAMING_SNAKE_CASE  :						Tuple      					= []
					for i, row in enumerate(__UpperCAmelCase      ):
									SCREAMING_SNAKE_CASE  :						str      					= []
									for j, tile in enumerate(__UpperCAmelCase      ):
													# blend the above tile and the left tile
													# to the current tile and add the current tile to the result row
													if i > 0:
																	SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= self.blend_v(rows[i - 1][j],					__UpperCAmelCase,					__UpperCAmelCase      )
													if j > 0:
																	SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= self.blend_h(row[j - 1],					__UpperCAmelCase,					__UpperCAmelCase      )
													result_row.append(tile[:, :, :row_limit, :row_limit]      )
									result_rows.append(torch.cat(__UpperCAmelCase,					dim=3      )      )

					SCREAMING_SNAKE_CASE  :						List[Any]      					= torch.cat(__UpperCAmelCase,					dim=2      )
					SCREAMING_SNAKE_CASE  :						Dict      					= DiagonalGaussianDistribution(__UpperCAmelCase      )

					if not return_dict:
									return (posterior,)

					return AutoencoderKLOutput(latent_dist=__UpperCAmelCase      )


	def 				lowercase__  (self : Tuple,					__UpperCAmelCase : torch.FloatTensor,					__UpperCAmelCase : bool = True      )     ->			Union[DecoderOutput, torch.FloatTensor]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						List[Any]      					= int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)      )
					SCREAMING_SNAKE_CASE  :						str      					= int(self.tile_sample_min_size * self.tile_overlap_factor      )
					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= self.tile_sample_min_size - blend_extent

					# Split z into overlapping 64x64 tiles and decode them separately.
					# The tiles have an overlap to avoid seams between tiles.
					SCREAMING_SNAKE_CASE  :						int      					= []
					for i in range(0,					z.shape[2],					__UpperCAmelCase      ):
									SCREAMING_SNAKE_CASE  :						Optional[Any]      					= []
									for j in range(0,					z.shape[3],					__UpperCAmelCase      ):
													SCREAMING_SNAKE_CASE  :						int      					= z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
													SCREAMING_SNAKE_CASE  :						List[Any]      					= self.post_quant_conv(__UpperCAmelCase      )
													SCREAMING_SNAKE_CASE  :						List[Any]      					= self.decoder(__UpperCAmelCase      )
													row.append(__UpperCAmelCase      )
									rows.append(__UpperCAmelCase      )
					SCREAMING_SNAKE_CASE  :						Tuple      					= []
					for i, row in enumerate(__UpperCAmelCase      ):
									SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= []
									for j, tile in enumerate(__UpperCAmelCase      ):
													# blend the above tile and the left tile
													# to the current tile and add the current tile to the result row
													if i > 0:
																	SCREAMING_SNAKE_CASE  :						List[Any]      					= self.blend_v(rows[i - 1][j],					__UpperCAmelCase,					__UpperCAmelCase      )
													if j > 0:
																	SCREAMING_SNAKE_CASE  :						Tuple      					= self.blend_h(row[j - 1],					__UpperCAmelCase,					__UpperCAmelCase      )
													result_row.append(tile[:, :, :row_limit, :row_limit]      )
									result_rows.append(torch.cat(__UpperCAmelCase,					dim=3      )      )

					SCREAMING_SNAKE_CASE  :						List[Any]      					= torch.cat(__UpperCAmelCase,					dim=2      )
					if not return_dict:
									return (dec,)

					return DecoderOutput(sample=__UpperCAmelCase      )






	def 				lowercase__  (self : int,					__UpperCAmelCase : torch.FloatTensor,					__UpperCAmelCase : bool = False,					__UpperCAmelCase : bool = True,					__UpperCAmelCase : Optional[torch.Generator] = None,					)     ->			Union[DecoderOutput, torch.FloatTensor]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						Optional[Any]      					= sample
					SCREAMING_SNAKE_CASE  :						List[Any]      					= self.encode(__UpperCAmelCase      ).latent_dist
					if sample_posterior:
									SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= posterior.sample(generator=__UpperCAmelCase      )
					else:
									SCREAMING_SNAKE_CASE  :						List[Any]      					= posterior.mode()
					SCREAMING_SNAKE_CASE  :						Any      					= self.decode(__UpperCAmelCase      ).sample

					if not return_dict:
									return (dec,)

					return DecoderOutput(sample=__UpperCAmelCase      )









'''simple docstring'''

import os
from datetime import datetime as dt

from github import Github


snake_case_			=     [
    """good first issue""",
    """good second issue""",
    """good difficult issue""",
    """enhancement""",
    """new pipeline/model""",
    """new scheduler""",
    """wip""",
]






def       __lowercase  ():
				SCREAMING_SNAKE_CASE  :						List[Any]      					= Github(os.environ['''GITHUB_TOKEN''']       )
				SCREAMING_SNAKE_CASE  :						List[str]      					= g.get_repo('''huggingface/diffusers'''       )
				SCREAMING_SNAKE_CASE  :						List[str]      					= repo.get_issues(state='''open'''       )

				for issue in open_issues:
								SCREAMING_SNAKE_CASE  :						List[Any]      					= sorted(issue.get_comments()    ,	key=lambda _SCREAMING_SNAKE_CASE       : i.created_at    ,	reverse=_SCREAMING_SNAKE_CASE       )
								SCREAMING_SNAKE_CASE  :						Optional[int]      					= comments[0] if len(_SCREAMING_SNAKE_CASE       ) > 0 else None
								if (
								    last_comment is not None
								    and last_comment.user.login == "github-actions[bot]"
								    and (dt.utcnow() - issue.updated_at).days > 7
								    and (dt.utcnow() - issue.created_at).days >= 30
								    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()       )
								):
												# Closes the issue after 7 days of inactivity since the Stalebot notification.
												issue.edit(state='''closed'''       )
								elif (
								    "stale" in issue.get_labels()
								    and last_comment is not None
								    and last_comment.user.login != "github-actions[bot]"
								):
												# Opens the issue if someone other than Stalebot commented.
												issue.edit(state='''open'''       )
												issue.remove_from_labels('''stale'''       )
								elif (
								    (dt.utcnow() - issue.updated_at).days > 23
								    and (dt.utcnow() - issue.created_at).days >= 30
								    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()       )
								):
												# Post a Stalebot notification after 23 days of inactivity.
												issue.create_comment(
												    '''This issue has been automatically marked as stale because it has not had '''
												    '''recent activity. If you think this still needs to be addressed '''
												    '''please comment on this thread.\n\nPlease note that issues that do not follow the '''
												    '''[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) '''
												    '''are likely to be ignored.'''       )
												issue.add_to_labels('''stale'''       )


if __name__ == "__main__":
	main()




