



"""simple docstring"""







import gc
import unittest

import numpy as np
import torch

from diffusers import RePaintPipeline, RePaintScheduler, UNetaDModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_image,
    load_numpy,
    nightly,
    require_torch_gpu,
    skip_mps,
    torch_device,
)

from ..pipeline_params import IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()





class    UpperCamelCase     (			snake_case ,					unittest.TestCase    ):




	"""simple docstring"""
	SCREAMING_SNAKE_CASE_				:    Union[str, Any]		    =   RePaintPipeline
	SCREAMING_SNAKE_CASE_				:    Tuple		    =   IMAGE_INPAINTING_PARAMS - {"width", "height", "guidance_scale"}
	SCREAMING_SNAKE_CASE_				:    List[Any]		    =   PipelineTesterMixin.required_optional_params - {
	    "latents",
	    "num_images_per_prompt",
	    "callback",
	    "callback_steps",
	}
	SCREAMING_SNAKE_CASE_				:    Optional[Any]		    =   IMAGE_INPAINTING_BATCH_PARAMS
	SCREAMING_SNAKE_CASE_				:    List[Any]		    =   False






	def 					lowerCamelCase__ (			self					):
			torch.manual_seed(0					)
			torch.manual_seed(0					)
			_lowercase							:      Optional[Any]			=					UNetaDModel(
			    block_out_channels=(32, 64)							,layers_per_block=2							,sample_size=32							,in_channels=3							,out_channels=3							,down_block_types=("""DownBlock2D""", """AttnDownBlock2D""")							,up_block_types=("""AttnUpBlock2D""", """UpBlock2D""")							,)
			_lowercase							:      str			=					RePaintScheduler()
			_lowercase							:      str			=					{"""unet""": unet, """scheduler""": scheduler}
			return components






	def 					lowerCamelCase__ (			self							,UpperCAmelCase_							,UpperCAmelCase_=0					):
			if str(UpperCAmelCase_					).startswith("""mps"""					):
					_lowercase							:      Tuple			=					torch.manual_seed(UpperCAmelCase_					)
			else:
					_lowercase							:      Optional[Any]			=					torch.Generator(device=UpperCAmelCase_					).manual_seed(UpperCAmelCase_					)
			_lowercase							:      str			=					np.random.RandomState(UpperCAmelCase_					).standard_normal((1, 3, 32, 32)					)
			_lowercase							:      Optional[Any]			=					torch.from_numpy(UpperCAmelCase_					).to(device=UpperCAmelCase_							,dtype=torch.floataa					)
			_lowercase							:      List[str]			=					(image > 0).to(device=UpperCAmelCase_							,dtype=torch.floataa					)
			_lowercase							:      Union[str, Any]			=					{
			    """image""": image,
			    """mask_image""": mask,
			    """generator""": generator,
			    """num_inference_steps""": 5,
			    """eta""": 0.0,
			    """jump_length""": 2,
			    """jump_n_sample""": 2,
			    """output_type""": """numpy""",
			}
			return inputs






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      int			=					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
			_lowercase							:      Any			=					self.get_dummy_components()
			_lowercase							:      Dict			=					RePaintPipeline(**UpperCAmelCase_					)
			_lowercase							:      List[Any]			=					sd_pipe.to(UpperCAmelCase_					)
			sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_					)

			_lowercase							:      str			=					self.get_dummy_inputs(UpperCAmelCase_					)
			_lowercase							:      int			=					sd_pipe(**UpperCAmelCase_					).images
			_lowercase							:      Tuple			=					image[0, -3:, -3:, -1]

			assert image.shape == (1, 32, 32, 3)
			_lowercase							:      Dict			=					np.array([1.0000, 0.5426, 0.5497, 0.2200, 1.0000, 1.0000, 0.5623, 1.0000, 0.6274]					)

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






	@skip_mps
	def 					lowerCamelCase__ (			self					):
			return super().test_save_load_local()






	@unittest.skip("""non-deterministic pipeline"""					)
	def 					lowerCamelCase__ (			self					):
			return super().test_inference_batch_single_identical()






	@skip_mps
	def 					lowerCamelCase__ (			self					):
			return super().test_dict_tuple_outputs_equivalent()






	@skip_mps
	def 					lowerCamelCase__ (			self					):
			return super().test_save_load_optional_components()






	@skip_mps
	def 					lowerCamelCase__ (			self					):
			return super().test_attention_slicing_forward_pass()







