



"""simple docstring"""
import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil
class 				lowerCamelCase  (			_lowerCAmelCase				):






					'''simple docstring'''





					def    lowerCAmelCase_				(       self:							Any						)   ->	Union[str, Any]:
											snake_case_ :int						=			pa.array(TypedSequence([1, 2, 3]						)						)
											self.assertEqual(arr.type						,     pa.intaa()						)






					def    lowerCAmelCase_				(       self:							int						)   ->	List[Any]:
											with self.assertRaises(A__						):
																	snake_case_ :str						=			pa.array(TypedSequence([1, 2, 3]						)						,     type=pa.intaa()						)






					def    lowerCAmelCase_				(       self:							int						)   ->	Tuple:
											with self.assertRaises(A__						):
																	snake_case_ :List[str]						=			pa.array(TypedSequence([1, 2, 3]						,     try_type=Value("""bool"""						)						,     type=Value("""int64"""						)						)						)






					def    lowerCAmelCase_				(       self:							List[Any]						)   ->	Any:
											snake_case_ :Any						=			pa.array(TypedSequence([1, 2, 3]						,     type=Value("""int32"""						)						)						)
											self.assertEqual(arr.type						,     pa.intaa()						)






					def    lowerCAmelCase_				(       self:							Optional[int]						)   ->	List[str]:
											with self.assertRaises((TypeError, pa.lib.ArrowInvalid)						):
																	snake_case_ :Any						=			pa.array(TypedSequence(["""foo""", """bar"""]						,     type=Value("""int64"""						)						)						)






					def    lowerCAmelCase_				(       self:							Tuple						)   ->	Optional[int]:
											snake_case_ :int						=			pa.array(TypedSequence([1, 2, 3]						,     try_type=Value("""int32"""						)						)						)
											self.assertEqual(arr.type						,     pa.intaa()						)






					def    lowerCAmelCase_				(       self:							int						)   ->	Tuple:
											snake_case_ :int						=			pa.array(TypedSequence(["""foo""", """bar"""]						,     try_type=Value("""int64"""						)						)						)
											self.assertEqual(arr.type						,     pa.string()						)






					def    lowerCAmelCase_				(       self:							Dict						)   ->	List[str]:
											snake_case_ :Tuple						=			pa.array(TypedSequence([[[1, 2, 3]]]						,     type=ArrayaD((1, 3)						,     """int64"""						)						)						)
											self.assertEqual(arr.type						,     ArrayaDExtensionType((1, 3)						,     """int64"""						)						)






					def    lowerCAmelCase_				(       self:							str						)   ->	List[Any]:
											with self.assertRaises((TypeError, pa.lib.ArrowInvalid)						):
																	snake_case_ :Dict						=			pa.array(TypedSequence(["""foo""", """bar"""]						,     type=ArrayaD((1, 3)						,     """int64"""						)						)						)






					def    lowerCAmelCase_				(       self:							str						)   ->	Optional[Any]:
											snake_case_ :Optional[int]						=			pa.array(TypedSequence([[[1, 2, 3]]]						,     try_type=ArrayaD((1, 3)						,     """int64"""						)						)						)
											self.assertEqual(arr.type						,     ArrayaDExtensionType((1, 3)						,     """int64"""						)						)






					def    lowerCAmelCase_				(       self:							Dict						)   ->	Optional[Any]:
											snake_case_ :List[Any]						=			pa.array(TypedSequence(["""foo""", """bar"""]						,     try_type=ArrayaD((1, 3)						,     """int64"""						)						)						)
											self.assertEqual(arr.type						,     pa.string()						)






					@require_pil
					def    lowerCAmelCase_				(       self:							List[Any]						)   ->	int:
											import PIL.Image

											snake_case_ :Dict						=			PIL.Image.fromarray(np.arange(10						,     dtype=np.uinta						).reshape(2						,     5						)						)
											with patch(
											    """datasets.arrow_writer.cast_to_python_objects"""						,     side_effect=A__						) as mock_cast_to_python_objects:
																	snake_case_ :Optional[int]						=			pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image]						,     type=Image()						)						)
																	snake_case_ :Any						=			mock_cast_to_python_objects.call_args_list[-1]
																	self.assertIn("""optimize_list_casting"""						,     A__						)
																	self.assertFalse(kwargs["""optimize_list_casting"""]						)

