





import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_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_speech_available():
							from transformers import WhisperFeatureExtractor

if is_torch_available():
							import torch

lowerCAmelCase							:       Optional[int]					 =	random.Random()






def 		lowerCAmelCase  (	UpperCamelCase__   :   Optional[Any]       ,			UpperCamelCase__   :   str=1.0       ,			UpperCamelCase__   :   Any=None       ,			UpperCamelCase__   :   Tuple=None					)      ->    Optional[Any]:

						"""simple docstring"""





						if rng is None:
												__SCREAMING_SNAKE_CASE:				Tuple           =   global_rng

						__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   []
						for batch_idx in range(shape[0]					):
												values.append([]					)
												for _ in range(shape[1]					):
																		values[-1].append(rng.random() * scale					)

						return values





@require_torch
@require_torchaudio
class 				a			(      unittest.TestCase			):






				def __init__(  self			, _lowerCAmelCase			, _lowerCAmelCase=7			, _lowerCAmelCase=400			, _lowerCAmelCase=2000			, _lowerCAmelCase=10			, _lowerCAmelCase=160			, _lowerCAmelCase=8			, _lowerCAmelCase=0.0			, _lowerCAmelCase=4000			, _lowerCAmelCase=False			, _lowerCAmelCase=True			, ):

										"""simple docstring"""




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






				def 			snake_case_    (  self					):

										"""simple docstring"""




										return {
										    "feature_size": self.feature_size,
										    "hop_length": self.hop_length,
										    "chunk_length": self.chunk_length,
										    "padding_value": self.padding_value,
										    "sampling_rate": self.sampling_rate,
										    "return_attention_mask": self.return_attention_mask,
										    "do_normalize": self.do_normalize,
										}






				def 			snake_case_    (  self			, _lowerCAmelCase=False			, _lowerCAmelCase=False					):

										"""simple docstring"""




										def _flatten(_lowerCAmelCase					):
																return list(itertools.chain(*_lowerCAmelCase					)					)

										if equal_length:
																__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   [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:				List[Any]           =   [np.asarray(_lowerCAmelCase					) for x in speech_inputs]
										return speech_inputs





@require_torch
@require_torchaudio
class 				a			(      __lowercase   ,unittest.TestCase			):
				SCREAMING_SNAKE_CASE__     :   Any		      =     WhisperFeatureExtractor if is_speech_available() else None






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				int           =   WhisperFeatureExtractionTester(self					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				List[str]           =   self.feature_extraction_class(**self.feat_extract_dict					)

										with tempfile.TemporaryDirectory() as tmpdirname:
																__SCREAMING_SNAKE_CASE:				Tuple           =   feat_extract_first.save_pretrained(_lowerCAmelCase					)[0]
																check_json_file_has_correct_format(_lowerCAmelCase					)
																__SCREAMING_SNAKE_CASE:				Tuple           =   self.feature_extraction_class.from_pretrained(_lowerCAmelCase					)

										__SCREAMING_SNAKE_CASE:				int           =   feat_extract_first.to_dict()
										__SCREAMING_SNAKE_CASE:				Optional[int]           =   feat_extract_second.to_dict()
										__SCREAMING_SNAKE_CASE:				Any           =   feat_extract_first.mel_filters
										__SCREAMING_SNAKE_CASE:				List[str]           =   feat_extract_second.mel_filters
										self.assertTrue(np.allclose(_lowerCAmelCase			, _lowerCAmelCase					)					)
										self.assertEqual(_lowerCAmelCase			, _lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""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(_lowerCAmelCase			, '''feat_extract.json'''					)
																feat_extract_first.to_json_file(_lowerCAmelCase					)
																__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   self.feature_extraction_class.from_json_file(_lowerCAmelCase					)

										__SCREAMING_SNAKE_CASE:				int           =   feat_extract_first.to_dict()
										__SCREAMING_SNAKE_CASE:				List[str]           =   feat_extract_second.to_dict()
										__SCREAMING_SNAKE_CASE:				Dict           =   feat_extract_first.mel_filters
										__SCREAMING_SNAKE_CASE:				str           =   feat_extract_second.mel_filters
										self.assertTrue(np.allclose(_lowerCAmelCase			, _lowerCAmelCase					)					)
										self.assertEqual(_lowerCAmelCase			, _lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Tuple           =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										# create three inputs of length 800, 1000, and 1200
										__SCREAMING_SNAKE_CASE:				Dict           =   [floats_list((1, x)					)[0] for x in range(800			, 1400			, 200					)]
										__SCREAMING_SNAKE_CASE:				Optional[int]           =   [np.asarray(_lowerCAmelCase					) for speech_input in speech_inputs]

										# Test feature size
										__SCREAMING_SNAKE_CASE:				Any           =   feature_extractor(_lowerCAmelCase			, padding='''max_length'''			, return_tensors='''np'''					).input_features
										self.assertTrue(input_features.ndim == 3					)
										self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames					)
										self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size					)

										# Test not batched input
										__SCREAMING_SNAKE_CASE:				Dict           =   feature_extractor(speech_inputs[0]			, return_tensors='''np'''					).input_features
										__SCREAMING_SNAKE_CASE:				int           =   feature_extractor(np_speech_inputs[0]			, return_tensors='''np'''					).input_features
										self.assertTrue(np.allclose(_lowerCAmelCase			, _lowerCAmelCase			, atol=1e-3					)					)

										# Test batched
										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   feature_extractor(_lowerCAmelCase			, return_tensors='''np'''					).input_features
										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   feature_extractor(_lowerCAmelCase			, return_tensors='''np'''					).input_features
										for enc_seq_a, enc_seq_a in zip(_lowerCAmelCase			, _lowerCAmelCase					):
																self.assertTrue(np.allclose(_lowerCAmelCase			, _lowerCAmelCase			, atol=1e-3					)					)

										# 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:				Optional[Any]           =   np.asarray(_lowerCAmelCase					)
										__SCREAMING_SNAKE_CASE:				List[str]           =   feature_extractor(_lowerCAmelCase			, return_tensors='''np'''					).input_features
										__SCREAMING_SNAKE_CASE:				int           =   feature_extractor(_lowerCAmelCase			, return_tensors='''np'''					).input_features
										for enc_seq_a, enc_seq_a in zip(_lowerCAmelCase			, _lowerCAmelCase					):
																self.assertTrue(np.allclose(_lowerCAmelCase			, _lowerCAmelCase			, atol=1e-3					)					)

										# Test truncation required
										__SCREAMING_SNAKE_CASE:				Dict           =   [floats_list((1, x)					)[0] for x in range(200			, (feature_extractor.n_samples + 500)			, 200					)]
										__SCREAMING_SNAKE_CASE:				int           =   [np.asarray(_lowerCAmelCase					) for speech_input in speech_inputs]

										__SCREAMING_SNAKE_CASE:				Dict           =   [x[: feature_extractor.n_samples] for x in speech_inputs]
										__SCREAMING_SNAKE_CASE:				List[Any]           =   [np.asarray(_lowerCAmelCase					) for speech_input in speech_inputs_truncated]

										__SCREAMING_SNAKE_CASE:				str           =   feature_extractor(_lowerCAmelCase			, return_tensors='''np'''					).input_features
										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   feature_extractor(_lowerCAmelCase			, return_tensors='''np'''					).input_features
										for enc_seq_a, enc_seq_a in zip(_lowerCAmelCase			, _lowerCAmelCase					):
																self.assertTrue(np.allclose(_lowerCAmelCase			, _lowerCAmelCase			, atol=1e-3					)					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										import torch

										__SCREAMING_SNAKE_CASE:				Tuple           =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										__SCREAMING_SNAKE_CASE:				List[str]           =   np.random.rand(100			, 32					).astype(np.floataa					)
										__SCREAMING_SNAKE_CASE:				List[Any]           =   np_speech_inputs.tolist()

										for inputs in [py_speech_inputs, np_speech_inputs]:
																__SCREAMING_SNAKE_CASE:				Dict           =   feature_extractor.pad([{'''input_features''': inputs}]			, return_tensors='''np'''					)
																self.assertTrue(np_processed.input_features.dtype == np.floataa					)
																__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   feature_extractor.pad([{'''input_features''': inputs}]			, return_tensors='''pt'''					)
																self.assertTrue(pt_processed.input_features.dtype == torch.floataa					)






				def 			snake_case_    (  self			, _lowerCAmelCase					):

										"""simple docstring"""




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

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






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Any           =   torch.tensor(
										    [
										        0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951,
										        0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678,
										        0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554,
										        -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854
										    ]					)
										# fmt: on

										__SCREAMING_SNAKE_CASE:				List[str]           =   self._load_datasamples(1					)
										__SCREAMING_SNAKE_CASE:				int           =   WhisperFeatureExtractor()
										__SCREAMING_SNAKE_CASE:				Tuple           =   feature_extractor(_lowerCAmelCase			, return_tensors='''pt'''					).input_features
										self.assertEqual(input_features.shape			, (1, 80, 3000)					)
										self.assertTrue(torch.allclose(input_features[0, 0, :30]			, _lowerCAmelCase			, atol=1e-4					)					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Optional[int]           =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										__SCREAMING_SNAKE_CASE:				int           =   self._load_datasamples(1					)[0]
										__SCREAMING_SNAKE_CASE:				List[str]           =   ((audio - audio.min()) / (audio.max() - audio.min())) * 65535  # Rescale to [0, 65535] to show issue
										__SCREAMING_SNAKE_CASE:				Any           =   feat_extract.zero_mean_unit_var_norm([audio]			, attention_mask=_lowerCAmelCase					)[0]

										self.assertTrue(np.all(np.mean(_lowerCAmelCase					) < 1e-3					)					)
										self.assertTrue(np.all(np.abs(np.var(_lowerCAmelCase					) - 1					) < 1e-3					)					)










import re






def 		lowerCAmelCase  (	UpperCamelCase__   :   str					)      ->    bool:

						"""simple docstring"""





						__SCREAMING_SNAKE_CASE:				Optional[int]           =   re.compile(
						    R'''^(?:0|94|\+94|0{2}94)''' R'''7(0|1|2|4|5|6|7|8)''' R'''(-| |)''' R'''\d{7}$'''					)

						return bool(re.search(UpperCamelCase__       ,			UpperCamelCase__					)					)


if __name__ == "__main__":
							lowerCAmelCase							:       str					 =	"""0094702343221"""

							print(is_sri_lankan_phone_number(phone))



