
"""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__   :					Any							=   pytest.mark.integration


@require_faiss
class 			__magic_name__       (       SCREAMING_SNAKE_CASE__ ):
       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			str       =     Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(A_       ) for x in np.arange(30       ).tolist()]}       )
         return dset
       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         import faiss

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





         """simple docstring"""




         import faiss

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





         """simple docstring"""




         import faiss

         _lowercase:			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       )

         _lowercase ,				_lowercase:			Dict       =     dset.get_nearest_examples('''vecs2''' ,				np.ones(5 ,				dtype=np.floataa       )       )
         self.assertEqual(examples['''filename'''][0] ,				'''my_name-train_29'''       )
       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         _lowercase:			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 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         from elasticsearch import Elasticsearch

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

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


@require_faiss
class 			__magic_name__       (       SCREAMING_SNAKE_CASE__ ):
       def 							lowercase_							(     self       )     ->	Any:





         """simple docstring"""




         import faiss

         _lowercase:			str       =     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
         _lowercase:			List[Any]       =     np.zeros(5 ,				dtype=np.floataa       )
         _lowercase:			int       =     1
         _lowercase ,				_lowercase:			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
         _lowercase:			Tuple       =     np.eye(5 ,				dtype=np.floataa       )[::-1]
         _lowercase ,				_lowercase:			str       =     index.search_batch(A_       )
         self.assertRaises(A_ ,				index.search_batch ,				queries[0]       )
         _lowercase:			Tuple       =     [scores[0] for scores in total_scores]
         _lowercase:			Union[str, Any]       =     [indices[0] for indices in total_indices]
         self.assertGreater(np.min(A_       ) ,				0       )
         self.assertListEqual([4, 3, 2, 1, 0] ,				A_       )
       def 							lowercase_							(     self       )     ->	Union[str, Any]:





         """simple docstring"""




         import faiss

         _lowercase:			Union[str, Any]       =     FaissIndex(string_factory='''Flat'''       )
         index.add_vectors(np.eye(5 ,				dtype=np.floataa       )       )
         self.assertIsInstance(index.faiss_index ,				faiss.IndexFlat       )
         _lowercase:			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_       ):
           _lowercase:			List[str]       =     FaissIndex(string_factory='''Flat''' ,				custom_index=faiss.IndexFlat(5       )       )
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         import faiss

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



       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         import faiss

         _lowercase:			Tuple       =     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       )
           _lowercase:			Optional[Any]       =     FaissIndex.load(tmp_file.name       )
         os.unlink(tmp_file.name       )

         _lowercase:			Optional[Any]       =     np.zeros(5 ,				dtype=np.floataa       )
         _lowercase:			Union[str, Any]       =     1
         _lowercase ,				_lowercase:			Tuple       =     index.search(A_       )
         self.assertGreater(scores[0] ,				0       )
         self.assertEqual(indices[0] ,				1       )




@require_faiss
def  _lowerCAmelCase		(		_UpperCamelCase						):






  """simple docstring"""



  import faiss

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

  _lowercase:			Tuple       =     '''index.faiss'''
  _lowercase:			str       =     f'''mock://{index_name}'''
  index.save(_UpperCamelCase ,				storage_options=mockfs.storage_options						)
  _lowercase:			List[Any]       =     FaissIndex.load(_UpperCamelCase ,				storage_options=mockfs.storage_options						)

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







@require_elasticsearch
class 			__magic_name__       (       SCREAMING_SNAKE_CASE__ ):
       def 							lowercase_							(     self       )     ->	int:





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

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

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

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

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


"""simple docstring"""




import comet  # From: unbabel-comet
import torch

import datasets


A__   :					int							=   datasets.logging.get_logger(__name__)

A__   :					Optional[Any]							=   '\\n@inproceedings{rei-EtAl:2020:WMT,\n   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},\n   title     = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},\n   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},\n   month          = {November},\n   year           = {2020},\n   address        = {Online},\n   publisher      = {Association for Computational Linguistics},\n   pages     = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n   title = "{COMET}: A Neural Framework for {MT} Evaluation",\n   author = "Rei, Ricardo  and\n      Stewart, Craig  and\n      Farinha, Ana C  and\n      Lavie, Alon",\n   booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",\n   month = nov,\n   year = "2020",\n   address = "Online",\n   publisher = "Association for Computational Linguistics",\n   url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",\n   pages = "2685--2702",\n}\n'

A__   :					Union[str, Any]							=   '\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n'

A__   :					int							=   '\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n    `scores`: List of scores.\n\nExamples:\n\n    >>> comet_metric = datasets.load_metric(\'comet\')\n    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use\n    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n    >>> print([round(v, 2) for v in results["scores"]])\n    [0.19, 0.92]\n'


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,					_KWARGS_DESCRIPTION )
class 			__magic_name__       (       datasets.Metric ):
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         return datasets.MetricInfo(
             description=_DESCRIPTION ,				citation=_CITATION ,				homepage='''https://unbabel.github.io/COMET/html/index.html''' ,				inputs_description=_KWARGS_DESCRIPTION ,				features=datasets.Features(
                 {
                     '''sources''': datasets.Value('''string''' ,				id='''sequence'''       ),
                     '''predictions''': datasets.Value('''string''' ,				id='''sequence'''       ),
                     '''references''': datasets.Value('''string''' ,				id='''sequence'''       ),
                 }       ) ,				codebase_urls=['''https://github.com/Unbabel/COMET'''] ,				reference_urls=[
                 '''https://github.com/Unbabel/COMET''',
                 '''https://www.aclweb.org/anthology/2020.emnlp-main.213/''',
                 '''http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6''',
             ] ,				)
       def 							lowercase_							(     self ,				A_       )     ->	Dict:





         """simple docstring"""




         if self.config_name == "default":
           _lowercase:			str       =     comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da'''       )       )
         else:
           _lowercase:			Optional[Any]       =     comet.load_from_checkpoint(comet.download_model(self.config_name       )       )



       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_=None ,				A_=False       )     ->	List[str]:





         """simple docstring"""




         if gpus is None:
           _lowercase:			Union[str, Any]       =     1 if torch.cuda.is_available() else 0
         _lowercase:			Any       =     {'''src''': sources, '''mt''': predictions, '''ref''': references}
         _lowercase:			int       =     [dict(zip(A_ ,				A_       )       ) for t in zip(*data.values()       )]
         _lowercase ,				_lowercase:			Tuple       =     self.scorer.predict(A_ ,				gpus=A_ ,				progress_bar=A_       )
         return {"mean_score": mean_score, "scores": scores}