def    A_  (			_lowercase,					_lowercase	):







						'''simple docstring'''


						snake_case_ :str						=			pa.BufferReader(lowercase_	) if isinstance(lowercase_,					pa.Buffer	) else pa.memory_map(lowercase_	)
						snake_case_ :Any						=			pa.ipc.open_stream(lowercase_	)
						snake_case_ :pa.Table						=			f.read_all()
						assert len(pa_table.to_batches()	) == expected_num_chunks
						assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
						del pa_table
@pytest.mark.parametrize("""writer_batch_size""",					[None, 1, 10]	)
@pytest.mark.parametrize(
    """fields""",					[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]	)
def    A_  (			_lowercase,					_lowercase	):







						'''simple docstring'''


						snake_case_ :List[Any]						=			pa.BufferOutputStream()
						snake_case_ :Dict						=			pa.schema(lowercase_	) if fields else None
						with ArrowWriter(stream=lowercase_,					schema=lowercase_,					writer_batch_size=lowercase_	) as writer:
												writer.write({"""col_1""": """foo""", """col_2""": 1}	)
												writer.write({"""col_1""": """bar""", """col_2""": 2}	)
												snake_case_ :List[Any]						=			writer.finalize()
						assert num_examples == 2
						assert num_bytes > 0
						if not fields:
												snake_case_ :Any						=			{"""col_1""": pa.string(), """col_2""": pa.intaa()}
						assert writer._schema == pa.schema(lowercase_,					metadata=writer._schema.metadata	)
						_check_output(output.getvalue(),					expected_num_chunks=num_examples if writer_batch_size == 1 else 1	)
def    A_  (			):







						'''simple docstring'''


						snake_case_ :List[Any]						=			pa.BufferOutputStream()
						snake_case_ :Optional[int]						=			Features({"""labels""": ClassLabel(names=["""neg""", """pos"""]	)}	)
						with ArrowWriter(stream=lowercase_,					features=lowercase_	) as writer:
												writer.write({"""labels""": 0}	)
												writer.write({"""labels""": 1}	)
												snake_case_ :int						=			writer.finalize()
						assert num_examples == 2
						assert num_bytes > 0
						assert writer._schema == features.arrow_schema
						assert writer._schema.metadata == features.arrow_schema.metadata
						snake_case_ :Any						=			pa.BufferReader(output.getvalue()	)
						snake_case_ :int						=			pa.ipc.open_stream(lowercase_	)
						snake_case_ :pa.Table						=			f.read_all()
						snake_case_ :List[Any]						=			pa_table.schema
						assert pa_table.num_rows == 2
						assert schema == features.arrow_schema
						assert schema.metadata == features.arrow_schema.metadata
						assert features == Features.from_arrow_schema(lowercase_	)
@pytest.mark.parametrize("""writer_batch_size""",					[None, 1, 10]	)
def    A_  (			_lowercase	):







						'''simple docstring'''


						snake_case_ :Optional[int]						=			pa.BufferOutputStream()
						with ArrowWriter(
						    stream=lowercase_,					writer_batch_size=lowercase_,					hash_salt="""split_name""",					check_duplicates=lowercase_,					) as writer:
												with pytest.raises(lowercase_	):
																		writer.write({"""col_1""": """foo""", """col_2""": 1},					key=[1, 2]	)
																		snake_case_ :int						=			writer.finalize()
@pytest.mark.parametrize("""writer_batch_size""",					[None, 2, 10]	)
def    A_  (			_lowercase	):







						'''simple docstring'''


						snake_case_ :Dict						=			pa.BufferOutputStream()
						with ArrowWriter(
						    stream=lowercase_,					writer_batch_size=lowercase_,					hash_salt="""split_name""",					check_duplicates=lowercase_,					) as writer:
												with pytest.raises(lowercase_	):
																		writer.write({"""col_1""": """foo""", """col_2""": 1},					key=10	)
																		writer.write({"""col_1""": """bar""", """col_2""": 2},					key=10	)
																		snake_case_ :Any						=			writer.finalize()
