






import unittest

from transformers import PegasusConfig, PegasusTokenizer, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
 import os

 # The slow tests are often failing with OOM error on GPU
 # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
 # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
 snake_case__   :						Union[str, Any]													=   """platform"""
 import jax
 import jax.numpy as jnp
 import numpy as np

 from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel


@require_flax
class     _a							:






  """simple docstring"""





  A_						       = PegasusConfig
  A_						       = {}
  A_						       = """gelu"""




  def __init__(  self		,		_UpperCAmelCase		,		_UpperCAmelCase=13		,		_UpperCAmelCase=7		,		_UpperCAmelCase=True		,		_UpperCAmelCase=False		,		_UpperCAmelCase=99		,		_UpperCAmelCase=32		,		_UpperCAmelCase=5		,		_UpperCAmelCase=4		,		_UpperCAmelCase=37		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=0.1		,		_UpperCAmelCase=20		,		_UpperCAmelCase=2		,		_UpperCAmelCase=1		,		_UpperCAmelCase=0		,		)      ->			Optional[int]:
     UpperCamelCase_						=  parent
     UpperCamelCase_						=  batch_size
     UpperCamelCase_						=  seq_length
     UpperCamelCase_						=  is_training
     UpperCamelCase_						=  use_labels
     UpperCamelCase_						=  vocab_size
     UpperCamelCase_						=  hidden_size
     UpperCamelCase_						=  num_hidden_layers
     UpperCamelCase_						=  num_attention_heads
     UpperCamelCase_						=  intermediate_size

     UpperCamelCase_						=  hidden_dropout_prob
     UpperCamelCase_						=  attention_probs_dropout_prob
     UpperCamelCase_						=  max_position_embeddings
     UpperCamelCase_						=  eos_token_id
     UpperCamelCase_						=  pad_token_id
     UpperCamelCase_						=  bos_token_id




  def  _UpperCAmelCase  (  self			)      ->			str:
     UpperCamelCase_						=  ids_tensor([self.batch_size, self.seq_length - 1]		,		self.vocab_size			).clip(3		,		self.vocab_size			)
     UpperCamelCase_						=  np.expand_dims(np.array([self.eos_token_id] * self.batch_size			)		,		1			)
     UpperCamelCase_						=  np.concatenate([input_ids, eos_tensor]		,		axis=1			)

     UpperCamelCase_						=  ids_tensor([self.batch_size, self.seq_length]		,		self.vocab_size			)

     UpperCamelCase_						=  self.config_cls(
         vocab_size=self.vocab_size		,		d_model=self.hidden_size		,		encoder_layers=self.num_hidden_layers		,		decoder_layers=self.num_hidden_layers		,		encoder_attention_heads=self.num_attention_heads		,		decoder_attention_heads=self.num_attention_heads		,		encoder_ffn_dim=self.intermediate_size		,		decoder_ffn_dim=self.intermediate_size		,		dropout=self.hidden_dropout_prob		,		attention_dropout=self.attention_probs_dropout_prob		,		max_position_embeddings=self.max_position_embeddings		,		eos_token_ids=[2]		,		bos_token_id=self.bos_token_id		,		pad_token_id=self.pad_token_id		,		decoder_start_token_id=self.pad_token_id		,		**self.config_updates		,		)
     UpperCamelCase_						=  prepare_pegasus_inputs_dict(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase			)
     return config, inputs_dict




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Any:
     UpperCamelCase_						=  20
     UpperCamelCase_						=  model_class_name(_UpperCAmelCase			)

     UpperCamelCase_						=  model.encode(inputs_dict['input_ids']			)

     UpperCamelCase_		,   UpperCamelCase_						=  (
         inputs_dict['decoder_input_ids'],
         inputs_dict['decoder_attention_mask'],
     )

     UpperCamelCase_						=  model.init_cache(decoder_input_ids.shape[0]		,		_UpperCAmelCase		,		_UpperCAmelCase			)
     UpperCamelCase_						=  jnp.ones((decoder_input_ids.shape[0], max_decoder_length)		,		dtype='i4'			)

     UpperCamelCase_						=  jnp.broadcast_to(
         jnp.arange(decoder_input_ids.shape[-1] - 1			)[None, :]		,		(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)		,		)
     UpperCamelCase_						=  model.decode(
         decoder_input_ids[:, :-1]		,		_UpperCAmelCase		,		decoder_attention_mask=_UpperCAmelCase		,		past_key_values=_UpperCAmelCase		,		decoder_position_ids=_UpperCAmelCase		,		)

     UpperCamelCase_						=  jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]		,		dtype='i4'			)
     UpperCamelCase_						=  model.decode(
         decoder_input_ids[:, -1:]		,		_UpperCAmelCase		,		decoder_attention_mask=_UpperCAmelCase		,		past_key_values=outputs_cache.past_key_values		,		decoder_position_ids=_UpperCAmelCase		,		)

     UpperCamelCase_						=  model.decode(_UpperCAmelCase		,		_UpperCAmelCase			)

     UpperCamelCase_						=  np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])			)			)
     self.parent.assertTrue(diff < 1e-3		,		msg=f"""Max diff is {diff}"""			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			List[Any]:
     UpperCamelCase_						=  20
     UpperCamelCase_						=  model_class_name(_UpperCAmelCase			)

     UpperCamelCase_						=  model.encode(inputs_dict['input_ids']			)

     UpperCamelCase_		,   UpperCamelCase_						=  (
         inputs_dict['decoder_input_ids'],
         inputs_dict['decoder_attention_mask'],
     )

     UpperCamelCase_						=  jnp.concatenate(
         [
             decoder_attention_mask,
             jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])			),
         ]		,		axis=-1		,		)

     UpperCamelCase_						=  model.init_cache(decoder_input_ids.shape[0]		,		_UpperCAmelCase		,		_UpperCAmelCase			)
     UpperCamelCase_						=  jnp.broadcast_to(
         jnp.arange(decoder_input_ids.shape[-1] - 1			)[None, :]		,		(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)		,		)

     UpperCamelCase_						=  model.decode(
         decoder_input_ids[:, :-1]		,		_UpperCAmelCase		,		decoder_attention_mask=_UpperCAmelCase		,		past_key_values=_UpperCAmelCase		,		decoder_position_ids=_UpperCAmelCase		,		)
     UpperCamelCase_						=  jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]		,		dtype='i4'			)
     UpperCamelCase_						=  model.decode(
         decoder_input_ids[:, -1:]		,		_UpperCAmelCase		,		past_key_values=outputs_cache.past_key_values		,		decoder_attention_mask=_UpperCAmelCase		,		decoder_position_ids=_UpperCAmelCase		,		)

     UpperCamelCase_						=  model.decode(_UpperCAmelCase		,		_UpperCAmelCase		,		decoder_attention_mask=_UpperCAmelCase			)

     UpperCamelCase_						=  np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])			)			)
     self.parent.assertTrue(diff < 1e-3		,		msg=f"""Max diff is {diff}"""			)






