




'''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


a_      :		Optional[Any]							      =       """"""


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


     class   __UpperCamelCase       ( tr.AbstractTransform				):






            def __init__(							self,		lowerCAmelCase = " "  ):



                   """simple docstring"""







                   lowerCamelCase_							=sentence_delimiter






            def      lowercase__     (							self,		lowerCAmelCase  ):



                   """simple docstring"""







                   return list(lowerCAmelCase  )






            def      lowercase__     (							self,		lowerCAmelCase  ):



                   """simple docstring"""







                   lowerCamelCase_							=[]
                   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





     a_      :		Tuple							      =       tr.Compose(
         [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
     )
else:
     a_      :		Optional[Any]							      =       tr.Compose(
         [
             tr.RemoveMultipleSpaces(),
             tr.Strip(),
             tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
             tr.ReduceToListOfListOfChars(),
         ]
     )


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

a_      :		int							      =       """\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).

CER'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
performance of the ASR system with a CER of 0 being a perfect score.
"""

a_      :		List[Any]							      =       """
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]
    >>> references = [\"this is the reference\", \"there is another one\"]
    >>> cer = datasets.load_metric(\"cer\")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
"""


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






       def      lowercase__     (							self  ):



              """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'''  ),
                      }  ),		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      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase=False  ):



              """simple docstring"""







              if concatenate_texts:
                     return jiwer.compute_measures(
                         lowerCAmelCase,		lowerCAmelCase,		truth_transform=lowerCAmelCase,		hypothesis_transform=lowerCAmelCase,		)["wer"]

              lowerCamelCase_							=0
              lowerCamelCase_							=0
              for prediction, reference in zip(lowerCAmelCase,		lowerCAmelCase  ):
                     lowerCamelCase_							=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






# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor
from ..utils import is_datasets_available
from .base import PipelineTool


if is_datasets_available():
  from datasets import load_dataset

class __snake_case		(      lowerCAmelCase     ):
    _a		:						Union[str, Any]=				"microsoft/speecht5_tts"
    _a		:						Tuple=				(
        "This is a tool that reads an English text out loud. It takes an input named `text` which should contain the "
        "text to read (in English) and returns a waveform object containing the sound."
    )
    _a		:						Dict=				"text_reader"
    _a		:						Optional[Any]=				SpeechTaProcessor
    _a		:						Tuple=				SpeechTaForTextToSpeech
    _a		:						Optional[int]=				SpeechTaHifiGan

    _a		:						Union[str, Any]=				["text"]
    _a		:						Optional[int]=				["audio"]
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           if self.post_processor is None:
                  lowercase							:     Any       	=      """microsoft/speecht5_hifigan"""
           super().setup()
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=None      ):



           '''simple docstring'''







           lowercase							:     int       	=      self.pre_processor(text=snake_case		,return_tensors="""pt"""		,truncation=snake_case      )

           if speaker_embeddings is None:
                  if not is_datasets_available():
                         raise ImportError("""Datasets needs to be installed if not passing speaker embeddings."""      )

                  lowercase							:     Tuple       	=      load_dataset("""Matthijs/cmu-arctic-xvectors"""		,split="""validation"""      )
                  lowercase							:     List[str]       	=      torch.tensor(embeddings_dataset[7305]["""xvector"""]      ).unsqueeze(0      )

           return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings}
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           with torch.no_grad():
                  return self.model.generate_speech(**snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           with torch.no_grad():
                  return self.post_processor(snake_case      ).cpu().detach()
