
"""simple docstring"""




import random
import unittest

import torch

from diffusers import IFInpaintingPipeline
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_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin


@skip_mps
class 			__magic_name__       (       SCREAMING_SNAKE_CASE__   ,					SCREAMING_SNAKE_CASE__   ,					unittest.TestCase ):
       UpperCamelCase_   =		IFInpaintingPipeline
       UpperCamelCase_   =		TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''}
       UpperCamelCase_   =		TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
       UpperCamelCase_   =		PipelineTesterMixin.required_optional_params - {'''latents'''}
       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         return self._get_dummy_components()
       def 							lowercase_							(     self ,				A_ ,				A_=0       )     ->	int:





         """simple docstring"""




         if str(A_       ).startswith('''mps'''       ):
           _lowercase       =     torch.manual_seed(A_       )
         else:
           _lowercase       =     torch.Generator(device=A_       ).manual_seed(A_       )

         _lowercase       =     floats_tensor((1, 3, 32, 32) ,				rng=random.Random(A_       )       ).to(A_       )
         _lowercase       =     floats_tensor((1, 3, 32, 32) ,				rng=random.Random(A_       )       ).to(A_       )

         _lowercase       =     {
             '''prompt''': '''A painting of a squirrel eating a burger''',
             '''image''': image,
             '''mask_image''': mask_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 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3       )
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         self._test_save_load_optional_components()
       @unittest.skipIf(torch_device != '''cuda''' ,				reason='''float16 requires CUDA'''       )
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         super().test_save_load_floataa(expected_max_diff=1E-1       )
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         self._test_attention_slicing_forward_pass(expected_max_diff=1E-2       )
       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         self._test_save_load_local()



       def 							lowercase_							(     self       )     ->	Union[str, Any]:





         """simple docstring"""




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


"""simple docstring"""




import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


A__   :					Any							=   'hf-internal-testing/tiny-random-bert'
A__   :					int							=   os.path.join(TRANSFORMERS_CACHE, 'models--hf-internal-testing--tiny-random-bert')
A__   :					Dict							=   '9b8c223d42b2188cb49d29af482996f9d0f3e5a6'


class 			__magic_name__       (       unittest.TestCase ):
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         _lowercase:			Dict       =     cached_file(A_ ,				A_       )
         # Should have downloaded the file in here
         self.assertTrue(os.path.isdir(A_       )       )
         # Cache should contain at least those three subfolders:
         for subfolder in ["blobs", "refs", "snapshots"]:
           self.assertTrue(os.path.isdir(os.path.join(A_ ,				A_       )       )       )
         with open(os.path.join(A_ ,				'''refs''' ,				'''main'''       )       ) as f:
           _lowercase:			Tuple       =     f.read()
         self.assertEqual(A_ ,				os.path.join(A_ ,				'''snapshots''' ,				A_ ,				A_       )       )
         self.assertTrue(os.path.isfile(A_       )       )

         # File is cached at the same place the second time.
         _lowercase:			List[Any]       =     cached_file(A_ ,				A_       )
         self.assertEqual(A_ ,				A_       )

         # Using a specific revision to test the full commit hash.
         _lowercase:			Union[str, Any]       =     cached_file(A_ ,				A_ ,				revision='''9b8c223'''       )
         self.assertEqual(A_ ,				os.path.join(A_ ,				'''snapshots''' ,				A_ ,				A_       )       )
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         with self.assertRaisesRegex(A_ ,				'''is not a valid model identifier'''       ):
           _lowercase:			Union[str, Any]       =     cached_file('''tiny-random-bert''' ,				A_       )

         with self.assertRaisesRegex(A_ ,				'''is not a valid git identifier'''       ):
           _lowercase:			List[Any]       =     cached_file(A_ ,				A_ ,				revision='''aaaa'''       )

         with self.assertRaisesRegex(A_ ,				'''does not appear to have a file named'''       ):
           _lowercase:			int       =     cached_file(A_ ,				'''conf'''       )
       def 							lowercase_							(     self       )     ->	Optional[int]:





         """simple docstring"""




         with self.assertRaisesRegex(A_ ,				'''does not appear to have a file named'''       ):
           _lowercase:			Dict       =     cached_file(A_ ,				'''conf'''       )

         with open(os.path.join(A_ ,				'''refs''' ,				'''main'''       )       ) as f:
           _lowercase:			int       =     f.read()
         self.assertTrue(os.path.isfile(os.path.join(A_ ,				'''.no_exist''' ,				A_ ,				'''conf'''       )       )       )

         _lowercase:			Optional[int]       =     cached_file(A_ ,				'''conf''' ,				_raise_exceptions_for_missing_entries=A_       )
         self.assertIsNone(A_       )

         _lowercase:			Optional[int]       =     cached_file(A_ ,				'''conf''' ,				local_files_only=A_ ,				_raise_exceptions_for_missing_entries=A_       )
         self.assertIsNone(A_       )

         _lowercase:			Optional[Any]       =     mock.Mock()
         _lowercase:			Optional[Any]       =     500
         _lowercase:			Optional[Any]       =     {}
         _lowercase:			Dict       =     HTTPError
         _lowercase:			Optional[Any]       =     {}

         # Under the mock environment we get a 500 error when trying to reach the tokenizer.
         with mock.patch('''requests.Session.request''' ,				return_value=A_       ) as mock_head:
           _lowercase:			Tuple       =     cached_file(A_ ,				'''conf''' ,				_raise_exceptions_for_connection_errors=A_       )
           self.assertIsNone(A_       )
           # This check we did call the fake head request
           mock_head.assert_called()
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' ,				A_       )       )
         self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' ,				A_       )       )
         self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' ,				A_       )       )
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         self.assertIsNone(get_file_from_repo('''bert-base-cased''' ,				'''ahah.txt'''       )       )

         # The function raises if the repository does not exist.
         with self.assertRaisesRegex(A_ ,				'''is not a valid model identifier'''       ):
           get_file_from_repo('''bert-base-case''' ,				A_       )

         # The function raises if the revision does not exist.
         with self.assertRaisesRegex(A_ ,				'''is not a valid git identifier'''       ):
           get_file_from_repo('''bert-base-cased''' ,				A_ ,				revision='''ahaha'''       )

         _lowercase:			Optional[int]       =     get_file_from_repo('''bert-base-cased''' ,				A_       )
         # The name is the cached name which is not very easy to test, so instead we load the content.
         _lowercase:			Union[str, Any]       =     json.loads(open(A_ ,				'''r'''       ).read()       )
         self.assertEqual(config['''hidden_size'''] ,				768       )



       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         with tempfile.TemporaryDirectory() as tmp_dir:
           _lowercase:			List[Any]       =     Path(A_       ) / '''a.txt'''
           filename.touch()
           self.assertEqual(get_file_from_repo(A_ ,				'''a.txt'''       ) ,				str(A_       )       )

           self.assertIsNone(get_file_from_repo(A_ ,				'''b.txt'''       )       )
