





'''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

_lowercase       						=			random.Random()

def    __UpperCamelCase	(	a    : List[Any]					,   a    : int=1.0					,   a    : Dict=None					,   a    : str=None     ) ->Optional[int]:
 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 			_lowercase						(       unittest.TestCase					):







     def __init__( self    ,   A__    ,   A__=7    ,   A__=4_00    ,   A__=20_00    ,   A__=10    ,   A__=1_60    ,   A__=8    ,   A__=0.0    ,   A__=40_00    ,   A__=False    ,   A__=True    ,   ) ->	Union[str, 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				=			padding_value
      snake_case				=			sampling_rate
      snake_case				=			return_attention_mask
      snake_case				=			do_normalize
      snake_case				=			feature_size
      snake_case				=			chunk_length
      snake_case				=			hop_length







     def     UpperCamelCase			( self    ) ->	Tuple:
      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     UpperCamelCase			( self    ,   A__=False    ,   A__=False    ) ->	List[Any]:
      def _flatten(A__    ):
       return list(itertools.chain(*A__    )    )

      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(A__    ) for x in speech_inputs]
      return speech_inputs




@require_torch
@require_torchaudio
class 			_lowercase						(       __a				,		unittest.TestCase					):
     _UpperCAmelCase										=					WhisperFeatureExtractor if is_speech_available() else None







     def     UpperCamelCase			( self    ) ->	Optional[Any]:
      snake_case				=			WhisperFeatureExtractionTester(self    )







     def     UpperCamelCase			( self    ) ->	Any:
      snake_case				=			self.feature_extraction_class(**self.feat_extract_dict    )

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

      snake_case				=			feat_extract_first.to_dict()
      snake_case				=			feat_extract_second.to_dict()
      snake_case				=			feat_extract_first.mel_filters
      snake_case				=			feat_extract_second.mel_filters
      self.assertTrue(np.allclose(A__    ,   A__    )    )
      self.assertEqual(A__    ,   A__    )







     def     UpperCamelCase			( self    ) ->	str:
      snake_case				=			self.feature_extraction_class(**self.feat_extract_dict    )

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

      snake_case				=			feat_extract_first.to_dict()
      snake_case				=			feat_extract_second.to_dict()
      snake_case				=			feat_extract_first.mel_filters
      snake_case				=			feat_extract_second.mel_filters
      self.assertTrue(np.allclose(A__    ,   A__    )    )
      self.assertEqual(A__    ,   A__    )







     def     UpperCamelCase			( self    ) ->	List[str]:
      # 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(8_00    ,   14_00    ,   2_00    )]
      snake_case				=			[np.asarray(A__    ) for speech_input in speech_inputs]

      # Test feature size
      snake_case				=			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
      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(A__    ,   A__    ,   atol=1e-3    )    )

      # Test batched
      snake_case				=			feature_extractor(A__    ,   return_tensors='''np'''    ).input_features
      snake_case				=			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.
      snake_case				=			[floats_list((1, x)    )[0] for x in (8_00, 8_00, 8_00)]
      snake_case				=			np.asarray(A__    )
      snake_case				=			feature_extractor(A__    ,   return_tensors='''np'''    ).input_features
      snake_case				=			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
      snake_case				=			[floats_list((1, x)    )[0] for x in range(2_00    ,   (feature_extractor.n_samples + 5_00)    ,   2_00    )]
      snake_case				=			[np.asarray(A__    ) for speech_input in speech_inputs]

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

      snake_case				=			feature_extractor(A__    ,   return_tensors='''np'''    ).input_features
      snake_case				=			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     UpperCamelCase			( self    ) ->	List[Any]:
      import torch

      snake_case				=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
      snake_case				=			np.random.rand(1_00    ,   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     UpperCamelCase			( self    ,   A__    ) ->	Union[str, Any]:
      snake_case				=			load_dataset('''hf-internal-testing/librispeech_asr_dummy'''    ,   '''clean'''    ,   split='''validation'''    )
      # automatic decoding with librispeech
      snake_case				=			ds.sort('''id'''    ).select(range(A__    )    )[:num_samples]['''audio''']

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







     def     UpperCamelCase			( self    ) ->	List[str]:
      # fmt: off
      snake_case				=			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

      snake_case				=			self._load_datasamples(1    )
      snake_case				=			WhisperFeatureExtractor()
      snake_case				=			feature_extractor(A__    ,   return_tensors='''pt'''    ).input_features
      self.assertEqual(input_features.shape    ,   (1, 80, 30_00)    )
      self.assertTrue(torch.allclose(input_features[0, 0, :30]    ,   A__    ,   atol=1e-4    )    )







     def     UpperCamelCase			( self    ) ->	Optional[Any]:
      snake_case				=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
      snake_case				=			self._load_datasamples(1    )[0]
      snake_case				=			((audio - audio.min()) / (audio.max() - audio.min())) * 6_55_35  # Rescale to [0, 65535] to show issue
      snake_case				=			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'''







