
"""simple docstring"""


import json
import os
import shutil
import tempfile
import unittest

import numpy as np

from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
						from PIL import Image

						from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor




@require_tokenizers
@require_vision
class  __lowerCamelCase  ( unittest.TestCase			):




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  tempfile.mkdtemp()

							# fmt: off
							lowerCamelCase_					=  ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''']
							# fmt: on
							lowerCamelCase_					=  os.path.join(self.tmpdirname							,						VOCAB_FILES_NAMES['''vocab_file''']   )
							with open(self.vocab_file							,						'''w'''							,						encoding='''utf-8'''   ) as vocab_writer:
										vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]   )   )

							lowerCamelCase_					=  {
							    '''do_resize''': True,
							    '''size''': {'''height''': 18, '''width''': 18},
							    '''do_normalize''': True,
							    '''image_mean''': [0.5, 0.5, 0.5],
							    '''image_std''': [0.5, 0.5, 0.5],
							}
							lowerCamelCase_					=  os.path.join(self.tmpdirname							,						UpperCAmelCase   )
							with open(self.image_processor_file							,						'''w'''							,						encoding='''utf-8'''   ) as fp:
										json.dump(UpperCAmelCase							,						UpperCAmelCase   )




				def        UpperCAmelCase__						(				self							,						**UpperCAmelCase   ):
							return BertTokenizer.from_pretrained(self.tmpdirname							,						**UpperCAmelCase   )




				def        UpperCAmelCase__						(				self							,						**UpperCAmelCase   ):
							return ViTImageProcessor.from_pretrained(self.tmpdirname							,						**UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							shutil.rmtree(self.tmpdirname   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  [np.random.randint(255							,						size=(3, 30, 400)							,						dtype=np.uinta   )]

							lowerCamelCase_					=  [Image.fromarray(np.moveaxis(UpperCAmelCase							,						0							,						-1   )   ) for x in image_inputs]

							return image_inputs




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_tokenizer()
							lowerCamelCase_					=  self.get_image_processor()

							lowerCamelCase_					=  VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

							processor.save_pretrained(self.tmpdirname   )
							lowerCamelCase_					=  VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname   )

							self.assertEqual(processor.tokenizer.get_vocab()							,						tokenizer.get_vocab()   )
							self.assertIsInstance(processor.tokenizer							,						(BertTokenizer, BertTokenizerFast)   )

							self.assertEqual(processor.image_processor.to_json_string()							,						image_processor.to_json_string()   )
							self.assertIsInstance(processor.image_processor							,						UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  VisionTextDualEncoderProcessor(
							    tokenizer=self.get_tokenizer()							,						image_processor=self.get_image_processor()   )
							processor.save_pretrained(self.tmpdirname   )

							lowerCamelCase_					=  self.get_tokenizer(bos_token='''(BOS)'''							,						eos_token='''(EOS)'''   )
							lowerCamelCase_					=  self.get_image_processor(do_normalize=UpperCAmelCase							,						padding_value=1.0   )

							lowerCamelCase_					=  VisionTextDualEncoderProcessor.from_pretrained(
							    self.tmpdirname							,						bos_token='''(BOS)'''							,						eos_token='''(EOS)'''							,						do_normalize=UpperCAmelCase							,						padding_value=1.0   )

							self.assertEqual(processor.tokenizer.get_vocab()							,						tokenizer_add_kwargs.get_vocab()   )
							self.assertIsInstance(processor.tokenizer							,						(BertTokenizer, BertTokenizerFast)   )

							self.assertEqual(processor.image_processor.to_json_string()							,						image_processor_add_kwargs.to_json_string()   )
							self.assertIsInstance(processor.image_processor							,						UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_image_processor()
							lowerCamelCase_					=  self.get_tokenizer()

							lowerCamelCase_					=  VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

							lowerCamelCase_					=  self.prepare_image_inputs()

							lowerCamelCase_					=  image_processor(UpperCAmelCase							,						return_tensors='''np'''   )
							lowerCamelCase_					=  processor(images=UpperCAmelCase							,						return_tensors='''np'''   )

							for key in input_feat_extract.keys():
										self.assertAlmostEqual(input_feat_extract[key].sum()							,						input_processor[key].sum()							,						delta=1e-2   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_image_processor()
							lowerCamelCase_					=  self.get_tokenizer()

							lowerCamelCase_					=  VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

							lowerCamelCase_					=  '''lower newer'''

							lowerCamelCase_					=  processor(text=UpperCAmelCase   )

							lowerCamelCase_					=  tokenizer(UpperCAmelCase   )

							for key in encoded_tok.keys():
										self.assertListEqual(encoded_tok[key]							,						encoded_processor[key]   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_image_processor()
							lowerCamelCase_					=  self.get_tokenizer()

							lowerCamelCase_					=  VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

							lowerCamelCase_					=  '''lower newer'''
							lowerCamelCase_					=  self.prepare_image_inputs()

							lowerCamelCase_					=  processor(text=UpperCAmelCase							,						images=UpperCAmelCase   )

							self.assertListEqual(list(inputs.keys()   )							,						['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values''']   )

							# test if it raises when no input is passed
							with self.assertRaises(UpperCAmelCase   ):
										processor()




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_image_processor()
							lowerCamelCase_					=  self.get_tokenizer()

							lowerCamelCase_					=  VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

							lowerCamelCase_					=  [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

							lowerCamelCase_					=  processor.batch_decode(UpperCAmelCase   )
							lowerCamelCase_					=  tokenizer.batch_decode(UpperCAmelCase   )

							self.assertListEqual(UpperCAmelCase							,						UpperCAmelCase   )





				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.get_image_processor()
							lowerCamelCase_					=  self.get_tokenizer()

							lowerCamelCase_					=  VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase							,						image_processor=UpperCAmelCase   )

							lowerCamelCase_					=  '''lower newer'''
							lowerCamelCase_					=  self.prepare_image_inputs()

							lowerCamelCase_					=  processor(text=UpperCAmelCase							,						images=UpperCAmelCase   )

							self.assertListEqual(list(inputs.keys()   )							,						processor.model_input_names   )





"""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



