


'''simple docstring'''
import itertools
import random
import unittest

import numpy as np

from transformers import BatchFeature, SpeechTaFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
		import torch


__snake_case							      =     random.Random()


def 			a      (			__a ,					__a=1.0 ,					__a=None ,					__a=None   )  ->	Any:



					'''simple docstring'''






					if rng is None:
										UpperCamelCase__   :Any												= global_rng

					UpperCamelCase__   :Optional[Any]												= []
					for batch_idx in range(shape[0]   ):
										values.append([]   )
										for _ in range(shape[1]   ):
															values[-1].append(rng.random() * scale   )

					return values
@require_torch
class    lowercase	(							unittest.TestCase					):

		"""simple docstring"""

		def __init__(		self    ,   UpperCamelCase_    ,   UpperCamelCase_=7    ,   UpperCamelCase_=400    ,   UpperCamelCase_=2000    ,   UpperCamelCase_=1    ,   UpperCamelCase_=0.0    ,   UpperCamelCase_=16000    ,   UpperCamelCase_=True    ,   UpperCamelCase_=80    ,   UpperCamelCase_=16    ,   UpperCamelCase_=64    ,   UpperCamelCase_="hann_window"    ,   UpperCamelCase_=80    ,   UpperCamelCase_=7600    ,   UpperCamelCase_=1e-10    ,   UpperCamelCase_=True    ,   ):

							'''simple docstring'''


							UpperCamelCase__   :str												= parent
							UpperCamelCase__   :List[Any]												= batch_size
							UpperCamelCase__   :str												= min_seq_length
							UpperCamelCase__   :Optional[Any]												= max_seq_length
							UpperCamelCase__   :Dict												= (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
							UpperCamelCase__   :List[Any]												= feature_size
							UpperCamelCase__   :Union[str, Any]												= padding_value
							UpperCamelCase__   :Any												= sampling_rate
							UpperCamelCase__   :Tuple												= do_normalize
							UpperCamelCase__   :int												= num_mel_bins
							UpperCamelCase__   :Tuple												= hop_length
							UpperCamelCase__   :Any												= win_length
							UpperCamelCase__   :int												= win_function
							UpperCamelCase__   :Optional[Any]												= fmin
							UpperCamelCase__   :List[str]												= fmax
							UpperCamelCase__   :Tuple												= mel_floor
							UpperCamelCase__   :Dict												= return_attention_mask




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							return {
							    "feature_size": self.feature_size,
							    "padding_value": self.padding_value,
							    "sampling_rate": self.sampling_rate,
							    "do_normalize": self.do_normalize,
							    "num_mel_bins": self.num_mel_bins,
							    "hop_length": self.hop_length,
							    "win_length": self.win_length,
							    "win_function": self.win_function,
							    "fmin": self.fmin,
							    "fmax": self.fmax,
							    "mel_floor": self.mel_floor,
							    "return_attention_mask": self.return_attention_mask,
							}




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_=False    ,   UpperCamelCase_=False							):

							'''simple docstring'''


							def _flatten(UpperCamelCase_							):
												return list(itertools.chain(*UpperCamelCase_							)							)

							if equal_length:
												UpperCamelCase__   :Optional[int]												= floats_list((self.batch_size, self.max_seq_length)							)
							else:
												# make sure that inputs increase in size
												UpperCamelCase__   :List[str]												= [
												    _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:
												UpperCamelCase__   :int												= [np.asarray(UpperCamelCase_							) for x in speech_inputs]

							return speech_inputs




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_=False    ,   UpperCamelCase_=False							):

							'''simple docstring'''


							if equal_length:
												UpperCamelCase__   :int												= [floats_list((self.max_seq_length, self.num_mel_bins)							) for _ in range(self.batch_size							)]
							else:
												# make sure that inputs increase in size
												UpperCamelCase__   :Dict												= [
												    floats_list((x, self.num_mel_bins)							)
												    for x in range(self.min_seq_length    ,   self.max_seq_length    ,   self.seq_length_diff							)
												]

							if numpify:
												UpperCamelCase__   :Optional[Any]												= [np.asarray(UpperCamelCase_							) for x in speech_inputs]

							return speech_inputs



