

from jiwer import compute_measures

import datasets


__A      		=     '''\
@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      		=     '''\
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.
'''

__A      		=     '''
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   lowercase_   (  datasets.Metric					):



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




import unittest

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_video_inputs


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import VivitImageProcessor



class   lowercase_   (  unittest.TestCase					):



      def __init__(      self				:    Union[str, Any]      , A__				:    int      , A__				:    List[str]=7      , A__				:    Tuple=3      , A__				:    List[str]=10      , A__				:    Optional[int]=18      , A__				:    int=30      , A__				:    Tuple=400      , A__				:    Dict=True      , A__				:    str=None      , A__				:    str=True      , A__				:    List[str]=[0.5, 0.5, 0.5]      , A__				:    int=[0.5, 0.5, 0.5]      , A__				:    List[Any]=None      , )   ->					int:
        _snake_case						=							size if size is not None else {'''shortest_edge''': 18}
        _snake_case						=							crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

        _snake_case						=							parent
        _snake_case						=							batch_size
        _snake_case						=							num_channels
        _snake_case						=							num_frames
        _snake_case						=							image_size
        _snake_case						=							min_resolution
        _snake_case						=							max_resolution
        _snake_case						=							do_resize
        _snake_case						=							size
        _snake_case						=							do_normalize
        _snake_case						=							image_mean
        _snake_case						=							image_std
        _snake_case						=							crop_size







      def 						UpperCamelCase_		(      self				:    List[str]		)   ->					Union[str, Any]:
        return {
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_normalize": self.do_normalize,
            "do_resize": self.do_resize,
            "size": self.size,
            "crop_size": self.crop_size,
        }



@require_torch
@require_vision
class   lowercase_   (  __lowercase       ,							unittest.TestCase					):
      UpperCamelCase_      :		Tuple										=    VivitImageProcessor if is_vision_available() else None



      def 						UpperCamelCase_		(      self				:    Union[str, Any]		)   ->					List[str]:
        _snake_case						=							VivitImageProcessingTester(self		)



      @property
      def 						UpperCamelCase_		(      self				:    Union[str, Any]		)   ->					Optional[Any]:
        return self.image_processor_tester.prepare_image_processor_dict()



      def 						UpperCamelCase_		(      self				:    Optional[int]		)   ->					Optional[Any]:
        _snake_case						=							self.image_processing_class(**self.image_processor_dict		)
        self.assertTrue(hasattr(A__      , '''image_mean'''		)		)
        self.assertTrue(hasattr(A__      , '''image_std'''		)		)
        self.assertTrue(hasattr(A__      , '''do_normalize'''		)		)
        self.assertTrue(hasattr(A__      , '''do_resize'''		)		)
        self.assertTrue(hasattr(A__      , '''do_center_crop'''		)		)
        self.assertTrue(hasattr(A__      , '''size'''		)		)



      def 						UpperCamelCase_		(      self				:    int		)   ->					List[Any]:
        _snake_case						=							self.image_processing_class.from_dict(self.image_processor_dict		)
        self.assertEqual(image_processor.size      , {'''shortest_edge''': 18}		)
        self.assertEqual(image_processor.crop_size      , {'''height''': 18, '''width''': 18}		)

        _snake_case						=							self.image_processing_class.from_dict(self.image_processor_dict      , size=42      , crop_size=84		)
        self.assertEqual(image_processor.size      , {'''shortest_edge''': 42}		)
        self.assertEqual(image_processor.crop_size      , {'''height''': 84, '''width''': 84}		)



      def 						UpperCamelCase_		(      self				:    List[Any]		)   ->					Optional[Any]:
        # Initialize image_processing
        _snake_case						=							self.image_processing_class(**self.image_processor_dict		)
        # create random PIL videos
        _snake_case						=							prepare_video_inputs(self.image_processor_tester      , equal_resolution=A__		)
        for video in video_inputs:
          self.assertIsInstance(A__      , A__		)
          self.assertIsInstance(video[0]      , Image.Image		)

        # Test not batched input
        _snake_case						=							image_processing(video_inputs[0]      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                1,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )

        # Test batched
        _snake_case						=							image_processing(A__      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )



      def 						UpperCamelCase_		(      self				:    Any		)   ->					List[str]:
        # Initialize image_processing
        _snake_case						=							self.image_processing_class(**self.image_processor_dict		)
        # create random numpy tensors
        _snake_case						=							prepare_video_inputs(self.image_processor_tester      , equal_resolution=A__      , numpify=A__		)
        for video in video_inputs:
          self.assertIsInstance(A__      , A__		)
          self.assertIsInstance(video[0]      , np.ndarray		)

        # Test not batched input
        _snake_case						=							image_processing(video_inputs[0]      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                1,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )

        # Test batched
        _snake_case						=							image_processing(A__      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )







      def 						UpperCamelCase_		(      self				:    Optional[Any]		)   ->					int:
        # Initialize image_processing
        _snake_case						=							self.image_processing_class(**self.image_processor_dict		)
        # create random PyTorch tensors
        _snake_case						=							prepare_video_inputs(self.image_processor_tester      , equal_resolution=A__      , torchify=A__		)
        for video in video_inputs:
          self.assertIsInstance(A__      , A__		)
          self.assertIsInstance(video[0]      , torch.Tensor		)

        # Test not batched input
        _snake_case						=							image_processing(video_inputs[0]      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                1,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )

        # Test batched
        _snake_case						=							image_processing(A__      , return_tensors='''pt'''		).pixel_values
        self.assertEqual(
            encoded_videos.shape      , (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_frames,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['''height'''],
                self.image_processor_tester.crop_size['''width'''],
            )      , )

