

"""simple docstring"""





import heapq as hq
import math
from collections.abc import Iterator







class 							SCREAMING_SNAKE_CASE   :






					"""simple docstring"""



					def __init__(			self     :							Dict  ,lowercase_     :							Tuple						):
						lowerCAmelCase__      :		Tuple    							=      str(id_						)
						lowerCAmelCase__      :		Union[str, Any]    							=      None
						lowerCAmelCase__      :		Union[str, Any]    							=      None
						lowerCAmelCase__      :		Optional[int]    							=      []
						lowerCAmelCase__      :		Optional[Any]    							=      {}  # {vertex:distance}







					def __lt__(			self     :							Dict  ,lowercase_     :							Optional[int]						):
						return self.key < other.key







					def __repr__(			self     :							Optional[int]						):
						return self.id







					def 			__lowerCAmelCase					(			self     :							Any  ,lowercase_     :							str						):
						self.neighbors.append(lowercase_						)







					def 			__lowerCAmelCase					(			self     :							List[Any]  ,lowercase_     :							Optional[int]  ,lowercase_     :							Any						):
						lowerCAmelCase__      :		str    							=      weight

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_		,	A_		,	A_					):
	# add the neighbors:
	graph[a - 1].add_neighbor(graph[b - 1]					)
	graph[b - 1].add_neighbor(graph[a - 1]					)
	# add the edges:
	graph[a - 1].add_edge(graph[b - 1]		,	A_					)
	graph[b - 1].add_edge(graph[a - 1]		,	A_					)

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_					):
	lowerCAmelCase__      :		List[str]    							=      []
	for u in graph:
		lowerCAmelCase__      :		Optional[Any]    							=      math.inf
		lowerCAmelCase__      :		List[str]    							=      None
	lowerCAmelCase__      :		Optional[Any]    							=      0
	lowerCAmelCase__      :		Dict    							=      graph[:]
	while q:
		lowerCAmelCase__      :		Optional[int]    							=      min(A_					)
		q.remove(A_					)
		for v in u.neighbors:
			if (v in q) and (u.edges[v.id] < v.key):
				lowerCAmelCase__      :		List[Any]    							=      u
				lowerCAmelCase__      :		List[str]    							=      u.edges[v.id]
	for i in range(1		,	len(A_					)					):
		a.append((int(graph[i].id					) + 1, int(graph[i].pi.id					) + 1)					)
	return a

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_					):
	for u in graph:
		lowerCAmelCase__      :		Tuple    							=      math.inf
		lowerCAmelCase__      :		Optional[Any]    							=      None
	lowerCAmelCase__      :		Tuple    							=      0

	lowerCAmelCase__      :		Optional[int]    							=      list(A_					)
	hq.heapify(A_					)

	while h:
		lowerCAmelCase__      :		int    							=      hq.heappop(A_					)
		for v in u.neighbors:
			if (v in h) and (u.edges[v.id] < v.key):
				lowerCAmelCase__      :		Tuple    							=      u
				lowerCAmelCase__      :		Any    							=      u.edges[v.id]
				hq.heapify(A_					)

	for i in range(1		,	len(A_					)					):
		yield (int(graph[i].id					) + 1, int(graph[i].pi.id					) + 1)

def     __SCREAMING_SNAKE_CASE    ( ):
	pass


if __name__ == "__main__":
							import doctest

							doctest.testmod()







