





import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference

class      A       (	__lowercase		,      unittest.TestCase						):
    _snake_case							     =ShapEImgaImgPipeline
    _snake_case							     =['''image''']
    _snake_case							     =['''image''']
    _snake_case							     =[
        '''num_images_per_prompt''',
        '''num_inference_steps''',
        '''generator''',
        '''latents''',
        '''guidance_scale''',
        '''frame_size''',
        '''output_type''',
        '''return_dict''',
    ]
    _snake_case							     =False



    @property
    def 	lowerCAmelCase__    (	self:						str       )						->    int:
       '''simple docstring'''

       return 32



    @property
    def 	lowerCAmelCase__    (	self:						str       )						->    Optional[int]:
       '''simple docstring'''

       return 32



    @property
    def 	lowerCAmelCase__    (	self:						str       )						->    Union[str, Any]:
       '''simple docstring'''

       return self.time_input_dim * 4



    @property
    def 	lowerCAmelCase__    (	self:						Union[str, Any]       )						->    Optional[Any]:
       '''simple docstring'''

       return 8



    @property
    def 	lowerCAmelCase__    (	self:						Dict       )						->    Tuple:
       '''simple docstring'''

       torch.manual_seed(0       )
       UpperCAmelCase_											=CLIPVisionConfig(
           hidden_size=self.text_embedder_hidden_size		,  image_size=64		,  projection_dim=self.text_embedder_hidden_size		,  intermediate_size=37		,  num_attention_heads=4		,  num_channels=3		,  num_hidden_layers=5		,  patch_size=1		,  )

       UpperCAmelCase_											=CLIPVisionModel(_lowerCAmelCase       )
       return model



    @property
    def 	lowerCAmelCase__    (	self:						Dict       )						->    int:
       '''simple docstring'''

       UpperCAmelCase_											=CLIPImageProcessor(
           crop_size=224		,  do_center_crop=_lowerCAmelCase		,  do_normalize=_lowerCAmelCase		,  do_resize=_lowerCAmelCase		,  image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]		,  image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]		,  resample=3		,  size=224		,  )

       return image_processor



    @property
    def 	lowerCAmelCase__    (	self:						Optional[Any]       )						->    List[Any]:
       '''simple docstring'''

       torch.manual_seed(0       )

       UpperCAmelCase_											={
           'num_attention_heads': 2,
           'attention_head_dim': 16,
           'embedding_dim': self.time_input_dim,
           'num_embeddings': 32,
           'embedding_proj_dim': self.text_embedder_hidden_size,
           'time_embed_dim': self.time_embed_dim,
           'num_layers': 1,
           'clip_embed_dim': self.time_input_dim * 2,
           'additional_embeddings': 0,
           'time_embed_act_fn': 'gelu',
           'norm_in_type': 'layer',
           'embedding_proj_norm_type': 'layer',
           'encoder_hid_proj_type': None,
           'added_emb_type': None,
       }

       UpperCAmelCase_											=PriorTransformer(**_lowerCAmelCase       )
       return model



    @property
    def 	lowerCAmelCase__    (	self:						Dict       )						->    Optional[Any]:
       '''simple docstring'''

       torch.manual_seed(0       )

       UpperCAmelCase_											={
           'param_shapes': (
               (self.renderer_dim, 93),
               (self.renderer_dim, 8),
               (self.renderer_dim, 8),
               (self.renderer_dim, 8),
           ),
           'd_latent': self.time_input_dim,
           'd_hidden': self.renderer_dim,
           'n_output': 12,
           'background': (
               0.1,
               0.1,
               0.1,
           ),
       }
       UpperCAmelCase_											=ShapERenderer(**_lowerCAmelCase       )
       return model



    def 	lowerCAmelCase__    (	self:						Union[str, Any]       )						->    List[Any]:
       '''simple docstring'''

       UpperCAmelCase_											=self.dummy_prior
       UpperCAmelCase_											=self.dummy_image_encoder
       UpperCAmelCase_											=self.dummy_image_processor
       UpperCAmelCase_											=self.dummy_renderer

       UpperCAmelCase_											=HeunDiscreteScheduler(
           beta_schedule="exp"		,  num_train_timesteps=1024		,  prediction_type="sample"		,  use_karras_sigmas=_lowerCAmelCase		,  clip_sample=_lowerCAmelCase		,  clip_sample_range=1.0		,  )
       UpperCAmelCase_											={
           'prior': prior,
           'image_encoder': image_encoder,
           'image_processor': image_processor,
           'renderer': renderer,
           'scheduler': scheduler,
       }

       return components



    def 	lowerCAmelCase__    (	self:						List[str]		,  _lowerCAmelCase:						Optional[int]		,  _lowerCAmelCase:						Optional[int]=0       )						->    List[Any]:
       '''simple docstring'''

       UpperCAmelCase_											=floats_tensor((1, 3, 64, 64)		,  rng=random.Random(_lowerCAmelCase       )       ).to(_lowerCAmelCase       )

       if str(_lowerCAmelCase       ).startswith("mps"       ):
          UpperCAmelCase_											=torch.manual_seed(_lowerCAmelCase       )
       else:
          UpperCAmelCase_											=torch.Generator(device=_lowerCAmelCase       ).manual_seed(_lowerCAmelCase       )
       UpperCAmelCase_											={
           'image': input_image,
           'generator': generator,
           'num_inference_steps': 1,
           'frame_size': 32,
           'output_type': 'np',
       }
       return inputs



    def 	lowerCAmelCase__    (	self:						str       )						->    List[str]:
       '''simple docstring'''

       UpperCAmelCase_											='cpu'

       UpperCAmelCase_											=self.get_dummy_components()

       UpperCAmelCase_											=self.pipeline_class(**_lowerCAmelCase       )
       UpperCAmelCase_											=pipe.to(_lowerCAmelCase       )

       pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

       UpperCAmelCase_											=pipe(**self.get_dummy_inputs(_lowerCAmelCase       )       )
       UpperCAmelCase_											=output.images[0]
       UpperCAmelCase_											=image[0, -3:, -3:, -1]

       assert image.shape == (20, 32, 32, 3)

       UpperCAmelCase_											=np.array(
           [
               0.00_03_92_16,
               0.00_03_92_16,
               0.00_03_92_16,
               0.00_03_92_16,
               0.00_03_92_16,
               0.00_03_92_16,
               0.00_03_92_16,
               0.00_03_92_16,
               0.00_03_92_16,
           ]       )

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



    def 	lowerCAmelCase__    (	self:						Optional[Any]       )						->    Union[str, Any]:
       '''simple docstring'''

       self._test_inference_batch_consistent(batch_sizes=[1, 2]       )



    def 	lowerCAmelCase__    (	self:						Union[str, Any]       )						->    int:
       '''simple docstring'''

       UpperCAmelCase_											=torch_device == 'cpu'
       UpperCAmelCase_											=True
       self._test_inference_batch_single_identical(
           batch_size=2		,  test_max_difference=_lowerCAmelCase		,  relax_max_difference=_lowerCAmelCase		,  )






    def 	lowerCAmelCase__    (	self:						Optional[Any]       )						->    Optional[Any]:
       '''simple docstring'''

       UpperCAmelCase_											=self.get_dummy_components()
       UpperCAmelCase_											=self.pipeline_class(**_lowerCAmelCase       )
       UpperCAmelCase_											=pipe.to(_lowerCAmelCase       )
       pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

       UpperCAmelCase_											=1
       UpperCAmelCase_											=2

       UpperCAmelCase_											=self.get_dummy_inputs(_lowerCAmelCase       )

       for key in inputs.keys():
          if key in self.batch_params:
             UpperCAmelCase_											=batch_size * [inputs[key]]

       UpperCAmelCase_											=pipe(**_lowerCAmelCase		,  num_images_per_prompt=_lowerCAmelCase       )[0]

       assert images.shape[0] == batch_size * num_images_per_prompt

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



    def 	lowerCAmelCase__    (	self:						int       )						->    Optional[Any]:
       '''simple docstring'''

       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()






    def 	lowerCAmelCase__    (	self:						Tuple       )						->    Tuple:
       '''simple docstring'''

       UpperCAmelCase_											=load_image(
           "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/shap_e/corgi.png"       )
       UpperCAmelCase_											=load_numpy(
           "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
           "/shap_e/test_shap_e_img2img_out.npy"       )
       UpperCAmelCase_											=ShapEImgaImgPipeline.from_pretrained("openai/shap-e-img2img"       )
       UpperCAmelCase_											=pipe.to(_lowerCAmelCase       )
       pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

       UpperCAmelCase_											=torch.Generator(device=_lowerCAmelCase       ).manual_seed(0       )

       UpperCAmelCase_											=pipe(
           _lowerCAmelCase		,  generator=_lowerCAmelCase		,  guidance_scale=3.0		,  num_inference_steps=64		,  frame_size=64		,  output_type="np"		,  ).images[0]

       assert images.shape == (20, 64, 64, 3)

       assert_mean_pixel_difference(_lowerCAmelCase		,  _lowerCAmelCase       )











