
"""simple docstring"""




import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
UpperCAmelCase__   :					Any												=				pytest.mark.integration


UpperCAmelCase__   :					List[str]												=				{"comet"}
UpperCAmelCase__   :					List[str]												=				importlib.util.find_spec('fairseq') is not None

UpperCAmelCase__   :					Optional[int]												=				{"code_eval"}
UpperCAmelCase__   :					Optional[Any]												=				os.name == "nt"

UpperCAmelCase__   :					Tuple												=				{"bertscore", "frugalscore", "perplexity"}
UpperCAmelCase__   :					str												=				importlib.util.find_spec('transformers') is not None

def lowercase_						(     _snake_case		):


       @wraps(__snake_case		)
       def wrapper(self     ,_snake_case		):
              if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
                     self.skipTest("""\"test requires Fairseq\""""		)
              else:
                     test_case(self     ,__snake_case		)

       return wrapper

def lowercase_						(     _snake_case		):


       @wraps(__snake_case		)
       def wrapper(self     ,_snake_case		):
              if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
                     self.skipTest("""\"test requires transformers\""""		)
              else:
                     test_case(self     ,__snake_case		)

       return wrapper

def lowercase_						(     _snake_case		):


       @wraps(__snake_case		)
       def wrapper(self     ,_snake_case		):
              if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
                     self.skipTest("""\"test not supported on Windows\""""		)
              else:
                     test_case(self     ,__snake_case		)

       return wrapper

def lowercase_						(     ):
       SCREAMING_SNAKE_CASE__		: List[str]     =     [metric_dir.split(os.sep		)[-2] for metric_dir in glob.glob("""./metrics/*/"""		)]
       return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished



@parameterized.named_parameters(get_local_metric_names()						)
@for_all_test_methods(
    _A				,      _A				,      _A						)
@local
class 			lowerCAmelCase_		(parameterized.TestCase						):


    """simple docstring"""



    __UpperCamelCase   :		int       =     {}
    __UpperCamelCase   :		str       =     None



    @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning"""					)
    @pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning"""					)
    def 			__magic_name__					(self     , SCREAMING_SNAKE_CASE__					)      ->	Optional[Any]:



           """simple docstring"""




           SCREAMING_SNAKE_CASE__		: List[Any]     =     "[...]"
           SCREAMING_SNAKE_CASE__		: List[Any]     =     importlib.import_module(
               datasets.load.metric_module_factory(os.path.join("""metrics"""     , SCREAMING_SNAKE_CASE__					)					).module_path					)
           SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     datasets.load.import_main_class(metric_module.__name__     , dataset=SCREAMING_SNAKE_CASE__					)
           # check parameters
           SCREAMING_SNAKE_CASE__		: Optional[int]     =     inspect.signature(metric._compute					).parameters
           self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()					)					)  # no **kwargs
           # run doctest
           with self.patch_intensive_calls(SCREAMING_SNAKE_CASE__     , metric_module.__name__					):
                  with self.use_local_metrics():
                         try:
                                SCREAMING_SNAKE_CASE__		: Tuple     =     doctest.testmod(SCREAMING_SNAKE_CASE__     , verbose=SCREAMING_SNAKE_CASE__     , raise_on_error=SCREAMING_SNAKE_CASE__					)
                         except doctest.UnexpectedException as e:
                                raise e.exc_info[1]  # raise the exception that doctest caught
           self.assertEqual(results.failed     , 0					)
           self.assertGreater(results.attempted     , 1					)



    @slow
    def 			__magic_name__					(self     , SCREAMING_SNAKE_CASE__					)      ->	Dict:



           """simple docstring"""




           SCREAMING_SNAKE_CASE__		: List[Any]     =     "[...]"
           SCREAMING_SNAKE_CASE__		: Optional[Any]     =     importlib.import_module(
               datasets.load.metric_module_factory(os.path.join("""metrics"""     , SCREAMING_SNAKE_CASE__					)					).module_path					)
           # run doctest
           with self.use_local_metrics():
                  SCREAMING_SNAKE_CASE__		: str     =     doctest.testmod(SCREAMING_SNAKE_CASE__     , verbose=SCREAMING_SNAKE_CASE__     , raise_on_error=SCREAMING_SNAKE_CASE__					)
           self.assertEqual(results.failed     , 0					)
           self.assertGreater(results.attempted     , 1					)



    @contextmanager
    def 			__magic_name__					(self     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__					)      ->	Optional[int]:



           """simple docstring"""




           if metric_name in self.INTENSIVE_CALLS_PATCHER:
                  with self.INTENSIVE_CALLS_PATCHER[metric_name](SCREAMING_SNAKE_CASE__					):
                         yield
           else:
                  yield



    @contextmanager
    def 			__magic_name__					(self					)      ->	Dict:



           """simple docstring"""




           def load_local_metric(SCREAMING_SNAKE_CASE__     , *SCREAMING_SNAKE_CASE__     , **SCREAMING_SNAKE_CASE__					):
                  return load_metric(os.path.join("""metrics"""     , SCREAMING_SNAKE_CASE__					)     , *SCREAMING_SNAKE_CASE__     , **SCREAMING_SNAKE_CASE__					)

           with patch("""datasets.load_metric"""					) as mock_load_metric:
                  SCREAMING_SNAKE_CASE__		: Any     =     load_local_metric
                  yield



    @classmethod
    def 			__magic_name__					(cls     , SCREAMING_SNAKE_CASE__					)      ->	Any:



           """simple docstring"""




           def wrapper(SCREAMING_SNAKE_CASE__					):
                  SCREAMING_SNAKE_CASE__		: Optional[Any]     =     contextmanager(SCREAMING_SNAKE_CASE__					)
                  SCREAMING_SNAKE_CASE__		: Optional[Any]     =     patcher
                  return patcher

           return wrapper