def      _snake_case     (__lowercase     ,   __lowercase     ,   __lowercase     ,   __lowercase=None     ,   __lowercase=None     ,   ):
   if attention_mask is None:
      UpperCamelCase_						=  np.not_equal(__lowercase     ,   config.pad_token_id).astype(np.inta)
   if decoder_attention_mask is None:
      UpperCamelCase_						=  np.concatenate(
          [
              np.ones(decoder_input_ids[:, :1].shape     ,   dtype=np.inta),
              np.not_equal(decoder_input_ids[:, 1:]     ,   config.pad_token_id).astype(np.inta),
          ]     ,   axis=-1     ,   )
   return {
       "input_ids": input_ids,
       "decoder_input_ids": decoder_input_ids,
       "attention_mask": attention_mask,
       "decoder_attention_mask": decoder_attention_mask,
   }


@require_flax
class     _a							(	UpperCAmelCase__    ,							unittest.TestCase     ):






  """simple docstring"""





  A_						       = (
      (
          FlaxPegasusForConditionalGeneration,
          FlaxPegasusModel,
      )
      if is_flax_available()
      else ()
  )
  A_						       = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else ()
  A_						       = True
  A_						       = False
  A_						       = False
  A_						       = False




  def  _UpperCAmelCase  (  self			)      ->			Dict:
     UpperCamelCase_						=  FlaxPegasusModelTester(self			)
     UpperCamelCase_						=  ConfigTester(self		,		config_class=_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self			)      ->			str:
     self.config_tester.run_common_tests()




  def  _UpperCAmelCase  (  self			)      ->			Dict:
     UpperCamelCase_		,   UpperCamelCase_						=  self.model_tester.prepare_config_and_inputs_for_common()
     for model_class in self.all_model_classes:
        self.model_tester.check_use_cache_forward(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self			)      ->			Tuple:
     UpperCamelCase_		,   UpperCamelCase_						=  self.model_tester.prepare_config_and_inputs_for_common()
     for model_class in self.all_model_classes:
        self.model_tester.check_use_cache_forward_with_attn_mask(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self			)      ->			Dict:
     UpperCamelCase_		,   UpperCamelCase_						=  self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        with self.subTest(model_class.__name__			):
           UpperCamelCase_						=  self._prepare_for_class(_UpperCAmelCase		,		_UpperCAmelCase			)
           UpperCamelCase_						=  model_class(_UpperCAmelCase			)

           @jax.jit
           def encode_jitted(_UpperCAmelCase		,		_UpperCAmelCase=None		,		**_UpperCAmelCase			):
              return model.encode(input_ids=_UpperCAmelCase		,		attention_mask=_UpperCAmelCase			)

           with self.subTest('JIT Enabled'			):
              UpperCamelCase_						=  encode_jitted(**_UpperCAmelCase			).to_tuple()

           with self.subTest('JIT Disabled'			):
              with jax.disable_jit():
                 UpperCamelCase_						=  encode_jitted(**_UpperCAmelCase			).to_tuple()

           self.assertEqual(len(_UpperCAmelCase			)		,		len(_UpperCAmelCase			)			)
           for jitted_output, output in zip(_UpperCAmelCase		,		_UpperCAmelCase			):
              self.assertEqual(jitted_output.shape		,		output.shape			)




  def  _UpperCAmelCase  (  self			)      ->			List[str]:
     UpperCamelCase_		,   UpperCamelCase_						=  self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        with self.subTest(model_class.__name__			):
           UpperCamelCase_						=  model_class(_UpperCAmelCase			)
           UpperCamelCase_						=  model.encode(inputs_dict['input_ids']		,		inputs_dict['attention_mask']			)

           UpperCamelCase_						=  {
               'decoder_input_ids': inputs_dict['decoder_input_ids'],
               'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
               'encoder_outputs': encoder_outputs,
           }

           @jax.jit
           def decode_jitted(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase			):
              return model.decode(
                  decoder_input_ids=_UpperCAmelCase		,		decoder_attention_mask=_UpperCAmelCase		,		encoder_outputs=_UpperCAmelCase		,		)

           with self.subTest('JIT Enabled'			):
              UpperCamelCase_						=  decode_jitted(**_UpperCAmelCase			).to_tuple()

           with self.subTest('JIT Disabled'			):
              with jax.disable_jit():
                 UpperCamelCase_						=  decode_jitted(**_UpperCAmelCase			).to_tuple()

           self.assertEqual(len(_UpperCAmelCase			)		,		len(_UpperCAmelCase			)			)
           for jitted_output, output in zip(_UpperCAmelCase		,		_UpperCAmelCase			):
              self.assertEqual(jitted_output.shape		,		output.shape			)




  @slow
  def  _UpperCAmelCase  (  self			)      ->			int:
     for model_class_name in self.all_model_classes:
        UpperCamelCase_						=  model_class_name.from_pretrained('google/pegasus-large'		,		from_pt=_UpperCAmelCase			)
        UpperCamelCase_						=  np.ones((1, 1)			)
        UpperCamelCase_						=  model(_UpperCAmelCase			)
        self.assertIsNotNone(_UpperCAmelCase			)




  @slow
  def  _UpperCAmelCase  (  self			)      ->			List[Any]:
     UpperCamelCase_						=  FlaxPegasusForConditionalGeneration.from_pretrained('google/pegasus-xsum'			)
     UpperCamelCase_						=  PegasusTokenizer.from_pretrained('google/pegasus-xsum'			)

     UpperCamelCase_						=  [
         ' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.',
         ' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ',
     ]

     UpperCamelCase_						=  [
         'California\'s largest electricity provider has turned off power to hundreds of thousands of customers.',
         'Pop group N-Dubz have revealed they were surprised to get four nominations for this year\'s Mobo Awards.',
     ]

     UpperCamelCase_						=  tokenizer(_UpperCAmelCase		,		return_tensors='np'		,		truncation=_UpperCAmelCase		,		max_length=512		,		padding=_UpperCAmelCase			)
     UpperCamelCase_						=  model.generate(**_UpperCAmelCase		,		num_beams=2			).sequences
     UpperCamelCase_						=  tokenizer.batch_decode(_UpperCAmelCase		,		skip_special_tokens=_UpperCAmelCase			)
     assert tgt_text == decoded








