

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 						__UpperCamelCase    (					lowercase						):




 def __get__(		self	:						List[str]		,	lowerCAmelCase	:						Union[str, Any]		,	lowerCAmelCase	:						List[str]=None							):


  '''simple docstring'''







  if obj is None:
   return self
  if self.fget is None:
   raise AttributeError("unreadable attribute"							)
  UpperCAmelCase_       				=			'''__cached_''' + self.fget.__name__
  UpperCAmelCase_       				=			getattr(UpperCAmelCase__		,	UpperCAmelCase__		,	UpperCAmelCase__							)
  if cached is None:
   UpperCAmelCase_       				=			self.fget(UpperCAmelCase__							)
   setattr(UpperCAmelCase__		,	UpperCAmelCase__		,	UpperCAmelCase__							)
  return cached



def       __lowerCAmelCase      (						A    ):
 UpperCAmelCase_       				=			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       __lowerCAmelCase      (						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       __lowerCAmelCase      (						A    ):
 return isinstance(A       ,     np.ndarray    )



def       __lowerCAmelCase      (						A    ):
 return _is_numpy(A    )



def       __lowerCAmelCase      (						A    ):
 import torch

 return isinstance(A       ,     torch.Tensor    )



def       __lowerCAmelCase      (						A    ):
 return False if not is_torch_available() else _is_torch(A    )



def       __lowerCAmelCase      (						A    ):
 import torch

 return isinstance(A       ,     torch.device    )



def       __lowerCAmelCase      (						A    ):
 return False if not is_torch_available() else _is_torch_device(A    )



def       __lowerCAmelCase      (						A    ):
 import torch

 if isinstance(A       ,     A    ):
  if hasattr(A       ,     A    ):
   UpperCAmelCase_       				=			getattr(A       ,     A    )
  else:
   return False
 return isinstance(A       ,     torch.dtype    )



def       __lowerCAmelCase      (						A    ):
 return False if not is_torch_available() else _is_torch_dtype(A    )



def       __lowerCAmelCase      (						A    ):
 import tensorflow as tf

 return isinstance(A       ,     tf.Tensor    )



def       __lowerCAmelCase      (						A    ):
 return False if not is_tf_available() else _is_tensorflow(A    )



def       __lowerCAmelCase      (						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       __lowerCAmelCase      (						A    ):
 return False if not is_tf_available() else _is_tf_symbolic_tensor(A    )



def       __lowerCAmelCase      (						A    ):
 import jax.numpy as jnp  # noqa: F811

 return isinstance(A       ,     jnp.ndarray    )



def       __lowerCAmelCase      (						A    ):
 return False if not is_flax_available() else _is_jax(A    )



def       __lowerCAmelCase      (						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       __lowerCAmelCase      (						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 						__UpperCamelCase    (					lowercase						):




 def       __A					(		self	:						Dict							):


  '''simple docstring'''







  UpperCAmelCase_       				=			fields(self							)

  # Safety and consistency checks
  if not len(UpperCAmelCase__							):
   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."							)

  UpperCAmelCase_       				=			getattr(self		,	class_fields[0].name							)
  UpperCAmelCase_       				=			all(getattr(self		,	field.name							) is None for field in class_fields[1:]							)

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




 def __delitem__(		self	:						Tuple		,	*lowerCAmelCase	:						Any		,	**lowerCAmelCase	:						Tuple							):


  '''simple docstring'''







  raise Exception(F"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."							)




 def       __A					(		self	:						Optional[Any]		,	*lowerCAmelCase	:						Any		,	**lowerCAmelCase	:						List[Any]							):


  '''simple docstring'''







  raise Exception(F"You cannot use ``setdefault`` on a {self.__class__.__name__} instance."							)




 def       __A					(		self	:						int		,	*lowerCAmelCase	:						Union[str, Any]		,	**lowerCAmelCase	:						Tuple							):


  '''simple docstring'''







  raise Exception(F"You cannot use ``pop`` on a {self.__class__.__name__} instance."							)




 def       __A					(		self	:						Optional[int]		,	*lowerCAmelCase	:						Tuple		,	**lowerCAmelCase	:						int							):


  '''simple docstring'''







  raise Exception(F"You cannot use ``update`` on a {self.__class__.__name__} instance."							)




 def __getitem__(		self	:						Optional[Any]		,	lowerCAmelCase	:						Tuple							):


  '''simple docstring'''







  if isinstance(UpperCAmelCase__		,	UpperCAmelCase__							):
   UpperCAmelCase_       				=			dict(self.items()							)
   return inner_dict[k]
  else:
   return self.to_tuple()[k]




 def __setattr__(		self	:						str		,	lowerCAmelCase	:						Optional[Any]		,	lowerCAmelCase	:						str							):


  '''simple docstring'''







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




 def __setitem__(		self	:						str		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						List[Any]							):


  '''simple docstring'''







  super().__setitem__(UpperCAmelCase__		,	UpperCAmelCase__							)
  # Don't call self.__setattr__ to avoid recursion errors
  super().__setattr__(UpperCAmelCase__		,	UpperCAmelCase__							)




 def       __A					(		self	:						List[Any]							):


  '''simple docstring'''







  return tuple(self[k] for k in self.keys()							)


class 						__UpperCamelCase    (					lowercase     ,     lowercase						):




 @classmethod
 def       __A					(		cls	:						str		,	lowerCAmelCase	:						str							):


  '''simple docstring'''







  raise ValueError(
      F"{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()							)}"							)


class 						__UpperCamelCase    (					lowercase						):
 SCREAMING_SNAKE_CASE__    				=     'longest'
 SCREAMING_SNAKE_CASE__    				=     'max_length'
 SCREAMING_SNAKE_CASE__    				=     'do_not_pad'


class 						__UpperCamelCase    (					lowercase						):
 SCREAMING_SNAKE_CASE__    				=     'pt'
 SCREAMING_SNAKE_CASE__    				=     'tf'
 SCREAMING_SNAKE_CASE__    				=     'np'
 SCREAMING_SNAKE_CASE__    				=     'jax'


class 						__UpperCamelCase    :




 def __init__(		self	:						List[str]		,	lowerCAmelCase	:						List[ContextManager]							):


  '''simple docstring'''







  UpperCAmelCase_       				=			context_managers
  UpperCAmelCase_       				=			ExitStack()




 def __enter__(		self	:						Tuple							):


  '''simple docstring'''







  for context_manager in self.context_managers:
   self.stack.enter_context(UpperCAmelCase__							)




 def __exit__(		self	:						int		,	*lowerCAmelCase	:						List[Any]		,	**lowerCAmelCase	:						Union[str, Any]							):


  '''simple docstring'''







  self.stack.__exit__(*UpperCAmelCase__		,	**UpperCAmelCase__							)



def       __lowerCAmelCase      (						A    ):
 UpperCAmelCase_       				=			infer_framework(A    )
 if framework == "tf":
  UpperCAmelCase_       				=			inspect.signature(model_class.call    )  # TensorFlow models
 elif framework == "pt":
  UpperCAmelCase_       				=			inspect.signature(model_class.forward    )  # PyTorch models
 else:
  UpperCAmelCase_       				=			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       __lowerCAmelCase      (						A    ):
 UpperCAmelCase_       				=			model_class.__name__
 UpperCAmelCase_       				=			infer_framework(A    )
 if framework == "tf":
  UpperCAmelCase_       				=			inspect.signature(model_class.call    )  # TensorFlow models
 elif framework == "pt":
  UpperCAmelCase_       				=			inspect.signature(model_class.forward    )  # PyTorch models
 else:
  UpperCAmelCase_       				=			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       __lowerCAmelCase      (						A       ,     A = ""       ,     A = "."    ):






 def _flatten_dict(A       ,     A=""       ,     A="."    ):
  for k, v in d.items():
   UpperCAmelCase_       				=			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       __lowerCAmelCase      (						A       ,     A = False    ):






 if use_temp_dir:
  with tempfile.TemporaryDirectory() as tmp_dir:
   yield tmp_dir
 else:
  yield working_dir



def       __lowerCAmelCase      (						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       __lowerCAmelCase      (						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       __lowerCAmelCase      (						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       __lowerCAmelCase      (						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       __lowerCAmelCase      (						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       __lowerCAmelCase      (						A       ,     A    ):






 for key, value in auto_map.items():
  if isinstance(A       ,     (tuple, list)    ):
   UpperCAmelCase_       				=			[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:
   UpperCAmelCase_       				=			F"{repo_id}--{value}"

 return auto_map




def       __lowerCAmelCase      (						A    ):






 for base_class in inspect.getmro(A    ):
  UpperCAmelCase_       				=			base_class.__module__
  UpperCAmelCase_       				=			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}."    )


from collections.abc import Sequence



def       __lowerCAmelCase      (						A       ,     A = False    ):
	if not arr:
		return 0

	UpperCAmelCase_       				=			0 if allow_empty_subarrays else float("-inf"    )
	UpperCAmelCase_       				=			0.0
	for num in arr:
		UpperCAmelCase_       				=			max(0 if allow_empty_subarrays else num       ,     curr_sum + num    )
		UpperCAmelCase_       				=			max(A       ,     A    )

	return max_sum


if __name__ == "__main__":
				from doctest import testmod

				testmod()

				_a:    Any 							=			[-2, 1, -3, 4, -1, 2, 1, -5, 4]
				print(F'{max_subarray_sum(nums) = }')