


'''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 					lowercase_     (    a__   ):


    def __get__(     self  ,					a  ,					a=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"    )
          UpperCamelCase__										=				"__cached_" + self.fget.__name__
          UpperCamelCase__										=				getattr(a  ,					a  ,					a    )
          if cached is None:
                UpperCamelCase__										=				self.fget(a    )
                setattr(a  ,					a  ,					a    )
          return cached







def _UpperCamelCase       (     __A    )							->		List[str]:


      '''simple docstring'''



      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 _UpperCamelCase       (     __A    )							->		List[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 _UpperCamelCase       (     __A    )							->		Tuple:


      '''simple docstring'''



      return isinstance(__A      ,			np.ndarray    )







def _UpperCamelCase       (     __A    )							->		Tuple:


      '''simple docstring'''



      return _is_numpy(__A    )







def _UpperCamelCase       (     __A    )							->		str:


      '''simple docstring'''



      import torch

      return isinstance(__A      ,			torch.Tensor    )







def _UpperCamelCase       (     __A    )							->		Dict:


      '''simple docstring'''



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







def _UpperCamelCase       (     __A    )							->		List[str]:


      '''simple docstring'''



      import torch

      return isinstance(__A      ,			torch.device    )







def _UpperCamelCase       (     __A    )							->		Any:


      '''simple docstring'''



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







def _UpperCamelCase       (     __A    )							->		str:


      '''simple docstring'''



      import torch

      if isinstance(__A      ,			__A    ):
            if hasattr(__A      ,			__A    ):
                  UpperCamelCase__										=				getattr(__A      ,			__A    )
            else:
                  return False
      return isinstance(__A      ,			torch.dtype    )







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


      '''simple docstring'''



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







def _UpperCamelCase       (     __A    )							->		List[str]:


      '''simple docstring'''



      import tensorflow as tf

      return isinstance(__A      ,			tf.Tensor    )







def _UpperCamelCase       (     __A    )							->		int:


      '''simple docstring'''



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







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


      '''simple docstring'''



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







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


      '''simple docstring'''



      import jax.numpy as jnp  # noqa: F811

      return isinstance(__A      ,			jnp.ndarray    )







def _UpperCamelCase       (     __A    )							->		int:


      '''simple docstring'''



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







def _UpperCamelCase       (     __A    )							->		Any:


      '''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 _UpperCamelCase       (     __A    )							->		str:


      '''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 					lowercase_     (    a__   ):


    def    __a							(     self    ):
          UpperCamelCase__										=				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.'''    )

          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(a    ):
                if isinstance(a  ,					a    ):
                      UpperCamelCase__										=				first_field.items()
                      UpperCamelCase__										=				True
                else:
                      try:
                            UpperCamelCase__										=				iter(a    )
                            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(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
                                        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  ,					*a  ,					**a    ):
          raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''    )


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


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


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


    def __getitem__(     self  ,					a    ):
          if isinstance(a  ,					a    ):
                UpperCamelCase__										=				dict(self.items()    )
                return inner_dict[k]
          else:
                return self.to_tuple()[k]


    def __setattr__(     self  ,					a  ,					a    ):
          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  ,					a  ,					a    ):
          # Will raise a KeyException if needed
          super().__setitem__(a  ,					a    )
          # Don't call self.__setattr__ to avoid recursion errors
          super().__setattr__(a  ,					a    )


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

class 					lowercase_     (    a__  ,						a__   ):


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

class 					lowercase_     (    a__   ):
    __UpperCAmelCase   			=	'longest'
    __UpperCAmelCase   			=	'max_length'
    __UpperCAmelCase   			=	'do_not_pad'

class 					lowercase_     (    a__   ):
    __UpperCAmelCase   			=	'pt'
    __UpperCAmelCase   			=	'tf'
    __UpperCAmelCase   			=	'np'
    __UpperCAmelCase   			=	'jax'

class 					lowercase_     :


    def __init__(     self  ,					a    ):
          UpperCamelCase__										=				context_managers
          UpperCamelCase__										=				ExitStack()


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


    def __exit__(     self  ,					*a  ,					**a    ):
          self.stack.__exit__(*a  ,					**a    )







def _UpperCamelCase       (     __A    )							->		Tuple:


      '''simple docstring'''



      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 _UpperCamelCase       (     __A    )							->		Tuple:


      '''simple docstring'''



      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 _UpperCamelCase       (     __A      ,			__A = ""      ,			__A = "."    )							->		Any:


      '''simple docstring'''



      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 _UpperCamelCase       (     __A      ,			__A = False    )							->		Any:


      '''simple docstring'''



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







def _UpperCamelCase       (     __A      ,			__A=None    )							->		Optional[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 _UpperCamelCase       (     __A      ,			__A    )							->		str:


      '''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 _UpperCamelCase       (     __A      ,			__A=None    )							->		Optional[Any]:


      '''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 _UpperCamelCase       (     __A      ,			__A    )							->		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 _UpperCamelCase       (     __A    )							->		str:


      '''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 _UpperCamelCase       (     __A      ,			__A    )							->		Dict:


      '''simple docstring'''



      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 _UpperCamelCase       (     __A    )							->		List[str]:


      '''simple docstring'''



      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}.'''    )












"""simple docstring"""





import re
import string

import numpy as np

import datasets


SCREAMING_SNAKE_CASE__					=   "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n"

SCREAMING_SNAKE_CASE__					=   "\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results[\"exact_match\"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n    >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results[\"exact_match\"], 1))\n    33.3\n\n"

SCREAMING_SNAKE_CASE__					=   "\n"

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,  _KWARGS_DESCRIPTION					)
class 		lowercase					(					datasets.Metric					):





      def     _snake_case			(       self )		->     Optional[int]:
            return datasets.MetricInfo(
                description=_DESCRIPTION      ,						citation=_CITATION      ,						inputs_description=_KWARGS_DESCRIPTION      ,						features=datasets.Features(
                    {
                        """predictions""": datasets.Value("""string"""      ,						id="""sequence""" ),
                        """references""": datasets.Value("""string"""      ,						id="""sequence""" ),
                    } )      ,						reference_urls=[]      ,						)





      def     _snake_case			(       self      ,						lowercase      ,						lowercase      ,						lowercase=None      ,						lowercase=False      ,						lowercase=False      ,						lowercase=False      ,						)		->     Optional[Any]:
            if regexes_to_ignore is not None:
                  for s in regexes_to_ignore:
                        lowerCAmelCase  						=       np.array([re.sub(lowercase      ,						""""""      ,						lowercase ) for x in predictions] )
                        lowerCAmelCase  						=       np.array([re.sub(lowercase      ,						""""""      ,						lowercase ) for x in references] )
            else:
                  lowerCAmelCase  						=       np.asarray(lowercase )
                  lowerCAmelCase  						=       np.asarray(lowercase )

            if ignore_case:
                  lowerCAmelCase  						=       np.char.lower(lowercase )
                  lowerCAmelCase  						=       np.char.lower(lowercase )

            if ignore_punctuation:
                  lowerCAmelCase  						=       string.punctuation.maketrans(""""""      ,						""""""      ,						string.punctuation )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )

            if ignore_numbers:
                  lowerCAmelCase  						=       string.digits.maketrans(""""""      ,						""""""      ,						string.digits )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )

            lowerCAmelCase  						=       predictions == references

            return {"exact_match": np.mean(lowercase ) * 100}






