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			:							List[Any]     ="hf-internal-testing/tiny-random-bert"
lowerCAmelCase			:							List[Any]     =os.path.join(TRANSFORMERS_CACHE, "models--hf-internal-testing--tiny-random-bert")
lowerCAmelCase			:							List[str]     ="9b8c223d42b2188cb49d29af482996f9d0f3e5a6"




class 	__snake_case	( unittest.TestCase		):





      '''simple docstring'''






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


          """simple docstring"""


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

          # File is cached at the same place the second time.
          _lowerCamelCase     :		Optional[int] 						=						cached_file(_UpperCamelCase    ,  _UpperCamelCase)
          self.assertEqual(_UpperCamelCase    ,  _UpperCamelCase)

          # Using a specific revision to test the full commit hash.
          _lowerCamelCase     :		str 						=						cached_file(_UpperCamelCase    ,  _UpperCamelCase    ,  revision="""9b8c223""")
          self.assertEqual(_UpperCamelCase    ,  os.path.join(_UpperCamelCase    ,  """snapshots"""    ,  _UpperCamelCase    ,  _UpperCamelCase))



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


          """simple docstring"""


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

          with self.assertRaisesRegex(_UpperCamelCase    ,  """is not a valid git identifier"""):
              _lowerCamelCase     :		List[str] 						=						cached_file(_UpperCamelCase    ,  _UpperCamelCase    ,  revision="""aaaa""")

          with self.assertRaisesRegex(_UpperCamelCase    ,  """does not appear to have a file named"""):
              _lowerCamelCase     :		int 						=						cached_file(_UpperCamelCase    ,  """conf""")



      def 	_SCREAMING_SNAKE_CASE    (					self     :				int)				->str:


          """simple docstring"""


          with self.assertRaisesRegex(_UpperCamelCase    ,  """does not appear to have a file named"""):
              _lowerCamelCase     :		List[str] 						=						cached_file(_UpperCamelCase    ,  """conf""")

          with open(os.path.join(_UpperCamelCase    ,  """refs"""    ,  """main""")) as f:
              _lowerCamelCase     :		Dict 						=						f.read()
          self.assertTrue(os.path.isfile(os.path.join(_UpperCamelCase    ,  """.no_exist"""    ,  _UpperCamelCase    ,  """conf""")))

          _lowerCamelCase     :		List[str] 						=						cached_file(_UpperCamelCase    ,  """conf"""    ,  _raise_exceptions_for_missing_entries=_UpperCamelCase)
          self.assertIsNone(_UpperCamelCase)

          _lowerCamelCase     :		str 						=						cached_file(_UpperCamelCase    ,  """conf"""    ,  local_files_only=_UpperCamelCase    ,  _raise_exceptions_for_missing_entries=_UpperCamelCase)
          self.assertIsNone(_UpperCamelCase)

          _lowerCamelCase     :		List[Any] 						=						mock.Mock()
          _lowerCamelCase     :		List[Any] 						=						500
          _lowerCamelCase     :		Any 						=						{}
          _lowerCamelCase     :		List[Any] 						=						HTTPError
          _lowerCamelCase     :		Any 						=						{}

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



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Tuple)				->Any:


          """simple docstring"""


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



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Dict)				->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(_UpperCamelCase    ,  """is not a valid model identifier"""):
              get_file_from_repo("""bert-base-case"""    ,  _UpperCamelCase)

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

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




      def 	_SCREAMING_SNAKE_CASE    (					self     :				str)				->List[str]:


          """simple docstring"""


          with tempfile.TemporaryDirectory() as tmp_dir:
              _lowerCamelCase     :		List[str] 						=						Path(_UpperCamelCase) / """a.txt"""
              filename.touch()
              self.assertEqual(get_file_from_repo(_UpperCamelCase    ,  """a.txt""")    ,  str(_UpperCamelCase))

              self.assertIsNone(get_file_from_repo(_UpperCamelCase    ,  """b.txt"""))





from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
    import PIL


lowerCAmelCase			:							Tuple     =logging.get_logger(__name__)




