



"""simple docstring"""






def      snake_case__   (		__lowerCamelCase				:    list[int]							,		__lowerCamelCase				:    list[int]	):
			"""simple docstring"""

			# Check if the input is valid
			if not len(__lowerCamelCase	) == len(__lowerCamelCase	) == 3:
						raise ValueError('''Please enter a valid equation.'''	)
			if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0:
						raise ValueError('''Both a & b of two equations can\'t be zero.'''	)

			# Extract the coefficients
			lowerCamelCase__	,   lowerCamelCase__	,   lowerCamelCase__		:		int			=equationa
			lowerCamelCase__	,   lowerCamelCase__	,   lowerCamelCase__		:		Optional[int]			=equationa

			# Calculate the determinants of the matrices
			lowerCamelCase__		:		Optional[Any]			=aa * ba - aa * ba
			lowerCamelCase__		:		str			=ca * ba - ca * ba
			lowerCamelCase__		:		Union[str, Any]			=aa * ca - aa * ca

			# Check if the system of linear equations has a solution (using Cramer's rule)
			if determinant == 0:
						if determinant_x == determinant_y == 0:
									raise ValueError('''Infinite solutions. (Consistent system)'''	)
						else:
									raise ValueError('''No solution. (Inconsistent system)'''	)
			else:
						if determinant_x == determinant_y == 0:
									# Trivial solution (Inconsistent system)
									return (0.0, 0.0)
						else:
									lowerCamelCase__		:		Any			=determinant_x / determinant
									lowerCamelCase__		:		Dict			=determinant_y / determinant
									# Non-Trivial Solution (Consistent system)
									return (x, y)









"""simple docstring"""






import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
		import jax.numpy as jnp

class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					def __get__(       self							:  Tuple,  lowerCamelCase							:  List[str],  lowerCamelCase							:  Optional[int]=None     )->					List[str]:
								# See docs.python.org/3/howto/descriptor.html#properties
								if obj is None:
											return self
								if self.fget is None:
											raise AttributeError('''unreadable attribute'''     )
								lowerCamelCase__		:		List[str]			='''__cached_''' + self.fget.__name__
								lowerCamelCase__		:		List[Any]			=getattr(lowerCamelCase,  lowerCamelCase,  lowerCamelCase     )
								if cached is None:
											lowerCamelCase__		:		Optional[int]			=self.fget(lowerCamelCase     )
											setattr(lowerCamelCase,  lowerCamelCase,  lowerCamelCase     )
								return cached






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			lowerCamelCase__		:		Optional[Any]			=val.lower()
			if val in {"y", "yes", "t", "true", "on", "1"}:
						return 1
			if val in {"n", "no", "f", "false", "off", "0"}:
						return 0
			raise ValueError(f'''invalid truth value {val!r}'''	)






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			if is_torch_fx_proxy(__lowerCamelCase	):
						return True
			if is_torch_available():
						import torch

						if isinstance(__lowerCamelCase							,		torch.Tensor	):
									return True
			if is_tf_available():
						import tensorflow as tf

						if isinstance(__lowerCamelCase							,		tf.Tensor	):
									return True

			if is_flax_available():
						import jax.numpy as jnp
						from jax.core import Tracer

						if isinstance(__lowerCamelCase							,		(jnp.ndarray, Tracer)	):
									return True

			return isinstance(__lowerCamelCase							,		np.ndarray	)






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			return isinstance(__lowerCamelCase							,		np.ndarray	)






def      snake_case__   (		__lowerCamelCase				:    Union[str, Any]	):
			"""simple docstring"""
			return _is_numpy(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    Any	):
			"""simple docstring"""
			import torch

			return isinstance(__lowerCamelCase							,		torch.Tensor	)






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]	):
			"""simple docstring"""
			return False if not is_torch_available() else _is_torch(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			import torch

			return isinstance(__lowerCamelCase							,		torch.device	)






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]	):
			"""simple docstring"""
			return False if not is_torch_available() else _is_torch_device(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    Tuple	):
			"""simple docstring"""
			import torch

			if isinstance(__lowerCamelCase							,		__lowerCamelCase	):
						if hasattr(__lowerCamelCase							,		__lowerCamelCase	):
									lowerCamelCase__		:		Tuple			=getattr(__lowerCamelCase							,		__lowerCamelCase	)
						else:
									return False
			return isinstance(__lowerCamelCase							,		torch.dtype	)






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			return False if not is_torch_available() else _is_torch_dtype(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]	):
			"""simple docstring"""
			import tensorflow as tf

			return isinstance(__lowerCamelCase							,		tf.Tensor	)






