


"""simple docstring"""





from unittest.mock import patch

import pyspark

from datasets.packaged_modules.spark.spark import (
    Spark,
    SparkExamplesIterable,
    _generate_iterable_examples,
)

from ..utils import (
    require_dill_gt_0_3_2,
    require_not_windows,
)


def    _snake_case  (  _snake_case :	Optional[Any]       ,      _snake_case :	Any	):
      lowerCAmelCase    :		List[str]				=      []
      for part_id in partition_order:
            lowerCAmelCase    :		Optional[int]				=      df.where(f'''SPARK_PARTITION_ID() = {part_id}'''	).collect()
            for row_idx, row in enumerate(_snake_case	):
                  expected_row_ids_and_row_dicts.append((f'''{part_id}_{row_idx}''', row.asDict())	)
      return expected_row_ids_and_row_dicts


@require_not_windows
@require_dill_gt_0_3_2
def    _snake_case  (  ):
      lowerCAmelCase    :		int				=      pyspark.sql.SparkSession.builder.master('''local[*]'''	).appName('''pyspark'''	).getOrCreate()
      lowerCAmelCase    :		Dict				=      spark.range(100	).repartition(1	)
      lowerCAmelCase    :		List[Any]				=      Spark(_snake_case	)
      # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means
      # that each partition can hold 2 rows.
      spark_builder._repartition_df_if_needed(max_shard_size=16	)
      # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions.
      assert spark_builder.df.rdd.getNumPartitions() == 50


@require_not_windows
@require_dill_gt_0_3_2
def    _snake_case  (  ):
      lowerCAmelCase    :		List[Any]				=      pyspark.sql.SparkSession.builder.master('''local[*]'''	).appName('''pyspark'''	).getOrCreate()
      lowerCAmelCase    :		List[str]				=      spark.range(10	).repartition(2	)
      lowerCAmelCase    :		List[Any]				=      [1, 0]
      lowerCAmelCase    :		Union[str, Any]				=      _generate_iterable_examples(_snake_case       ,      _snake_case	)  # Reverse the partitions.
      lowerCAmelCase    :		Dict				=      _get_expected_row_ids_and_row_dicts_for_partition_order(_snake_case       ,      _snake_case	)

      for i, (row_id, row_dict) in enumerate(generate_fn()	):
            lowerCAmelCase,					lowerCAmelCase    :		Any				=      expected_row_ids_and_row_dicts[i]
            assert row_id == expected_row_id
            assert row_dict == expected_row_dict


@require_not_windows
@require_dill_gt_0_3_2
def    _snake_case  (  ):
      lowerCAmelCase    :		int				=      pyspark.sql.SparkSession.builder.master('''local[*]'''	).appName('''pyspark'''	).getOrCreate()
      lowerCAmelCase    :		Any				=      spark.range(10	).repartition(1	)
      lowerCAmelCase    :		Optional[int]				=      SparkExamplesIterable(_snake_case	)
      assert it.n_shards == 1
      for i, (row_id, row_dict) in enumerate(_snake_case	):
            assert row_id == f'''0_{i}'''
            assert row_dict == {"id": i}


@require_not_windows
@require_dill_gt_0_3_2
def    _snake_case  (  ):
      lowerCAmelCase    :		Union[str, Any]				=      pyspark.sql.SparkSession.builder.master('''local[*]'''	).appName('''pyspark'''	).getOrCreate()
      lowerCAmelCase    :		Union[str, Any]				=      spark.range(30	).repartition(3	)
      # Mock the generator so that shuffle reverses the partition indices.
      with patch('''numpy.random.Generator'''	) as generator_mock:
            lowerCAmelCase    :		List[Any]				=      lambda _snake_case	: x.reverse()
            lowerCAmelCase    :		Union[str, Any]				=      _get_expected_row_ids_and_row_dicts_for_partition_order(_snake_case       ,      [2, 1, 0]	)

            lowerCAmelCase    :		Optional[Any]				=      SparkExamplesIterable(_snake_case	).shuffle_data_sources(_snake_case	)
            assert shuffled_it.n_shards == 3
            for i, (row_id, row_dict) in enumerate(_snake_case	):
                  lowerCAmelCase,					lowerCAmelCase    :		List[str]				=      expected_row_ids_and_row_dicts[i]
                  assert row_id == expected_row_id
                  assert row_dict == expected_row_dict


