





import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


_UpperCAmelCase        =				datasets.utils.logging.get_logger(__name__)

_UpperCAmelCase        =				['''names''', '''prefix''']
_UpperCAmelCase        =				['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']
_UpperCAmelCase        =				['''encoding_errors''', '''on_bad_lines''']
_UpperCAmelCase        =				['''date_format''']



@dataclass
class 							_UpperCamelCase					(	datasets.BuilderConfig     ):
							_UpperCamelCase				:					str         =   ","
							_UpperCamelCase				:					Optional[str]         =   None
							_UpperCamelCase				:					Optional[Union[int, List[int], str]]         =   "infer"
							_UpperCamelCase				:					Optional[List[str]]         =   None
							_UpperCamelCase				:					Optional[List[str]]         =   None
							_UpperCamelCase				:					Optional[Union[int, str, List[int], List[str]]]         =   None
							_UpperCamelCase				:					Optional[Union[List[int], List[str]]]         =   None
							_UpperCamelCase				:					Optional[str]         =   None
							_UpperCamelCase				:					bool         =   True
							_UpperCamelCase				:					Optional[Literal["c", "python", "pyarrow"]]         =   None
							_UpperCamelCase				:					Dict[Union[int, str], Callable[[Any], Any]]         =   None
							_UpperCamelCase				:					Optional[list]         =   None
							_UpperCamelCase				:					Optional[list]         =   None
							_UpperCamelCase				:					bool         =   False
							_UpperCamelCase				:					Optional[Union[int, List[int]]]         =   None
							_UpperCamelCase				:					Optional[int]         =   None
							_UpperCamelCase				:					Optional[Union[str, List[str]]]         =   None
							_UpperCamelCase				:					bool         =   True
							_UpperCamelCase				:					bool         =   True
							_UpperCamelCase				:					bool         =   False
							_UpperCamelCase				:					bool         =   True
							_UpperCamelCase				:					Optional[str]         =   None
							_UpperCamelCase				:					str         =   "."
							_UpperCamelCase				:					Optional[str]         =   None
							_UpperCamelCase				:					str         =   '"'
							_UpperCamelCase				:					int         =   0
							_UpperCamelCase				:					Optional[str]         =   None
							_UpperCamelCase				:					Optional[str]         =   None
							_UpperCamelCase				:					Optional[str]         =   None
							_UpperCamelCase				:					Optional[str]         =   None
							_UpperCamelCase				:					bool         =   True
							_UpperCamelCase				:					bool         =   True
							_UpperCamelCase				:					int         =   0
							_UpperCamelCase				:					bool         =   True
							_UpperCamelCase				:					bool         =   False
							_UpperCamelCase				:					Optional[str]         =   None
							_UpperCamelCase				:					int         =   1_0_0_0_0
							_UpperCamelCase				:					Optional[datasets.Features]         =   None
							_UpperCamelCase				:					Optional[str]         =   "strict"
							_UpperCamelCase				:					Literal["error", "warn", "skip"]         =   "error"
							_UpperCamelCase				:					Optional[str]         =   None

							def lowercase (		self: List[Any]		)       -> str:




														"""simple docstring"""


														if self.delimiter is not None:
																					UpperCamelCase_          =  self.delimiter
														if self.column_names is not None:
																					UpperCamelCase_          =  self.column_names



							@property
							def lowercase (		self: int		)       -> Dict:




														"""simple docstring"""


														UpperCamelCase_          =  {
														    "sep": self.sep,
														    "header": self.header,
														    "names": self.names,
														    "index_col": self.index_col,
														    "usecols": self.usecols,
														    "prefix": self.prefix,
														    "mangle_dupe_cols": self.mangle_dupe_cols,
														    "engine": self.engine,
														    "converters": self.converters,
														    "true_values": self.true_values,
														    "false_values": self.false_values,
														    "skipinitialspace": self.skipinitialspace,
														    "skiprows": self.skiprows,
														    "nrows": self.nrows,
														    "na_values": self.na_values,
														    "keep_default_na": self.keep_default_na,
														    "na_filter": self.na_filter,
														    "verbose": self.verbose,
														    "skip_blank_lines": self.skip_blank_lines,
														    "thousands": self.thousands,
														    "decimal": self.decimal,
														    "lineterminator": self.lineterminator,
														    "quotechar": self.quotechar,
														    "quoting": self.quoting,
														    "escapechar": self.escapechar,
														    "comment": self.comment,
														    "encoding": self.encoding,
														    "dialect": self.dialect,
														    "error_bad_lines": self.error_bad_lines,
														    "warn_bad_lines": self.warn_bad_lines,
														    "skipfooter": self.skipfooter,
														    "doublequote": self.doublequote,
														    "memory_map": self.memory_map,
														    "float_precision": self.float_precision,
														    "chunksize": self.chunksize,
														    "encoding_errors": self.encoding_errors,
														    "on_bad_lines": self.on_bad_lines,
														    "date_format": self.date_format,
														}

														# some kwargs must not be passed if they don't have a default value
														# some others are deprecated and we can also not pass them if they are the default value
														for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
																					if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()					,   __SCREAMING_SNAKE_CASE		):
																												del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
														if not (datasets.config.PANDAS_VERSION.major >= 2):
																					for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
																												del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
														if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
																					for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
																												del pd_read_csv_kwargs[pd_read_csv_parameter]

														return pd_read_csv_kwargs



