






import inspect
import unittest

from transformers import SwinaSRConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch
   from torch import nn

   from transformers import SwinaSRForImageSuperResolution, SwinaSRModel
   from transformers.models.swinasr.modeling_swinasr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
   from PIL import Image

   from transformers import SwinaSRImageProcessor


class        SCREAMING_SNAKE_CASE	:
     '''simple docstring'''


     def __init__( self				:		List[Any]    ,       UpperCAmelCase_				:		Tuple    ,       UpperCAmelCase_				:		int=13    ,       UpperCAmelCase_				:		int=32    ,       UpperCAmelCase_				:		Optional[Any]=1    ,       UpperCAmelCase_				:		Union[str, Any]=3    ,       UpperCAmelCase_				:		int=16    ,       UpperCAmelCase_				:		Union[str, Any]=[1, 2, 1]    ,       UpperCAmelCase_				:		str=[2, 2, 4]    ,       UpperCAmelCase_				:		List[Any]=2    ,       UpperCAmelCase_				:		Tuple=2.0    ,       UpperCAmelCase_				:		List[str]=True    ,       UpperCAmelCase_				:		Tuple=0.0    ,       UpperCAmelCase_				:		List[Any]=0.0    ,       UpperCAmelCase_				:		Optional[int]=0.1    ,       UpperCAmelCase_				:		Optional[Any]="gelu"    ,       UpperCAmelCase_				:		Any=False    ,       UpperCAmelCase_				:		str=True    ,       UpperCAmelCase_				:		Dict=0.02    ,       UpperCAmelCase_				:		List[Any]=1E-5    ,       UpperCAmelCase_				:		Optional[int]=True    ,       UpperCAmelCase_				:		str=None    ,       UpperCAmelCase_				:		List[Any]=False    ,       UpperCAmelCase_				:		Dict=2    ,       ):
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			parent
       SCREAMING_SNAKE_CASE				:					List[str]		  =			batch_size
       SCREAMING_SNAKE_CASE				:					str		  =			image_size
       SCREAMING_SNAKE_CASE				:					Tuple		  =			patch_size
       SCREAMING_SNAKE_CASE				:					List[str]		  =			num_channels
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			embed_dim
       SCREAMING_SNAKE_CASE				:					Union[str, Any]		  =			depths
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			num_heads
       SCREAMING_SNAKE_CASE				:					str		  =			window_size
       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			mlp_ratio
       SCREAMING_SNAKE_CASE				:					Dict		  =			qkv_bias
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			hidden_dropout_prob
       SCREAMING_SNAKE_CASE				:					Any		  =			attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE				:					Any		  =			drop_path_rate
       SCREAMING_SNAKE_CASE				:					Tuple		  =			hidden_act
       SCREAMING_SNAKE_CASE				:					str		  =			use_absolute_embeddings
       SCREAMING_SNAKE_CASE				:					int		  =			patch_norm
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			layer_norm_eps
       SCREAMING_SNAKE_CASE				:					Dict		  =			initializer_range
       SCREAMING_SNAKE_CASE				:					Any		  =			is_training
       SCREAMING_SNAKE_CASE				:					Any		  =			scope
       SCREAMING_SNAKE_CASE				:					Any		  =			use_labels
       SCREAMING_SNAKE_CASE				:					Dict		  =			upscale

       # here we set some attributes to make tests pass
       SCREAMING_SNAKE_CASE				:					Any		  =			len(UpperCAmelCase_					)
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			embed_dim
       SCREAMING_SNAKE_CASE				:					str		  =			(image_size // patch_size) ** 2


     def  _A				( self				:		Optional[int]					):
       SCREAMING_SNAKE_CASE				:					str		  =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

       SCREAMING_SNAKE_CASE				:					List[Any]		  =			None
       if self.use_labels:
         SCREAMING_SNAKE_CASE				:					Dict		  =			ids_tensor([self.batch_size]    ,       self.type_sequence_label_size					)

       SCREAMING_SNAKE_CASE				:					Tuple		  =			self.get_config()

       return config, pixel_values, labels


     def  _A				( self				:		str					):
       return SwinaSRConfig(
           image_size=self.image_size    ,       patch_size=self.patch_size    ,       num_channels=self.num_channels    ,       embed_dim=self.embed_dim    ,       depths=self.depths    ,       num_heads=self.num_heads    ,       window_size=self.window_size    ,       mlp_ratio=self.mlp_ratio    ,       qkv_bias=self.qkv_bias    ,       hidden_dropout_prob=self.hidden_dropout_prob    ,       attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,       drop_path_rate=self.drop_path_rate    ,       hidden_act=self.hidden_act    ,       use_absolute_embeddings=self.use_absolute_embeddings    ,       path_norm=self.patch_norm    ,       layer_norm_eps=self.layer_norm_eps    ,       initializer_range=self.initializer_range    ,       upscale=self.upscale    ,       )


     def  _A				( self				:		Any    ,       UpperCAmelCase_				:		str    ,       UpperCAmelCase_				:		Tuple    ,       UpperCAmelCase_				:		List[Any]					):
       SCREAMING_SNAKE_CASE				:					Union[str, Any]		  =			SwinaSRModel(config=UpperCAmelCase_					)
       model.to(UpperCAmelCase_					)
       model.eval()
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			model(UpperCAmelCase_					)

       self.parent.assertEqual(
           result.last_hidden_state.shape    ,       (self.batch_size, self.embed_dim, self.image_size, self.image_size)					)


     def  _A				( self				:		Tuple    ,       UpperCAmelCase_				:		List[str]    ,       UpperCAmelCase_				:		List[Any]    ,       UpperCAmelCase_				:		Optional[Any]					):
       SCREAMING_SNAKE_CASE				:					Dict		  =			SwinaSRForImageSuperResolution(UpperCAmelCase_					)
       model.to(UpperCAmelCase_					)
       model.eval()
       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			model(UpperCAmelCase_					)

       SCREAMING_SNAKE_CASE				:					List[Any]		  =			self.image_size * self.upscale
       self.parent.assertEqual(
           result.reconstruction.shape    ,       (self.batch_size, self.num_channels, expected_image_size, expected_image_size)					)






     def  _A				( self				:		Any					):
       SCREAMING_SNAKE_CASE				:					Dict		  =			self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE  ,     SCREAMING_SNAKE_CASE  ,     SCREAMING_SNAKE_CASE				:					Tuple		  =			config_and_inputs
       SCREAMING_SNAKE_CASE				:					Union[str, Any]		  =			{"pixel_values": pixel_values}
       return config, inputs_dict





@require_torch
class        SCREAMING_SNAKE_CASE	(	lowerCAmelCase					,						lowerCAmelCase					,						unittest.TestCase    ):
     '''simple docstring'''


     UpperCamelCase_							:						int								=		(SwinaSRModel, SwinaSRForImageSuperResolution) if is_torch_available() else ()
     UpperCamelCase_							:						Union[str, Any]								=		{'''feature-extraction''': SwinaSRModel} if is_torch_available() else {}

     UpperCamelCase_							:						List[str]								=		False
     UpperCamelCase_							:						List[str]								=		False
     UpperCamelCase_							:						Optional[int]								=		False
     UpperCamelCase_							:						Union[str, Any]								=		False
     UpperCamelCase_							:						Tuple								=		False


     def  _A				( self				:		str					):
       SCREAMING_SNAKE_CASE				:					Union[str, Any]		  =			SwinaSRModelTester(self					)
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			ConfigTester(self    ,       config_class=UpperCAmelCase_    ,       embed_dim=37					)


     def  _A				( self				:		str					):
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()


     def  _A				( self				:		int					):
       SCREAMING_SNAKE_CASE				:					str		  =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCAmelCase_					)


     def  _A				( self				:		Dict					):
       SCREAMING_SNAKE_CASE				:					str		  =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_super_resolution(*UpperCAmelCase_					)


     @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0."					)
     def  _A				( self				:		Union[str, Any]					):
       pass


     @unittest.skip(reason="Swin2SR does not use inputs_embeds"					)
     def  _A				( self				:		Tuple					):
       pass


     @unittest.skip(reason="Swin2SR does not support training yet"					)
     def  _A				( self				:		int					):
       pass


     @unittest.skip(reason="Swin2SR does not support training yet"					)
     def  _A				( self				:		Tuple					):
       pass


     def  _A				( self				:		List[Any]					):
       SCREAMING_SNAKE_CASE  ,     SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			model_class(UpperCAmelCase_					)
         self.assertIsInstance(model.get_input_embeddings()    ,       (nn.Module)					)
         SCREAMING_SNAKE_CASE				:					str		  =			model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(UpperCAmelCase_    ,       nn.Linear					)					)


     def  _A				( self				:		Union[str, Any]					):
       SCREAMING_SNAKE_CASE  ,     SCREAMING_SNAKE_CASE				:					Any		  =			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         SCREAMING_SNAKE_CASE				:					int		  =			model_class(UpperCAmelCase_					)
         SCREAMING_SNAKE_CASE				:					Dict		  =			inspect.signature(model.forward					)
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         SCREAMING_SNAKE_CASE				:					Optional[int]		  =			[*signature.parameters.keys()]

         SCREAMING_SNAKE_CASE				:					int		  =			["pixel_values"]
         self.assertListEqual(arg_names[:1]    ,       UpperCAmelCase_					)


     @slow
     def  _A				( self				:		Optional[Any]					):
       for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         SCREAMING_SNAKE_CASE				:					str		  =			SwinaSRModel.from_pretrained(UpperCAmelCase_					)
         self.assertIsNotNone(UpperCAmelCase_					)


     def  _A				( self				:		int					):
       SCREAMING_SNAKE_CASE  ,     SCREAMING_SNAKE_CASE				:					Tuple		  =			self.model_tester.prepare_config_and_inputs_for_common()

       SCREAMING_SNAKE_CASE				:					List[str]		  =			_config_zero_init(UpperCAmelCase_					)
       for model_class in self.all_model_classes:
         SCREAMING_SNAKE_CASE				:					str		  =			model_class(config=UpperCAmelCase_					)
         for name, param in model.named_parameters():
           if "logit_scale" in name:
             continue
           if param.requires_grad:
             self.assertIn(
                 ((param.data.mean() * 1E9).round() / 1E9).item()    ,       [0.0, 1.0]    ,       msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''    ,       )






     def  _A				( self				:		Union[str, Any]					):
       SCREAMING_SNAKE_CASE  ,     SCREAMING_SNAKE_CASE				:					List[str]		  =			self.model_tester.prepare_config_and_inputs_for_common()
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			True

       for model_class in self.all_model_classes:
         SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			True
         SCREAMING_SNAKE_CASE				:					Tuple		  =			False
         SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			True
         SCREAMING_SNAKE_CASE				:					int		  =			model_class(UpperCAmelCase_					)
         model.to(UpperCAmelCase_					)
         model.eval()
         with torch.no_grad():
           SCREAMING_SNAKE_CASE				:					int		  =			model(**self._prepare_for_class(UpperCAmelCase_    ,       UpperCAmelCase_					)					)
         SCREAMING_SNAKE_CASE				:					str		  =			outputs.attentions
         SCREAMING_SNAKE_CASE				:					Tuple		  =			len(self.model_tester.depths					)
         self.assertEqual(len(UpperCAmelCase_					)    ,       UpperCAmelCase_					)

         # check that output_attentions also work using config
         del inputs_dict["output_attentions"]
         SCREAMING_SNAKE_CASE				:					Union[str, Any]		  =			True
         SCREAMING_SNAKE_CASE				:					int		  =			config.window_size**2
         SCREAMING_SNAKE_CASE				:					List[Any]		  =			model_class(UpperCAmelCase_					)
         model.to(UpperCAmelCase_					)
         model.eval()
         with torch.no_grad():
           SCREAMING_SNAKE_CASE				:					List[str]		  =			model(**self._prepare_for_class(UpperCAmelCase_    ,       UpperCAmelCase_					)					)
         SCREAMING_SNAKE_CASE				:					str		  =			outputs.attentions
         self.assertEqual(len(UpperCAmelCase_					)    ,       UpperCAmelCase_					)

         self.assertListEqual(
             list(attentions[0].shape[-3:]					)    ,       [self.model_tester.num_heads[0], window_size_squared, window_size_squared]    ,       )
         SCREAMING_SNAKE_CASE				:					List[Any]		  =			len(UpperCAmelCase_					)

         # Check attention is always last and order is fine
         SCREAMING_SNAKE_CASE				:					Any		  =			True
         SCREAMING_SNAKE_CASE				:					List[str]		  =			True
         SCREAMING_SNAKE_CASE				:					Tuple		  =			model_class(UpperCAmelCase_					)
         model.to(UpperCAmelCase_					)
         model.eval()
         with torch.no_grad():
           SCREAMING_SNAKE_CASE				:					Any		  =			model(**self._prepare_for_class(UpperCAmelCase_    ,       UpperCAmelCase_					)					)

         self.assertEqual(out_len + 1    ,       len(UpperCAmelCase_					)					)

         SCREAMING_SNAKE_CASE				:					Dict		  =			outputs.attentions

         self.assertEqual(len(UpperCAmelCase_					)    ,       UpperCAmelCase_					)

         self.assertListEqual(
             list(self_attentions[0].shape[-3:]					)    ,       [self.model_tester.num_heads[0], window_size_squared, window_size_squared]    ,       )





