from typing import Any, Callable, Dict, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker


__lowercase							 =					'''CompVis/stable-diffusion-v1-1'''
__lowercase							 =					'''CompVis/stable-diffusion-v1-2'''
__lowercase							 =					'''CompVis/stable-diffusion-v1-3'''
__lowercase							 =					'''CompVis/stable-diffusion-v1-4'''


class 	lowerCamelCase_     (   UpperCAmelCase_ ):






    '''simple docstring'''






    def __init__(	self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase = True , )       ->	Union[str, Any]:
        super()._init_()

        __UpperCamelCase     :Dict			  =		StableDiffusionPipeline.from_pretrained(__lowercase)
        __UpperCamelCase     :Union[str, Any]			  =		StableDiffusionPipeline.from_pretrained(__lowercase)
        __UpperCamelCase     :Optional[int]			  =		StableDiffusionPipeline.from_pretrained(__lowercase)
        __UpperCamelCase     :Tuple			  =		StableDiffusionPipeline(
            vae=__lowercase , text_encoder=__lowercase , tokenizer=__lowercase , unet=__lowercase , scheduler=__lowercase , safety_checker=__lowercase , feature_extractor=__lowercase , requires_safety_checker=__lowercase , )

        self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea)







    @property
    def 			UpperCamelCase__   (	self)       ->	Dict[str, Any]:
        return {k: getattr(self , __lowercase) for k in self.config.keys() if not k.startswith('''_''')}







    def 			UpperCamelCase__   (	self , __lowercase = "auto")       ->	str:
        if slice_size == "auto":
            # half the attention head size is usually a good trade-off between
            # speed and memory
            __UpperCamelCase     :Optional[Any]			  =		self.unet.config.attention_head_dim // 2
        self.unet.set_attention_slice(__lowercase)







    def 			UpperCamelCase__   (	self)       ->	str:
        self.enable_attention_slicing(__lowercase)







    @torch.no_grad()
    def 			UpperCamelCase__   (	self , __lowercase , __lowercase = 512 , __lowercase = 512 , __lowercase = 50 , __lowercase = 7.5 , __lowercase = None , __lowercase = 1 , __lowercase = 0.0 , __lowercase = None , __lowercase = None , __lowercase = "pil" , __lowercase = True , __lowercase = None , __lowercase = 1 , **__lowercase , )       ->	Union[str, Any]:
        return self.pipea(
            prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , )







    @torch.no_grad()
    def 			UpperCamelCase__   (	self , __lowercase , __lowercase = 512 , __lowercase = 512 , __lowercase = 50 , __lowercase = 7.5 , __lowercase = None , __lowercase = 1 , __lowercase = 0.0 , __lowercase = None , __lowercase = None , __lowercase = "pil" , __lowercase = True , __lowercase = None , __lowercase = 1 , **__lowercase , )       ->	int:
        return self.pipea(
            prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , )







    @torch.no_grad()
    def 			UpperCamelCase__   (	self , __lowercase , __lowercase = 512 , __lowercase = 512 , __lowercase = 50 , __lowercase = 7.5 , __lowercase = None , __lowercase = 1 , __lowercase = 0.0 , __lowercase = None , __lowercase = None , __lowercase = "pil" , __lowercase = True , __lowercase = None , __lowercase = 1 , **__lowercase , )       ->	str:
        return self.pipea(
            prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , )







    @torch.no_grad()
    def 			UpperCamelCase__   (	self , __lowercase , __lowercase = 512 , __lowercase = 512 , __lowercase = 50 , __lowercase = 7.5 , __lowercase = None , __lowercase = 1 , __lowercase = 0.0 , __lowercase = None , __lowercase = None , __lowercase = "pil" , __lowercase = True , __lowercase = None , __lowercase = 1 , **__lowercase , )       ->	str:
        return self.pipea(
            prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , )







    @torch.no_grad()
    def 			UpperCamelCase__   (	self , __lowercase , __lowercase = 512 , __lowercase = 512 , __lowercase = 50 , __lowercase = 7.5 , __lowercase = None , __lowercase = 1 , __lowercase = 0.0 , __lowercase = None , __lowercase = None , __lowercase = "pil" , __lowercase = True , __lowercase = None , __lowercase = 1 , **__lowercase , )       ->	Optional[int]:
        __UpperCamelCase     :Optional[Any]			  =		'''cuda''' if torch.cuda.is_available() else '''cpu'''
        self.to(__lowercase)

        # Checks if the height and width are divisible by 8 or not
        if height % 8 != 0 or width % 8 != 0:
            raise ValueError(f"""`height` and `width` must be divisible by 8 but are {height} and {width}.""")

        # Get first result from Stable Diffusion Checkpoint v1.1
        __UpperCamelCase     :Tuple			  =		self.textaimg_sda_a(
            prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , )

        # Get first result from Stable Diffusion Checkpoint v1.2
        __UpperCamelCase     :Any			  =		self.textaimg_sda_a(
            prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , )

        # Get first result from Stable Diffusion Checkpoint v1.3
        __UpperCamelCase     :Dict			  =		self.textaimg_sda_a(
            prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , )

        # Get first result from Stable Diffusion Checkpoint v1.4
        __UpperCamelCase     :Optional[Any]			  =		self.textaimg_sda_a(
            prompt=__lowercase , height=__lowercase , width=__lowercase , num_inference_steps=__lowercase , guidance_scale=__lowercase , negative_prompt=__lowercase , num_images_per_prompt=__lowercase , eta=__lowercase , generator=__lowercase , latents=__lowercase , output_type=__lowercase , return_dict=__lowercase , callback=__lowercase , callback_steps=__lowercase , **__lowercase , )

        # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
        return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]])






# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool


class 	lowerCamelCase_     (   UpperCAmelCase_ ):






    '''simple docstring'''






    a__	:						Optional[Any]						=      """facebook/bart-large-mnli"""
    a__	:						int						=      (
        """This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which """
        """should be the text to classify, and `labels`, which should be the list of labels to use for classification. """
        """It returns the most likely label in the list of provided `labels` for the input text."""
    )
    a__	:						Optional[Any]						=      """text_classifier"""
    a__	:						Any						=      AutoTokenizer
    a__	:						str						=      AutoModelForSequenceClassification

    a__	:						str						=      ["""text""", ["""text"""]]
    a__	:						Optional[int]						=      ["""text"""]







    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        super().setup()
        __UpperCamelCase     :int			  =		self.model.config
        __UpperCamelCase     :Optional[Any]			  =		-1
        for idx, label in config.idalabel.items():
            if label.lower().startswith('''entail'''):
                __UpperCamelCase     :List[Any]			  =		int(__lowercase)
        if self.entailment_id == -1:
            raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.''')







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase)       ->	Union[str, Any]:
        __UpperCamelCase     :Any			  =		labels
        return self.pre_processor(
            [text] * len(__lowercase) , [f"""This example is {label}""" for label in labels] , return_tensors='''pt''' , padding='''max_length''' , )







    def 			UpperCamelCase__   (	self , __lowercase)       ->	Optional[Any]:
        __UpperCamelCase     :List[Any]			  =		outputs.logits
        __UpperCamelCase     :Any			  =		torch.argmax(logits[:, 2]).item()
        return self._labels[label_id]





