




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


__A								=       logging.get_logger(__name__)







class        __lowerCAmelCase					:

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = None     ,		lowerCamelCase__=None     ,		lowerCamelCase__=None				)       -> Optional[int]:



							'''simple docstring'''
							if not conversation_id:
											__lowerCamelCase									=       uuid.uuida()
							if past_user_inputs is None:
											__lowerCamelCase									=       []
							if generated_responses is None:
											__lowerCamelCase									=       []

							__lowerCamelCase									=       conversation_id
							__lowerCamelCase									=       past_user_inputs
							__lowerCamelCase									=       generated_responses
							__lowerCamelCase									=       text


			def __eq__( self     ,		lowerCamelCase__				)       -> List[Any]:



							'''simple docstring'''
							if not isinstance(lowerCamelCase__     ,		lowerCamelCase__				):
											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  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__ = 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}\"."""				)
															__lowerCamelCase									=       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:
											__lowerCamelCase									=       text


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



							'''simple docstring'''
							if self.new_user_input:
											self.past_user_inputs.append(self.new_user_input				)
							__lowerCamelCase									=       None


			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> Optional[Any]:



							'''simple docstring'''
							self.generated_responses.append(lowerCamelCase__				)


			def  lowercase_       ( self				)       -> Union[str, 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				)       -> List[str]:



							'''simple docstring'''
							__lowerCamelCase									=       f"""Conversation id: {self.uuid} \n"""
							for is_user, text in self.iter_texts():
											__lowerCamelCase									=       'user' if is_user else 'bot'
											output += f"""{name} >> {text} \n"""
							return output







