



import warnings
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


A__  :  Tuple								=					logging.get_logger(__name__)



class 				__snake_case						(     UpperCamelCase_						):
							_a			      = ['''input_values''', '''attention_mask''']




							def __init__(       self     :       Any				,				A_     :       int = 1				,				A_     :       int = 1_6_0_0_0				,				A_     :       float = 0.0				,				A_     :       bool = False				,				A_     :       int = 8_0				,				A_     :       int = 1_6				,				A_     :       int = 6_4				,				A_     :       str = "hann_window"				,				A_     :       float = 1.0				,				A_     :       float = 8_0				,				A_     :       float = 7_6_0_0				,				A_     :       float = 1e-10				,				A_     :       int = 2				,				A_     :       bool = True				,				**A_     :       Union[str, Any]				,				):
									super().__init__(feature_size=A_				,				sampling_rate=A_				,				padding_value=A_				,				**A_)
									lowerCAmelCase_			:     Union[str, Any]									= do_normalize
									lowerCAmelCase_			:     Dict									= return_attention_mask

									lowerCAmelCase_			:     Optional[Any]									= num_mel_bins
									lowerCAmelCase_			:     Union[str, Any]									= hop_length
									lowerCAmelCase_			:     List[str]									= win_length
									lowerCAmelCase_			:     Any									= win_function
									lowerCAmelCase_			:     Union[str, Any]									= frame_signal_scale
									lowerCAmelCase_			:     Optional[int]									= fmin
									lowerCAmelCase_			:     List[str]									= fmax
									lowerCAmelCase_			:     Optional[Any]									= mel_floor
									lowerCAmelCase_			:     List[Any]									= reduction_factor

									lowerCAmelCase_			:     Any									= win_length * sampling_rate // 1_0_0_0
									lowerCAmelCase_			:     Union[str, Any]									= hop_length * sampling_rate // 1_0_0_0
									lowerCAmelCase_			:     Optional[Any]									= optimal_fft_length(self.sample_size)
									lowerCAmelCase_			:     Tuple									= (self.n_fft // 2) + 1

									lowerCAmelCase_			:     Union[str, Any]									= window_function(window_length=self.sample_size				,				name=self.win_function				,				periodic=A_)

									lowerCAmelCase_			:     str									= mel_filter_bank(
									    num_frequency_bins=self.n_freqs				,				num_mel_filters=self.num_mel_bins				,				min_frequency=self.fmin				,				max_frequency=self.fmax				,				sampling_rate=self.sampling_rate				,				norm='''slaney'''				,				mel_scale='''slaney'''				,				)

									if frame_signal_scale != 1.0:
											warnings.warn(
											    '''The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers'''				,				A_				,				)
									if reduction_factor != 2.0:
											warnings.warn(
											    '''The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers'''				,				A_				,				)




							@staticmethod
							# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
							def    UpperCAmelCase__			(       A_     :       List[np.ndarray]				,				A_     :       List[np.ndarray]				,				A_     :       float = 0.0):
									if attention_mask is not None:
											lowerCAmelCase_			:     int									= np.array(A_				,				np.intaa)
											lowerCAmelCase_			:     Tuple									= []

											for vector, length in zip(A_				,				attention_mask.sum(-1)):
													lowerCAmelCase_			:     Optional[Any]									= (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7)
													if length < normed_slice.shape[0]:
															lowerCAmelCase_			:     Any									= padding_value

													normed_input_values.append(A_)
									else:
											lowerCAmelCase_			:     Optional[int]									= [(x - x.mean()) / np.sqrt(x.var() + 1e-7) for x in input_values]

									return normed_input_values




							def    UpperCAmelCase__			(       self     :       str				,				A_     :       np.ndarray				,				):
									lowerCAmelCase_			:     Optional[int]									= spectrogram(
									    A_				,				window=self.window				,				frame_length=self.sample_size				,				hop_length=self.sample_stride				,				fft_length=self.n_fft				,				mel_filters=self.mel_filters				,				mel_floor=self.mel_floor				,				log_mel='''log10'''				,				)
									return log_mel_spec.T




							def __call__(       self     :       Tuple				,				A_     :       Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None				,				A_     :       Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None				,				A_     :       Union[bool, str, PaddingStrategy] = False				,				A_     :       Optional[int] = None				,				A_     :       bool = False				,				A_     :       Optional[int] = None				,				A_     :       Optional[bool] = None				,				A_     :       Optional[Union[str, TensorType]] = None				,				A_     :       Optional[int] = None				,				**A_     :       str				,				):
									if audio is None and audio_target is None:
											raise ValueError('''You must provide either `audio` or `audio_target` values.''')

									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 audio 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.''')

									if audio is not None:
											lowerCAmelCase_			:     Optional[int]									= self._process_audio(
											    A_				,				A_				,				A_				,				A_				,				A_				,				A_				,				A_				,				A_				,				**A_				,				)
									else:
											lowerCAmelCase_			:     Tuple									= None

									if audio_target is not None:
											lowerCAmelCase_			:     Tuple									= self._process_audio(
											    A_				,				A_				,				A_				,				A_				,				A_				,				A_				,				A_				,				A_				,				**A_				,				)

											if inputs is None:
													return inputs_target
											else:
													lowerCAmelCase_			:     Tuple									= inputs_target['''input_values''']
													lowerCAmelCase_			:     List[Any]									= inputs_target.get('''attention_mask''')
													if decoder_attention_mask is not None:
															lowerCAmelCase_			:     int									= decoder_attention_mask

									return inputs




							def    UpperCAmelCase__			(       self     :       Optional[Any]				,				A_     :       Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]				,				A_     :       bool = False				,				A_     :       Union[bool, str, PaddingStrategy] = False				,				A_     :       Optional[int] = None				,				A_     :       bool = False				,				A_     :       Optional[int] = None				,				A_     :       Optional[bool] = None				,				A_     :       Optional[Union[str, TensorType]] = None				,				**A_     :       Union[str, Any]				,				):
									lowerCAmelCase_			:     str									= isinstance(A_				,				np.ndarray) and len(speech.shape) > 1
									if is_batched_numpy and len(speech.shape) > 2:
											raise ValueError(F"""Only mono-channel audio is supported for input to {self}""")
									lowerCAmelCase_			:     List[str]									= is_batched_numpy or (
									    isinstance(A_				,				(list, tuple)) and (isinstance(speech[0]				,				(np.ndarray, tuple, list)))
									)

									if is_batched:
											lowerCAmelCase_			:     str									= [np.asarray(A_				,				dtype=np.floataa) for speech in speech]
									elif not is_batched and not isinstance(A_				,				np.ndarray):
											lowerCAmelCase_			:     int									= np.asarray(A_				,				dtype=np.floataa)
									elif isinstance(A_				,				np.ndarray) and speech.dtype is np.dtype(np.floataa):
											lowerCAmelCase_			:     List[str]									= speech.astype(np.floataa)

									# always return batch
									if not is_batched:
											lowerCAmelCase_			:     Union[str, Any]									= [speech]

									# needed to make pad() work on spectrogram inputs
									lowerCAmelCase_			:     str									= self.feature_size

									# convert into correct format for padding
									if is_target:
											lowerCAmelCase_			:     Optional[Any]									= [self._extract_mel_features(A_) for waveform in speech]
											lowerCAmelCase_			:     Dict									= BatchFeature({'''input_values''': features})
											lowerCAmelCase_			:     Union[str, Any]									= self.num_mel_bins
									else:
											lowerCAmelCase_			:     int									= BatchFeature({'''input_values''': speech})

									lowerCAmelCase_			:     Tuple									= self.pad(
									    A_				,				padding=A_				,				max_length=A_				,				truncation=A_				,				pad_to_multiple_of=A_				,				return_attention_mask=A_				,				**A_				,				)

									lowerCAmelCase_			:     Tuple									= feature_size_hack

									# convert input values to correct format
									lowerCAmelCase_			:     List[str]									= padded_inputs['''input_values''']
									if not isinstance(input_values[0]				,				np.ndarray):
											lowerCAmelCase_			:     List[str]									= [np.asarray(A_				,				dtype=np.floataa) for array in input_values]
									elif (
									    not isinstance(A_				,				np.ndarray)
									    and isinstance(input_values[0]				,				np.ndarray)
									    and input_values[0].dtype is np.dtype(np.floataa)
									):
											lowerCAmelCase_			:     Any									= [array.astype(np.floataa) for array in input_values]
									elif isinstance(A_				,				np.ndarray) and input_values.dtype is np.dtype(np.floataa):
											lowerCAmelCase_			:     Dict									= input_values.astype(np.floataa)

									# convert attention_mask to correct format
									lowerCAmelCase_			:     List[Any]									= padded_inputs.get('''attention_mask''')
									if attention_mask is not None:
											lowerCAmelCase_			:     Optional[Any]									= [np.asarray(A_				,				dtype=np.intaa) for array in attention_mask]

									# zero-mean and unit-variance normalization
									if not is_target and self.do_normalize:
											lowerCAmelCase_			:     Tuple									= (
											    attention_mask
											    if self._get_padding_strategies(A_				,				max_length=A_) is not PaddingStrategy.DO_NOT_PAD
											    else None
											)
											lowerCAmelCase_			:     str									= self.zero_mean_unit_var_norm(
											    padded_inputs['''input_values''']				,				attention_mask=A_				,				padding_value=self.padding_value)

									if return_tensors is not None:
											lowerCAmelCase_			:     Dict									= padded_inputs.convert_to_tensors(A_)

									return padded_inputs







							def    UpperCAmelCase__			(       self     :       List[str]):
									lowerCAmelCase_			:     Any									= super().to_dict()

									# Don't serialize these as they are derived from the other properties.
									lowerCAmelCase_			:     List[Any]									= ['''window''', '''mel_filters''', '''sample_size''', '''sample_stride''', '''n_fft''', '''n_freqs''']
									for name in names:
											if name in output:
													del output[name]

									return output










import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_realm import RealmTokenizer


A__  :  str								=					logging.get_logger(__name__)

A__  :  Any								=					{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

A__  :  str								=					{
    '''vocab_file''': {
        '''google/realm-cc-news-pretrained-embedder''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt'''
        ),
        '''google/realm-cc-news-pretrained-encoder''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt'''
        ),
        '''google/realm-cc-news-pretrained-scorer''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt'''
        ),
        '''google/realm-cc-news-pretrained-openqa''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt'''
        ),
        '''google/realm-orqa-nq-openqa''': '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt''',
        '''google/realm-orqa-nq-reader''': '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt''',
        '''google/realm-orqa-wq-openqa''': '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt''',
        '''google/realm-orqa-wq-reader''': '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt''',
    },
    '''tokenizer_file''': {
        '''google/realm-cc-news-pretrained-embedder''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont'''
        ),
        '''google/realm-cc-news-pretrained-encoder''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json'''
        ),
        '''google/realm-cc-news-pretrained-scorer''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json'''
        ),
        '''google/realm-cc-news-pretrained-openqa''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json'''
        ),
        '''google/realm-orqa-nq-openqa''': (
            '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json'''
        ),
        '''google/realm-orqa-nq-reader''': (
            '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json'''
        ),
        '''google/realm-orqa-wq-openqa''': (
            '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json'''
        ),
        '''google/realm-orqa-wq-reader''': (
            '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json'''
        ),
    },
}