@require_vision
@require_torch
@slow
class        SCREAMING_SNAKE_CASE	(	unittest.TestCase    ):
     '''simple docstring'''


     def  _A				( self				:		List[str]					):
       SCREAMING_SNAKE_CASE				:					Any		  =			SwinaSRImageProcessor()
       SCREAMING_SNAKE_CASE				:					Dict		  =			SwinaSRForImageSuperResolution.from_pretrained("caidas/swin2SR-classical-sr-x2-64"					).to(UpperCAmelCase_					)

       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
       SCREAMING_SNAKE_CASE				:					int		  =			processor(images=UpperCAmelCase_    ,       return_tensors="pt"					).to(UpperCAmelCase_					)

       # forward pass
       with torch.no_grad():
         SCREAMING_SNAKE_CASE				:					Tuple		  =			model(**UpperCAmelCase_					)

       # verify the logits
       SCREAMING_SNAKE_CASE				:					Dict		  =			torch.Size([1, 3, 976, 1296]					)
       self.assertEqual(outputs.reconstruction.shape    ,       UpperCAmelCase_					)
       SCREAMING_SNAKE_CASE				:					Union[str, Any]		  =			torch.tensor(
           [[0.5_458, 0.5_546, 0.5_638], [0.5_526, 0.5_565, 0.5_651], [0.5_396, 0.5_426, 0.5_621]]					).to(UpperCAmelCase_					)
       self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3]    ,       UpperCAmelCase_    ,       atol=1E-4					)					)














