






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	: Optional[int]    		=  pytest.mark.integration


__UpperCamelCase	: int    		=  {'comet'}
__UpperCamelCase	: Optional[int]    		=  importlib.util.find_spec('fairseq') is not None

__UpperCamelCase	: Optional[Any]    		=  {'code_eval'}
__UpperCamelCase	: List[str]    		=  os.name == 'nt'

__UpperCamelCase	: Optional[Any]    		=  {'bertscore', 'frugalscore', 'perplexity'}
__UpperCamelCase	: Dict    		=  importlib.util.find_spec('transformers') is not None
def    A			(					_lowercase		):
						@wraps(_lowercase		)
						def wrapper(self	,						_lowercase		):
												if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
																		self.skipTest('''"test requires Fairseq"'''		)
												else:
																		test_case(self	,						_lowercase		)

						return wrapper
def    A			(					_lowercase		):
						@wraps(_lowercase		)
						def wrapper(self	,						_lowercase		):
												if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
																		self.skipTest('''"test requires transformers"'''		)
												else:
																		test_case(self	,						_lowercase		)

						return wrapper
def    A			(					_lowercase		):
						@wraps(_lowercase		)
						def wrapper(self	,						_lowercase		):
												if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
																		self.skipTest('''"test not supported on Windows"'''		)
												else:
																		test_case(self	,						_lowercase		)

						return wrapper
def    A			(					):
						SCREAMING_SNAKE_CASE							:					List[Any]           =							[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(
    UpperCamelCase_			,							UpperCamelCase_			,							UpperCamelCase_)
@local
class       lowercase__		(     parameterized.TestCase):
						UpperCamelCase_  =	{}
						UpperCamelCase_  =	None


						@pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning'''		)
						@pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning'''		)
						def  __A ( self			:       Dict					,	UpperCamelCase__			:       int		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					int           =							'''[...]'''
												SCREAMING_SNAKE_CASE							:					List[Any]           =							importlib.import_module(
												    datasets.load.metric_module_factory(os.path.join('''metrics'''					,	UpperCamelCase__		)		).module_path		)
												SCREAMING_SNAKE_CASE							:					List[str]           =							datasets.load.import_main_class(metric_module.__name__					,	dataset=UpperCamelCase__		)
												# 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(UpperCamelCase__					,	metric_module.__name__		):
																		with self.use_local_metrics():
																								try:
																														SCREAMING_SNAKE_CASE							:					Tuple           =							doctest.testmod(UpperCamelCase__					,	verbose=UpperCamelCase__					,	raise_on_error=UpperCamelCase__		)
																								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  __A ( self			:       Optional[Any]					,	UpperCamelCase__			:       Dict		):





												'''simple docstring'''





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


						@contextmanager
						def  __A ( self			:       int					,	UpperCamelCase__			:       Any					,	UpperCamelCase__			:       List[str]		):





												'''simple docstring'''





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


						@contextmanager
						def  __A ( self			:       Optional[Any]		):





												'''simple docstring'''





												def load_local_metric(UpperCamelCase__			:       List[Any]					,	*UpperCamelCase__			:       str					,	**UpperCamelCase__			:       Any		):
																		return load_metric(os.path.join('''metrics'''					,	UpperCamelCase__		)					,	*UpperCamelCase__					,	**UpperCamelCase__		)

												with patch('''datasets.load_metric'''		) as mock_load_metric:
																		SCREAMING_SNAKE_CASE							:					Optional[Any]           =							load_local_metric
																		yield



						@classmethod
						def  __A ( cls			:       str					,	UpperCamelCase__			:       Dict		):





												'''simple docstring'''





												def wrapper(UpperCamelCase__			:       Dict		):
																		SCREAMING_SNAKE_CASE							:					Optional[Any]           =							contextmanager(UpperCamelCase__		)
																		SCREAMING_SNAKE_CASE							:					Dict           =							patcher
																		return patcher

												return wrapper






@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''		)
def    A			(					_lowercase		):
						import tensorflow.compat.va as tf
						from bleurt.score import Predictor

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





						class       lowercase__		(     UpperCamelCase_):


												def  __A ( self			:       Optional[int]					,	UpperCamelCase__			:       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[str]           =							MockedPredictor()
												yield
@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''		)
def    A			(					_lowercase		):
						import torch

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

						# 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    A			(					_lowercase		):
						def load_from_checkpoint(_lowercase		):





												class       lowercase__		:


																		def  __A ( self			:       Any					,	UpperCamelCase__			:       Optional[int]					,	*UpperCamelCase__			:       List[str]					,	**UpperCamelCase__			:       int		):





																								'''simple docstring'''





																								assert len(UpperCamelCase__		) == 2
																								SCREAMING_SNAKE_CASE							:					str           =							[0.19, 0.92]
																								return scores, sum(UpperCamelCase__		) / len(UpperCamelCase__		)






												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							:					int           =							None
												with patch('''comet.load_from_checkpoint'''		) as mock_load_from_checkpoint:
																		SCREAMING_SNAKE_CASE							:					Any           =							load_from_checkpoint
																		yield



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






