




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


_lowerCamelCase      :  Any      						=						pytest.mark.integration
@require_faiss
class        __snake_case  (_a		):



				def       SCREAMING_SNAKE_CASE       (      self      :		str      )  ->    int:





								'''simple docstring'''




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



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





								'''simple docstring'''




								import faiss

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





								'''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       SCREAMING_SNAKE_CASE       (      self      :		Tuple      )  ->    Optional[int]:





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

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






@require_faiss
class        __snake_case  (_a		):



				def       SCREAMING_SNAKE_CASE       (      self      :		Any      )  ->    Tuple:





								'''simple docstring'''




								import faiss

								_lowerCAmelCase    :    List[Any]										=      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    :    List[str]										=      np.zeros(5		,	dtype=np.floataa      )
								_lowerCAmelCase    :    List[str]										=      1
								_lowerCAmelCase					,    _lowerCAmelCase    :    int										=      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    :    Tuple										=      np.eye(5		,	dtype=np.floataa      )[::-1]
								_lowerCAmelCase					,    _lowerCAmelCase    :    int										=      index.search_batch(_UpperCAmelCase      )
								self.assertRaises(_UpperCAmelCase		,	index.search_batch		,	queries[0]      )
								_lowerCAmelCase    :    Optional[Any]										=      [scores[0] for scores in total_scores]
								_lowerCAmelCase    :    Optional[int]										=      [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      :		int      )  ->    Tuple:





								'''simple docstring'''




								import faiss

								_lowerCAmelCase    :    Optional[int]										=      FaissIndex(string_factory="""Flat"""      )
								index.add_vectors(np.eye(5		,	dtype=np.floataa      )      )
								self.assertIsInstance(index.faiss_index		,	faiss.IndexFlat      )
								_lowerCAmelCase    :    int										=      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    :    Dict										=      FaissIndex(string_factory="""Flat"""		,	custom_index=faiss.IndexFlat(5      )      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Tuple      )  ->    str:





								'''simple docstring'''




								import faiss

								_lowerCAmelCase    :    Dict										=      faiss.IndexFlat(5      )
								_lowerCAmelCase    :    str										=      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      :		str      )  ->    Any:





								'''simple docstring'''




								import faiss

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

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






@require_faiss
def 							_UpperCAmelCase  (UpperCamelCase_ : str       ):
				'''simple docstring'''
				import faiss

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

				_lowerCAmelCase    :    Optional[int]										=      """index.faiss"""
				_lowerCAmelCase    :    Dict										=      F"mock://{index_name}"
				index.save(UpperCamelCase_      ,    storage_options=mockfs.storage_options       )
				_lowerCAmelCase    :    Union[str, Any]										=      FaissIndex.load(UpperCamelCase_      ,    storage_options=mockfs.storage_options       )

				_lowerCAmelCase    :    List[str]										=      np.zeros(5      ,    dtype=np.floataa       )
				_lowerCAmelCase    :    Dict										=      1
				_lowerCAmelCase					,    _lowerCAmelCase    :    List[str]										=      index.search(UpperCamelCase_       )
				assert scores[0] > 0
				assert indices[0] == 1





@require_elasticsearch
class        __snake_case  (_a		):



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





								'''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    :    Optional[int]										=      {"""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    :    Optional[int]										=      """foo"""
												_lowerCAmelCase    :    str										=      {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 0}]}}
												_lowerCAmelCase					,    _lowerCAmelCase    :    Any										=      index.search(_UpperCAmelCase      )
												self.assertEqual(scores[0]		,	1      )
												self.assertEqual(indices[0]		,	0      )

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

												# batched queries
												_lowerCAmelCase    :    Tuple										=      ["""foo""", """bar""", """foobar"""]
												_lowerCAmelCase    :    Tuple										=      {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}}
												_lowerCAmelCase					,    _lowerCAmelCase    :    Any										=      index.search_batch(_UpperCAmelCase      )
												_lowerCAmelCase    :    Optional[int]										=      [scores[0] for scores in total_scores]
												_lowerCAmelCase    :    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    :    Any										=      ["""foo""", """bar""", """foobar"""]
												_lowerCAmelCase    :    List[str]										=      {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}}
												_lowerCAmelCase					,    _lowerCAmelCase    :    Optional[Any]										=      index.search_batch(_UpperCAmelCase		,	request_timeout=30      )
												_lowerCAmelCase    :    int										=      [scores[0] for scores in total_scores]
												_lowerCAmelCase    :    Tuple										=      [indices[0] for indices in total_indices]
												self.assertGreater(np.min(_UpperCAmelCase      )		,	0      )
												self.assertListEqual([1, 1, 1]		,	_UpperCAmelCase      )







import comet  # From: unbabel-comet
import torch

import datasets


_lowerCamelCase      :  List[Any]      						=						datasets.logging.get_logger(__name__)

_lowerCamelCase      :  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"

_lowerCamelCase      :  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"

_lowerCamelCase      :  Optional[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        __snake_case  (datasets.Metric		):



				def       SCREAMING_SNAKE_CASE       (      self      :		List[Any]      )  ->    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       SCREAMING_SNAKE_CASE       (      self      :		Dict		,	_UpperCAmelCase      :		List[str]      )  ->    Dict:





								'''simple docstring'''




								if self.config_name == "default":
												_lowerCAmelCase    :    Union[str, Any]										=      comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da"""      )      )
								else:
												_lowerCAmelCase    :    Dict										=      comet.load_from_checkpoint(comet.download_model(self.config_name      )      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Tuple		,	_UpperCAmelCase      :		Dict		,	_UpperCAmelCase      :		int		,	_UpperCAmelCase      :		Union[str, Any]		,	_UpperCAmelCase      :		Dict=None		,	_UpperCAmelCase      :		Tuple=False      )  ->    int:





								'''simple docstring'''




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

