'''simple docstring'''

import re
import string

import numpy as np

import datasets


__a:			List[str]	       =       """
Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.
"""

__a:			List[Any]	       =       """
Args:
    predictions: List of predicted texts.
    references: List of reference texts.
    regexes_to_ignore: List, defaults to None. Regex expressions of characters to
        ignore when calculating the exact matches. Note: these regexes are removed
        from the input data before the changes based on the options below (e.g. ignore_case,
        ignore_punctuation, ignore_numbers) are applied.
    ignore_case: Boolean, defaults to False. If true, turns everything
        to lowercase so that capitalization differences are ignored.
    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
Returns:
    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.
Examples:
    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results[\"exact_match\"], 1))
    25.0

    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results[\"exact_match\"], 1))
    50.0


    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results[\"exact_match\"], 1))
    75.0

    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)
    >>> print(round(results[\"exact_match\"], 1))
    100.0

    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]
    >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results[\"exact_match\"], 1))
    33.3

"""

__a:			Dict	       =       """
"""



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





       '''simple docstring'''



       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        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 _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase=None     ,       __lowerCAmelCase=False     ,       __lowerCAmelCase=False     ,       __lowerCAmelCase=False     ,       )  ->  Any:


        if regexes_to_ignore is not None:
         for s in regexes_to_ignore:
          lowercase__    :   int						= np.array([re.sub(snake_case__     ,       ''''''     ,       snake_case__			) for x in predictions]			)
          lowercase__    :   List[Any]						= np.array([re.sub(snake_case__     ,       ''''''     ,       snake_case__			) for x in references]			)
        else:
         lowercase__    :   Optional[int]						= np.asarray(snake_case__			)
         lowercase__    :   Any						= np.asarray(snake_case__			)

        if ignore_case:
         lowercase__    :   List[str]						= np.char.lower(snake_case__			)
         lowercase__    :   Union[str, Any]						= np.char.lower(snake_case__			)

        if ignore_punctuation:
         lowercase__    :   Optional[Any]						= string.punctuation.maketrans(''''''     ,       ''''''     ,       string.punctuation			)
         lowercase__    :   List[str]						= np.char.translate(snake_case__     ,       table=snake_case__			)
         lowercase__    :   int						= np.char.translate(snake_case__     ,       table=snake_case__			)

        if ignore_numbers:
         lowercase__    :   Optional[int]						= string.digits.maketrans(''''''     ,       ''''''     ,       string.digits			)
         lowercase__    :   Union[str, Any]						= np.char.translate(snake_case__     ,       table=snake_case__			)
         lowercase__    :   Optional[Any]						= np.char.translate(snake_case__     ,       table=snake_case__			)

        lowercase__    :   Optional[int]						= predictions == references

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

'''simple docstring'''

import unittest

import numpy as np
import torch

