




"""simple docstring"""







from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('3.8'):
  import importlib_metadata
else:
  import importlib.metadata as importlib_metadata


SCREAMING_SNAKE_CASE_	     =       ''


if version.parse(importlib_metadata.version('jiwer')) < version.parse('2.3.0'):

  class 				snake_case_			(					tr.AbstractTransform			):







     """simple docstring"""




     def __init__(		self       ,					lowerCamelCase_ = " ")				->   List[str]:
         UpperCamelCase              =	sentence_delimiter







     def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   Tuple:
         return list(lowerCamelCase_)







     def   UpperCAmelCase__			(		self       ,					lowerCamelCase_)				->   Optional[Any]:
         UpperCamelCase              =	[]
         for sent_idx, sentence in enumerate(lowerCamelCase_):
             chars.extend(self.process_string(lowerCamelCase_))
             if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(lowerCamelCase_) - 1:
                 chars.append(self.sentence_delimiter)
         return chars
  SCREAMING_SNAKE_CASE_	     =       tr.Compose(
      [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
  )
else:
  SCREAMING_SNAKE_CASE_	     =       tr.Compose(
      [
          tr.RemoveMultipleSpaces(),
          tr.Strip(),
          tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
          tr.ReduceToListOfListOfChars(),
      ]
  )


SCREAMING_SNAKE_CASE_	     =       '\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n'

SCREAMING_SNAKE_CASE_	     =       '\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n'

SCREAMING_SNAKE_CASE_	     =       '\nComputes CER score of transcribed segments against references.\nArgs:\n    references: list of references for each speech input.\n    predictions: list of transcribtions to score.\n    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n    (float): the character error rate\n\nExamples:\n\n    >>> predictions = ["this is the prediction", "there is an other sample"]\n    >>> references = ["this is the reference", "there is another one"]\n    >>> cer = datasets.load_metric("cer")\n    >>> cer_score = cer.compute(predictions=predictions, references=references)\n    >>> print(cer_score)\n    0.34146341463414637\n'

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







   """simple docstring"""




   def   UpperCAmelCase__			(		self)				->   Dict:
       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'''),
               })       ,					codebase_urls=['''https://github.com/jitsi/jiwer/''']       ,					reference_urls=[
               '''https://en.wikipedia.org/wiki/Word_error_rate''',
               '''https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates''',
           ]       ,					)







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_=False)				->   List[Any]:
       if concatenate_texts:
           return jiwer.compute_measures(
               lowerCamelCase_       ,					lowerCamelCase_       ,					truth_transform=lowerCamelCase_       ,					hypothesis_transform=lowerCamelCase_       ,					)["wer"]

       UpperCamelCase              =	0
       UpperCamelCase              =	0
       for prediction, reference in zip(lowerCamelCase_       ,					lowerCamelCase_):
           UpperCamelCase              =	jiwer.compute_measures(
               lowerCamelCase_       ,					lowerCamelCase_       ,					truth_transform=lowerCamelCase_       ,					hypothesis_transform=lowerCamelCase_       ,					)
           incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
           total += measures["substitutions"] + measures["deletions"] + measures["hits"]

       return incorrect / total






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     A     (SCREAMING_SNAKE_CASE       ):
			'''simple docstring'''




			def __init__(     self  :       Any				,      __lowerCAmelCase  :       Union[str, "sqlalchemy.sql.Selectable"]				,      __lowerCAmelCase  :       Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]				,      __lowerCAmelCase  :       Optional[Features] = None				,      __lowerCAmelCase  :       str = None				,      __lowerCAmelCase  :       bool = False				,      **__lowerCAmelCase  :       Dict				,      )      ->      Any:







					"""simple docstring"""






					super().__init__(features=__lowerCAmelCase				,      cache_dir=__lowerCAmelCase				,      keep_in_memory=__lowerCAmelCase				,      **__lowerCAmelCase  )
					A__     =  Sql(
					    cache_dir=__lowerCAmelCase				,      features=__lowerCAmelCase				,      sql=__lowerCAmelCase				,      con=__lowerCAmelCase				,      **__lowerCAmelCase				,      )







			def   a_			(     self  :       Optional[int]  )      ->      Optional[int]:







					"""simple docstring"""






					A__     =  None
					A__     =  None
					A__     =  None
					A__     =  None

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

					# Build dataset for splits
					A__     =  self.builder.as_dataset(
					    split="""train"""				,      verification_mode=__lowerCAmelCase				,      in_memory=self.keep_in_memory  )
					return dataset


class     A     :
			'''simple docstring'''




			def __init__(     self  :       Optional[int]				,      __lowerCAmelCase  :       Dataset				,      __lowerCAmelCase  :       str				,      __lowerCAmelCase  :       Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]				,      __lowerCAmelCase  :       Optional[int] = None				,      __lowerCAmelCase  :       Optional[int] = None				,      **__lowerCAmelCase  :       List[Any]				,      )      ->      Any:







					"""simple docstring"""






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

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






			def   a_			(     self  :       Any  )      ->      int:







					"""simple docstring"""






					A__     =  self.to_sql_kwargs.pop("""sql"""				,      __lowerCAmelCase  )
					A__     =  self.to_sql_kwargs.pop("""con"""				,      __lowerCAmelCase  )
					A__     =  self.to_sql_kwargs.pop("""index"""				,      __lowerCAmelCase  )

					A__     =  self._write(index=__lowerCAmelCase				,      **self.to_sql_kwargs  )
					return written






			def   a_			(     self  :       Union[str, Any]				,      __lowerCAmelCase  :       Optional[Any]  )      ->      Optional[Any]:







					"""simple docstring"""






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







			def   a_			(     self  :       Optional[int]				,      __lowerCAmelCase  :       Tuple				,      **__lowerCAmelCase  :       Dict  )      ->      int:







					"""simple docstring"""






					A__     =  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:
							A__ ,     A__     =  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				,      __lowerCAmelCase				,      __lowerCAmelCase  )]				,      )				,      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



