



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__       =			"""block_records.npy"""


A__       =			logging.get_logger(__name__)


def 						_UpperCAmelCase							( snake_case      ,		snake_case     ):





					"""simple docstring"""

					import tensorflow.compat.va as tf

					_lowerCAmelCase         =       tf.data.TFRecordDataset(snake_case      ,		buffer_size=5_12 * 10_24 * 10_24     )
					_lowerCAmelCase         =       blocks_dataset.batch(snake_case      ,		drop_remainder=snake_case     )
					_lowerCAmelCase         =       next(blocks_dataset.take(1     ).as_numpy_iterator()     )

					return np_record





class    __lowerCAmelCase					:




				def __init__(				self		,							_snake_case		,							_snake_case		,							_snake_case=2		,							_snake_case=1000		,							_snake_case=100		,							_snake_case=100000		,							):



									"""simple docstring"""





									from scann.scann_ops.py.scann_ops_pybind import builder as Builder

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

									_lowerCAmelCase         =       builder.build()




				def 				snake_case  (				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase      ,      _lowerCAmelCase         =       self.searcher.search_batched(question_projection.detach().cpu()						)
									return retrieved_block_ids.astype("""int64"""						)





class    __lowerCAmelCase					:




				def __init__(				self		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									super().__init__()
									_lowerCAmelCase         =       block_records
									_lowerCAmelCase         =       tokenizer




				def __call__(				self		,							_snake_case		,							_snake_case		,							_snake_case		,							_snake_case=None		,							_snake_case="pt"						):



									"""simple docstring"""





									_lowerCAmelCase         =       np.take(self.block_records		,							indices=_snake_case		,							axis=0						)

									_lowerCAmelCase         =       self.tokenizer.decode(question_input_ids[0]		,							skip_special_tokens=_snake_case						)

									_lowerCAmelCase         =       []
									_lowerCAmelCase         =       []
									for retrieved_block in retrieved_blocks:
														text.append(_snake_case						)
														text_pair.append(retrieved_block.decode()						)

									_lowerCAmelCase         =       self.tokenizer(
									    _snake_case		,							_snake_case		,							padding=_snake_case		,							truncation=_snake_case		,							return_special_tokens_mask=_snake_case		,							max_length=_snake_case						)
									_lowerCAmelCase         =       concat_inputs.convert_to_tensors(_snake_case						)

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




				@classmethod
				def 				snake_case  (				cls		,							_snake_case		,							*_snake_case		,							**_snake_case						):



									"""simple docstring"""





									if os.path.isdir(_snake_case						):
														_lowerCAmelCase         =       os.path.join(_snake_case		,							_REALM_BLOCK_RECORDS_FILENAME						)
									else:
														_lowerCAmelCase         =       hf_hub_download(
														    repo_id=_snake_case		,							filename=_REALM_BLOCK_RECORDS_FILENAME		,							**_snake_case						)
									_lowerCAmelCase         =       np.load(_snake_case		,							allow_pickle=_snake_case						)

									_lowerCAmelCase         =       AutoTokenizer.from_pretrained(_snake_case		,							*_snake_case		,							**_snake_case						)

									return cls(_snake_case		,							_snake_case						)




				def 				snake_case  (				self		,							_snake_case						):



									"""simple docstring"""





									np.save(os.path.join(_snake_case		,							_REALM_BLOCK_RECORDS_FILENAME						)		,							self.block_records						)
									# save tokenizer
									self.tokenizer.save_pretrained(_snake_case						)




				def 				snake_case  (				self		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       []
									_lowerCAmelCase         =       []
									_lowerCAmelCase         =       []
									_lowerCAmelCase         =       0

									for input_id in concat_inputs.input_ids:
														_lowerCAmelCase         =       input_id.tolist()
														# Check answers between two [SEP] tokens
														_lowerCAmelCase         =       input_id_list.index(self.tokenizer.sep_token_id						)
														_lowerCAmelCase         =       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		,							_snake_case						):
																								if answer[0] == input_id_list[idx]:
																													if input_id_list[idx : idx + len(_snake_case						)] == answer:
																																		start_pos[-1].append(_snake_case						)
																																		end_pos[-1].append(idx + len(_snake_case						) - 1						)

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

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







import bisect
import copy
from collections import defaultdict

import numpy as np
from torch.utils.data import BatchSampler, Sampler

from utils import logger



def 			_a      (    __UpperCamelCase	,	__UpperCamelCase			):
     a_     :  Optional[Any]				      =     copy.deepcopy(__UpperCamelCase			)
     a_     :  Dict				      =     sorted(__UpperCamelCase			)
     a_     :  Dict				      =     [bisect.bisect_right(__UpperCamelCase	,	__UpperCamelCase			) for y in x]
     return quantized



def 			_a      (    __UpperCamelCase	,	__UpperCamelCase=0			):
     a_     :  str				      =     np.arange(start=3	,	stop=__UpperCamelCase	,	step=4			).tolist() if k > 0 else [1_0]
     a_     :  Any				      =     _quantize(__UpperCamelCase	,	__UpperCamelCase			)
     # count number of elements per group
     a_     :  Optional[int]				      =     np.unique(__UpperCamelCase	,	return_counts=__UpperCamelCase			)[1]
     a_     :  List[str]				      =     [0] + bins + [np.inf]
     logger.info("""Using {} as bins for aspect lengths quantization""".format(__UpperCamelCase			)			)
     logger.info("""Count of instances per bin: {}""".format(__UpperCamelCase			)			)
     return groups


class 	a__						(    lowerCAmelCase_     ):

       def __init__( self   :  int   ,				lowerCamelCase_   :  str   ,				lowerCamelCase_   :  int   ,				lowerCamelCase_   :  str     ):
            if not isinstance(lowerCamelCase_   ,				lowerCamelCase_     ):
                 raise ValueError(
                     """sampler should be an instance of torch.utils.data.Sampler, but got sampler={}""".format(lowerCamelCase_     )     )
            a_     :  Optional[Any]				      =     sampler
            a_     :  List[Any]				      =     group_ids
            a_     :  Tuple				      =     batch_size

       def __iter__( self   :  Dict     ):
            a_     :  Tuple				      =     defaultdict(lowerCamelCase_     )
            a_     :  Any				      =     defaultdict(lowerCamelCase_     )

            a_     :  Any				      =     0
            for idx in self.sampler:
                 a_     :  str				      =     self.group_ids[idx]
                 buffer_per_group[group_id].append(lowerCamelCase_     )
                 samples_per_group[group_id].append(lowerCamelCase_     )
                 if len(buffer_per_group[group_id]     ) == self.batch_size:
                      yield buffer_per_group[group_id]  # TODO
                      num_batches += 1
                      del buffer_per_group[group_id]
                 assert len(buffer_per_group[group_id]     ) < self.batch_size

            # now we have run out of elements that satisfy
            # the group criteria, let's return the remaining
            # elements so that the size of the sampler is
            # deterministic
            a_     :  Optional[Any]				      =     len(self     )
            a_     :  Any				      =     expected_num_batches - num_batches
            if num_remaining > 0:
                 # for the remaining batches, group the batches by similar lengths
                 a_     :  str				      =     []
                 for group_id, idxs in sorted(buffer_per_group.items()   ,				key=lambda lowerCamelCase_     : x[0]     ):
                      batch_idx.extend(lowerCamelCase_     )
                      if len(lowerCamelCase_     ) >= self.batch_size:
                           yield batch_idx[: self.batch_size]
                           a_     :  Union[str, Any]				      =     batch_idx[self.batch_size :]
                           num_remaining -= 1
                 if len(lowerCamelCase_     ) > 0:
                      yield batch_idx
                      num_remaining -= 1
            assert num_remaining == 0

       def __len__( self   :  List[Any]     ):
            return (len(self.sampler     ) + self.batch_size - 1) // self.batch_size



