





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       =				pytest.mark.integration






@require_faiss
class   snake_case_							(						_UpperCamelCase		):






  def  UpperCAmelCase__		(				self					:	Union[str, Any]     )->str:






   '''simple docstring'''

   __lowerCAmelCase	:			Any         =  Dataset.from_dict({"""filename""": ["""my_name-train""" + """_""" + str(_UpperCAmelCase     ) for x in np.arange(30     ).tolist()]}     )
   return dset






  def  UpperCAmelCase__		(				self					:	int     )->List[Any]:






   '''simple docstring'''

   import faiss

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






   '''simple docstring'''

   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	:			Optional[int]         =  dset.get_nearest_examples("""vecs"""  ,    np.ones(5  ,    dtype=np.floataa     )     )
   self.assertEqual(examples["""filename"""][0]  ,    """my_name-train_29"""     )






  def  UpperCAmelCase__		(				self					:	Dict     )->List[str]:






   '''simple docstring'''

   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	:			List[str]         =  dset.get_nearest_examples("""vecs2"""  ,    np.ones(5  ,    dtype=np.floataa     )     )
   self.assertEqual(examples["""filename"""][0]  ,    """my_name-train_29"""     )






  def  UpperCAmelCase__		(				self					:	str     )->Optional[Any]:






   '''simple docstring'''

   __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  UpperCAmelCase__		(				self					:	Optional[Any]     )->List[str]:






   '''simple docstring'''

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

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






