





import itertools
import random
import unittest

import numpy as np

from transformers import is_speech_available
from transformers.testing_utils import require_torch, require_torchaudio

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
					from transformers import SpeechaTextFeatureExtractor

UpperCAmelCase_ 							=       random.Random()





def   lowerCamelCase__       (       UpperCamelCase__     :    str    ,      UpperCamelCase__     :    Optional[int]=1.0    ,      UpperCamelCase__     :    Dict=None    ,      UpperCamelCase__     :    Optional[Any]=None  )     ->	Any:



					'''simple docstring'''




					if rng is None:
										_snake_case													=			global_rng

					_snake_case													=			[]
					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      UpperCamelCase_						(					unittest.TestCase   ):




					def __init__(						self			,  lowerCAmelCase_			,  lowerCAmelCase_=7			,  lowerCAmelCase_=400			,  lowerCAmelCase_=2000			,  lowerCAmelCase_=24			,  lowerCAmelCase_=24			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=1_6000			,  lowerCAmelCase_=True			,  lowerCAmelCase_=True			,  )						->							Optional[Any]:
										_snake_case													=			parent
										_snake_case													=			batch_size
										_snake_case													=			min_seq_length
										_snake_case													=			max_seq_length
										_snake_case													=			(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
										_snake_case													=			feature_size
										_snake_case													=			num_mel_bins
										_snake_case													=			padding_value
										_snake_case													=			sampling_rate
										_snake_case													=			return_attention_mask
										_snake_case													=			do_normalize




					def 		lowerCAmelCase     (						self					)						->							Dict:
										return {
										    "feature_size": self.feature_size,
										    "num_mel_bins": self.num_mel_bins,
										    "padding_value": self.padding_value,
										    "sampling_rate": self.sampling_rate,
										    "return_attention_mask": self.return_attention_mask,
										    "do_normalize": self.do_normalize,
										}






					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_=False			,  lowerCAmelCase_=False					)						->							Optional[Any]:
										def _flatten(lowerCAmelCase_					):
															return list(itertools.chain(*lowerCAmelCase_					)					)

										if equal_length:
															_snake_case													=			[floats_list((self.max_seq_length, self.feature_size)					) for _ in range(self.batch_size					)]
										else:
															# make sure that inputs increase in size
															_snake_case													=			[
															    floats_list((x, self.feature_size)					)
															    for x in range(self.min_seq_length			,  self.max_seq_length			,  self.seq_length_diff					)
															]
										if numpify:
															_snake_case													=			[np.asarray(lowerCAmelCase_					) for x in speech_inputs]
										return speech_inputs