from typing import List

from packaging import version
from sklearn.metrics import fa_score

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


# TODO(Patrick/Anton)
snake_case			 =						"""\
"""

snake_case			 =						"""\
    XTREME-S is a benchmark to evaluate universal cross-lingual speech representations in many languages.
    XTREME-S covers four task families: speech recognition, classification, speech-to-text translation and retrieval.
"""

snake_case			 =						"""
Compute XTREME-S evaluation metric associated to each XTREME-S dataset.
Args:
    predictions: list of predictions to score.
        Each translation should be tokenized into a list of tokens.
    references: list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    bleu_kwargs: optional dict of keywords to be passed when computing 'bleu'.
        Keywords include Dict can be one of 'smooth_method', 'smooth_value', 'force', 'lowercase',
        'tokenize', 'use_effective_order'.
    wer_kwargs: optional dict of keywords to be passed when computing 'wer' and 'cer'.
        Keywords include 'concatenate_texts'.
Returns: depending on the XTREME-S task, one or several of:
    \"accuracy\": Accuracy - for 'fleurs-lang_id', 'minds14'
    \"f1\": F1 score - for 'minds14'
    \"wer\": Word error rate - for 'mls', 'fleurs-asr', 'voxpopuli', 'babel'
    \"cer\": Character error rate - for 'mls', 'fleurs-asr', 'voxpopuli', 'babel'
    \"bleu\": BLEU score according to the `sacrebleu` metric - for 'covost2'
Examples:

    >>> xtreme_s_metric = datasets.load_metric('xtreme_s', 'mls')  # 'mls', 'voxpopuli', 'fleurs-asr' or 'babel'
    >>> references = [\"it is sunny here\", \"paper and pen are essentials\"]
    >>> predictions = [\"it's sunny\", \"paper pen are essential\"]
    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)
    >>> print({k: round(v, 2) for k, v in results.items()})
    {'wer': 0.56, 'cer': 0.27}

    >>> xtreme_s_metric = datasets.load_metric('xtreme_s', 'covost2')
    >>> references = [\"bonjour paris\", \"il est necessaire de faire du sport de temps en temp\"]
    >>> predictions = [\"bonjour paris\", \"il est important de faire du sport souvent\"]
    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)
    >>> print({k: round(v, 2) for k, v in results.items()})
    {'bleu': 31.65}

    >>> xtreme_s_metric = datasets.load_metric('xtreme_s', 'fleurs-lang_id')
    >>> references = [0, 1, 0, 0, 1]
    >>> predictions = [0, 1, 1, 0, 0]
    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)
    >>> print({k: round(v, 2) for k, v in results.items()})
    {'accuracy': 0.6}

    >>> xtreme_s_metric = datasets.load_metric('xtreme_s', 'minds14')
    >>> references = [0, 1, 0, 0, 1]
    >>> predictions = [0, 1, 1, 0, 0]
    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)
    >>> print({k: round(v, 2) for k, v in results.items()})
    {'f1': 0.58, 'accuracy': 0.6}
"""