@require_not_windows
@require_dill_gt_0_3_2
def    _snake_case  (  ):
      lowerCAmelCase    :		Dict				=      pyspark.sql.SparkSession.builder.master('''local[*]'''	).appName('''pyspark'''	).getOrCreate()
      lowerCAmelCase    :		int				=      spark.range(20	).repartition(4	)

      # Partitions 0 and 2
      lowerCAmelCase    :		List[str]				=      SparkExamplesIterable(_snake_case	).shard_data_sources(worker_id=0       ,      num_workers=2	)
      assert shard_it_a.n_shards == 2
      lowerCAmelCase    :		List[str]				=      _get_expected_row_ids_and_row_dicts_for_partition_order(_snake_case       ,      [0, 2]	)
      for i, (row_id, row_dict) in enumerate(_snake_case	):
            lowerCAmelCase,					lowerCAmelCase    :		Optional[int]				=      expected_row_ids_and_row_dicts_a[i]
            assert row_id == expected_row_id
            assert row_dict == expected_row_dict

      # Partitions 1 and 3
      lowerCAmelCase    :		Tuple				=      SparkExamplesIterable(_snake_case	).shard_data_sources(worker_id=1       ,      num_workers=2	)
      assert shard_it_a.n_shards == 2
      lowerCAmelCase    :		Any				=      _get_expected_row_ids_and_row_dicts_for_partition_order(_snake_case       ,      [1, 3]	)
      for i, (row_id, row_dict) in enumerate(_snake_case	):
            lowerCAmelCase,					lowerCAmelCase    :		Dict				=      expected_row_ids_and_row_dicts_a[i]
            assert row_id == expected_row_id
            assert row_dict == expected_row_dict






@require_not_windows
@require_dill_gt_0_3_2
def    _snake_case  (  ):
      lowerCAmelCase    :		int				=      pyspark.sql.SparkSession.builder.master('''local[*]'''	).appName('''pyspark'''	).getOrCreate()
      lowerCAmelCase    :		List[Any]				=      spark.range(100	).repartition(1	)
      lowerCAmelCase    :		List[str]				=      Spark(_snake_case	)
      # Choose a small max_shard_size for maximum partitioning.
      spark_builder._repartition_df_if_needed(max_shard_size=1	)
      # The new number of partitions should not be greater than the number of rows.
      assert spark_builder.df.rdd.getNumPartitions() == 100









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


_UpperCAmelCase				:       str	   =				pytest.mark.integration

