


import gc
import unittest

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

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import 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 			_lowercase (							lowercase__							,  unittest.TestCase):


       """simple docstring"""




       A__											=			ShapEPipeline
       A__											=			["prompt"]
       A__											=			["prompt"]
       A__											=			[
           "num_images_per_prompt",
           "num_inference_steps",
           "generator",
           "latents",
           "guidance_scale",
           "frame_size",
           "output_type",
           "return_dict",
       ]
       A__											=			False





       @property
       def 						lowerCAmelCase     (   self							:			List[Any]       ):


             '''simple docstring'''



             return 32





       @property
       def 						lowerCAmelCase     (   self							:			Optional[Any]       ):


             '''simple docstring'''



             return 32





       @property
       def 						lowerCAmelCase     (   self							:			Any       ):


             '''simple docstring'''



             return self.time_input_dim * 4





       @property
       def 						lowerCAmelCase     (   self							:			Optional[int]       ):


             '''simple docstring'''



             return 8





       @property
       def 						lowerCAmelCase     (   self							:			Union[str, Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Dict    =  CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )
             return tokenizer





       @property
       def 						lowerCAmelCase     (   self							:			Optional[Any]       ):


             '''simple docstring'''



             torch.manual_seed(0       )
             lowerCamelCase__		:				Optional[Any]    =  CLIPTextConfig(
                 bos_token_id=0					,      eos_token_id=2					,      hidden_size=self.text_embedder_hidden_size					,      projection_dim=self.text_embedder_hidden_size					,      intermediate_size=37					,      layer_norm_eps=1E-0_5					,      num_attention_heads=4					,      num_hidden_layers=5					,      pad_token_id=1					,      vocab_size=1000					,      )
             return CLIPTextModelWithProjection(__lowerCamelCase       )





       @property
       def 						lowerCAmelCase     (   self							:			Any       ):


             '''simple docstring'''



             torch.manual_seed(0       )

             lowerCamelCase__		:				Union[str, Any]    =  {
                 "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",
                 "encoder_hid_proj_type": None,
                 "added_emb_type": None,
             }

             lowerCamelCase__		:				List[str]    =  PriorTransformer(**__lowerCamelCase       )
             return model





       @property
       def 						lowerCAmelCase     (   self							:			int       ):


             '''simple docstring'''



             torch.manual_seed(0       )

             lowerCamelCase__		:				Union[str, 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,
                 ),
             }
             lowerCamelCase__		:				Any    =  ShapERenderer(**__lowerCamelCase       )
             return model





       def 						lowerCAmelCase     (   self							:			List[str]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Tuple    =  self.dummy_prior
             lowerCamelCase__		:				str    =  self.dummy_text_encoder
             lowerCamelCase__		:				Optional[int]    =  self.dummy_tokenizer
             lowerCamelCase__		:				Dict    =  self.dummy_renderer

             lowerCamelCase__		:				Any    =  HeunDiscreteScheduler(
                 beta_schedule="exp"					,      num_train_timesteps=1024					,      prediction_type="sample"					,      use_karras_sigmas=__lowerCamelCase					,      clip_sample=__lowerCamelCase					,      clip_sample_range=1.0					,      )
             lowerCamelCase__		:				Tuple    =  {
                 "prior": prior,
                 "text_encoder": text_encoder,
                 "tokenizer": tokenizer,
                 "renderer": renderer,
                 "scheduler": scheduler,
             }

             return components





       def 						lowerCAmelCase     (   self							:			List[str]					,      __lowerCamelCase							:			List[str]					,      __lowerCamelCase							:			Optional[Any]=0       ):


             '''simple docstring'''



             if str(__lowerCamelCase       ).startswith("mps"       ):
                   lowerCamelCase__		:				Dict    =  torch.manual_seed(__lowerCamelCase       )
             else:
                   lowerCamelCase__		:				Tuple    =  torch.Generator(device=__lowerCamelCase       ).manual_seed(__lowerCamelCase       )
             lowerCamelCase__		:				List[str]    =  {
                 "prompt": "horse",
                 "generator": generator,
                 "num_inference_steps": 1,
                 "frame_size": 32,
                 "output_type": "np",
             }
             return inputs





       def 						lowerCAmelCase     (   self							:			Dict       ):


             '''simple docstring'''



             lowerCamelCase__		:				Any    =  "cpu"

             lowerCamelCase__		:				Any    =  self.get_dummy_components()

             lowerCamelCase__		:				Dict    =  self.pipeline_class(**__lowerCamelCase       )
             lowerCamelCase__		:				List[Any]    =  pipe.to(__lowerCamelCase       )

             pipe.set_progress_bar_config(disable=__lowerCamelCase       )

             lowerCamelCase__		:				Dict    =  pipe(**self.get_dummy_inputs(__lowerCamelCase       )       )
             lowerCamelCase__		:				List[Any]    =  output.images[0]
             lowerCamelCase__		:				Tuple    =  image[0, -3:, -3:, -1]

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

             lowerCamelCase__		:				str    =  np.array(
                 [
                     0.0_0_0_3_9_2_1_6,
                     0.0_0_0_3_9_2_1_6,
                     0.0_0_0_3_9_2_1_6,
                     0.0_0_0_3_9_2_1_6,
                     0.0_0_0_3_9_2_1_6,
                     0.0_0_0_3_9_2_1_6,
                     0.0_0_0_3_9_2_1_6,
                     0.0_0_0_3_9_2_1_6,
                     0.0_0_0_3_9_2_1_6,
                 ]       )

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





       def 						lowerCAmelCase     (   self							:			List[Any]       ):


             '''simple docstring'''



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





       def 						lowerCAmelCase     (   self							:			List[str]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Tuple    =  torch_device == "cpu"
             lowerCamelCase__		:				List[str]    =  True

             self._test_inference_batch_single_identical(
                 batch_size=2					,      test_max_difference=__lowerCamelCase					,      relax_max_difference=__lowerCamelCase					,      )





       def 						lowerCAmelCase     (   self							:			List[Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				int    =  self.get_dummy_components()
             lowerCamelCase__		:				Union[str, Any]    =  self.pipeline_class(**__lowerCamelCase       )
             lowerCamelCase__		:				str    =  pipe.to(__lowerCamelCase       )
             pipe.set_progress_bar_config(disable=__lowerCamelCase       )

             lowerCamelCase__		:				str    =  1
             lowerCamelCase__		:				List[Any]    =  2

             lowerCamelCase__		:				Dict    =  self.get_dummy_inputs(__lowerCamelCase       )

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

             lowerCamelCase__		:				Optional[int]    =  pipe(**__lowerCamelCase					,      num_images_per_prompt=__lowerCamelCase       )[0]

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







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


       """simple docstring"""




       def 						lowerCAmelCase     (   self							:			Any       ):


             '''simple docstring'''



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





       def 						lowerCAmelCase     (   self							:			Tuple       ):


             '''simple docstring'''



             lowerCamelCase__		:				int    =  load_numpy(
                 "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                 "/shap_e/test_shap_e_np_out.npy"       )
             lowerCamelCase__		:				Optional[Any]    =  ShapEPipeline.from_pretrained("openai/shap-e"       )
             lowerCamelCase__		:				Tuple    =  pipe.to(__lowerCamelCase       )
             pipe.set_progress_bar_config(disable=__lowerCamelCase       )

             lowerCamelCase__		:				Any    =  torch.Generator(device=__lowerCamelCase       ).manual_seed(0       )

             lowerCamelCase__		:				Optional[int]    =  pipe(
                 "a shark"					,      generator=__lowerCamelCase					,      guidance_scale=1_5.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 datasets

from .evaluate import evaluate


A      :    Dict		=					"\\n@article{hendrycks2021cuad,\n      title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n      author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n      journal={arXiv preprint arXiv:2103.06268},\n      year={2021}\n}\n"

A      :    Any		=					"\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n"

A      :    str		=					"\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n    predictions: List of question-answers dictionaries with the following key-values:\n        - 'id': id of the question-answer pair as given in the references (see below)\n        - 'prediction_text': list of possible texts for the answer, as a list of strings\n        depending on a threshold on the confidence probability of each prediction.\n    references: List of question-answers dictionaries with the following key-values:\n        - 'id': id of the question-answer pair (see above),\n        - 'answers': a Dict in the CUAD dataset format\n            {\n                'text': list of possible texts for the answer, as a list of strings\n                'answer_start': list of start positions for the answer, as a list of ints\n            }\n            Note that answer_start values are not taken into account to compute the metric.\nReturns:\n    'exact_match': Exact match (the normalized answer exactly match the gold answer)\n    'f1': The F-score of predicted tokens versus the gold answer\n    'aupr': Area Under the Precision-Recall curve\n    'prec_at_80_recall': Precision at 80% recall\n    'prec_at_90_recall': Precision at 90% recall\nExamples:\n    >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]\n    >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]\n    >>> cuad_metric = datasets.load_metric(\"cuad\")\n    >>> results = cuad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0}\n"







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


       """simple docstring"""




       def 						lowerCAmelCase     (   self							:			Optional[Any]       ):


             '''simple docstring'''



             return datasets.MetricInfo(
                 description=_DESCRIPTION					,      citation=_CITATION					,      inputs_description=_KWARGS_DESCRIPTION					,      features=datasets.Features(
                     {
                         "predictions": {
                             "id": datasets.Value("string"       ),
                             "prediction_text": datasets.features.Sequence(datasets.Value("string"       )       ),
                         },
                         "references": {
                             "id": datasets.Value("string"       ),
                             "answers": datasets.features.Sequence(
                                 {
                                     "text": datasets.Value("string"       ),
                                     "answer_start": datasets.Value("int32"       ),
                                 }       ),
                         },
                     }       )					,      codebase_urls=["https://www.atticusprojectai.org/cuad"]					,      reference_urls=["https://www.atticusprojectai.org/cuad"]					,      )





       def 						lowerCAmelCase     (   self							:			Union[str, Any]					,      __lowerCamelCase							:			List[str]					,      __lowerCamelCase							:			Dict       ):


             '''simple docstring'''



             lowerCamelCase__		:				int    =  {prediction["id"]: prediction["prediction_text"] for prediction in predictions}
             lowerCamelCase__		:				Any    =  [
                 {
                     "paragraphs": [
                         {
                             "qas": [
                                 {
                                     "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]],
                                     "id": ref["id"],
                                 }
                                 for ref in references
                             ]
                         }
                     ]
                 }
             ]
             lowerCamelCase__		:				Optional[int]    =  evaluate(dataset=__lowerCamelCase					,      predictions=__lowerCamelCase       )
             return score


