from dataclasses import dataclass
from typing import 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 .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer





@dataclass
class 		_lowercase						(					snake_case_       ):
 lowercase				     =   42





class 		_lowercase						(					snake_case_						,      snake_case_       ):

 @register_to_config
 def __init__( self	:							str   ,      snake_case	:							int = 3   ,      snake_case	:							int = 3   ,      snake_case	:							Tuple[str] = ("DownEncoderBlock2D",)   ,      snake_case	:							Tuple[str] = ("UpDecoderBlock2D",)   ,      snake_case	:							Tuple[int] = (6_4,)   ,      snake_case	:							int = 1   ,      snake_case	:							str = "silu"   ,      snake_case	:							int = 3   ,      snake_case	:							int = 3_2   ,      snake_case	:							int = 2_5_6   ,      snake_case	:							int = 3_2   ,      snake_case	:							Optional[int] = None   ,      snake_case	:							float = 0.18215   ,      snake_case	:							str = "group"   ,      )   ->						Tuple:

  """simple docstring"""





  super().__init__()

  # pass init params to Encoder
  UpperCamelCase_					:						Optional[int] =					Encoder(
      in_channels=snake_case   ,      out_channels=snake_case   ,      down_block_types=snake_case   ,      block_out_channels=snake_case   ,      layers_per_block=snake_case   ,      act_fn=snake_case   ,      norm_num_groups=snake_case   ,      double_z=snake_case   ,      )

  UpperCamelCase_					:						Union[str, Any] =					vq_embed_dim if vq_embed_dim is not None else latent_channels

  UpperCamelCase_					:						Any =					nn.Convad(snake_case   ,      snake_case   ,      1			)
  UpperCamelCase_					:						Optional[Any] =					VectorQuantizer(snake_case   ,      snake_case   ,      beta=0.25   ,      remap=snake_case   ,      sane_index_shape=snake_case			)
  UpperCamelCase_					:						Optional[int] =					nn.Convad(snake_case   ,      snake_case   ,      1			)

  # pass init params to Decoder
  UpperCamelCase_					:						List[Any] =					Decoder(
      in_channels=snake_case   ,      out_channels=snake_case   ,      up_block_types=snake_case   ,      block_out_channels=snake_case   ,      layers_per_block=snake_case   ,      act_fn=snake_case   ,      norm_num_groups=snake_case   ,      norm_type=snake_case   ,      )

 @apply_forward_hook
 def 						SCREAMING_SNAKE_CASE__   ( self	:							Union[str, Any]   ,      snake_case	:							torch.FloatTensor   ,      snake_case	:							bool = True			)   ->						VQEncoderOutput:

  """simple docstring"""





  UpperCamelCase_					:						Optional[int] =					self.encoder(snake_case			)
  UpperCamelCase_					:						Any =					self.quant_conv(snake_case			)

  if not return_dict:
   return (h,)

  return VQEncoderOutput(latents=snake_case			)

 @apply_forward_hook
 def 						SCREAMING_SNAKE_CASE__   ( self	:							Union[str, Any]   ,      snake_case	:							torch.FloatTensor   ,      snake_case	:							bool = False   ,      snake_case	:							bool = True			)   ->						Union[DecoderOutput, torch.FloatTensor]:

  """simple docstring"""





  if not force_not_quantize:
   UpperCamelCase_, UpperCamelCase_, UpperCamelCase_					:						Optional[int] =					self.quantize(snake_case			)
  else:
   UpperCamelCase_					:						int =					h
  UpperCamelCase_					:						Optional[int] =					self.post_quant_conv(snake_case			)
  UpperCamelCase_					:						str =					self.decoder(snake_case   ,      quant if self.config.norm_type == 'spatial' else None			)

  if not return_dict:
   return (dec,)

  return DecoderOutput(sample=snake_case			)


 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[int]   ,      snake_case	:							torch.FloatTensor   ,      snake_case	:							bool = True			)   ->						Union[DecoderOutput, torch.FloatTensor]:

  """simple docstring"""





  UpperCamelCase_					:						Optional[int] =					sample
  UpperCamelCase_					:						Tuple =					self.encode(snake_case			).latents
  UpperCamelCase_					:						List[str] =					self.decode(snake_case			).sample

  if not return_dict:
   return (dec,)

  return DecoderOutput(sample=snake_case			)




import builtins
import sys

from ...utils.imports import _is_package_available
from . import cursor, input
from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
from .keymap import KEYMAP


a_    					=       False
try:
   a_    					=       _is_package_available('google.colab')
except ModuleNotFoundError:
   pass





