



import multiprocessing
import os
from typing import BinaryIO, Optional, Union

import fsspec

from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.json.json import Json
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader



class 						UpperCAmelCase_					( a):







							def __init__(     self,    __a,    __a = None,    __a = None,    __a = None,    __a = False,    __a = False,    __a = None,    __a = None,    **__a,    ):

														'''simple docstring'''

														super().__init__(
														    __a,    split=__a,    features=__a,    cache_dir=__a,    keep_in_memory=__a,    streaming=__a,    num_proc=__a,    **__a,    )
														_lowerCAmelCase  :							List[Any]				     =					field
														_lowerCAmelCase  :							Tuple				     =					path_or_paths if isinstance(__a,    __a) else {self.split: path_or_paths}
														_lowerCAmelCase  :							str				     =					Json(
														    cache_dir=__a,    data_files=__a,    features=__a,    field=__a,    **__a,    )







							def      snake_case__   (     self):

														'''simple docstring'''

														if self.streaming:
																					_lowerCAmelCase  :							List[Any]				     =					self.builder.as_streaming_dataset(split=self.split)
														# Build regular (map-style) dataset
														else:
																					_lowerCAmelCase  :							Optional[Any]				     =					None
																					_lowerCAmelCase  :							str				     =					None
																					_lowerCAmelCase  :							Optional[int]				     =					None
																					_lowerCAmelCase  :							Union[str, Any]				     =					None

																					self.builder.download_and_prepare(
																					    download_config=__a,    download_mode=__a,    verification_mode=__a,    base_path=__a,    num_proc=self.num_proc,    )
																					_lowerCAmelCase  :							Optional[Any]				     =					self.builder.as_dataset(
																					    split=self.split,    verification_mode=__a,    in_memory=self.keep_in_memory)
														return dataset



class 						UpperCAmelCase_					:







							def __init__(     self,    __a,    __a,    __a = None,    __a = None,    **__a,    ):

														'''simple docstring'''

														if num_proc is not None and num_proc <= 0:
																					raise ValueError(f"num_proc {num_proc} must be an integer > 0.")

														_lowerCAmelCase  :							int				     =					dataset
														_lowerCAmelCase  :							Dict				     =					path_or_buf
														_lowerCAmelCase  :							Any				     =					batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
														_lowerCAmelCase  :							int				     =					num_proc
														_lowerCAmelCase  :							Dict				     =					"utf-8"
														_lowerCAmelCase  :							List[str]				     =					to_json_kwargs







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Optional[int]				     =					self.to_json_kwargs.pop("path_or_buf",    __a)
														_lowerCAmelCase  :							List[Any]				     =					self.to_json_kwargs.pop("orient",    "records")
														_lowerCAmelCase  :							int				     =					self.to_json_kwargs.pop("lines",    True if orient == "records" else False)
														_lowerCAmelCase  :							List[Any]				     =					self.to_json_kwargs.pop("index",    False if orient in ["split", "table"] else True)
														_lowerCAmelCase  :							Dict				     =					self.to_json_kwargs.pop("compression",    __a)

														if compression not in [None, "infer", "gzip", "bz2", "xz"]:
																					raise NotImplementedError(f"`datasets` currently does not support {compression} compression")

														if isinstance(self.path_or_buf,    (str, bytes, os.PathLike)):
																					with fsspec.open(self.path_or_buf,    "wb",    compression=__a) as buffer:
																												_lowerCAmelCase  :							Dict				     =					self._write(file_obj=__a,    orient=__a,    lines=__a,    index=__a,    **self.to_json_kwargs)
														else:
																					if compression:
																												raise NotImplementedError(
																												    f"The compression parameter is not supported when writing to a buffer, but compression={compression}"
																												    " was passed. Please provide a local path instead.")
																					_lowerCAmelCase  :							Tuple				     =					self._write(
																					    file_obj=self.path_or_buf,    orient=__a,    lines=__a,    index=__a,    **self.to_json_kwargs)
														return written







							def      snake_case__   (     self,    __a):

														'''simple docstring'''

														_lowerCAmelCase  :							Optional[int]				     =					args

														_lowerCAmelCase  :							Optional[int]				     =					query_table(
														    table=self.dataset.data,    key=slice(__a,    offset + self.batch_size),    indices=self.dataset._indices,    )
														_lowerCAmelCase  :							str				     =					batch.to_pandas().to_json(
														    path_or_buf=__a,    orient=__a,    lines=__a,    index=__a,    **__a)
														if not json_str.endswith("\n"):
																					json_str += "\n"
														return json_str.encode(self.encoding)







							def      snake_case__   (     self,    __a,    __a,    __a,    __a,    **__a,    ):

														'''simple docstring'''

														_lowerCAmelCase  :							Optional[int]				     =					0

														if self.num_proc is None or self.num_proc == 1:
																					for offset in logging.tqdm(
																					    range(0,    len(self.dataset),    self.batch_size),    unit="ba",    disable=not logging.is_progress_bar_enabled(),    desc="Creating json from Arrow format",    ):
																												_lowerCAmelCase  :							Any				     =					self._batch_json((offset, orient, lines, index, to_json_kwargs))
																												written += file_obj.write(__a)
														else:
																					_lowerCAmelCase  :							Tuple				     =					len(self.dataset), self.batch_size
																					with multiprocessing.Pool(self.num_proc) as pool:
																												for json_str in logging.tqdm(
																												    pool.imap(
																												        self._batch_json,    [(offset, orient, lines, index, to_json_kwargs) for offset in range(0,    __a,    __a)],    ),    total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size,    unit="ba",    disable=not logging.is_progress_bar_enabled(),    desc="Creating json from Arrow format",    ):
																																			written += file_obj.write(__a)

														return written