"""simple docstring"""




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_				:      List[str]           =			pytest.mark.integration





@require_faiss
class  lowerCamelCase    (A__      ):

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     Tuple:
						SCREAMING_SNAKE_CASE__										=   Dataset.from_dict({"""filename""": ["""my_name-train""" + """_""" + str(__UpperCAmelCase							) for x in np.arange(3_0							).tolist()]}							)
						return dset

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     Tuple:
						import faiss

						SCREAMING_SNAKE_CASE__										=   self._create_dummy_dataset()
						SCREAMING_SNAKE_CASE__										=   dset.map(
						    lambda __UpperCAmelCase     ,					__UpperCAmelCase							: {"vecs": i * np.ones(5     ,					dtype=np.floataa							)}     ,					with_indices=__UpperCAmelCase     ,					keep_in_memory=__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   dset.add_faiss_index("""vecs"""     ,					batch_size=1_0_0     ,					metric_type=faiss.METRIC_INNER_PRODUCT							)
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   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        SCREAMING_SNAKE_CASE					(       self					:    List[str]							) ->     str:
						import faiss

						SCREAMING_SNAKE_CASE__										=   self._create_dummy_dataset()
						dset.add_faiss_index_from_external_arrays(
						    external_arrays=np.ones((3_0, 5)							) * np.arange(3_0							).reshape(-1     ,					1							)     ,					index_name="""vecs"""     ,					batch_size=1_0_0     ,					metric_type=faiss.METRIC_INNER_PRODUCT     ,					)
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   dset.get_nearest_examples("""vecs"""     ,					np.ones(5     ,					dtype=np.floataa							)							)
						self.assertEqual(examples["""filename"""][0]     ,					"""my_name-train_29"""							)

			def        SCREAMING_SNAKE_CASE					(       self					:    List[Any]							) ->     Any:
						import faiss

						SCREAMING_SNAKE_CASE__										=   self._create_dummy_dataset()
						dset.add_faiss_index_from_external_arrays(
						    external_arrays=np.ones((3_0, 5)							) * np.arange(3_0							).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							)

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

			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[int]							) ->     int:
						SCREAMING_SNAKE_CASE__										=   self._create_dummy_dataset()
						dset.add_faiss_index_from_external_arrays(
						    external_arrays=np.ones((3_0, 5)							) * np.arange(3_0							).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        SCREAMING_SNAKE_CASE					(       self					:    List[str]							) ->     str:
						from elasticsearch import Elasticsearch

						SCREAMING_SNAKE_CASE__										=   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:
									SCREAMING_SNAKE_CASE__										=   {"""acknowledged""": True}
									mocked_bulk.return_value([(True, None)] * 3_0							)
									SCREAMING_SNAKE_CASE__										=   {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 2_9}]}}
									SCREAMING_SNAKE_CASE__										=   Elasticsearch()

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





