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_image_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import ViTImageProcessor





class      lowerCAmelCase						(					unittest.TestCase			):



     def __init__(					self				,      lowerCAmelCase__				,      lowerCAmelCase__=13				,      lowerCAmelCase__=3				,      lowerCAmelCase__=224				,      lowerCAmelCase__=30				,      lowerCAmelCase__=400				,      lowerCAmelCase__=True				,      lowerCAmelCase__=None				,      lowerCAmelCase__=True				,      lowerCAmelCase__=[0.5, 0.5, 0.5]				,      lowerCAmelCase__=[0.5, 0.5, 0.5]				,      ):
            _A=	size if size is not None else {'height': 18, 'width': 18}
            _A=	parent
            _A=	batch_size
            _A=	num_channels
            _A=	image_size
            _A=	min_resolution
            _A=	max_resolution
            _A=	do_resize
            _A=	size
            _A=	do_normalize
            _A=	image_mean
            _A=	image_std





     def 			a__  (					self       ):
            return {
                "image_mean": self.image_mean,
                "image_std": self.image_std,
                "do_normalize": self.do_normalize,
                "do_resize": self.do_resize,
                "size": self.size,
            }





@require_torch
@require_vision
class      lowerCAmelCase						(					_a			,		unittest.TestCase			):
     _SCREAMING_SNAKE_CASE     :     List[str]		=ViTImageProcessor if is_vision_available() else None



     def 			a__  (					self       ):
            _A=	EfficientFormerImageProcessorTester(self       )



     @property
     def 			a__  (					self       ):
            return self.image_proc_tester.prepare_image_processor_dict()



     def 			a__  (					self       ):
            _A=	self.image_processing_class(**self.image_processor_dict       )
            self.assertTrue(hasattr(lowerCAmelCase__				,      'image_mean'       )       )
            self.assertTrue(hasattr(lowerCAmelCase__				,      'image_std'       )       )
            self.assertTrue(hasattr(lowerCAmelCase__				,      'do_normalize'       )       )
            self.assertTrue(hasattr(lowerCAmelCase__				,      'do_resize'       )       )
            self.assertTrue(hasattr(lowerCAmelCase__				,      'size'       )       )



     def 			a__  (					self       ):
            pass



     def 			a__  (					self       ):
            # Initialize image_processor
            _A=	self.image_processing_class(**self.image_processor_dict       )
            # create random PIL images
            _A=	prepare_image_inputs(self.image_proc_tester				,      equal_resolution=lowerCAmelCase__       )
            for image in image_inputs:
                   self.assertIsInstance(lowerCAmelCase__				,      Image.Image       )

            # Test not batched input
            _A=	image_processor(image_inputs[0]				,      return_tensors='pt'       ).pixel_values
            self.assertEqual(
                encoded_images.shape				,      (
                    1,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['height'],
                    self.image_proc_tester.size['width'],
                )				,      )

            # Test batched
            _A=	image_processor(lowerCAmelCase__				,      return_tensors='pt'       ).pixel_values
            self.assertEqual(
                encoded_images.shape				,      (
                    self.image_proc_tester.batch_size,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['height'],
                    self.image_proc_tester.size['width'],
                )				,      )



     def 			a__  (					self       ):
            # Initialize image_processor
            _A=	self.image_processing_class(**self.image_processor_dict       )
            # create random numpy tensors
            _A=	prepare_image_inputs(self.image_proc_tester				,      equal_resolution=lowerCAmelCase__				,      numpify=lowerCAmelCase__       )
            for image in image_inputs:
                   self.assertIsInstance(lowerCAmelCase__				,      np.ndarray       )

            # Test not batched input
            _A=	image_processor(image_inputs[0]				,      return_tensors='pt'       ).pixel_values
            self.assertEqual(
                encoded_images.shape				,      (
                    1,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['height'],
                    self.image_proc_tester.size['width'],
                )				,      )

            # Test batched
            _A=	image_processor(lowerCAmelCase__				,      return_tensors='pt'       ).pixel_values
            self.assertEqual(
                encoded_images.shape				,      (
                    self.image_proc_tester.batch_size,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['height'],
                    self.image_proc_tester.size['width'],
                )				,      )





     def 			a__  (					self       ):
            # Initialize image_processor
            _A=	self.image_processing_class(**self.image_processor_dict       )
            # create random PyTorch tensors
            _A=	prepare_image_inputs(self.image_proc_tester				,      equal_resolution=lowerCAmelCase__				,      torchify=lowerCAmelCase__       )
            for image in image_inputs:
                   self.assertIsInstance(lowerCAmelCase__				,      torch.Tensor       )

            # Test not batched input
            _A=	image_processor(image_inputs[0]				,      return_tensors='pt'       ).pixel_values
            self.assertEqual(
                encoded_images.shape				,      (
                    1,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['height'],
                    self.image_proc_tester.size['width'],
                )				,      )

            # Test batched
            _A=	image_processor(lowerCAmelCase__				,      return_tensors='pt'       ).pixel_values
            self.assertEqual(
                encoded_images.shape				,      (
                    self.image_proc_tester.batch_size,
                    self.image_proc_tester.num_channels,
                    self.image_proc_tester.size['height'],
                    self.image_proc_tester.size['width'],
                )				,      )
from jiwer import compute_measures

import datasets


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

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

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



     def 			a__  (					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 			a__  (					self				,      lowerCAmelCase__=None				,      lowerCAmelCase__=None				,      lowerCAmelCase__=False       ):
            if concatenate_texts:
                   return compute_measures(lowerCAmelCase__				,      lowerCAmelCase__       )["wer"]
            else:
                   _A=	0
                   _A=	0
                   for prediction, reference in zip(lowerCAmelCase__				,      lowerCAmelCase__       ):
                          _A=	compute_measures(lowerCAmelCase__				,      lowerCAmelCase__       )
                          incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                          total += measures["substitutions"] + measures["deletions"] + measures["hits"]
                   return incorrect / total