@pytest.mark.parametrize("""writer_batch_size""",					[None, 2, 10]	)
def    A_  (			_lowercase	):







						'''simple docstring'''


						snake_case_ :Any						=			pa.BufferOutputStream()
						with ArrowWriter(
						    stream=lowercase_,					writer_batch_size=lowercase_,					hash_salt="""split_name""",					check_duplicates=lowercase_,					) as writer:
												writer.write({"""col_1""": """foo""", """col_2""": 1},					key=1	)
												writer.write({"""col_1""": """bar""", """col_2""": 2},					key=2	)
												snake_case_ :Optional[int]						=			writer.finalize()
						assert num_examples == 2
						assert num_bytes > 0
						_check_output(output.getvalue(),					expected_num_chunks=num_examples if writer_batch_size == 1 else 1	)
@pytest.mark.parametrize("""writer_batch_size""",					[None, 1, 10]	)
@pytest.mark.parametrize(
    """fields""",					[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]	)
def    A_  (			_lowercase,					_lowercase	):







						'''simple docstring'''


						snake_case_ :str						=			pa.BufferOutputStream()
						snake_case_ :Dict						=			pa.schema(lowercase_	) if fields else None
						with ArrowWriter(stream=lowercase_,					schema=lowercase_,					writer_batch_size=lowercase_	) as writer:
												writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]}	)
												writer.write_batch({"""col_1""": [], """col_2""": []}	)
												snake_case_ :Optional[int]						=			writer.finalize()
						assert num_examples == 2
						assert num_bytes > 0
						if not fields:
												snake_case_ :str						=			{"""col_1""": pa.string(), """col_2""": pa.intaa()}
						assert writer._schema == pa.schema(lowercase_,					metadata=writer._schema.metadata	)
						_check_output(output.getvalue(),					expected_num_chunks=num_examples if writer_batch_size == 1 else 1	)
@pytest.mark.parametrize("""writer_batch_size""",					[None, 1, 10]	)
@pytest.mark.parametrize(
    """fields""",					[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]	)
def    A_  (			_lowercase,					_lowercase	):







						'''simple docstring'''


						snake_case_ :Dict						=			pa.BufferOutputStream()
						snake_case_ :Optional[Any]						=			pa.schema(lowercase_	) if fields else None
						with ArrowWriter(stream=lowercase_,					schema=lowercase_,					writer_batch_size=lowercase_	) as writer:
												writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]}	)	)
												snake_case_ :Optional[Any]						=			writer.finalize()
						assert num_examples == 2
						assert num_bytes > 0
						if not fields:
												snake_case_ :Optional[Any]						=			{"""col_1""": pa.string(), """col_2""": pa.intaa()}
						assert writer._schema == pa.schema(lowercase_,					metadata=writer._schema.metadata	)
						_check_output(output.getvalue(),					expected_num_chunks=num_examples if writer_batch_size == 1 else 1	)
@pytest.mark.parametrize("""writer_batch_size""",					[None, 1, 10]	)
@pytest.mark.parametrize(
    """fields""",					[None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]	)
def    A_  (			_lowercase,					_lowercase	):







						'''simple docstring'''


						snake_case_ :int						=			pa.BufferOutputStream()
						snake_case_ :int						=			pa.schema(lowercase_	) if fields else None
						with ArrowWriter(stream=lowercase_,					schema=lowercase_,					writer_batch_size=lowercase_	) as writer:
												writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]}	)	)
												writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]}	)	)
												snake_case_ :List[str]						=			writer.finalize()
						assert num_examples == 2
						assert num_bytes > 0
						if not fields:
												snake_case_ :Tuple						=			{"""col_1""": pa.string(), """col_2""": pa.intaa()}
						assert writer._schema == pa.schema(lowercase_,					metadata=writer._schema.metadata	)
						_check_output(output.getvalue(),					expected_num_chunks=num_examples if writer_batch_size == 1 else 1	)
def    A_  (			):







						'''simple docstring'''


						with tempfile.TemporaryDirectory() as tmp_dir:
												snake_case_ :List[str]						=			{"""col_1""": pa.string(), """col_2""": pa.intaa()}
												snake_case_ :int						=			os.path.join(lowercase_,					"""test.arrow"""	)
												with ArrowWriter(path=lowercase_,					schema=pa.schema(lowercase_	)	) as writer:
																		writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]}	)
																		snake_case_ :Any						=			writer.finalize()
												assert num_examples == 2
												assert num_bytes > 0
												assert writer._schema == pa.schema(lowercase_,					metadata=writer._schema.metadata	)
												_check_output(lowercase_,					1	)
