"""simple docstring"""






from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


__A			   = logging.get_logger(__name__)


class     UpperCAmelCase						(_UpperCAmelCase  ):



    """simple docstring"""

    _UpperCAmelCase	:str						    = ["pixel_values"]






    def __init__(   self    ,			_UpperCAmelCase = True    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = PILImageResampling.BILINEAR    ,			_UpperCAmelCase = True    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = True    ,			_UpperCAmelCase = 1 / 255    ,			_UpperCAmelCase = True    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			**_UpperCAmelCase    ,			):
       super().__init__(**_UpperCAmelCase							)
       lowercase__:   Optional[int]					=      size if size is not None else {'''shortest_edge''': 256}
       lowercase__:   Any					=      get_size_dict(_UpperCAmelCase    ,			default_to_square=_UpperCAmelCase							)
       lowercase__:   Optional[Any]					=      crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
       lowercase__:   str					=      get_size_dict(_UpperCAmelCase							)
       lowercase__:   int					=      do_resize
       lowercase__:   str					=      size
       lowercase__:   Dict					=      resample
       lowercase__:   Dict					=      do_center_crop
       lowercase__:   List[Any]					=      crop_size
       lowercase__:   str					=      do_rescale
       lowercase__:   str					=      rescale_factor
       lowercase__:   List[str]					=      do_normalize
       lowercase__:   List[Any]					=      image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       lowercase__:   List[Any]					=      image_std if image_std is not None else IMAGENET_STANDARD_STD






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase = PILImageResampling.BICUBIC    ,			_UpperCAmelCase = None    ,			**_UpperCAmelCase    ,			):
       lowercase__:   str					=      get_size_dict(_UpperCAmelCase    ,			default_to_square=_UpperCAmelCase							)
       if "shortest_edge" not in size:
          raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""							)
       lowercase__:   List[str]					=      get_resize_output_image_size(_UpperCAmelCase    ,			size=size['''shortest_edge''']    ,			default_to_square=_UpperCAmelCase							)
       return resize(_UpperCAmelCase    ,			size=_UpperCAmelCase    ,			resample=_UpperCAmelCase    ,			data_format=_UpperCAmelCase    ,			**_UpperCAmelCase							)






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase = None    ,			**_UpperCAmelCase    ,			):
       lowercase__:   List[Any]					=      get_size_dict(_UpperCAmelCase							)
       return center_crop(_UpperCAmelCase    ,			size=(size['''height'''], size['''width'''])    ,			data_format=_UpperCAmelCase    ,			**_UpperCAmelCase							)






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase = None    ,			**_UpperCAmelCase							):
       return rescale(_UpperCAmelCase    ,			scale=_UpperCAmelCase    ,			data_format=_UpperCAmelCase    ,			**_UpperCAmelCase							)






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase = None    ,			**_UpperCAmelCase    ,			):
       return normalize(_UpperCAmelCase    ,			mean=_UpperCAmelCase    ,			std=_UpperCAmelCase    ,			data_format=_UpperCAmelCase    ,			**_UpperCAmelCase							)






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = None    ,			_UpperCAmelCase = ChannelDimension.FIRST    ,			**_UpperCAmelCase    ,			):
       lowercase__:   Any					=      do_resize if do_resize is not None else self.do_resize
       lowercase__:   Optional[Any]					=      size if size is not None else self.size
       lowercase__:   Tuple					=      get_size_dict(_UpperCAmelCase    ,			default_to_square=_UpperCAmelCase							)
       lowercase__:   Any					=      resample if resample is not None else self.resample
       lowercase__:   int					=      do_center_crop if do_center_crop is not None else self.do_center_crop
       lowercase__:   int					=      crop_size if crop_size is not None else self.crop_size
       lowercase__:   Optional[int]					=      get_size_dict(_UpperCAmelCase							)
       lowercase__:   str					=      do_rescale if do_rescale is not None else self.do_rescale
       lowercase__:   Union[str, Any]					=      rescale_factor if rescale_factor is not None else self.rescale_factor
       lowercase__:   List[str]					=      do_normalize if do_normalize is not None else self.do_normalize
       lowercase__:   Dict					=      image_mean if image_mean is not None else self.image_mean
       lowercase__:   List[Any]					=      image_std if image_std is not None else self.image_std

       lowercase__:   Dict					=      make_list_of_images(_UpperCAmelCase							)

       if not valid_images(_UpperCAmelCase							):
          raise ValueError(
              '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
              '''torch.Tensor, tf.Tensor or jax.ndarray.'''							)

       if do_resize and size is None:
          raise ValueError('''Size must be specified if do_resize is True.'''							)

       if do_center_crop and crop_size is None:
          raise ValueError('''Crop size must be specified if do_center_crop is True.'''							)

       if do_rescale and rescale_factor is None:
          raise ValueError('''Rescale factor must be specified if do_rescale is True.'''							)

       if do_normalize and (image_mean is None or image_std is None):
          raise ValueError('''Image mean and std must be specified if do_normalize is True.'''							)

       # All transformations expect numpy arrays.
       lowercase__:   List[Any]					=      [to_numpy_array(_UpperCAmelCase							) for image in images]

       if do_resize:
          lowercase__:   int					=      [self.resize(image=_UpperCAmelCase    ,			size=_UpperCAmelCase    ,			resample=_UpperCAmelCase							) for image in images]

       if do_center_crop:
          lowercase__:   Optional[Any]					=      [self.center_crop(image=_UpperCAmelCase    ,			size=_UpperCAmelCase							) for image in images]

       if do_rescale:
          lowercase__:   Dict					=      [self.rescale(image=_UpperCAmelCase    ,			scale=_UpperCAmelCase							) for image in images]

       if do_normalize:
          lowercase__:   List[str]					=      [self.normalize(image=_UpperCAmelCase    ,			mean=_UpperCAmelCase    ,			std=_UpperCAmelCase							) for image in images]

       lowercase__:   int					=      [to_channel_dimension_format(_UpperCAmelCase    ,			_UpperCAmelCase							) for image in images]

       lowercase__:   List[Any]					=      {'''pixel_values''': images}
       return BatchFeature(data=_UpperCAmelCase    ,			tensor_type=_UpperCAmelCase							)

"""simple docstring"""






from jiwer import compute_measures

import datasets


__A			   = "\\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"

__A			   = "\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (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 words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n"

__A			   = "\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word 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    >>> wer = datasets.load_metric(\"wer\")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n"


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



    """simple docstring"""

    def _snake_case			(   self							):
       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''',
           ]    ,			)






    def _snake_case			(   self    ,			_UpperCAmelCase=None    ,			_UpperCAmelCase=None    ,			_UpperCAmelCase=False							):
       if concatenate_texts:
          return compute_measures(_UpperCAmelCase    ,			_UpperCAmelCase							)["wer"]
       else:
          lowercase__:   Dict					=      0
          lowercase__:   Union[str, Any]					=      0
          for prediction, reference in zip(_UpperCAmelCase    ,			_UpperCAmelCase							):
             lowercase__:   Tuple					=      compute_measures(_UpperCAmelCase    ,			_UpperCAmelCase							)
             incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
             total += measures["substitutions"] + measures["deletions"] + measures["hits"]
          return incorrect / total
