




from io import BytesIO
from typing import List, Union

import requests

from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_decord_available():
  import numpy as np
  from decord import VideoReader


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

UpperCAmelCase_ 		=      logging.get_logger(__name__)





@add_end_docstrings(__magic_name__ )
class    __lowercase						(  __magic_name__ ):







   def __init__(	self      ,							*UpperCamelCase      ,							**UpperCamelCase      )				->    Optional[Any]:
     super().__init__(*UpperCamelCase      ,							**UpperCamelCase      )
     requires_backends(self      ,							'decord'      )
     self.check_model_type(UpperCamelCase      )







   def 		UpperCamelCase__			(	self      ,							UpperCamelCase=None      ,							UpperCamelCase=None      ,							UpperCamelCase=None      )				->    int:
     __a			=					{}
     if frame_sampling_rate is not None:
       __a			=					frame_sampling_rate
     if num_frames is not None:
       __a			=					num_frames

     __a			=					{}
     if top_k is not None:
       __a			=					top_k
     return preprocess_params, {}, postprocess_params







   def __call__(	self      ,							UpperCamelCase      ,							**UpperCamelCase      )				->    Optional[int]:
     return super().__call__(UpperCamelCase      ,							**UpperCamelCase      )







   def 		UpperCamelCase__			(	self      ,							UpperCamelCase      ,							UpperCamelCase=None      ,							UpperCamelCase=1      )				->    List[str]:
     if num_frames is None:
       __a			=					self.model.config.num_frames

     if video.startswith('http://'      ) or video.startswith('https://'      ):
       __a			=					BytesIO(requests.get(UpperCamelCase      ).content      )

     __a			=					VideoReader(UpperCamelCase      )
     videoreader.seek(0      )

     __a			=					0
     __a			=					num_frames * frame_sampling_rate - 1
     __a			=					np.linspace(UpperCamelCase      ,							UpperCamelCase      ,							num=UpperCamelCase      ,							dtype=np.intaa      )

     __a			=					videoreader.get_batch(UpperCamelCase      ).asnumpy()
     __a			=					list(UpperCamelCase      )

     __a			=					self.image_processor(UpperCamelCase      ,							return_tensors=self.framework      )
     return model_inputs







   def 		UpperCamelCase__			(	self      ,							UpperCamelCase      )				->    Any:
     __a			=					self.model(**UpperCamelCase      )
     return model_outputs







   def 		UpperCamelCase__			(	self      ,							UpperCamelCase      ,							UpperCamelCase=5      )				->    str:
     if top_k > self.model.config.num_labels:
       __a			=					self.model.config.num_labels

     if self.framework == "pt":
       __a			=					model_outputs.logits.softmax(-1      )[0]
       __a	,       __a			=					probs.topk(UpperCamelCase      )
     else:
       raise ValueError(f"Unsupported framework: {self.framework}"      )

     __a			=					scores.tolist()
     __a			=					ids.tolist()
     return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(UpperCamelCase      ,							UpperCamelCase      )]









'''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      ,							UpperCamelCase = " "      )				->    Tuple:
       __a			=					sentence_delimiter







     def 		UpperCamelCase__			(	self      ,							UpperCamelCase      )				->    Union[str, Any]:
       return list(UpperCamelCase      )







     def 		UpperCamelCase__			(	self      ,							UpperCamelCase      )				->    int:
       __a			=					[]
       for sent_idx, sentence in enumerate(UpperCamelCase      ):
         chars.extend(self.process_string(UpperCamelCase      )      )
         if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(UpperCamelCase      ) - 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 		UpperCamelCase__			(	self      )				->    Any:
     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 		UpperCamelCase__			(	self      ,							UpperCamelCase      ,							UpperCamelCase      ,							UpperCamelCase=False      )				->    int:
     if concatenate_texts:
       return jiwer.compute_measures(
           UpperCamelCase      ,							UpperCamelCase      ,							truth_transform=UpperCamelCase      ,							hypothesis_transform=UpperCamelCase      ,							)["wer"]

     __a			=					0
     __a			=					0
     for prediction, reference in zip(UpperCamelCase      ,							UpperCamelCase      ):
       __a			=					jiwer.compute_measures(
           UpperCamelCase      ,							UpperCamelCase      ,							truth_transform=UpperCamelCase      ,							hypothesis_transform=UpperCamelCase      ,							)
       incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
       total += measures["substitutions"] + measures["deletions"] + measures["hits"]

     return incorrect / total



