

import itertools
import random
import unittest

import numpy as np

from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor
from transformers.testing_utils import require_torch, slow

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


__lowercase				      =						random.Random()







def 							_lowerCamelCase   (			SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE=1.0		,				SCREAMING_SNAKE_CASE=None		,				SCREAMING_SNAKE_CASE=None   ):
      '''simple docstring'''







      if rng is None:
            A_							       =		global_rng

      A_							       =		[]
      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	:    Dict			,						lowerCamelCase__	:    Optional[Any]			,						lowerCamelCase__	:    Optional[Any]=7			,						lowerCamelCase__	:    Optional[Any]=4_0_0			,						lowerCamelCase__	:    Any=2_0_0_0			,						lowerCamelCase__	:    Dict=1			,						lowerCamelCase__	:    Tuple=0.0			,						lowerCamelCase__	:    Tuple=1_6_0_0_0			,						lowerCamelCase__	:    List[str]=True			,						lowerCamelCase__	:    Union[str, Any]=True			,						) ->			Optional[int]:
         """simple docstring"""





         A_							       =		parent
         A_							       =		batch_size
         A_							       =		min_seq_length
         A_							       =		max_seq_length
         A_							       =		(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
         A_							       =		feature_size
         A_							       =		padding_value
         A_							       =		sampling_rate
         A_							       =		return_attention_mask
         A_							       =		do_normalize

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			str:
         """simple docstring"""





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





   def     UpperCamelCase					(				self	:    Optional[int]			,						lowerCamelCase__	:    Union[str, Any]=False			,						lowerCamelCase__	:    Tuple=False       ) ->			Dict:
         """simple docstring"""





         def _flatten(lowerCamelCase__	:    Dict       ):
               return list(itertools.chain(*lowerCamelCase__       )       )

         if equal_length:
               A_							       =		floats_list((self.batch_size, self.max_seq_length)       )
         else:
               # make sure that inputs increase in size
               A_							       =		[
                   _flatten(floats_list((x, self.feature_size)       )       )
                   for x in range(self.min_seq_length			,						self.max_seq_length			,						self.seq_length_diff       )
               ]

         if numpify:
               A_							       =		[np.asarray(lowerCamelCase__       ) for x in speech_inputs]

         return speech_inputs



class    _lowercase				(					__lowerCamelCase,unittest.TestCase			):
   _lowercase     :       Optional[int]  					=    WavaVecaFeatureExtractor

   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			List[Any]:
         """simple docstring"""





         A_							       =		WavaVecaFeatureExtractionTester(self       )

   def     UpperCamelCase					(				self	:    Union[str, Any]			,						lowerCamelCase__	:    Tuple       ) ->			Optional[int]:
         """simple docstring"""





         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     UpperCamelCase					(				self	:    Any       ) ->			str:
         """simple docstring"""





         A_							       =		self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         # create three inputs of length 800, 1000, and 1200
         A_							       =		[floats_list((1, x)       )[0] for x in range(8_0_0			,						1_4_0_0			,						2_0_0       )]
         A_							       =		[np.asarray(lowerCamelCase__       ) for speech_input in speech_inputs]

         # Test not batched input
         A_							       =		feat_extract(speech_inputs[0]			,						return_tensors='''np'''       ).input_values
         A_							       =		feat_extract(np_speech_inputs[0]			,						return_tensors='''np'''       ).input_values
         self.assertTrue(np.allclose(lowerCamelCase__			,						lowerCamelCase__			,						atol=1e-3       )       )

         # Test batched
         A_							       =		feat_extract(lowerCamelCase__			,						return_tensors='''np'''       ).input_values
         A_							       =		feat_extract(lowerCamelCase__			,						return_tensors='''np'''       ).input_values
         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.
         A_							       =		[floats_list((1, x)       )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
         A_							       =		np.asarray(lowerCamelCase__       )
         A_							       =		feat_extract(lowerCamelCase__			,						return_tensors='''np'''       ).input_values
         A_							       =		feat_extract(lowerCamelCase__			,						return_tensors='''np'''       ).input_values
         for enc_seq_a, enc_seq_a in zip(lowerCamelCase__			,						lowerCamelCase__       ):
               self.assertTrue(np.allclose(lowerCamelCase__			,						lowerCamelCase__			,						atol=1e-3       )       )

   def     UpperCamelCase					(				self	:    str       ) ->			Optional[int]:
         """simple docstring"""





         A_							       =		self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         A_							       =		[floats_list((1, x)       )[0] for x in range(8_0_0			,						1_4_0_0			,						2_0_0       )]

         A_							       =		['''longest''', '''max_length''', '''do_not_pad''']
         A_							       =		[None, 1_6_0_0, None]
         for max_length, padding in zip(lowerCamelCase__			,						lowerCamelCase__       ):
               A_							       =		feat_extract(lowerCamelCase__			,						padding=lowerCamelCase__			,						max_length=lowerCamelCase__			,						return_tensors='''np'''       )
               A_							       =		processed.input_values

               self._check_zero_mean_unit_variance(input_values[0][:8_0_0]       )
               self.assertTrue(input_values[0][8_0_0:].sum() < 1e-6       )
               self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0]       )
               self.assertTrue(input_values[0][1_0_0_0:].sum() < 1e-6       )
               self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0]       )

   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			Union[str, Any]:
         """simple docstring"""





         A_							       =		self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         A_							       =		range(8_0_0			,						1_4_0_0			,						2_0_0       )
         A_							       =		[floats_list((1, x)       )[0] for x in lengths]

         A_							       =		['''longest''', '''max_length''', '''do_not_pad''']
         A_							       =		[None, 1_6_0_0, None]

         for max_length, padding in zip(lowerCamelCase__			,						lowerCamelCase__       ):
               A_							       =		feat_extract(lowerCamelCase__			,						max_length=lowerCamelCase__			,						padding=lowerCamelCase__       )
               A_							       =		processed.input_values

               self._check_zero_mean_unit_variance(input_values[0][:8_0_0]       )
               self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0]       )
               self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0]       )

   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			Dict:
         """simple docstring"""





         A_							       =		self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         A_							       =		[floats_list((1, x)       )[0] for x in range(8_0_0			,						1_4_0_0			,						2_0_0       )]
         A_							       =		feat_extract(
             lowerCamelCase__			,						truncation=lowerCamelCase__			,						max_length=1_0_0_0			,						padding='''max_length'''			,						return_tensors='''np'''       )
         A_							       =		processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :8_0_0]       )
         self._check_zero_mean_unit_variance(input_values[1]       )
         self._check_zero_mean_unit_variance(input_values[2]       )

   def     UpperCamelCase					(				self	:    str       ) ->			Optional[Any]:
         """simple docstring"""





         A_							       =		self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         A_							       =		[floats_list((1, x)       )[0] for x in range(8_0_0			,						1_4_0_0			,						2_0_0       )]
         A_							       =		feat_extract(
             lowerCamelCase__			,						truncation=lowerCamelCase__			,						max_length=1_0_0_0			,						padding='''longest'''			,						return_tensors='''np'''       )
         A_							       =		processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :8_0_0]       )
         self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0]       )
         self._check_zero_mean_unit_variance(input_values[2]       )

         # make sure that if max_length < longest -> then pad to max_length
         self.assertTrue(input_values.shape == (3, 1_0_0_0)       )

         A_							       =		[floats_list((1, x)       )[0] for x in range(8_0_0			,						1_4_0_0			,						2_0_0       )]
         A_							       =		feat_extract(
             lowerCamelCase__			,						truncation=lowerCamelCase__			,						max_length=2_0_0_0			,						padding='''longest'''			,						return_tensors='''np'''       )
         A_							       =		processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :8_0_0]       )
         self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0]       )
         self._check_zero_mean_unit_variance(input_values[2]       )

         # make sure that if max_length > longest -> then pad to longest
         self.assertTrue(input_values.shape == (3, 1_2_0_0)       )

   @require_torch
   def     UpperCamelCase					(				self	:    str       ) ->			List[Any]:
         """simple docstring"""





         import torch

         A_							       =		self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         A_							       =		np.random.rand(1_0_0       ).astype(np.floataa       )
         A_							       =		np_speech_inputs.tolist()

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





   @slow
   @require_torch
   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			Union[str, Any]:
         """simple docstring"""





         for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
               A_							       =		WavaVecaConfig.from_pretrained(lowerCamelCase__       )
               A_							       =		WavaVecaFeatureExtractor.from_pretrained(lowerCamelCase__       )

               # only "layer" feature extraction norm should make use of
               # attention_mask
               self.assertEqual(feat_extract.return_attention_mask			,						config.feat_extract_norm == '''layer'''       )








