





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






			def       lowerCamelCase  (self   )					->       Tuple:


							'''simple docstring'''



							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       lowerCamelCase  (self ,							__magic_name__=None ,							__magic_name__=None ,							__magic_name__=False   )					->       Tuple:


							'''simple docstring'''



							if concatenate_texts:
											return compute_measures(__magic_name__ ,							__magic_name__   )["wer"]
							else:
											snake_case_						:   int           =  0
											snake_case_						:   str           =  0
											for prediction, reference in zip(__magic_name__ ,							__magic_name__   ):
															snake_case_						:   List[str]           =  compute_measures(__magic_name__ ,							__magic_name__   )
															incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
															total += measures["substitutions"] + measures["deletions"] + measures["hits"]
											return incorrect / total







import os
from typing import List, Optional, Union

from ...image_processing_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
from ..auto import AutoTokenizer



class  __lowerCAmelCase	(      _a					):
			lowerCamelCase_					:					Optional[Any]	      =				['''image_processor''', '''tokenizer''']
			lowerCamelCase_					:					List[Any]	      =				'''BlipImageProcessor'''
			lowerCamelCase_					:					Union[str, Any]	      =				'''AutoTokenizer'''






			def __init__(self ,							__magic_name__ ,							__magic_name__ ,							__magic_name__   )					->       Dict:


							'''simple docstring'''



							super().__init__(__magic_name__ ,							__magic_name__   )

							# add QFormer tokenizer
							snake_case_						:   Optional[Any]           =  qformer_tokenizer






			def __call__(self ,							__magic_name__ = None ,							__magic_name__ = None ,							__magic_name__ = True ,							__magic_name__ = False ,							__magic_name__ = None ,							__magic_name__ = None ,							__magic_name__ = 0 ,							__magic_name__ = None ,							__magic_name__ = None ,							__magic_name__ = False ,							__magic_name__ = False ,							__magic_name__ = False ,							__magic_name__ = False ,							__magic_name__ = False ,							__magic_name__ = True ,							__magic_name__ = None ,							**__magic_name__ ,							)					->       BatchFeature:


							'''simple docstring'''



							if images is None and text is None:
											raise ValueError('''You have to specify at least images or text.'''   )

							snake_case_						:   Tuple           =  BatchFeature()

							if text is not None:
											snake_case_						:   Tuple           =  self.tokenizer(
											    text=__magic_name__ ,							add_special_tokens=__magic_name__ ,							padding=__magic_name__ ,							truncation=__magic_name__ ,							max_length=__magic_name__ ,							stride=__magic_name__ ,							pad_to_multiple_of=__magic_name__ ,							return_attention_mask=__magic_name__ ,							return_overflowing_tokens=__magic_name__ ,							return_special_tokens_mask=__magic_name__ ,							return_offsets_mapping=__magic_name__ ,							return_token_type_ids=__magic_name__ ,							return_length=__magic_name__ ,							verbose=__magic_name__ ,							return_tensors=__magic_name__ ,							**__magic_name__ ,							)
											encoding.update(__magic_name__   )
											snake_case_						:   Optional[Any]           =  self.qformer_tokenizer(
											    text=__magic_name__ ,							add_special_tokens=__magic_name__ ,							padding=__magic_name__ ,							truncation=__magic_name__ ,							max_length=__magic_name__ ,							stride=__magic_name__ ,							pad_to_multiple_of=__magic_name__ ,							return_attention_mask=__magic_name__ ,							return_overflowing_tokens=__magic_name__ ,							return_special_tokens_mask=__magic_name__ ,							return_offsets_mapping=__magic_name__ ,							return_token_type_ids=__magic_name__ ,							return_length=__magic_name__ ,							verbose=__magic_name__ ,							return_tensors=__magic_name__ ,							**__magic_name__ ,							)
											snake_case_						:   Optional[int]           =  qformer_text_encoding.pop('''input_ids'''   )
											snake_case_						:   Tuple           =  qformer_text_encoding.pop('''attention_mask'''   )

							if images is not None:
											snake_case_						:   Any           =  self.image_processor(__magic_name__ ,							return_tensors=__magic_name__   )
											encoding.update(__magic_name__   )

							return encoding






			def       lowerCamelCase  (self ,							*__magic_name__ ,							**__magic_name__   )					->       List[Any]:


							'''simple docstring'''



							return self.tokenizer.batch_decode(*__magic_name__ ,							**__magic_name__   )






			def       lowerCamelCase  (self ,							*__magic_name__ ,							**__magic_name__   )					->       Union[str, Any]:


							'''simple docstring'''



							return self.tokenizer.decode(*__magic_name__ ,							**__magic_name__   )






			@property
			# Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
			def       lowerCamelCase  (self   )					->       Any:


							'''simple docstring'''



							snake_case_						:   Optional[Any]           =  self.tokenizer.model_input_names
							snake_case_						:   List[Any]           =  self.image_processor.model_input_names
							return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names   )   )






			def       lowerCamelCase  (self ,							__magic_name__ ,							**__magic_name__   )					->       List[Any]:


							'''simple docstring'''



							if os.path.isfile(__magic_name__   ):
											raise ValueError(F'''Provided path ({save_directory}) should be a directory, not a file'''   )
							os.makedirs(__magic_name__ ,							exist_ok=__magic_name__   )
							snake_case_						:   Any           =  os.path.join(__magic_name__ ,							'''qformer_tokenizer'''   )
							self.qformer_tokenizer.save_pretrained(__magic_name__   )
							return super().save_pretrained(__magic_name__ ,							**__magic_name__   )






			@classmethod
			def       lowerCamelCase  (cls ,							__magic_name__ ,							**__magic_name__   )					->       Union[str, Any]:


							'''simple docstring'''



							snake_case_						:   Any           =  AutoTokenizer.from_pretrained(__magic_name__ ,							subfolder='''qformer_tokenizer'''   )
							snake_case_						:   str           =  cls._get_arguments_from_pretrained(__magic_name__ ,							**__magic_name__   )
							args.append(__magic_name__   )
							return cls(*__magic_name__   )