@require_torch
class    lowercase	(							_a	,		unittest.TestCase					):

		"""simple docstring"""

		_a     =				SpeechTaFeatureExtractor




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :str												= SpeechTaFeatureExtractionTester(self							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							self.assertTrue(np.all(np.mean(UpperCamelCase_    ,   axis=0							) < 1e-3							)							)
							self.assertTrue(np.all(np.abs(np.var(UpperCamelCase_    ,   axis=0							) - 1							) < 1e-3							)							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Tuple												= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
							# create three inputs of length 800, 1000, and 1200
							UpperCamelCase__   :Dict												= [floats_list((1, x)							)[0] for x in range(800    ,   1400    ,   200							)]
							UpperCamelCase__   :Any												= [np.asarray(UpperCamelCase_							) for speech_input in speech_inputs]

							# Test not batched input
							UpperCamelCase__   :Optional[Any]												= feat_extract(speech_inputs[0]    ,   return_tensors='''np'''							).input_values
							UpperCamelCase__   :Union[str, Any]												= feat_extract(np_speech_inputs[0]    ,   return_tensors='''np'''							).input_values
							self.assertTrue(np.allclose(UpperCamelCase_    ,   UpperCamelCase_    ,   atol=1e-3							)							)

							# Test batched
							UpperCamelCase__   :int												= feat_extract(UpperCamelCase_    ,   return_tensors='''np'''							).input_values
							UpperCamelCase__   :Tuple												= feat_extract(UpperCamelCase_    ,   return_tensors='''np'''							).input_values
							for enc_seq_a, enc_seq_a in zip(UpperCamelCase_    ,   UpperCamelCase_							):
												self.assertTrue(np.allclose(UpperCamelCase_    ,   UpperCamelCase_    ,   atol=1e-3							)							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Tuple												= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
							UpperCamelCase__   :Union[str, Any]												= [floats_list((1, x)							)[0] for x in range(800    ,   1400    ,   200							)]

							UpperCamelCase__   :str												= ['longest', 'max_length', 'do_not_pad']
							UpperCamelCase__   :List[str]												= [None, 1600, None]
							for max_length, padding in zip(UpperCamelCase_    ,   UpperCamelCase_							):
												UpperCamelCase__   :Any												= feat_extract(UpperCamelCase_    ,   padding=UpperCamelCase_    ,   max_length=UpperCamelCase_    ,   return_tensors='''np'''							)
												UpperCamelCase__   :Optional[Any]												= processed.input_values

												self._check_zero_mean_unit_variance(input_values[0][:800]							)
												self.assertTrue(input_values[0][800:].sum() < 1e-6							)
												self._check_zero_mean_unit_variance(input_values[1][:1000]							)
												self.assertTrue(input_values[0][1000:].sum() < 1e-6							)
												self._check_zero_mean_unit_variance(input_values[2][:1200]							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Dict												= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
							UpperCamelCase__   :Tuple												= range(800    ,   1400    ,   200							)
							UpperCamelCase__   :Optional[int]												= [floats_list((1, x)							)[0] for x in lengths]

							UpperCamelCase__   :Optional[Any]												= ['longest', 'max_length', 'do_not_pad']
							UpperCamelCase__   :Optional[int]												= [None, 1600, None]

							for max_length, padding in zip(UpperCamelCase_    ,   UpperCamelCase_							):
												UpperCamelCase__   :Union[str, Any]												= feat_extract(UpperCamelCase_    ,   max_length=UpperCamelCase_    ,   padding=UpperCamelCase_							)
												UpperCamelCase__   :List[Any]												= processed.input_values

												self._check_zero_mean_unit_variance(input_values[0][:800]							)
												self._check_zero_mean_unit_variance(input_values[1][:1000]							)
												self._check_zero_mean_unit_variance(input_values[2][:1200]							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :List[Any]												= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
							UpperCamelCase__   :Dict												= [floats_list((1, x)							)[0] for x in range(800    ,   1400    ,   200							)]
							UpperCamelCase__   :Union[str, Any]												= feat_extract(
							    UpperCamelCase_    ,   truncation=UpperCamelCase_    ,   max_length=1000    ,   padding='''max_length'''    ,   return_tensors='''np'''							)
							UpperCamelCase__   :List[str]												= processed.input_values

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




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Optional[int]												= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
							UpperCamelCase__   :Optional[Any]												= [floats_list((1, x)							)[0] for x in range(800    ,   1400    ,   200							)]
							UpperCamelCase__   :int												= feat_extract(
							    UpperCamelCase_    ,   truncation=UpperCamelCase_    ,   max_length=1000    ,   padding='''longest'''    ,   return_tensors='''np'''							)
							UpperCamelCase__   :Dict												= processed.input_values

							self._check_zero_mean_unit_variance(input_values[0, :800]							)
							self._check_zero_mean_unit_variance(input_values[1, :1000]							)
							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, 1000)							)

							UpperCamelCase__   :Optional[int]												= [floats_list((1, x)							)[0] for x in range(800    ,   1400    ,   200							)]
							UpperCamelCase__   :Any												= feat_extract(
							    UpperCamelCase_    ,   truncation=UpperCamelCase_    ,   max_length=2000    ,   padding='''longest'''    ,   return_tensors='''np'''							)
							UpperCamelCase__   :List[str]												= processed.input_values

							self._check_zero_mean_unit_variance(input_values[0, :800]							)
							self._check_zero_mean_unit_variance(input_values[1, :1000]							)
							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, 1200)							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Optional[Any]												= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
							UpperCamelCase__   :Optional[Any]												= np.random.rand(100							).astype(np.floataa							)
							UpperCamelCase__   :Any												= np_speech_inputs.tolist()

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




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :int												= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
							# create three inputs of length 800, 1000, and 1200
							UpperCamelCase__   :List[str]												= [floats_list((1, x)							)[0] for x in range(800    ,   1400    ,   200							)]
							UpperCamelCase__   :Optional[int]												= [np.asarray(UpperCamelCase_							) for speech_input in speech_inputs]

							# Test feature size
							UpperCamelCase__   :Optional[int]												= feature_extractor(audio_target=UpperCamelCase_    ,   padding=UpperCamelCase_    ,   return_tensors='''np'''							).input_values
							self.assertTrue(input_values.ndim == 3							)
							self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins							)

							# Test not batched input
							UpperCamelCase__   :Union[str, Any]												= feature_extractor(speech_inputs[0]    ,   return_tensors='''np'''							).input_values
							UpperCamelCase__   :Tuple												= feature_extractor(np_speech_inputs[0]    ,   return_tensors='''np'''							).input_values
							self.assertTrue(np.allclose(UpperCamelCase_    ,   UpperCamelCase_    ,   atol=1e-3							)							)

							# Test batched
							UpperCamelCase__   :int												= feature_extractor(UpperCamelCase_    ,   return_tensors='''np'''							).input_values
							UpperCamelCase__   :Union[str, Any]												= feature_extractor(UpperCamelCase_    ,   return_tensors='''np'''							).input_values
							for enc_seq_a, enc_seq_a in zip(UpperCamelCase_    ,   UpperCamelCase_							):
												self.assertTrue(np.allclose(UpperCamelCase_    ,   UpperCamelCase_    ,   atol=1e-3							)							)

							# Test 2-D numpy arrays are batched.
							UpperCamelCase__   :List[Any]												= [floats_list((1, x)							)[0] for x in (800, 800, 800)]
							UpperCamelCase__   :Tuple												= np.asarray(UpperCamelCase_							)
							UpperCamelCase__   :int												= feature_extractor(UpperCamelCase_    ,   return_tensors='''np'''							).input_values
							UpperCamelCase__   :List[str]												= feature_extractor(UpperCamelCase_    ,   return_tensors='''np'''							).input_values
							for enc_seq_a, enc_seq_a in zip(UpperCamelCase_    ,   UpperCamelCase_							):
												self.assertTrue(np.allclose(UpperCamelCase_    ,   UpperCamelCase_    ,   atol=1e-3							)							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Tuple												= self.feat_extract_tester.prepare_inputs_for_target()
							UpperCamelCase__   :str												= self.feature_extraction_class(**self.feat_extract_dict							)
							UpperCamelCase__   :str												= feat_extract.model_input_names[0]

							UpperCamelCase__   :int												= BatchFeature({input_name: speech_inputs}							)

							self.assertTrue(all(len(UpperCamelCase_							) == len(UpperCamelCase_							) for x, y in zip(UpperCamelCase_    ,   processed_features[input_name]							)							)							)

							UpperCamelCase__   :List[str]												= self.feat_extract_tester.prepare_inputs_for_target(equal_length=UpperCamelCase_							)
							UpperCamelCase__   :Dict												= BatchFeature({input_name: speech_inputs}    ,   tensor_type='''np'''							)

							UpperCamelCase__   :List[str]												= processed_features[input_name]

							if len(batch_features_input.shape							) < 3:
												UpperCamelCase__   :Optional[int]												= batch_features_input[:, :, None]

							self.assertTrue(
							    batch_features_input.shape
							    == (self.feat_extract_tester.batch_size, len(speech_inputs[0]							), self.feat_extract_tester.num_mel_bins)							)




		@require_torch
		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Optional[int]												= self.feat_extract_tester.prepare_inputs_for_target(equal_length=UpperCamelCase_							)
							UpperCamelCase__   :str												= self.feature_extraction_class(**self.feat_extract_dict							)
							UpperCamelCase__   :Optional[int]												= feat_extract.model_input_names[0]

							UpperCamelCase__   :str												= BatchFeature({input_name: speech_inputs}    ,   tensor_type='''pt'''							)

							UpperCamelCase__   :str												= processed_features[input_name]

							if len(batch_features_input.shape							) < 3:
												UpperCamelCase__   :Tuple												= batch_features_input[:, :, None]

							self.assertTrue(
							    batch_features_input.shape
							    == (self.feat_extract_tester.batch_size, len(speech_inputs[0]							), self.feat_extract_tester.num_mel_bins)							)




		@require_torch
		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Dict												= self.feature_extraction_class(**self.feat_extract_dict							)
							UpperCamelCase__   :str												= self.feat_extract_tester.prepare_inputs_for_target()
							UpperCamelCase__   :Any												= feat_extract.model_input_names[0]

							UpperCamelCase__   :Union[str, Any]												= BatchFeature({input_name: speech_inputs}							)

							UpperCamelCase__   :List[str]												= feat_extract.num_mel_bins  # hack!

							UpperCamelCase__   :int												= feat_extract.pad(UpperCamelCase_    ,   padding='''longest'''    ,   return_tensors='''np'''							)[input_name]
							UpperCamelCase__   :List[str]												= feat_extract.pad(UpperCamelCase_    ,   padding='''longest'''    ,   return_tensors='''pt'''							)[input_name]

							self.assertTrue(abs(input_np.astype(np.floataa							).sum() - input_pt.numpy().astype(np.floataa							).sum()							) < 1e-2							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :int												= self.feat_extract_dict
							UpperCamelCase__   :int												= True
							UpperCamelCase__   :Optional[int]												= self.feature_extraction_class(**UpperCamelCase_							)
							UpperCamelCase__   :int												= self.feat_extract_tester.prepare_inputs_for_target()
							UpperCamelCase__   :List[str]												= [len(UpperCamelCase_							) for x in speech_inputs]
							UpperCamelCase__   :Dict												= feat_extract.model_input_names[0]

							UpperCamelCase__   :Tuple												= BatchFeature({input_name: speech_inputs}							)

							UpperCamelCase__   :Tuple												= feat_extract.num_mel_bins  # hack!

							UpperCamelCase__   :Union[str, Any]												= feat_extract.pad(UpperCamelCase_    ,   padding='''longest'''    ,   return_tensors='''np'''							)
							self.assertIn('''attention_mask'''    ,   UpperCamelCase_							)
							self.assertListEqual(list(processed.attention_mask.shape							)    ,   list(processed[input_name].shape[:2]							)							)
							self.assertListEqual(processed.attention_mask.sum(-1							).tolist()    ,   UpperCamelCase_							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :int												= self.feat_extract_dict
							UpperCamelCase__   :int												= True
							UpperCamelCase__   :Dict												= self.feature_extraction_class(**UpperCamelCase_							)
							UpperCamelCase__   :Union[str, Any]												= self.feat_extract_tester.prepare_inputs_for_target()
							UpperCamelCase__   :List[Any]												= [len(UpperCamelCase_							) for x in speech_inputs]
							UpperCamelCase__   :List[str]												= feat_extract.model_input_names[0]

							UpperCamelCase__   :Optional[Any]												= BatchFeature({input_name: speech_inputs}							)
							UpperCamelCase__   :Dict												= min(UpperCamelCase_							)

							UpperCamelCase__   :Optional[int]												= feat_extract.num_mel_bins  # hack!

							UpperCamelCase__   :Optional[int]												= feat_extract.pad(
							    UpperCamelCase_    ,   padding='''max_length'''    ,   max_length=UpperCamelCase_    ,   truncation=UpperCamelCase_    ,   return_tensors='''np'''							)
							self.assertIn('''attention_mask'''    ,   UpperCamelCase_							)
							self.assertListEqual(
							    list(processed_pad.attention_mask.shape							)    ,   [processed_pad[input_name].shape[0], max_length]							)
							self.assertListEqual(
							    processed_pad.attention_mask[:, :max_length].sum(-1							).tolist()    ,   [max_length for x in speech_inputs]							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							from datasets import load_dataset

							UpperCamelCase__   :Union[str, Any]												= load_dataset('''hf-internal-testing/librispeech_asr_dummy'''    ,   '''clean'''    ,   split='''validation'''							)
							# automatic decoding with librispeech
							UpperCamelCase__   :List[Any]												= ds.sort('''id'''							).select(range(UpperCamelCase_							)							)[:num_samples]['audio']

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




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Dict												= torch.tensor(
							    [2.38_04e-03, 2.07_52e-03, 1.98_36e-03, 2.10_57e-03, 1.61_74e-03,
							     3.05_18e-04, 9.15_53e-05, 3.35_69e-04, 9.76_56e-04, 1.83_11e-03,
							     2.01_42e-03, 2.10_57e-03, 1.73_95e-03, 4.57_76e-04, -3.96_73e-04,
							     4.57_76e-04, 1.00_71e-03, 9.15_53e-05, 4.88_28e-04, 1.15_97e-03,
							     7.32_42e-04, 9.46_04e-04, 1.80_05e-03, 1.83_11e-03, 8.85_01e-04,
							     4.27_25e-04, 4.88_28e-04, 7.32_42e-04, 1.09_86e-03, 2.10_57e-03]							)
							# fmt: on

							UpperCamelCase__   :List[str]												= self._load_datasamples(1							)
							UpperCamelCase__   :Any												= SpeechTaFeatureExtractor()
							UpperCamelCase__   :Union[str, Any]												= feature_extractor(UpperCamelCase_    ,   return_tensors='''pt'''							).input_values
							self.assertEquals(input_values.shape    ,   (1, 93680)							)
							self.assertTrue(torch.allclose(input_values[0, :30]    ,   UpperCamelCase_    ,   atol=1e-6							)							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Optional[Any]												= torch.tensor(
							    [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777,
							     -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386,
							     -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571,
							     -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998]							)
							# fmt: on

							UpperCamelCase__   :Optional[int]												= self._load_datasamples(1							)
							UpperCamelCase__   :str												= SpeechTaFeatureExtractor()
							UpperCamelCase__   :Any												= feature_extractor(audio_target=UpperCamelCase_    ,   return_tensors='''pt'''							).input_values
							self.assertEquals(input_values.shape    ,   (1, 366, 80)							)
							self.assertTrue(torch.allclose(input_values[0, 0, :30]    ,   UpperCamelCase_    ,   atol=1e-4							)							)



import collections
from typing import List, Optional, Union

from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
from ..bert.tokenization_bert import BertTokenizer


SCREAMING_SNAKE_CASE       :      Any												= logging.get_logger(__name__)

SCREAMING_SNAKE_CASE       :      Union[str, Any]												= {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

SCREAMING_SNAKE_CASE       :      Union[str, Any]												= {
    "vocab_file": {
        "facebook/dpr-ctx_encoder-single-nq-base": (
            "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt"
        ),
        "facebook/dpr-ctx_encoder-multiset-base": (
            "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt"
        ),
    },
    "tokenizer_file": {
        "facebook/dpr-ctx_encoder-single-nq-base": (
            "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json"
        ),
        "facebook/dpr-ctx_encoder-multiset-base": (
            "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json"
        ),
    },
}
SCREAMING_SNAKE_CASE       :      Dict												= {
    "vocab_file": {
        "facebook/dpr-question_encoder-single-nq-base": (
            "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt"
        ),
        "facebook/dpr-question_encoder-multiset-base": (
            "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt"
        ),
    },
    "tokenizer_file": {
        "facebook/dpr-question_encoder-single-nq-base": (
            "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json"
        ),
        "facebook/dpr-question_encoder-multiset-base": (
            "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json"
        ),
    },
}
SCREAMING_SNAKE_CASE       :      str												= {
    "vocab_file": {
        "facebook/dpr-reader-single-nq-base": (
            "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt"
        ),
        "facebook/dpr-reader-multiset-base": (
            "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt"
        ),
    },
    "tokenizer_file": {
        "facebook/dpr-reader-single-nq-base": (
            "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json"
        ),
        "facebook/dpr-reader-multiset-base": (
            "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json"
        ),
    },
}

SCREAMING_SNAKE_CASE       :      Dict												= {
    "facebook/dpr-ctx_encoder-single-nq-base": 512,
    "facebook/dpr-ctx_encoder-multiset-base": 512,
}
SCREAMING_SNAKE_CASE       :      Optional[Any]												= {
    "facebook/dpr-question_encoder-single-nq-base": 512,
    "facebook/dpr-question_encoder-multiset-base": 512,
}
SCREAMING_SNAKE_CASE       :      Dict												= {
    "facebook/dpr-reader-single-nq-base": 512,
    "facebook/dpr-reader-multiset-base": 512,
}


SCREAMING_SNAKE_CASE       :      List[Any]												= {
    "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True},
    "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True},
}
SCREAMING_SNAKE_CASE       :      Dict												= {
    "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True},
    "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True},
}
SCREAMING_SNAKE_CASE       :      Dict												= {
    "facebook/dpr-reader-single-nq-base": {"do_lower_case": True},
    "facebook/dpr-reader-multiset-base": {"do_lower_case": True},
}






class _lowerCamelCase(						_a   ):
       lowercase_ :	Any     =			VOCAB_FILES_NAMES
       lowercase_ :	Optional[int]     =			CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
       lowercase_ :	str     =			CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowercase_ :	str     =			CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION






class _lowerCamelCase(						_a   ):
       lowercase_ :	Optional[int]     =			VOCAB_FILES_NAMES
       lowercase_ :	Any     =			QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
       lowercase_ :	str     =			QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowercase_ :	Union[str, Any]     =			QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION


SCREAMING_SNAKE_CASE       :      Optional[int]												= collections.namedtuple(
    "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"]
)

SCREAMING_SNAKE_CASE       :      Any												= collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"])


SCREAMING_SNAKE_CASE       :      str												= r"\n    Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n    It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n    using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n    with the format:\n\n    ```\n    [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n    ```\n\n    Args:\n        questions (`str` or `List[str]`):\n            The questions to be encoded. You can specify one question for many passages. In this case, the question\n            will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n            `titles` or `texts`.\n        titles (`str` or `List[str]`):\n            The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n        texts (`str` or `List[str]`):\n            The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n            Activates and controls padding. Accepts the following values:\n\n            - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n              if provided).\n            - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided.\n            - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n              lengths).\n        truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n            Activates and controls truncation. Accepts the following values:\n\n            - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n              the maximum acceptable input length for the model if that argument is not provided. This will truncate\n              token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n              of pairs) is provided.\n            - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided. This will only truncate the first\n              sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n            - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided. This will only truncate the\n              second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n            - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n              greater than the model maximum admissible input size).\n        max_length (`int`, *optional*):\n                Controls the maximum length to use by one of the truncation/padding parameters.\n\n                If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n                is required by one of the truncation/padding parameters. If the model has no specific maximum input\n                length (like XLNet) truncation/padding to a maximum length will be deactivated.\n        return_tensors (`str` or [`~utils.TensorType`], *optional*):\n                If set, will return tensors instead of list of python integers. Acceptable values are:\n\n                - `'tf'`: Return TensorFlow `tf.constant` objects.\n                - `'pt'`: Return PyTorch `torch.Tensor` objects.\n                - `'np'`: Return Numpy `np.ndarray` objects.\n        return_attention_mask (`bool`, *optional*):\n            Whether or not to return the attention mask. If not set, will return the attention mask according to the\n            specific tokenizer's default, defined by the `return_outputs` attribute.\n\n            [What are attention masks?](../glossary#attention-mask)\n\n    Returns:\n        `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n        - `input_ids`: List of token ids to be fed to a model.\n        - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n    "






@add_start_docstrings(_a   )
class _lowerCamelCase:
       def __call__(					self,      lowerCamelCase,      lowerCamelCase = None,      lowerCamelCase = None,      lowerCamelCase = False,      lowerCamelCase = False,      lowerCamelCase = None,      lowerCamelCase = None,      lowerCamelCase = None,      **lowerCamelCase,      )       ->   BatchEncoding:




           """simple docstring"""

           if titles is None and texts is None:
               return super().__call__(
                   lowerCamelCase,      padding=lowerCamelCase,      truncation=lowerCamelCase,      max_length=lowerCamelCase,      return_tensors=lowerCamelCase,      return_attention_mask=lowerCamelCase,      **lowerCamelCase,      )
           elif titles is None or texts is None:
               _lowercase       :							Dict      		=		titles if texts is None else texts
               return super().__call__(
                   lowerCamelCase,      lowerCamelCase,      padding=lowerCamelCase,      truncation=lowerCamelCase,      max_length=lowerCamelCase,      return_tensors=lowerCamelCase,      return_attention_mask=lowerCamelCase,      **lowerCamelCase,      )
           _lowercase       :							Union[str, Any]      		=		titles if not isinstance(lowerCamelCase,      lowerCamelCase) else [titles]
           _lowercase       :							Tuple      		=		texts if not isinstance(lowerCamelCase,      lowerCamelCase) else [texts]
           _lowercase       :							Optional[Any]      		=		len(lowerCamelCase)
           _lowercase       :							Any      		=		questions if not isinstance(lowerCamelCase,      lowerCamelCase) else [questions] * n_passages
           if len(lowerCamelCase) != len(lowerCamelCase):
               raise ValueError(
                   F'''There should be as many titles than texts but got {len(lowerCamelCase)} titles and {len(lowerCamelCase)} texts.''')
           _lowercase       :							Any      		=		super().__call__(lowerCamelCase,      lowerCamelCase,      padding=lowerCamelCase,      truncation=lowerCamelCase)['input_ids']
           _lowercase       :							Tuple      		=		super().__call__(lowerCamelCase,      add_special_tokens=lowerCamelCase,      padding=lowerCamelCase,      truncation=lowerCamelCase)['input_ids']
           _lowercase       :							int      		=		{
               'input_ids': [
                   (encoded_question_and_title + encoded_text)[:max_length]
                   if max_length is not None and truncation
                   else encoded_question_and_title + encoded_text
                   for encoded_question_and_title, encoded_text in zip(lowerCamelCase,      lowerCamelCase)
               ]
           }
           if return_attention_mask is not False:
               _lowercase       :							Optional[Any]      		=		[]
               for input_ids in encoded_inputs["input_ids"]:
                   attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids])
               _lowercase       :							Union[str, Any]      		=		attention_mask
           return self.pad(lowerCamelCase,      padding=lowerCamelCase,      max_length=lowerCamelCase,      return_tensors=lowerCamelCase)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase = 16,      lowerCamelCase = 64,      lowerCamelCase = 4,      )       ->   List[DPRSpanPrediction]:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		reader_input['input_ids']
           _lowercase		,				_lowercase		,				_lowercase       :							Tuple      		=		reader_output[:3]
           _lowercase       :							Tuple      		=		len(lowerCamelCase)
           _lowercase       :							str      		=		sorted(range(lowerCamelCase),      reverse=lowerCamelCase,      key=relevance_logits.__getitem__)
           _lowercase       :							List[DPRReaderOutput]      		=		[]
           for doc_id in sorted_docs:
               _lowercase       :							str      		=		list(input_ids[doc_id])
               # assuming question & title information is at the beginning of the sequence
               _lowercase       :							Any      		=		sequence_ids.index(self.sep_token_id,      2) + 1  # second sep id
               if sequence_ids[-1] == self.pad_token_id:
                   _lowercase       :							List[Any]      		=		sequence_ids.index(self.pad_token_id)
               else:
                   _lowercase       :							List[str]      		=		len(lowerCamelCase)

               _lowercase       :							Tuple      		=		self._get_best_spans(
                   start_logits=start_logits[doc_id][passage_offset:sequence_len],      end_logits=end_logits[doc_id][passage_offset:sequence_len],      max_answer_length=lowerCamelCase,      top_spans=lowerCamelCase,      )
               for start_index, end_index in best_spans:
                   start_index += passage_offset
                   end_index += passage_offset
                   nbest_spans_predictions.append(
                       DPRSpanPrediction(
                           span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index],      relevance_score=relevance_logits[doc_id],      doc_id=lowerCamelCase,      start_index=lowerCamelCase,      end_index=lowerCamelCase,      text=self.decode(sequence_ids[start_index : end_index + 1]),      ))
               if len(lowerCamelCase) >= num_spans:
                   break
           return nbest_spans_predictions[:num_spans]




       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      )       ->   List[DPRSpanPrediction]:




           """simple docstring"""

           _lowercase       :							str      		=		[]
           for start_index, start_score in enumerate(lowerCamelCase):
               for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]):
                   scores.append(((start_index, start_index + answer_length), start_score + end_score))
           _lowercase       :							Dict      		=		sorted(lowerCamelCase,      key=lambda lowerCamelCase: x[1],      reverse=lowerCamelCase)
           _lowercase       :							List[str]      		=		[]
           for (start_index, end_index), score in scores:
               if start_index > end_index:
                   raise ValueError(F'''Wrong span indices: [{start_index}:{end_index}]''')
               _lowercase       :							Dict      		=		end_index - start_index + 1
               if length > max_answer_length:
                   raise ValueError(F'''Span is too long: {length} > {max_answer_length}''')
               if any(
                   start_index <= prev_start_index <= prev_end_index <= end_index
                   or prev_start_index <= start_index <= end_index <= prev_end_index
                   for (prev_start_index, prev_end_index) in chosen_span_intervals):
                   continue
               chosen_span_intervals.append((start_index, end_index))

               if len(lowerCamelCase) == top_spans:
                   break
           return chosen_span_intervals






@add_end_docstrings(_a   )
class _lowerCamelCase(						_a, _a   ):
       lowercase_ :	Union[str, Any]     =			VOCAB_FILES_NAMES
       lowercase_ :	Any     =			READER_PRETRAINED_VOCAB_FILES_MAP
       lowercase_ :	Dict     =			READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowercase_ :	Optional[int]     =			READER_PRETRAINED_INIT_CONFIGURATION
       lowercase_ :	str     =			["""input_ids""", """attention_mask"""]


