



'''simple docstring'''





import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class     UpperCAmelCase_       (       _a		,		unittest.TestCase	):
    """simple docstring"""







    lowercase					=		LDMTextToImagePipeline
    lowercase					=		TEXT_TO_IMAGE_PARAMS - {
        "negative_prompt",
        "negative_prompt_embeds",
        "cross_attention_kwargs",
        "prompt_embeds",
    }
    lowercase					=		PipelineTesterMixin.required_optional_params - {
        "num_images_per_prompt",
        "callback",
        "callback_steps",
    }
    lowercase					=		TEXT_TO_IMAGE_BATCH_PARAMS
    lowercase					=		False




    def lowerCamelCase       (    self					:     List[Any]						):
          torch.manual_seed(0						)
          snake_case__  :    List[str]    						=      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 ,     )
          snake_case__  :    List[str]    						=      DDIMScheduler(
              beta_start=0.00085 ,     beta_end=0.012 ,     beta_schedule="""scaled_linear""" ,     clip_sample=snake_case_ ,     set_alpha_to_one=snake_case_ ,     )
          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 ,     )
          torch.manual_seed(0						)
          snake_case__  :    Optional[int]    						=      CLIPTextConfig(
              bos_token_id=0 ,     eos_token_id=2 ,     hidden_size=32 ,     intermediate_size=37 ,     layer_norm_eps=1E-0_5 ,     num_attention_heads=4 ,     num_hidden_layers=5 ,     pad_token_id=1 ,     vocab_size=1_000 ,     )
          snake_case__  :    Optional[Any]    						=      CLIPTextModel(snake_case_						)
          snake_case__  :    List[Any]    						=      CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""						)

          snake_case__  :    Any    						=      {
              """unet""": unet,
              """scheduler""": scheduler,
              """vqvae""": vae,
              """bert""": text_encoder,
              """tokenizer""": tokenizer,
          }
          return components




    def lowerCamelCase       (    self					:     Tuple ,     snake_case_					:     Any ,     snake_case_					:     Optional[int]=0						):
          if str(snake_case_						).startswith("""mps"""						):
                snake_case__  :    str    						=      torch.manual_seed(snake_case_						)
          else:
                snake_case__  :    Any    						=      torch.Generator(device=snake_case_						).manual_seed(snake_case_						)
          snake_case__  :    List[str]    						=      {
              """prompt""": """A painting of a squirrel eating a burger""",
              """generator""": generator,
              """num_inference_steps""": 2,
              """guidance_scale""": 6.0,
              """output_type""": """numpy""",
          }
          return inputs




    def lowerCamelCase       (    self					:     int						):
          snake_case__  :    Dict    						=      """cpu"""  # ensure determinism for the device-dependent torch.Generator

          snake_case__  :    List[Any]    						=      self.get_dummy_components()
          snake_case__  :    Any    						=      LDMTextToImagePipeline(**snake_case_						)
          pipe.to(snake_case_						)
          pipe.set_progress_bar_config(disable=snake_case_						)

          snake_case__  :    Tuple    						=      self.get_dummy_inputs(snake_case_						)
          snake_case__  :    Union[str, Any]    						=      pipe(**snake_case_						).images
          snake_case__  :    Dict    						=      image[0, -3:, -3:, -1]

          assert image.shape == (1, 16, 16, 3)
          snake_case__  :    Dict    						=      np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014]						)

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







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







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




    def lowerCamelCase       (    self					:     Tuple ,     snake_case_					:     List[Any] ,     snake_case_					:     List[Any]=torch.floataa ,     snake_case_					:     Tuple=0						):
          snake_case__  :    Any    						=      torch.manual_seed(snake_case_						)
          snake_case__  :    str    						=      np.random.RandomState(snake_case_						).standard_normal((1, 4, 32, 32)						)
          snake_case__  :    int    						=      torch.from_numpy(snake_case_						).to(device=snake_case_ ,     dtype=snake_case_						)
          snake_case__  :    List[Any]    						=      {
              """prompt""": """A painting of a squirrel eating a burger""",
              """latents""": latents,
              """generator""": generator,
              """num_inference_steps""": 3,
              """guidance_scale""": 6.0,
              """output_type""": """numpy""",
          }
          return inputs




    def lowerCamelCase       (    self					:     Tuple						):
          snake_case__  :    Dict    						=      LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""						).to(snake_case_						)
          pipe.set_progress_bar_config(disable=snake_case_						)

          snake_case__  :    int    						=      self.get_inputs(snake_case_						)
          snake_case__  :    Optional[Any]    						=      pipe(**snake_case_						).images
          snake_case__  :    Tuple    						=      image[0, -3:, -3:, -1].flatten()

          assert image.shape == (1, 256, 256, 3)
          snake_case__  :    List[Any]    						=      np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878]						)
          snake_case__  :    Any    						=      np.abs(expected_slice - image_slice						).max()
          assert max_diff < 1E-3







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







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




    def lowerCamelCase       (    self					:     Union[str, Any] ,     snake_case_					:     Optional[int] ,     snake_case_					:     Tuple=torch.floataa ,     snake_case_					:     List[str]=0						):
          snake_case__  :    Tuple    						=      torch.manual_seed(snake_case_						)
          snake_case__  :    Union[str, Any]    						=      np.random.RandomState(snake_case_						).standard_normal((1, 4, 32, 32)						)
          snake_case__  :    List[str]    						=      torch.from_numpy(snake_case_						).to(device=snake_case_ ,     dtype=snake_case_						)
          snake_case__  :    Optional[int]    						=      {
              """prompt""": """A painting of a squirrel eating a burger""",
              """latents""": latents,
              """generator""": generator,
              """num_inference_steps""": 50,
              """guidance_scale""": 6.0,
              """output_type""": """numpy""",
          }
          return inputs




    def lowerCamelCase       (    self					:     List[Any]						):
          snake_case__  :    Any    						=      LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""						).to(snake_case_						)
          pipe.set_progress_bar_config(disable=snake_case_						)

          snake_case__  :    Tuple    						=      self.get_inputs(snake_case_						)
          snake_case__  :    Tuple    						=      pipe(**snake_case_						).images[0]

          snake_case__  :    int    						=      load_numpy(
              """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy"""						)
          snake_case__  :    List[str]    						=      np.abs(expected_image - image						).max()
          assert max_diff < 1E-3







