





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 				A_				(      UpperCAmelCase	):







       """simple docstring"""





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

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[int]     )      ->						Optional[int]:
  _lowercase							= 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__       (  snake_case__  :Tuple     )      ->						List[str]:
  if is_torch_fx_proxy(snake_case__     ):
    return True
  if is_torch_available():
    import torch

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

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

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

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

  return isinstance(snake_case__			,							np.ndarray     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :str     )      ->						Dict:
  return isinstance(snake_case__			,							np.ndarray     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :List[Any]     )      ->						Any:
  return _is_numpy(snake_case__     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Dict     )      ->						Optional[int]:
  import torch

  return isinstance(snake_case__			,							torch.Tensor     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :List[Any]     )      ->						Union[str, Any]:
  return False if not is_torch_available() else _is_torch(snake_case__     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Tuple     )      ->						List[str]:
  import torch

  return isinstance(snake_case__			,							torch.device     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[Any]     )      ->						int:
  return False if not is_torch_available() else _is_torch_device(snake_case__     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Union[str, Any]     )      ->						List[Any]:
  import torch

  if isinstance(snake_case__			,							snake_case__     ):
    if hasattr(snake_case__			,							snake_case__     ):
      _lowercase							= getattr(snake_case__			,							snake_case__     )
    else:
      return False
  return isinstance(snake_case__			,							torch.dtype     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :str     )      ->						Dict:
  return False if not is_torch_available() else _is_torch_dtype(snake_case__     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[Any]     )      ->						List[Any]:
  import tensorflow as tf

  return isinstance(snake_case__			,							tf.Tensor     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :int     )      ->						Union[str, Any]:
  return False if not is_tf_available() else _is_tensorflow(snake_case__     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :List[str]     )      ->						Tuple:
  import tensorflow as tf

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

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[int]     )      ->						Tuple:
  return False if not is_tf_available() else _is_tf_symbolic_tensor(snake_case__     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :List[str]     )      ->						Optional[int]:
  import jax.numpy as jnp  # noqa: F811

  return isinstance(snake_case__			,							jnp.ndarray     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Any     )      ->						Optional[Any]:
  return False if not is_flax_available() else _is_jax(snake_case__     )

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

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[Any]     )      ->						Dict:
  if isinstance(snake_case__			,							(dict, UserDict)     ):
    return {k: to_numpy(snake_case__     ) for k, v in obj.items()}
  elif isinstance(snake_case__			,							(list, tuple)     ):
    return np.array(snake_case__     )
  elif is_tf_tensor(snake_case__     ):
    return obj.numpy()
  elif is_torch_tensor(snake_case__     ):
    return obj.detach().cpu().numpy()
  elif is_jax_tensor(snake_case__     ):
    return np.asarray(snake_case__     )
  else:
    return obj