@require_faiss
class  lowerCamelCase    (A__      ):

			def        SCREAMING_SNAKE_CASE					(       self					:    int							) ->     List[str]:
						import faiss

						SCREAMING_SNAKE_CASE__										=   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     ,					1_0							)

						# single query
						SCREAMING_SNAKE_CASE__										=   np.zeros(5     ,					dtype=np.floataa							)
						SCREAMING_SNAKE_CASE__										=   1
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   index.search(__UpperCAmelCase							)
						self.assertRaises(__UpperCAmelCase     ,					index.search     ,					query.reshape(-1     ,					1							)							)
						self.assertGreater(scores[0]     ,					0							)
						self.assertEqual(indices[0]     ,					1							)

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

			def        SCREAMING_SNAKE_CASE					(       self					:    List[str]							) ->     str:
						import faiss

						SCREAMING_SNAKE_CASE__										=   FaissIndex(string_factory="""Flat"""							)
						index.add_vectors(np.eye(5     ,					dtype=np.floataa							)							)
						self.assertIsInstance(index.faiss_index     ,					faiss.IndexFlat							)
						SCREAMING_SNAKE_CASE__										=   FaissIndex(string_factory="""LSH"""							)
						index.add_vectors(np.eye(5     ,					dtype=np.floataa							)							)
						self.assertIsInstance(index.faiss_index     ,					faiss.IndexLSH							)
						with self.assertRaises(__UpperCAmelCase							):
									SCREAMING_SNAKE_CASE__										=   FaissIndex(string_factory="""Flat"""     ,					custom_index=faiss.IndexFlat(5							)							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict							) ->     Any:
						import faiss

						SCREAMING_SNAKE_CASE__										=   faiss.IndexFlat(5							)
						SCREAMING_SNAKE_CASE__										=   FaissIndex(custom_index=__UpperCAmelCase							)
						index.add_vectors(np.eye(5     ,					dtype=np.floataa							)							)
						self.assertIsInstance(index.faiss_index     ,					faiss.IndexFlat							)





			def        SCREAMING_SNAKE_CASE					(       self					:    Union[str, Any]							) ->     str:
						import faiss

						SCREAMING_SNAKE_CASE__										=   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							)
									SCREAMING_SNAKE_CASE__										=   FaissIndex.load(tmp_file.name							)
						os.unlink(tmp_file.name							)

						SCREAMING_SNAKE_CASE__										=   np.zeros(5     ,					dtype=np.floataa							)
						SCREAMING_SNAKE_CASE__										=   1
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   index.search(__UpperCAmelCase							)
						self.assertGreater(scores[0]     ,					0							)
						self.assertEqual(indices[0]     ,					1							)

