





"""simple docstring"""


import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import require_keras_nlp, require_tf, slow


if is_tf_available():
  import tensorflow as tf

if is_keras_nlp_available():
  from transformers.models.gpta import TFGPTaTokenizer


lowerCamelCase__						= ["gpt2"]
lowerCamelCase__						= "gpt2"

if is_tf_available():



  class   __SCREAMING_SNAKE_CASE     (    tf.Module ):







    '''simple docstring'''


    def __init__(		self :							str       , __a :							str						)		->					Optional[Any]:
          super().__init__()
          _UpperCamelCase   :						int    =							tokenizer
          _UpperCamelCase   :						Optional[int]    =							AutoConfig.from_pretrained(__a						)
          _UpperCamelCase   :						Any    =							TFGPTaLMHeadModel.from_config(__a						)


    @tf.function(input_signature=(tf.TensorSpec((None,)       , tf.string       , name="text"						),)						)
    def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]       , __a :							int						)		->					Union[str, Any]:
          _UpperCamelCase   :						List[str]    =							self.tokenizer(__a						)
          _UpperCamelCase   :						List[str]    =							tokenized["input_ids"].to_tensor()

          _UpperCamelCase   :						Optional[Any]    =							tf.cast(input_ids_dense > 0       , tf.intaa						)
          # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])

          _UpperCamelCase   :						List[Any]    =							self.model(input_ids=__a       , attention_mask=__a						)["logits"]

          return outputs



@require_tf
@require_keras_nlp
class   __SCREAMING_SNAKE_CASE     (    unittest.TestCase ):







  '''simple docstring'''


  def  __SCREAMING_SNAKE_CASE					(		self :							Union[str, Any]						)		->					Union[str, Any]:
        super().setUp()

        _UpperCamelCase   :						Tuple    =							[GPTaTokenizer.from_pretrained(__a						) for checkpoint in (TOKENIZER_CHECKPOINTS)]
        _UpperCamelCase   :						List[Any]    =							[TFGPTaTokenizer.from_pretrained(__a						) for checkpoint in TOKENIZER_CHECKPOINTS]
        assert len(self.tokenizers						) == len(self.tf_tokenizers						)

        _UpperCamelCase   :						Dict    =							[
            "This is a straightforward English test sentence.",
            "This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.",
            "Now we're going to add some Chinese: 一 二 三 一二三",
            "And some much more rare Chinese: 齉 堃 齉堃",
            "Je vais aussi écrire en français pour tester les accents",
            "Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ",
        ]
        _UpperCamelCase   :						Any    =							list(zip(self.test_sentences       , self.test_sentences[::-1]						)						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					Dict:
        for tokenizer, tf_tokenizer in zip(self.tokenizers       , self.tf_tokenizers						):
              for test_inputs in self.test_sentences:
                    _UpperCamelCase   :						str    =							tokenizer([test_inputs]       , return_tensors="tf"						)
                    _UpperCamelCase   :						List[str]    =							tf_tokenizer([test_inputs]						)

                    for key in python_outputs.keys():
                          # convert them to numpy to avoid messing with ragged tensors
                          _UpperCamelCase   :						List[Any]    =							python_outputs[key].numpy()
                          _UpperCamelCase   :						List[Any]    =							tf_outputs[key].numpy()

                          self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape						)						)
                          self.assertTrue(tf.reduce_all(tf.cast(__a       , tf.intaa						) == tf_outputs_values						)						)

  @slow
  def  __SCREAMING_SNAKE_CASE					(		self :							List[str]						)		->					Any:
        for tf_tokenizer in self.tf_tokenizers:
              _UpperCamelCase   :						Optional[Any]    =							tf.function(__a						)
              for test_inputs in self.test_sentences:
                    _UpperCamelCase   :						List[str]    =							tf.constant(__a						)
                    _UpperCamelCase   :						Dict    =							compiled_tokenizer(__a						)
                    _UpperCamelCase   :						Tuple    =							tf_tokenizer(__a						)

                    for key in eager_outputs.keys():
                          self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]						)						)

  @slow
  def  __SCREAMING_SNAKE_CASE					(		self :							Union[str, Any]						)		->					List[Any]:
        for tf_tokenizer in self.tf_tokenizers:
              _UpperCamelCase   :						Union[str, Any]    =							ModelToSave(tokenizer=__a						)
              _UpperCamelCase   :						List[Any]    =							tf.convert_to_tensor([self.test_sentences[0]]						)
              _UpperCamelCase   :						Optional[Any]    =							model.serving(__a						)  # Build model with some sample inputs
              with TemporaryDirectory() as tempdir:
                    _UpperCamelCase   :						str    =							Path(__a						) / "saved.model"
                    tf.saved_model.save(__a       , __a       , signatures={"serving_default": model.serving}						)
                    _UpperCamelCase   :						int    =							tf.saved_model.load(__a						)
              _UpperCamelCase   :						int    =							loaded_model.signatures["serving_default"](__a						)["output_0"]
              # We may see small differences because the loaded model is compiled, so we need an epsilon for the test
              self.assertTrue(tf.reduce_all(out == loaded_output						)						)

  @slow
  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					Dict:
        for tf_tokenizer in self.tf_tokenizers:
              _UpperCamelCase   :						Any    =							tf.convert_to_tensor([self.test_sentences[0]]						)
              _UpperCamelCase   :						str    =							tf_tokenizer(__a						)  # Build model with some sample inputs

              _UpperCamelCase   :						str    =							tf_tokenizer.get_config()
              _UpperCamelCase   :						List[Any]    =							TFGPTaTokenizer.from_config(__a						)
              _UpperCamelCase   :						Optional[Any]    =							model_from_config(__a						)

              for key in from_config_output.keys():
                    self.assertTrue(tf.reduce_all(from_config_output[key] == out[key]						)						)


  @slow
  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]						)		->					List[str]:
        for tf_tokenizer in self.tf_tokenizers:
              # for the test to run
              _UpperCamelCase   :						str    =							12_3123

              for max_length in [3, 5, 1024]:
                    _UpperCamelCase   :						Tuple    =							tf.convert_to_tensor([self.test_sentences[0]]						)
                    _UpperCamelCase   :						Union[str, Any]    =							tf_tokenizer(__a       , max_length=__a						)

                    _UpperCamelCase   :						int    =							out["input_ids"].numpy().shape[1]

                    assert out_length == max_length