class 							_UpperCamelCase					(	datasets.ArrowBasedBuilder     ):
							_UpperCamelCase				:					List[Any]         =   CsvConfig

							def lowercase (		self: List[Any]		)       -> int:




														"""simple docstring"""


														return datasets.DatasetInfo(features=self.config.features		)

							def lowercase (		self: List[str]					,   _SCREAMING_SNAKE_CASE: str		)       -> Dict:




														"""simple docstring"""


														if not self.config.data_files:
																					raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}'''		)
														UpperCamelCase_          =  dl_manager.download_and_extract(self.config.data_files		)
														if isinstance(__SCREAMING_SNAKE_CASE					,   (str, list, tuple)		):
																					UpperCamelCase_          =  data_files
																					if isinstance(__SCREAMING_SNAKE_CASE					,   __SCREAMING_SNAKE_CASE		):
																												UpperCamelCase_          =  [files]
																					UpperCamelCase_          =  [dl_manager.iter_files(__SCREAMING_SNAKE_CASE		) for file in files]
																					return [datasets.SplitGenerator(name=datasets.Split.TRAIN					,   gen_kwargs={"files": files}		)]
														UpperCamelCase_          =  []
														for split_name, files in data_files.items():
																					if isinstance(__SCREAMING_SNAKE_CASE					,   __SCREAMING_SNAKE_CASE		):
																												UpperCamelCase_          =  [files]
																					UpperCamelCase_          =  [dl_manager.iter_files(__SCREAMING_SNAKE_CASE		) for file in files]
																					splits.append(datasets.SplitGenerator(name=__SCREAMING_SNAKE_CASE					,   gen_kwargs={"files": files}		)		)
														return splits

							def lowercase (		self: Union[str, Any]					,   _SCREAMING_SNAKE_CASE: pa.Table		)       -> List[str]:




														"""simple docstring"""


														if self.config.features is not None:
																					UpperCamelCase_          =  self.config.features.arrow_schema
																					if all(not require_storage_cast(__SCREAMING_SNAKE_CASE		) for feature in self.config.features.values()		):
																												# cheaper cast
																												UpperCamelCase_          =  pa.Table.from_arrays([pa_table[field.name] for field in schema]					,   schema=__SCREAMING_SNAKE_CASE		)
																					else:
																												# more expensive cast; allows str <-> int/float or str to Audio for example
																												UpperCamelCase_          =  table_cast(__SCREAMING_SNAKE_CASE					,   __SCREAMING_SNAKE_CASE		)
														return pa_table



							def lowercase (		self: int					,   _SCREAMING_SNAKE_CASE: Optional[Any]		)       -> Optional[Any]:




														"""simple docstring"""


														UpperCamelCase_          =  self.config.features.arrow_schema if self.config.features else None
														# dtype allows reading an int column as str
														UpperCamelCase_          =  (
														    {
														        name: dtype.to_pandas_dtype() if not require_storage_cast(__SCREAMING_SNAKE_CASE		) else object
														        for name, dtype, feature in zip(schema.names					,   schema.types					,   self.config.features.values()		)
														    }
														    if schema is not None
														    else None
														)
														for file_idx, file in enumerate(itertools.chain.from_iterable(__SCREAMING_SNAKE_CASE		)		):
																					UpperCamelCase_          =  pd.read_csv(__SCREAMING_SNAKE_CASE					,   iterator=__SCREAMING_SNAKE_CASE					,   dtype=__SCREAMING_SNAKE_CASE					,   **self.config.pd_read_csv_kwargs		)
																					try:
																												for batch_idx, df in enumerate(__SCREAMING_SNAKE_CASE		):
																																			UpperCamelCase_          =  pa.Table.from_pandas(__SCREAMING_SNAKE_CASE		)
																																			# Uncomment for debugging (will print the Arrow table size and elements)
																																			# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																																			# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																																			yield (file_idx, batch_idx), self._cast_table(__SCREAMING_SNAKE_CASE		)
																					except ValueError as e:
																												logger.error(f'''Failed to read file \'{file}\' with error {type(__SCREAMING_SNAKE_CASE		)}: {e}'''		)
																												raise








import re
import string

import numpy as np

import datasets


_UpperCAmelCase        =				'\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'

_UpperCAmelCase        =				'\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'

_UpperCAmelCase        =				'\n'



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

       def lowercase (		self: Any		)       -> List[str]:




              """simple docstring"""


              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 lowercase (		self: Any					,   _SCREAMING_SNAKE_CASE: Any					,   _SCREAMING_SNAKE_CASE: Tuple					,   _SCREAMING_SNAKE_CASE: List[Any]=None					,   _SCREAMING_SNAKE_CASE: Tuple=False					,   _SCREAMING_SNAKE_CASE: Optional[int]=False					,   _SCREAMING_SNAKE_CASE: Any=False					,   )       -> Optional[Any]:




              """simple docstring"""


              if regexes_to_ignore is not None:
                     for s in regexes_to_ignore:
                            UpperCamelCase_          =  np.array([re.sub(_SCREAMING_SNAKE_CASE					,   ""					,   _SCREAMING_SNAKE_CASE		) for x in predictions]		)
                            UpperCamelCase_          =  np.array([re.sub(_SCREAMING_SNAKE_CASE					,   ""					,   _SCREAMING_SNAKE_CASE		) for x in references]		)
              else:
                     UpperCamelCase_          =  np.asarray(_SCREAMING_SNAKE_CASE		)
                     UpperCamelCase_          =  np.asarray(_SCREAMING_SNAKE_CASE		)

              if ignore_case:
                     UpperCamelCase_          =  np.char.lower(_SCREAMING_SNAKE_CASE		)
                     UpperCamelCase_          =  np.char.lower(_SCREAMING_SNAKE_CASE		)

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

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

              UpperCamelCase_          =  predictions == references

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

