






'''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 UpperCAmelCase_					(    lowercase__				):




      """simple docstring"""




      def __get__( self			:		Union[str, Any]     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		Any=None		)  ->  Any:


       '''simple docstring'''

       if obj is None:
        return self
       if self.fget is None:
        raise AttributeError('''unreadable attribute'''		)
       lowercase					:   Optional[int]				  ="__cached_" + self.fget.__name__
       lowercase					:   Optional[Any]				  =getattr(__lowerCamelCase     ,      __lowerCamelCase     ,      __lowerCamelCase		)
       if cached is None:
        lowercase					:   List[Any]				  =self.fget(__lowerCamelCase		)
        setattr(__lowerCamelCase     ,      __lowerCamelCase     ,      __lowerCamelCase		)
       return cached





def 							lowercase_				(    __A :       List[str]			)       ->      Optional[Any]:



 """simple docstring"""




 lowercase					:   List[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 							lowercase_				(    __A :       str			)       ->      Any:



 """simple docstring"""




 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 							lowercase_				(    __A :       int			)       ->      Union[str, Any]:



 """simple docstring"""




 return isinstance(_A					,      np.ndarray			)


def 							lowercase_				(    __A :       Dict			)       ->      Union[str, Any]:



 """simple docstring"""




 return _is_numpy(_A			)


def 							lowercase_				(    __A :       List[str]			)       ->      Any:



 """simple docstring"""




 import torch

 return isinstance(_A					,      torch.Tensor			)


def 							lowercase_				(    __A :       Any			)       ->      List[str]:



 """simple docstring"""




 return False if not is_torch_available() else _is_torch(_A			)


def 							lowercase_				(    __A :       str			)       ->      Union[str, Any]:



 """simple docstring"""




 import torch

 return isinstance(_A					,      torch.device			)


def 							lowercase_				(    __A :       Any			)       ->      Optional[Any]:



 """simple docstring"""




 return False if not is_torch_available() else _is_torch_device(_A			)


def 							lowercase_				(    __A :       int			)       ->      int:



 """simple docstring"""




 import torch

 if isinstance(_A					,      _A			):
  if hasattr(_A					,      _A			):
   lowercase					:   List[Any]				  =getattr(_A					,      _A			)
  else:
   return False
 return isinstance(_A					,      torch.dtype			)


def 							lowercase_				(    __A :       Tuple			)       ->      str:



 """simple docstring"""




 return False if not is_torch_available() else _is_torch_dtype(_A			)


def 							lowercase_				(    __A :       str			)       ->      Union[str, Any]:



 """simple docstring"""




 import tensorflow as tf

 return isinstance(_A					,      tf.Tensor			)


def 							lowercase_				(    __A :       Union[str, Any]			)       ->      Optional[Any]:



 """simple docstring"""




 return False if not is_tf_available() else _is_tensorflow(_A			)


def 							lowercase_				(    __A :       Dict			)       ->      List[Any]:



 """simple docstring"""




 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 							lowercase_				(    __A :       Optional[Any]			)       ->      Optional[int]:



 """simple docstring"""




 return False if not is_tf_available() else _is_tf_symbolic_tensor(_A			)


def 							lowercase_				(    __A :       Optional[int]			)       ->      List[str]:



 """simple docstring"""




 import jax.numpy as jnp  # noqa: F811

 return isinstance(_A					,      jnp.ndarray			)


def 							lowercase_				(    __A :       List[Any]			)       ->      str:



 """simple docstring"""




 return False if not is_flax_available() else _is_jax(_A			)


def 							lowercase_				(    __A :       Any			)       ->      List[str]:



 """simple docstring"""




 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 							lowercase_				(    __A :       List[Any]			)       ->      Tuple:



 """simple docstring"""




 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__				):




      """simple docstring"""




      def 				A__      ( self			:		Tuple		)  ->  Union[str, Any]:


       '''simple docstring'''

       lowercase					:   Optional[int]				  =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.'		)

       lowercase					:   str				  =getattr(self     ,      class_fields[0].name		)
       lowercase					:   List[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		):
         lowercase					:   Dict				  =first_field.items()
         lowercase					:   List[str]				  =True
        else:
         try:
          lowercase					:   Dict				  =iter(__lowerCamelCase		)
          lowercase					:   Dict				  =True
         except TypeError:
          lowercase					:   Optional[int]				  =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
            lowercase					:   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:
           lowercase					:   Optional[int]				  =element[1]
        elif first_field is not None:
         lowercase					:   str				  =first_field
       else:
        for field in class_fields:
         lowercase					:   str				  =getattr(self     ,      field.name		)
         if v is not None:
          lowercase					:   Any				  =v






      def __delitem__( self			:		Tuple     ,      *UpperCAmelCase			:		str     ,      **UpperCAmelCase			:		Union[str, Any]		)  ->  Optional[Any]:


       '''simple docstring'''

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






      def 				A__      ( self			:		Optional[int]     ,      *UpperCAmelCase			:		Tuple     ,      **UpperCAmelCase			:		Optional[int]		)  ->  Any:


       '''simple docstring'''

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






      def 				A__      ( self			:		Optional[int]     ,      *UpperCAmelCase			:		Any     ,      **UpperCAmelCase			:		int		)  ->  str:


       '''simple docstring'''

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






      def 				A__      ( self			:		str     ,      *UpperCAmelCase			:		Union[str, Any]     ,      **UpperCAmelCase			:		str		)  ->  Dict:


       '''simple docstring'''

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






      def __getitem__( self			:		int     ,      UpperCAmelCase			:		Any		)  ->  List[str]:


       '''simple docstring'''

       if isinstance(__lowerCamelCase     ,      __lowerCamelCase		):
        lowercase					:   List[str]				  =dict(self.items()		)
        return inner_dict[k]
       else:
        return self.to_tuple()[k]






      def __setattr__( self			:		List[str]     ,      UpperCAmelCase			:		Tuple     ,      UpperCAmelCase			:		Union[str, Any]		)  ->  Any:


       '''simple docstring'''

       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			:		Tuple     ,      UpperCAmelCase			:		Tuple     ,      UpperCAmelCase			:		List[str]		)  ->  Union[str, Any]:


       '''simple docstring'''

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






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


       '''simple docstring'''

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





class UpperCAmelCase_					(    lowercase__				,       lowercase__				):




      """simple docstring"""




      @classmethod
      def 				A__      ( cls			:		List[Any]     ,      UpperCAmelCase			:		List[str]		)  ->  Any:


       '''simple docstring'''

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





class UpperCAmelCase_					(    lowercase__				):




      """simple docstring"""




      UpperCamelCase_								=			'''longest'''
      UpperCamelCase_								=			'''max_length'''
      UpperCamelCase_								=			'''do_not_pad'''





class UpperCAmelCase_					(    lowercase__				):




      """simple docstring"""




      UpperCamelCase_								=			'''pt'''
      UpperCamelCase_								=			'''tf'''
      UpperCamelCase_								=			'''np'''
      UpperCamelCase_								=			'''jax'''





class UpperCAmelCase_					:




      """simple docstring"""




      def __init__( self			:		Tuple     ,      UpperCAmelCase			:		List[ContextManager]		)  ->  int:


       '''simple docstring'''

       lowercase					:   Optional[int]				  =context_managers
       lowercase					:   Dict				  =ExitStack()






      def __enter__( self			:		Dict		)  ->  int:


       '''simple docstring'''

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






      def __exit__( self			:		List[str]     ,      *UpperCAmelCase			:		Any     ,      **UpperCAmelCase			:		int		)  ->  int:


       '''simple docstring'''

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





def 							lowercase_				(    __A :       List[Any]			)       ->      Dict:



 """simple docstring"""




 lowercase					:   str				  =infer_framework(_A			)
 if framework == "tf":
  lowercase					:   Union[str, Any]				  =inspect.signature(model_class.call			)  # TensorFlow models
 elif framework == "pt":
  lowercase					:   Union[str, Any]				  =inspect.signature(model_class.forward			)  # PyTorch models
 else:
  lowercase					:   Optional[Any]				  =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 							lowercase_				(    __A :       Any			)       ->      Tuple:



 """simple docstring"""




 lowercase					:   Any				  =model_class.__name__
 lowercase					:   Optional[Any]				  =infer_framework(_A			)
 if framework == "tf":
  lowercase					:   Optional[int]				  =inspect.signature(model_class.call			)  # TensorFlow models
 elif framework == "pt":
  lowercase					:   Optional[Any]				  =inspect.signature(model_class.forward			)  # PyTorch models
 else:
  lowercase					:   Optional[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 							lowercase_				(    __A :       MutableMapping					,      __A :       str = ""					,      __A :       str = "."			)       ->      Any:



 """simple docstring"""




 def _flatten_dict(__A :       Optional[int]					,      __A :       Any=""					,      __A :       Any="."			):
  for k, v in d.items():
   lowercase					:   List[str]				  =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 							lowercase_				(    __A :       Dict					,      __A :       bool = False			)       ->      List[Any]:



 """simple docstring"""




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


def 							lowercase_				(    __A :       Optional[int]					,      __A :       Optional[int]=None			)       ->      Union[str, Any]:



 """simple docstring"""




 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 							lowercase_				(    __A :       Any					,      __A :       Any			)       ->      Union[str, Any]:



 """simple docstring"""




 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 							lowercase_				(    __A :       Dict					,      __A :       int=None			)       ->      Tuple:



 """simple docstring"""




 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 							lowercase_				(    __A :       Any					,      __A :       Union[str, Any]			)       ->      List[str]:



 """simple docstring"""




 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 							lowercase_				(    __A :       int			)       ->      Any:



 """simple docstring"""




 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 							lowercase_				(    __A :       Tuple					,      __A :       Tuple			)       ->      Optional[Any]:



 """simple docstring"""




 for key, value in auto_map.items():
  if isinstance(_A					,      (tuple, list)			):
   lowercase					:   Optional[Any]				  =[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					:   Tuple				  =F'{repo_id}--{value}'

 return auto_map





def 							lowercase_				(    __A :       Dict			)       ->      List[str]:



 """simple docstring"""




 for base_class in inspect.getmro(_A			):
  lowercase					:   Optional[int]				  =base_class.__module__
  lowercase					:   List[str]				  =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}.'			)











'''simple docstring'''



import re


def 							lowercase_				(    __A :       str			)       ->      bool:



 """simple docstring"""




 lowercase					:   Any				  =re.compile(R'''^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$'''			)
 if match := re.search(__A					,      __A			):
  return match.string == phone
 return False


if __name__ == "__main__":
      print(indian_phone_validator('+918827897895'))