@input.register
class 		_lowercase						:

 def __init__( self	:							Dict   ,      snake_case	:							str = None   ,      snake_case	:							list = []			)   ->						Union[str, Any]:

  """simple docstring"""





  UpperCamelCase_					:						Any =					0
  UpperCamelCase_					:						Optional[Any] =					choices
  UpperCamelCase_					:						Any =					prompt
  if sys.platform == "win32":
   UpperCamelCase_					:						Optional[Any] =					'*'
  else:
   UpperCamelCase_					:						str =					'➔ '

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[int]   ,      snake_case	:							List[str]   ,      snake_case	:							str = ""			)   ->						List[Any]:

  """simple docstring"""





  if sys.platform != "win32":
   writeColor(self.choices[index]   ,      3_2   ,      snake_case			)
  else:
   forceWrite(self.choices[index]   ,      snake_case			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							List[str]   ,      snake_case	:							int			)   ->						List[Any]:

  """simple docstring"""





  if index == self.position:
   forceWrite(f" {self.arrow_char} "			)
   self.write_choice(snake_case			)
  else:
   forceWrite(f"    {self.choices[index]}"			)
  reset_cursor()

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Any   ,      snake_case	:							Direction   ,      snake_case	:							int = 1			)   ->						List[str]:

  """simple docstring"""





  UpperCamelCase_					:						Any =					self.position
  if direction == Direction.DOWN:
   if self.position + 1 >= len(self.choices			):
    return
   self.position += num_spaces
  else:
   if self.position - 1 < 0:
    return
   self.position -= num_spaces
  clear_line()
  self.print_choice(snake_case			)
  move_cursor(snake_case   ,      direction.name			)
  self.print_choice(self.position			)

 @input.mark(KEYMAP['up']			)
 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[int]			)   ->						List[Any]:

  """simple docstring"""





  self.move_direction(Direction.UP			)

 @input.mark(KEYMAP['down']			)
 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[int]			)   ->						Optional[Any]:

  """simple docstring"""





  self.move_direction(Direction.DOWN			)

 @input.mark(KEYMAP['newline']			)
 def 						SCREAMING_SNAKE_CASE__   ( self	:							str			)   ->						Optional[int]:

  """simple docstring"""





  move_cursor(len(self.choices			) - self.position   ,      'DOWN'			)
  return self.position

 @input.mark(KEYMAP['interrupt']			)
 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[Any]			)   ->						Optional[Any]:

  """simple docstring"""





  move_cursor(len(self.choices			) - self.position   ,      'DOWN'			)
  raise KeyboardInterrupt

 @input.mark_multiple(*[KEYMAP[str(snake_case			)] for number in range(1_0			)]			)
 def 						SCREAMING_SNAKE_CASE__   ( self	:							int			)   ->						Dict:

  """simple docstring"""





  UpperCamelCase_					:						List[Any] =					int(chr(self.current_selection			)			)
  UpperCamelCase_					:						Optional[int] =					index - self.position
  if index == self.position:
   return
  if index < len(self.choices			):
   if self.position > index:
    self.move_direction(Direction.UP   ,      -movement			)
   elif self.position < index:
    self.move_direction(Direction.DOWN   ,      snake_case			)
   else:
    return
  else:
   return


 def 						SCREAMING_SNAKE_CASE__   ( self	:							List[Any]   ,      snake_case	:							int = 0			)   ->						Union[str, Any]:

  """simple docstring"""





  if self.prompt:
   linebreak()
   forceWrite(self.prompt   ,      '\n'			)
   if in_colab:
    forceWrite('Please input a choice index (starting from 0), and press enter'   ,      '\n'			)
   else:
    forceWrite('Please select a choice using the arrow or number keys, and selecting with enter'   ,      '\n'			)
  UpperCamelCase_					:						Optional[int] =					default_choice
  for i in range(len(self.choices			)			):
   self.print_choice(snake_case			)
   forceWrite('\n'			)
  move_cursor(len(self.choices			) - self.position   ,      'UP'			)
  with cursor.hide():
   while True:
    if in_colab:
     try:
      UpperCamelCase_					:						Tuple =					int(builtins.input()			)
     except ValueError:
      UpperCamelCase_					:						Tuple =					default_choice
    else:
     UpperCamelCase_					:						Optional[Any] =					self.handle_input()
    if choice is not None:
     reset_cursor()
     for _ in range(len(self.choices			) + 1			):
      move_cursor(1   ,      'UP'			)
      clear_line()
     self.write_choice(snake_case   ,      '\n'			)
     return choice