import os
from tempfile import TemporaryDirectory
from unittest import TestCase

import pytest
from absl.testing import parameterized

from datasets import config
from datasets.arrow_reader import HF_GCP_BASE_URL
from datasets.builder import DatasetBuilder
from datasets.dataset_dict import IterableDatasetDict
from datasets.iterable_dataset import IterableDataset
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.file_utils import cached_path


_lowercase       						=			[
    {'dataset': 'wikipedia', 'config_name': '20220301.de'},
    {'dataset': 'wikipedia', 'config_name': '20220301.en'},
    {'dataset': 'wikipedia', 'config_name': '20220301.fr'},
    {'dataset': 'wikipedia', 'config_name': '20220301.frr'},
    {'dataset': 'wikipedia', 'config_name': '20220301.it'},
    {'dataset': 'wikipedia', 'config_name': '20220301.simple'},
    {'dataset': 'snli', 'config_name': 'plain_text'},
    {'dataset': 'eli5', 'config_name': 'LFQA_reddit'},
    {'dataset': 'wiki40b', 'config_name': 'en'},
    {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'},
    {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'},
    {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'},
    {'dataset': 'natural_questions', 'config_name': 'default'},
]

def    __UpperCamelCase	(	a    : Dict=True     ) ->str:
 if with_config:
  return [
      {
          "testcase_name": d["dataset"] + "/" + d["config_name"],
          "dataset": d["dataset"],
          "config_name": d["config_name"],
      }
      for d in DATASETS_ON_HF_GCP
  ]
 else:
  return [
      {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP}
  ]
@parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=__a					)					)
class 			_lowercase						(       __a					):
     _UpperCAmelCase										=					None
     _UpperCAmelCase										=					None







     def     UpperCamelCase			( self    ,   A__    ,   A__    ) ->	str:
      with TemporaryDirectory() as tmp_dir:
       snake_case				=			dataset_module_factory(A__    ,   cache_dir=A__    )

       snake_case				=			import_main_class(dataset_module.module_path    ,   dataset=A__    )

       snake_case				=			builder_cls(
           cache_dir=A__    ,   config_name=A__    ,   hash=dataset_module.hash    ,   )

       snake_case				=			'''/'''.join(
           [
               HF_GCP_BASE_URL,
               builder_instance._relative_data_dir(with_hash=A__    ).replace(os.sep    ,   '''/'''    ),
               config.DATASET_INFO_FILENAME,
           ]    )
       snake_case				=			cached_path(A__    ,   cache_dir=A__    )
       self.assertTrue(os.path.exists(A__    )    )




@pytest.mark.integration
def    __UpperCamelCase	(	a    : List[str]     ) ->Any:
 snake_case				=			tmp_path_factory.mktemp('''test_hf_gcp'''     ) / '''test_wikipedia_simple'''
 snake_case				=			dataset_module_factory('''wikipedia'''					,   cache_dir=a     )
 snake_case				=			import_main_class(dataset_module.module_path     )
 snake_case				=			builder_cls(
     cache_dir=a					,   config_name='''20220301.frr'''					,   hash=dataset_module.hash					,   )
 # use the HF cloud storage, not the original download_and_prepare that uses apache-beam
 snake_case				=			None
 builder_instance.download_and_prepare()
 snake_case				=			builder_instance.as_dataset()
 assert ds






@pytest.mark.integration
def    __UpperCamelCase	(	a    : Any     ) ->Union[str, Any]:
 snake_case				=			dataset_module_factory('''wikipedia'''					,   cache_dir=a     )
 snake_case				=			import_main_class(dataset_module.module_path					,   dataset=a     )
 snake_case				=			builder_cls(
     cache_dir=a					,   config_name='''20220301.frr'''					,   hash=dataset_module.hash					,   )
 snake_case				=			builder_instance.as_streaming_dataset()
 assert ds
 assert isinstance(a					,   a     )
 assert "train" in ds
 assert isinstance(ds['''train''']					,   a     )
 assert next(iter(ds['''train''']     )     )

