





import multiprocessing
from typing import TYPE_CHECKING, Optional, Union

from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream


if TYPE_CHECKING:
    import sqlitea

    import sqlalchemy

class 		SCREAMING_SNAKE_CASE__    (	snake_case_  ):


      def __init__(self	:				str    ,      a__	:				Optional[int]    ,      a__	:				Optional[Any]    ,      a__	:				Tuple = None    ,      a__	:				Dict = None    ,      a__	:				Optional[int] = False    ,      **a__	:				List[Any]    ,      ):





         """simple docstring"""



         super().__init__(features=a__    ,      cache_dir=a__    ,      keep_in_memory=a__    ,      **a__				)
         __snake_case								=       Sql(
             cache_dir=a__    ,      features=a__    ,      sql=a__    ,      con=a__    ,      **a__    ,      )


      def        a			(self	:				Tuple				):





         """simple docstring"""



         __snake_case								=       None
         __snake_case								=       None
         __snake_case								=       None
         __snake_case								=       None

         self.builder.download_and_prepare(
             download_config=a__    ,      download_mode=a__    ,      verification_mode=a__    ,      base_path=a__    ,      )

         # Build dataset for splits
         __snake_case								=       self.builder.as_dataset(
             split='''train'''    ,      verification_mode=a__    ,      in_memory=self.keep_in_memory				)
         return dataset






class 		SCREAMING_SNAKE_CASE__    :


      def __init__(self	:				Optional[Any]    ,      a__	:				Optional[int]    ,      a__	:				List[Any]    ,      a__	:				List[str]    ,      a__	:				str = None    ,      a__	:				int = None    ,      **a__	:				Optional[int]    ,      ):





         """simple docstring"""



         if num_proc is not None and num_proc <= 0:
            raise ValueError(f"""num_proc {num_proc} must be an integer > 0."""				)

         __snake_case								=       dataset
         __snake_case								=       name
         __snake_case								=       con
         __snake_case								=       batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
         __snake_case								=       num_proc
         __snake_case								=       to_sql_kwargs


      def        a			(self	:				List[Any]				):





         """simple docstring"""



         __snake_case								=       self.to_sql_kwargs.pop('''sql'''    ,      a__				)
         __snake_case								=       self.to_sql_kwargs.pop('''con'''    ,      a__				)
         __snake_case								=       self.to_sql_kwargs.pop('''index'''    ,      a__				)

         __snake_case								=       self._write(index=a__    ,      **self.to_sql_kwargs				)
         return written


      def        a			(self	:				str    ,      a__	:				List[str]				):





         """simple docstring"""



         __snake_case	,     __snake_case	,     __snake_case								=       args
         __snake_case								=       {**to_sql_kwargs, '''if_exists''': '''append'''} if offset > 0 else to_sql_kwargs
         __snake_case								=       query_table(
             table=self.dataset.data    ,      key=slice(a__    ,      offset + self.batch_size				)    ,      indices=self.dataset._indices    ,      )
         __snake_case								=       batch.to_pandas()
         __snake_case								=       df.to_sql(self.name    ,      self.con    ,      index=a__    ,      **a__				)
         return num_rows or len(a__				)


      def        a			(self	:				Optional[int]    ,      a__	:				List[str]    ,      **a__	:				List[Any]				):





         """simple docstring"""



         __snake_case								=       0

         if self.num_proc is None or self.num_proc == 1:
            for offset in logging.tqdm(
                range(0    ,      len(self.dataset				)    ,      self.batch_size				)    ,      unit='''ba'''    ,      disable=not logging.is_progress_bar_enabled()    ,      desc='''Creating SQL from Arrow format'''    ,      ):
               written += self._batch_sql((offset, index, to_sql_kwargs)				)
         else:
            __snake_case	,     __snake_case								=       len(self.dataset				), self.batch_size
            with multiprocessing.Pool(self.num_proc				) as pool:
               for num_rows in logging.tqdm(
                   pool.imap(
                       self._batch_sql    ,      [(offset, index, to_sql_kwargs) for offset in range(0    ,      a__    ,      a__				)]    ,      )    ,      total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size    ,      unit='''ba'''    ,      disable=not logging.is_progress_bar_enabled()    ,      desc='''Creating SQL from Arrow format'''    ,      ):
                  written += num_rows

         return written








import re
import string

import numpy as np

import datasets


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'

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'

snake_case_           =      '\n'

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


      def        a			(self	:				Optional[Any]				):





         """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        a			(self	:				List[Any]    ,      a__	:				int    ,      a__	:				Optional[int]    ,      a__	:				Optional[Any]=None    ,      a__	:				Any=False    ,      a__	:				Dict=False    ,      a__	:				Tuple=False    ,      ):





         """simple docstring"""



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

         if ignore_case:
            __snake_case								=       np.char.lower(a__				)
            __snake_case								=       np.char.lower(a__				)

         if ignore_punctuation:
            __snake_case								=       string.punctuation.maketrans(''''''    ,      ''''''    ,      string.punctuation				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)

         if ignore_numbers:
            __snake_case								=       string.digits.maketrans(''''''    ,      ''''''    ,      string.digits				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)

         __snake_case								=       predictions == references

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