import math_equivalence  # From: git+https://github.com/hendrycks/math.git

import datasets


__lowercase  :   int						      ="""\
@article{hendrycksmath2021,
  title={Measuring Mathematical Problem Solving With the MATH Dataset},
  author={Dan Hendrycks
    and Collin Burns
    and Saurav Kadavath
    and Akul Arora
    and Steven Basart
    and Eric Tang
    and Dawn Song
    and Jacob Steinhardt},
  journal={arXiv preprint arXiv:2103.03874},
  year={2021}
}
"""


__lowercase  :   List[Any]						      ="""\
This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.
It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy.
"""


__lowercase  :   str						      =R"""
Calculates accuracy after canonicalizing inputs.

Args:
    predictions: list of predictions to score. Each prediction
        is a string that contains natural language and LaTex.
    references: list of reference for each prediction. Each
        reference is a string that contains natural language
        and LaTex.
Returns:
    accuracy: accuracy after canonicalizing inputs
        (e.g., converting \"1/2\" to \"\\frac{1}{2}\")

Examples:
    >>> metric = datasets.load_metric(\"competition_math\")
    >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"])
    >>> print(results)
    {'accuracy': 1.0}
"""

@datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION		,      _KWARGS_DESCRIPTION						)
class      A       (	datasets.Metric						):



      def 	lowerCAmelCase__    (	self:						Any       )						->    Optional[Any]:
         '''simple docstring'''

         return datasets.MetricInfo(
             description=_DESCRIPTION		,  citation=_CITATION		,  inputs_description=_KWARGS_DESCRIPTION		,  features=datasets.Features(
                 {
                     "predictions": datasets.Value("string"       ),
                     "references": datasets.Value("string"       ),
                 }       )		,  homepage="https://github.com/hendrycks/math"		,  codebase_urls=["https://github.com/hendrycks/math"]		,  )






      def 	lowerCAmelCase__    (	self:						Any		,  _lowerCAmelCase:						Tuple		,  _lowerCAmelCase:						Union[str, Any]       )						->    Dict:
         '''simple docstring'''

         UpperCAmelCase_											=0.0
         for i, j in zip(_lowerCAmelCase		,  _lowerCAmelCase       ):
            n_correct += 1.0 if math_equivalence.is_equiv(_lowerCAmelCase		,  _lowerCAmelCase       ) else 0.0
         UpperCAmelCase_											=n_correct / len(_lowerCAmelCase       )
         return {
             "accuracy": accuracy,
         }




