


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 		lowerCAmelCase     ( _a			):

					'''simple docstring'''

					_A						:			List[Any]									=      42







class 		lowerCAmelCase     ( _a      ,       _a			):

					'''simple docstring'''

					_A						:			int									=      True



					@register_to_config
					def __init__(  self				:	Tuple		,     __a				:	Tuple = 3		,     __a				:	Tuple = 3		,     __a				:	Optional[int] = ("DownEncoderBlock2D",)		,     __a				:	List[str] = ("UpDecoderBlock2D",)		,     __a				:	Any = (64,)		,     __a				:	Tuple = 1		,     __a				:	List[str] = "silu"		,     __a				:	Union[str, Any] = 4		,     __a				:	Union[str, Any] = 32		,     __a				:	Union[str, Any] = 32		,     __a				:	Union[str, Any] = 0.18215		,     )			->  Tuple:


												"""simple docstring"""

												super().__init__()

												# pass init params to Encoder
												__lowercase      :							str				=     Encoder(
												    in_channels=_A		,     out_channels=_A		,     down_block_types=_A		,     block_out_channels=_A		,     layers_per_block=_A		,     act_fn=_A		,     norm_num_groups=_A		,     double_z=_A		,     )

												# pass init params to Decoder
												__lowercase      :							str				=     Decoder(
												    in_channels=_A		,     out_channels=_A		,     up_block_types=_A		,     block_out_channels=_A		,     layers_per_block=_A		,     norm_num_groups=_A		,     act_fn=_A		,     )

												__lowercase      :							List[str]				=     nn.Convad(2 * latent_channels		,     2 * latent_channels		,     1							)
												__lowercase      :							Any				=     nn.Convad(_A		,     _A		,     1							)

												__lowercase      :							str				=     False
												__lowercase      :							Any				=     False

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



					def       lowerCAmelCase				(  self				:	Optional[int]		,     __a				:	int		,     __a				:	Dict=False							)			->  Dict:


												"""simple docstring"""

												if isinstance(_A		,     (Encoder, Decoder)							):
																			__lowercase      :							List[str]				=     value



					def       lowerCAmelCase				(  self				:	Optional[int]		,     __a				:	Optional[int] = True							)			->  str:


												"""simple docstring"""

												__lowercase      :							List[Any]				=     use_tiling



					def       lowerCAmelCase				(  self				:	Any							)			->  Dict:


												"""simple docstring"""

												self.enable_tiling(_A							)



					def       lowerCAmelCase				(  self				:	Tuple							)			->  str:


												"""simple docstring"""

												__lowercase      :							str				=     True



					def       lowerCAmelCase				(  self				:	Tuple							)			->  Dict:


												"""simple docstring"""

												__lowercase      :							Optional[Any]				=     False



					@property
					# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
					def       lowerCAmelCase				(  self				:	Tuple							)			->  Union[str, Any]:


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     {}

												def fn_recursive_add_processors(__a				:	List[str]		,     __a				:	Tuple		,     __a				:	List[str]							):
																			if hasattr(_A		,     """set_processor"""							):
																										__lowercase      :							Dict				=     module.processor

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

																			return processors

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

												return processors



					def       lowerCAmelCase				(  self				:	str		,     __a				:	List[str]							)			->  Optional[int]:


												"""simple docstring"""

												__lowercase      :							Optional[Any]				=     len(self.attn_processors.keys()							)

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

												def fn_recursive_attn_processor(__a				:	Optional[int]		,     __a				:	Union[str, Any]		,     __a				:	List[str]							):
																			if hasattr(_A		,     """set_processor"""							):
																										if not isinstance(_A		,     _A							):
																																	module.set_processor(_A							)
																										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}"		,     _A		,     _A							)

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



					def       lowerCAmelCase				(  self				:	Union[str, Any]							)			->  Any:


												"""simple docstring"""

												self.set_attn_processor(AttnProcessor()							)



					@apply_forward_hook
					def       lowerCAmelCase				(  self				:	List[Any]		,     __a				:	int		,     __a				:	Union[str, Any] = True							)			->  Any:


												"""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(_A		,     return_dict=_A							)

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

												__lowercase      :							Dict				=     self.quant_conv(_A							)
												__lowercase      :							str				=     DiagonalGaussianDistribution(_A							)

												if not return_dict:
																			return (posterior,)

												return AutoencoderKLOutput(latent_dist=_A							)



					def       lowerCAmelCase				(  self				:	Optional[int]		,     __a				:	Optional[Any]		,     __a				:	Optional[Any] = True							)			->  int:


												"""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(_A		,     return_dict=_A							)

												__lowercase      :							Optional[Any]				=     self.post_quant_conv(_A							)
												__lowercase      :							str				=     self.decoder(_A							)

												if not return_dict:
																			return (dec,)

												return DecoderOutput(sample=_A							)



					@apply_forward_hook
					def       lowerCAmelCase				(  self				:	Optional[Any]		,     __a				:	str		,     __a				:	Any = True							)			->  Union[str, Any]:


												"""simple docstring"""

												if self.use_slicing and z.shape[0] > 1:
																			__lowercase      :							Any				=     [self._decode(_A							).sample for z_slice in z.split(1							)]
																			__lowercase      :							Optional[int]				=     torch.cat(_A							)
												else:
																			__lowercase      :							Union[str, Any]				=     self._decode(_A							).sample

												if not return_dict:
																			return (decoded,)

												return DecoderOutput(sample=_A							)



					def       lowerCAmelCase				(  self				:	List[Any]		,     __a				:	int		,     __a				:	Optional[int]		,     __a				:	Any							)			->  List[Any]:


												"""simple docstring"""

												__lowercase      :							List[str]				=     min(a.shape[2]		,     b.shape[2]		,     _A							)
												for y in range(_A							):
																			__lowercase      :							Union[str, Any]				=     a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
												return b



					def       lowerCAmelCase				(  self				:	Dict		,     __a				:	Tuple		,     __a				:	Any		,     __a				:	List[Any]							)			->  Optional[int]:


												"""simple docstring"""

												__lowercase      :							Dict				=     min(a.shape[3]		,     b.shape[3]		,     _A							)
												for x in range(_A							):
																			__lowercase      :							int				=     a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
												return b



					def       lowerCAmelCase				(  self				:	Tuple		,     __a				:	Tuple		,     __a				:	Optional[Any] = True							)			->  Optional[int]:


												"""simple docstring"""

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

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

												__lowercase      :							List[str]				=     torch.cat(_A		,     dim=2							)
												__lowercase      :							List[Any]				=     DiagonalGaussianDistribution(_A							)

												if not return_dict:
																			return (posterior,)

												return AutoencoderKLOutput(latent_dist=_A							)



					def       lowerCAmelCase				(  self				:	Tuple		,     __a				:	List[Any]		,     __a				:	List[Any] = True							)			->  str:


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)							)
												__lowercase      :							List[str]				=     int(self.tile_sample_min_size * self.tile_overlap_factor							)
												__lowercase      :							str				=     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.
												__lowercase      :							int				=     []
												for i in range(0		,     z.shape[2]		,     _A							):
																			__lowercase      :							Union[str, Any]				=     []
																			for j in range(0		,     z.shape[3]		,     _A							):
																										__lowercase      :							Tuple				=     z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
																										__lowercase      :							str				=     self.post_quant_conv(_A							)
																										__lowercase      :							Union[str, Any]				=     self.decoder(_A							)
																										row.append(_A							)
																			rows.append(_A							)
												__lowercase      :							Dict				=     []
												for i, row in enumerate(_A							):
																			__lowercase      :							Optional[int]				=     []
																			for j, tile in enumerate(_A							):
																										# blend the above tile and the left tile
																										# to the current tile and add the current tile to the result row
																										if i > 0:
																																	__lowercase      :							List[str]				=     self.blend_v(rows[i - 1][j]		,     _A		,     _A							)
																										if j > 0:
																																	__lowercase      :							Tuple				=     self.blend_h(row[j - 1]		,     _A		,     _A							)
																										result_row.append(tile[:, :, :row_limit, :row_limit]							)
																			result_rows.append(torch.cat(_A		,     dim=3							)							)

												__lowercase      :							Optional[int]				=     torch.cat(_A		,     dim=2							)
												if not return_dict:
																			return (dec,)

												return DecoderOutput(sample=_A							)



					def       lowerCAmelCase				(  self				:	Optional[Any]		,     __a				:	Tuple		,     __a				:	Optional[int] = False		,     __a				:	List[Any] = True		,     __a				:	List[str] = None		,     )			->  Any:


												"""simple docstring"""

												__lowercase      :							int				=     sample
												__lowercase      :							Any				=     self.encode(_A							).latent_dist
												if sample_posterior:
																			__lowercase      :							List[str]				=     posterior.sample(generator=_A							)
												else:
																			__lowercase      :							int				=     posterior.mode()
												__lowercase      :							Dict				=     self.decode(_A							).sample

												if not return_dict:
																			return (dec,)

												return DecoderOutput(sample=_A							)