import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


_snake_case	=						"\\n@INPROCEEDINGS{Papineni02bleu:a,\n    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n    booktitle = {},\n    year = {2002},\n    pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n    title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n    author = \"Lin, Chin-Yew  and\n      Och, Franz Josef\",\n    booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n    month = \"aug 23{--}aug 27\",\n    year = \"2004\",\n    address = \"Geneva, Switzerland\",\n    publisher = \"COLING\",\n    url = \"https://www.aclweb.org/anthology/C04-1072\",\n    pages = \"501--507\",\n}\n"

_snake_case	=						"\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n"

_snake_case	=						"\nComputes BLEU score of translated segments against one or more references.\nArgs:\n    predictions: list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    max_order: Maximum n-gram order to use when computing BLEU score.\n    smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n    'bleu': bleu score,\n    'precisions': geometric mean of n-gram precisions,\n    'brevity_penalty': brevity penalty,\n    'length_ratio': ratio of lengths,\n    'translation_length': translation_length,\n    'reference_length': reference_length\nExamples:\n\n    >>> predictions = [\n    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample\n    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample\n    ... ]\n    >>> references = [\n    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)\n    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)\n    ... ]\n    >>> bleu = datasets.load_metric(\"bleu\")\n    >>> results = bleu.compute(predictions=predictions, references=references)\n    >>> print(results[\"bleu\"])\n    1.0\n"



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,      _KWARGS_DESCRIPTION)
class 						UpperCAmelCase_					( datasets.Metric):







							def      snake_case__   (     self):

														'''simple docstring'''

														return datasets.MetricInfo(
														    description=_DESCRIPTION,    citation=_CITATION,    inputs_description=_KWARGS_DESCRIPTION,    features=datasets.Features(
														        {
														            "predictions": datasets.Sequence(datasets.Value("string",    id="token"),    id="sequence"),
														            "references": datasets.Sequence(
														                datasets.Sequence(datasets.Value("string",    id="token"),    id="sequence"),    id="references"),
														        }),    codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"],    reference_urls=[
														        "https://en.wikipedia.org/wiki/BLEU",
														        "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213",
														    ],    )







							def      snake_case__   (     self,    __a,    __a,    __a=4,    __a=False):

														'''simple docstring'''

														_lowerCAmelCase  :							List[str]				     =					compute_bleu(
														    reference_corpus=__a,    translation_corpus=__a,    max_order=__a,    smooth=__a)
														((_lowerCAmelCase)     ,					(_lowerCAmelCase)     ,					(_lowerCAmelCase)     ,					(_lowerCAmelCase)     ,					(_lowerCAmelCase)     ,					(_lowerCAmelCase))  :							Dict				     =					score
														return {
														    "bleu": bleu,
														    "precisions": precisions,
														    "brevity_penalty": bp,
														    "length_ratio": ratio,
														    "translation_length": translation_length,
														    "reference_length": reference_length,
														}
