






'''simple docstring'''







import os
from typing import Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ... import AutoTokenizer
from ...utils import logging


__A   :							Dict     	=						'block_records.npy'


__A   :							Optional[int]     	=						logging.get_logger(__name__)


def     _UpperCamelCase				(  snake_case__				,      snake_case__				):
      import tensorflow.compat.va as tf

      __A		 =   tf.data.TFRecordDataset(snake_case__				,      buffer_size=512 * 1_024 * 1_024				)
      __A		 =   blocks_dataset.batch(snake_case__				,      drop_remainder=snake_case__				)
      __A		 =   next(blocks_dataset.take(1				).as_numpy_iterator()				)

      return np_record






class        a__     :
     '''simple docstring'''







     def __init__(self     :						Optional[int]					,					lowercase__     :						Optional[Any]					,					lowercase__     :						int					,					lowercase__     :						str=2					,					lowercase__     :						List[str]=1000					,					lowercase__     :						Any=100					,					lowercase__     :						Union[str, Any]=100000					,					)	->							Union[str, Any]:
           from scann.scann_ops.py.scann_ops_pybind import builder as Builder

           __A		 =   Builder(db=lowercase__					,					num_neighbors=lowercase__					,					distance_measure="dot_product"       )
           __A		 =   builder.tree(
               num_leaves=lowercase__					,					num_leaves_to_search=lowercase__					,					training_sample_size=lowercase__       )
           __A		 =   builder.score_ah(dimensions_per_block=lowercase__       )

           __A		 =   builder.build()






     def      _UpperCamelCase (self     :						Optional[int]					,					lowercase__     :						Tuple       )	->							Union[str, Any]:
           __A ,					__A		 =   self.searcher.search_batched(question_projection.detach().cpu()       )
           return retrieved_block_ids.astype("int64"       )







class        a__     :
     '''simple docstring'''







     def __init__(self     :						Union[str, Any]					,					lowercase__     :						Dict					,					lowercase__     :						Optional[Any]       )	->							Union[str, Any]:
           super().__init__()
           __A		 =   block_records
           __A		 =   tokenizer






     def __call__(self     :						Dict					,					lowercase__     :						Union[str, Any]					,					lowercase__     :						str					,					lowercase__     :						Tuple					,					lowercase__     :						Tuple=None					,					lowercase__     :						Optional[int]="pt"       )	->							Dict:
           __A		 =   np.take(self.block_records					,					indices=lowercase__					,					axis=0       )

           __A		 =   self.tokenizer.decode(question_input_ids[0]					,					skip_special_tokens=lowercase__       )

           __A		 =   []
           __A		 =   []
           for retrieved_block in retrieved_blocks:
                 text.append(lowercase__       )
                 text_pair.append(retrieved_block.decode()       )

           __A		 =   self.tokenizer(
               lowercase__					,					lowercase__					,					padding=lowercase__					,					truncation=lowercase__					,					return_special_tokens_mask=lowercase__					,					max_length=lowercase__       )
           __A		 =   concat_inputs.convert_to_tensors(lowercase__       )

           if answer_ids is not None:
                 return self.block_has_answer(lowercase__					,					lowercase__       ) + (concat_inputs_tensors,)
           else:
                 return (None, None, None, concat_inputs_tensors)






     @classmethod
     def      _UpperCamelCase (cls     :						List[str]					,					lowercase__     :						Optional[Union[str, os.PathLike]]					,					*lowercase__     :						str					,					**lowercase__     :						Union[str, Any]       )	->							Tuple:
           if os.path.isdir(lowercase__       ):
                 __A		 =   os.path.join(lowercase__					,					_REALM_BLOCK_RECORDS_FILENAME       )
           else:
                 __A		 =   hf_hub_download(
                     repo_id=lowercase__					,					filename=_REALM_BLOCK_RECORDS_FILENAME					,					**lowercase__       )
           __A		 =   np.load(lowercase__					,					allow_pickle=lowercase__       )

           __A		 =   AutoTokenizer.from_pretrained(lowercase__					,					*lowercase__					,					**lowercase__       )

           return cls(lowercase__					,					lowercase__       )






     def      _UpperCamelCase (self     :						List[str]					,					lowercase__     :						List[str]       )	->							Union[str, Any]:
           # save block records
           np.save(os.path.join(lowercase__					,					_REALM_BLOCK_RECORDS_FILENAME       )					,					self.block_records       )
           # save tokenizer
           self.tokenizer.save_pretrained(lowercase__       )






     def      _UpperCamelCase (self     :						List[Any]					,					lowercase__     :						Optional[int]					,					lowercase__     :						str       )	->							str:
           __A		 =   []
           __A		 =   []
           __A		 =   []
           __A		 =   0

           for input_id in concat_inputs.input_ids:
                 __A		 =   input_id.tolist()
                 # Check answers between two [SEP] tokens
                 __A		 =   input_id_list.index(self.tokenizer.sep_token_id       )
                 __A		 =   first_sep_idx + 1 + input_id_list[first_sep_idx + 1 :].index(self.tokenizer.sep_token_id       )

                 start_pos.append([]       )
                 end_pos.append([]       )
                 for answer in answer_ids:
                       for idx in range(first_sep_idx + 1					,					lowercase__       ):
                             if answer[0] == input_id_list[idx]:
                                   if input_id_list[idx : idx + len(lowercase__       )] == answer:
                                         start_pos[-1].append(lowercase__       )
                                         end_pos[-1].append(idx + len(lowercase__       ) - 1       )

                 if len(start_pos[-1]       ) == 0:
                       has_answers.append(lowercase__       )
                 else:
                       has_answers.append(lowercase__       )
                       if len(start_pos[-1]       ) > max_answers:
                             __A		 =   len(start_pos[-1]       )

        # Pad -1 to max_answers
           for start_pos_, end_pos_ in zip(lowercase__					,					lowercase__       ):
                 if len(start_pos_       ) < max_answers:
                       __A		 =   [-1] * (max_answers - len(start_pos_       ))
                       start_pos_ += padded
                       end_pos_ += padded
           return has_answers, start_pos, end_pos










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