A__  :  Union[str, Any]								=					{
    '''google/realm-cc-news-pretrained-embedder''': 512,
    '''google/realm-cc-news-pretrained-encoder''': 512,
    '''google/realm-cc-news-pretrained-scorer''': 512,
    '''google/realm-cc-news-pretrained-openqa''': 512,
    '''google/realm-orqa-nq-openqa''': 512,
    '''google/realm-orqa-nq-reader''': 512,
    '''google/realm-orqa-wq-openqa''': 512,
    '''google/realm-orqa-wq-reader''': 512,
}

A__  :  Dict								=					{
    '''google/realm-cc-news-pretrained-embedder''': {'''do_lower_case''': True},
    '''google/realm-cc-news-pretrained-encoder''': {'''do_lower_case''': True},
    '''google/realm-cc-news-pretrained-scorer''': {'''do_lower_case''': True},
    '''google/realm-cc-news-pretrained-openqa''': {'''do_lower_case''': True},
    '''google/realm-orqa-nq-openqa''': {'''do_lower_case''': True},
    '''google/realm-orqa-nq-reader''': {'''do_lower_case''': True},
    '''google/realm-orqa-wq-openqa''': {'''do_lower_case''': True},
    '''google/realm-orqa-wq-reader''': {'''do_lower_case''': True},
}