@add_end_docstrings(
    __magic_name__     ,							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					(			__magic_name__					):

			"""simple docstring"""







			def __init__( self     ,		*lowerCamelCase__     ,		**lowerCamelCase__				)       -> List[Any]:



							'''simple docstring'''
							super().__init__(*lowerCamelCase__     ,		**lowerCamelCase__				)
							if self.tokenizer.pad_token_id is None:
											__lowerCamelCase									=       self.tokenizer.eos_token


			def  lowercase_       ( self     ,		lowerCamelCase__=None     ,		lowerCamelCase__=None     ,		lowerCamelCase__=None     ,		**lowerCamelCase__				)       -> List[str]:



							'''simple docstring'''
							__lowerCamelCase									=       {}
							__lowerCamelCase									=       {}
							__lowerCamelCase									=       {}

							if min_length_for_response is not None:
											__lowerCamelCase									=       min_length_for_response
							if minimum_tokens is not None:
											__lowerCamelCase									=       minimum_tokens

							if "max_length" in generate_kwargs:
											__lowerCamelCase									=       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:
											__lowerCamelCase									=       clean_up_tokenization_spaces

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


			def __call__( self     ,		lowerCamelCase__     ,		lowerCamelCase__=0     ,		**lowerCamelCase__				)       -> Optional[int]:



							'''simple docstring'''
							__lowerCamelCase									=       super().__call__(lowerCamelCase__     ,		num_workers=lowerCamelCase__     ,		**lowerCamelCase__				)
							if isinstance(lowerCamelCase__     ,		lowerCamelCase__				) and len(lowerCamelCase__				) == 1:
											return outputs[0]
							return outputs


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__=32				)       -> Dict[str, Any]:



							'''simple docstring'''
							if not isinstance(lowerCamelCase__     ,		lowerCamelCase__				):
											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'				):
											__lowerCamelCase									=       self.tokenizer._build_conversation_input_ids(lowerCamelCase__				)
							else:
											# If the tokenizer cannot handle conversations, we default to only the old version
											__lowerCamelCase									=       self._legacy_parse_and_tokenize(lowerCamelCase__				)

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


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__=10     ,		**lowerCamelCase__				)       -> str:



							'''simple docstring'''
							__lowerCamelCase									=       generate_kwargs.get('max_length'     ,		self.model.config.max_length				)

							__lowerCamelCase									=       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})"""				)
											__lowerCamelCase									=       max_length - minimum_tokens
											__lowerCamelCase									=       model_inputs['input_ids'][:, -trim:]
											if "attention_mask" in model_inputs:
															__lowerCamelCase									=       model_inputs['attention_mask'][:, -trim:]
							__lowerCamelCase									=       model_inputs.pop('conversation'				)
							__lowerCamelCase									=       max_length
							__lowerCamelCase									=       self.model.generate(**lowerCamelCase__     ,		**lowerCamelCase__				)
							if self.model.config.is_encoder_decoder:
											__lowerCamelCase									=       1
							else:
											__lowerCamelCase									=       n
							return {"output_ids": output_ids[:, start_position:], "conversation": conversation}


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__=True				)       -> Union[str, Any]:



							'''simple docstring'''
							__lowerCamelCase									=       model_outputs['output_ids']
							__lowerCamelCase									=       self.tokenizer.decode(
							    output_ids[0]     ,		skip_special_tokens=lowerCamelCase__     ,		clean_up_tokenization_spaces=lowerCamelCase__     ,		)
							__lowerCamelCase									=       model_outputs['conversation']
							conversation.mark_processed()
							conversation.append_response(lowerCamelCase__				)
							return conversation






			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> Dict:



							'''simple docstring'''
							__lowerCamelCase									=       self.tokenizer.eos_token_id
							__lowerCamelCase									=       []
							for is_user, text in conversation.iter_texts():
											if eos_token_id is not None:
															input_ids.extend(self.tokenizer.encode(lowerCamelCase__     ,		add_special_tokens=lowerCamelCase__				) + [eos_token_id]				)
											else:
															input_ids.extend(self.tokenizer.encode(lowerCamelCase__     ,		add_special_tokens=lowerCamelCase__				)				)

							if len(lowerCamelCase__				) > self.tokenizer.model_max_length:
											__lowerCamelCase									=       input_ids[-self.tokenizer.model_max_length :]
							return input_ids








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
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block







@dataclass
class        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			snake_case_  						=			42







class        __lowerCAmelCase					(			__magic_name__     ,							__magic_name__					):

			"""simple docstring"""







			@register_to_config
			def __init__( self     ,		lowerCamelCase__ = 65_536     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = 2     ,		lowerCamelCase__ = 2     ,		lowerCamelCase__ = 0     ,		lowerCamelCase__ = "fourier"     ,		lowerCamelCase__ = True     ,		lowerCamelCase__ = False     ,		lowerCamelCase__ = 0.0     ,		lowerCamelCase__ = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")     ,		lowerCamelCase__ = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")     ,		lowerCamelCase__ = "UNetMidBlock1D"     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = (32, 32, 64)     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = 8     ,		lowerCamelCase__ = 1     ,		lowerCamelCase__ = False     ,		)       -> Dict:



							'''simple docstring'''
							super().__init__()
							__lowerCamelCase									=       sample_size

							# time
							if time_embedding_type == "fourier":
											__lowerCamelCase									=       GaussianFourierProjection(
											    embedding_size=8     ,		set_W_to_weight=lowerCamelCase__     ,		log=lowerCamelCase__     ,		flip_sin_to_cos=lowerCamelCase__				)
											__lowerCamelCase									=       2 * block_out_channels[0]
							elif time_embedding_type == "positional":
											__lowerCamelCase									=       Timesteps(
											    block_out_channels[0]     ,		flip_sin_to_cos=lowerCamelCase__     ,		downscale_freq_shift=lowerCamelCase__				)
											__lowerCamelCase									=       block_out_channels[0]

							if use_timestep_embedding:
											__lowerCamelCase									=       block_out_channels[0] * 4
											__lowerCamelCase									=       TimestepEmbedding(
											    in_channels=lowerCamelCase__     ,		time_embed_dim=lowerCamelCase__     ,		act_fn=lowerCamelCase__     ,		out_dim=block_out_channels[0]     ,		)

							__lowerCamelCase									=       nn.ModuleList([]				)
							__lowerCamelCase									=       None
							__lowerCamelCase									=       nn.ModuleList([]				)
							__lowerCamelCase									=       None

							# down
							__lowerCamelCase									=       in_channels
							for i, down_block_type in enumerate(lowerCamelCase__				):
											__lowerCamelCase									=       output_channel
											__lowerCamelCase									=       block_out_channels[i]

											if i == 0:
															input_channel += extra_in_channels

											__lowerCamelCase									=       i == len(lowerCamelCase__				) - 1

											__lowerCamelCase									=       get_down_block(
											    lowerCamelCase__     ,		num_layers=lowerCamelCase__     ,		in_channels=lowerCamelCase__     ,		out_channels=lowerCamelCase__     ,		temb_channels=block_out_channels[0]     ,		add_downsample=not is_final_block or downsample_each_block     ,		)
											self.down_blocks.append(lowerCamelCase__				)

							# mid
							__lowerCamelCase									=       get_mid_block(
							    lowerCamelCase__     ,		in_channels=block_out_channels[-1]     ,		mid_channels=block_out_channels[-1]     ,		out_channels=block_out_channels[-1]     ,		embed_dim=block_out_channels[0]     ,		num_layers=lowerCamelCase__     ,		add_downsample=lowerCamelCase__     ,		)

							# up
							__lowerCamelCase									=       list(reversed(lowerCamelCase__				)				)
							__lowerCamelCase									=       reversed_block_out_channels[0]
							if out_block_type is None:
											__lowerCamelCase									=       out_channels
							else:
											__lowerCamelCase									=       block_out_channels[0]

							for i, up_block_type in enumerate(lowerCamelCase__				):
											__lowerCamelCase									=       output_channel
											__lowerCamelCase									=       (
											    reversed_block_out_channels[i + 1] if i < len(lowerCamelCase__				) - 1 else final_upsample_channels
											)

											__lowerCamelCase									=       i == len(lowerCamelCase__				) - 1

											__lowerCamelCase									=       get_up_block(
											    lowerCamelCase__     ,		num_layers=lowerCamelCase__     ,		in_channels=lowerCamelCase__     ,		out_channels=lowerCamelCase__     ,		temb_channels=block_out_channels[0]     ,		add_upsample=not is_final_block     ,		)
											self.up_blocks.append(lowerCamelCase__				)
											__lowerCamelCase									=       output_channel

							# out
							__lowerCamelCase									=       norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4     ,		32				)
							__lowerCamelCase									=       get_out_block(
							    out_block_type=lowerCamelCase__     ,		num_groups_out=lowerCamelCase__     ,		embed_dim=block_out_channels[0]     ,		out_channels=lowerCamelCase__     ,		act_fn=lowerCamelCase__     ,		fc_dim=block_out_channels[-1] // 4     ,		)






			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__ = True     ,		)       -> Union[UNetaDOutput, Tuple]:



							'''simple docstring'''
							__lowerCamelCase									=       timestep
							if not torch.is_tensor(lowerCamelCase__				):
											__lowerCamelCase									=       torch.tensor([timesteps]     ,		dtype=torch.long     ,		device=sample.device				)
							elif torch.is_tensor(lowerCamelCase__				) and len(timesteps.shape				) == 0:
											__lowerCamelCase									=       timesteps[None].to(sample.device				)

							__lowerCamelCase									=       self.time_proj(lowerCamelCase__				)
							if self.config.use_timestep_embedding:
											__lowerCamelCase									=       self.time_mlp(lowerCamelCase__				)
							else:
											__lowerCamelCase									=       timestep_embed[..., None]
											__lowerCamelCase									=       timestep_embed.repeat([1, 1, sample.shape[2]]				).to(sample.dtype				)
											__lowerCamelCase									=       timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:])				)

							# 2. down
							__lowerCamelCase									=       ()
							for downsample_block in self.down_blocks:
											__lowerCamelCase			,		__lowerCamelCase									=       downsample_block(hidden_states=lowerCamelCase__     ,		temb=lowerCamelCase__				)
											down_block_res_samples += res_samples

							# 3. mid
							if self.mid_block:
											__lowerCamelCase									=       self.mid_block(lowerCamelCase__     ,		lowerCamelCase__				)

							# 4. up
							for i, upsample_block in enumerate(self.up_blocks				):
											__lowerCamelCase									=       down_block_res_samples[-1:]
											__lowerCamelCase									=       down_block_res_samples[:-1]
											__lowerCamelCase									=       upsample_block(lowerCamelCase__     ,		res_hidden_states_tuple=lowerCamelCase__     ,		temb=lowerCamelCase__				)

							# 5. post-process
							if self.out_block:
											__lowerCamelCase									=       self.out_block(lowerCamelCase__     ,		lowerCamelCase__				)

							if not return_dict:
											return (sample,)

							return UNetaDOutput(sample=lowerCamelCase__				)


