import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
__SCREAMING_SNAKE_CASE						:   List[Any]         =			pytest.mark.integration


__SCREAMING_SNAKE_CASE						:   Tuple         =			{'comet'}
__SCREAMING_SNAKE_CASE						:   Dict         =			importlib.util.find_spec('fairseq') is not None

__SCREAMING_SNAKE_CASE						:   Tuple         =			{'code_eval'}
__SCREAMING_SNAKE_CASE						:   Optional[int]         =			os.name == 'nt'

__SCREAMING_SNAKE_CASE						:   str         =			{'bertscore', 'frugalscore', 'perplexity'}
__SCREAMING_SNAKE_CASE						:   str         =			importlib.util.find_spec('transformers') is not None
def  snake_case						(__lowercase						)	->	Optional[Any]:

						'''simple docstring'''



						@wraps(__lowercase						)
						def wrapper(self ,      __lowercase						):
												if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
																		self.skipTest("\"test requires Fairseq\""						)
												else:
																		test_case(self ,      __lowercase						)

						return wrapper
def  snake_case						(__lowercase						)	->	List[Any]:

						'''simple docstring'''



						@wraps(__lowercase						)
						def wrapper(self ,      __lowercase						):
												if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
																		self.skipTest("\"test requires transformers\""						)
												else:
																		test_case(self ,      __lowercase						)

						return wrapper
def  snake_case						(__lowercase						)	->	str:

						'''simple docstring'''



						@wraps(__lowercase						)
						def wrapper(self ,      __lowercase						):
												if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
																		self.skipTest("\"test not supported on Windows\""						)
												else:
																		test_case(self ,      __lowercase						)

						return wrapper
def  snake_case						()	->	Optional[int]:

						'''simple docstring'''



						_snake_case						:					List[Any]    =   [metric_dir.split(os.sep						)[-2] for metric_dir in glob.glob("./metrics/*/"						)]
						return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished



@parameterized.named_parameters(get_local_metric_names()		)
@for_all_test_methods(
    __snake_case						,			__snake_case						,			__snake_case		)
@local
class        lowercase_   (					parameterized.TestCase		):
							_lowerCamelCase						=		{}
							_lowerCamelCase						=		None



							@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning"    )
							@pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning"    )
							def 	UpperCamelCase	(						self				,    lowercase_    ):
													_snake_case						:					Tuple    =   "[...]"
													_snake_case						:					Tuple    =   importlib.import_module(
													    datasets.load.metric_module_factory(os.path.join("metrics"				,    lowercase_    )    ).module_path    )
													_snake_case						:					List[str]    =   datasets.load.import_main_class(metric_module.__name__				,    dataset=lowercase_    )
													# check parameters
													_snake_case						:					int    =   inspect.signature(metric._compute    ).parameters
													self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()    )    )  # no **kwargs
													# run doctest
													with self.patch_intensive_calls(lowercase_				,    metric_module.__name__    ):
																			with self.use_local_metrics():
																									try:
																															_snake_case						:					List[str]    =   doctest.testmod(lowercase_				,    verbose=lowercase_				,    raise_on_error=lowercase_    )
																									except doctest.UnexpectedException as e:
																															raise e.exc_info[1]  # raise the exception that doctest caught
													self.assertEqual(results.failed				,    0    )
													self.assertGreater(results.attempted				,    1    )



							@slow
							def 	UpperCamelCase	(						self				,    lowercase_    ):
													_snake_case						:					Dict    =   "[...]"
													_snake_case						:					str    =   importlib.import_module(
													    datasets.load.metric_module_factory(os.path.join("metrics"				,    lowercase_    )    ).module_path    )
													# run doctest
													with self.use_local_metrics():
																			_snake_case						:					str    =   doctest.testmod(lowercase_				,    verbose=lowercase_				,    raise_on_error=lowercase_    )
													self.assertEqual(results.failed				,    0    )
													self.assertGreater(results.attempted				,    1    )



							@contextmanager
							def 	UpperCamelCase	(						self				,    lowercase_				,    lowercase_    ):
													if metric_name in self.INTENSIVE_CALLS_PATCHER:
																			with self.INTENSIVE_CALLS_PATCHER[metric_name](lowercase_    ):
																									yield
													else:
																			yield



							@contextmanager
							def 	UpperCamelCase	(						self    ):
													def load_local_metric(lowercase_				,    *lowercase_				,    **lowercase_    ):
																			return load_metric(os.path.join("metrics"				,    lowercase_    )				,    *lowercase_				,    **lowercase_    )

													with patch("datasets.load_metric"    ) as mock_load_metric:
																			_snake_case						:					Tuple    =   load_local_metric
																			yield



							@classmethod
							def 	UpperCamelCase	(						cls				,    lowercase_    ):
													def wrapper(lowercase_    ):
																			_snake_case						:					Tuple    =   contextmanager(lowercase_    )
																			_snake_case						:					List[Any]    =   patcher
																			return patcher

													return wrapper




