





'''simple docstring'''



from typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


_SCREAMING_SNAKE_CASE    =			logging.get_logger(__name__)






class 							__lowercase				(					lowerCAmelCase__  ):







	'''simple docstring'''

	a			: Optional[int]      =				["input_values", "attention_mask"]


	def __init__(self   ,_lowerCamelCase=1   ,_lowerCamelCase=16000   ,_lowerCamelCase=128   ,_lowerCamelCase=1024   ,_lowerCamelCase=0.0   ,_lowerCamelCase=True   ,_lowerCamelCase=-4.2_6_7_7_3_9_3   ,_lowerCamelCase=4.5_6_8_9_9_7_4   ,_lowerCamelCase=False   ,**_lowerCamelCase   ,)							->							Optional[int]:







				'''simple docstring'''





				super().__init__(feature_size=_lowerCamelCase   ,sampling_rate=_lowerCamelCase   ,padding_value=_lowerCamelCase   ,**_lowerCamelCase       )
				__lowercase   =							num_mel_bins
				__lowercase   =							max_length
				__lowercase   =							do_normalize
				__lowercase   =							mean
				__lowercase   =							std
				__lowercase   =							return_attention_mask


	def   _UpperCAmelCase   (self   ,_lowerCamelCase   ,_lowerCamelCase   ,)							->							np.ndarray:







				'''simple docstring'''





				__lowercase   =							torch.from_numpy(_lowerCamelCase       ).unsqueeze(0       )
				__lowercase   =							ta_kaldi.fbank(
				    _lowerCamelCase   ,htk_compat=_lowerCamelCase   ,sample_frequency=self.sampling_rate   ,use_energy=_lowerCamelCase   ,window_type='''hanning'''   ,num_mel_bins=self.num_mel_bins   ,dither=0.0   ,frame_shift=10   ,)

				__lowercase   =							fbank.shape[0]
				__lowercase   =							max_length - n_frames

				# pad or truncate, depending on difference
				if difference > 0:
							__lowercase   =							torch.nn.ZeroPadad((0, 0, 0, difference)       )
							__lowercase   =							pad_module(_lowerCamelCase       )
				elif difference < 0:
							__lowercase   =							fbank[0:max_length, :]

				__lowercase   =							fbank.numpy()

				return fbank


	def   _UpperCAmelCase   (self   ,_lowerCamelCase       )							->							np.ndarray:







				'''simple docstring'''





				return (input_values - (self.mean)) / (self.std * 2)


	def __call__(self   ,_lowerCamelCase   ,_lowerCamelCase = None   ,_lowerCamelCase = None   ,**_lowerCamelCase   ,)							->							BatchFeature:







				'''simple docstring'''





				if sampling_rate is not None:
							if sampling_rate != self.sampling_rate:
										raise ValueError(
										    f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
										    f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
										    f" {self.sampling_rate} and not {sampling_rate}."       )
				else:
							logger.warning(
							    '''It is strongly recommended to pass the `sampling_rate` argument to this function. '''
							    '''Failing to do so can result in silent errors that might be hard to debug.'''       )

				__lowercase   =							isinstance(_lowerCamelCase   ,np.ndarray       ) and len(raw_speech.shape       ) > 1
				if is_batched_numpy and len(raw_speech.shape       ) > 2:
							raise ValueError(f"Only mono-channel audio is supported for input to {self}"       )
				__lowercase   =							is_batched_numpy or (
				    isinstance(_lowerCamelCase   ,(list, tuple)       ) and (isinstance(raw_speech[0]   ,(np.ndarray, tuple, list)       ))
				)

				if is_batched:
							__lowercase   =							[np.asarray(_lowerCamelCase   ,dtype=np.floataa       ) for speech in raw_speech]
				elif not is_batched and not isinstance(_lowerCamelCase   ,np.ndarray       ):
							__lowercase   =							np.asarray(_lowerCamelCase   ,dtype=np.floataa       )
				elif isinstance(_lowerCamelCase   ,np.ndarray       ) and raw_speech.dtype is np.dtype(np.floataa       ):
							__lowercase   =							raw_speech.astype(np.floataa       )

				# always return batch
				if not is_batched:
							__lowercase   =							[raw_speech]

				# extract fbank features and pad/truncate to max_length
				__lowercase   =							[self._extract_fbank_features(_lowerCamelCase   ,max_length=self.max_length       ) for waveform in raw_speech]

				# convert into BatchFeature
				__lowercase   =							BatchFeature({'''input_values''': features}       )

				# make sure list is in array format
				__lowercase   =							padded_inputs.get('''input_values'''       )
				if isinstance(input_values[0]   ,_lowerCamelCase       ):
							__lowercase   =							[np.asarray(_lowerCamelCase   ,dtype=np.floataa       ) for feature in input_values]

				# normalization
				if self.do_normalize:
							__lowercase   =							[self.normalize(_lowerCamelCase       ) for feature in input_values]

				if return_tensors is not None:
							__lowercase   =							padded_inputs.convert_to_tensors(_lowerCamelCase       )

				return padded_inputs












