





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,
)


lowerCAmelCase_    =				'''hf-internal-testing/tiny-random-bert'''
lowerCAmelCase_    =				os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''')
lowerCAmelCase_    =				'''9b8c223d42b2188cb49d29af482996f9d0f3e5a6'''



class 					__lowerCAmelCase       (			unittest.TestCase     ):






			def 			lowerCamelCase  (self    )     ->   Tuple:


							'''simple docstring'''



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

							# File is cached at the same place the second time.
							snake_case_						:    str				=  cached_file(__magic_name__					,							__magic_name__    )
							self.assertEqual(__magic_name__					,							__magic_name__    )

							# Using a specific revision to test the full commit hash.
							snake_case_						:    Tuple				=  cached_file(__magic_name__					,							__magic_name__					,							revision='''9b8c223'''    )
							self.assertEqual(__magic_name__					,							os.path.join(__magic_name__					,							'''snapshots'''					,							__magic_name__					,							__magic_name__    )    )






			def 			lowerCamelCase  (self    )     ->   str:


							'''simple docstring'''



							with self.assertRaisesRegex(__magic_name__					,							'''is not a valid model identifier'''    ):
											snake_case_						:    List[str]				=  cached_file('''tiny-random-bert'''					,							__magic_name__    )

							with self.assertRaisesRegex(__magic_name__					,							'''is not a valid git identifier'''    ):
											snake_case_						:    Tuple				=  cached_file(__magic_name__					,							__magic_name__					,							revision='''aaaa'''    )

							with self.assertRaisesRegex(__magic_name__					,							'''does not appear to have a file named'''    ):
											snake_case_						:    str				=  cached_file(__magic_name__					,							'''conf'''    )






			def 			lowerCamelCase  (self    )     ->   Dict:


							'''simple docstring'''



							with self.assertRaisesRegex(__magic_name__					,							'''does not appear to have a file named'''    ):
											snake_case_						:    List[Any]				=  cached_file(__magic_name__					,							'''conf'''    )

							with open(os.path.join(__magic_name__					,							'''refs'''					,							'''main'''    )    ) as f:
											snake_case_						:    Optional[Any]				=  f.read()
							self.assertTrue(os.path.isfile(os.path.join(__magic_name__					,							'''.no_exist'''					,							__magic_name__					,							'''conf'''    )    )    )

							snake_case_						:    List[Any]				=  cached_file(__magic_name__					,							'''conf'''					,							_raise_exceptions_for_missing_entries=__magic_name__    )
							self.assertIsNone(__magic_name__    )

							snake_case_						:    str				=  cached_file(__magic_name__					,							'''conf'''					,							local_files_only=__magic_name__					,							_raise_exceptions_for_missing_entries=__magic_name__    )
							self.assertIsNone(__magic_name__    )

							snake_case_						:    Optional[Any]				=  mock.Mock()
							snake_case_						:    List[str]				=  500
							snake_case_						:    List[Any]				=  {}
							snake_case_						:    int				=  HTTPError
							snake_case_						:    Dict				=  {}

							# Under the mock environment we get a 500 error when trying to reach the tokenizer.
							with mock.patch('''requests.Session.request'''					,							return_value=__magic_name__    ) as mock_head:
											snake_case_						:    List[Any]				=  cached_file(__magic_name__					,							'''conf'''					,							_raise_exceptions_for_connection_errors=__magic_name__    )
											self.assertIsNone(__magic_name__    )
											# This check we did call the fake head request
											mock_head.assert_called()






			def 			lowerCamelCase  (self    )     ->   int:


							'''simple docstring'''



							self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only'''					,							__magic_name__    )    )
							self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only'''					,							__magic_name__    )    )
							self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only'''					,							__magic_name__    )    )






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


							'''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(__magic_name__					,							'''is not a valid model identifier'''    ):
											get_file_from_repo('''bert-base-case'''					,							__magic_name__    )

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

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






			def 			lowerCamelCase  (self    )     ->   Optional[Any]:


							'''simple docstring'''



							with tempfile.TemporaryDirectory() as tmp_dir:
											snake_case_						:    Any				=  Path(__magic_name__    ) / '''a.txt'''
											filename.touch()
											self.assertEqual(get_file_from_repo(__magic_name__					,							'''a.txt'''    )					,							str(__magic_name__    )    )

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







import PIL.Image
import PIL.ImageOps
from packaging import version
from PIL import Image


if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''):
	lowerCAmelCase_    =				{
	    '''linear''': PIL.Image.Resampling.BILINEAR,
	    '''bilinear''': PIL.Image.Resampling.BILINEAR,
	    '''bicubic''': PIL.Image.Resampling.BICUBIC,
	    '''lanczos''': PIL.Image.Resampling.LANCZOS,
	    '''nearest''': PIL.Image.Resampling.NEAREST,
	}
else:
	lowerCAmelCase_    =				{
	    '''linear''': PIL.Image.LINEAR,
	    '''bilinear''': PIL.Image.BILINEAR,
	    '''bicubic''': PIL.Image.BICUBIC,
	    '''lanczos''': PIL.Image.LANCZOS,
	    '''nearest''': PIL.Image.NEAREST,
	}






def      lowerCamelCase_						(				_UpperCamelCase )		->						Optional[int]:






				"""simple docstring"""


				snake_case_						:    Dict				=  (images / 2 + 0.5).clamp(0 ,				1 )
				snake_case_						:    Dict				=  images.cpu().permute(0 ,				2 ,				3 ,				1 ).float().numpy()
				snake_case_						:    int				=  numpy_to_pil(_UpperCamelCase )
				return images






def      lowerCamelCase_						(				_UpperCamelCase )		->						List[Any]:






				"""simple docstring"""


				if images.ndim == 3:
								snake_case_						:    Optional[Any]				=  images[None, ...]
				snake_case_						:    Any				=  (images * 255).round().astype('''uint8''' )
				if images.shape[-1] == 1:
								# special case for grayscale (single channel) images
								snake_case_						:    str				=  [Image.fromarray(image.squeeze() ,				mode='''L''' ) for image in images]
				else:
								snake_case_						:    List[Any]				=  [Image.fromarray(_UpperCamelCase ) for image in images]

				return pil_images