@require_torch
@require_torchaudio
class      UpperCamelCase_						(					_lowerCamelCase							,					unittest.TestCase   ):
					lowerCAmelCase_							=		SpeechaTextFeatureExtractor if is_speech_available() else None




					def 		lowerCAmelCase     (						self					)						->							Optional[int]:
										_snake_case													=			SpeechaTextFeatureExtractionTester(self					)




					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_					)						->							Union[str, Any]:
										self.assertTrue(np.all(np.mean(lowerCAmelCase_			,  axis=0					) < 1E-3					)					)
										self.assertTrue(np.all(np.abs(np.var(lowerCAmelCase_			,  axis=0					) - 1					) < 1E-3					)					)




					def 		lowerCAmelCase     (						self					)						->							Optional[Any]:
										# Tests that all call wrap to encode_plus and batch_encode_plus
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										# create three inputs of length 800, 1000, and 1200
										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]
										_snake_case													=			[np.asarray(lowerCAmelCase_					) for speech_input in speech_inputs]

										# Test feature size
										_snake_case													=			feature_extractor(lowerCAmelCase_			,  padding=lowerCAmelCase_			,  return_tensors='np'					).input_features
										self.assertTrue(input_features.ndim == 3					)
										self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size					)

										# Test not batched input
										_snake_case													=			feature_extractor(speech_inputs[0]			,  return_tensors='np'					).input_features
										_snake_case													=			feature_extractor(np_speech_inputs[0]			,  return_tensors='np'					).input_features
										self.assertTrue(np.allclose(lowerCAmelCase_			,  lowerCAmelCase_			,  atol=1E-3					)					)

										# Test batched
										_snake_case													=			feature_extractor(lowerCAmelCase_			,  return_tensors='np'					).input_features
										_snake_case													=			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.
										_snake_case													=			[floats_list((1, x)					)[0] for x in (800, 800, 800)]
										_snake_case													=			np.asarray(lowerCAmelCase_					)
										_snake_case													=			feature_extractor(lowerCAmelCase_			,  return_tensors='np'					).input_features
										_snake_case													=			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 		lowerCAmelCase     (						self					)						->							Dict:
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]

										_snake_case													=			['longest', 'max_length', 'do_not_pad']
										_snake_case													=			[None, 16, None]
										for max_length, padding in zip(lowerCAmelCase_			,  lowerCAmelCase_					):
															_snake_case													=			feature_extractor(
															    lowerCAmelCase_			,  padding=lowerCAmelCase_			,  max_length=lowerCAmelCase_			,  return_attention_mask=lowerCAmelCase_					)
															_snake_case													=			inputs.input_features
															_snake_case													=			inputs.attention_mask
															_snake_case													=			[np.sum(lowerCAmelCase_					) for x in attention_mask]

															self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]					)
															self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]					)
															self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]					)




					def 		lowerCAmelCase     (						self					)						->							List[Any]:
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]

										_snake_case													=			['longest', 'max_length', 'do_not_pad']
										_snake_case													=			[None, 16, None]
										for max_length, padding in zip(lowerCAmelCase_			,  lowerCAmelCase_					):
															_snake_case													=			feature_extractor(
															    lowerCAmelCase_			,  max_length=lowerCAmelCase_			,  padding=lowerCAmelCase_			,  return_tensors='np'			,  return_attention_mask=lowerCAmelCase_					)
															_snake_case													=			inputs.input_features
															_snake_case													=			inputs.attention_mask
															_snake_case													=			[np.sum(lowerCAmelCase_					) for x in attention_mask]

															self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]					)
															self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1E-6					)
															self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]					)
															self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1E-6					)
															self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]					)




					def 		lowerCAmelCase     (						self					)						->							Optional[int]:
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]
										_snake_case													=			feature_extractor(
										    lowerCAmelCase_			,  padding='max_length'			,  max_length=4			,  truncation=lowerCAmelCase_			,  return_tensors='np'			,  return_attention_mask=lowerCAmelCase_			,  )
										_snake_case													=			inputs.input_features
										_snake_case													=			inputs.attention_mask
										_snake_case													=			np.sum(attention_mask == 1			,  axis=1					)

										self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]					)
										self._check_zero_mean_unit_variance(input_features[1]					)
										self._check_zero_mean_unit_variance(input_features[2]					)




					def 		lowerCAmelCase     (						self					)						->							str:
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]
										_snake_case													=			feature_extractor(
										    lowerCAmelCase_			,  padding='longest'			,  max_length=4			,  truncation=lowerCAmelCase_			,  return_tensors='np'			,  return_attention_mask=lowerCAmelCase_			,  )
										_snake_case													=			inputs.input_features
										_snake_case													=			inputs.attention_mask
										_snake_case													=			np.sum(attention_mask == 1			,  axis=1					)

										self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]					)
										self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]					)
										self._check_zero_mean_unit_variance(input_features[2]					)

										# make sure that if max_length < longest -> then pad to max_length
										self.assertEqual(input_features.shape			,  (3, 4, 24)					)

										_snake_case													=			[floats_list((1, x)					)[0] for x in range(800			,  1400			,  200					)]
										_snake_case													=			feature_extractor(
										    lowerCAmelCase_			,  padding='longest'			,  max_length=16			,  truncation=lowerCAmelCase_			,  return_tensors='np'			,  return_attention_mask=lowerCAmelCase_			,  )
										_snake_case													=			inputs.input_features
										_snake_case													=			inputs.attention_mask
										_snake_case													=			np.sum(attention_mask == 1			,  axis=1					)

										self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]					)
										self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]					)
										self._check_zero_mean_unit_variance(input_features[2]					)

										# make sure that if max_length < longest -> then pad to max_length
										self.assertEqual(input_features.shape			,  (3, 6, 24)					)




					def 		lowerCAmelCase     (						self					)						->							Any:
										import torch

										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			np.random.rand(100			,  32					).astype(np.floataa					)
										_snake_case													=			np_speech_inputs.tolist()

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




					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_					)						->							str:
										from datasets import load_dataset

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

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






					def 		lowerCAmelCase     (						self					)						->							Any:
										# fmt: off
										_snake_case													=			np.array([
										    -1.57_45, -1.77_13, -1.70_20, -1.60_69, -1.22_50, -1.11_05, -0.90_72, -0.82_41,
										    -1.23_10, -0.80_98, -0.33_20, -0.41_01, -0.79_85, -0.49_96, -0.82_13, -0.91_28,
										    -1.04_20, -1.12_86, -1.04_40, -0.79_99, -0.84_05, -1.22_75, -1.54_43, -1.46_25,
										]					)
										# fmt: on

										_snake_case													=			self._load_datasamples(1					)
										_snake_case													=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
										_snake_case													=			feature_extractor(lowerCAmelCase_			,  return_tensors='pt'					).input_features
										self.assertEquals(input_features.shape			,  (1, 584, 24)					)
										self.assertTrue(np.allclose(input_features[0, 0, :30]			,  lowerCAmelCase_			,  atol=1E-4					)					)










from collections.abc import Sequence





def   lowerCamelCase__       (       UpperCamelCase__     :    Sequence[float]    ,      UpperCamelCase__     :    bool = False  )     ->	float:



					'''simple docstring'''




					if not arr:
										return 0

					_snake_case													=			0 if allow_empty_subarrays else float('-inf'  )
					_snake_case													=			0.0
					for num in arr:
										_snake_case													=			max(0 if allow_empty_subarrays else num    ,      curr_sum + num  )
										_snake_case													=			max(UpperCamelCase__    ,      UpperCamelCase__  )

					return max_sum


if __name__ == "__main__":
					from doctest import testmod

					testmod()

					UpperCAmelCase_ 							=       [-2, 1, -3, 4, -1, 2, 1, -5, 4]
					print(F"{max_subarray_sum(nums) = }")