@require_faiss
class    lowerCAmelCase							(					__UpperCamelCase			):
 def      A_	(      self  :      List[Any]	)			->	Union[str, Any]:
     lowerCamelCase__    :      List[Any]					 =		Dataset.from_dict({'filename': ['my_name-train' + '_' + str(UpperCAmelCase	) for x in np.arange(30	).tolist()]}	)
     return dset
 def      A_	(      self  :      Optional[Any]	)			->	Optional[int]:
     import faiss

     lowerCamelCase__    :      Dataset					 =		self._create_dummy_dataset()
     lowerCamelCase__    :      List[Any]					 =		dset.map(
         lambda UpperCAmelCase			,     UpperCAmelCase	: {"vecs": i * np.ones(5			,     dtype=np.floataa	)}			,     with_indices=UpperCAmelCase			,     keep_in_memory=UpperCAmelCase	)
     lowerCamelCase__    :      Tuple					 =		dset.add_faiss_index('vecs'			,     batch_size=100			,     metric_type=faiss.METRIC_INNER_PRODUCT	)
     lowerCamelCase__ ,							lowerCamelCase__    :      str					 =		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  :      Union[str, Any]	)			->	int:
     import faiss

     lowerCamelCase__    :      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			,     )
     lowerCamelCase__ ,							lowerCamelCase__    :      Optional[Any]					 =		dset.get_nearest_examples('vecs'			,     np.ones(5			,     dtype=np.floataa	)	)
     self.assertEqual(examples['filename'][0]			,     'my_name-train_29'	)
 def      A_	(      self  :      List[str]	)			->	Tuple:
     import faiss

     lowerCamelCase__    :      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=UpperCAmelCase	) as tmp_file:
         dset.save_faiss_index('vecs'			,     tmp_file.name	)
         dset.load_faiss_index('vecs2'			,     tmp_file.name	)
     os.unlink(tmp_file.name	)

     lowerCamelCase__ ,							lowerCamelCase__    :      str					 =		dset.get_nearest_examples('vecs2'			,     np.ones(5			,     dtype=np.floataa	)	)
     self.assertEqual(examples['filename'][0]			,     'my_name-train_29'	)
 def      A_	(      self  :      Any	)			->	Optional[Any]:
     lowerCamelCase__    :      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(UpperCAmelCase			,     partial(dset.get_nearest_examples			,     'vecs2'			,     np.ones(5			,     dtype=np.floataa	)	)	)







 def      A_	(      self  :      Dict	)			->	Dict:
     from elasticsearch import Elasticsearch

     lowerCamelCase__    :      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:
         lowerCamelCase__    :      List[Any]					 =		{'acknowledged': True}
         mocked_bulk.return_value([(True, None)] * 30	)
         lowerCamelCase__    :      int					 =		{'hits': {'hits': [{'_score': 1, '_id': 29}]}}
         lowerCamelCase__    :      List[str]					 =		Elasticsearch()

         dset.add_elasticsearch_index('filename'			,     es_client=UpperCAmelCase	)
         lowerCamelCase__ ,							lowerCamelCase__    :      Dict					 =		dset.get_nearest_examples('filename'			,     'my_name-train_29'	)
         self.assertEqual(examples['filename'][0]			,     'my_name-train_29'	)


@require_faiss
class    lowerCAmelCase							(					__UpperCamelCase			):
 def      A_	(      self  :      Any	)			->	Dict:
     import faiss

     lowerCamelCase__    :      Tuple					 =		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
     lowerCamelCase__    :      int					 =		np.zeros(5			,     dtype=np.floataa	)
     lowerCamelCase__    :      Any					 =		1
     lowerCamelCase__ ,							lowerCamelCase__    :      Union[str, Any]					 =		index.search(UpperCAmelCase	)
     self.assertRaises(UpperCAmelCase			,     index.search			,     query.reshape(-1			,     1	)	)
     self.assertGreater(scores[0]			,     0	)
     self.assertEqual(indices[0]			,     1	)

     # batched queries
     lowerCamelCase__    :      str					 =		np.eye(5			,     dtype=np.floataa	)[::-1]
     lowerCamelCase__ ,							lowerCamelCase__    :      Dict					 =		index.search_batch(UpperCAmelCase	)
     self.assertRaises(UpperCAmelCase			,     index.search_batch			,     queries[0]	)
     lowerCamelCase__    :      str					 =		[scores[0] for scores in total_scores]
     lowerCamelCase__    :      List[str]					 =		[indices[0] for indices in total_indices]
     self.assertGreater(np.min(UpperCAmelCase	)			,     0	)
     self.assertListEqual([4, 3, 2, 1, 0]			,     UpperCAmelCase	)
 def      A_	(      self  :      List[Any]	)			->	List[Any]:
     import faiss

     lowerCamelCase__    :      Any					 =		FaissIndex(string_factory='Flat'	)
     index.add_vectors(np.eye(5			,     dtype=np.floataa	)	)
     self.assertIsInstance(index.faiss_index			,     faiss.IndexFlat	)
     lowerCamelCase__    :      Tuple					 =		FaissIndex(string_factory='LSH'	)
     index.add_vectors(np.eye(5			,     dtype=np.floataa	)	)
     self.assertIsInstance(index.faiss_index			,     faiss.IndexLSH	)
     with self.assertRaises(UpperCAmelCase	):
         lowerCamelCase__    :      List[str]					 =		FaissIndex(string_factory='Flat'			,     custom_index=faiss.IndexFlat(5	)	)
 def      A_	(      self  :      List[str]	)			->	Optional[int]:
     import faiss

     lowerCamelCase__    :      Optional[Any]					 =		faiss.IndexFlat(5	)
     lowerCamelCase__    :      int					 =		FaissIndex(custom_index=UpperCAmelCase	)
     index.add_vectors(np.eye(5			,     dtype=np.floataa	)	)
     self.assertIsInstance(index.faiss_index			,     faiss.IndexFlat	)







 def      A_	(      self  :      Any	)			->	Optional[int]:
     import faiss

     lowerCamelCase__    :      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=UpperCAmelCase	) as tmp_file:
         index.save(tmp_file.name	)
         lowerCamelCase__    :      List[Any]					 =		FaissIndex.load(tmp_file.name	)
     os.unlink(tmp_file.name	)

     lowerCamelCase__    :      List[str]					 =		np.zeros(5			,     dtype=np.floataa	)
     lowerCamelCase__    :      Tuple					 =		1
     lowerCamelCase__ ,							lowerCamelCase__    :      str					 =		index.search(UpperCAmelCase	)
     self.assertGreater(scores[0]			,     0	)
     self.assertEqual(indices[0]			,     1	)