from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class       UpperCAmelCase  (						a__   ,						unittest.TestCase ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   DDIMPipeline
       SCREAMING_SNAKE_CASE 		=   UNCONDITIONAL_IMAGE_GENERATION_PARAMS
       SCREAMING_SNAKE_CASE 		=   PipelineTesterMixin.required_optional_params - {
           "num_images_per_prompt",
           "latents",
           "callback",
           "callback_steps",
       }
       SCREAMING_SNAKE_CASE 		=   UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
       SCREAMING_SNAKE_CASE 		=   False

       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        torch.manual_seed(0			)
        lowercase__    :   Optional[int]						= UNetaDModel(
            block_out_channels=(32, 64)     ,       layers_per_block=2     ,       sample_size=32     ,       in_channels=3     ,       out_channels=3     ,       down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')     ,       up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')     ,       )
        lowercase__    :   Any						= DDIMScheduler()
        lowercase__    :   Union[str, Any]						= {'''unet''': unet, '''scheduler''': scheduler}
        return components

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase=0			)  ->  int:
        if str(__lowerCAmelCase			).startswith('''mps'''			):
         lowercase__    :   Optional[Any]						= torch.manual_seed(__lowerCAmelCase			)
        else:
         lowercase__    :   int						= torch.Generator(device=__lowerCAmelCase			).manual_seed(__lowerCAmelCase			)
        lowercase__    :   List[Any]						= {
            '''batch_size''': 1,
            '''generator''': generator,
            '''num_inference_steps''': 2,
            '''output_type''': '''numpy''',
        }
        return inputs

       def _lowerCAmelCase(						self			)  ->  Optional[Any]:
        lowercase__    :   int						= '''cpu'''

        lowercase__    :   Optional[Any]						= self.get_dummy_components()
        lowercase__    :   str						= self.pipeline_class(**__lowerCAmelCase			)
        pipe.to(__lowerCAmelCase			)
        pipe.set_progress_bar_config(disable=__lowerCAmelCase			)

        lowercase__    :   str						= self.get_dummy_inputs(__lowerCAmelCase			)
        lowercase__    :   str						= pipe(**__lowerCAmelCase			).images
        lowercase__    :   List[str]						= image[0, -3:, -3:, -1]

        self.assertEqual(image.shape     ,       (1, 32, 32, 3)			)
        lowercase__    :   Optional[int]						= np.array(
            [1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04]			)
        lowercase__    :   Optional[Any]						= np.abs(image_slice.flatten() - expected_slice			).max()
        self.assertLessEqual(__lowerCAmelCase     ,       1E-3			)

       def _lowerCAmelCase(						self			)  ->  str:
        super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3			)

       def _lowerCAmelCase(						self			)  ->  List[str]:
        super().test_save_load_local(expected_max_difference=3E-3			)

       def _lowerCAmelCase(						self			)  ->  Tuple:
        super().test_save_load_optional_components(expected_max_difference=3E-3			)


       def _lowerCAmelCase(						self			)  ->  int:
        super().test_inference_batch_single_identical(expected_max_diff=3E-3			)



@slow
@require_torch_gpu
class       UpperCAmelCase  (						unittest.TestCase ):





       '''simple docstring'''



       def _lowerCAmelCase(						self			)  ->  List[Any]:
        lowercase__    :   List[str]						= '''google/ddpm-cifar10-32'''

        lowercase__    :   List[Any]						= UNetaDModel.from_pretrained(__lowerCAmelCase			)
        lowercase__    :   str						= DDIMScheduler()

        lowercase__    :   List[Any]						= DDIMPipeline(unet=__lowerCAmelCase     ,       scheduler=__lowerCAmelCase			)
        ddim.to(__lowerCAmelCase			)
        ddim.set_progress_bar_config(disable=__lowerCAmelCase			)

        lowercase__    :   Dict						= torch.manual_seed(0			)
        lowercase__    :   Optional[int]						= ddim(generator=__lowerCAmelCase     ,       eta=0.0     ,       output_type='''numpy'''			).images

        lowercase__    :   List[str]						= image[0, -3:, -3:, -1]

        assert image.shape == (1, 32, 32, 3)
        lowercase__    :   Optional[int]						= np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3]			)

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


       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        lowercase__    :   Optional[Any]						= '''google/ddpm-ema-bedroom-256'''

        lowercase__    :   Tuple						= UNetaDModel.from_pretrained(__lowerCAmelCase			)
        lowercase__    :   Union[str, Any]						= DDIMScheduler.from_pretrained(__lowerCAmelCase			)

        lowercase__    :   List[Any]						= DDIMPipeline(unet=__lowerCAmelCase     ,       scheduler=__lowerCAmelCase			)
        ddpm.to(__lowerCAmelCase			)
        ddpm.set_progress_bar_config(disable=__lowerCAmelCase			)

        lowercase__    :   Union[str, Any]						= torch.manual_seed(0			)
        lowercase__    :   Optional[Any]						= ddpm(generator=__lowerCAmelCase     ,       output_type='''numpy'''			).images

        lowercase__    :   List[Any]						= image[0, -3:, -3:, -1]

        assert image.shape == (1, 256, 256, 3)
        lowercase__    :   Union[str, Any]						= np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9]			)

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

