



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


__snake_case     :Dict			       =logging.get_logger(__name__)



class        lowerCAmelCase__					:


				def __init__(							self      :  str						, __UpperCamelCase      :  str = None						, __UpperCamelCase      :  uuid.UUID = None						, __UpperCamelCase      :  Optional[Any]=None						, __UpperCamelCase      :  str=None       )		->     Optional[int]:
											if not conversation_id:
																		A      						=    uuid.uuida()
											if past_user_inputs is None:
																		A      						=    []
											if generated_responses is None:
																		A      						=    []

											A      						=    conversation_id
											A      						=    past_user_inputs
											A      						=    generated_responses
											A      						=    text


				def __eq__(							self      :  Tuple						, __UpperCamelCase      :  int       )		->     Union[str, Any]:
											if not isinstance(__UpperCamelCase						, __UpperCamelCase       ):
																		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 __UpperCamelCase						(							self      :  str						, __UpperCamelCase      :  str						, __UpperCamelCase      :  bool = False       )		->     Union[str, Any]:
											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}".'''       )
																									A      						=    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:
																		A      						=    text


				def __UpperCamelCase						(							self      :  str       )		->     List[Any]:
											if self.new_user_input:
																		self.past_user_inputs.append(self.new_user_input       )
											A      						=    None


				def __UpperCamelCase						(							self      :  Any						, __UpperCamelCase      :  str       )		->     List[Any]:
											self.generated_responses.append(__UpperCamelCase       )


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





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


				def __init__(							self      :  Tuple						, *__UpperCamelCase      :  Tuple						, **__UpperCamelCase      :  Tuple       )		->     str:
											super().__init__(*__UpperCamelCase						, **__UpperCamelCase       )
											if self.tokenizer.pad_token_id is None:
																		A      						=    self.tokenizer.eos_token


				def __UpperCamelCase						(							self      :  Any						, __UpperCamelCase      :  Optional[Any]=None						, __UpperCamelCase      :  Optional[int]=None						, __UpperCamelCase      :  Optional[Any]=None						, **__UpperCamelCase      :  int       )		->     Optional[Any]:
											A      						=    {}
											A      						=    {}
											A      						=    {}

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

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

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


				def __call__(							self      :  List[str]						, __UpperCamelCase      :  Union[Conversation, List[Conversation]]						, __UpperCamelCase      :  List[str]=0						, **__UpperCamelCase      :  str       )		->     Any:
											A      						=    super().__call__(__UpperCamelCase						, num_workers=__UpperCamelCase						, **__UpperCamelCase       )
											if isinstance(__UpperCamelCase						, __UpperCamelCase       ) and len(__UpperCamelCase       ) == 1:
																		return outputs[0]
											return outputs


				def __UpperCamelCase						(							self      :  Tuple						, __UpperCamelCase      :  Conversation						, __UpperCamelCase      :  Union[str, Any]=32       )		->     Dict[str, Any]:
											if not isinstance(__UpperCamelCase						, __UpperCamelCase       ):
																		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'       ):
																		A      						=    self.tokenizer._build_conversation_input_ids(__UpperCamelCase       )
											else:
																		# If the tokenizer cannot handle conversations, we default to only the old version
																		A      						=    self._legacy_parse_and_tokenize(__UpperCamelCase       )

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


				def __UpperCamelCase						(							self      :  List[str]						, __UpperCamelCase      :  Any						, __UpperCamelCase      :  Union[str, Any]=10						, **__UpperCamelCase      :  Dict       )		->     Any:
											A      						=    generate_kwargs.get('max_length'						, self.model.config.max_length       )

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


				def __UpperCamelCase						(							self      :  Dict						, __UpperCamelCase      :  Dict						, __UpperCamelCase      :  Any=True       )		->     int:
											A      						=    model_outputs['output_ids']
											A      						=    self.tokenizer.decode(
											    output_ids[0]						, skip_special_tokens=__UpperCamelCase						, clean_up_tokenization_spaces=__UpperCamelCase						, )
											A      						=    model_outputs['conversation']
											conversation.mark_processed()
											conversation.append_response(__UpperCamelCase       )
											return conversation


				def __UpperCamelCase						(							self      :  Union[str, Any]						, __UpperCamelCase      :  Conversation       )		->     Dict:
											A      						=    self.tokenizer.eos_token_id
											A      						=    []
											for is_user, text in conversation.iter_texts():
																		if eos_token_id is not None:
																									input_ids.extend(self.tokenizer.encode(__UpperCamelCase						, add_special_tokens=__UpperCamelCase       ) + [eos_token_id]       )
																		else:
																									input_ids.extend(self.tokenizer.encode(__UpperCamelCase						, add_special_tokens=__UpperCamelCase       )       )

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


'''simple docstring'''

import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()






