





'''simple docstring'''




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

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







def _lowerCAmelCase     (      _lowerCAmelCase       ,    _lowerCAmelCase=1.0       ,    _lowerCAmelCase=None       ,    _lowerCAmelCase=None    )->     str:
 if rng is None:
  __UpperCAmelCase					=   global_rng

 __UpperCAmelCase					=   []
 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     ,			__A     ,			__A=7     ,			__A=400     ,			__A=2_000     ,			__A=10     ,			__A=160     ,			__A=8     ,			__A=0.0     ,			__A=4_000     ,			__A=False     ,			__A=True     ,			):
     __UpperCAmelCase					=   parent
     __UpperCAmelCase					=   batch_size
     __UpperCAmelCase					=   min_seq_length
     __UpperCAmelCase					=   max_seq_length
     __UpperCAmelCase					=   (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
     __UpperCAmelCase					=   padding_value
     __UpperCAmelCase					=   sampling_rate
     __UpperCAmelCase					=   return_attention_mask
     __UpperCAmelCase					=   do_normalize
     __UpperCAmelCase					=   feature_size
     __UpperCAmelCase					=   chunk_length
     __UpperCAmelCase					=   hop_length



    def 					__lowerCamelCase						(  self					):
     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 					__lowerCamelCase						(  self     ,			__A=False     ,			__A=False					):
     def _flatten(__A					):
      return list(itertools.chain(*__A					)					)

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






@require_torch
@require_torchaudio
class UpperCAmelCase							(		UpperCAmelCase_					,			unittest.TestCase							):
    _A :			List[str]						   =       WhisperFeatureExtractor if is_speech_available() else None



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   WhisperFeatureExtractionTester(self					)



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.feature_extraction_class(**self.feat_extract_dict					)

     with tempfile.TemporaryDirectory() as tmpdirname:
      __UpperCAmelCase					=   feat_extract_first.save_pretrained(__A					)[0]
      check_json_file_has_correct_format(__A					)
      __UpperCAmelCase					=   self.feature_extraction_class.from_pretrained(__A					)

     __UpperCAmelCase					=   feat_extract_first.to_dict()
     __UpperCAmelCase					=   feat_extract_second.to_dict()
     __UpperCAmelCase					=   feat_extract_first.mel_filters
     __UpperCAmelCase					=   feat_extract_second.mel_filters
     self.assertTrue(np.allclose(__A     ,			__A					)					)
     self.assertEqual(__A     ,			__A					)



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.feature_extraction_class(**self.feat_extract_dict					)

     with tempfile.TemporaryDirectory() as tmpdirname:
      __UpperCAmelCase					=   os.path.join(__A     ,			'feat_extract.json'					)
      feat_extract_first.to_json_file(__A					)
      __UpperCAmelCase					=   self.feature_extraction_class.from_json_file(__A					)

     __UpperCAmelCase					=   feat_extract_first.to_dict()
     __UpperCAmelCase					=   feat_extract_second.to_dict()
     __UpperCAmelCase					=   feat_extract_first.mel_filters
     __UpperCAmelCase					=   feat_extract_second.mel_filters
     self.assertTrue(np.allclose(__A     ,			__A					)					)
     self.assertEqual(__A     ,			__A					)



    def 					__lowerCamelCase						(  self					):
     # Tests that all call wrap to encode_plus and batch_encode_plus
     __UpperCAmelCase					=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
     # create three inputs of length 800, 1000, and 1200
     __UpperCAmelCase					=   [floats_list((1, x)					)[0] for x in range(800     ,			1_400     ,			200					)]
     __UpperCAmelCase					=   [np.asarray(__A					) for speech_input in speech_inputs]

     # Test feature size
     __UpperCAmelCase					=   feature_extractor(__A     ,			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
     __UpperCAmelCase					=   feature_extractor(speech_inputs[0]     ,			return_tensors='np'					).input_features
     __UpperCAmelCase					=   feature_extractor(np_speech_inputs[0]     ,			return_tensors='np'					).input_features
     self.assertTrue(np.allclose(__A     ,			__A     ,			atol=1E-3					)					)

     # Test batched
     __UpperCAmelCase					=   feature_extractor(__A     ,			return_tensors='np'					).input_features
     __UpperCAmelCase					=   feature_extractor(__A     ,			return_tensors='np'					).input_features
     for enc_seq_a, enc_seq_a in zip(__A     ,			__A					):
      self.assertTrue(np.allclose(__A     ,			__A     ,			atol=1E-3					)					)

     # Test 2-D numpy arrays are batched.
     __UpperCAmelCase					=   [floats_list((1, x)					)[0] for x in (800, 800, 800)]
     __UpperCAmelCase					=   np.asarray(__A					)
     __UpperCAmelCase					=   feature_extractor(__A     ,			return_tensors='np'					).input_features
     __UpperCAmelCase					=   feature_extractor(__A     ,			return_tensors='np'					).input_features
     for enc_seq_a, enc_seq_a in zip(__A     ,			__A					):
      self.assertTrue(np.allclose(__A     ,			__A     ,			atol=1E-3					)					)

     # Test truncation required
     __UpperCAmelCase					=   [floats_list((1, x)					)[0] for x in range(200     ,			(feature_extractor.n_samples + 500)     ,			200					)]
     __UpperCAmelCase					=   [np.asarray(__A					) for speech_input in speech_inputs]

     __UpperCAmelCase					=   [x[: feature_extractor.n_samples] for x in speech_inputs]
     __UpperCAmelCase					=   [np.asarray(__A					) for speech_input in speech_inputs_truncated]

     __UpperCAmelCase					=   feature_extractor(__A     ,			return_tensors='np'					).input_features
     __UpperCAmelCase					=   feature_extractor(__A     ,			return_tensors='np'					).input_features
     for enc_seq_a, enc_seq_a in zip(__A     ,			__A					):
      self.assertTrue(np.allclose(__A     ,			__A     ,			atol=1E-3					)					)



    def 					__lowerCamelCase						(  self					):
     import torch

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

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



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

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



    def 					__lowerCamelCase						(  self					):
     # fmt: off
     __UpperCAmelCase					=   torch.tensor(
         [
             0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
             0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
             0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
             -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
         ]					)
     # fmt: on

     __UpperCAmelCase					=   self._load_datasamples(1					)
     __UpperCAmelCase					=   WhisperFeatureExtractor()
     __UpperCAmelCase					=   feature_extractor(__A     ,			return_tensors='pt'					).input_features
     self.assertEqual(input_features.shape     ,			(1, 80, 3_000)					)
     self.assertTrue(torch.allclose(input_features[0, 0, :30]     ,			__A     ,			atol=1E-4					)					)




    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
     __UpperCAmelCase					=   self._load_datasamples(1					)[0]
     __UpperCAmelCase					=   ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535  # Rescale to [0, 65535] to show issue
     __UpperCAmelCase					=   feat_extract.zero_mean_unit_var_norm([audio]     ,			attention_mask=__A					)[0]

     self.assertTrue(np.all(np.mean(__A					) < 1E-3					)					)
     self.assertTrue(np.all(np.abs(np.var(__A					) - 1					) < 1E-3					)					)












'''simple docstring'''




from __future__ import annotations







def _lowerCAmelCase     (      _lowerCAmelCase       ,    _lowerCAmelCase       ,    _lowerCAmelCase       ,    )->     tuple:
 if (electron_conc, hole_conc, intrinsic_conc).count(0    ) != 1:
  raise ValueError('You cannot supply more or less than 2 values'    )
 elif electron_conc < 0:
  raise ValueError('Electron concentration cannot be negative in a semiconductor'    )
 elif hole_conc < 0:
  raise ValueError('Hole concentration cannot be negative in a semiconductor'    )
 elif intrinsic_conc < 0:
  raise ValueError(
      'Intrinsic concentration cannot be negative in a semiconductor'    )
 elif electron_conc == 0:
  return (
      "electron_conc",
      intrinsic_conc**2 / hole_conc,
  )
 elif hole_conc == 0:
  return (
      "hole_conc",
      intrinsic_conc**2 / electron_conc,
  )
 elif intrinsic_conc == 0:
  return (
      "intrinsic_conc",
      (electron_conc * hole_conc) ** 0.5,
  )
 else:
  return (-1, -1)


if __name__ == "__main__":
    import doctest

    doctest.testmod()





