


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  :		Optional[Any]		     =	logging.get_logger(__name__)



class  lowerCAmelCase				:



	def __init__(					self ,					snake_case__ = None ,					snake_case__ = None ,					snake_case__=None ,					snake_case__=None    ):

		if not conversation_id:
			lowerCAmelCase					:    str      							= uuid.uuida()
		if past_user_inputs is None:
			lowerCAmelCase					:    str      							= []
		if generated_responses is None:
			lowerCAmelCase					:    Tuple      							= []

		lowerCAmelCase					:    Dict      							= conversation_id
		lowerCAmelCase					:    List[Any]      							= past_user_inputs
		lowerCAmelCase					:    int      							= generated_responses
		lowerCAmelCase					:    Optional[Any]      							= text



	def __eq__(					self ,					snake_case__    ):

		if not isinstance(snake_case__ ,					snake_case__    ):
			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 ,					snake_case__ ,					snake_case__ = False    ):

		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					:    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:
			lowerCAmelCase					:    Optional[int]      							= text



	def 				lowercase     (					self    ):

		if self.new_user_input:
			self.past_user_inputs.append(self.new_user_input    )
		lowerCAmelCase					:    List[Any]      							= None



	def 				lowercase     (					self ,					snake_case__    ):
		self.generated_responses.append(snake_case__    )



	def 				lowercase     (					self    ):

		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    ):
		lowerCAmelCase					:    List[Any]      							= f"Conversation id: {self.uuid} \n"
		for is_user, text in self.iter_texts():
			lowerCAmelCase					:    List[str]      							= 'user' if is_user else 'bot'
			output += f"{name} >> {text} \n"
		return output



@add_end_docstrings(
    _snake_case      ,				R"""\n        min_length_for_response (`int`, *optional*, defaults to 32):\n            The minimum length (in number of tokens) for a response.\n        minimum_tokens (`int`, *optional*, defaults to 10):\n            The minimum length of tokens to leave for a response.\n    """      ,				)
class  lowerCAmelCase				(				_snake_case							):



	def __init__(					self ,					*snake_case__ ,					**snake_case__    ):
		super().__init__(*snake_case__ ,					**snake_case__    )
		if self.tokenizer.pad_token_id is None:
			lowerCAmelCase					:    Optional[int]      							= self.tokenizer.eos_token



	def 				lowercase     (					self ,					snake_case__=None ,					snake_case__=None ,					snake_case__=None ,					**snake_case__    ):
		lowerCAmelCase					:    int      							= {}
		lowerCAmelCase					:    Dict      							= {}
		lowerCAmelCase					:    Optional[Any]      							= {}

		if min_length_for_response is not None:
			lowerCAmelCase					:    int      							= min_length_for_response
		if minimum_tokens is not None:
			lowerCAmelCase					:    str      							= minimum_tokens

		if "max_length" in generate_kwargs:
			lowerCAmelCase					:    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:
			lowerCAmelCase					:    Union[str, Any]      							= clean_up_tokenization_spaces

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



	def __call__(					self ,					snake_case__ ,					snake_case__=0 ,					**snake_case__    ):
		lowerCAmelCase					:    List[str]      							= super().__call__(snake_case__ ,					num_workers=snake_case__ ,					**snake_case__    )
		if isinstance(snake_case__ ,					snake_case__    ) and len(snake_case__    ) == 1:
			return outputs[0]
		return outputs



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=32    ):

		if not isinstance(snake_case__ ,					snake_case__    ):
			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					:    int      							= self.tokenizer._build_conversation_input_ids(snake_case__    )
		else:
			# If the tokenizer cannot handle conversations, we default to only the old version
			lowerCAmelCase					:    Optional[Any]      							= self._legacy_parse_and_tokenize(snake_case__    )

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



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=10 ,					**snake_case__    ):
		lowerCAmelCase					:    List[Any]      							= generate_kwargs.get('max_length' ,					self.model.config.max_length    )

		lowerCAmelCase					:    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})"    )
			lowerCAmelCase					:    Optional[int]      							= max_length - minimum_tokens
			lowerCAmelCase					:    List[Any]      							= model_inputs['input_ids'][:, -trim:]
			if "attention_mask" in model_inputs:
				lowerCAmelCase					:    Dict      							= model_inputs['attention_mask'][:, -trim:]
		lowerCAmelCase					:    str      							= model_inputs.pop('conversation'    )
		lowerCAmelCase					:    str      							= max_length
		lowerCAmelCase					:    int      							= self.model.generate(**snake_case__ ,					**snake_case__    )
		if self.model.config.is_encoder_decoder:
			lowerCAmelCase					:    Union[str, Any]      							= 1
		else:
			lowerCAmelCase					:    Union[str, Any]      							= n
		return {"output_ids": output_ids[:, start_position:], "conversation": conversation}



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=True    ):
		lowerCAmelCase					:    Optional[int]      							= model_outputs['output_ids']
		lowerCAmelCase					:    str      							= self.tokenizer.decode(
		    output_ids[0] ,					skip_special_tokens=snake_case__ ,					clean_up_tokenization_spaces=snake_case__ ,					)
		lowerCAmelCase					:    Union[str, Any]      							= model_outputs['conversation']
		conversation.mark_processed()
		conversation.append_response(snake_case__    )
		return conversation



	def 				lowercase     (					self ,					snake_case__    ):
		lowerCAmelCase					:    str      							= self.tokenizer.eos_token_id
		lowerCAmelCase					:    Optional[int]      							= []
		for is_user, text in conversation.iter_texts():
			if eos_token_id is not None:
				input_ids.extend(self.tokenizer.encode(snake_case__ ,					add_special_tokens=snake_case__    ) + [eos_token_id]    )
			else:
				input_ids.extend(self.tokenizer.encode(snake_case__ ,					add_special_tokens=snake_case__    )    )

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