def    A_  (			_lowercase	):







						'''simple docstring'''


						if pa.types.is_list(lowercase_	):
												return get_base_dtype(arr_type.value_type	)
						else:
												return arr_type
def    A_  (			_lowercase,					_lowercase	):







						'''simple docstring'''


						if isinstance(lst[0],					lowercase_	):
												change_first_primitive_element_in_list(lst[0],					lowercase_	)
						else:
												snake_case_ :Optional[int]						=			value
@pytest.mark.parametrize("""optimized_int_type, expected_dtype""",					[(None, pa.intaa()), (Value("""int32"""	), pa.intaa())]	)
@pytest.mark.parametrize("""sequence""",					[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]	)
def    A_  (			_lowercase,					_lowercase,					_lowercase	):







						'''simple docstring'''


						snake_case_ :Optional[int]						=			pa.array(TypedSequence(lowercase_,					optimized_int_type=lowercase_	)	)
						assert get_base_dtype(arr.type	) == expected_dtype
@pytest.mark.parametrize(
    """col, expected_dtype""",					[
        ("""attention_mask""", pa.inta()),
        ("""special_tokens_mask""", pa.inta()),
        ("""token_type_ids""", pa.inta()),
        ("""input_ids""", pa.intaa()),
        ("""other""", pa.intaa()),
    ],					)
@pytest.mark.parametrize("""sequence""",					[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]	)
def    A_  (			_lowercase,					_lowercase,					_lowercase	):







						'''simple docstring'''


						snake_case_ :str						=			pa.array(OptimizedTypedSequence(lowercase_,					col=lowercase_	)	)
						assert get_base_dtype(arr.type	) == expected_dtype

						# not in range
						if col != "other":
												# avoids errors due to in-place modifications
												snake_case_ :Optional[int]						=			copy.deepcopy(lowercase_	)
												snake_case_ :Any						=			np.iinfo(expected_dtype.to_pandas_dtype()	).max + 1
												change_first_primitive_element_in_list(lowercase_,					lowercase_	)
												snake_case_ :Optional[Any]						=			pa.array(OptimizedTypedSequence(lowercase_,					col=lowercase_	)	)
												assert get_base_dtype(arr.type	) == pa.intaa()
@pytest.mark.parametrize("""raise_exception""",					[False, True]	)
def    A_  (			_lowercase,					_lowercase	):







						'''simple docstring'''


						snake_case_ :List[str]						=			str(tmp_path / """dataset-train.arrow"""	)
						try:
												with ArrowWriter(path=lowercase_	) as writer:
																		if raise_exception:
																								raise pa.lib.ArrowInvalid()
																		else:
																								writer.stream.close()
						except pa.lib.ArrowInvalid:
												pass
						finally:
												assert writer.stream.closed
def    A_  (			_lowercase	):







						'''simple docstring'''


						snake_case_ :Tuple						=			"""mock://dataset-train.arrow"""
						with ArrowWriter(path=lowercase_,					storage_options=mockfs.storage_options	) as writer:
												assert isinstance(writer._fs,					type(lowercase_	)	)
												assert writer._fs.storage_options == mockfs.storage_options
												writer.write({"""col_1""": """foo""", """col_2""": 1}	)
												writer.write({"""col_1""": """bar""", """col_2""": 2}	)
												snake_case_ :Optional[int]						=			writer.finalize()
						assert num_examples == 2
						assert num_bytes > 0
						assert mockfs.exists(lowercase_	)
def    A_  (			):







						'''simple docstring'''


						snake_case_ :List[str]						=			pa.BufferOutputStream()
						with ParquetWriter(stream=lowercase_	) as writer:
												writer.write({"""col_1""": """foo""", """col_2""": 1}	)
												writer.write({"""col_1""": """bar""", """col_2""": 2}	)
												snake_case_ :Any						=			writer.finalize()
						assert num_examples == 2
						assert num_bytes > 0
						snake_case_ :int						=			pa.BufferReader(output.getvalue()	)
						snake_case_ :pa.Table						=			pq.read_table(lowercase_	)
						assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
