



import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow


if is_tf_available():
			import tensorflow as tf

if is_tensorflow_text_available():
			from transformers.models.bert import TFBertTokenizer


UpperCamelCase__ =						["bert-base-uncased", "bert-base-cased"]
UpperCamelCase__ =						"hf-internal-testing/tiny-bert-tf-only"

if is_tf_available():
			class 			_lowerCAmelCase   ( tf.keras.Model			):






						"""simple docstring"""





						def __init__(				self	:       Union[str, Any]			,     lowercase	:       Optional[Any]   )						->					Any:
												"""simple docstring"""







												super().__init__()
												__lowercase					=				tokenizer
												__lowercase					=				AutoConfig.from_pretrained(lowercase   )
												__lowercase					=				TFAutoModel.from_config(lowercase   )







						def 		snake_case__			(				self	:       Any			,     lowercase	:       int   )						->					List[Any]:
												"""simple docstring"""







												__lowercase					=				self.tokenizer(lowercase   )
												__lowercase					=				self.bert(**lowercase   )
												return out["pooler_output"]
@require_tf
@require_tensorflow_text
class 			_lowerCAmelCase   ( unittest.TestCase			):






			"""simple docstring"""





			def 		snake_case__			(				self	:       Dict   )						->					Dict:
									"""simple docstring"""







									super().setUp()

									__lowercase					=				[
									    BertTokenizer.from_pretrained(lowercase   ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
									]  # repeat for when fast_bert_tokenizer=false
									__lowercase					=				[TFBertTokenizer.from_pretrained(lowercase   ) for checkpoint in TOKENIZER_CHECKPOINTS] + [
									    TFBertTokenizer.from_pretrained(lowercase			,     use_fast_bert_tokenizer=lowercase   )
									    for checkpoint in TOKENIZER_CHECKPOINTS
									]
									assert len(self.tokenizers   ) == len(self.tf_tokenizers   )

									__lowercase					=				[
									    """This is a straightforward English test sentence.""",
									    """This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.""",
									    """Now we're going to add some Chinese: 一 二 三 一二三""",
									    """And some much more rare Chinese: 齉 堃 齉堃""",
									    """Je vais aussi écrire en français pour tester les accents""",
									    """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""",
									]
									__lowercase					=				list(zip(self.test_sentences			,     self.test_sentences[::-1]   )   )





			def 		snake_case__			(				self	:       Optional[int]   )						->					Tuple:
									"""simple docstring"""







									for tokenizer, tf_tokenizer in zip(self.tokenizers			,     self.tf_tokenizers   ):
															for test_inputs in (self.test_sentences, self.paired_sentences):
																					__lowercase					=				tokenizer(lowercase			,     return_tensors="""tf"""			,     padding="""longest"""   )
																					__lowercase					=				tf_tokenizer(lowercase   )

																					for key in python_outputs.keys():
																											self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape   )   )
																											self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key]			,     tf.intaa   ) == tf_outputs[key]   )   )





			@slow
			def 		snake_case__			(				self	:       Any   )						->					Any:
									"""simple docstring"""







									for tf_tokenizer in self.tf_tokenizers:
															__lowercase					=				tf_tokenizer(self.paired_sentences   )
															__lowercase					=				tf_tokenizer(
															    text=[sentence[0] for sentence in self.paired_sentences]			,     text_pair=[sentence[1] for sentence in self.paired_sentences]			,     )
															for key in merged_outputs.keys():
																					self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key]			,     tf.intaa   ) == separated_outputs[key]   )   )





			@slow
			def 		snake_case__			(				self	:       Dict   )						->					Optional[int]:
									"""simple docstring"""







									for tf_tokenizer in self.tf_tokenizers:
															__lowercase					=				tf.function(lowercase   )
															for test_inputs in (self.test_sentences, self.paired_sentences):
																					__lowercase					=				tf.constant(lowercase   )
																					__lowercase					=				compiled_tokenizer(lowercase   )
																					__lowercase					=				tf_tokenizer(lowercase   )

																					for key in eager_outputs.keys():
																											self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]   )   )







			@slow
			def 		snake_case__			(				self	:       List[Any]   )						->					Tuple:
									"""simple docstring"""







									for tf_tokenizer in self.tf_tokenizers:
															__lowercase					=				ModelToSave(tokenizer=lowercase   )
															__lowercase					=				tf.convert_to_tensor(self.test_sentences   )
															__lowercase					=				model(lowercase   )  # Build model with some sample inputs
															with TemporaryDirectory() as tempdir:
																					__lowercase					=				Path(lowercase   ) / """saved.model"""
																					model.save(lowercase   )
																					__lowercase					=				tf.keras.models.load_model(lowercase   )
															__lowercase					=				loaded_model(lowercase   )
															# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
															self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output   )   )			,     1E-5   )










import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class 			_lowerCAmelCase   ( _UpperCAmelCase    ,					_UpperCAmelCase    ,					unittest.TestCase			):






			"""simple docstring"""





			lowercase__      :  int      =			IFImgaImgSuperResolutionPipeline
			lowercase__      :  Optional[int]      =			TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""width""", """height"""}
			lowercase__      :  Optional[int]      =			TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""original_image"""}			)
			lowercase__      :  Tuple      =			PipelineTesterMixin.required_optional_params - {"""latents"""}





			def 		snake_case__			(				self	:       Tuple   )						->					Any:
									"""simple docstring"""







									return self._get_superresolution_dummy_components()





			def 		snake_case__			(				self	:       List[str]			,     lowercase	:       Optional[int]			,     lowercase	:       Optional[Any]=0   )						->					Union[str, Any]:
									"""simple docstring"""







									if str(lowercase   ).startswith("""mps"""   ):
															__lowercase					=				torch.manual_seed(lowercase   )
									else:
															__lowercase					=				torch.Generator(device=lowercase   ).manual_seed(lowercase   )

									__lowercase					=				floats_tensor((1, 3, 32, 32)			,     rng=random.Random(lowercase   )   ).to(lowercase   )
									__lowercase					=				floats_tensor((1, 3, 16, 16)			,     rng=random.Random(lowercase   )   ).to(lowercase   )

									__lowercase					=				{
									    """prompt""": """A painting of a squirrel eating a burger""",
									    """image""": image,
									    """original_image""": original_image,
									    """generator""": generator,
									    """num_inference_steps""": 2,
									    """output_type""": """numpy""",
									}

									return inputs





			@unittest.skipIf(
			    torch_device != """cuda""" or not is_xformers_available()			,     reason="""XFormers attention is only available with CUDA and `xformers` installed"""			,     )
			def 		snake_case__			(				self	:       Optional[Any]   )						->					Tuple:
									"""simple docstring"""







									self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3   )





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







									self._test_save_load_optional_components()





			@unittest.skipIf(torch_device != """cuda"""			,     reason="""float16 requires CUDA"""   )
			def 		snake_case__			(				self	:       List[Any]   )						->					Dict:
									"""simple docstring"""







									super().test_save_load_floataa(expected_max_diff=1E-1   )





			def 		snake_case__			(				self	:       Dict   )						->					int:
									"""simple docstring"""







									self._test_attention_slicing_forward_pass(expected_max_diff=1E-2   )





			def 		snake_case__			(				self	:       Optional[Any]   )						->					int:
									"""simple docstring"""







									self._test_save_load_local()







			def 		snake_case__			(				self	:       Optional[int]   )						->					Optional[int]:
									"""simple docstring"""







									self._test_inference_batch_single_identical(
									    expected_max_diff=1E-2			,     )