import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
	import tensorflow as tf

if is_torch_available():
	import torch


lowerCamelCase : List[Any]						   =       logging.get_logger(__name__)

class 		lowerCAmelCase     :

					'''simple docstring'''

					def __init__(  self				:	List[str]		,     __a				:	str = None		,     __a				:	uuid.UUID = None		,     __a				:	Any=None		,     __a				:	List[Any]=None							)			->  List[Any]:


												"""simple docstring"""

												if not conversation_id:
																			__lowercase      :							Any				=     uuid.uuida()
												if past_user_inputs is None:
																			__lowercase      :							Dict				=     []
												if generated_responses is None:
																			__lowercase      :							Dict				=     []

												__lowercase      :							uuid.UUID				=     conversation_id
												__lowercase      :							List[str]				=     past_user_inputs
												__lowercase      :							List[str]				=     generated_responses
												__lowercase      :							Optional[str]				=     text



					def __eq__(  self				:	Dict		,     __a				:	Dict							)			->  Any:


												"""simple docstring"""

												if not isinstance(__a		,     __a							):
																			return False
												if self.uuid == other.uuid:
																			return True
												return (
												    self.new_user_input == other.new_user_input
												    and self.past_user_inputs == other.past_user_inputs
												    and self.generated_responses == other.generated_responses
												)



					def       lowerCAmelCase				(  self				:	List[str]		,     __a				:	str		,     __a				:	bool = False							)			->  Dict:


												"""simple docstring"""

												if self.new_user_input:
																			if overwrite:
																										logger.warning(
																										    F"User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten "
																										    F"with: \"{text}\"."							)
																										__lowercase      :							Optional[int]				=     text
																			else:
																										logger.warning(
																										    F"User input added while unprocessed input was existing: \"{self.new_user_input}\" new input "
																										    F"ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input"							)
												else:
																			__lowercase      :							Dict				=     text



					def       lowerCAmelCase				(  self				:	int							)			->  Optional[Any]:


												"""simple docstring"""

												if self.new_user_input:
																			self.past_user_inputs.append(self.new_user_input							)
												__lowercase      :							Dict				=     None



					def       lowerCAmelCase				(  self				:	Optional[int]		,     __a				:	str							)			->  List[Any]:


												"""simple docstring"""

												self.generated_responses.append(__a							)



					def       lowerCAmelCase				(  self				:	Any							)			->  Optional[Any]:


												"""simple docstring"""

												for user_input, generated_response in zip(self.past_user_inputs		,     self.generated_responses							):
																			yield True, user_input
																			yield False, generated_response
												if self.new_user_input:
																			yield True, self.new_user_input



					def __repr__(  self				:	int							)			->  str:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     F"Conversation id: {self.uuid} \n"
												for is_user, text in self.iter_texts():
																			__lowercase      :							Optional[Any]				=     """user""" if is_user else """bot"""
																			output += F"{name} >> {text} \n"
												return output