'''simple docstring'''




import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class  lowerCAmelCase				(				a      ,				unittest.TestCase							):
	_lowerCamelCase   :					List[Any]			      = LDMTextToImagePipeline
	_lowerCamelCase   :					Optional[Any]			      = TEXT_TO_IMAGE_PARAMS - {
	    """negative_prompt""",
	    """negative_prompt_embeds""",
	    """cross_attention_kwargs""",
	    """prompt_embeds""",
	}
	_lowerCamelCase   :					List[str]			      = PipelineTesterMixin.required_optional_params - {
	    """num_images_per_prompt""",
	    """callback""",
	    """callback_steps""",
	}
	_lowerCamelCase   :					Union[str, Any]			      = TEXT_TO_IMAGE_BATCH_PARAMS
	_lowerCamelCase   :					Optional[int]			      = False



	def 				lowercase     (					self    ):
		torch.manual_seed(0    )
		lowerCAmelCase					:    Dict      							= UNetaDConditionModel(
		    block_out_channels=(32, 64) ,					layers_per_block=2 ,					sample_size=32 ,					in_channels=4 ,					out_channels=4 ,					down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,					up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,					cross_attention_dim=32 ,					)
		lowerCAmelCase					:    int      							= DDIMScheduler(
		    beta_start=0.0_0_0_8_5 ,					beta_end=0.0_1_2 ,					beta_schedule='scaled_linear' ,					clip_sample=snake_case__ ,					set_alpha_to_one=snake_case__ ,					)
		torch.manual_seed(0    )
		lowerCAmelCase					:    str      							= AutoencoderKL(
		    block_out_channels=(32, 64) ,					in_channels=3 ,					out_channels=3 ,					down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') ,					up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') ,					latent_channels=4 ,					)
		torch.manual_seed(0    )
		lowerCAmelCase					:    Any      							= CLIPTextConfig(
		    bos_token_id=0 ,					eos_token_id=2 ,					hidden_size=32 ,					intermediate_size=37 ,					layer_norm_eps=1e-0_5 ,					num_attention_heads=4 ,					num_hidden_layers=5 ,					pad_token_id=1 ,					vocab_size=1000 ,					)
		lowerCAmelCase					:    str      							= CLIPTextModel(snake_case__    )
		lowerCAmelCase					:    str      							= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    )

		lowerCAmelCase					:    List[Any]      							= {
		    'unet': unet,
		    'scheduler': scheduler,
		    'vqvae': vae,
		    'bert': text_encoder,
		    'tokenizer': tokenizer,
		}
		return components



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=0    ):
		if str(snake_case__    ).startswith('mps'    ):
			lowerCAmelCase					:    Optional[int]      							= torch.manual_seed(snake_case__    )
		else:
			lowerCAmelCase					:    str      							= torch.Generator(device=snake_case__    ).manual_seed(snake_case__    )
		lowerCAmelCase					:    Tuple      							= {
		    'prompt': 'A painting of a squirrel eating a burger',
		    'generator': generator,
		    'num_inference_steps': 2,
		    'guidance_scale': 6.0,
		    'output_type': 'numpy',
		}
		return inputs



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[str]      							= 'cpu'  # ensure determinism for the device-dependent torch.Generator

		lowerCAmelCase					:    Optional[Any]      							= self.get_dummy_components()
		lowerCAmelCase					:    Optional[Any]      							= LDMTextToImagePipeline(**snake_case__    )
		pipe.to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    Tuple      							= self.get_dummy_inputs(snake_case__    )
		lowerCAmelCase					:    Union[str, Any]      							= pipe(**snake_case__    ).images
		lowerCAmelCase					:    str      							= image[0, -3:, -3:, -1]

		assert image.shape == (1, 16, 16, 3)
		lowerCAmelCase					:    List[Any]      							= np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4]    )

		assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-3



