




"""simple docstring"""




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 (  __a      ,       unittest.TestCase				):
  _UpperCamelCase       :      Any			=      ShapEImgaImgPipeline
  _UpperCamelCase       :      Dict			=      ["""image"""]
  _UpperCamelCase       :      Tuple			=      ["""image"""]
  _UpperCamelCase       :      List[str]			=      [
      """num_images_per_prompt""",
      """num_inference_steps""",
      """generator""",
      """latents""",
      """guidance_scale""",
      """frame_size""",
      """output_type""",
      """return_dict""",
  ]
  _UpperCamelCase       :      Any			=      False






  @property
  def  __a      (  self		:     Optional[int]				)		->   Dict:






       """simple docstring"""







       return 32






  @property
  def  __a      (  self		:     int				)		->   int:






       """simple docstring"""







       return 32






  @property
  def  __a      (  self		:     int				)		->   Optional[Any]:






       """simple docstring"""







       return self.time_input_dim * 4






  @property
  def  __a      (  self		:     Tuple				)		->   Optional[Any]:






       """simple docstring"""







       return 8






  @property
  def  __a      (  self		:     List[str]				)		->   Optional[Any]:






       """simple docstring"""







       torch.manual_seed(0				)
       lowercase :       Optional[int]       =			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				,						)

       lowercase :       Optional[int]       =			CLIPVisionModel(a__				)
       return model






  @property
  def  __a      (  self		:     Union[str, Any]				)		->   List[Any]:






       """simple docstring"""







       lowercase :       Dict       =			CLIPImageProcessor(
           crop_size=224				,						do_center_crop=a__				,						do_normalize=a__				,						do_resize=a__				,						image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073]				,						image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711]				,						resample=3				,						size=224				,						)

       return image_processor






  @property
  def  __a      (  self		:     List[Any]				)		->   str:






       """simple docstring"""







       torch.manual_seed(0				)

       lowercase :       Dict       =			{
           '''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,
       }

       lowercase :       Optional[Any]       =			PriorTransformer(**a__				)
       return model






  @property
  def  __a      (  self		:     List[str]				)		->   str:






       """simple docstring"""







       torch.manual_seed(0				)

       lowercase :       Optional[Any]       =			{
           '''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,
           ),
       }
       lowercase :       Dict       =			ShapERenderer(**a__				)
       return model






  def  __a      (  self		:     Optional[Any]				)		->   List[str]:






       """simple docstring"""







       lowercase :       Any       =			self.dummy_prior
       lowercase :       Optional[Any]       =			self.dummy_image_encoder
       lowercase :       List[Any]       =			self.dummy_image_processor
       lowercase :       str       =			self.dummy_renderer

       lowercase :       Optional[Any]       =			HeunDiscreteScheduler(
           beta_schedule='''exp'''				,						num_train_timesteps=1_024				,						prediction_type='''sample'''				,						use_karras_sigmas=a__				,						clip_sample=a__				,						clip_sample_range=1.0				,						)
       lowercase :       Optional[int]       =			{
           '''prior''': prior,
           '''image_encoder''': image_encoder,
           '''image_processor''': image_processor,
           '''renderer''': renderer,
           '''scheduler''': scheduler,
       }

       return components






  def  __a      (  self		:     Optional[Any]				,						_A		:     List[Any]				,						_A		:     Union[str, Any]=0				)		->   List[str]:






       """simple docstring"""







       lowercase :       List[Any]       =			floats_tensor((1, 3, 64, 64)				,						rng=random.Random(a__				)				).to(a__				)

       if str(a__				).startswith('''mps'''				):
            lowercase :       List[str]       =			torch.manual_seed(a__				)
       else:
            lowercase :       List[Any]       =			torch.Generator(device=a__				).manual_seed(a__				)
       lowercase :       int       =			{
           '''image''': input_image,
           '''generator''': generator,
           '''num_inference_steps''': 1,
           '''frame_size''': 32,
           '''output_type''': '''np''',
       }
       return inputs






  def  __a      (  self		:     Dict				)		->   str:






       """simple docstring"""







       lowercase :       Optional[Any]       =			'''cpu'''

       lowercase :       Union[str, Any]       =			self.get_dummy_components()

       lowercase :       Optional[int]       =			self.pipeline_class(**a__				)
       lowercase :       Union[str, Any]       =			pipe.to(a__				)

       pipe.set_progress_bar_config(disable=a__				)

       lowercase :       str       =			pipe(**self.get_dummy_inputs(a__				)				)
       lowercase :       List[str]       =			output.images[0]
       lowercase :       Dict       =			image[0, -3:, -3:, -1]

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

       lowercase :       Optional[Any]       =			np.array(
           [
               0.00_039_216,
               0.00_039_216,
               0.00_039_216,
               0.00_039_216,
               0.00_039_216,
               0.00_039_216,
               0.00_039_216,
               0.00_039_216,
               0.00_039_216,
           ]				)

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






  def  __a      (  self		:     Optional[int]				)		->   int:






       """simple docstring"""







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






  def  __a      (  self		:     Any				)		->   Optional[Any]:






       """simple docstring"""







       lowercase :       Optional[int]       =			torch_device == '''cpu'''
       lowercase :       List[Any]       =			True
       self._test_inference_batch_single_identical(
           batch_size=2				,						test_max_difference=a__				,						relax_max_difference=a__				,						)






  def  __a      (  self		:     List[str]				)		->   List[Any]:






       """simple docstring"""







       lowercase :       Dict       =			self.get_dummy_components()
       lowercase :       Dict       =			self.pipeline_class(**a__				)
       lowercase :       str       =			pipe.to(a__				)
       pipe.set_progress_bar_config(disable=a__				)

       lowercase :       Union[str, Any]       =			1
       lowercase :       Optional[Any]       =			2

       lowercase :       Optional[int]       =			self.get_dummy_inputs(a__				)

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

       lowercase :       int       =			pipe(**a__				,						num_images_per_prompt=a__				)[0]

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


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






  def  __a      (  self		:     Tuple				)		->   List[str]:






       """simple docstring"""







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






  def  __a      (  self		:     Dict				)		->   Dict:






       """simple docstring"""







       lowercase :       Any       =			load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png'''				)
       lowercase :       Optional[Any]       =			load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/shap_e/test_shap_e_img2img_out.npy'''				)
       lowercase :       Tuple       =			ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img'''				)
       lowercase :       Optional[Any]       =			pipe.to(a__				)
       pipe.set_progress_bar_config(disable=a__				)

       lowercase :       List[str]       =			torch.Generator(device=a__				).manual_seed(0				)

       lowercase :       Any       =			pipe(
           a__				,						generator=a__				,						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(a__				,						a__				)





from sklearn.metrics import mean_squared_error

import datasets


lowerCAmelCase_						=			'\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n'

lowerCAmelCase_						=			'\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n'


lowerCAmelCase_						=			'\nArgs:\n    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Estimated target values.\n    references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Ground truth (correct) target values.\n    sample_weight: array-like of shape (n_samples,), default=None\n        Sample weights.\n    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"\n        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n        "raw_values" : Returns a full set of errors in case of multioutput input.\n\n        "uniform_average" : Errors of all outputs are averaged with uniform weight.\n\n    squared : bool, default=True\n        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n    mse : mean squared error.\nExamples:\n\n    >>> mse_metric = datasets.load_metric("mse")\n    >>> predictions = [2.5, 0.0, 2, 8]\n    >>> references = [3, -0.5, 2, 7]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'mse\': 0.375}\n    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n    >>> print(rmse_result)\n    {\'mse\': 0.6123724356957945}\n\n    If you\'re using multi-dimensional lists, then set the config as follows :\n\n    >>> mse_metric = datasets.load_metric("mse", "multilist")\n    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n    >>> references = [[0, 2], [-1, 2], [8, -5]]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'mse\': 0.7083333333333334}\n    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {\'mse\': array([0.41666667, 1. ])}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION      ,       _KWARGS_DESCRIPTION				)
class 						_A (  datasets.Metric				):






  def  __a      (  self		:     List[Any]				)		->   Optional[Any]:






       """simple docstring"""







       return datasets.MetricInfo(
           description=_DESCRIPTION				,						citation=_CITATION				,						inputs_description=_KWARGS_DESCRIPTION				,						features=datasets.Features(self._get_feature_types()				)				,						reference_urls=[
               '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html'''
           ]				,						)






  def  __a      (  self		:     List[Any]				)		->   int:






       """simple docstring"""







       if self.config_name == "multilist":
            return {
                "predictions": datasets.Sequence(datasets.Value('''float'''				)				),
                "references": datasets.Sequence(datasets.Value('''float'''				)				),
            }
       else:
            return {
                "predictions": datasets.Value('''float'''				),
                "references": datasets.Value('''float'''				),
            }






  def  __a      (  self		:     Any				,						_A		:     Dict				,						_A		:     Any				,						_A		:     Any=None				,						_A		:     Any="uniform_average"				,						_A		:     Optional[Any]=True				)		->   Dict:






       """simple docstring"""







       lowercase :       Any       =			mean_squared_error(
           _A				,						_A				,						sample_weight=_A				,						multioutput=_A				,						squared=_A				)

       return {"mse": mse}