class 				__snake_case						(     UpperCamelCase_						):
							_a			      = VOCAB_FILES_NAMES
							_a			      = PRETRAINED_VOCAB_FILES_MAP
							_a			      = PRETRAINED_INIT_CONFIGURATION
							_a			      = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							_a			      = RealmTokenizer




							def __init__(       self     :       int				,				A_     :       Optional[int]=None				,				A_     :       Optional[Any]=None				,				A_     :       Optional[Any]=True				,				A_     :       Optional[int]="[UNK]"				,				A_     :       List[Any]="[SEP]"				,				A_     :       List[Any]="[PAD]"				,				A_     :       Optional[Any]="[CLS]"				,				A_     :       Dict="[MASK]"				,				A_     :       List[Any]=True				,				A_     :       List[str]=None				,				**A_     :       List[str]				,				):
									super().__init__(
									    A_				,				tokenizer_file=A_				,				do_lower_case=A_				,				unk_token=A_				,				sep_token=A_				,				pad_token=A_				,				cls_token=A_				,				mask_token=A_				,				tokenize_chinese_chars=A_				,				strip_accents=A_				,				**A_				,				)

									lowerCAmelCase_			:     Optional[int]									= json.loads(self.backend_tokenizer.normalizer.__getstate__())
									if (
									    normalizer_state.get('''lowercase'''				,				A_) != do_lower_case
									    or normalizer_state.get('''strip_accents'''				,				A_) != strip_accents
									    or normalizer_state.get('''handle_chinese_chars'''				,				A_) != tokenize_chinese_chars
									):
											lowerCAmelCase_			:     int									= getattr(A_				,				normalizer_state.pop('''type'''))
											lowerCAmelCase_			:     str									= do_lower_case
											lowerCAmelCase_			:     Dict									= strip_accents
											lowerCAmelCase_			:     Optional[Any]									= tokenize_chinese_chars
											lowerCAmelCase_			:     Union[str, Any]									= normalizer_class(**A_)

									lowerCAmelCase_			:     Any									= do_lower_case




							def    UpperCAmelCase__			(       self     :       Optional[Any]				,				A_     :       Optional[Any]				,				**A_     :       Tuple):
									lowerCAmelCase_			:     List[str]									= PaddingStrategy.MAX_LENGTH

									lowerCAmelCase_			:     str									= text
									lowerCAmelCase_			:     int									= kwargs.pop('''text_pair'''				,				A_)
									lowerCAmelCase_			:     str									= kwargs.pop('''return_tensors'''				,				A_)

									lowerCAmelCase_			:     int									= {
									    '''input_ids''': [],
									    '''attention_mask''': [],
									    '''token_type_ids''': [],
									}

									for idx, candidate_text in enumerate(A_):
											if batch_text_pair is not None:
													lowerCAmelCase_			:     List[Any]									= batch_text_pair[idx]
											else:
													lowerCAmelCase_			:     List[Any]									= None

											lowerCAmelCase_			:     int									= super().__call__(A_				,				A_				,				return_tensors=A_				,				**A_)

											lowerCAmelCase_			:     Optional[Any]									= encoded_candidates.get('''input_ids''')
											lowerCAmelCase_			:     List[str]									= encoded_candidates.get('''attention_mask''')
											lowerCAmelCase_			:     Optional[Any]									= encoded_candidates.get('''token_type_ids''')

											if encoded_input_ids is not None:
													output_data["input_ids"].append(A_)
											if encoded_attention_mask is not None:
													output_data["attention_mask"].append(A_)
											if encoded_token_type_ids is not None:
													output_data["token_type_ids"].append(A_)

									lowerCAmelCase_			:     List[str]									= {key: item for key, item in output_data.items() if len(A_) != 0}

									return BatchEncoding(A_				,				tensor_type=A_)




							def    UpperCAmelCase__			(       self     :       List[str]				,				A_     :       Tuple				,				A_     :       List[Any]=None):
									lowerCAmelCase_			:     Optional[Any]									= [self.cls_token_id] + token_ids_a + [self.sep_token_id]

									if token_ids_a:
											output += token_ids_a + [self.sep_token_id]

									return output




							def    UpperCAmelCase__			(       self     :       Tuple				,				A_     :       List[int]				,				A_     :       Optional[List[int]] = None):
									lowerCAmelCase_			:     Tuple									= [self.sep_token_id]
									lowerCAmelCase_			:     Union[str, Any]									= [self.cls_token_id]
									if token_ids_a is None:
											return len(cls + token_ids_a + sep) * [0]
									return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1]







							def    UpperCAmelCase__			(       self     :       List[str]				,				A_     :       str				,				A_     :       Optional[str] = None):
									lowerCAmelCase_			:     List[str]									= self._tokenizer.model.save(A_				,				name=A_)
									return tuple(A_)