@require_pil
@pytest.mark.parametrize("""embed_local_files""",					[False, True]	)
def    A_  (			_lowercase,					_lowercase	):







						'''simple docstring'''


						import PIL.Image

						snake_case_ :List[Any]						=			str(tmp_path / """test_image_rgb.jpg"""	)
						PIL.Image.fromarray(np.zeros((5, 5),					dtype=np.uinta	)	).save(lowercase_,					format="""png"""	)
						snake_case_ :List[str]						=			pa.BufferOutputStream()
						with ParquetWriter(
						    stream=lowercase_,					features=Features({"""image""": Image()}	),					embed_local_files=lowercase_	) as writer:
												writer.write({"""image""": image_path}	)
												writer.finalize()
						snake_case_ :Tuple						=			pa.BufferReader(output.getvalue()	)
						snake_case_ :pa.Table						=			pq.read_table(lowercase_	)
						snake_case_ :Optional[int]						=			pa_table.to_pydict()
						if embed_local_files:
												assert isinstance(out["""image"""][0]["""path"""],					lowercase_	)
												with open(lowercase_,					"""rb"""	) as f:
																		assert out["image"][0]["bytes"] == f.read()
						else:
												assert out["image"][0]["path"] == image_path
												assert out["image"][0]["bytes"] is None

def    A_  (			):







						'''simple docstring'''


						snake_case_ :Optional[Any]						=			pa.schema([pa.field("""col_1""",					pa.string(),					nullable=lowercase_	)]	)
						snake_case_ :Union[str, Any]						=			pa.BufferOutputStream()
						with ArrowWriter(stream=lowercase_	) as writer:
												writer._build_writer(inferred_schema=lowercase_	)
												assert writer._schema == pa.schema([pa.field("""col_1""",					pa.string()	)]	)



import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pytest

from datasets.arrow_dataset import Dataset
from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex

from .utils import require_elasticsearch, require_faiss


A_       : Any         =			pytest.mark.integration