from itertools import product







def 							_lowerCamelCase   (			SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE   ):
      '''simple docstring'''







      A_							       =		sides_number
      A_							       =		max_face_number * dice_number
      A_							       =		[0] * (max_total + 1)

      A_							       =		1
      A_							       =		range(SCREAMING_SNAKE_CASE		,				max_face_number + 1   )
      for dice_numbers in product(SCREAMING_SNAKE_CASE		,				repeat=SCREAMING_SNAKE_CASE   ):
            A_							       =		sum(SCREAMING_SNAKE_CASE   )
            totals_frequencies[total] += 1

      return totals_frequencies







def 							_lowerCamelCase   (			):
      '''simple docstring'''







      A_							       =		total_frequency_distribution(
          sides_number=4		,				dice_number=9   )
      A_							       =		total_frequency_distribution(
          sides_number=6		,				dice_number=6   )

      A_							       =		0
      A_							       =		9
      A_							       =		4 * 9
      A_							       =		6
      for peter_total in range(SCREAMING_SNAKE_CASE		,				max_peter_total + 1   ):
            peter_wins_count += peter_totals_frequencies[peter_total] * sum(
                colin_totals_frequencies[min_colin_total:peter_total]   )

      A_							       =		(4**9) * (6**6)
      A_							       =		peter_wins_count / total_games_number

      A_							       =		round(SCREAMING_SNAKE_CASE		,				ndigits=7   )

      return rounded_peter_win_probability


if __name__ == "__main__":
      print(f'{solution() = }')