import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
					import torch

if is_datasets_available():
					from datasets import load_dataset

__UpperCamelCase	: Dict    		=  random.Random()
def    A			(					_lowercase	,						_lowercase=1.0	,						_lowercase=None	,						_lowercase=None		):
						if rng is None:
												SCREAMING_SNAKE_CASE							:					Any           =							global_rng

						SCREAMING_SNAKE_CASE							:					int           =							[]
						for batch_idx in range(shape[0]		):
												values.append([]		)
												for _ in range(shape[1]		):
																		values[-1].append(rng.random() * scale		)

						return values





class       lowercase__		(     unittest.TestCase):


						def __init__( self			:       List[Any]					,	UpperCamelCase__			:       Optional[int]					,	UpperCamelCase__			:       str=7					,	UpperCamelCase__			:       Any=400					,	UpperCamelCase__			:       List[str]=2000					,	UpperCamelCase__			:       List[Any]=2048					,	UpperCamelCase__			:       Any=128					,	UpperCamelCase__			:       Union[str, Any]=1					,	UpperCamelCase__			:       List[Any]=512					,	UpperCamelCase__			:       str=30					,	UpperCamelCase__			:       Tuple=4_4100					,	):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					str           =							parent
												SCREAMING_SNAKE_CASE							:					str           =							batch_size
												SCREAMING_SNAKE_CASE							:					str           =							min_seq_length
												SCREAMING_SNAKE_CASE							:					Dict           =							max_seq_length
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							spectrogram_length
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							feature_size
												SCREAMING_SNAKE_CASE							:					Tuple           =							num_audio_channels
												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							hop_length
												SCREAMING_SNAKE_CASE							:					List[Any]           =							chunk_length
												SCREAMING_SNAKE_CASE							:					str           =							sampling_rate


						def  __A ( self			:       Optional[Any]		):





												'''simple docstring'''





												return {
												    "spectrogram_length": self.spectrogram_length,
												    "feature_size": self.feature_size,
												    "num_audio_channels": self.num_audio_channels,
												    "hop_length": self.hop_length,
												    "chunk_length": self.chunk_length,
												    "sampling_rate": self.sampling_rate,
												}



						def  __A ( self			:       Tuple					,	UpperCamelCase__			:       List[str]=False					,	UpperCamelCase__			:       Optional[int]=False		):





												'''simple docstring'''





												def _flatten(UpperCamelCase__			:       str		):
																		return list(itertools.chain(*UpperCamelCase__		)		)

												if equal_length:
																		SCREAMING_SNAKE_CASE							:					List[str]           =							[floats_list((self.max_seq_length, self.feature_size)		) for _ in range(self.batch_size		)]
												else:
																		# make sure that inputs increase in size
																		SCREAMING_SNAKE_CASE							:					int           =							[
																		    floats_list((x, self.feature_size)		)
																		    for x in range(self.min_seq_length					,	self.max_seq_length					,	self.seq_length_diff		)
																		]
												if numpify:
																		SCREAMING_SNAKE_CASE							:					Optional[Any]           =							[np.asarray(UpperCamelCase__		) for x in speech_inputs]
												return speech_inputs






