



from jiwer import compute_measures

import datasets


_lowerCamelCase						    =  """\
@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.}
}
"""

_lowerCamelCase						    =  """\
Word error rate (WER) is a common metric of the performance of an automatic speech recognition system.

The 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.

This 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.

Word error rate can then be computed as:

WER = (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 words,
N is the number of words in the reference (N=S+D+C).

This value indicates the average number of errors per reference word. The lower the value, the better the
performance of the ASR system with a WER of 0 being a perfect score.
"""

_lowerCamelCase						    =  """
Compute WER score of transcribed segments against references.

Args:
    references: List of references for each speech input.
    predictions: List of transcriptions to score.
    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.

Returns:
    (float): the word error rate

Examples:

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

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





     def 	__snake_case    (       self :							List[Any]				)->str:
      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 :							Tuple     ,  UpperCamelCase :							int=None     ,  UpperCamelCase :							List[str]=None     ,  UpperCamelCase :							Optional[Any]=False				)->Optional[int]:
      if concatenate_texts:
       return compute_measures(UpperCamelCase     ,  UpperCamelCase				)["wer"]
      else:
       __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	0
       __SCREAMING_SNAKE_CASE       :    int       =	0
       for prediction, reference in zip(UpperCamelCase     ,  UpperCamelCase				):
        __SCREAMING_SNAKE_CASE       :    Any       =	compute_measures(UpperCamelCase     ,  UpperCamelCase				)
        incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
        total += measures["substitutions"] + measures["deletions"] + measures["hits"]
       return incorrect / total











import unittest
from typing import Dict, List, Optional, Union

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import BridgeTowerImageProcessor

class       _SCREAMING_SNAKE_CASE	(unittest.TestCase ):





     def __init__(       self :							Union[str, Any]     ,  UpperCamelCase :							List[Any]     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Dict[str, int] = None     ,  UpperCamelCase :							int = 3_2     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Union[int, float] = 1 / 2_5_5     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Optional[Union[float, List[float]]] = [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]     ,  UpperCamelCase :							Optional[Union[float, List[float]]] = [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Dict=7     ,  UpperCamelCase :							Dict=3_0     ,  UpperCamelCase :							Tuple=4_0_0     ,  UpperCamelCase :							Union[str, Any]=3     ,  )->Optional[int]:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	parent
      __SCREAMING_SNAKE_CASE       :    str       =	do_resize
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	size if size is not None else {"shortest_edge": 2_8_8}
      __SCREAMING_SNAKE_CASE       :    List[str]       =	size_divisor
      __SCREAMING_SNAKE_CASE       :    str       =	do_rescale
      __SCREAMING_SNAKE_CASE       :    int       =	rescale_factor
      __SCREAMING_SNAKE_CASE       :    Tuple       =	do_normalize
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	do_center_crop
      __SCREAMING_SNAKE_CASE       :    List[str]       =	image_mean
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	image_std
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	do_pad
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	batch_size
      __SCREAMING_SNAKE_CASE       :    str       =	num_channels
      __SCREAMING_SNAKE_CASE       :    List[str]       =	min_resolution
      __SCREAMING_SNAKE_CASE       :    Tuple       =	max_resolution





     def 	__snake_case    (       self :							Optional[Any]				)->List[str]:
      return {
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_normalize": self.do_normalize,
          "do_resize": self.do_resize,
          "size": self.size,
          "size_divisor": self.size_divisor,
      }






     def 	__snake_case    (       self :							Optional[Any]     ,  UpperCamelCase :							Optional[int]     ,  UpperCamelCase :							Dict=False				)->Optional[Any]:
      if not batched:
       __SCREAMING_SNAKE_CASE       :    Optional[int]       =	self.size["shortest_edge"]
       __SCREAMING_SNAKE_CASE       :    List[Any]       =	image_inputs[0]
       if isinstance(UpperCamelCase     ,  Image.Image				):
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[Any]       =	image.size
       else:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	image.shape[1], image.shape[2]
       __SCREAMING_SNAKE_CASE       :    Tuple       =	size / min(UpperCamelCase     ,  UpperCamelCase				)
       if h < w:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    int       =	size, scale * w
       else:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[str]       =	scale * h, size

       __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	int((1_3_3_3 / 8_0_0) * size				)
       if max(UpperCamelCase     ,  UpperCamelCase				) > max_size:
        __SCREAMING_SNAKE_CASE       :    Any       =	max_size / max(UpperCamelCase     ,  UpperCamelCase				)
        __SCREAMING_SNAKE_CASE       :    List[Any]       =	newh * scale
        __SCREAMING_SNAKE_CASE       :    Optional[int]       =	neww * scale

       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[Any]       =	int(newh + 0.5				), int(neww + 0.5				)
       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Optional[Any]       =	(
           newh // self.size_divisor * self.size_divisor,
           neww // self.size_divisor * self.size_divisor,
       )

      else:
       __SCREAMING_SNAKE_CASE       :    Optional[int]       =	[]
       for image in image_inputs:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Optional[Any]       =	self.get_expected_values([image]				)
        expected_values.append((expected_height, expected_width)				)
       __SCREAMING_SNAKE_CASE       :    int       =	max(UpperCamelCase     ,  key=lambda UpperCamelCase				: item[0]				)[0]
       __SCREAMING_SNAKE_CASE       :    List[str]       =	max(UpperCamelCase     ,  key=lambda UpperCamelCase				: item[1]				)[1]

      return expected_height, expected_width






@require_torch
@require_vision
class       _SCREAMING_SNAKE_CASE	(UpperCamelCase			,    unittest.TestCase ):
     lowerCAmelCase					=			BridgeTowerImageProcessor if is_vision_available() else None





     def 	__snake_case    (       self :							str				)->int:
      __SCREAMING_SNAKE_CASE       :    str       =	BridgeTowerImageProcessingTester(self				)





     @property
     def 	__snake_case    (       self :							str				)->Any:
      return self.image_processor_tester.prepare_image_processor_dict()





     def 	__snake_case    (       self :							Optional[int]				)->Dict:
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	self.image_processing_class(**self.image_processor_dict				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "image_mean"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "image_std"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "do_normalize"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "do_resize"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "size"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "size_divisor"				)				)





     def 	__snake_case    (       self :							Optional[int]				)->int:
      pass





     def 	__snake_case    (       self :							str				)->Union[str, Any]:
      # Initialize image processor
      __SCREAMING_SNAKE_CASE       :    Any       =	self.image_processing_class(**self.image_processor_dict				)
      # create random PIL images
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=UpperCamelCase				)
      for image in image_inputs:
       self.assertIsInstance(UpperCamelCase     ,  Image.Image				)

      # Test not batched input
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	image_processing(image_inputs[0]     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Tuple       =	self.image_processor_tester.get_expected_values(UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,  )

      # Test batched
      __SCREAMING_SNAKE_CASE       :    Any       =	image_processing(UpperCamelCase     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	self.image_processor_tester.get_expected_values(UpperCamelCase     ,  batched=UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )     ,  )





     def 	__snake_case    (       self :							List[str]				)->Optional[int]:
      # Initialize image processor
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	self.image_processing_class(**self.image_processor_dict				)
      # create random numpy tensors
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=UpperCamelCase     ,  numpify=UpperCamelCase				)
      for image in image_inputs:
       self.assertIsInstance(UpperCamelCase     ,  np.ndarray				)

      # Test not batched input
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	image_processing(image_inputs[0]     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Optional[int]       =	self.image_processor_tester.get_expected_values(UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,  )

      # Test batched
      __SCREAMING_SNAKE_CASE       :    str       =	image_processing(UpperCamelCase     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[Any]       =	self.image_processor_tester.get_expected_values(UpperCamelCase     ,  batched=UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )     ,  )






     def 	__snake_case    (       self :							Optional[Any]				)->Union[str, Any]:
      # Initialize image processor
      __SCREAMING_SNAKE_CASE       :    Dict       =	self.image_processing_class(**self.image_processor_dict				)
      # create random PyTorch tensors
      __SCREAMING_SNAKE_CASE       :    List[str]       =	prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=UpperCamelCase     ,  torchify=UpperCamelCase				)
      for image in image_inputs:
       self.assertIsInstance(UpperCamelCase     ,  torch.Tensor				)

      # Test not batched input
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	image_processing(image_inputs[0]     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Dict       =	self.image_processor_tester.get_expected_values(UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,  )

      # Test batched
      __SCREAMING_SNAKE_CASE       :    str       =	image_processing(UpperCamelCase     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Any       =	self.image_processor_tester.get_expected_values(UpperCamelCase     ,  batched=UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )     ,  )