"""simple docstring"""





import re
import string

import numpy as np

import datasets


SCREAMING_SNAKE_CASE__					=   "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n"

SCREAMING_SNAKE_CASE__					=   "\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results[\"exact_match\"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n    >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results[\"exact_match\"], 1))\n    33.3\n\n"

SCREAMING_SNAKE_CASE__					=   "\n"

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,  _KWARGS_DESCRIPTION					)
class 		lowercase					(					datasets.Metric					):





      def     _snake_case			(       self )		->     Optional[int]:
            return datasets.MetricInfo(
                description=_DESCRIPTION      ,						citation=_CITATION      ,						inputs_description=_KWARGS_DESCRIPTION      ,						features=datasets.Features(
                    {
                        """predictions""": datasets.Value("""string"""      ,						id="""sequence""" ),
                        """references""": datasets.Value("""string"""      ,						id="""sequence""" ),
                    } )      ,						reference_urls=[]      ,						)





      def     _snake_case			(       self      ,						lowercase      ,						lowercase      ,						lowercase=None      ,						lowercase=False      ,						lowercase=False      ,						lowercase=False      ,						)		->     Optional[Any]:
            if regexes_to_ignore is not None:
                  for s in regexes_to_ignore:
                        lowerCAmelCase  						=       np.array([re.sub(lowercase      ,						""""""      ,						lowercase ) for x in predictions] )
                        lowerCAmelCase  						=       np.array([re.sub(lowercase      ,						""""""      ,						lowercase ) for x in references] )
            else:
                  lowerCAmelCase  						=       np.asarray(lowercase )
                  lowerCAmelCase  						=       np.asarray(lowercase )

            if ignore_case:
                  lowerCAmelCase  						=       np.char.lower(lowercase )
                  lowerCAmelCase  						=       np.char.lower(lowercase )

            if ignore_punctuation:
                  lowerCAmelCase  						=       string.punctuation.maketrans(""""""      ,						""""""      ,						string.punctuation )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )

            if ignore_numbers:
                  lowerCAmelCase  						=       string.digits.maketrans(""""""      ,						""""""      ,						string.digits )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )

            lowerCAmelCase  						=       predictions == references

            return {"exact_match": np.mean(lowercase ) * 100}