"""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   (						a_			):






					"""simple docstring"""



					def __get__(			self     :							List[Any]  ,lowercase_     :							Any  ,lowercase_     :							List[str]=None						):
						# 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__      :		Optional[Any]    							=      '''__cached_''' + self.fget.__name__
						lowerCAmelCase__      :		Any    							=      getattr(lowercase_  ,lowercase_  ,lowercase_						)
						if cached is None:
							lowerCAmelCase__      :		str    							=      self.fget(lowercase_						)
							setattr(lowercase_  ,lowercase_  ,lowercase_						)
						return cached

def     __SCREAMING_SNAKE_CASE    ( A_					):
	lowerCAmelCase__      :		int    							=      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     __SCREAMING_SNAKE_CASE    ( A_					):
	if is_torch_fx_proxy(A_					):
		return True
	if is_torch_available():
		import torch

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

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

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

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

	return isinstance(A_		,	np.ndarray					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return isinstance(A_		,	np.ndarray					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return _is_numpy(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import torch

	return isinstance(A_		,	torch.Tensor					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_torch_available() else _is_torch(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import torch

	return isinstance(A_		,	torch.device					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_torch_available() else _is_torch_device(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import torch

	if isinstance(A_		,	A_					):
		if hasattr(A_		,	A_					):
			lowerCAmelCase__      :		int    							=      getattr(A_		,	A_					)
		else:
			return False
	return isinstance(A_		,	torch.dtype					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_torch_available() else _is_torch_dtype(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import tensorflow as tf

	return isinstance(A_		,	tf.Tensor					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_tf_available() else _is_tensorflow(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import tensorflow as tf

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

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_tf_available() else _is_tf_symbolic_tensor(A_					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	import jax.numpy as jnp  # noqa: F811

	return isinstance(A_		,	jnp.ndarray					)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	return False if not is_flax_available() else _is_jax(A_					)

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

def     __SCREAMING_SNAKE_CASE    ( A_					):
	if isinstance(A_		,	(dict, UserDict)					):
		return {k: to_numpy(A_					) for k, v in obj.items()}
	elif isinstance(A_		,	(list, tuple)					):
		return np.array(A_					)
	elif is_tf_tensor(A_					):
		return obj.numpy()
	elif is_torch_tensor(A_					):
		return obj.detach().cpu().numpy()
	elif is_jax_tensor(A_					):
		return np.asarray(A_					)
	else:
		return obj







class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					def 			__lowerCAmelCase					(			self     :							Any						):
						lowerCAmelCase__      :		Optional[int]    							=      fields(self						)

						# Safety and consistency checks
						if not len(lowercase_						):
							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__      :		str    							=      getattr(self  ,class_fields[0].name						)
						lowerCAmelCase__      :		List[str]    							=      all(getattr(self  ,field.name						) is None for field in class_fields[1:]						)

						if other_fields_are_none and not is_tensor(lowercase_						):
							if isinstance(lowercase_  ,lowercase_						):
								lowerCAmelCase__      :		str    							=      first_field.items()
								lowerCAmelCase__      :		List[str]    							=      True
							else:
								try:
									lowerCAmelCase__      :		Union[str, Any]    							=      iter(lowercase_						)
									lowerCAmelCase__      :		int    							=      True
								except TypeError:
									lowerCAmelCase__      :		Dict    							=      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(lowercase_						):
									if (
									    not isinstance(lowercase_  ,(list, tuple)						)
									    or not len(lowercase_						) == 2
									    or not isinstance(element[0]  ,lowercase_						)
									):
										if idx == 0:
											# If we do not have an iterator of key/values, set it as attribute
											lowerCAmelCase__      :		Tuple    							=      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__      :		Dict    							=      element[1]
							elif first_field is not None:
								lowerCAmelCase__      :		Any    							=      first_field
						else:
							for field in class_fields:
								lowerCAmelCase__      :		Any    							=      getattr(self  ,field.name						)
								if v is not None:
									lowerCAmelCase__      :		List[str]    							=      v







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







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







					def 			__lowerCAmelCase					(			self     :							str  ,*lowercase_     :							Union[str, Any]  ,**lowercase_     :							Any						):
						raise Exception(F'You cannot use ``pop`` on a {self.__class__.__name__} instance.'						)







					def 			__lowerCAmelCase					(			self     :							int  ,*lowercase_     :							List[str]  ,**lowercase_     :							int						):
						raise Exception(F'You cannot use ``update`` on a {self.__class__.__name__} instance.'						)







					def __getitem__(			self     :							Any  ,lowercase_     :							Any						):
						if isinstance(lowercase_  ,lowercase_						):
							lowerCAmelCase__      :		Optional[Any]    							=      dict(self.items()						)
							return inner_dict[k]
						else:
							return self.to_tuple()[k]







					def __setattr__(			self     :							Dict  ,lowercase_     :							Dict  ,lowercase_     :							int						):
						if name in self.keys() and value is not None:
							# Don't call self.__setitem__ to avoid recursion errors
							super().__setitem__(lowercase_  ,lowercase_						)
						super().__setattr__(lowercase_  ,lowercase_						)







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







					def 			__lowerCAmelCase					(			self     :							Optional[int]						):
						return tuple(self[k] for k in self.keys()						)







class 							SCREAMING_SNAKE_CASE   (						a_       ,				a_			):






					"""simple docstring"""



					@classmethod
					def 			__lowerCAmelCase					(			cls     :							Dict  ,lowercase_     :							Optional[Any]						):
						raise ValueError(
						    F'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()						)}'						)







class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					lowercase__												=			"longest"
					lowercase__												=			"max_length"
					lowercase__												=			"do_not_pad"







class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					lowercase__												=			"pt"
					lowercase__												=			"tf"
					lowercase__												=			"np"
					lowercase__												=			"jax"







class 							SCREAMING_SNAKE_CASE   :






					"""simple docstring"""



					def __init__(			self     :							List[Any]  ,lowercase_     :							List[ContextManager]						):
						lowerCAmelCase__      :		Optional[int]    							=      context_managers
						lowerCAmelCase__      :		Tuple    							=      ExitStack()







					def __enter__(			self     :							str						):
						for context_manager in self.context_managers:
							self.stack.enter_context(lowercase_						)







					def __exit__(			self     :							Tuple  ,*lowercase_     :							Tuple  ,**lowercase_     :							List[Any]						):
						self.stack.__exit__(*lowercase_  ,**lowercase_						)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	lowerCAmelCase__      :		Union[str, Any]    							=      infer_framework(A_					)
	if framework == "tf":
		lowerCAmelCase__      :		List[str]    							=      inspect.signature(model_class.call					)  # TensorFlow models
	elif framework == "pt":
		lowerCAmelCase__      :		Any    							=      inspect.signature(model_class.forward					)  # PyTorch models
	else:
		lowerCAmelCase__      :		Dict    							=      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     __SCREAMING_SNAKE_CASE    ( A_					):
	lowerCAmelCase__      :		List[str]    							=      model_class.__name__
	lowerCAmelCase__      :		List[Any]    							=      infer_framework(A_					)
	if framework == "tf":
		lowerCAmelCase__      :		Tuple    							=      inspect.signature(model_class.call					)  # TensorFlow models
	elif framework == "pt":
		lowerCAmelCase__      :		List[str]    							=      inspect.signature(model_class.forward					)  # PyTorch models
	else:
		lowerCAmelCase__      :		Optional[int]    							=      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     __SCREAMING_SNAKE_CASE    ( A_		,	A_ = ""		,	A_ = "."					):

	def _flatten_dict(A_		,	A_=""		,	A_="."					):
		for k, v in d.items():
			lowerCAmelCase__      :		Any    							=      str(A_					) + delimiter + str(A_					) if parent_key else k
			if v and isinstance(A_		,	A_					):
				yield from flatten_dict(A_		,	A_		,	delimiter=A_					).items()
			else:
				yield key, v

	return dict(_flatten_dict(A_		,	A_		,	A_					)					)

@contextmanager
def     __SCREAMING_SNAKE_CASE    ( A_		,	A_ = False					):
	if use_temp_dir:
		with tempfile.TemporaryDirectory() as tmp_dir:
			yield tmp_dir
	else:
		yield working_dir

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_=None					):
	if is_numpy_array(A_					):
		return np.transpose(A_		,	axes=A_					)
	elif is_torch_tensor(A_					):
		return array.T if axes is None else array.permute(*A_					)
	elif is_tf_tensor(A_					):
		import tensorflow as tf

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

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_					):
	if is_numpy_array(A_					):
		return np.reshape(A_		,	A_					)
	elif is_torch_tensor(A_					):
		return array.reshape(*A_					)
	elif is_tf_tensor(A_					):
		import tensorflow as tf

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

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_=None					):
	if is_numpy_array(A_					):
		return np.squeeze(A_		,	axis=A_					)
	elif is_torch_tensor(A_					):
		return array.squeeze() if axis is None else array.squeeze(dim=A_					)
	elif is_tf_tensor(A_					):
		import tensorflow as tf

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

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_					):
	if is_numpy_array(A_					):
		return np.expand_dims(A_		,	A_					)
	elif is_torch_tensor(A_					):
		return array.unsqueeze(dim=A_					)
	elif is_tf_tensor(A_					):
		import tensorflow as tf

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

def     __SCREAMING_SNAKE_CASE    ( A_					):
	if is_numpy_array(A_					):
		return np.size(A_					)
	elif is_torch_tensor(A_					):
		return array.numel()
	elif is_tf_tensor(A_					):
		import tensorflow as tf

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

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_					):
	for key, value in auto_map.items():
		if isinstance(A_		,	(tuple, list)					):
			lowerCAmelCase__      :		Tuple    							=      [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     __SCREAMING_SNAKE_CASE    ( A_					):
	for base_class in inspect.getmro(A_					):
		lowerCAmelCase__      :		List[str]    							=      base_class.__module__
		lowerCAmelCase__      :		List[Any]    							=      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}.'					)




