


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


_SCREAMING_SNAKE_CASE      :			List[str]      				=   logging.get_logger(__name__)

class   A__ :







    """simple docstring"""

    def __init__(	self      , __snake_case = None      , __snake_case = None      , __snake_case=None      , __snake_case=None   ):
         if not conversation_id:
              snake_case					=    uuid.uuida()
         if past_user_inputs is None:
              snake_case					=    []
         if generated_responses is None:
              snake_case					=    []

         snake_case					=    conversation_id
         snake_case					=    past_user_inputs
         snake_case					=    generated_responses
         snake_case					=    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 		a_      (	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}".'''   )
                   snake_case					=    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:
              snake_case					=    text
    def 		a_      (	self   ):
         if self.new_user_input:
              self.past_user_inputs.append(self.new_user_input   )
         snake_case					=    None
    def 		a_      (	self      , __snake_case   ):
         self.generated_responses.append(__snake_case   )
    def 		a_      (	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   ):
         snake_case					=    F'''Conversation id: {self.uuid} \n'''
         for is_user, text in self.iter_texts():
              snake_case					=    '''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   A__ (   snake_case__     ):







    """simple docstring"""

    def __init__(	self      , *__snake_case      , **__snake_case   ):
         super().__init__(*__snake_case      , **__snake_case   )
         if self.tokenizer.pad_token_id is None:
              snake_case					=    self.tokenizer.eos_token
    def 		a_      (	self      , __snake_case=None      , __snake_case=None      , __snake_case=None      , **__snake_case   ):
         snake_case					=    {}
         snake_case					=    {}
         snake_case					=    {}

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

         if "max_length" in generate_kwargs:
              snake_case					=    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:
              snake_case					=    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   ):
         snake_case					=    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 		a_      (	self      , __snake_case      , __snake_case=3_2   ):
         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'''   ):
              snake_case					=    self.tokenizer._build_conversation_input_ids(__snake_case   )
         else:
              # If the tokenizer cannot handle conversations, we default to only the old version
              snake_case					=    self._legacy_parse_and_tokenize(__snake_case   )

         if self.framework == "pt":
              snake_case					=    torch.LongTensor([input_ids]   )
         elif self.framework == "tf":
              snake_case					=    tf.constant([input_ids]   )
         return {"input_ids": input_ids, "conversation": conversation}
    def 		a_      (	self      , __snake_case      , __snake_case=1_0      , **__snake_case   ):
         snake_case					=    generate_kwargs.get('''max_length'''      , self.model.config.max_length   )

         snake_case					=    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})'''   )
              snake_case					=    max_length - minimum_tokens
              snake_case					=    model_inputs['''input_ids'''][:, -trim:]
              if "attention_mask" in model_inputs:
                   snake_case					=    model_inputs['''attention_mask'''][:, -trim:]
         snake_case					=    model_inputs.pop('''conversation'''   )
         snake_case					=    max_length
         snake_case					=    self.model.generate(**__snake_case      , **__snake_case   )
         if self.model.config.is_encoder_decoder:
              snake_case					=    1
         else:
              snake_case					=    n
         return {"output_ids": output_ids[:, start_position:], "conversation": conversation}
    def 		a_      (	self      , __snake_case      , __snake_case=True   ):
         snake_case					=    model_outputs['''output_ids''']
         snake_case					=    self.tokenizer.decode(
             output_ids[0]      , skip_special_tokens=__snake_case      , clean_up_tokenization_spaces=__snake_case      , )
         snake_case					=    model_outputs['''conversation''']
         conversation.mark_processed()
         conversation.append_response(__snake_case   )
         return conversation




    def 		a_      (	self      , __snake_case   ):
         snake_case					=    self.tokenizer.eos_token_id
         snake_case					=    []
         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:
              snake_case					=    input_ids[-self.tokenizer.model_max_length :]
         return input_ids








import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
 import onnxruntime as ort

class   A__ (   snake_case__	, unittest.TestCase     ):







    """simple docstring"""

    __magic_name__        =		'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'
    def 		a_      (	self      , __snake_case=0   ):
         snake_case					=    floats_tensor((1, 3, 1_2_8, 1_2_8)      , rng=random.Random(__snake_case   )   )
         snake_case					=    np.random.RandomState(__snake_case   )
         snake_case					=    {
             '''prompt''': '''A painting of a squirrel eating a burger''',
             '''image''': image,
             '''generator''': generator,
             '''num_inference_steps''': 3,
             '''strength''': 0.75,
             '''guidance_scale''': 7.5,
             '''output_type''': '''numpy''',
         }
         return inputs
    def 		a_      (	self   ):
         snake_case					=    OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      , provider='''CPUExecutionProvider'''   )
         pipe.set_progress_bar_config(disable=__snake_case   )

         snake_case					=    self.get_dummy_inputs()
         snake_case					=    pipe(**__snake_case   ).images
         snake_case					=    image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 1_2_8, 1_2_8, 3)
         snake_case					=    np.array([0.6_9643, 0.5_8484, 0.5_0314, 0.5_8760, 0.5_5368, 0.5_9643, 0.5_1529, 0.4_1217, 0.4_9087]   )
         assert np.abs(image_slice - expected_slice   ).max() < 1E-1
    def 		a_      (	self   ):
         snake_case					=    OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      , provider='''CPUExecutionProvider'''   )
         snake_case					=    PNDMScheduler.from_config(pipe.scheduler.config      , skip_prk_steps=__snake_case   )
         pipe.set_progress_bar_config(disable=__snake_case   )

         snake_case					=    self.get_dummy_inputs()
         snake_case					=    pipe(**__snake_case   ).images
         snake_case					=    image[0, -3:, -3:, -1]

         assert image.shape == (1, 1_2_8, 1_2_8, 3)
         snake_case					=    np.array([0.6_1737, 0.5_4642, 0.5_3183, 0.5_4465, 0.5_2742, 0.6_0525, 0.4_9969, 0.4_0655, 0.4_8154]   )

         assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-1
    def 		a_      (	self   ):
         snake_case					=    OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      , provider='''CPUExecutionProvider'''   )
         snake_case					=    LMSDiscreteScheduler.from_config(pipe.scheduler.config   )
         pipe.set_progress_bar_config(disable=__snake_case   )

         # warmup pass to apply optimizations
         snake_case					=    pipe(**self.get_dummy_inputs()   )

         snake_case					=    self.get_dummy_inputs()
         snake_case					=    pipe(**__snake_case   ).images
         snake_case					=    image[0, -3:, -3:, -1]

         assert image.shape == (1, 1_2_8, 1_2_8, 3)
         snake_case					=    np.array([0.5_2761, 0.5_9977, 0.4_9033, 0.4_9619, 0.5_4282, 0.5_0311, 0.4_7600, 0.4_0918, 0.4_5203]   )

         assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-1
    def 		a_      (	self   ):
         snake_case					=    OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      , provider='''CPUExecutionProvider'''   )
         snake_case					=    EulerDiscreteScheduler.from_config(pipe.scheduler.config   )
         pipe.set_progress_bar_config(disable=__snake_case   )

         snake_case					=    self.get_dummy_inputs()
         snake_case					=    pipe(**__snake_case   ).images
         snake_case					=    image[0, -3:, -3:, -1]

         assert image.shape == (1, 1_2_8, 1_2_8, 3)
         snake_case					=    np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304]   )

         assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-1
    def 		a_      (	self   ):
         snake_case					=    OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      , provider='''CPUExecutionProvider'''   )
         snake_case					=    EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config   )
         pipe.set_progress_bar_config(disable=__snake_case   )

         snake_case					=    self.get_dummy_inputs()
         snake_case					=    pipe(**__snake_case   ).images
         snake_case					=    image[0, -3:, -3:, -1]

         assert image.shape == (1, 1_2_8, 1_2_8, 3)
         snake_case					=    np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304]   )

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




    def 		a_      (	self   ):
         snake_case					=    OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint      , provider='''CPUExecutionProvider'''   )
         snake_case					=    DPMSolverMultistepScheduler.from_config(pipe.scheduler.config   )
         pipe.set_progress_bar_config(disable=__snake_case   )

         snake_case					=    self.get_dummy_inputs()
         snake_case					=    pipe(**__snake_case   ).images
         snake_case					=    image[0, -3:, -3:, -1]

         assert image.shape == (1, 1_2_8, 1_2_8, 3)
         snake_case					=    np.array([0.6_5331, 0.5_8277, 0.4_8204, 0.5_6059, 0.5_3665, 0.5_6235, 0.5_0969, 0.4_0009, 0.4_6552]   )

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






@nightly
@require_onnxruntime
@require_torch_gpu
class   A__ (   unittest.TestCase     ):







    """simple docstring"""

    @property
    def 		a_      (	self   ):
         return (
             "CUDAExecutionProvider",
             {
                 "gpu_mem_limit": "15000000000",  # 15GB
                 "arena_extend_strategy": "kSameAsRequested",
             },
         )
    @property
    def 		a_      (	self   ):
         snake_case					=    ort.SessionOptions()
         snake_case					=    False
         return options
    def 		a_      (	self   ):
         snake_case					=    load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/img2img/sketch-mountains-input.jpg'''   )
         snake_case					=    init_image.resize((7_6_8, 5_1_2)   )
         # using the PNDM scheduler by default
         snake_case					=    OnnxStableDiffusionImgaImgPipeline.from_pretrained(
             '''CompVis/stable-diffusion-v1-4'''      , revision='''onnx'''      , safety_checker=__snake_case      , feature_extractor=__snake_case      , provider=self.gpu_provider      , sess_options=self.gpu_options      , )
         pipe.set_progress_bar_config(disable=__snake_case   )

         snake_case					=    '''A fantasy landscape, trending on artstation'''

         snake_case					=    np.random.RandomState(0   )
         snake_case					=    pipe(
             prompt=__snake_case      , image=__snake_case      , strength=0.75      , guidance_scale=7.5      , num_inference_steps=1_0      , generator=__snake_case      , output_type='''np'''      , )
         snake_case					=    output.images
         snake_case					=    images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

         assert images.shape == (1, 5_1_2, 7_6_8, 3)
         snake_case					=    np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019]   )
         # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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




    def 		a_      (	self   ):
         snake_case					=    load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/img2img/sketch-mountains-input.jpg'''   )
         snake_case					=    init_image.resize((7_6_8, 5_1_2)   )
         snake_case					=    LMSDiscreteScheduler.from_pretrained(
             '''runwayml/stable-diffusion-v1-5'''      , subfolder='''scheduler'''      , revision='''onnx'''   )
         snake_case					=    OnnxStableDiffusionImgaImgPipeline.from_pretrained(
             '''runwayml/stable-diffusion-v1-5'''      , revision='''onnx'''      , scheduler=__snake_case      , safety_checker=__snake_case      , feature_extractor=__snake_case      , provider=self.gpu_provider      , sess_options=self.gpu_options      , )
         pipe.set_progress_bar_config(disable=__snake_case   )

         snake_case					=    '''A fantasy landscape, trending on artstation'''

         snake_case					=    np.random.RandomState(0   )
         snake_case					=    pipe(
             prompt=__snake_case      , image=__snake_case      , strength=0.75      , guidance_scale=7.5      , num_inference_steps=2_0      , generator=__snake_case      , output_type='''np'''      , )
         snake_case					=    output.images
         snake_case					=    images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

         assert images.shape == (1, 5_1_2, 7_6_8, 3)
         snake_case					=    np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431]   )
         # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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