class 	__snake_case	( __lowerCAmelCase		):





      '''simple docstring'''






      _snake_case    		=       ['pixel_values']



      def __init__(					self     :				Optional[Any]    ,  _UpperCamelCase     :				bool = True    ,  _UpperCamelCase     :				Dict[str, int] = None    ,  _UpperCamelCase     :				PILImageResampling = PIL.Image.BICUBIC    ,  _UpperCamelCase     :				bool = True    ,  _UpperCamelCase     :				Dict[str, int] = None    ,  _UpperCamelCase     :				Union[int, float] = 1 / 255    ,  _UpperCamelCase     :				bool = True    ,  _UpperCamelCase     :				bool = True    ,  _UpperCamelCase     :				Optional[Union[float, List[float]]] = None    ,  _UpperCamelCase     :				Optional[Union[float, List[float]]] = None    ,  **_UpperCamelCase     :				str    ,  )				->None:


          """simple docstring"""


          super().__init__(**_UpperCamelCase)
          _lowerCamelCase     :		Tuple 						=						size if size is not None else {"""height""": 256, """width""": 256}
          _lowerCamelCase     :		Optional[Any] 						=						get_size_dict(_UpperCamelCase)
          _lowerCamelCase     :		Any 						=						crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
          _lowerCamelCase     :		Any 						=						get_size_dict(_UpperCamelCase    ,  param_name="""crop_size""")

          _lowerCamelCase     :		int 						=						do_resize
          _lowerCamelCase     :		int 						=						size
          _lowerCamelCase     :		Optional[int] 						=						resample
          _lowerCamelCase     :		int 						=						do_center_crop
          _lowerCamelCase     :		Optional[Any] 						=						crop_size
          _lowerCamelCase     :		Union[str, Any] 						=						do_rescale
          _lowerCamelCase     :		List[str] 						=						rescale_factor
          _lowerCamelCase     :		List[Any] 						=						do_normalize
          _lowerCamelCase     :		Dict 						=						image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
          _lowerCamelCase     :		int 						=						image_std if image_std is not None else IMAGENET_STANDARD_STD



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Any    ,  _UpperCamelCase     :				np.ndarray    ,  _UpperCamelCase     :				Dict[str, int]    ,  _UpperCamelCase     :				PILImageResampling = PIL.Image.BICUBIC    ,  _UpperCamelCase     :				Optional[Union[str, ChannelDimension]] = None    ,  **_UpperCamelCase     :				Union[str, Any]    ,  )				->np.ndarray:


          """simple docstring"""


          _lowerCamelCase     :		Dict 						=						get_size_dict(_UpperCamelCase)
          if "height" not in size or "width" not in size:
              raise ValueError(F"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}""")
          return resize(
              _UpperCamelCase    ,  size=(size["""height"""], size["""width"""])    ,  resample=_UpperCamelCase    ,  data_format=_UpperCamelCase    ,  **_UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				List[str]    ,  _UpperCamelCase     :				np.ndarray    ,  _UpperCamelCase     :				Dict[str, int]    ,  _UpperCamelCase     :				Optional[Union[str, ChannelDimension]] = None    ,  **_UpperCamelCase     :				List[str]    ,  )				->np.ndarray:


          """simple docstring"""


          _lowerCamelCase     :		Union[str, Any] 						=						get_size_dict(_UpperCamelCase)
          if "height" not in size or "width" not in size:
              raise ValueError(F"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}""")
          return center_crop(_UpperCamelCase    ,  size=(size["""height"""], size["""width"""])    ,  data_format=_UpperCamelCase    ,  **_UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Union[str, Any]    ,  _UpperCamelCase     :				np.ndarray    ,  _UpperCamelCase     :				Union[int, float]    ,  _UpperCamelCase     :				Optional[Union[str, ChannelDimension]] = None    ,  **_UpperCamelCase     :				Union[str, Any]    ,  )				->str:


          """simple docstring"""


          return rescale(_UpperCamelCase    ,  scale=_UpperCamelCase    ,  data_format=_UpperCamelCase    ,  **_UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				List[Any]    ,  _UpperCamelCase     :				np.ndarray    ,  _UpperCamelCase     :				Union[float, List[float]]    ,  _UpperCamelCase     :				Union[float, List[float]]    ,  _UpperCamelCase     :				Optional[Union[str, ChannelDimension]] = None    ,  **_UpperCamelCase     :				Union[str, Any]    ,  )				->np.ndarray:


          """simple docstring"""


          return normalize(_UpperCamelCase    ,  mean=_UpperCamelCase    ,  std=_UpperCamelCase    ,  data_format=_UpperCamelCase    ,  **_UpperCamelCase)




      def 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[Any]    ,  _UpperCamelCase     :				ImageInput    ,  _UpperCamelCase     :				bool = None    ,  _UpperCamelCase     :				Dict[str, int] = None    ,  _UpperCamelCase     :				Tuple=None    ,  _UpperCamelCase     :				bool = None    ,  _UpperCamelCase     :				Dict[str, int] = None    ,  _UpperCamelCase     :				bool = None    ,  _UpperCamelCase     :				float = None    ,  _UpperCamelCase     :				bool = None    ,  _UpperCamelCase     :				Optional[Union[float, List[float]]] = None    ,  _UpperCamelCase     :				Optional[Union[float, List[float]]] = None    ,  _UpperCamelCase     :				Optional[Union[str, TensorType]] = None    ,  _UpperCamelCase     :				ChannelDimension = ChannelDimension.FIRST    ,  **_UpperCamelCase     :				List[Any]    ,  )				->PIL.Image.Image:


          """simple docstring"""


          _lowerCamelCase     :		Any 						=						do_resize if do_resize is not None else self.do_resize
          _lowerCamelCase     :		List[str] 						=						resample if resample is not None else self.resample
          _lowerCamelCase     :		Dict 						=						do_center_crop if do_center_crop is not None else self.do_center_crop
          _lowerCamelCase     :		Optional[Any] 						=						do_rescale if do_rescale is not None else self.do_rescale
          _lowerCamelCase     :		Dict 						=						rescale_factor if rescale_factor is not None else self.rescale_factor
          _lowerCamelCase     :		Dict 						=						do_normalize if do_normalize is not None else self.do_normalize
          _lowerCamelCase     :		int 						=						image_mean if image_mean is not None else self.image_mean
          _lowerCamelCase     :		Dict 						=						image_std if image_std is not None else self.image_std

          _lowerCamelCase     :		Optional[Any] 						=						size if size is not None else self.size
          _lowerCamelCase     :		Optional[int] 						=						get_size_dict(_UpperCamelCase)
          _lowerCamelCase     :		List[str] 						=						crop_size if crop_size is not None else self.crop_size
          _lowerCamelCase     :		Dict 						=						get_size_dict(_UpperCamelCase    ,  param_name="""crop_size""")

          _lowerCamelCase     :		int 						=						make_list_of_images(_UpperCamelCase)

          if not valid_images(_UpperCamelCase):
              raise ValueError(
                  """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
                  """torch.Tensor, tf.Tensor or jax.ndarray.""")

          if do_resize and size is None or resample is None:
              raise ValueError("""Size and resample must be specified if do_resize is True.""")

          if do_center_crop and crop_size is None:
              raise ValueError("""Crop size must be specified if do_center_crop is True.""")

          if do_rescale and rescale_factor is None:
              raise ValueError("""Rescale factor must be specified if do_rescale is True.""")

          if do_normalize and (image_mean is None or image_std is None):
              raise ValueError("""Image mean and std must be specified if do_normalize is True.""")

          # All transformations expect numpy arrays.
          _lowerCamelCase     :		Union[str, Any] 						=						[to_numpy_array(_UpperCamelCase) for image in images]

          if do_resize:
              _lowerCamelCase     :		Any 						=						[self.resize(image=_UpperCamelCase    ,  size=_UpperCamelCase    ,  resample=_UpperCamelCase) for image in images]

          if do_center_crop:
              _lowerCamelCase     :		str 						=						[self.center_crop(image=_UpperCamelCase    ,  size=_UpperCamelCase) for image in images]

          if do_rescale:
              _lowerCamelCase     :		Optional[int] 						=						[self.rescale(image=_UpperCamelCase    ,  scale=_UpperCamelCase) for image in images]

          if do_normalize:
              _lowerCamelCase     :		List[str] 						=						[self.normalize(image=_UpperCamelCase    ,  mean=_UpperCamelCase    ,  std=_UpperCamelCase) for image in images]

          _lowerCamelCase     :		List[str] 						=						[to_channel_dimension_format(_UpperCamelCase    ,  _UpperCamelCase) for image in images]

          _lowerCamelCase     :		int 						=						{"""pixel_values""": images}
          return BatchFeature(data=_UpperCamelCase    ,  tensor_type=_UpperCamelCase)