@require_faiss
def 						A							(  snake_case__     ):




			'''simple docstring'''


			import faiss

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

			SCREAMING_SNAKE_CASE__										=   """index.faiss"""
			SCREAMING_SNAKE_CASE__										=   f"""mock://{index_name}"""
			index.save(snake_case__		,					storage_options=mockfs.storage_options     )
			SCREAMING_SNAKE_CASE__										=   FaissIndex.load(snake_case__		,					storage_options=mockfs.storage_options     )

			SCREAMING_SNAKE_CASE__										=   np.zeros(5		,					dtype=np.floataa     )
			SCREAMING_SNAKE_CASE__										=   1
			SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   index.search(snake_case__     )
			assert scores[0] > 0
			assert indices[0] == 1





@require_elasticsearch
class  lowerCamelCase    (A__      ):

			def        SCREAMING_SNAKE_CASE					(       self					:    Tuple							) ->     Dict:
						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:
									SCREAMING_SNAKE_CASE__										=   Elasticsearch()
									SCREAMING_SNAKE_CASE__										=   {"""acknowledged""": True}
									SCREAMING_SNAKE_CASE__										=   ElasticSearchIndex(es_client=__UpperCAmelCase							)
									mocked_bulk.return_value([(True, None)] * 3							)
									index.add_documents(["""foo""", """bar""", """foobar"""]							)

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

									# single query with timeout
									SCREAMING_SNAKE_CASE__										=   """foo"""
									SCREAMING_SNAKE_CASE__										=   {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 0}]}}
									SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   index.search(__UpperCAmelCase     ,					request_timeout=3_0							)
									self.assertEqual(scores[0]     ,					1							)
									self.assertEqual(indices[0]     ,					0							)

									# batched queries
									SCREAMING_SNAKE_CASE__										=   ["""foo""", """bar""", """foobar"""]
									SCREAMING_SNAKE_CASE__										=   {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}}
									SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   index.search_batch(__UpperCAmelCase							)
									SCREAMING_SNAKE_CASE__										=   [scores[0] for scores in total_scores]
									SCREAMING_SNAKE_CASE__										=   [indices[0] for indices in total_indices]
									self.assertGreater(np.min(__UpperCAmelCase							)     ,					0							)
									self.assertListEqual([1, 1, 1]     ,					__UpperCAmelCase							)

									# batched queries with timeout
									SCREAMING_SNAKE_CASE__										=   ["""foo""", """bar""", """foobar"""]
									SCREAMING_SNAKE_CASE__										=   {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}}
									SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   index.search_batch(__UpperCAmelCase     ,					request_timeout=3_0							)
									SCREAMING_SNAKE_CASE__										=   [scores[0] for scores in total_scores]
									SCREAMING_SNAKE_CASE__										=   [indices[0] for indices in total_indices]
									self.assertGreater(np.min(__UpperCAmelCase							)     ,					0							)
									self.assertListEqual([1, 1, 1]     ,					__UpperCAmelCase							)