@LocalMetricTest.register_intensive_calls_patcher("""bleurt"""		)
def lowercase_						(     _snake_case		):
       import tensorflow.compat.va as tf
       from bleurt.score import Predictor

       tf.flags.DEFINE_string("""sv"""     ,""""""     ,""""""		)  # handle pytest cli flags



       class 			lowerCAmelCase_		(_A						):


           """simple docstring"""



           def 			__magic_name__					(self     , SCREAMING_SNAKE_CASE__					)      ->	List[str]:



                  """simple docstring"""




                  assert len(input_dict["""input_ids"""]					) == 2
                  return np.array([1.03, 1.04]					)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
       with patch("""bleurt.score._create_predictor"""		) as mock_create_predictor:
              SCREAMING_SNAKE_CASE__		: List[Any]     =     MockedPredictor()
              yield

@LocalMetricTest.register_intensive_calls_patcher("""bertscore"""		)
def lowercase_						(     _snake_case		):
       import torch

       def bert_cos_score_idf(_snake_case     ,_snake_case     ,*_snake_case     ,**_snake_case		):
              return torch.tensor([[1.0, 1.0, 1.0]] * len(__snake_case		)		)

       # mock get_model which is supposed to do download a bert model
       # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
       with patch("""bert_score.scorer.get_model"""		), patch(
           """bert_score.scorer.bert_cos_score_idf"""		) as mock_bert_cos_score_idf:
              SCREAMING_SNAKE_CASE__		: Any     =     bert_cos_score_idf
              yield

@LocalMetricTest.register_intensive_calls_patcher("""comet"""		)
def lowercase_						(     _snake_case		):


       def load_from_checkpoint(_snake_case		):



              class 			lowerCAmelCase_		:


                  """simple docstring"""



                  def 			__magic_name__					(self     , SCREAMING_SNAKE_CASE__     , *SCREAMING_SNAKE_CASE__     , **SCREAMING_SNAKE_CASE__					)      ->	Dict:



                         """simple docstring"""




                         assert len(SCREAMING_SNAKE_CASE__					) == 2
                         SCREAMING_SNAKE_CASE__		: int     =     [0.19, 0.92]
                         return scores, sum(SCREAMING_SNAKE_CASE__					) / len(SCREAMING_SNAKE_CASE__					)






              return Model()

       # mock load_from_checkpoint which is supposed to do download a bert model
       # mock load_from_checkpoint which is supposed to do download a bert model
       with patch("""comet.download_model"""		) as mock_download_model:
              SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     None
              with patch("""comet.load_from_checkpoint"""		) as mock_load_from_checkpoint:
                     SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     load_from_checkpoint
                     yield