@slow
@require_torch_gpu
class  lowerCAmelCase				(				unittest.TestCase							):



	def 				lowercase     (					self    ):
		super().tearDown()
		gc.collect()
		torch.cuda.empty_cache()



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=torch.floataa ,					snake_case__=0    ):
		lowerCAmelCase					:    List[str]      							= torch.manual_seed(snake_case__    )
		lowerCAmelCase					:    int      							= np.random.RandomState(snake_case__    ).standard_normal((1, 4, 32, 32)    )
		lowerCAmelCase					:    Optional[Any]      							= torch.from_numpy(snake_case__    ).to(device=snake_case__ ,					dtype=snake_case__    )
		lowerCAmelCase					:    List[str]      							= {
		    'prompt': 'A painting of a squirrel eating a burger',
		    'latents': latents,
		    'generator': generator,
		    'num_inference_steps': 3,
		    'guidance_scale': 6.0,
		    'output_type': 'numpy',
		}
		return inputs



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Tuple      							= LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'    ).to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    Optional[Any]      							= self.get_inputs(snake_case__    )
		lowerCAmelCase					:    List[Any]      							= pipe(**snake_case__    ).images
		lowerCAmelCase					:    str      							= image[0, -3:, -3:, -1].flatten()

		assert image.shape == (1, 256, 256, 3)
		lowerCAmelCase					:    Tuple      							= np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8]    )
		lowerCAmelCase					:    int      							= np.abs(expected_slice - image_slice    ).max()
		assert max_diff < 1e-3



@nightly
@require_torch_gpu
class  lowerCAmelCase				(				unittest.TestCase							):



	def 				lowercase     (					self    ):
		super().tearDown()
		gc.collect()
		torch.cuda.empty_cache()



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=torch.floataa ,					snake_case__=0    ):
		lowerCAmelCase					:    List[str]      							= torch.manual_seed(snake_case__    )
		lowerCAmelCase					:    Any      							= np.random.RandomState(snake_case__    ).standard_normal((1, 4, 32, 32)    )
		lowerCAmelCase					:    List[Any]      							= torch.from_numpy(snake_case__    ).to(device=snake_case__ ,					dtype=snake_case__    )
		lowerCAmelCase					:    List[str]      							= {
		    'prompt': 'A painting of a squirrel eating a burger',
		    'latents': latents,
		    'generator': generator,
		    'num_inference_steps': 50,
		    'guidance_scale': 6.0,
		    'output_type': 'numpy',
		}
		return inputs



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[int]      							= LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'    ).to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    int      							= self.get_inputs(snake_case__    )
		lowerCAmelCase					:    Optional[int]      							= pipe(**snake_case__    ).images[0]

		lowerCAmelCase					:    Optional[int]      							= load_numpy(
		    'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'    )
		lowerCAmelCase					:    List[str]      							= np.abs(expected_image - image    ).max()
		assert max_diff < 1e-3