class 				A_				(      UpperCAmelCase	):







       """simple docstring"""





       def    __UpperCAmelCase (    self	:	List[Any]  )						->					List[str]:
         _lowercase							= fields(self  )

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

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

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







       def __delitem__(    self	:	List[str]						,*__A	:	Dict						,**__A	:	Tuple  )						->					List[Any]:
         raise Exception(F"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""  )







       def    __UpperCAmelCase (    self	:	Optional[int]						,*__A	:	Tuple						,**__A	:	Dict  )						->					List[str]:
         raise Exception(F"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance."""  )







       def    __UpperCAmelCase (    self	:	List[Any]						,*__A	:	List[str]						,**__A	:	str  )						->					Optional[Any]:
         raise Exception(F"""You cannot use ``pop`` on a {self.__class__.__name__} instance."""  )







       def    __UpperCAmelCase (    self	:	List[Any]						,*__A	:	List[Any]						,**__A	:	Union[str, Any]  )						->					Any:
         raise Exception(F"""You cannot use ``update`` on a {self.__class__.__name__} instance."""  )







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







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







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







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





class 				A_				(      UpperCAmelCase					,	UpperCAmelCase	):







       """simple docstring"""





       @classmethod
       def    __UpperCAmelCase (    cls	:	str						,__A	:	int  )						->					List[str]:
         raise ValueError(
             F"""{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()  )}"""  )





class 				A_				(      UpperCAmelCase	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Any      =  '''longest'''
       SCREAMING_SNAKE_CASE_      : Optional[int]      =  '''max_length'''
       SCREAMING_SNAKE_CASE_      : Union[str, Any]      =  '''do_not_pad'''





class 				A_				(      UpperCAmelCase	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Tuple      =  '''pt'''
       SCREAMING_SNAKE_CASE_      : Union[str, Any]      =  '''tf'''
       SCREAMING_SNAKE_CASE_      : List[str]      =  '''np'''
       SCREAMING_SNAKE_CASE_      : Any      =  '''jax'''





class 				A_				:







       """simple docstring"""





       def __init__(    self	:	List[str]						,__A	:	List[ContextManager]  )						->					List[str]:
         _lowercase							= context_managers
         _lowercase							= ExitStack()







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







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

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Any     )      ->						str:
  _lowercase							= infer_framework(snake_case__     )
  if framework == "tf":
    _lowercase							= inspect.signature(model_class.call     )  # TensorFlow models
  elif framework == "pt":
    _lowercase							= inspect.signature(model_class.forward     )  # PyTorch models
  else:
    _lowercase							= 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__       (  snake_case__  :Union[str, Any]     )      ->						str:
  _lowercase							= model_class.__name__
  _lowercase							= infer_framework(snake_case__     )
  if framework == "tf":
    _lowercase							= inspect.signature(model_class.call     )  # TensorFlow models
  elif framework == "pt":
    _lowercase							= inspect.signature(model_class.forward     )  # PyTorch models
  else:
    _lowercase							= 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__       (  snake_case__  :MutableMapping			,							snake_case__  :str = ""			,							snake_case__  :str = "."     )      ->						List[str]:

  def _flatten_dict(snake_case__  :Tuple			,							snake_case__  :Tuple=""			,							snake_case__  :List[Any]="."     ):
    for k, v in d.items():
      _lowercase							= str(snake_case__     ) + delimiter + str(snake_case__     ) if parent_key else k
      if v and isinstance(snake_case__			,							snake_case__     ):
        yield from flatten_dict(snake_case__			,							snake_case__			,							delimiter=snake_case__     ).items()
      else:
        yield key, v

  return dict(_flatten_dict(snake_case__			,							snake_case__			,							snake_case__     )     )

@contextmanager
def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[int]			,							snake_case__  :bool = False     )      ->						str:
  if use_temp_dir:
    with tempfile.TemporaryDirectory() as tmp_dir:
      yield tmp_dir
  else:
    yield working_dir

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :List[str]			,							snake_case__  :Union[str, Any]=None     )      ->						Tuple:
  if is_numpy_array(snake_case__     ):
    return np.transpose(snake_case__			,							axes=snake_case__     )
  elif is_torch_tensor(snake_case__     ):
    return array.T if axes is None else array.permute(*snake_case__     )
  elif is_tf_tensor(snake_case__     ):
    import tensorflow as tf

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

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Dict			,							snake_case__  :Tuple     )      ->						Union[str, Any]:
  if is_numpy_array(snake_case__     ):
    return np.reshape(snake_case__			,							snake_case__     )
  elif is_torch_tensor(snake_case__     ):
    return array.reshape(*snake_case__     )
  elif is_tf_tensor(snake_case__     ):
    import tensorflow as tf

    return tf.reshape(snake_case__			,							snake_case__     )
  elif is_jax_tensor(snake_case__     ):
    return jnp.reshape(snake_case__			,							snake_case__     )
  else:
    raise ValueError(F"""Type not supported for reshape: {type(snake_case__     )}."""     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Tuple			,							snake_case__  :int=None     )      ->						Dict:
  if is_numpy_array(snake_case__     ):
    return np.squeeze(snake_case__			,							axis=snake_case__     )
  elif is_torch_tensor(snake_case__     ):
    return array.squeeze() if axis is None else array.squeeze(dim=snake_case__     )
  elif is_tf_tensor(snake_case__     ):
    import tensorflow as tf

    return tf.squeeze(snake_case__			,							axis=snake_case__     )
  elif is_jax_tensor(snake_case__     ):
    return jnp.squeeze(snake_case__			,							axis=snake_case__     )
  else:
    raise ValueError(F"""Type not supported for squeeze: {type(snake_case__     )}."""     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :str			,							snake_case__  :Tuple     )      ->						str:
  if is_numpy_array(snake_case__     ):
    return np.expand_dims(snake_case__			,							snake_case__     )
  elif is_torch_tensor(snake_case__     ):
    return array.unsqueeze(dim=snake_case__     )
  elif is_tf_tensor(snake_case__     ):
    import tensorflow as tf

    return tf.expand_dims(snake_case__			,							axis=snake_case__     )
  elif is_jax_tensor(snake_case__     ):
    return jnp.expand_dims(snake_case__			,							axis=snake_case__     )
  else:
    raise ValueError(F"""Type not supported for expand_dims: {type(snake_case__     )}."""     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Dict     )      ->						Optional[Any]:
  if is_numpy_array(snake_case__     ):
    return np.size(snake_case__     )
  elif is_torch_tensor(snake_case__     ):
    return array.numel()
  elif is_tf_tensor(snake_case__     ):
    import tensorflow as tf

    return tf.size(snake_case__     )
  elif is_jax_tensor(snake_case__     ):
    return array.size
  else:
    raise ValueError(F"""Type not supported for expand_dims: {type(snake_case__     )}."""     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Tuple			,							snake_case__  :Dict     )      ->						Optional[Any]:
  for key, value in auto_map.items():
    if isinstance(snake_case__			,							(tuple, list)     ):
      _lowercase							= [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:
      _lowercase							= F"""{repo_id}--{value}"""

  return auto_map







def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[int]     )      ->						Union[str, Any]:
  for base_class in inspect.getmro(snake_case__     ):
    _lowercase							= base_class.__module__
    _lowercase							= 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 itertools import count

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :int = 50     )      ->						int:
  _lowercase							= [1] * min_block_length

  for n in count(snake_case__     ):
    fill_count_functions.append(1     )

    for block_length in range(snake_case__			,							n + 1     ):
      for block_start in range(n - block_length     ):
        fill_count_functions[n] += fill_count_functions[
            n - block_start - block_length - 1
        ]

      fill_count_functions[n] += 1

    if fill_count_functions[n] > 100_0000:
      break

  return n


if __name__ == "__main__":
      print(F"""{solution() = }""")