def lowercase_						(     ):
       SCREAMING_SNAKE_CASE__		: Optional[Any]     =     load_metric(os.path.join("""metrics"""     ,"""seqeval"""		)		)
       SCREAMING_SNAKE_CASE__		: List[str]     =     "ERROR"
       SCREAMING_SNAKE_CASE__		: Dict     =     f'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'''
       with pytest.raises(__snake_case     ,match=re.escape(__snake_case		)		):
              metric.compute(predictions=[]     ,references=[]     ,scheme=__snake_case		)






"""simple docstring"""




import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase__   :					str												=				logging.get_logger(__name__)

UpperCAmelCase__   :					Dict												=				{
    'microsoft/unispeech-large-1500h-cv': (
        'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json'
    ),
    # See all UniSpeech models at https://huggingface.co/models?filter=unispeech
}



class 			lowerCAmelCase_		(a__						):


				"""simple docstring"""



				__UpperCamelCase   :		List[str]       =     '''unispeech'''



				def __init__(self     , SCREAMING_SNAKE_CASE__=32     , SCREAMING_SNAKE_CASE__=7_68     , SCREAMING_SNAKE_CASE__=12     , SCREAMING_SNAKE_CASE__=12     , SCREAMING_SNAKE_CASE__=30_72     , SCREAMING_SNAKE_CASE__="gelu"     , SCREAMING_SNAKE_CASE__=0.1     , SCREAMING_SNAKE_CASE__=0.1     , SCREAMING_SNAKE_CASE__=0.1     , SCREAMING_SNAKE_CASE__=0.0     , SCREAMING_SNAKE_CASE__=0.0     , SCREAMING_SNAKE_CASE__=0.1     , SCREAMING_SNAKE_CASE__=0.1     , SCREAMING_SNAKE_CASE__=0.02     , SCREAMING_SNAKE_CASE__=1E-5     , SCREAMING_SNAKE_CASE__="group"     , SCREAMING_SNAKE_CASE__="gelu"     , SCREAMING_SNAKE_CASE__=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12)     , SCREAMING_SNAKE_CASE__=(5, 2, 2, 2, 2, 2, 2)     , SCREAMING_SNAKE_CASE__=(10, 3, 3, 3, 3, 2, 2)     , SCREAMING_SNAKE_CASE__=False     , SCREAMING_SNAKE_CASE__=1_28     , SCREAMING_SNAKE_CASE__=16     , SCREAMING_SNAKE_CASE__=False     , SCREAMING_SNAKE_CASE__=True     , SCREAMING_SNAKE_CASE__=0.05     , SCREAMING_SNAKE_CASE__=10     , SCREAMING_SNAKE_CASE__=2     , SCREAMING_SNAKE_CASE__=0.0     , SCREAMING_SNAKE_CASE__=10     , SCREAMING_SNAKE_CASE__=0     , SCREAMING_SNAKE_CASE__=3_20     , SCREAMING_SNAKE_CASE__=2     , SCREAMING_SNAKE_CASE__=0.1     , SCREAMING_SNAKE_CASE__=1_00     , SCREAMING_SNAKE_CASE__=2_56     , SCREAMING_SNAKE_CASE__=2_56     , SCREAMING_SNAKE_CASE__=0.1     , SCREAMING_SNAKE_CASE__="mean"     , SCREAMING_SNAKE_CASE__=False     , SCREAMING_SNAKE_CASE__=False     , SCREAMING_SNAKE_CASE__=2_56     , SCREAMING_SNAKE_CASE__=80     , SCREAMING_SNAKE_CASE__=0     , SCREAMING_SNAKE_CASE__=1     , SCREAMING_SNAKE_CASE__=2     , SCREAMING_SNAKE_CASE__=0.5     , **SCREAMING_SNAKE_CASE__     , )      ->	List[Any]:



											"""simple docstring"""




											super().__init__(**SCREAMING_SNAKE_CASE__     , pad_token_id=SCREAMING_SNAKE_CASE__     , bos_token_id=SCREAMING_SNAKE_CASE__     , eos_token_id=SCREAMING_SNAKE_CASE__					)
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     hidden_size
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     feat_extract_norm
											SCREAMING_SNAKE_CASE__		: Any     =     feat_extract_activation
											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     list(SCREAMING_SNAKE_CASE__					)
											SCREAMING_SNAKE_CASE__		: str     =     list(SCREAMING_SNAKE_CASE__					)
											SCREAMING_SNAKE_CASE__		: Tuple     =     list(SCREAMING_SNAKE_CASE__					)
											SCREAMING_SNAKE_CASE__		: List[str]     =     conv_bias
											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     num_conv_pos_embeddings
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     num_conv_pos_embedding_groups
											SCREAMING_SNAKE_CASE__		: Dict     =     len(self.conv_dim					)
											SCREAMING_SNAKE_CASE__		: List[str]     =     num_hidden_layers
											SCREAMING_SNAKE_CASE__		: str     =     intermediate_size
											SCREAMING_SNAKE_CASE__		: Optional[int]     =     hidden_act
											SCREAMING_SNAKE_CASE__		: Any     =     num_attention_heads
											SCREAMING_SNAKE_CASE__		: Dict     =     hidden_dropout
											SCREAMING_SNAKE_CASE__		: List[str]     =     attention_dropout
											SCREAMING_SNAKE_CASE__		: Any     =     activation_dropout
											SCREAMING_SNAKE_CASE__		: int     =     feat_proj_dropout
											SCREAMING_SNAKE_CASE__		: List[Any]     =     final_dropout
											SCREAMING_SNAKE_CASE__		: str     =     layerdrop
											SCREAMING_SNAKE_CASE__		: Optional[int]     =     layer_norm_eps
											SCREAMING_SNAKE_CASE__		: Dict     =     initializer_range
											SCREAMING_SNAKE_CASE__		: Dict     =     num_ctc_classes
											SCREAMING_SNAKE_CASE__		: List[Any]     =     vocab_size
											SCREAMING_SNAKE_CASE__		: str     =     do_stable_layer_norm
											SCREAMING_SNAKE_CASE__		: Dict     =     use_weighted_layer_sum
											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     classifier_proj_size

											if (
											    (len(self.conv_stride					) != self.num_feat_extract_layers)
											    or (len(self.conv_kernel					) != self.num_feat_extract_layers)
											    or (len(self.conv_dim					) != self.num_feat_extract_layers)
											):
																		raise ValueError(
																		    """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
																		    """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
																		    F''' {len(self.conv_dim					)}`, `len(config.conv_stride) = {len(self.conv_stride					)}`,'''
																		    F''' `len(config.conv_kernel) = {len(self.conv_kernel					)}`.'''					)

											# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
											SCREAMING_SNAKE_CASE__		: Tuple     =     apply_spec_augment
											SCREAMING_SNAKE_CASE__		: Optional[int]     =     mask_time_prob
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     mask_time_length
											SCREAMING_SNAKE_CASE__		: List[str]     =     mask_time_min_masks
											SCREAMING_SNAKE_CASE__		: Tuple     =     mask_feature_prob
											SCREAMING_SNAKE_CASE__		: Any     =     mask_feature_length
											SCREAMING_SNAKE_CASE__		: int     =     mask_feature_min_masks

											# parameters for pretraining with codevector quantized representations
											SCREAMING_SNAKE_CASE__		: Dict     =     num_codevectors_per_group
											SCREAMING_SNAKE_CASE__		: Any     =     num_codevector_groups
											SCREAMING_SNAKE_CASE__		: str     =     contrastive_logits_temperature
											SCREAMING_SNAKE_CASE__		: str     =     feat_quantizer_dropout
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     num_negatives
											SCREAMING_SNAKE_CASE__		: Tuple     =     codevector_dim
											SCREAMING_SNAKE_CASE__		: List[Any]     =     proj_codevector_dim
											SCREAMING_SNAKE_CASE__		: Tuple     =     diversity_loss_weight

											# ctc loss
											SCREAMING_SNAKE_CASE__		: int     =     ctc_loss_reduction
											SCREAMING_SNAKE_CASE__		: str     =     ctc_zero_infinity

											# pretraining loss
											SCREAMING_SNAKE_CASE__		: List[str]     =     replace_prob



				@property
				def 			__magic_name__					(self					)      ->	Tuple:



											"""simple docstring"""




											return functools.reduce(operator.mul     , self.conv_stride     , 1					)