snake_case			 =						["""fleurs-asr""", """mls""", """voxpopuli""", """babel""", """covost2""", """fleurs-lang_id""", """minds14"""]
snake_case			 =						""""""

try:
   from jiwer import transforms as tr

   snake_case			 =						True
except ImportError:
   snake_case			 =						False

if _jiwer_available and version.parse(importlib_metadata.version("""jiwer""")) < version.parse("""2.3.0"""):


   class        SCREAMING_SNAKE_CASE	(	tr.AbstractTransform    ):
        '''simple docstring'''


        def __init__( self				:		Dict    ,       UpperCAmelCase_				:		str = " "					):
          SCREAMING_SNAKE_CASE				:					List[Any]		  =			sentence_delimiter


        def  _A				( self				:		Optional[int]    ,       UpperCAmelCase_				:		str					):
          return list(UpperCAmelCase_					)






        def  _A				( self				:		str    ,       UpperCAmelCase_				:		List[str]					):
          SCREAMING_SNAKE_CASE				:					Tuple		  =			[]
          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





   snake_case			 =						tr.Compose(
       [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
   )
elif _jiwer_available:
   snake_case			 =						tr.Compose(
       [
           tr.RemoveMultipleSpaces(),
           tr.Strip(),
           tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
           tr.ReduceToListOfListOfChars(),
       ]
   )
else:
   snake_case			 =						None


def      lowerCamelCase__	(   lowercase  ,   lowercase ):

  """simple docstring"""






  return float((preds == labels).mean() )


def      lowerCamelCase__	(   lowercase  ,   lowercase ):

  """simple docstring"""






  return {
      "f1": float(fa_score(y_true=lowercase  ,   y_pred=lowercase  ,   average="macro" ) ),
      "accuracy": simple_accuracy(lowercase  ,   lowercase ),
  }


def      lowerCamelCase__	(   lowercase  ,   lowercase  ,   lowercase="exp"  ,   lowercase=None  ,   lowercase=False  ,   lowercase=False  ,   lowercase=None  ,   lowercase=False  ,   ):

  """simple docstring"""






  SCREAMING_SNAKE_CASE				:					str		  =			[[label] for label in labels]
  SCREAMING_SNAKE_CASE				:					Tuple		  =			list(lowercase )
  try:
    import sacrebleu as scb
  except ImportError:
    raise ValueError(
        "sacrebleu has to be installed in order to apply the bleu metric for covost2."
        "You can install it via `pip install sacrebleu`." )

  if version.parse(scb.__version__ ) < version.parse("1.4.12" ):
    raise ImportWarning(
        "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
        "You can install it with `pip install \"sacrebleu>=1.4.12\"`." )

  SCREAMING_SNAKE_CASE				:					Tuple		  =			len(labels[0] )
  if any(len(lowercase ) != references_per_prediction for refs in labels ):
    raise ValueError("Sacrebleu requires the same number of references for each prediction" )
  SCREAMING_SNAKE_CASE				:					Dict		  =			[[refs[i] for refs in labels] for i in range(lowercase )]
  SCREAMING_SNAKE_CASE				:					List[str]		  =			scb.corpus_bleu(
      lowercase  ,   lowercase  ,   smooth_method=lowercase  ,   smooth_value=lowercase  ,   force=lowercase  ,   lowercase=lowercase  ,   use_effective_order=lowercase  ,   **({"tokenize": tokenize} if tokenize else {})  ,   )
  return {"bleu": output.score}


def      lowerCamelCase__	(   lowercase  ,   lowercase  ,   lowercase  ,   lowercase ):

  """simple docstring"""






  try:
    from jiwer import compute_measures
  except ImportError:
    raise ValueError(
        F'''jiwer has to be installed in order to apply the wer metric for {config_name}.'''
        "You can install it via `pip install jiwer`." )

  if concatenate_texts:
    SCREAMING_SNAKE_CASE				:					Tuple		  =			compute_measures(lowercase  ,   lowercase )["wer"]

    SCREAMING_SNAKE_CASE				:					int		  =			compute_measures(lowercase  ,   lowercase  ,   truth_transform=lowercase  ,   hypothesis_transform=lowercase )["wer"]
    return {"wer": wer, "cer": cer}
  else:

    def compute_score(lowercase  ,   lowercase  ,   lowercase="wer" ):
      SCREAMING_SNAKE_CASE				:					Tuple		  =			0
      SCREAMING_SNAKE_CASE				:					str		  =			0
      for prediction, reference in zip(lowercase  ,   lowercase ):
        if score_type == "wer":
          SCREAMING_SNAKE_CASE				:					int		  =			compute_measures(lowercase  ,   lowercase )
        elif score_type == "cer":
          SCREAMING_SNAKE_CASE				:					int		  =			compute_measures(
              lowercase  ,   lowercase  ,   truth_transform=lowercase  ,   hypothesis_transform=lowercase )
        incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
        total += measures["substitutions"] + measures["deletions"] + measures["hits"]
      return incorrect / total

    return {"wer": compute_score(lowercase  ,   lowercase  ,   "wer" ), "cer": compute_score(lowercase  ,   lowercase  ,   "cer" )}


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					,						_KWARGS_DESCRIPTION    )
class        SCREAMING_SNAKE_CASE	(	datasets.Metric    ):
     '''simple docstring'''


     def  _A				( self				:		str					):
       if self.config_name not in _CONFIG_NAMES:
         raise KeyError(f'''You should supply a configuration name selected in {_CONFIG_NAMES}'''					)

       SCREAMING_SNAKE_CASE				:					Tuple		  =			"int64" if self.config_name in ["fleurs-lang_id", "minds14"] else "string"

       return datasets.MetricInfo(
           description=_DESCRIPTION    ,       citation=_CITATION    ,       inputs_description=_KWARGS_DESCRIPTION    ,       features=datasets.Features(
               {"predictions": datasets.Value(UpperCAmelCase_					), "references": datasets.Value(UpperCAmelCase_					)}					)    ,       codebase_urls=[]    ,       reference_urls=[]    ,       format="numpy"    ,       )






     def  _A				( self				:		Optional[Any]    ,       UpperCAmelCase_				:		int    ,       UpperCAmelCase_				:		Union[str, Any]    ,       UpperCAmelCase_				:		str=None    ,       UpperCAmelCase_				:		Dict=None					):
       SCREAMING_SNAKE_CASE				:					str		  =			bleu_kwargs if bleu_kwargs is not None else {}
       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			wer_kwargs if wer_kwargs is not None else {}

       if self.config_name == "fleurs-lang_id":
         return {"accuracy": simple_accuracy(UpperCAmelCase_    ,       UpperCAmelCase_					)}
       elif self.config_name == "minds14":
         return fa_and_simple_accuracy(UpperCAmelCase_    ,       UpperCAmelCase_					)
       elif self.config_name == "covost2":
         SCREAMING_SNAKE_CASE				:					int		  =			bleu_kwargs.pop("smooth_method"    ,       "exp"					)
         SCREAMING_SNAKE_CASE				:					Dict		  =			bleu_kwargs.pop("smooth_value"    ,       UpperCAmelCase_					)
         SCREAMING_SNAKE_CASE				:					List[Any]		  =			bleu_kwargs.pop("force"    ,       UpperCAmelCase_					)
         SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			bleu_kwargs.pop("lowercase"    ,       UpperCAmelCase_					)
         SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			bleu_kwargs.pop("tokenize"    ,       UpperCAmelCase_					)
         SCREAMING_SNAKE_CASE				:					Dict		  =			bleu_kwargs.pop("use_effective_order"    ,       UpperCAmelCase_					)
         return bleu(
             preds=UpperCAmelCase_    ,       labels=UpperCAmelCase_    ,       smooth_method=UpperCAmelCase_    ,       smooth_value=UpperCAmelCase_    ,       force=UpperCAmelCase_    ,       lowercase=UpperCAmelCase_    ,       tokenize=UpperCAmelCase_    ,       use_effective_order=UpperCAmelCase_    ,       )
       elif self.config_name in ["fleurs-asr", "mls", "voxpopuli", "babel"]:
         SCREAMING_SNAKE_CASE				:					Tuple		  =			wer_kwargs.pop("concatenate_texts"    ,       UpperCAmelCase_					)
         return wer_and_cer(UpperCAmelCase_    ,       UpperCAmelCase_    ,       UpperCAmelCase_    ,       self.config_name					)
       else:
         raise KeyError(f'''You should supply a configuration name selected in {_CONFIG_NAMES}'''					)