@require_faiss
class     _a						(__magic_name__				):


					'''simple docstring'''






					def   __A			( self			):
						A__							:    Tuple        =		Dataset.from_dict({"""filename""": ["""my_name-train""" + """_""" + str(A__			) for x in np.arange(30			).tolist()]}			)
						return dset






					def   __A			( self			):
						import faiss

						A__							:    Dataset        =		self._create_dummy_dataset()
						A__							:    Union[str, Any]        =		dset.map(
						    lambda A__    ,       A__			: {"vecs": i * np.ones(5    ,       dtype=np.floataa			)}    ,       with_indices=A__    ,       keep_in_memory=A__			)
						A__							:    int        =		dset.add_faiss_index("""vecs"""    ,       batch_size=100    ,       metric_type=faiss.METRIC_INNER_PRODUCT			)
						A__   ,   A__							:    Optional[Any]        =		dset.get_nearest_examples("""vecs"""    ,       np.ones(5    ,       dtype=np.floataa			)			)
						self.assertEqual(examples["""filename"""][0]    ,       """my_name-train_29"""			)
						dset.drop_index("""vecs"""			)






					def   __A			( self			):
						import faiss

						A__							:    Dataset        =		self._create_dummy_dataset()
						dset.add_faiss_index_from_external_arrays(
						    external_arrays=np.ones((30, 5)			) * np.arange(30			).reshape(-1    ,       1			)    ,       index_name="""vecs"""    ,       batch_size=100    ,       metric_type=faiss.METRIC_INNER_PRODUCT    ,       )
						A__   ,   A__							:    str        =		dset.get_nearest_examples("""vecs"""    ,       np.ones(5    ,       dtype=np.floataa			)			)
						self.assertEqual(examples["""filename"""][0]    ,       """my_name-train_29"""			)






					def   __A			( self			):
						import faiss

						A__							:    Dataset        =		self._create_dummy_dataset()
						dset.add_faiss_index_from_external_arrays(
						    external_arrays=np.ones((30, 5)			) * np.arange(30			).reshape(-1    ,       1			)    ,       index_name="""vecs"""    ,       metric_type=faiss.METRIC_INNER_PRODUCT    ,       )

						# Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
						# ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
						# see https://bugs.python.org/issue14243 and
						# https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
						with tempfile.NamedTemporaryFile(delete=A__			) as tmp_file:
							dset.save_faiss_index("""vecs"""    ,       tmp_file.name			)
							dset.load_faiss_index("""vecs2"""    ,       tmp_file.name			)
						os.unlink(tmp_file.name			)

						A__   ,   A__							:    Tuple        =		dset.get_nearest_examples("""vecs2"""    ,       np.ones(5    ,       dtype=np.floataa			)			)
						self.assertEqual(examples["""filename"""][0]    ,       """my_name-train_29"""			)






					def   __A			( self			):
						A__							:    Dataset        =		self._create_dummy_dataset()
						dset.add_faiss_index_from_external_arrays(
						    external_arrays=np.ones((30, 5)			) * np.arange(30			).reshape(-1    ,       1			)    ,       index_name="""vecs"""			)
						dset.drop_index("""vecs"""			)
						self.assertRaises(A__    ,       partial(dset.get_nearest_examples    ,       """vecs2"""    ,       np.ones(5    ,       dtype=np.floataa			)			)			)






					def   __A			( self			):
						from elasticsearch import Elasticsearch

						A__							:    Dataset        =		self._create_dummy_dataset()
						with patch("""elasticsearch.Elasticsearch.search"""			) as mocked_search, patch(
						    """elasticsearch.client.IndicesClient.create"""			) as mocked_index_create, patch("""elasticsearch.helpers.streaming_bulk"""			) as mocked_bulk:
							A__							:    List[Any]        =		{"""acknowledged""": True}
							mocked_bulk.return_value([(True, None)] * 30			)
							A__							:    List[Any]        =		{"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 29}]}}
							A__							:    Any        =		Elasticsearch()

							dset.add_elasticsearch_index("""filename"""    ,       es_client=A__			)
							A__   ,   A__							:    Any        =		dset.get_nearest_examples("""filename"""    ,       """my_name-train_29"""			)
							self.assertEqual(examples["""filename"""][0]    ,       """my_name-train_29"""			)



@require_faiss
class     _a						(__magic_name__				):


					'''simple docstring'''






					def   __A			( self			):
						import faiss

						A__							:    Optional[int]        =		FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT			)

						# add vectors
						index.add_vectors(np.eye(5    ,       dtype=np.floataa			)			)
						self.assertIsNotNone(index.faiss_index			)
						self.assertEqual(index.faiss_index.ntotal    ,       5			)
						index.add_vectors(np.zeros((5, 5)    ,       dtype=np.floataa			)			)
						self.assertEqual(index.faiss_index.ntotal    ,       10			)

						# single query
						A__							:    Any        =		np.zeros(5    ,       dtype=np.floataa			)
						A__							:    str        =		1
						A__   ,   A__							:    Optional[Any]        =		index.search(A__			)
						self.assertRaises(A__    ,       index.search    ,       query.reshape(-1    ,       1			)			)
						self.assertGreater(scores[0]    ,       0			)
						self.assertEqual(indices[0]    ,       1			)

						# batched queries
						A__							:    Optional[int]        =		np.eye(5    ,       dtype=np.floataa			)[::-1]
						A__   ,   A__							:    str        =		index.search_batch(A__			)
						self.assertRaises(A__    ,       index.search_batch    ,       queries[0]			)
						A__							:    str        =		[scores[0] for scores in total_scores]
						A__							:    Tuple        =		[indices[0] for indices in total_indices]
						self.assertGreater(np.min(A__			)    ,       0			)
						self.assertListEqual([4, 3, 2, 1, 0]    ,       A__			)






					def   __A			( self			):
						import faiss

						A__							:    Dict        =		FaissIndex(string_factory="""Flat"""			)
						index.add_vectors(np.eye(5    ,       dtype=np.floataa			)			)
						self.assertIsInstance(index.faiss_index    ,       faiss.IndexFlat			)
						A__							:    Dict        =		FaissIndex(string_factory="""LSH"""			)
						index.add_vectors(np.eye(5    ,       dtype=np.floataa			)			)
						self.assertIsInstance(index.faiss_index    ,       faiss.IndexLSH			)
						with self.assertRaises(A__			):
							A__							:    List[Any]        =		FaissIndex(string_factory="""Flat"""    ,       custom_index=faiss.IndexFlat(5			)			)






					def   __A			( self			):
						import faiss

						A__							:    List[Any]        =		faiss.IndexFlat(5			)
						A__							:    Union[str, Any]        =		FaissIndex(custom_index=A__			)
						index.add_vectors(np.eye(5    ,       dtype=np.floataa			)			)
						self.assertIsInstance(index.faiss_index    ,       faiss.IndexFlat			)






					def   __A			( self			):
						import faiss

						A__							:    Any        =		FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT			)
						index.add_vectors(np.eye(5    ,       dtype=np.floataa			)			)

						# Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
						# ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
						# see https://bugs.python.org/issue14243 and
						# https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
						with tempfile.NamedTemporaryFile(delete=A__			) as tmp_file:
							index.save(tmp_file.name			)
							A__							:    int        =		FaissIndex.load(tmp_file.name			)
						os.unlink(tmp_file.name			)

						A__							:    Optional[Any]        =		np.zeros(5    ,       dtype=np.floataa			)
						A__							:    Optional[int]        =		1
						A__   ,   A__							:    List[Any]        =		index.search(A__			)
						self.assertGreater(scores[0]    ,       0			)
						self.assertEqual(indices[0]    ,       1			)