@add_end_docstrings(
    __a      ,       r'''
        min_length_for_response (`int`, *optional*, defaults to 32):
            The minimum length (in number of tokens) for a response.
        minimum_tokens (`int`, *optional*, defaults to 10):
            The minimum length of tokens to leave for a response.
    '''      ,       )
class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

					def __init__(  self				:	Any		,     *__a				:	int		,     **__a				:	str							)			->  Union[str, Any]:


												"""simple docstring"""

												super().__init__(*__a		,     **__a							)
												if self.tokenizer.pad_token_id is None:
																			__lowercase      :							List[Any]				=     self.tokenizer.eos_token



					def       lowerCAmelCase				(  self				:	Union[str, Any]		,     __a				:	int=None		,     __a				:	Tuple=None		,     __a				:	Any=None		,     **__a				:	List[str]							)			->  Optional[int]:


												"""simple docstring"""

												__lowercase      :							List[str]				=     {}
												__lowercase      :							Tuple				=     {}
												__lowercase      :							List[str]				=     {}

												if min_length_for_response is not None:
																			__lowercase      :							Dict				=     min_length_for_response
												if minimum_tokens is not None:
																			__lowercase      :							Union[str, Any]				=     minimum_tokens

												if "max_length" in generate_kwargs:
																			__lowercase      :							Union[str, Any]				=     generate_kwargs["""max_length"""]
																			# self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
												if clean_up_tokenization_spaces is not None:
																			__lowercase      :							Union[str, Any]				=     clean_up_tokenization_spaces

												if generate_kwargs:
																			forward_params.update(__a							)
												return preprocess_params, forward_params, postprocess_params



					def __call__(  self				:	Optional[int]		,     __a				:	Union[Conversation, List[Conversation]]		,     __a				:	Dict=0		,     **__a				:	List[Any]							)			->  Tuple:


												"""simple docstring"""

												__lowercase      :							List[Any]				=     super().__call__(__a		,     num_workers=__a		,     **__a							)
												if isinstance(__a		,     __a							) and len(__a							) == 1:
																			return outputs[0]
												return outputs



					def       lowerCAmelCase				(  self				:	Union[str, Any]		,     __a				:	Conversation		,     __a				:	Tuple=32							)			->  Dict[str, Any]:


												"""simple docstring"""

												if not isinstance(__a		,     __a							):
																			raise ValueError("""ConversationalPipeline, expects Conversation as inputs"""							)
												if conversation.new_user_input is None:
																			raise ValueError(
																			    F"Conversation with UUID {type(conversation.uuid							)} does not contain new user input to process. "
																			    """Add user inputs with the conversation's `add_user_input` method"""							)
												if hasattr(self.tokenizer		,     """_build_conversation_input_ids"""							):
																			__lowercase      :							List[Any]				=     self.tokenizer._build_conversation_input_ids(__a							)
												else:
																			# If the tokenizer cannot handle conversations, we default to only the old version
																			__lowercase      :							Tuple				=     self._legacy_parse_and_tokenize(__a							)

												if self.framework == "pt":
																			__lowercase      :							List[Any]				=     torch.LongTensor([input_ids]							)
												elif self.framework == "tf":
																			__lowercase      :							List[str]				=     tf.constant([input_ids]							)
												return {"input_ids": input_ids, "conversation": conversation}



					def       lowerCAmelCase				(  self				:	Any		,     __a				:	Dict		,     __a				:	Any=10		,     **__a				:	Dict							)			->  Optional[Any]:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     generate_kwargs.get("""max_length"""		,     self.model.config.max_length							)

												__lowercase      :							List[Any]				=     model_inputs["""input_ids"""].shape[1]
												if max_length - minimum_tokens < n:
																			logger.warning(F"Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})"							)
																			__lowercase      :							Any				=     max_length - minimum_tokens
																			__lowercase      :							int				=     model_inputs["""input_ids"""][:, -trim:]
																			if "attention_mask" in model_inputs:
																										__lowercase      :							Dict				=     model_inputs["""attention_mask"""][:, -trim:]
												__lowercase      :							Union[str, Any]				=     model_inputs.pop("""conversation"""							)
												__lowercase      :							Tuple				=     max_length
												__lowercase      :							int				=     self.model.generate(**__a		,     **__a							)
												if self.model.config.is_encoder_decoder:
																			__lowercase      :							Optional[int]				=     1
												else:
																			__lowercase      :							str				=     n
												return {"output_ids": output_ids[:, start_position:], "conversation": conversation}



					def       lowerCAmelCase				(  self				:	int		,     __a				:	Tuple		,     __a				:	List[Any]=True							)			->  List[str]:


												"""simple docstring"""

												__lowercase      :							int				=     model_outputs["""output_ids"""]
												__lowercase      :							Union[str, Any]				=     self.tokenizer.decode(
												    output_ids[0]		,     skip_special_tokens=__a		,     clean_up_tokenization_spaces=__a		,     )
												__lowercase      :							List[str]				=     model_outputs["""conversation"""]
												conversation.mark_processed()
												conversation.append_response(__a							)
												return conversation



					def       lowerCAmelCase				(  self				:	int		,     __a				:	Conversation							)			->  Dict:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     self.tokenizer.eos_token_id
												__lowercase      :							Optional[Any]				=     []
												for is_user, text in conversation.iter_texts():
																			if eos_token_id is not None:
																										input_ids.extend(self.tokenizer.encode(__a		,     add_special_tokens=__a							) + [eos_token_id]							)
																			else:
																										input_ids.extend(self.tokenizer.encode(__a		,     add_special_tokens=__a							)							)

												if len(__a							) > self.tokenizer.model_max_length:
																			__lowercase      :							List[Any]				=     input_ids[-self.tokenizer.model_max_length :]
												return input_ids