class    snake_case     (      unittest.TestCase		):






				"""simple docstring"""



				def   a__					(    self       )     ->							int:
											# clean up the VRAM after each test
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()



				@property
				def   a__					(    self       )     ->							Optional[int]:
											SCREAMING_SNAKE_CASE_				=				1
											SCREAMING_SNAKE_CASE_				=				3
											SCREAMING_SNAKE_CASE_				=				(32, 32)

											SCREAMING_SNAKE_CASE_				=				floats_tensor((batch_size, num_channels) + sizes,     rng=random.Random(0       )       ).to(_lowercase       )
											return image



				@property
				def   a__					(    self       )     ->							Any:
											torch.manual_seed(0       )
											SCREAMING_SNAKE_CASE_				=				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,     )
											return model



				@property
				def   a__					(    self       )     ->							Tuple:
											torch.manual_seed(0       )
											SCREAMING_SNAKE_CASE_				=				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,     )
											return model



				@property
				def   a__					(    self       )     ->							Tuple:
											torch.manual_seed(0       )
											SCREAMING_SNAKE_CASE_				=				RobertaSeriesConfig(
											    hidden_size=32,     project_dim=32,     intermediate_size=37,     layer_norm_eps=1E-05,     num_attention_heads=4,     num_hidden_layers=5,     pad_token_id=1,     vocab_size=5006,     )
											return RobertaSeriesModelWithTransformation(_lowercase       )



				@property
				def   a__					(    self       )     ->							List[str]:
											def extract(*_lowercase,     **_lowercase       ):






																		class    snake_case     :






																						"""simple docstring"""



																						def __init__(    self       )     ->							Dict:
																													SCREAMING_SNAKE_CASE_				=				torch.ones([0]       )





																						def   a__					(    self,     _lowercase       )     ->							List[str]:
																													self.pixel_values.to(_lowercase       )
																													return self


																		return Out()

											return extract



				def   a__					(    self       )     ->							Tuple:
											SCREAMING_SNAKE_CASE_				=				'cpu'  # ensure determinism for the device-dependent torch.Generator
											SCREAMING_SNAKE_CASE_				=				self.dummy_cond_unet
											SCREAMING_SNAKE_CASE_				=				PNDMScheduler(skip_prk_steps=_lowercase       )
											SCREAMING_SNAKE_CASE_				=				self.dummy_vae
											SCREAMING_SNAKE_CASE_				=				self.dummy_text_encoder
											SCREAMING_SNAKE_CASE_				=				XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'       )
											SCREAMING_SNAKE_CASE_				=				77

											SCREAMING_SNAKE_CASE_				=				self.dummy_image.to(_lowercase       )
											SCREAMING_SNAKE_CASE_				=				init_image / 2 + 0.5

											# make sure here that pndm scheduler skips prk
											SCREAMING_SNAKE_CASE_				=				AltDiffusionImgaImgPipeline(
											    unet=_lowercase,     scheduler=_lowercase,     vae=_lowercase,     text_encoder=_lowercase,     tokenizer=_lowercase,     safety_checker=_lowercase,     feature_extractor=self.dummy_extractor,     )
											SCREAMING_SNAKE_CASE_				=				VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor,     do_normalize=_lowercase       )
											SCREAMING_SNAKE_CASE_				=				alt_pipe.to(_lowercase       )
											alt_pipe.set_progress_bar_config(disable=_lowercase       )

											SCREAMING_SNAKE_CASE_				=				'A painting of a squirrel eating a burger'
											SCREAMING_SNAKE_CASE_				=				torch.Generator(device=_lowercase       ).manual_seed(0       )
											SCREAMING_SNAKE_CASE_				=				alt_pipe(
											    [prompt],     generator=_lowercase,     guidance_scale=6.0,     num_inference_steps=2,     output_type='np',     image=_lowercase,     )

											SCREAMING_SNAKE_CASE_				=				output.images

											SCREAMING_SNAKE_CASE_				=				torch.Generator(device=_lowercase       ).manual_seed(0       )
											SCREAMING_SNAKE_CASE_				=				alt_pipe(
											    [prompt],     generator=_lowercase,     guidance_scale=6.0,     num_inference_steps=2,     output_type='np',     image=_lowercase,     return_dict=_lowercase,     )[0]

											SCREAMING_SNAKE_CASE_				=				image[0, -3:, -3:, -1]
											SCREAMING_SNAKE_CASE_				=				image_from_tuple[0, -3:, -3:, -1]

											assert image.shape == (1, 32, 32, 3)
											SCREAMING_SNAKE_CASE_				=				np.array([0.4_427, 0.3_731, 0.4_249, 0.4_941, 0.4_546, 0.4_148, 0.4_193, 0.4_666, 0.4_499]       )

											assert np.abs(image_slice.flatten() - expected_slice       ).max() < 5E-3
											assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < 5E-3



				@unittest.skipIf(torch_device != 'cuda',     'This test requires a GPU'       )
				def   a__					(    self       )     ->							str:
											SCREAMING_SNAKE_CASE_				=				self.dummy_cond_unet
											SCREAMING_SNAKE_CASE_				=				PNDMScheduler(skip_prk_steps=_lowercase       )
											SCREAMING_SNAKE_CASE_				=				self.dummy_vae
											SCREAMING_SNAKE_CASE_				=				self.dummy_text_encoder
											SCREAMING_SNAKE_CASE_				=				XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'       )
											SCREAMING_SNAKE_CASE_				=				77

											SCREAMING_SNAKE_CASE_				=				self.dummy_image.to(_lowercase       )

											# put models in fp16
											SCREAMING_SNAKE_CASE_				=				unet.half()
											SCREAMING_SNAKE_CASE_				=				vae.half()
											SCREAMING_SNAKE_CASE_				=				bert.half()

											# make sure here that pndm scheduler skips prk
											SCREAMING_SNAKE_CASE_				=				AltDiffusionImgaImgPipeline(
											    unet=_lowercase,     scheduler=_lowercase,     vae=_lowercase,     text_encoder=_lowercase,     tokenizer=_lowercase,     safety_checker=_lowercase,     feature_extractor=self.dummy_extractor,     )
											SCREAMING_SNAKE_CASE_				=				VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor,     do_normalize=_lowercase       )
											SCREAMING_SNAKE_CASE_				=				alt_pipe.to(_lowercase       )
											alt_pipe.set_progress_bar_config(disable=_lowercase       )

											SCREAMING_SNAKE_CASE_				=				'A painting of a squirrel eating a burger'
											SCREAMING_SNAKE_CASE_				=				torch.manual_seed(0       )
											SCREAMING_SNAKE_CASE_				=				alt_pipe(
											    [prompt],     generator=_lowercase,     num_inference_steps=2,     output_type='np',     image=_lowercase,     ).images

											assert image.shape == (1, 32, 32, 3)





				@unittest.skipIf(torch_device != 'cuda',     'This test requires a GPU'       )
				def   a__					(    self       )     ->							Optional[Any]:
											SCREAMING_SNAKE_CASE_				=				load_image(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
											    '/img2img/sketch-mountains-input.jpg'       )
											# resize to resolution that is divisible by 8 but not 16 or 32
											SCREAMING_SNAKE_CASE_				=				init_image.resize((760, 504)       )

											SCREAMING_SNAKE_CASE_				=				'BAAI/AltDiffusion'
											SCREAMING_SNAKE_CASE_				=				AltDiffusionImgaImgPipeline.from_pretrained(
											    _lowercase,     safety_checker=_lowercase,     )
											pipe.to(_lowercase       )
											pipe.set_progress_bar_config(disable=_lowercase       )
											pipe.enable_attention_slicing()

											SCREAMING_SNAKE_CASE_				=				'A fantasy landscape, trending on artstation'

											SCREAMING_SNAKE_CASE_				=				torch.manual_seed(0       )
											SCREAMING_SNAKE_CASE_				=				pipe(
											    prompt=_lowercase,     image=_lowercase,     strength=0.75,     guidance_scale=7.5,     generator=_lowercase,     output_type='np',     )
											SCREAMING_SNAKE_CASE_				=				output.images[0]

											SCREAMING_SNAKE_CASE_				=				image[255:258, 383:386, -1]

											assert image.shape == (504, 760, 3)
											SCREAMING_SNAKE_CASE_				=				np.array([0.9_358, 0.9_397, 0.9_599, 0.9_901, 1.0_000, 1.0_000, 0.9_882, 1.0_000, 1.0_000]       )

											assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2






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






				"""simple docstring"""



				def   a__					(    self       )     ->							List[Any]:
											# clean up the VRAM after each test
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()





				def   a__					(    self       )     ->							Optional[int]:
											SCREAMING_SNAKE_CASE_				=				load_image(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
											    '/img2img/sketch-mountains-input.jpg'       )
											SCREAMING_SNAKE_CASE_				=				init_image.resize((768, 512)       )
											SCREAMING_SNAKE_CASE_				=				load_numpy(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'       )

											SCREAMING_SNAKE_CASE_				=				'BAAI/AltDiffusion'
											SCREAMING_SNAKE_CASE_				=				AltDiffusionImgaImgPipeline.from_pretrained(
											    _lowercase,     safety_checker=_lowercase,     )
											pipe.to(_lowercase       )
											pipe.set_progress_bar_config(disable=_lowercase       )
											pipe.enable_attention_slicing()

											SCREAMING_SNAKE_CASE_				=				'A fantasy landscape, trending on artstation'

											SCREAMING_SNAKE_CASE_				=				torch.manual_seed(0       )
											SCREAMING_SNAKE_CASE_				=				pipe(
											    prompt=_lowercase,     image=_lowercase,     strength=0.75,     guidance_scale=7.5,     generator=_lowercase,     output_type='np',     )
											SCREAMING_SNAKE_CASE_				=				output.images[0]

											assert image.shape == (512, 768, 3)
											# img2img is flaky across GPUs even in fp32, so using MAE here
											assert np.abs(expected_image - image       ).max() < 1E-2





