

"""simple docstring"""




from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('3.8'):
						import importlib_metadata
else:
						import importlib.metadata as importlib_metadata


__UpperCAmelCase =				''


if version.parse(importlib_metadata.version('jiwer')) < version.parse('2.3.0'):







						class      __lowercase			(    tr.AbstractTransform					):

								def __init__(  self		:			List[str]					,A		:			str = " "    ):






									'''simple docstring'''
									UpperCAmelCase__					:  str					   =					sentence_delimiter

								def    __lowercase       (  self		:			Union[str, Any]					,A		:			str    ):






									'''simple docstring'''
									return list(A    )




								def    __lowercase       (  self		:			int					,A		:			List[str]    ):






									'''simple docstring'''
									UpperCAmelCase__					:  Any					   =					[]
									for sent_idx, sentence in enumerate(A    ):
										chars.extend(self.process_string(A    )    )
										if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(A    ) - 1:
											chars.append(self.sentence_delimiter    )
									return chars







						__UpperCAmelCase =				tr.Compose(
						    [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
						)
else:
						__UpperCAmelCase =				tr.Compose(
						    [
						        tr.RemoveMultipleSpaces(),
						        tr.Strip(),
						        tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
						        tr.ReduceToListOfListOfChars(),
						    ]
						)


__UpperCAmelCase =				'\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n'

__UpperCAmelCase =				'\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n'

__UpperCAmelCase =				'\nComputes CER score of transcribed segments against references.\nArgs:\n    references: list of references for each speech input.\n    predictions: list of transcribtions to score.\n    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n    (float): the character error rate\n\nExamples:\n\n    >>> predictions = ["this is the prediction", "there is an other sample"]\n    >>> references = ["this is the reference", "there is another one"]\n    >>> cer = datasets.load_metric("cer")\n    >>> cer_score = cer.compute(predictions=predictions, references=references)\n    >>> print(cer_score)\n    0.34146341463414637\n'







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,			_KWARGS_DESCRIPTION					)
class      __lowercase			(    datasets.Metric					):

		def    __lowercase       (  self		:			int    ):






			'''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""",
			        """https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates""",
			    ]					,)




		def    __lowercase       (  self		:			Union[str, Any]					,A		:			Optional[Any]					,A		:			Tuple					,A		:			str=False    ):






			'''simple docstring'''
			if concatenate_texts:
				return jiwer.compute_measures(
				    A					,A					,truth_transform=A					,hypothesis_transform=A					,)["wer"]

			UpperCAmelCase__					:  Tuple					   =					0
			UpperCAmelCase__					:  Any					   =					0
			for prediction, reference in zip(A					,A    ):
				UpperCAmelCase__					:  List[str]					   =					jiwer.compute_measures(
				    A					,A					,truth_transform=A					,hypothesis_transform=A					,)
				incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
				total += measures["substitutions"] + measures["deletions"] + measures["hits"]

			return incorrect / total








"""simple docstring"""




from typing import Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
      from PIL import Image

      from ..image_utils import load_image

if is_torch_available():
      from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING

__UpperCAmelCase =				logging.get_logger(__name__)







@add_end_docstrings(__lowerCamelCase					)
class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			List[str]					,*A		:			Optional[int]					,**A		:			List[str]    ):






   '''simple docstring'''
   super().__init__(*A					,**A    )
   self.check_model_type(A    )

  def    __lowercase       (  self		:			Optional[int]					,A		:			Dict=None					,A		:			Optional[int]=None					,A		:			Tuple=None					,**A		:			str    ):






   '''simple docstring'''
   UpperCAmelCase__   ,      UpperCAmelCase__					:  Any					   =					{}, {}
   if padding is not None:
    UpperCAmelCase__					:  Union[str, Any]					   =					padding
   if truncation is not None:
    UpperCAmelCase__					:  List[str]					   =					truncation
   if top_k is not None:
    UpperCAmelCase__					:  List[Any]					   =					top_k
   return preprocess_params, {}, postprocess_params

  def __call__(  self		:			List[Any]					,A		:			Union["Image.Image", str]					,A		:			str = None					,**A		:			Union[str, Any]    ):






   '''simple docstring'''
   if isinstance(A					,(Image.Image, str)    ) and isinstance(A					,A    ):
    UpperCAmelCase__					:  Any					   =					{"""image""": image, """question""": question}
   else:
    UpperCAmelCase__					:  Dict					   =					image
   UpperCAmelCase__					:  Dict					   =					super().__call__(A					,**A    )
   return results

  def    __lowercase       (  self		:			Optional[int]					,A		:			Optional[Any]					,A		:			Optional[Any]=False					,A		:			List[Any]=False    ):






   '''simple docstring'''
   UpperCAmelCase__					:  List[Any]					   =					load_image(inputs["""image"""]    )
   UpperCAmelCase__					:  Optional[Any]					   =					self.tokenizer(
       inputs["""question"""]					,return_tensors=self.framework					,padding=A					,truncation=A    )
   UpperCAmelCase__					:  int					   =					self.image_processor(images=A					,return_tensors=self.framework    )
   model_inputs.update(A    )
   return model_inputs

  def    __lowercase       (  self		:			Dict					,A		:			Tuple    ):






   '''simple docstring'''
   UpperCAmelCase__					:  List[Any]					   =					self.model(**A    )
   return model_outputs




  def    __lowercase       (  self		:			int					,A		:			List[Any]					,A		:			List[str]=5    ):






   '''simple docstring'''
   if top_k > self.model.config.num_labels:
    UpperCAmelCase__					:  Any					   =					self.model.config.num_labels

   if self.framework == "pt":
    UpperCAmelCase__					:  Optional[int]					   =					model_outputs.logits.sigmoid()[0]
    UpperCAmelCase__   ,      UpperCAmelCase__					:  Optional[int]					   =					probs.topk(A    )
   else:
    raise ValueError(f"Unsupported framework: {self.framework}"    )

   UpperCAmelCase__					:  List[str]					   =					scores.tolist()
   UpperCAmelCase__					:  Optional[int]					   =					ids.tolist()
   return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(A					,A    )]