@require_faiss
def        SCREAMING_SNAKE_CASE      (       _UpperCAmelCase )			->     Any:
    import faiss

    lowerCamelCase__    :      Optional[Any]					 =		FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT )
    index.add_vectors(np.eye(5						,	dtype=np.floataa ) )

    lowerCamelCase__    :      Optional[int]					 =		'index.faiss'
    lowerCamelCase__    :      Optional[Any]					 =		F"""mock://{index_name}"""
    index.save(_UpperCAmelCase						,	storage_options=mockfs.storage_options )
    lowerCamelCase__    :      Tuple					 =		FaissIndex.load(_UpperCAmelCase						,	storage_options=mockfs.storage_options )

    lowerCamelCase__    :      Optional[int]					 =		np.zeros(5						,	dtype=np.floataa )
    lowerCamelCase__    :      Dict					 =		1
    lowerCamelCase__ ,							lowerCamelCase__    :      str					 =		index.search(_UpperCAmelCase )
    assert scores[0] > 0
    assert indices[0] == 1


@require_elasticsearch
class    lowerCAmelCase							(					__UpperCamelCase			):
 def      A_	(      self  :      Dict	)			->	List[Any]:
     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:
         lowerCamelCase__    :      Any					 =		Elasticsearch()
         lowerCamelCase__    :      Tuple					 =		{'acknowledged': True}
         lowerCamelCase__    :      Tuple					 =		ElasticSearchIndex(es_client=UpperCAmelCase	)
         mocked_bulk.return_value([(True, None)] * 3	)
         index.add_documents(['foo', 'bar', 'foobar']	)

         # single query
         lowerCamelCase__    :      Optional[int]					 =		'foo'
         lowerCamelCase__    :      str					 =		{'hits': {'hits': [{'_score': 1, '_id': 0}]}}
         lowerCamelCase__ ,							lowerCamelCase__    :      Optional[Any]					 =		index.search(UpperCAmelCase	)
         self.assertEqual(scores[0]			,     1	)
         self.assertEqual(indices[0]			,     0	)

         # single query with timeout
         lowerCamelCase__    :      Any					 =		'foo'
         lowerCamelCase__    :      List[str]					 =		{'hits': {'hits': [{'_score': 1, '_id': 0}]}}
         lowerCamelCase__ ,							lowerCamelCase__    :      Tuple					 =		index.search(UpperCAmelCase			,     request_timeout=30	)
         self.assertEqual(scores[0]			,     1	)
         self.assertEqual(indices[0]			,     0	)

         # batched queries
         lowerCamelCase__    :      List[str]					 =		['foo', 'bar', 'foobar']
         lowerCamelCase__    :      str					 =		{'hits': {'hits': [{'_score': 1, '_id': 1}]}}
         lowerCamelCase__ ,							lowerCamelCase__    :      str					 =		index.search_batch(UpperCAmelCase	)
         lowerCamelCase__    :      List[str]					 =		[scores[0] for scores in total_scores]
         lowerCamelCase__    :      List[Any]					 =		[indices[0] for indices in total_indices]
         self.assertGreater(np.min(UpperCAmelCase	)			,     0	)
         self.assertListEqual([1, 1, 1]			,     UpperCAmelCase	)

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





