




import logging
import os
import threading
import time


try:
	import warnings
except ImportError:
	a__		     =     None

try:
	import msvcrt
except ImportError:
	a__		     =     None

try:
	import fcntl
except ImportError:
	a__		     =     None


# Backward compatibility
# ------------------------------------------------
try:
	TimeoutError
except NameError:
	a__		     =     OSError


# Data
# ------------------------------------------------
a__		     =     [
    '''Timeout''',
    '''BaseFileLock''',
    '''WindowsFileLock''',
    '''UnixFileLock''',
    '''SoftFileLock''',
    '''FileLock''',
]

a__		     =     '''3.0.12'''


a__		     =     None





def 				A__ ()     ->						int:
					global _logger
					__UpperCamelCase					:	List[Any]             =      _logger or logging.getLogger(__name__				)
					return _logger


class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



	"""simple docstring"""


	def __init__(					self		:						str					,     lowerCAmelCase		:						List[str]	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	List[str]             =      lock_file
						return None






	def __str__(					self		:						int	)	->       Optional[Any]:







						"""simple docstring"""







						__UpperCamelCase					:	Dict             =      F'''The file lock \'{self.lock_file}\' could not be acquired.'''
						return temp






class    SCREAMING_SNAKE_CASE_				:



	"""simple docstring"""


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







						"""simple docstring"""







						__UpperCamelCase					:	Optional[Any]             =      lock
						return None






	def __enter__(					self		:						List[str]	)	->       Tuple:







						"""simple docstring"""







						return self.lock






	def __exit__(					self		:						int					,     lowerCAmelCase		:						Optional[Any]					,     lowerCAmelCase		:						List[str]					,     lowerCAmelCase		:						Optional[int]	)	->       Tuple:







						"""simple docstring"""







						self.lock.release()
						return None






class    SCREAMING_SNAKE_CASE_				:



	"""simple docstring"""


	def __init__(					self		:						List[Any]					,     lowerCAmelCase		:						Union[str, Any]					,     lowerCAmelCase		:						List[Any]=-1					,     lowerCAmelCase		:						Tuple=None	)	->       Optional[int]:







						"""simple docstring"""







						__UpperCamelCase					:	str             =      max_filename_length if max_filename_length is not None else 255
						# Hash the filename if it's too long
						__UpperCamelCase					:	str             =      self.hash_filename_if_too_long(lowerCAmelCase					,     lowerCAmelCase	)
						# The path to the lock file.
						__UpperCamelCase					:	Union[str, Any]             =      lock_file

						# The file descriptor for the *_lock_file* as it is returned by the
						# os.open() function.
						# This file lock is only NOT None, if the object currently holds the
						# lock.
						__UpperCamelCase					:	Tuple             =      None

						# The default timeout value.
						__UpperCamelCase					:	Union[str, Any]             =      timeout

						# We use this lock primarily for the lock counter.
						__UpperCamelCase					:	List[Any]             =      threading.Lock()

						# The lock counter is used for implementing the nested locking
						# mechanism. Whenever the lock is acquired, the counter is increased and
						# the lock is only released, when this value is 0 again.
						__UpperCamelCase					:	Dict             =      0
						return None






	@property
	def 					lowerCamelCase__     (					self		:						str	)	->       int:







						"""simple docstring"""







						return self._lock_file






	@property
	def 					lowerCamelCase__     (					self		:						Dict	)	->       Union[str, Any]:







						"""simple docstring"""







						return self._timeout






	@timeout.setter
	def 					lowerCamelCase__     (					self		:						Union[str, Any]					,     lowerCAmelCase		:						List[Any]	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	Tuple             =      float(lowerCAmelCase	)
						return None






	def 					lowerCamelCase__     (					self		:						Tuple	)	->       List[str]:







						"""simple docstring"""







						raise NotImplementedError()






	def 					lowerCamelCase__     (					self		:						List[Any]	)	->       List[str]:







						"""simple docstring"""







						raise NotImplementedError()






	@property
	def 					lowerCamelCase__     (					self		:						str	)	->       Optional[int]:







						"""simple docstring"""







						return self._lock_file_fd is not None






	def 					lowerCamelCase__     (					self		:						Optional[int]					,     lowerCAmelCase		:						Optional[int]=None					,     lowerCAmelCase		:						str=0.05	)	->       List[str]:







						"""simple docstring"""







						if timeout is None:
											__UpperCamelCase					:	Union[str, Any]             =      self.timeout

						# Increment the number right at the beginning.
						# We can still undo it, if something fails.
						with self._thread_lock:
											self._lock_counter += 1

						__UpperCamelCase					:	Optional[Any]             =      id(self	)
						__UpperCamelCase					:	Tuple             =      self._lock_file
						__UpperCamelCase					:	List[Any]             =      time.time()
						try:
											while True:
																with self._thread_lock:
																					if not self.is_locked:
																										logger().debug(F'''Attempting to acquire lock {lock_id} on {lock_filename}'''	)
																										self._acquire()

																if self.is_locked:
																					logger().debug(F'''Lock {lock_id} acquired on {lock_filename}'''	)
																					break
																elif timeout >= 0 and time.time() - start_time > timeout:
																					logger().debug(F'''Timeout on acquiring lock {lock_id} on {lock_filename}'''	)
																					raise Timeout(self._lock_file	)
																else:
																					logger().debug(
																					    F'''Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...'''	)
																					time.sleep(lowerCAmelCase	)
						except:  # noqa
											# Something did go wrong, so decrement the counter.
											with self._thread_lock:
																__UpperCamelCase					:	Optional[int]             =      max(0					,     self._lock_counter - 1	)

											raise
						return _Acquire_ReturnProxy(lock=self	)






	def 					lowerCamelCase__     (					self		:						Optional[Any]					,     lowerCAmelCase		:						List[str]=False	)	->       List[Any]:







						"""simple docstring"""







						with self._thread_lock:
											if self.is_locked:
																self._lock_counter -= 1

																if self._lock_counter == 0 or force:
																					__UpperCamelCase					:	List[Any]             =      id(self	)
																					__UpperCamelCase					:	List[str]             =      self._lock_file

																					logger().debug(F'''Attempting to release lock {lock_id} on {lock_filename}'''	)
																					self._release()
																					__UpperCamelCase					:	str             =      0
																					logger().debug(F'''Lock {lock_id} released on {lock_filename}'''	)

						return None






	def __enter__(					self		:						List[Any]	)	->       Optional[int]:







						"""simple docstring"""







						self.acquire()
						return self






	def __exit__(					self		:						Any					,     lowerCAmelCase		:						int					,     lowerCAmelCase		:						List[Any]					,     lowerCAmelCase		:						Dict	)	->       Optional[int]:







						"""simple docstring"""







						self.release()
						return None






	def __del__(					self		:						Optional[Any]	)	->       int:







						"""simple docstring"""







						self.release(force=lowerCAmelCase	)
						return None






	def 					lowerCamelCase__     (					self		:						Any					,     lowerCAmelCase		:						str					,     lowerCAmelCase		:						int	)	->       str:







						"""simple docstring"""







						__UpperCamelCase					:	List[str]             =      os.path.basename(lowerCAmelCase	)
						if len(lowerCAmelCase	) > max_length and max_length > 0:
											__UpperCamelCase					:	str             =      os.path.dirname(lowerCAmelCase	)
											__UpperCamelCase					:	str             =      str(hash(lowerCAmelCase	)	)
											__UpperCamelCase					:	Union[str, Any]             =      filename[: max_length - len(lowerCAmelCase	) - 8] + """...""" + hashed_filename + """.lock"""
											return os.path.join(lowerCAmelCase					,     lowerCAmelCase	)
						else:
											return path






class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



	"""simple docstring"""


	def __init__(					self		:						Optional[int]					,     lowerCAmelCase		:						Any					,     lowerCAmelCase		:						Union[str, Any]=-1					,     lowerCAmelCase		:						Any=None	)	->       Union[str, Any]:







						"""simple docstring"""







						from .file_utils import relative_to_absolute_path

						super().__init__(lowerCAmelCase					,     timeout=lowerCAmelCase					,     max_filename_length=lowerCAmelCase	)
						__UpperCamelCase					:	Optional[Any]             =      """\\\\?\\""" + relative_to_absolute_path(self.lock_file	)






	def 					lowerCamelCase__     (					self		:						str	)	->       Tuple:







						"""simple docstring"""







						__UpperCamelCase					:	Tuple             =      os.O_RDWR | os.O_CREAT | os.O_TRUNC

						try:
											__UpperCamelCase					:	str             =      os.open(self._lock_file					,     lowerCAmelCase	)
						except OSError:
											pass
						else:
											try:
																msvcrt.locking(lowerCAmelCase					,     msvcrt.LK_NBLCK					,     1	)
											except OSError:
																os.close(lowerCAmelCase	)
											else:
																__UpperCamelCase					:	List[Any]             =      fd
						return None






	def 					lowerCamelCase__     (					self		:						int	)	->       List[Any]:







						"""simple docstring"""







						__UpperCamelCase					:	List[str]             =      self._lock_file_fd
						__UpperCamelCase					:	Any             =      None
						msvcrt.locking(lowerCAmelCase					,     msvcrt.LK_UNLCK					,     1	)
						os.close(lowerCAmelCase	)

						try:
											os.remove(self._lock_file	)
						# Probably another instance of the application
						# that acquired the file lock.
						except OSError:
											pass
						return None






class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



	"""simple docstring"""


	def __init__(					self		:						List[Any]					,     lowerCAmelCase		:						Optional[Any]					,     lowerCAmelCase		:						Union[str, Any]=-1					,     lowerCAmelCase		:						Dict=None	)	->       str:







						"""simple docstring"""







						__UpperCamelCase					:	Tuple             =      os.statvfs(os.path.dirname(lowerCAmelCase	)	).f_namemax
						super().__init__(lowerCAmelCase					,     timeout=lowerCAmelCase					,     max_filename_length=lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						Tuple	)	->       int:







						"""simple docstring"""







						__UpperCamelCase					:	List[Any]             =      os.O_RDWR | os.O_CREAT | os.O_TRUNC
						__UpperCamelCase					:	List[str]             =      os.open(self._lock_file					,     lowerCAmelCase	)

						try:
											fcntl.flock(lowerCAmelCase					,     fcntl.LOCK_EX | fcntl.LOCK_NB	)
						except OSError:
											os.close(lowerCAmelCase	)
						else:
											__UpperCamelCase					:	Optional[Any]             =      fd
						return None






	def 					lowerCamelCase__     (					self		:						int	)	->       List[Any]:







						"""simple docstring"""







						__UpperCamelCase					:	List[Any]             =      self._lock_file_fd
						__UpperCamelCase					:	Union[str, Any]             =      None
						fcntl.flock(lowerCAmelCase					,     fcntl.LOCK_UN	)
						os.close(lowerCAmelCase	)
						return None






class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



	"""simple docstring"""


	def 					lowerCamelCase__     (					self		:						Dict	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[Any]             =      os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
						try:
											__UpperCamelCase					:	int             =      os.open(self._lock_file					,     lowerCAmelCase	)
						except OSError:
											pass
						else:
											__UpperCamelCase					:	Optional[Any]             =      fd
						return None






	def 					lowerCamelCase__     (					self		:						Tuple	)	->       int:







						"""simple docstring"""







						os.close(self._lock_file_fd	)
						__UpperCamelCase					:	Optional[int]             =      None

						try:
											os.remove(self._lock_file	)
						# The file is already deleted and that's what we want.
						except OSError:
											pass
						return None






a__		     =     None

if msvcrt:
	a__		     =     WindowsFileLock
elif fcntl:
	a__		     =     UnixFileLock
else:
	a__		     =     SoftFileLock

	if warnings is not None:
		warnings.warn('''only soft file lock is available''')












import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402


a__		     =     get_tests_dir('''fixtures/dummy-config.json''')


class    SCREAMING_SNAKE_CASE_				(       unittest.TestCase   ):



	"""simple docstring"""


	def 					lowerCamelCase__     (					self		:						str	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[Any]             =      0






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







						"""simple docstring"""







						self.assertIsNotNone(transformers.models.auto.__spec__	)
						self.assertIsNotNone(importlib.util.find_spec("""transformers.models.auto"""	)	)






	def 					lowerCamelCase__     (					self		:						Optional[Any]	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	int             =      AutoConfig.from_pretrained("""bert-base-uncased"""	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						List[Any]	)	->       Optional[Any]:







						"""simple docstring"""







						__UpperCamelCase					:	Dict             =      AutoConfig.from_pretrained(lowerCAmelCase	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						Any	)	->       Optional[int]:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[int]             =      AutoConfig.from_pretrained(lowerCAmelCase	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						Tuple	)	->       Any:







						"""simple docstring"""







						__UpperCamelCase					:	List[Any]             =      AutoConfig.for_model("""roberta"""	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						int	)	->       List[Any]:







						"""simple docstring"""







						with tempfile.TemporaryDirectory() as tmp_dir:
											# This model name contains bert and roberta, but roberta ends up being picked.
											__UpperCamelCase					:	Union[str, Any]             =      os.path.join(lowerCAmelCase					,     """fake-roberta"""	)
											os.makedirs(lowerCAmelCase					,     exist_ok=lowerCAmelCase	)
											with open(os.path.join(lowerCAmelCase					,     """config.json"""	)					,     """w"""	) as f:
																f.write(json.dumps({}	)	)
											__UpperCamelCase					:	Dict             =      AutoConfig.from_pretrained(lowerCAmelCase	)
											self.assertEqual(type(lowerCAmelCase	)					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						int	)	->       str:







						"""simple docstring"""







						try:
											AutoConfig.register("""custom"""					,     lowerCAmelCase	)
											# Wrong model type will raise an error
											with self.assertRaises(lowerCAmelCase	):
																AutoConfig.register("""model"""					,     lowerCAmelCase	)
											# Trying to register something existing in the Transformers library will raise an error
											with self.assertRaises(lowerCAmelCase	):
																AutoConfig.register("""bert"""					,     lowerCAmelCase	)

											# Now that the config is registered, it can be used as any other config with the auto-API
											__UpperCamelCase					:	Optional[Any]             =      CustomConfig()
											with tempfile.TemporaryDirectory() as tmp_dir:
																config.save_pretrained(lowerCAmelCase	)
																__UpperCamelCase					:	List[str]             =      AutoConfig.from_pretrained(lowerCAmelCase	)
																self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)

						finally:
											if "custom" in CONFIG_MAPPING._extra_content:
																del CONFIG_MAPPING._extra_content["custom"]






	def 					lowerCamelCase__     (					self		:						int	)	->       Optional[Any]:







						"""simple docstring"""







						with self.assertRaisesRegex(
						    lowerCAmelCase					,     """bert-base is not a local folder and is not a valid model identifier"""	):
											__UpperCamelCase					:	Tuple             =      AutoConfig.from_pretrained("""bert-base"""	)






	def 					lowerCamelCase__     (					self		:						Dict	)	->       Any:







						"""simple docstring"""







						with self.assertRaisesRegex(
						    lowerCAmelCase					,     R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""	):
											__UpperCamelCase					:	Optional[Any]             =      AutoConfig.from_pretrained(lowerCAmelCase					,     revision="""aaaaaa"""	)






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







						"""simple docstring"""







						with self.assertRaisesRegex(
						    lowerCAmelCase					,     """hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."""					,     ):
											__UpperCamelCase					:	Union[str, Any]             =      AutoConfig.from_pretrained("""hf-internal-testing/no-config-test-repo"""	)






	def 					lowerCamelCase__     (					self		:						Optional[int]	)	->       Optional[int]:







						"""simple docstring"""







						with self.assertRaises(lowerCAmelCase	):
											__UpperCamelCase					:	str             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""	)
						# If remote code is disabled, we can't load this config.
						with self.assertRaises(lowerCAmelCase	):
											__UpperCamelCase					:	Tuple             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)

						__UpperCamelCase					:	List[str]             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)
						self.assertEqual(config.__class__.__name__					,     """NewModelConfig"""	)

						# Test config can be reloaded.
						with tempfile.TemporaryDirectory() as tmp_dir:
											config.save_pretrained(lowerCAmelCase	)
											__UpperCamelCase					:	str             =      AutoConfig.from_pretrained(lowerCAmelCase					,     trust_remote_code=lowerCAmelCase	)
						self.assertEqual(reloaded_config.__class__.__name__					,     """NewModelConfig"""	)






	def 					lowerCamelCase__     (					self		:						Optional[int]	)	->       str:







						"""simple docstring"""







						class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



							"""simple docstring"""


							__magic_name__   :       int      	=		'new-model'

						try:
											AutoConfig.register("""new-model"""					,     lowerCAmelCase	)
											# If remote code is not set, the default is to use local
											__UpperCamelCase					:	Tuple             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""	)
											self.assertEqual(config.__class__.__name__					,     """NewModelConfigLocal"""	)

											# If remote code is disabled, we load the local one.
											__UpperCamelCase					:	Any             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)
											self.assertEqual(config.__class__.__name__					,     """NewModelConfigLocal"""	)

											# If remote is enabled, we load from the Hub
											__UpperCamelCase					:	List[Any]             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)
											self.assertEqual(config.__class__.__name__					,     """NewModelConfig"""	)

						finally:
											if "new-model" in CONFIG_MAPPING._extra_content:
																del CONFIG_MAPPING._extra_content["new-model"]