__A   :							int     	=						logging.get_logger(__name__)






class        a__     (      lowerCamelCase    ):
     '''simple docstring'''







     _snake_case							   =	['input_values', 'attention_mask']






     def __init__(self     :						Optional[int]					,					lowercase__     :						Tuple=1					,					lowercase__     :						Optional[int]=16000					,					lowercase__     :						Any=128					,					lowercase__     :						Optional[Any]=1024					,					lowercase__     :						int=0.0					,					lowercase__     :						List[str]=True					,					lowercase__     :						Dict=-4.2_67_73_93					,					lowercase__     :						Tuple=4.5_68_99_74					,					lowercase__     :						Optional[int]=False					,					**lowercase__     :						Optional[int]					,					)	->							Tuple:
           super().__init__(feature_size=lowercase__					,					sampling_rate=lowercase__					,					padding_value=lowercase__					,					**lowercase__       )
           __A		 =   num_mel_bins
           __A		 =   max_length
           __A		 =   do_normalize
           __A		 =   mean
           __A		 =   std
           __A		 =   return_attention_mask






     def      _UpperCamelCase (self     :						List[Any]					,					lowercase__     :						np.ndarray					,					lowercase__     :						int					,					)	->							np.ndarray:
           __A		 =   torch.from_numpy(lowercase__       ).unsqueeze(0       )
           __A		 =   ta_kaldi.fbank(
               lowercase__					,					htk_compat=lowercase__					,					sample_frequency=self.sampling_rate					,					use_energy=lowercase__					,					window_type="hanning"					,					num_mel_bins=self.num_mel_bins					,					dither=0.0					,					frame_shift=10					,					)

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

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

           __A		 =   fbank.numpy()

           return fbank






     def      _UpperCamelCase (self     :						int					,					lowercase__     :						np.ndarray       )	->							np.ndarray:
           return (input_values - (self.mean)) / (self.std * 2)






     def __call__(self     :						str					,					lowercase__     :						Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]					,					lowercase__     :						Optional[int] = None					,					lowercase__     :						Optional[Union[str, TensorType]] = None					,					**lowercase__     :						List[Any]					,					)	->							BatchFeature:

           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."       )

           __A		 =   isinstance(lowercase__					,					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}"       )
           __A		 =   is_batched_numpy or (
               isinstance(lowercase__					,					(list, tuple)       ) and (isinstance(raw_speech[0]					,					(np.ndarray, tuple, list)       ))
           )

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

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

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

           # convert into BatchFeature
           __A		 =   BatchFeature({"input_values": features}       )

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

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

           if return_tensors is not None:
                 __A		 =   padded_inputs.convert_to_tensors(lowercase__       )

           return padded_inputs