@LocalMetricTest.register_intensive_calls_patcher("bleurt"						)
def  snake_case						(__lowercase						)	->	Tuple:

						'''simple docstring'''



						import tensorflow.compat.va as tf
						from bleurt.score import Predictor

						tf.flags.DEFINE_string("sv" ,      "" ,      ""						)  # handle pytest cli flags



						class        lowercase_   (					__snake_case		):



													def 	UpperCamelCase	(						self				,    lowercase_    ):
																			assert len(input_dict["input_ids"]    ) == 2
																			return np.array([1.03, 1.04]    )

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
						with patch("bleurt.score._create_predictor"						) as mock_create_predictor:
												_snake_case						:					Any    =   MockedPredictor()
												yield
@LocalMetricTest.register_intensive_calls_patcher("bertscore"						)
def  snake_case						(__lowercase						)	->	Optional[Any]:

						'''simple docstring'''



						import torch

						def bert_cos_score_idf(__lowercase ,      __lowercase ,      *__lowercase ,      **__lowercase						):
												return torch.tensor([[1.0, 1.0, 1.0]] * len(__lowercase						)						)

						# mock get_model which is supposed to do download a bert model
						# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
						with patch("bert_score.scorer.get_model"						), patch(
						    "bert_score.scorer.bert_cos_score_idf"						) as mock_bert_cos_score_idf:
												_snake_case						:					Any    =   bert_cos_score_idf
												yield
@LocalMetricTest.register_intensive_calls_patcher("comet"						)
def  snake_case						(__lowercase						)	->	Any:

						'''simple docstring'''



						def load_from_checkpoint(__lowercase						):



												class        lowercase_   :



																			def 	UpperCamelCase	(						self				,    lowercase_				,    *lowercase_				,    **lowercase_    ):
																									assert len(lowercase_    ) == 2
																									_snake_case						:					Union[str, Any]    =   [0.19, 0.92]
																									return scores, sum(lowercase_    ) / len(lowercase_    )




												return Model()

						# mock load_from_checkpoint which is supposed to do download a bert model
						# mock load_from_checkpoint which is supposed to do download a bert model
						with patch("comet.download_model"						) as mock_download_model:
												_snake_case						:					Tuple    =   None
												with patch("comet.load_from_checkpoint"						) as mock_load_from_checkpoint:
																		_snake_case						:					Union[str, Any]    =   load_from_checkpoint
																		yield

def  snake_case						()	->	Optional[int]:

						'''simple docstring'''



						_snake_case						:					Any    =   load_metric(os.path.join("metrics" ,      "seqeval"						)						)
						_snake_case						:					int    =   "ERROR"
						_snake_case						:					Dict    =   F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
						with pytest.raises(__lowercase ,      match=re.escape(__lowercase						)						):
												metric.compute(predictions=[] ,      references=[] ,      scheme=__lowercase						)
import tempfile

import numpy as np
import torch
from transformers import AutoTokenizer, TaEncoderModel

from diffusers import DDPMScheduler, UNetaDConditionModel
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.pipelines.deepfloyd_if import IFWatermarker
from diffusers.utils.testing_utils import torch_device

from ..test_pipelines_common import to_np