@require_faiss
class   snake_case_							(						_UpperCamelCase		):






  def  UpperCAmelCase__		(				self					:	str     )->Any:






   '''simple docstring'''

   import faiss

   __lowerCAmelCase	:			Dict         =  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	:			Optional[Any]         =  np.zeros(5  ,    dtype=np.floataa     )
   __lowerCAmelCase	:			Dict         =  1
   __lowerCAmelCase	:			Optional[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	:			Any         =  np.eye(5  ,    dtype=np.floataa     )[::-1]
   __lowerCAmelCase	:			List[Any]         =  index.search_batch(_UpperCAmelCase     )
   self.assertRaises(_UpperCAmelCase  ,    index.search_batch  ,    queries[0]     )
   __lowerCAmelCase	:			Union[str, Any]         =  [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([4, 3, 2, 1, 0]  ,    _UpperCAmelCase     )






  def  UpperCAmelCase__		(				self					:	Tuple     )->int:






   '''simple docstring'''

   import faiss

   __lowerCAmelCase	:			Tuple         =  FaissIndex(string_factory="""Flat"""     )
   index.add_vectors(np.eye(5  ,    dtype=np.floataa     )     )
   self.assertIsInstance(index.faiss_index  ,    faiss.IndexFlat     )
   __lowerCAmelCase	:			Union[str, Any]         =  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	:			Union[str, Any]         =  FaissIndex(string_factory="""Flat"""  ,    custom_index=faiss.IndexFlat(5     )     )






  def  UpperCAmelCase__		(				self					:	List[str]     )->List[Any]:






   '''simple docstring'''

   import faiss

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






  def  UpperCAmelCase__		(				self					:	List[str]     )->str:






   '''simple docstring'''

   import faiss

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

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






@require_faiss
def 			_SCREAMING_SNAKE_CASE						(     SCREAMING_SNAKE_CASE						:List[str]       )     ->       Tuple:
 import faiss

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

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

 __lowerCAmelCase	:			Tuple         =  np.zeros(5       ,       dtype=np.floataa       )
 __lowerCAmelCase	:			int         =  1
 __lowerCAmelCase	:			List[str]         =  index.search(lowerCAmelCase_       )
 assert scores[0] > 0
 assert indices[0] == 1







@require_elasticsearch
class   snake_case_							(						_UpperCamelCase		):






  def  UpperCAmelCase__		(				self					:	Tuple     )->List[str]:






   '''simple docstring'''

   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	:			Optional[int]         =  Elasticsearch()
    __lowerCAmelCase	:			Union[str, Any]         =  {'acknowledged': True}
    __lowerCAmelCase	:			Optional[int]         =  ElasticSearchIndex(es_client=_UpperCAmelCase     )
    mocked_bulk.return_value([(True, None)] * 3     )
    index.add_documents(["""foo""", """bar""", """foobar"""]     )

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

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

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

    # batched queries with timeout
    __lowerCAmelCase	:			Dict         =  ['foo', 'bar', 'foobar']
    __lowerCAmelCase	:			List[Any]         =  {'hits': {'hits': [{'_score': 1, '_id': 1}]}}
    __lowerCAmelCase	:			str         =  index.search_batch(_UpperCAmelCase  ,    request_timeout=30     )
    __lowerCAmelCase	:			Dict         =  [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     )




'''simple docstring'''

from __future__ import annotations

import unittest

from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
							import tensorflow as tf

							from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel

@require_tf
class       __magic_name__		:
							lowerCAmelCase			:       Optional[Any]  							=   MBartConfig
							lowerCAmelCase			:       str  							=   {}
							lowerCAmelCase			:       Dict  							=   'gelu'







							def __init__(				self   :			List[str]      ,_UpperCAmelCase   :			List[str]      ,_UpperCAmelCase   :			Tuple=13      ,_UpperCAmelCase   :			str=7      ,_UpperCAmelCase   :			Dict=True      ,_UpperCAmelCase   :			Optional[int]=False      ,_UpperCAmelCase   :			List[str]=99      ,_UpperCAmelCase   :			str=32      ,_UpperCAmelCase   :			List[str]=2      ,_UpperCAmelCase   :			Optional[int]=4      ,_UpperCAmelCase   :			str=37      ,_UpperCAmelCase   :			Union[str, Any]=0.1      ,_UpperCAmelCase   :			str=0.1      ,_UpperCAmelCase   :			Dict=20      ,_UpperCAmelCase   :			Optional[Any]=2      ,_UpperCAmelCase   :			Union[str, Any]=1      ,_UpperCAmelCase   :			List[str]=0      ,):
									_a	: Any								=				parent
									_a	: List[Any]								=				batch_size
									_a	: Any								=				seq_length
									_a	: List[str]								=				is_training
									_a	: str								=				use_labels
									_a	: List[Any]								=				vocab_size
									_a	: List[str]								=				hidden_size
									_a	: Union[str, Any]								=				num_hidden_layers
									_a	: Optional[Any]								=				num_attention_heads
									_a	: Optional[int]								=				intermediate_size
									_a	: Any								=				hidden_dropout_prob
									_a	: int								=				attention_probs_dropout_prob
									_a	: Union[str, Any]								=				max_position_embeddings
									_a	: Union[str, Any]								=				eos_token_id
									_a	: int								=				pad_token_id
									_a	: Union[str, Any]								=				bos_token_id







							def 				__lowercase     (				self   :			Optional[Any]						):
									_a	: str								=				ids_tensor([self.batch_size, self.seq_length - 1]      ,self.vocab_size						)
									_a	: List[str]								=				tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size						)      ,1						)
									_a	: str								=				tf.concat([input_ids, eos_tensor]      ,axis=1						)

									_a	: Dict								=				ids_tensor([self.batch_size, self.seq_length]      ,self.vocab_size						)

									_a	: List[str]								=				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      ,)
									_a	: Optional[int]								=				prepare_mbart_inputs_dict(_UpperCAmelCase      ,_UpperCAmelCase      ,_UpperCAmelCase						)
									return config, inputs_dict







							def 				__lowercase     (				self   :			Optional[Any]      ,_UpperCAmelCase   :			Union[str, Any]      ,_UpperCAmelCase   :			Optional[int]						):
									_a	: str								=				TFMBartModel(config=_UpperCAmelCase						).get_decoder()
									_a	: List[Any]								=				inputs_dict['input_ids']

									_a	: Optional[Any]								=				input_ids[:1, :]
									_a	: Tuple								=				inputs_dict['attention_mask'][:1, :]
									_a	: List[Any]								=				inputs_dict['head_mask']
									_a	: str								=				1

									# first forward pass
									_a	: Union[str, Any]								=				model(_UpperCAmelCase      ,attention_mask=_UpperCAmelCase      ,head_mask=_UpperCAmelCase      ,use_cache=_UpperCAmelCase						)

									_a			,   _a	: Optional[int]								=				outputs.to_tuple()
									_a	: Union[str, Any]								=				past_key_values[1]