"""simple docstring"""


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


lowerCamelCase__						= "CompVis/stable-diffusion-v1-1"
lowerCamelCase__						= "CompVis/stable-diffusion-v1-2"
lowerCamelCase__						= "CompVis/stable-diffusion-v1-3"
lowerCamelCase__						= "CompVis/stable-diffusion-v1-4"



class   __SCREAMING_SNAKE_CASE     (    _UpperCamelCase ):







  '''simple docstring'''


  def __init__(		self :							Union[str, Any]       , __a :							AutoencoderKL       , __a :							CLIPTextModel       , __a :							CLIPTokenizer       , __a :							UNetaDConditionModel       , __a :							Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]       , __a :							StableDiffusionSafetyChecker       , __a :							CLIPImageProcessor       , __a :							bool = True       , )		->					List[str]:
        super()._init_()

        _UpperCamelCase   :						Optional[int]    =							StableDiffusionPipeline.from_pretrained(__a						)
        _UpperCamelCase   :						int    =							StableDiffusionPipeline.from_pretrained(__a						)
        _UpperCamelCase   :						List[Any]    =							StableDiffusionPipeline.from_pretrained(__a						)
        _UpperCamelCase   :						int    =							StableDiffusionPipeline(
            vae=__a       , text_encoder=__a       , tokenizer=__a       , unet=__a       , scheduler=__a       , safety_checker=__a       , feature_extractor=__a       , requires_safety_checker=__a       , )

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

  @property
  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]						)		->					Dict[str, Any]:
        return {k: getattr(self       , __a						) for k in self.config.keys() if not k.startswith("_"						)}

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

  def  __SCREAMING_SNAKE_CASE					(		self :							str						)		->					Any:
        self.enable_attention_slicing(__a						)

  @torch.no_grad()
  def  __SCREAMING_SNAKE_CASE					(		self :							List[str]       , __a :							Union[str, List[str]]       , __a :							int = 512       , __a :							int = 512       , __a :							int = 50       , __a :							float = 7.5       , __a :							Optional[Union[str, List[str]]] = None       , __a :							Optional[int] = 1       , __a :							float = 0.0       , __a :							Optional[torch.Generator] = None       , __a :							Optional[torch.FloatTensor] = None       , __a :							Optional[str] = "pil"       , __a :							bool = True       , __a :							Optional[Callable[[int, int, torch.FloatTensor], None]] = None       , __a :							int = 1       , **__a :							Any       , )		->					Optional[int]:
        return self.pipea(
            prompt=__a       , height=__a       , width=__a       , num_inference_steps=__a       , guidance_scale=__a       , negative_prompt=__a       , num_images_per_prompt=__a       , eta=__a       , generator=__a       , latents=__a       , output_type=__a       , return_dict=__a       , callback=__a       , callback_steps=__a       , **__a       , )

  @torch.no_grad()
  def  __SCREAMING_SNAKE_CASE					(		self :							List[Any]       , __a :							Union[str, List[str]]       , __a :							int = 512       , __a :							int = 512       , __a :							int = 50       , __a :							float = 7.5       , __a :							Optional[Union[str, List[str]]] = None       , __a :							Optional[int] = 1       , __a :							float = 0.0       , __a :							Optional[torch.Generator] = None       , __a :							Optional[torch.FloatTensor] = None       , __a :							Optional[str] = "pil"       , __a :							bool = True       , __a :							Optional[Callable[[int, int, torch.FloatTensor], None]] = None       , __a :							int = 1       , **__a :							Tuple       , )		->					str:
        return self.pipea(
            prompt=__a       , height=__a       , width=__a       , num_inference_steps=__a       , guidance_scale=__a       , negative_prompt=__a       , num_images_per_prompt=__a       , eta=__a       , generator=__a       , latents=__a       , output_type=__a       , return_dict=__a       , callback=__a       , callback_steps=__a       , **__a       , )

  @torch.no_grad()
  def  __SCREAMING_SNAKE_CASE					(		self :							List[Any]       , __a :							Union[str, List[str]]       , __a :							int = 512       , __a :							int = 512       , __a :							int = 50       , __a :							float = 7.5       , __a :							Optional[Union[str, List[str]]] = None       , __a :							Optional[int] = 1       , __a :							float = 0.0       , __a :							Optional[torch.Generator] = None       , __a :							Optional[torch.FloatTensor] = None       , __a :							Optional[str] = "pil"       , __a :							bool = True       , __a :							Optional[Callable[[int, int, torch.FloatTensor], None]] = None       , __a :							int = 1       , **__a :							Tuple       , )		->					Any:
        return self.pipea(
            prompt=__a       , height=__a       , width=__a       , num_inference_steps=__a       , guidance_scale=__a       , negative_prompt=__a       , num_images_per_prompt=__a       , eta=__a       , generator=__a       , latents=__a       , output_type=__a       , return_dict=__a       , callback=__a       , callback_steps=__a       , **__a       , )

  @torch.no_grad()
  def  __SCREAMING_SNAKE_CASE					(		self :							Dict       , __a :							Union[str, List[str]]       , __a :							int = 512       , __a :							int = 512       , __a :							int = 50       , __a :							float = 7.5       , __a :							Optional[Union[str, List[str]]] = None       , __a :							Optional[int] = 1       , __a :							float = 0.0       , __a :							Optional[torch.Generator] = None       , __a :							Optional[torch.FloatTensor] = None       , __a :							Optional[str] = "pil"       , __a :							bool = True       , __a :							Optional[Callable[[int, int, torch.FloatTensor], None]] = None       , __a :							int = 1       , **__a :							List[Any]       , )		->					Union[str, Any]:
        return self.pipea(
            prompt=__a       , height=__a       , width=__a       , num_inference_steps=__a       , guidance_scale=__a       , negative_prompt=__a       , num_images_per_prompt=__a       , eta=__a       , generator=__a       , latents=__a       , output_type=__a       , return_dict=__a       , callback=__a       , callback_steps=__a       , **__a       , )


  @torch.no_grad()
  def  __SCREAMING_SNAKE_CASE					(		self :							str       , __a :							Union[str, List[str]]       , __a :							int = 512       , __a :							int = 512       , __a :							int = 50       , __a :							float = 7.5       , __a :							Optional[Union[str, List[str]]] = None       , __a :							Optional[int] = 1       , __a :							float = 0.0       , __a :							Optional[torch.Generator] = None       , __a :							Optional[torch.FloatTensor] = None       , __a :							Optional[str] = "pil"       , __a :							bool = True       , __a :							Optional[Callable[[int, int, torch.FloatTensor], None]] = None       , __a :							int = 1       , **__a :							int       , )		->					List[Any]:
        _UpperCamelCase   :						Tuple    =							"cuda" if torch.cuda.is_available() else "cpu"
        self.to(__a						)

        # 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   :						List[str]    =							self.textaimg_sda_a(
            prompt=__a       , height=__a       , width=__a       , num_inference_steps=__a       , guidance_scale=__a       , negative_prompt=__a       , num_images_per_prompt=__a       , eta=__a       , generator=__a       , latents=__a       , output_type=__a       , return_dict=__a       , callback=__a       , callback_steps=__a       , **__a       , )

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

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

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

        # 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]]						)
