



'''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     UpperCAmelCase_       (       unittest.TestCase	):
    """simple docstring"""







    def lowerCamelCase       (    self					:     List[Any]						):
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()




    @property
    def lowerCamelCase       (    self					:     List[Any]						):
          snake_case__  :    Any    						=      1
          snake_case__  :    Optional[Any]    						=      3
          snake_case__  :    Optional[Any]    						=      (32, 32)

          snake_case__  :    Tuple    						=      floats_tensor((batch_size, num_channels) + sizes ,     rng=random.Random(0						)						).to(__lowerCamelCase						)
          return image




    @property
    def lowerCamelCase       (    self					:     Optional[int]						):
          torch.manual_seed(0						)
          snake_case__  :    Any    						=      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 lowerCamelCase       (    self					:     Union[str, Any]						):
          torch.manual_seed(0						)
          snake_case__  :    Optional[Any]    						=      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 lowerCamelCase       (    self					:     Any						):
          torch.manual_seed(0						)
          snake_case__  :    Optional[Any]    						=      RobertaSeriesConfig(
              hidden_size=32 ,     project_dim=32 ,     intermediate_size=37 ,     layer_norm_eps=1E-0_5 ,     num_attention_heads=4 ,     num_hidden_layers=5 ,     pad_token_id=1 ,     vocab_size=5_006 ,     )
          return RobertaSeriesModelWithTransformation(__lowerCamelCase						)




    @property
    def lowerCamelCase       (    self					:     str						):




          def extract(*snake_case_					:     Any ,     **snake_case_					:     str						):







                class     UpperCAmelCase_       :
                    """simple docstring"""







                    def __init__(    self					:     Tuple						):
                          snake_case__  :    Any    						=      torch.ones([0]						)




                    def lowerCamelCase       (    self					:     List[Any] ,     snake_case_					:     Optional[Any]						):
                          self.pixel_values.to(__lowerCamelCase						)
                          return self
                return Out()

          return extract




    def lowerCamelCase       (    self					:     int						):
          snake_case__  :    Any    						=      '''cpu'''  # ensure determinism for the device-dependent torch.Generator
          snake_case__  :    Optional[int]    						=      self.dummy_cond_unet
          snake_case__  :    int    						=      PNDMScheduler(skip_prk_steps=__lowerCamelCase						)
          snake_case__  :    Union[str, Any]    						=      self.dummy_vae
          snake_case__  :    Optional[Any]    						=      self.dummy_text_encoder
          snake_case__  :    int    						=      XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""						)
          snake_case__  :    Dict    						=      77

          snake_case__  :    int    						=      self.dummy_image.to(__lowerCamelCase						)
          snake_case__  :    List[str]    						=      init_image / 2 + 0.5

          # make sure here that pndm scheduler skips prk
          snake_case__  :    Optional[Any]    						=      AltDiffusionImgaImgPipeline(
              unet=__lowerCamelCase ,     scheduler=__lowerCamelCase ,     vae=__lowerCamelCase ,     text_encoder=__lowerCamelCase ,     tokenizer=__lowerCamelCase ,     safety_checker=__lowerCamelCase ,     feature_extractor=self.dummy_extractor ,     )
          snake_case__  :    str    						=      VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor ,     do_normalize=__lowerCamelCase						)
          snake_case__  :    List[str]    						=      alt_pipe.to(__lowerCamelCase						)
          alt_pipe.set_progress_bar_config(disable=__lowerCamelCase						)

          snake_case__  :    Any    						=      '''A painting of a squirrel eating a burger'''
          snake_case__  :    Tuple    						=      torch.Generator(device=__lowerCamelCase						).manual_seed(0						)
          snake_case__  :    List[str]    						=      alt_pipe(
              [prompt] ,     generator=__lowerCamelCase ,     guidance_scale=6.0 ,     num_inference_steps=2 ,     output_type="""np""" ,     image=__lowerCamelCase ,     )

          snake_case__  :    List[Any]    						=      output.images

          snake_case__  :    Union[str, Any]    						=      torch.Generator(device=__lowerCamelCase						).manual_seed(0						)
          snake_case__  :    Optional[Any]    						=      alt_pipe(
              [prompt] ,     generator=__lowerCamelCase ,     guidance_scale=6.0 ,     num_inference_steps=2 ,     output_type="""np""" ,     image=__lowerCamelCase ,     return_dict=__lowerCamelCase ,     )[0]

          snake_case__  :    Optional[Any]    						=      image[0, -3:, -3:, -1]
          snake_case__  :    Optional[int]    						=      image_from_tuple[0, -3:, -3:, -1]

          assert image.shape == (1, 32, 32, 3)
          snake_case__  :    List[Any]    						=      np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]						)

          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 lowerCamelCase       (    self					:     Any						):
          snake_case__  :    Any    						=      self.dummy_cond_unet
          snake_case__  :    Dict    						=      PNDMScheduler(skip_prk_steps=__lowerCamelCase						)
          snake_case__  :    List[Any]    						=      self.dummy_vae
          snake_case__  :    Optional[int]    						=      self.dummy_text_encoder
          snake_case__  :    Tuple    						=      XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""						)
          snake_case__  :    int    						=      77

          snake_case__  :    List[Any]    						=      self.dummy_image.to(__lowerCamelCase						)

          # put models in fp16
          snake_case__  :    Dict    						=      unet.half()
          snake_case__  :    Tuple    						=      vae.half()
          snake_case__  :    int    						=      bert.half()

          # make sure here that pndm scheduler skips prk
          snake_case__  :    Dict    						=      AltDiffusionImgaImgPipeline(
              unet=__lowerCamelCase ,     scheduler=__lowerCamelCase ,     vae=__lowerCamelCase ,     text_encoder=__lowerCamelCase ,     tokenizer=__lowerCamelCase ,     safety_checker=__lowerCamelCase ,     feature_extractor=self.dummy_extractor ,     )
          snake_case__  :    int    						=      VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor ,     do_normalize=__lowerCamelCase						)
          snake_case__  :    str    						=      alt_pipe.to(__lowerCamelCase						)
          alt_pipe.set_progress_bar_config(disable=__lowerCamelCase						)

          snake_case__  :    List[Any]    						=      '''A painting of a squirrel eating a burger'''
          snake_case__  :    str    						=      torch.manual_seed(0						)
          snake_case__  :    int    						=      alt_pipe(
              [prompt] ,     generator=__lowerCamelCase ,     num_inference_steps=2 ,     output_type="""np""" ,     image=__lowerCamelCase ,     ).images

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




    @unittest.skipIf(torch_device != """cuda""" ,     """This test requires a GPU"""						)
    def lowerCamelCase       (    self					:     Tuple						):
          snake_case__  :    Union[str, Any]    						=      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
          snake_case__  :    str    						=      init_image.resize((760, 504)						)

          snake_case__  :    List[Any]    						=      '''BAAI/AltDiffusion'''
          snake_case__  :    List[str]    						=      AltDiffusionImgaImgPipeline.from_pretrained(
              __lowerCamelCase ,     safety_checker=__lowerCamelCase ,     )
          pipe.to(__lowerCamelCase						)
          pipe.set_progress_bar_config(disable=__lowerCamelCase						)
          pipe.enable_attention_slicing()

          snake_case__  :    List[str]    						=      '''A fantasy landscape, trending on artstation'''

          snake_case__  :    List[Any]    						=      torch.manual_seed(0						)
          snake_case__  :    Tuple    						=      pipe(
              prompt=__lowerCamelCase ,     image=__lowerCamelCase ,     strength=0.75 ,     guidance_scale=7.5 ,     generator=__lowerCamelCase ,     output_type="""np""" ,     )
          snake_case__  :    str    						=      output.images[0]

          snake_case__  :    Optional[int]    						=      image[255:258, 383:386, -1]

          assert image.shape == (504, 760, 3)
          snake_case__  :    Optional[Any]    						=      np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]						)

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







@slow
@require_torch_gpu
class     UpperCAmelCase_       (       unittest.TestCase	):
    """simple docstring"""







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




    def lowerCamelCase       (    self					:     List[str]						):
          snake_case__  :    str    						=      load_image(
              """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
              """/img2img/sketch-mountains-input.jpg"""						)
          snake_case__  :    Optional[int]    						=      init_image.resize((768, 512)						)
          snake_case__  :    Optional[Any]    						=      load_numpy(
              """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""						)

          snake_case__  :    Optional[int]    						=      '''BAAI/AltDiffusion'''
          snake_case__  :    Dict    						=      AltDiffusionImgaImgPipeline.from_pretrained(
              __lowerCamelCase ,     safety_checker=__lowerCamelCase ,     )
          pipe.to(__lowerCamelCase						)
          pipe.set_progress_bar_config(disable=__lowerCamelCase						)
          pipe.enable_attention_slicing()

          snake_case__  :    List[Any]    						=      '''A fantasy landscape, trending on artstation'''

          snake_case__  :    int    						=      torch.manual_seed(0						)
          snake_case__  :    Dict    						=      pipe(
              prompt=__lowerCamelCase ,     image=__lowerCamelCase ,     strength=0.75 ,     guidance_scale=7.5 ,     generator=__lowerCamelCase ,     output_type="""np""" ,     )
          snake_case__  :    int    						=      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







"""simple docstring"""



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 		__snake_case					:





 """simple docstring"""


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



     '''simple docstring'''




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

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

 def __eq__(    self					,						__lowerCamelCase  ):



     '''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 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase = False  ):



     '''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}\"."""  )
             __A    :						str						 =     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    :						Union[str, Any]						 =     text

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     self.generated_responses.append(__lowerCamelCase  )

 def 					UpperCamelCase__(    self  ):



     '''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  ):



     '''simple docstring'''




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






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





 """simple docstring"""


 def __init__(    self					,						*__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     super().__init__(*__lowerCamelCase					,						**__lowerCamelCase  )
     if self.tokenizer.pad_token_id is None:
         __A    :						Union[str, Any]						 =     self.tokenizer.eos_token

 def 					UpperCamelCase__(    self					,						__lowerCamelCase=None					,						__lowerCamelCase=None					,						__lowerCamelCase=None					,						**__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						str						 =     {}
     __A    :						List[str]						 =     {}
     __A    :						Any						 =     {}

     if min_length_for_response is not None:
         __A    :						int						 =     min_length_for_response
     if minimum_tokens is not None:
         __A    :						Any						 =     minimum_tokens

     if "max_length" in generate_kwargs:
         __A    :						List[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:
         __A    :						str						 =     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  ):



     '''simple docstring'''




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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase=32  ):



     '''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'''  ):
         __A    :						List[Any]						 =     self.tokenizer._build_conversation_input_ids(__lowerCamelCase  )
     else:
         # If the tokenizer cannot handle conversations, we default to only the old version
         __A    :						int						 =     self._legacy_parse_and_tokenize(__lowerCamelCase  )

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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase=10					,						**__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Tuple						 =     generate_kwargs.get('''max_length'''					,						self.model.config.max_length  )

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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase=True  ):



     '''simple docstring'''




     __A    :						int						 =     model_outputs['''output_ids''']
     __A    :						Optional[int]						 =     self.tokenizer.decode(
         output_ids[0]					,						skip_special_tokens=__lowerCamelCase					,						clean_up_tokenization_spaces=__lowerCamelCase					,						)
     __A    :						Dict						 =     model_outputs['''conversation''']
     conversation.mark_processed()
     conversation.append_response(__lowerCamelCase  )
     return conversation







 def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Tuple						 =     self.tokenizer.eos_token_id
     __A    :						List[str]						 =     []
     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:
         __A    :						List[str]						 =     input_ids[-self.tokenizer.model_max_length :]
     return input_ids




