


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


_lowerCAmelCase     :							Dict    =				"hf-internal-testing/tiny-random-bert"
_lowerCAmelCase     :							str    =				os.path.join(TRANSFORMERS_CACHE, "models--hf-internal-testing--tiny-random-bert")
_lowerCAmelCase     :							Dict    =				"9b8c223d42b2188cb49d29af482996f9d0f3e5a6"

class 		snake_case				(    unittest.TestCase						):

				"""simple docstring"""




				def    lowercase__							(	self )    ->      List[Any]:







					"""simple docstring"""






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

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

					# Using a specific revision to test the full commit hash.
					snake_case__			:			Optional[Any]             =		cached_file(lowerCamelCase       ,    lowerCamelCase       ,    revision='''9b8c223''' )
					self.assertEqual(lowerCamelCase       ,    os.path.join(lowerCamelCase       ,    '''snapshots'''       ,    lowerCamelCase       ,    lowerCamelCase ) )





				def    lowercase__							(	self )    ->      Dict:







					"""simple docstring"""






					with self.assertRaisesRegex(lowerCamelCase       ,    '''is not a valid model identifier''' ):
						snake_case__			:			str             =		cached_file('''tiny-random-bert'''       ,    lowerCamelCase )

					with self.assertRaisesRegex(lowerCamelCase       ,    '''is not a valid git identifier''' ):
						snake_case__			:			str             =		cached_file(lowerCamelCase       ,    lowerCamelCase       ,    revision='''aaaa''' )

					with self.assertRaisesRegex(lowerCamelCase       ,    '''does not appear to have a file named''' ):
						snake_case__			:			Union[str, Any]             =		cached_file(lowerCamelCase       ,    '''conf''' )





				def    lowercase__							(	self )    ->      int:







					"""simple docstring"""






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

					with open(os.path.join(lowerCamelCase       ,    '''refs'''       ,    '''main''' ) ) as f:
						snake_case__			:			Any             =		f.read()
					self.assertTrue(os.path.isfile(os.path.join(lowerCamelCase       ,    '''.no_exist'''       ,    lowerCamelCase       ,    '''conf''' ) ) )

					snake_case__			:			int             =		cached_file(lowerCamelCase       ,    '''conf'''       ,    _raise_exceptions_for_missing_entries=lowerCamelCase )
					self.assertIsNone(lowerCamelCase )

					snake_case__			:			str             =		cached_file(lowerCamelCase       ,    '''conf'''       ,    local_files_only=lowerCamelCase       ,    _raise_exceptions_for_missing_entries=lowerCamelCase )
					self.assertIsNone(lowerCamelCase )

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

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





				def    lowercase__							(	self )    ->      int:







					"""simple docstring"""






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





				def    lowercase__							(	self )    ->      str:







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

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

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





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







					"""simple docstring"""






					with tempfile.TemporaryDirectory() as tmp_dir:
						snake_case__			:			Optional[int]             =		Path(lowerCamelCase ) / '''a.txt'''
						filename.touch()
						self.assertEqual(get_file_from_repo(lowerCamelCase       ,    '''a.txt''' )       ,    str(lowerCamelCase ) )

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










'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


lowercase_									=    {
    "configuration_blip": [
        "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "BlipConfig",
        "BlipTextConfig",
        "BlipVisionConfig",
    ],
    "processing_blip": ["BlipProcessor"],
}

try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_									=    ["BlipImageProcessor"]


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_									=    [
      "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
      "BlipModel",
      "BlipPreTrainedModel",
      "BlipForConditionalGeneration",
      "BlipForQuestionAnswering",
      "BlipVisionModel",
      "BlipTextModel",
      "BlipForImageTextRetrieval",
  ]

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowercase_									=    [
      "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
      "TFBlipModel",
      "TFBlipPreTrainedModel",
      "TFBlipForConditionalGeneration",
      "TFBlipForQuestionAnswering",
      "TFBlipVisionModel",
      "TFBlipTextModel",
      "TFBlipForImageTextRetrieval",
  ]

if TYPE_CHECKING:
  from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig
  from .processing_blip import BlipProcessor

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .image_processing_blip import BlipImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_blip import (
        BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
        BlipForConditionalGeneration,
        BlipForImageTextRetrieval,
        BlipForQuestionAnswering,
        BlipModel,
        BlipPreTrainedModel,
        BlipTextModel,
        BlipVisionModel,
    )

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_blip import (
        TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFBlipForConditionalGeneration,
        TFBlipForImageTextRetrieval,
        TFBlipForQuestionAnswering,
        TFBlipModel,
        TFBlipPreTrainedModel,
        TFBlipTextModel,
        TFBlipVisionModel,
    )

else:
  import sys

  lowercase_									=    _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