def      snake_case__   (		__lowerCamelCase				:    int	):
			"""simple docstring"""
			return False if not is_tf_available() else _is_tensorflow(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			import tensorflow as tf

			# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
			if hasattr(__lowerCamelCase							,		'''is_symbolic_tensor'''	):
						return tf.is_symbolic_tensor(__lowerCamelCase	)
			return type(__lowerCamelCase	) == tf.Tensor






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]	):
			"""simple docstring"""
			return False if not is_tf_available() else _is_tf_symbolic_tensor(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			import jax.numpy as jnp  # noqa: F811

			return isinstance(__lowerCamelCase							,		jnp.ndarray	)






def      snake_case__   (		__lowerCamelCase				:    Tuple	):
			"""simple docstring"""
			return False if not is_flax_available() else _is_jax(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			if isinstance(__lowerCamelCase							,		(dict, UserDict)	):
						return {k: to_py_obj(__lowerCamelCase	) for k, v in obj.items()}
			elif isinstance(__lowerCamelCase							,		(list, tuple)	):
						return [to_py_obj(__lowerCamelCase	) for o in obj]
			elif is_tf_tensor(__lowerCamelCase	):
						return obj.numpy().tolist()
			elif is_torch_tensor(__lowerCamelCase	):
						return obj.detach().cpu().tolist()
			elif is_jax_tensor(__lowerCamelCase	):
						return np.asarray(__lowerCamelCase	).tolist()
			elif isinstance(__lowerCamelCase							,		(np.ndarray, np.number)	):  # tolist also works on 0d np arrays
						return obj.tolist()
			else:
						return obj






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			if isinstance(__lowerCamelCase							,		(dict, UserDict)	):
						return {k: to_numpy(__lowerCamelCase	) for k, v in obj.items()}
			elif isinstance(__lowerCamelCase							,		(list, tuple)	):
						return np.array(__lowerCamelCase	)
			elif is_tf_tensor(__lowerCamelCase	):
						return obj.numpy()
			elif is_torch_tensor(__lowerCamelCase	):
						return obj.detach().cpu().numpy()
			elif is_jax_tensor(__lowerCamelCase	):
						return np.asarray(__lowerCamelCase	)
			else:
						return obj

class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					def 		snake_case       (       self							:  int     )->					Optional[int]:
								lowerCamelCase__		:		Union[str, Any]			=fields(self     )

								# Safety and consistency checks
								if not len(lowerCamelCase     ):
											raise ValueError(F'''{self.__class__.__name__} has no fields.'''     )
								if not all(field.default is None for field in class_fields[1:]     ):
											raise ValueError(F'''{self.__class__.__name__} should not have more than one required field.'''     )

								lowerCamelCase__		:		List[Any]			=getattr(self,  class_fields[0].name     )
								lowerCamelCase__		:		Union[str, Any]			=all(getattr(self,  field.name     ) is None for field in class_fields[1:]     )

								if other_fields_are_none and not is_tensor(lowerCamelCase     ):
											if isinstance(lowerCamelCase,  lowerCamelCase     ):
														lowerCamelCase__		:		Optional[int]			=first_field.items()
														lowerCamelCase__		:		Union[str, Any]			=True
											else:
														try:
																	lowerCamelCase__		:		int			=iter(lowerCamelCase     )
																	lowerCamelCase__		:		List[Any]			=True
														except TypeError:
																	lowerCamelCase__		:		List[Any]			=False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
											if first_field_iterator:
														for idx, element in enumerate(lowerCamelCase     ):
																	if (
																	    not isinstance(lowerCamelCase,  (list, tuple)     )
																	    or not len(lowerCamelCase     ) == 2
																	    or not isinstance(element[0],  lowerCamelCase     )
																	):
																				if idx == 0:
																							# If we do not have an iterator of key/values, set it as attribute
																							lowerCamelCase__		:		Optional[int]			=first_field
																				else:
																							# If we have a mixed iterator, raise an error
																							raise ValueError(
																							    F'''Cannot set key/value for {element}. It needs to be a tuple (key, value).'''     )
																				break
																	setattr(self,  element[0],  element[1]     )
																	if element[1] is not None:
																				lowerCamelCase__		:		str			=element[1]
											elif first_field is not None:
														lowerCamelCase__		:		Dict			=first_field
								else:
											for field in class_fields:
														lowerCamelCase__		:		Union[str, Any]			=getattr(self,  field.name     )
														if v is not None:
																	lowerCamelCase__		:		Optional[int]			=v



					def __delitem__(       self							:  int,  *lowerCamelCase							:  List[str],  **lowerCamelCase							:  Optional[int]     )->					str:
								raise Exception(F'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''     )



					def 		snake_case       (       self							:  Optional[int],  *lowerCamelCase							:  int,  **lowerCamelCase							:  List[str]     )->					Optional[Any]:
								raise Exception(F'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''     )



					def 		snake_case       (       self							:  Dict,  *lowerCamelCase							:  Optional[int],  **lowerCamelCase							:  Optional[Any]     )->					int:
								raise Exception(F'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''     )



					def 		snake_case       (       self							:  List[Any],  *lowerCamelCase							:  Tuple,  **lowerCamelCase							:  List[Any]     )->					Optional[int]:
								raise Exception(F'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''     )



					def __getitem__(       self							:  Optional[Any],  lowerCamelCase							:  Optional[int]     )->					List[Any]:
								if isinstance(lowerCamelCase,  lowerCamelCase     ):
											lowerCamelCase__		:		Union[str, Any]			=dict(self.items()     )
											return inner_dict[k]
								else:
											return self.to_tuple()[k]



					def __setattr__(       self							:  Union[str, Any],  lowerCamelCase							:  List[str],  lowerCamelCase							:  List[str]     )->					Dict:
								if name in self.keys() and value is not None:
											# Don't call self.__setitem__ to avoid recursion errors
											super().__setitem__(lowerCamelCase,  lowerCamelCase     )
								super().__setattr__(lowerCamelCase,  lowerCamelCase     )



					def __setitem__(       self							:  Optional[Any],  lowerCamelCase							:  Union[str, Any],  lowerCamelCase							:  int     )->					List[Any]:
								# Will raise a KeyException if needed
								super().__setitem__(lowerCamelCase,  lowerCamelCase     )
								# Don't call self.__setattr__ to avoid recursion errors
								super().__setattr__(lowerCamelCase,  lowerCamelCase     )




					def 		snake_case       (       self							:  str     )->					Tuple[Any]:
								return tuple(self[k] for k in self.keys()     )





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_		,   lowerCAmelCase_   ):


					'''simple docstring'''





					@classmethod
					def 		snake_case       (       cls							:  Optional[Any],  lowerCamelCase							:  int     )->					str:
								raise ValueError(
								    F'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()     )}'''     )





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							'longest'
					_a   			=							'max_length'
					_a   			=							'do_not_pad'





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							'pt'
					_a   			=							'tf'
					_a   			=							'np'
					_a   			=							'jax'





class        __SCREAMING_SNAKE_CASE	:


					'''simple docstring'''





					def __init__(       self							:  Optional[int],  lowerCamelCase							:  List[ContextManager]     )->					str:
								lowerCamelCase__		:		List[str]			=context_managers
								lowerCamelCase__		:		int			=ExitStack()



					def __enter__(       self							:  List[str]     )->					Union[str, Any]:
								for context_manager in self.context_managers:
											self.stack.enter_context(lowerCamelCase     )




					def __exit__(       self							:  Tuple,  *lowerCamelCase							:  Union[str, Any],  **lowerCamelCase							:  Tuple     )->					List[Any]:
								self.stack.__exit__(*lowerCamelCase,  **lowerCamelCase     )






def      snake_case__   (		__lowerCamelCase				:    int	):
			"""simple docstring"""
			lowerCamelCase__		:		Tuple			=infer_framework(__lowerCamelCase	)
			if framework == "tf":
						lowerCamelCase__		:		Any			=inspect.signature(model_class.call	)  # TensorFlow models
			elif framework == "pt":
						lowerCamelCase__		:		Tuple			=inspect.signature(model_class.forward	)  # PyTorch models
			else:
						lowerCamelCase__		:		List[str]			=inspect.signature(model_class.__call__	)  # Flax models

			for p in signature.parameters:
						if p == "return_loss" and signature.parameters[p].default is True:
									return True

			return False






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			lowerCamelCase__		:		Optional[Any]			=model_class.__name__
			lowerCamelCase__		:		Tuple			=infer_framework(__lowerCamelCase	)
			if framework == "tf":
						lowerCamelCase__		:		int			=inspect.signature(model_class.call	)  # TensorFlow models
			elif framework == "pt":
						lowerCamelCase__		:		Any			=inspect.signature(model_class.forward	)  # PyTorch models
			else:
						lowerCamelCase__		:		Union[str, Any]			=inspect.signature(model_class.__call__	)  # Flax models

			if "QuestionAnswering" in model_name:
						return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
			else:
						return [p for p in signature.parameters if "label" in p]






def      snake_case__   (		__lowerCamelCase				:    MutableMapping							,		__lowerCamelCase				:    str = ""							,		__lowerCamelCase				:    str = "."	):
			"""simple docstring"""

			def _flatten_dict(__lowerCamelCase				:    Optional[int]							,		__lowerCamelCase				:    Optional[int]=""							,		__lowerCamelCase				:    str="."	):
						for k, v in d.items():
									lowerCamelCase__		:		List[str]			=str(__lowerCamelCase	) + delimiter + str(__lowerCamelCase	) if parent_key else k
									if v and isinstance(__lowerCamelCase							,		__lowerCamelCase	):
												yield from flatten_dict(__lowerCamelCase							,		__lowerCamelCase							,		delimiter=__lowerCamelCase	).items()
									else:
												yield key, v

			return dict(_flatten_dict(__lowerCamelCase							,		__lowerCamelCase							,		__lowerCamelCase	)	)






@contextmanager
def      snake_case__   (		__lowerCamelCase				:    Tuple							,		__lowerCamelCase				:    bool = False	):
			"""simple docstring"""
			if use_temp_dir:
						with tempfile.TemporaryDirectory() as tmp_dir:
									yield tmp_dir
			else:
						yield working_dir






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]							,		__lowerCamelCase				:    Dict=None	):
			"""simple docstring"""
			if is_numpy_array(__lowerCamelCase	):
						return np.transpose(__lowerCamelCase							,		axes=__lowerCamelCase	)
			elif is_torch_tensor(__lowerCamelCase	):
						return array.T if axes is None else array.permute(*__lowerCamelCase	)
			elif is_tf_tensor(__lowerCamelCase	):
						import tensorflow as tf

						return tf.transpose(__lowerCamelCase							,		perm=__lowerCamelCase	)
			elif is_jax_tensor(__lowerCamelCase	):
						return jnp.transpose(__lowerCamelCase							,		axes=__lowerCamelCase	)
			else:
						raise ValueError(f'''Type not supported for transpose: {type(__lowerCamelCase	)}.'''	)






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]							,		__lowerCamelCase				:    Optional[int]	):
			"""simple docstring"""
			if is_numpy_array(__lowerCamelCase	):
						return np.reshape(__lowerCamelCase							,		__lowerCamelCase	)
			elif is_torch_tensor(__lowerCamelCase	):
						return array.reshape(*__lowerCamelCase	)
			elif is_tf_tensor(__lowerCamelCase	):
						import tensorflow as tf

						return tf.reshape(__lowerCamelCase							,		__lowerCamelCase	)
			elif is_jax_tensor(__lowerCamelCase	):
						return jnp.reshape(__lowerCamelCase							,		__lowerCamelCase	)
			else:
						raise ValueError(f'''Type not supported for reshape: {type(__lowerCamelCase	)}.'''	)






def      snake_case__   (		__lowerCamelCase				:    Optional[Any]							,		__lowerCamelCase				:    List[str]=None	):
			"""simple docstring"""
			if is_numpy_array(__lowerCamelCase	):
						return np.squeeze(__lowerCamelCase							,		axis=__lowerCamelCase	)
			elif is_torch_tensor(__lowerCamelCase	):
						return array.squeeze() if axis is None else array.squeeze(dim=__lowerCamelCase	)
			elif is_tf_tensor(__lowerCamelCase	):
						import tensorflow as tf

						return tf.squeeze(__lowerCamelCase							,		axis=__lowerCamelCase	)
			elif is_jax_tensor(__lowerCamelCase	):
						return jnp.squeeze(__lowerCamelCase							,		axis=__lowerCamelCase	)
			else:
						raise ValueError(f'''Type not supported for squeeze: {type(__lowerCamelCase	)}.'''	)






def      snake_case__   (		__lowerCamelCase				:    Dict							,		__lowerCamelCase				:    Optional[int]	):
			"""simple docstring"""
			if is_numpy_array(__lowerCamelCase	):
						return np.expand_dims(__lowerCamelCase							,		__lowerCamelCase	)
			elif is_torch_tensor(__lowerCamelCase	):
						return array.unsqueeze(dim=__lowerCamelCase	)
			elif is_tf_tensor(__lowerCamelCase	):
						import tensorflow as tf

						return tf.expand_dims(__lowerCamelCase							,		axis=__lowerCamelCase	)
			elif is_jax_tensor(__lowerCamelCase	):
						return jnp.expand_dims(__lowerCamelCase							,		axis=__lowerCamelCase	)
			else:
						raise ValueError(f'''Type not supported for expand_dims: {type(__lowerCamelCase	)}.'''	)






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			if is_numpy_array(__lowerCamelCase	):
						return np.size(__lowerCamelCase	)
			elif is_torch_tensor(__lowerCamelCase	):
						return array.numel()
			elif is_tf_tensor(__lowerCamelCase	):
						import tensorflow as tf

						return tf.size(__lowerCamelCase	)
			elif is_jax_tensor(__lowerCamelCase	):
						return array.size
			else:
						raise ValueError(f'''Type not supported for expand_dims: {type(__lowerCamelCase	)}.'''	)






def      snake_case__   (		__lowerCamelCase				:    Union[str, Any]							,		__lowerCamelCase				:    Tuple	):
			"""simple docstring"""
			for key, value in auto_map.items():
						if isinstance(__lowerCamelCase							,		(tuple, list)	):
									lowerCamelCase__		:		Optional[int]			=[f'''{repo_id}--{v}''' if (v is not None and '''--''' not in v) else v for v in value]
						elif value is not None and "--" not in value:
									lowerCamelCase__		:		Tuple			=f'''{repo_id}--{value}'''

			return auto_map






def      snake_case__   (		__lowerCamelCase				:    Optional[int]	):
			"""simple docstring"""
			for base_class in inspect.getmro(__lowerCamelCase	):
						lowerCamelCase__		:		Tuple			=base_class.__module__
						lowerCamelCase__		:		Tuple			=base_class.__name__
						if module.startswith('''tensorflow'''	) or module.startswith('''keras'''	) or name == "TFPreTrainedModel":
									return "tf"
						elif module.startswith('''torch'''	) or name == "PreTrainedModel":
									return "pt"
						elif module.startswith('''flax'''	) or module.startswith('''jax'''	) or name == "FlaxPreTrainedModel":
									return "flax"
			else:
						raise TypeError(f'''Could not infer framework from class {model_class}.'''	)