'''simple docstring'''



import csv
import json
import os

import datasets


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_SCREAMING_SNAKE_CASE    =			'''\
@InProceedings{huggingface:dataset,
title = {A great new dataset},
author={huggingface, Inc.
},
year={2020}
}
'''

# TODO: Add description of the dataset here
# You can copy an official description
_SCREAMING_SNAKE_CASE    =			'''\
This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
'''

# TODO: Add a link to an official homepage for the dataset here
_SCREAMING_SNAKE_CASE    =			''''''

# TODO: Add the licence for the dataset here if you can find it
_SCREAMING_SNAKE_CASE    =			''''''

# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_SCREAMING_SNAKE_CASE    =			{
    '''first_domain''': '''https://huggingface.co/great-new-dataset-first_domain.zip''',
    '''second_domain''': '''https://huggingface.co/great-new-dataset-second_domain.zip''',
}






class 							__lowercase				(					datasets.GeneratorBasedBuilder  ):







	'''simple docstring'''

	a			: Tuple      =				datasets.Version("1.1.0"  )

	# This is an example of a dataset with multiple configurations.
	# If you don't want/need to define several sub-sets in your dataset,
	# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

	# If you need to make complex sub-parts in the datasets with configurable options
	# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
	# BUILDER_CONFIG_CLASS = MyBuilderConfig

	# You will be able to load one or the other configurations in the following list with
	# data = datasets.load_dataset('my_dataset', 'first_domain')
	# data = datasets.load_dataset('my_dataset', 'second_domain')
	a			: List[Any]      =				[
	    datasets.BuilderConfig(name="first_domain"       ,					version=lowerCAmelCase__       ,					description="This part of my dataset covers a first domain"  ),
	    datasets.BuilderConfig(name="second_domain"       ,					version=lowerCAmelCase__       ,					description="This part of my dataset covers a second domain"  ),
	]

	a			: Dict      =				"first_domain"  # It's not mandatory to have a default configuration. Just use one if it make sense.


	def   _UpperCAmelCase   (self       )							->							List[str]:







				'''simple docstring'''





				if self.config.name == "first_domain":  # This is the name of the configuration selected in BUILDER_CONFIGS above
							__lowercase   =							datasets.Features(
							    {
							        '''sentence''': datasets.Value('''string'''       ),
							        '''option1''': datasets.Value('''string'''       ),
							        '''answer''': datasets.Value('''string'''       )
							        # These are the features of your dataset like images, labels ...
							    }       )
				else:  # This is an example to show how to have different features for "first_domain" and "second_domain"
							__lowercase   =							datasets.Features(
							    {
							        '''sentence''': datasets.Value('''string'''       ),
							        '''option2''': datasets.Value('''string'''       ),
							        '''second_domain_answer''': datasets.Value('''string'''       )
							        # These are the features of your dataset like images, labels ...
							    }       )
				return datasets.DatasetInfo(
				    # This is the description that will appear on the datasets page.
				    description=_DESCRIPTION   ,features=_lowerCamelCase   ,homepage=_HOMEPAGE   ,license=_LICENSE   ,citation=_CITATION   ,)


	def   _UpperCAmelCase   (self   ,_lowerCamelCase       )							->							Dict:







				'''simple docstring'''





				__lowercase   =							_URLS[self.config.name]
				__lowercase   =							dl_manager.download_and_extract(_lowerCamelCase       )
				return [
				    datasets.SplitGenerator(
				        name=datasets.Split.TRAIN   ,gen_kwargs={
				            '''filepath''': os.path.join(_lowerCamelCase   ,'''train.jsonl'''       ),
				            '''split''': '''train''',
				        }   ,),
				    datasets.SplitGenerator(
				        name=datasets.Split.VALIDATION   ,gen_kwargs={
				            '''filepath''': os.path.join(_lowerCamelCase   ,'''dev.jsonl'''       ),
				            '''split''': '''dev''',
				        }   ,),
				    datasets.SplitGenerator(
				        name=datasets.Split.TEST   ,gen_kwargs={
				            '''filepath''': os.path.join(_lowerCamelCase   ,'''test.jsonl'''       ),
				            '''split''': '''test'''
				        }   ,),
				]


	def   _UpperCAmelCase   (self   ,_lowerCamelCase   ,_lowerCamelCase       )							->							str:







				'''simple docstring'''





				with open(_lowerCamelCase   ,encoding='''utf-8'''       ) as f:
							for key, row in enumerate(_lowerCamelCase       ):
										__lowercase   =							json.loads(_lowerCamelCase       )
										if self.config.name == "first_domain":
													# Yields examples as (key, example) tuples
													yield key, {
													    "sentence": data["sentence"],
													    "option1": data["option1"],
													    "answer": "" if split == "test" else data["answer"],
													}
										else:
													yield key, {
													    "sentence": data["sentence"],
													    "option2": data["option2"],
													    "second_domain_answer": "" if split == "test" else data["second_domain_answer"],
													}





