"""simple docstring"""





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 GLPNImageProcessor




class 			_snake_case		(     unittest.TestCase			):







				"""simple docstring"""






				def __init__(   self				:				int   ,     _A				:				List[Any]   ,     _A				:				List[Any]=7   ,     _A				:				str=3   ,     _A				:				List[str]=1_8   ,     _A				:				Optional[Any]=3_0   ,     _A				:				Dict=4_0_0   ,     _A				:				Any=True   ,     _A				:				List[str]=3_2   ,     _A				:				Optional[Any]=True   ,     ):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:    Optional[Any]      	=     parent
											_SCREAMING_SNAKE_CASE		:    Tuple      	=     batch_size
											_SCREAMING_SNAKE_CASE		:    List[Any]      	=     num_channels
											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     image_size
											_SCREAMING_SNAKE_CASE		:    Tuple      	=     min_resolution
											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     max_resolution
											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     do_resize
											_SCREAMING_SNAKE_CASE		:    Any      	=     size_divisor
											_SCREAMING_SNAKE_CASE		:    Tuple      	=     do_rescale





				def 		_lowerCAmelCase		(   self				:				Optional[Any]):



											"""simple docstring"""







											return {
											    "do_resize": self.do_resize,
											    "size_divisor": self.size_divisor,
											    "do_rescale": self.do_rescale,
											}




@require_torch
@require_vision
class 			_snake_case		(     __snake_case ,							unittest.TestCase			):







				"""simple docstring"""






				a      =    GLPNImageProcessor if is_vision_available() else None





				def 		_lowerCAmelCase		(   self				:				Optional[Any]):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:    List[Any]      	=     GLPNImageProcessingTester(self)





				@property
				def 		_lowerCAmelCase		(   self				:				Union[str, Any]):



											"""simple docstring"""







											return self.image_processor_tester.prepare_image_processor_dict()





				def 		_lowerCAmelCase		(   self				:				Tuple):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:    List[str]      	=     self.image_processing_class(**self.image_processor_dict)
											self.assertTrue(hasattr(_A   ,     """do_resize"""))
											self.assertTrue(hasattr(_A   ,     """size_divisor"""))
											self.assertTrue(hasattr(_A   ,     """resample"""))
											self.assertTrue(hasattr(_A   ,     """do_rescale"""))





				def 		_lowerCAmelCase		(   self				:				Dict):



											"""simple docstring"""







											pass





				def 		_lowerCAmelCase		(   self				:				List[Any]):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:    str      	=     self.image_processing_class(**self.image_processor_dict)
											# create random PIL images
											_SCREAMING_SNAKE_CASE		:    List[str]      	=     prepare_image_inputs(self.image_processor_tester   ,     equal_resolution=_A)
											for image in image_inputs:
																		self.assertIsInstance(_A   ,     Image.Image)

											# Test not batched input (GLPNImageProcessor doesn't support batching)
											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     image_processing(image_inputs[0]   ,     return_tensors="""pt""").pixel_values
											self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0)
											self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0)





				def 		_lowerCAmelCase		(   self				:				Tuple):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:    Optional[Any]      	=     self.image_processing_class(**self.image_processor_dict)
											# create random numpy tensors
											_SCREAMING_SNAKE_CASE		:    List[Any]      	=     prepare_image_inputs(self.image_processor_tester   ,     equal_resolution=_A   ,     numpify=_A)
											for image in image_inputs:
																		self.assertIsInstance(_A   ,     np.ndarray)

											# Test not batched input (GLPNImageProcessor doesn't support batching)
											_SCREAMING_SNAKE_CASE		:    Union[str, Any]      	=     image_processing(image_inputs[0]   ,     return_tensors="""pt""").pixel_values
											self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0)
											self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0)





				def 		_lowerCAmelCase		(   self				:				Any):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:    Optional[Any]      	=     self.image_processing_class(**self.image_processor_dict)
											# create random PyTorch tensors
											_SCREAMING_SNAKE_CASE		:    Optional[int]      	=     prepare_image_inputs(self.image_processor_tester   ,     equal_resolution=_A   ,     torchify=_A)
											for image in image_inputs:
																		self.assertIsInstance(_A   ,     torch.Tensor)

											# Test not batched input (GLPNImageProcessor doesn't support batching)
											_SCREAMING_SNAKE_CASE		:    List[Any]      	=     image_processing(image_inputs[0]   ,     return_tensors="""pt""").pixel_values
											self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0)
											self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0)




"""simple docstring"""


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  __lowerCamelCase  ( datasets.Metric			):




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