@require_torch
@require_torchaudio
class       lowercase__		(     UpperCamelCase_			,							unittest.TestCase):
						UpperCamelCase_  =	TvltFeatureExtractor


						def  __A ( self			:       List[str]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Dict           =							TvltFeatureExtractionTester(self		)


						def  __A ( self			:       Union[str, Any]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Any           =							self.feature_extraction_class(**self.feat_extract_dict		)
												self.assertTrue(hasattr(UpperCamelCase__					,	'''spectrogram_length'''		)		)
												self.assertTrue(hasattr(UpperCamelCase__					,	'''feature_size'''		)		)
												self.assertTrue(hasattr(UpperCamelCase__					,	'''num_audio_channels'''		)		)
												self.assertTrue(hasattr(UpperCamelCase__					,	'''hop_length'''		)		)
												self.assertTrue(hasattr(UpperCamelCase__					,	'''chunk_length'''		)		)
												self.assertTrue(hasattr(UpperCamelCase__					,	'''sampling_rate'''		)		)


						def  __A ( self			:       Union[str, Any]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							self.feature_extraction_class(**self.feat_extract_dict		)

												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:					Optional[Any]           =							feat_extract_first.save_pretrained(UpperCamelCase__		)[0]
																		check_json_file_has_correct_format(UpperCamelCase__		)
																		SCREAMING_SNAKE_CASE							:					List[Any]           =							self.feature_extraction_class.from_pretrained(UpperCamelCase__		)

												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							feat_extract_first.to_dict()
												SCREAMING_SNAKE_CASE							:					str           =							feat_extract_second.to_dict()
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							dict_first.pop('''mel_filters'''		)
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							dict_second.pop('''mel_filters'''		)
												self.assertTrue(np.allclose(UpperCamelCase__					,	UpperCamelCase__		)		)
												self.assertEqual(UpperCamelCase__					,	UpperCamelCase__		)


						def  __A ( self			:       int		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Dict           =							self.feature_extraction_class(**self.feat_extract_dict		)

												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:					Tuple           =							os.path.join(UpperCamelCase__					,	'''feat_extract.json'''		)
																		feat_extract_first.to_json_file(UpperCamelCase__		)
																		SCREAMING_SNAKE_CASE							:					List[str]           =							self.feature_extraction_class.from_json_file(UpperCamelCase__		)

												SCREAMING_SNAKE_CASE							:					Any           =							feat_extract_first.to_dict()
												SCREAMING_SNAKE_CASE							:					str           =							feat_extract_second.to_dict()
												SCREAMING_SNAKE_CASE							:					int           =							dict_first.pop('''mel_filters'''		)
												SCREAMING_SNAKE_CASE							:					Any           =							dict_second.pop('''mel_filters'''		)
												self.assertTrue(np.allclose(UpperCamelCase__					,	UpperCamelCase__		)		)
												self.assertEqual(UpperCamelCase__					,	UpperCamelCase__		)


						def  __A ( self			:       Any		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					int           =							self.feature_extraction_class(**self.feat_extract_dict		)

												# create three inputs of length 800, 1000, and 1200
												SCREAMING_SNAKE_CASE							:					List[Any]           =							[floats_list((1, x)		)[0] for x in range(800					,	1400					,	200		)]
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							[np.asarray(UpperCamelCase__		) for speech_input in speech_inputs]

												# Test not batched input
												SCREAMING_SNAKE_CASE							:					List[Any]           =							feature_extractor(np_speech_inputs[0]					,	return_tensors='''np'''					,	sampling_rate=4_4100		).audio_values

												self.assertTrue(encoded_audios.ndim == 4		)
												self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
												self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
												self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)

												# Test batched
												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							feature_extractor(UpperCamelCase__					,	return_tensors='''np'''					,	sampling_rate=4_4100		).audio_values

												self.assertTrue(encoded_audios.ndim == 4		)
												self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
												self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
												self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)

												# Test audio masking
												SCREAMING_SNAKE_CASE							:					List[str]           =							feature_extractor(
												    UpperCamelCase__					,	return_tensors='''np'''					,	sampling_rate=4_4100					,	mask_audio=UpperCamelCase__		).audio_values

												self.assertTrue(encoded_audios.ndim == 4		)
												self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
												self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
												self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)

												# Test 2-D numpy arrays are batched.
												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							[floats_list((1, x)		)[0] for x in (800, 800, 800)]
												SCREAMING_SNAKE_CASE							:					Dict           =							np.asarray(UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					str           =							feature_extractor(UpperCamelCase__					,	return_tensors='''np'''					,	sampling_rate=4_4100		).audio_values
												self.assertTrue(encoded_audios.ndim == 4		)
												self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
												self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
												self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)


						def  __A ( self			:       Optional[int]					,	UpperCamelCase__			:       int		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					List[str]           =							load_dataset('''hf-internal-testing/librispeech_asr_dummy'''					,	'''clean'''					,	split='''validation'''		)
												# automatic decoding with librispeech
												SCREAMING_SNAKE_CASE							:					Dict           =							ds.sort('''id'''		).select(range(UpperCamelCase__		)		)[:num_samples]['''audio''']

												return [x["array"] for x in speech_samples]



						def  __A ( self			:       List[Any]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							self._load_datasamples(1		)
												SCREAMING_SNAKE_CASE							:					int           =							TvltFeatureExtractor()
												SCREAMING_SNAKE_CASE							:					List[Any]           =							feature_extractor(UpperCamelCase__					,	return_tensors='''pt'''		).audio_values

												self.assertEquals(audio_values.shape					,	(1, 1, 192, 128)		)

												SCREAMING_SNAKE_CASE							:					str           =							torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]]		)
												self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]					,	UpperCamelCase__					,	atol=1E-4		)		)