@require_faiss
def 						UpperCamelCase					(lowercase_: Dict					)     ->      Optional[Any]:
	import faiss

	A__							:    Dict        =		FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT					)
	index.add_vectors(np.eye(5    ,      dtype=np.floataa					)					)

	A__							:    Optional[Any]        =		"""index.faiss"""
	A__							:    Any        =		f"""mock://{index_name}"""
	index.save(lowercase_    ,      storage_options=mockfs.storage_options					)
	A__							:    str        =		FaissIndex.load(lowercase_    ,      storage_options=mockfs.storage_options					)

	A__							:    int        =		np.zeros(5    ,      dtype=np.floataa					)
	A__							:    Union[str, Any]        =		1
	A__   ,   A__							:    Any        =		index.search(lowercase_					)
	assert scores[0] > 0
	assert indices[0] == 1



@require_elasticsearch
class     _a						(__magic_name__				):


					'''simple docstring'''






					def   __A			( self			):
						from elasticsearch import Elasticsearch

						with patch("""elasticsearch.Elasticsearch.search"""			) as mocked_search, patch(
						    """elasticsearch.client.IndicesClient.create"""			) as mocked_index_create, patch("""elasticsearch.helpers.streaming_bulk"""			) as mocked_bulk:
							A__							:    List[str]        =		Elasticsearch()
							A__							:    List[Any]        =		{"""acknowledged""": True}
							A__							:    int        =		ElasticSearchIndex(es_client=A__			)
							mocked_bulk.return_value([(True, None)] * 3			)
							index.add_documents(["""foo""", """bar""", """foobar"""]			)

							# single query
							A__							:    Dict        =		"""foo"""
							A__							:    Tuple        =		{"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 0}]}}
							A__   ,   A__							:    Tuple        =		index.search(A__			)
							self.assertEqual(scores[0]    ,       1			)
							self.assertEqual(indices[0]    ,       0			)

							# single query with timeout
							A__							:    List[str]        =		"""foo"""
							A__							:    str        =		{"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 0}]}}
							A__   ,   A__							:    Dict        =		index.search(A__    ,       request_timeout=30			)
							self.assertEqual(scores[0]    ,       1			)
							self.assertEqual(indices[0]    ,       0			)

							# batched queries
							A__							:    Union[str, Any]        =		["""foo""", """bar""", """foobar"""]
							A__							:    Tuple        =		{"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}}
							A__   ,   A__							:    Dict        =		index.search_batch(A__			)
							A__							:    Tuple        =		[scores[0] for scores in total_scores]
							A__							:    Optional[int]        =		[indices[0] for indices in total_indices]
							self.assertGreater(np.min(A__			)    ,       0			)
							self.assertListEqual([1, 1, 1]    ,       A__			)

							# batched queries with timeout
							A__							:    int        =		["""foo""", """bar""", """foobar"""]
							A__							:    List[Any]        =		{"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}}
							A__   ,   A__							:    Tuple        =		index.search_batch(A__    ,       request_timeout=30			)
							A__							:    List[Any]        =		[scores[0] for scores in total_scores]
							A__							:    Optional[int]        =		[indices[0] for indices in total_indices]
							self.assertGreater(np.min(A__			)    ,       0			)
							self.assertListEqual([1, 1, 1]    ,       A__			)