@nightly
@require_torch_gpu
class    UpperCamelCase     (			unittest.TestCase    ):




	"""simple docstring"""






	def 					lowerCamelCase__ (			self					):
			super().tearDown()
			gc.collect()
			torch.cuda.empty_cache()






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      str			=					load_image(
			    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/"""
			    """repaint/celeba_hq_256.png"""					)
			_lowercase							:      List[str]			=					load_image(
			    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/mask_256.png"""					)
			_lowercase							:      Tuple			=					load_numpy(
			    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/"""
			    """repaint/celeba_hq_256_result.npy"""					)

			_lowercase							:      Dict			=					"""google/ddpm-ema-celebahq-256"""
			_lowercase							:      Tuple			=					UNetaDModel.from_pretrained(UpperCAmelCase_					)
			_lowercase							:      Optional[Any]			=					RePaintScheduler.from_pretrained(UpperCAmelCase_					)

			_lowercase							:      Dict			=					RePaintPipeline(unet=UpperCAmelCase_							,scheduler=UpperCAmelCase_					).to(UpperCAmelCase_					)
			repaint.set_progress_bar_config(disable=UpperCAmelCase_					)
			repaint.enable_attention_slicing()

			_lowercase							:      str			=					torch.manual_seed(0					)
			_lowercase							:      Any			=					repaint(
			    UpperCAmelCase_							,UpperCAmelCase_							,num_inference_steps=2_50							,eta=0.0							,jump_length=10							,jump_n_sample=10							,generator=UpperCAmelCase_							,output_type="""np"""							,)
			_lowercase							:      Any			=					output.images[0]

			assert image.shape == (2_56, 2_56, 3)
			assert np.abs(expected_image - image					).mean() < 1E-2








"""simple docstring"""







import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class    UpperCamelCase     (			snake_case ,					unittest.TestCase    ):




	"""simple docstring"""
	SCREAMING_SNAKE_CASE_				:    str		    =   PreTrainedTokenizerFast
	SCREAMING_SNAKE_CASE_				:    Optional[Any]		    =   False
	SCREAMING_SNAKE_CASE_				:    Optional[int]		    =   True
	SCREAMING_SNAKE_CASE_				:    int		    =   "tokenizer_file"






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      Optional[int]			=					False  # because we don't have pretrained_vocab_files_map
			super().setUp()
			_lowercase							:      Tuple			=					True

			_lowercase							:      Optional[Any]			=					["""robot-test/dummy-tokenizer-fast""", """robot-test/dummy-tokenizer-wordlevel"""]
			_lowercase							:      Dict			=					"""SaulLu/dummy-tokenizer-bytelevel-bpe"""

			# Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
			_lowercase							:      Dict			=					[(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

			_lowercase							:      Any			=					PreTrainedTokenizerFast.from_pretrained(model_paths[0]					)
			tokenizer.save_pretrained(self.tmpdirname					)






	def 					lowerCamelCase__ (			self					):
			# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
			# model
			pass






	def 					lowerCamelCase__ (			self					):
			# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
			# model
			pass






	def 					lowerCamelCase__ (			self					):
			# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
			# model
			pass






	def 					lowerCamelCase__ (			self					):
			# PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
			pass






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      List[str]			=					self.tmpdirname
			# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
			for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
					with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""					):
							try:
									_lowercase							:      Optional[Any]			=					tempfile.mkdtemp()
									_lowercase							:      Any			=					self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_							,**UpperCAmelCase_					)

									tokenizer.save_pretrained(self.tmpdirname					)
									super().test_training_new_tokenizer()
							finally:
									# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
									# is restored
									shutil.rmtree(self.tmpdirname					)
									_lowercase							:      List[Any]			=					tmpdirname_orig






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      List[str]			=					self.tmpdirname
			# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
			for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
					with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""					):
							try:
									_lowercase							:      Optional[int]			=					tempfile.mkdtemp()
									_lowercase							:      Tuple			=					self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_							,**UpperCAmelCase_					)

									tokenizer.save_pretrained(self.tmpdirname					)
									super().test_training_new_tokenizer_with_special_tokens_change()
							finally:
									# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
									# is restored
									shutil.rmtree(self.tmpdirname					)
									_lowercase							:      Optional[int]			=					tmpdirname_orig






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      List[Any]			=					self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name					)

			_lowercase							:      List[str]			=					("""a""" for _ in range(10_00					))
			_lowercase							:      Dict			=					tokenizer.train_new_from_iterator(text_iterator=UpperCAmelCase_							,length=10_00							,vocab_size=50					)

			_lowercase							:      List[str]			=					new_tokenizer.encode("""a🤗"""					)
			self.assertEqual(UpperCAmelCase_							,[64, 1_72, 2_53, 97, 2_45]					)







@require_tokenizers
class    UpperCamelCase     (			unittest.TestCase    ):




	"""simple docstring"""






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      List[Any]			=					AutoTokenizer.from_pretrained("""bert-base-cased"""					)
			_lowercase							:      Optional[Any]			=					json.loads(tokenizer._tokenizer.to_str()					)
			_lowercase							:      Dict			=					len(UpperCAmelCase_					)

			with tempfile.TemporaryDirectory() as tmp_dir:
					# Hack to save this in the tokenizer_config.json
					_lowercase							:      str			=					["""tokenizer.4.0.0.json"""]
					tokenizer.save_pretrained(UpperCAmelCase_					)
					json.dump(UpperCAmelCase_							,open(os.path.join(UpperCAmelCase_							,"""tokenizer.4.0.0.json"""					)							,"""w"""					)					)

					# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
					_lowercase							:      int			=					AutoTokenizer.from_pretrained(UpperCAmelCase_					)
					self.assertEqual(len(UpperCAmelCase_					)							,len(UpperCAmelCase_					) + 1					)
					_lowercase							:      List[str]			=					json.loads(new_tokenizer._tokenizer.to_str()					)
					self.assertIn("""huggingface"""							,json_tokenizer["""model"""]["""vocab"""]					)

					# Will need to be adjusted if we reach v42 and this test is still here.
					# Should pick the old tokenizer file as the version of Transformers is < 4.0.0
					shutil.move(os.path.join(UpperCAmelCase_							,"""tokenizer.4.0.0.json"""					)							,os.path.join(UpperCAmelCase_							,"""tokenizer.42.0.0.json"""					)					)
					_lowercase							:      Optional[int]			=					["""tokenizer.42.0.0.json"""]
					tokenizer.save_pretrained(UpperCAmelCase_					)
					_lowercase							:      List[Any]			=					AutoTokenizer.from_pretrained(UpperCAmelCase_					)
					self.assertEqual(len(UpperCAmelCase_					)							,len(UpperCAmelCase_					)					)
					_lowercase							:      List[Any]			=					json.loads(new_tokenizer._tokenizer.to_str()					)
					self.assertNotIn("""huggingface"""							,json_tokenizer["""model"""]["""vocab"""]					)






	def 					lowerCamelCase__ (			self					):
			# This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
			_lowercase							:      Tuple			=					"""hf-internal-testing/test-two-tokenizers"""

			# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
			_lowercase							:      List[Any]			=					AutoTokenizer.from_pretrained(UpperCAmelCase_					)
			self.assertEqual(len(UpperCAmelCase_					)							,2_89_97					)
			_lowercase							:      List[Any]			=					json.loads(tokenizer._tokenizer.to_str()					)
			self.assertIn("""huggingface"""							,json_tokenizer["""model"""]["""vocab"""]					)

			# Testing an older version by monkey-patching the version in the module it's used.
			import transformers as old_transformers

			_lowercase							:      Optional[Any]			=					"""3.0.0"""
			_lowercase							:      int			=					old_transformers.models.auto.AutoTokenizer.from_pretrained(UpperCAmelCase_					)
			self.assertEqual(len(UpperCAmelCase_					)							,2_89_96					)
			_lowercase							:      str			=					json.loads(old_tokenizer._tokenizer.to_str()					)
			self.assertNotIn("""huggingface"""							,json_tokenizer["""model"""]["""vocab"""]					)







@require_tokenizers
class    UpperCamelCase     (			unittest.TestCase    ):




	"""simple docstring"""






	def 					lowerCamelCase__ (			self					):
			# See https://github.com/huggingface/transformers/pull/12550
			# and https://github.com/huggingface/tokenizers/issues/537
			_lowercase							:      Optional[int]			=					PreTrainedTokenizerFast.from_pretrained("""robot-test/dummy-tokenizer-wordlevel"""					)
			_lowercase							:      List[str]			=					"""The Matrix is a 1999 science fiction action film."""

			with concurrent.futures.ThreadPoolExecutor() as executor:
					_lowercase							:      Tuple			=					[executor.submit(self.fetch							,UpperCAmelCase_							,UpperCAmelCase_					) for i in range(10					)]
					_lowercase							:      str			=					[future.result() for future in futures]
					self.assertEqual(UpperCAmelCase_							,[[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10					)]					)






	def 					lowerCamelCase__ (			self							,UpperCAmelCase_							,UpperCAmelCase_					):
			return tokenizer.encode(UpperCAmelCase_							,truncation="""longest_first"""							,padding="""longest"""					)



