

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


_UpperCAmelCase						:  Any									=			"""hf-internal-testing/tiny-random-bert"""
_UpperCAmelCase						:  Union[str, Any]									=			os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
_UpperCAmelCase						:  List[str]									=			"""9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""







class 					lowercase							(			unittest.TestCase     ):




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

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

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




				def        a				(   self			):
											with self.assertRaisesRegex(snake_case ,  'is not a valid model identifier'			):
																		snake_case_     							=       cached_file('tiny-random-bert' ,  snake_case			)

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

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




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

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

											snake_case_     							=       cached_file(snake_case ,  'conf' ,  _raise_exceptions_for_missing_entries=snake_case			)
											self.assertIsNone(snake_case			)

											snake_case_     							=       cached_file(snake_case ,  'conf' ,  local_files_only=snake_case ,  _raise_exceptions_for_missing_entries=snake_case			)
											self.assertIsNone(snake_case			)

											snake_case_     							=       mock.Mock()
											snake_case_     							=       500
											snake_case_     							=       {}
											snake_case_     							=       HTTPError
											snake_case_     							=       {}

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




				def        a				(   self			):
											self.assertTrue(has_file('hf-internal-testing/tiny-bert-pt-only' ,  snake_case			)			)
											self.assertFalse(has_file('hf-internal-testing/tiny-bert-pt-only' ,  snake_case			)			)
											self.assertFalse(has_file('hf-internal-testing/tiny-bert-pt-only' ,  snake_case			)			)




				def        a				(   self			):
											# `get_file_from_repo` returns None if the file does not exist
											self.assertIsNone(get_file_from_repo('bert-base-cased' ,  'ahah.txt'			)			)

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

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

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




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

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







import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict

from ..features import ClassLabel, Features, Value
from .base import TaskTemplate







@dataclass(frozen=lowercase_     )
class 					lowercase							(			lowercase_     ):
				# `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization
				__SCREAMING_SNAKE_CASE   :					str			     =     field(default='''text-classification'''      ,    metadata={'''include_in_asdict_even_if_is_default''': True}     )
				__SCREAMING_SNAKE_CASE   :					ClassVar[Features]			     =     Features({'''text''': Value('''string'''     )}     )
				__SCREAMING_SNAKE_CASE   :					ClassVar[Features]			     =     Features({'''labels''': ClassLabel}     )
				__SCREAMING_SNAKE_CASE   :					str			     =     "text"
				__SCREAMING_SNAKE_CASE   :					str			     =     "labels"




				def        a				(   self ,  snake_case			):
											if self.label_column not in features:
																		raise ValueError(F'''Column {self.label_column} is not present in features.'''			)
											if not isinstance(features[self.label_column] ,  snake_case			):
																		raise ValueError(F'''Column {self.label_column} is not a ClassLabel.'''			)
											snake_case_     							=       copy.deepcopy(self			)
											snake_case_     							=       self.label_schema.copy()
											snake_case_     							=       features[self.label_column]
											snake_case_     							=       label_schema
											return task_template




				@property
				def        a				(   self			):
											return {
											    self.text_column: "text",
											    self.label_column: "labels",
											}