def 	__lowerCamelCase	( lowerCAmelCase_		,     lowerCAmelCase_		,     lowerCAmelCase_		,     lowerCAmelCase_=None		,     lowerCAmelCase_=None		,     lowerCAmelCase_=None		,     lowerCAmelCase_=None		,     lowerCAmelCase_=None		,     )     -> Union[str, Any]:
		if attention_mask is None:
				_a	: List[Any]								=				tf.cast(tf.math.not_equal(lowerCAmelCase_		,     config.pad_token_id    )		,     tf.inta    )
		if decoder_attention_mask is None:
				_a	: Any								=				tf.concat(
				    [
				        tf.ones(decoder_input_ids[:, :1].shape		,     dtype=tf.inta    ),
				        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]		,     config.pad_token_id    )		,     tf.inta    ),
				    ]		,     axis=-1		,     )
		if head_mask is None:
				_a	: int								=				tf.ones((config.encoder_layers, config.encoder_attention_heads)    )
		if decoder_head_mask is None:
				_a	: Any								=				tf.ones((config.decoder_layers, config.decoder_attention_heads)    )
		if cross_attn_head_mask is None:
				_a	: int								=				tf.ones((config.decoder_layers, config.decoder_attention_heads)    )
		return {
		    "input_ids": input_ids,
		    "decoder_input_ids": decoder_input_ids,
		    "attention_mask": attention_mask,
		    "decoder_attention_mask": decoder_attention_mask,
		    "head_mask": head_mask,
		    "decoder_head_mask": decoder_head_mask,
		    "cross_attn_head_mask": cross_attn_head_mask,
		}

@require_tf
class       __magic_name__		(       _UpperCamelCase     ,		_UpperCamelCase     ,		unittest.TestCase  ):
							lowerCAmelCase			:       List[str]  							=   (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
							lowerCAmelCase			:       Optional[Any]  							=   (TFMBartForConditionalGeneration,) if is_tf_available() else ()
							lowerCAmelCase			:       Dict  							=   (
							    {
							        'conversational': TFMBartForConditionalGeneration,
							        'feature-extraction': TFMBartModel,
							        'summarization': TFMBartForConditionalGeneration,
							        'text2text-generation': TFMBartForConditionalGeneration,
							        'translation': TFMBartForConditionalGeneration,
							    }
							    if is_tf_available()
							    else {}
							)
							lowerCAmelCase			:       Dict  							=   True
							lowerCAmelCase			:       List[str]  							=   False
							lowerCAmelCase			:       str  							=   False







							def 				__lowercase     (				self   :			int      ,_UpperCAmelCase   :			Dict      ,_UpperCAmelCase   :			str      ,_UpperCAmelCase   :			Union[str, Any]      ,_UpperCAmelCase   :			Union[str, Any]      ,_UpperCAmelCase   :			int						):
									if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
											# Exception encountered when calling layer '...'
											return True

									return False







							def 				__lowercase     (				self   :			Optional[Any]						):
									_a	: Optional[int]								=				TFMBartModelTester(self						)
									_a	: Dict								=				ConfigTester(self      ,config_class=_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Optional[int]						):
									self.config_tester.run_common_tests()







							def 				__lowercase     (				self   :			Optional[int]						):
									_a	: List[Any]								=				self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.check_decoder_model_past_large_inputs(*_UpperCAmelCase						)

@require_sentencepiece
@require_tokenizers
@require_tf
class       __magic_name__		(       unittest.TestCase  ):
							lowerCAmelCase			:       List[Any]  							=   [
							    ' UN Chief Says There Is No Military Solution in Syria',
							]
							lowerCAmelCase			:       Dict  							=   [
							    'Şeful ONU declară că nu există o soluţie militară în Siria',
							]
							lowerCAmelCase			:       Tuple  							=   'facebook/mbart-large-en-ro'







							@cached_property
							def 				__lowercase     (				self   :			Optional[int]						):
									return AutoTokenizer.from_pretrained(self.model_name						)







							@cached_property
							def 				__lowercase     (				self   :			Optional[int]						):
									_a	: Any								=				TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name						)
									return model







							def 				__lowercase     (				self   :			Optional[int]      ,**_UpperCAmelCase   :			Dict						):
									_a	: List[Any]								=				self.translate_src_text(**_UpperCAmelCase						)
									self.assertListEqual(self.expected_text      ,_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Tuple      ,**_UpperCAmelCase   :			str						):
									_a	: List[Any]								=				self.tokenizer(self.src_text      ,**_UpperCAmelCase      ,return_tensors='tf'						)
									_a	: Any								=				self.model.generate(
									    model_inputs.input_ids      ,attention_mask=model_inputs.attention_mask      ,num_beams=2						)
									_a	: Tuple								=				self.tokenizer.batch_decode(_UpperCAmelCase      ,skip_special_tokens=_UpperCAmelCase						)
									return generated_words







							@slow
							def 				__lowercase     (				self   :			Tuple						):
									self._assert_generated_batch_equal_expected()




