


'''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_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_batched,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_a   :   Tuple												=   logging.get_logger(__name__)




class 			_lowercase (	__lowercase							):
   _SCREAMING_SNAKE_CASE  :  Optional[Any]          =	["pixel_values"]
   def __init__(						self       :      Union[str, Any]       ,   SCREAMING_SNAKE_CASE_       :      bool = True       ,   SCREAMING_SNAKE_CASE_       :      Optional[Dict[str, int]] = None       ,   SCREAMING_SNAKE_CASE_       :      PILImageResampling = PILImageResampling.BICUBIC       ,   SCREAMING_SNAKE_CASE_       :      bool = True       ,   SCREAMING_SNAKE_CASE_       :      bool = True       ,   SCREAMING_SNAKE_CASE_       :      Union[int, float] = 1 / 255       ,   SCREAMING_SNAKE_CASE_       :      Dict[str, int] = None       ,   SCREAMING_SNAKE_CASE_       :      bool = True       ,   SCREAMING_SNAKE_CASE_       :      Optional[Union[float, List[float]]] = None       ,   SCREAMING_SNAKE_CASE_       :      Optional[Union[float, List[float]]] = None       ,   **SCREAMING_SNAKE_CASE_       :      Dict       ,   ) ->							None:
        super().__init__(**SCREAMING_SNAKE_CASE_      )
        __snake_case           =						size if size is not None else {'height': 224, 'width': 224}
        __snake_case           =						get_size_dict(SCREAMING_SNAKE_CASE_      )
        __snake_case           =						crop_size if crop_size is not None else {'height': 224, 'width': 224}
        __snake_case           =						get_size_dict(SCREAMING_SNAKE_CASE_       ,   default_to_square=SCREAMING_SNAKE_CASE_       ,   param_name='crop_size'      )

        __snake_case           =						do_resize
        __snake_case           =						do_rescale
        __snake_case           =						do_normalize
        __snake_case           =						do_center_crop
        __snake_case           =						crop_size
        __snake_case           =						size
        __snake_case           =						resample
        __snake_case           =						rescale_factor
        __snake_case           =						image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
        __snake_case           =						image_std if image_std is not None else IMAGENET_DEFAULT_STD
   def a  (						self       :      List[str]       ,   SCREAMING_SNAKE_CASE_       :      np.ndarray       ,   SCREAMING_SNAKE_CASE_       :      Dict[str, int]       ,   SCREAMING_SNAKE_CASE_       :      PILImageResampling = PILImageResampling.BILINEAR       ,   SCREAMING_SNAKE_CASE_       :      Optional[Union[str, ChannelDimension]] = None       ,   **SCREAMING_SNAKE_CASE_       :      Any       ,   ) ->							np.ndarray:
        __snake_case           =						get_size_dict(SCREAMING_SNAKE_CASE_      )

        if "shortest_edge" in size:
             __snake_case           =						get_resize_output_image_size(SCREAMING_SNAKE_CASE_       ,   size=size['shortest_edge']       ,   default_to_square=SCREAMING_SNAKE_CASE_      )
             # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
        elif "height" in size and "width" in size:
             __snake_case           =						(size['height'], size['width'])
        else:
             raise ValueError(f'Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}'      )
        return resize(SCREAMING_SNAKE_CASE_       ,   size=SCREAMING_SNAKE_CASE_       ,   resample=SCREAMING_SNAKE_CASE_       ,   data_format=SCREAMING_SNAKE_CASE_       ,   **SCREAMING_SNAKE_CASE_      )
   def a  (						self       :      List[str]       ,   SCREAMING_SNAKE_CASE_       :      np.ndarray       ,   SCREAMING_SNAKE_CASE_       :      Dict[str, int]       ,   SCREAMING_SNAKE_CASE_       :      Optional[Union[str, ChannelDimension]] = None       ,   **SCREAMING_SNAKE_CASE_       :      Optional[int]       ,   ) ->							np.ndarray:
        __snake_case           =						get_size_dict(SCREAMING_SNAKE_CASE_      )
        if "height" not in size or "width" not in size:
             raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}'      )
        return center_crop(SCREAMING_SNAKE_CASE_       ,   size=(size['height'], size['width'])       ,   data_format=SCREAMING_SNAKE_CASE_       ,   **SCREAMING_SNAKE_CASE_      )
   def a  (						self       :      Optional[int]       ,   SCREAMING_SNAKE_CASE_       :      np.ndarray       ,   SCREAMING_SNAKE_CASE_       :      float       ,   SCREAMING_SNAKE_CASE_       :      Optional[Union[str, ChannelDimension]] = None       ,   **SCREAMING_SNAKE_CASE_       :      Union[str, Any]      ) ->							np.ndarray:
        return rescale(SCREAMING_SNAKE_CASE_       ,   scale=SCREAMING_SNAKE_CASE_       ,   data_format=SCREAMING_SNAKE_CASE_       ,   **SCREAMING_SNAKE_CASE_      )
   def a  (						self       :      Optional[int]       ,   SCREAMING_SNAKE_CASE_       :      np.ndarray       ,   SCREAMING_SNAKE_CASE_       :      Union[float, List[float]]       ,   SCREAMING_SNAKE_CASE_       :      Union[float, List[float]]       ,   SCREAMING_SNAKE_CASE_       :      Optional[Union[str, ChannelDimension]] = None       ,   **SCREAMING_SNAKE_CASE_       :      List[Any]       ,   ) ->							np.ndarray:
        return normalize(SCREAMING_SNAKE_CASE_       ,   mean=SCREAMING_SNAKE_CASE_       ,   std=SCREAMING_SNAKE_CASE_       ,   data_format=SCREAMING_SNAKE_CASE_       ,   **SCREAMING_SNAKE_CASE_      )





   def a  (						self       :      Optional[Any]       ,   SCREAMING_SNAKE_CASE_       :      ImageInput       ,   SCREAMING_SNAKE_CASE_       :      Optional[bool] = None       ,   SCREAMING_SNAKE_CASE_       :      Dict[str, int] = None       ,   SCREAMING_SNAKE_CASE_       :      PILImageResampling = None       ,   SCREAMING_SNAKE_CASE_       :      bool = None       ,   SCREAMING_SNAKE_CASE_       :      int = None       ,   SCREAMING_SNAKE_CASE_       :      Optional[bool] = None       ,   SCREAMING_SNAKE_CASE_       :      Optional[float] = None       ,   SCREAMING_SNAKE_CASE_       :      Optional[bool] = None       ,   SCREAMING_SNAKE_CASE_       :      Optional[Union[float, List[float]]] = None       ,   SCREAMING_SNAKE_CASE_       :      Optional[Union[float, List[float]]] = None       ,   SCREAMING_SNAKE_CASE_       :      Optional[Union[str, TensorType]] = None       ,   SCREAMING_SNAKE_CASE_       :      Union[str, ChannelDimension] = ChannelDimension.FIRST       ,   **SCREAMING_SNAKE_CASE_       :      str       ,   ) ->							BatchFeature:
        __snake_case           =						do_resize if do_resize is not None else self.do_resize
        __snake_case           =						do_rescale if do_rescale is not None else self.do_rescale
        __snake_case           =						do_normalize if do_normalize is not None else self.do_normalize
        __snake_case           =						do_center_crop if do_center_crop is not None else self.do_center_crop
        __snake_case           =						crop_size if crop_size is not None else self.crop_size
        __snake_case           =						get_size_dict(SCREAMING_SNAKE_CASE_       ,   param_name='crop_size'       ,   default_to_square=SCREAMING_SNAKE_CASE_      )
        __snake_case           =						resample if resample is not None else self.resample
        __snake_case           =						rescale_factor if rescale_factor is not None else self.rescale_factor
        __snake_case           =						image_mean if image_mean is not None else self.image_mean
        __snake_case           =						image_std if image_std is not None else self.image_std

        __snake_case           =						size if size is not None else self.size
        __snake_case           =						get_size_dict(SCREAMING_SNAKE_CASE_      )

        if not is_batched(SCREAMING_SNAKE_CASE_      ):
             __snake_case           =						[images]

        if not valid_images(SCREAMING_SNAKE_CASE_      ):
             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.'      )

        # All transformations expect numpy arrays.
        __snake_case           =						[to_numpy_array(SCREAMING_SNAKE_CASE_      ) for image in images]

        if do_resize:
             __snake_case           =						[self.resize(image=SCREAMING_SNAKE_CASE_       ,   size=SCREAMING_SNAKE_CASE_       ,   resample=SCREAMING_SNAKE_CASE_      ) for image in images]

        if do_center_crop:
             __snake_case           =						[self.center_crop(image=SCREAMING_SNAKE_CASE_       ,   size=SCREAMING_SNAKE_CASE_      ) for image in images]

        if do_rescale:
             __snake_case           =						[self.rescale(image=SCREAMING_SNAKE_CASE_       ,   scale=SCREAMING_SNAKE_CASE_      ) for image in images]

        if do_normalize:
             __snake_case           =						[self.normalize(image=SCREAMING_SNAKE_CASE_       ,   mean=SCREAMING_SNAKE_CASE_       ,   std=SCREAMING_SNAKE_CASE_      ) for image in images]

        __snake_case           =						[to_channel_dimension_format(SCREAMING_SNAKE_CASE_       ,   SCREAMING_SNAKE_CASE_      ) for image in images]

        __snake_case           =						{'pixel_values': images}
        return BatchFeature(data=SCREAMING_SNAKE_CASE_       ,   tensor_type=SCREAMING_SNAKE_CASE_      )











'''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__							:  Dict    =''''''


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




      class 					UpperCAmelCase	(     tr.AbstractTransform  ):




            def __init__(     self     :					Any     ,     __snake_case     :					str = " "    )							-> Any:
                  _lowerCAmelCase					=				sentence_delimiter




            def 							lowercase__       (     self     :					str     ,     __snake_case     :					str    )							-> Optional[int]:
                  return list(__snake_case    )




            def 							lowercase__       (     self     :					Tuple     ,     __snake_case     :					List[str]    )							-> Union[str, Any]:
                  _lowerCAmelCase					=				[]
                  for sent_idx, sentence in enumerate(__snake_case    ):
                        chars.extend(self.process_string(__snake_case    )    )
                        if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__snake_case    ) - 1:
                              chars.append(self.sentence_delimiter    )
                  return chars




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


A__							:  List[str]    ='''\
@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__							:  Optional[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[str]    ='''
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     :					Any    )							-> 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 							lowercase__       (     self     :					Optional[Any]     ,     __snake_case     :					Optional[Any]     ,     __snake_case     :					List[str]     ,     __snake_case     :					Tuple=False    )							-> List[Any]:
            if concatenate_texts:
                  return jiwer.compute_measures(
                      __snake_case     ,     __snake_case     ,     truth_transform=__snake_case     ,     hypothesis_transform=__snake_case     ,     )["wer"]

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

            return incorrect / total