class        lowercase_   :



							def 	UpperCamelCase	(						self    ):
													torch.manual_seed(0    )
													_snake_case						:					Tuple    =   TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5"    )

													torch.manual_seed(0    )
													_snake_case						:					List[Any]    =   AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5"    )

													torch.manual_seed(0    )
													_snake_case						:					Optional[int]    =   UNetaDConditionModel(
													    sample_size=32				,    layers_per_block=1				,    block_out_channels=[32, 64]				,    down_block_types=[
													        "ResnetDownsampleBlock2D",
													        "SimpleCrossAttnDownBlock2D",
													    ]				,    mid_block_type="UNetMidBlock2DSimpleCrossAttn"				,    up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"]				,    in_channels=3				,    out_channels=6				,    cross_attention_dim=32				,    encoder_hid_dim=32				,    attention_head_dim=8				,    addition_embed_type="text"				,    addition_embed_type_num_heads=2				,    cross_attention_norm="group_norm"				,    resnet_time_scale_shift="scale_shift"				,    act_fn="gelu"				,    )
													unet.set_attn_processor(AttnAddedKVProcessor()    )  # For reproducibility tests

													torch.manual_seed(0    )
													_snake_case						:					str    =   DDPMScheduler(
													    num_train_timesteps=1_000				,    beta_schedule="squaredcos_cap_v2"				,    beta_start=0.0_001				,    beta_end=0.02				,    thresholding=lowercase_				,    dynamic_thresholding_ratio=0.95				,    sample_max_value=1.0				,    prediction_type="epsilon"				,    variance_type="learned_range"				,    )

													torch.manual_seed(0    )
													_snake_case						:					int    =   IFWatermarker()

													return {
													    "text_encoder": text_encoder,
													    "tokenizer": tokenizer,
													    "unet": unet,
													    "scheduler": scheduler,
													    "watermarker": watermarker,
													    "safety_checker": None,
													    "feature_extractor": None,
													}



							def 	UpperCamelCase	(						self    ):
													torch.manual_seed(0    )
													_snake_case						:					List[str]    =   TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5"    )

													torch.manual_seed(0    )
													_snake_case						:					Tuple    =   AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5"    )

													torch.manual_seed(0    )
													_snake_case						:					Any    =   UNetaDConditionModel(
													    sample_size=32				,    layers_per_block=[1, 2]				,    block_out_channels=[32, 64]				,    down_block_types=[
													        "ResnetDownsampleBlock2D",
													        "SimpleCrossAttnDownBlock2D",
													    ]				,    mid_block_type="UNetMidBlock2DSimpleCrossAttn"				,    up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"]				,    in_channels=6				,    out_channels=6				,    cross_attention_dim=32				,    encoder_hid_dim=32				,    attention_head_dim=8				,    addition_embed_type="text"				,    addition_embed_type_num_heads=2				,    cross_attention_norm="group_norm"				,    resnet_time_scale_shift="scale_shift"				,    act_fn="gelu"				,    class_embed_type="timestep"				,    mid_block_scale_factor=1.414				,    time_embedding_act_fn="gelu"				,    time_embedding_dim=32				,    )
													unet.set_attn_processor(AttnAddedKVProcessor()    )  # For reproducibility tests

													torch.manual_seed(0    )
													_snake_case						:					Union[str, Any]    =   DDPMScheduler(
													    num_train_timesteps=1_000				,    beta_schedule="squaredcos_cap_v2"				,    beta_start=0.0_001				,    beta_end=0.02				,    thresholding=lowercase_				,    dynamic_thresholding_ratio=0.95				,    sample_max_value=1.0				,    prediction_type="epsilon"				,    variance_type="learned_range"				,    )

													torch.manual_seed(0    )
													_snake_case						:					List[str]    =   DDPMScheduler(
													    num_train_timesteps=1_000				,    beta_schedule="squaredcos_cap_v2"				,    beta_start=0.0_001				,    beta_end=0.02				,    )

													torch.manual_seed(0    )
													_snake_case						:					Dict    =   IFWatermarker()

													return {
													    "text_encoder": text_encoder,
													    "tokenizer": tokenizer,
													    "unet": unet,
													    "scheduler": scheduler,
													    "image_noising_scheduler": image_noising_scheduler,
													    "watermarker": watermarker,
													    "safety_checker": None,
													    "feature_extractor": None,
													}



							def 	UpperCamelCase	(						self    ):
													_snake_case						:					List[Any]    =   self.get_dummy_components()
													_snake_case						:					List[Any]    =   self.pipeline_class(**lowercase_    )
													pipe.to(lowercase_    )
													pipe.set_progress_bar_config(disable=lowercase_    )

													_snake_case						:					Union[str, Any]    =   self.get_dummy_inputs(lowercase_    )

													_snake_case						:					Union[str, Any]    =   inputs["prompt"]
													_snake_case						:					Dict    =   inputs["generator"]
													_snake_case						:					Any    =   inputs["num_inference_steps"]
													_snake_case						:					Union[str, Any]    =   inputs["output_type"]

													if "image" in inputs:
																			_snake_case						:					int    =   inputs["image"]
													else:
																			_snake_case						:					Union[str, Any]    =   None

													if "mask_image" in inputs:
																			_snake_case						:					int    =   inputs["mask_image"]
													else:
																			_snake_case						:					List[str]    =   None

													if "original_image" in inputs:
																			_snake_case						:					Tuple    =   inputs["original_image"]
													else:
																			_snake_case						:					Any    =   None

													_snake_case    ,_snake_case						:					Optional[int]    =   pipe.encode_prompt(lowercase_    )

													# inputs with prompt converted to embeddings
													_snake_case						:					Dict    =   {
													    "prompt_embeds": prompt_embeds,
													    "negative_prompt_embeds": negative_prompt_embeds,
													    "generator": generator,
													    "num_inference_steps": num_inference_steps,
													    "output_type": output_type,
													}

													if image is not None:
																			_snake_case						:					int    =   image

													if mask_image is not None:
																			_snake_case						:					int    =   mask_image

													if original_image is not None:
																			_snake_case						:					Any    =   original_image

													# set all optional components to None
													for optional_component in pipe._optional_components:
																			setattr(lowercase_				,    lowercase_				,    lowercase_    )

													_snake_case						:					Optional[int]    =   pipe(**lowercase_    )[0]

													with tempfile.TemporaryDirectory() as tmpdir:
																			pipe.save_pretrained(lowercase_    )
																			_snake_case						:					Any    =   self.pipeline_class.from_pretrained(lowercase_    )
																			pipe_loaded.to(lowercase_    )
																			pipe_loaded.set_progress_bar_config(disable=lowercase_    )

													pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()    )  # For reproducibility tests

													for optional_component in pipe._optional_components:
																			self.assertTrue(
																			    getattr(lowercase_				,    lowercase_    ) is None				,    f"""`{optional_component}` did not stay set to None after loading."""				,    )

													_snake_case						:					int    =   self.get_dummy_inputs(lowercase_    )

													_snake_case						:					Optional[int]    =   inputs["generator"]
													_snake_case						:					List[Any]    =   inputs["num_inference_steps"]
													_snake_case						:					Tuple    =   inputs["output_type"]

													# inputs with prompt converted to embeddings
													_snake_case						:					int    =   {
													    "prompt_embeds": prompt_embeds,
													    "negative_prompt_embeds": negative_prompt_embeds,
													    "generator": generator,
													    "num_inference_steps": num_inference_steps,
													    "output_type": output_type,
													}

													if image is not None:
																			_snake_case						:					int    =   image

													if mask_image is not None:
																			_snake_case						:					str    =   mask_image

													if original_image is not None:
																			_snake_case						:					int    =   original_image

													_snake_case						:					Optional[Any]    =   pipe_loaded(**lowercase_    )[0]

													_snake_case						:					Dict    =   np.abs(to_np(lowercase_    ) - to_np(lowercase_    )    ).max()
													self.assertLess(lowercase_				,    1e-4    )



							def 	UpperCamelCase	(						self    ):
													_snake_case						:					Tuple    =   self.get_dummy_components()
													_snake_case						:					Any    =   self.pipeline_class(**lowercase_    )
													pipe.to(lowercase_    )
													pipe.set_progress_bar_config(disable=lowercase_    )

													_snake_case						:					int    =   self.get_dummy_inputs(lowercase_    )
													_snake_case						:					List[str]    =   pipe(**lowercase_    )[0]

													with tempfile.TemporaryDirectory() as tmpdir:
																			pipe.save_pretrained(lowercase_    )
																			_snake_case						:					List[Any]    =   self.pipeline_class.from_pretrained(lowercase_    )
																			pipe_loaded.to(lowercase_    )
																			pipe_loaded.set_progress_bar_config(disable=lowercase_    )

													pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()    )  # For reproducibility tests

													_snake_case						:					Optional[Any]    =   self.get_dummy_inputs(lowercase_    )
													_snake_case						:					int    =   pipe_loaded(**lowercase_    )[0]

													_snake_case						:					Tuple    =   np.abs(to_np(lowercase_    ) - to_np(lowercase_    )    ).max()
													self.assertLess(lowercase_				,    1e-4    )