diff --git a/ckpts/llama-3b/global_step100/bf16_zero_pp_rank_185_mp_rank_03_optim_states.pt b/ckpts/llama-3b/global_step100/bf16_zero_pp_rank_185_mp_rank_03_optim_states.pt new file mode 100644 index 0000000000000000000000000000000000000000..cf456b1ace9fef679695df5e32aba34e1770959b --- /dev/null +++ b/ckpts/llama-3b/global_step100/bf16_zero_pp_rank_185_mp_rank_03_optim_states.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f11ad3c628f3b289310485e8b4e321494534e97bf89b0783ae3e28e7190e95c +size 41830468 diff --git a/ckpts/llama-3b/global_step100/bf16_zero_pp_rank_46_mp_rank_03_optim_states.pt b/ckpts/llama-3b/global_step100/bf16_zero_pp_rank_46_mp_rank_03_optim_states.pt new file mode 100644 index 0000000000000000000000000000000000000000..4dae9317e5d6705b39bc51831bb9b1153fa7f31f --- /dev/null +++ b/ckpts/llama-3b/global_step100/bf16_zero_pp_rank_46_mp_rank_03_optim_states.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5adc5ccdc0be2c82049e8e3acc48c781f74f0e7e2d9fe9a3c8b7e6e12318ec4 +size 41830330 diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__init__.py b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb6c2d0a1556d8119d3b400a9adcff73b34e6e5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__init__.py @@ -0,0 +1,20 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ruff: noqa: F401 +"""Contains helpers to serialize tensors.""" + +from ._base import StateDictSplit, split_state_dict_into_shards_factory +from ._numpy import split_numpy_state_dict_into_shards +from ._tensorflow import split_tf_state_dict_into_shards +from ._torch import split_torch_state_dict_into_shards diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60c4e34ab37da24c8839ee35665ad1e3783c1d1c Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_base.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..418af0de338aa4f0d1ca5d65997dfe78068ef352 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_numpy.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_numpy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45aaba0c41c5645dbba439a5f6a17995c52ad9e3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_numpy.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_tensorflow.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_tensorflow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66c43f9af3160c8b0b1763ed4ed019997493765e Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_tensorflow.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_torch.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_torch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b0178ea1784af1a3be25619cdeb44c36aae7c52 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/__pycache__/_torch.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_base.py b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a7f7bba89263d31d5facb1ebed66c5f701dba973 --- /dev/null +++ b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_base.py @@ -0,0 +1,169 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains helpers to split tensors into shards.""" + +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, List, Optional, TypeVar + +from .. import logging + + +TensorT = TypeVar("TensorT") +TensorSizeFn_T = Callable[[TensorT], int] +StorageIDFn_T = Callable[[TensorT], Optional[Any]] + +MAX_SHARD_SIZE = 5_000_000_000 # 5GB +FILENAME_PATTERN = "model{suffix}.safetensors" + +logger = logging.get_logger(__file__) + + +@dataclass +class StateDictSplit: + is_sharded: bool = field(init=False) + metadata: Dict[str, Any] + filename_to_tensors: Dict[str, List[str]] + tensor_to_filename: Dict[str, str] + + def __post_init__(self): + self.is_sharded = len(self.filename_to_tensors) > 1 + + +def split_state_dict_into_shards_factory( + state_dict: Dict[str, TensorT], + *, + get_tensor_size: TensorSizeFn_T, + get_storage_id: StorageIDFn_T = lambda tensor: None, + filename_pattern: str = FILENAME_PATTERN, + max_shard_size: int = MAX_SHARD_SIZE, +) -> StateDictSplit: + """ + Split a model state dictionary in shards so that each shard is smaller than a given size. + + The shards are determined by iterating through the `state_dict` in the order of its keys. There is no optimization + made to make each shard as close as possible to the maximum size passed. For example, if the limit is 10GB and we + have tensors of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not + [6+2+2GB], [6+2GB], [6GB]. + + + + If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a + size greater than `max_shard_size`. + + + + Args: + state_dict (`Dict[str, Tensor]`): + The state dictionary to save. + get_tensor_size (`Callable[[Tensor], int]`): + A function that returns the size of a tensor in bytes. + get_storage_id (`Callable[[Tensor], Optional[Any]]`, *optional*): + A function that returns a unique identifier to a tensor storage. Multiple different tensors can share the + same underlying storage. This identifier is guaranteed to be unique and constant for this tensor's storage + during its lifetime. Two tensor storages with non-overlapping lifetimes may have the same id. + filename_pattern (`str`, *optional*): + The pattern to generate the files names in which the model will be saved. Pattern must be a string that + can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix` + Defaults to `"model{suffix}.safetensors"`. + max_shard_size (`int` or `str`, *optional*): + The maximum size of each shard, in bytes. Defaults to 5GB. + + Returns: + [`StateDictSplit`]: A `StateDictSplit` object containing the shards and the index to retrieve them. + """ + storage_id_to_tensors: Dict[Any, List[str]] = {} + + shard_list: List[Dict[str, TensorT]] = [] + current_shard: Dict[str, TensorT] = {} + current_shard_size = 0 + total_size = 0 + + for key, tensor in state_dict.items(): + # when bnb serialization is used the weights in the state dict can be strings + # check: https://github.com/huggingface/transformers/pull/24416 for more details + if isinstance(tensor, str): + logger.info("Skipping tensor %s as it is a string (bnb serialization)", key) + continue + + # If a `tensor` shares the same underlying storage as another tensor, we put `tensor` in the same `block` + storage_id = get_storage_id(tensor) + if storage_id is not None: + if storage_id in storage_id_to_tensors: + # We skip this tensor for now and will reassign to correct shard later + storage_id_to_tensors[storage_id].append(key) + continue + else: + # This is the first tensor with this storage_id, we create a new entry + # in the storage_id_to_tensors dict => we will assign the shard id later + storage_id_to_tensors[storage_id] = [key] + + # Compute tensor size + tensor_size = get_tensor_size(tensor) + + # If this tensor is bigger than the maximal size, we put it in its own shard + if tensor_size > max_shard_size: + total_size += tensor_size + shard_list.append({key: tensor}) + continue + + # If this tensor is going to tip up over the maximal size, we split. + # Current shard already has some tensors, we add it to the list of shards and create a new one. + if current_shard_size + tensor_size > max_shard_size: + shard_list.append(current_shard) + current_shard = {} + current_shard_size = 0 + + # Add the tensor to the current shard + current_shard[key] = tensor + current_shard_size += tensor_size + total_size += tensor_size + + # Add the last shard + if len(current_shard) > 0: + shard_list.append(current_shard) + nb_shards = len(shard_list) + + # Loop over the tensors that share the same storage and assign them together + for storage_id, keys in storage_id_to_tensors.items(): + # Let's try to find the shard where the first tensor of this storage is and put all tensors in the same shard + for shard in shard_list: + if keys[0] in shard: + for key in keys: + shard[key] = state_dict[key] + break + + # If we only have one shard, we return it => no need to build the index + if nb_shards == 1: + filename = filename_pattern.format(suffix="") + return StateDictSplit( + metadata={"total_size": total_size}, + filename_to_tensors={filename: list(state_dict.keys())}, + tensor_to_filename={key: filename for key in state_dict.keys()}, + ) + + # Now that each tensor is assigned to a shard, let's assign a filename to each shard + tensor_name_to_filename = {} + filename_to_tensors = {} + for idx, shard in enumerate(shard_list): + filename = filename_pattern.format(suffix=f"-{idx+1:05d}-of-{nb_shards:05d}") + for key in shard: + tensor_name_to_filename[key] = filename + filename_to_tensors[filename] = list(shard.keys()) + + # Build the index and return + return StateDictSplit( + metadata={"total_size": total_size}, + filename_to_tensors=filename_to_tensors, + tensor_to_filename=tensor_name_to_filename, + ) diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_numpy.py b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..214c77d9acde2a14069f403ed337e6c8c57047ad --- /dev/null +++ b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_numpy.py @@ -0,0 +1,68 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains numpy-specific helpers.""" + +from typing import TYPE_CHECKING, Dict + +from ._base import FILENAME_PATTERN, MAX_SHARD_SIZE, StateDictSplit, split_state_dict_into_shards_factory + + +if TYPE_CHECKING: + import numpy as np + + +def split_numpy_state_dict_into_shards( + state_dict: Dict[str, "np.ndarray"], + *, + filename_pattern: str = FILENAME_PATTERN, + max_shard_size: int = MAX_SHARD_SIZE, +) -> StateDictSplit: + """ + Split a model state dictionary in shards so that each shard is smaller than a given size. + + The shards are determined by iterating through the `state_dict` in the order of its keys. There is no optimization + made to make each shard as close as possible to the maximum size passed. For example, if the limit is 10GB and we + have tensors of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not + [6+2+2GB], [6+2GB], [6GB]. + + + + If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a + size greater than `max_shard_size`. + + + + Args: + state_dict (`Dict[str, np.ndarray]`): + The state dictionary to save. + filename_pattern (`str`, *optional*): + The pattern to generate the files names in which the model will be saved. Pattern must be a string that + can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix` + Defaults to `"model{suffix}.safetensors"`. + max_shard_size (`int` or `str`, *optional*): + The maximum size of each shard, in bytes. Defaults to 5GB. + + Returns: + [`StateDictSplit`]: A `StateDictSplit` object containing the shards and the index to retrieve them. + """ + return split_state_dict_into_shards_factory( + state_dict, + max_shard_size=max_shard_size, + filename_pattern=filename_pattern, + get_tensor_size=get_tensor_size, + ) + + +def get_tensor_size(tensor: "np.ndarray") -> int: + return tensor.nbytes diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_tensorflow.py b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..f8d752c083063d3e9772b69982e8f979fbda53ea --- /dev/null +++ b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_tensorflow.py @@ -0,0 +1,94 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains tensorflow-specific helpers.""" + +import math +import re +from typing import TYPE_CHECKING, Dict + +from ._base import MAX_SHARD_SIZE, StateDictSplit, split_state_dict_into_shards_factory + + +if TYPE_CHECKING: + import tensorflow as tf + + +def split_tf_state_dict_into_shards( + state_dict: Dict[str, "tf.Tensor"], + *, + filename_pattern: str = "tf_model{suffix}.h5", + max_shard_size: int = MAX_SHARD_SIZE, +) -> StateDictSplit: + """ + Split a model state dictionary in shards so that each shard is smaller than a given size. + + The shards are determined by iterating through the `state_dict` in the order of its keys. There is no optimization + made to make each shard as close as possible to the maximum size passed. For example, if the limit is 10GB and we + have tensors of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not + [6+2+2GB], [6+2GB], [6GB]. + + + + If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a + size greater than `max_shard_size`. + + + + Args: + state_dict (`Dict[str, Tensor]`): + The state dictionary to save. + filename_pattern (`str`, *optional*): + The pattern to generate the files names in which the model will be saved. Pattern must be a string that + can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix` + Defaults to `"tf_model{suffix}.h5"`. + max_shard_size (`int` or `str`, *optional*): + The maximum size of each shard, in bytes. Defaults to 5GB. + + Returns: + [`StateDictSplit`]: A `StateDictSplit` object containing the shards and the index to retrieve them. + """ + return split_state_dict_into_shards_factory( + state_dict, + max_shard_size=max_shard_size, + filename_pattern=filename_pattern, + get_tensor_size=get_tensor_size, + ) + + +def get_tensor_size(tensor: "tf.Tensor") -> int: + # Return `math.ceil` since dtype byte size can be a float (e.g., 0.125 for tf.bool). + # Better to overestimate than underestimate. + return math.ceil(tensor.numpy().size * _dtype_byte_size_tf(tensor.dtype)) + + +def _dtype_byte_size_tf(dtype) -> float: + """ + Returns the size (in bytes) occupied by one parameter of type `dtype`. + Taken from https://github.com/huggingface/transformers/blob/74d9d0cebb0263a3f8ab9c280569170cc74651d0/src/transformers/modeling_tf_utils.py#L608. + NOTE: why not `tensor.numpy().nbytes`? + Example: + ```py + >>> _dtype_byte_size(tf.float32) + 4 + ``` + """ + import tensorflow as tf + + if dtype == tf.bool: + return 1 / 8 + bit_search = re.search(r"[^\d](\d+)$", dtype.name) + if bit_search is None: + raise ValueError(f"`dtype` is not a valid dtype: {dtype}.") + bit_size = int(bit_search.groups()[0]) + return bit_size // 8 diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_torch.py b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..00ab7e2c80d7a8fde928588c284213fca2100cf3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/huggingface_hub/serialization/_torch.py @@ -0,0 +1,200 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains pytorch-specific helpers.""" + +import importlib +from functools import lru_cache +from typing import TYPE_CHECKING, Dict, Tuple + +from ._base import FILENAME_PATTERN, MAX_SHARD_SIZE, StateDictSplit, split_state_dict_into_shards_factory + + +if TYPE_CHECKING: + import torch + + +def split_torch_state_dict_into_shards( + state_dict: Dict[str, "torch.Tensor"], + *, + filename_pattern: str = FILENAME_PATTERN, + max_shard_size: int = MAX_SHARD_SIZE, +) -> StateDictSplit: + """ + Split a model state dictionary in shards so that each shard is smaller than a given size. + + The shards are determined by iterating through the `state_dict` in the order of its keys. There is no optimization + made to make each shard as close as possible to the maximum size passed. For example, if the limit is 10GB and we + have tensors of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not + [6+2+2GB], [6+2GB], [6GB]. + + + + If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a + size greater than `max_shard_size`. + + + + Args: + state_dict (`Dict[str, torch.Tensor]`): + The state dictionary to save. + filename_pattern (`str`, *optional*): + The pattern to generate the files names in which the model will be saved. Pattern must be a string that + can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix` + Defaults to `"model{suffix}.safetensors"`. + max_shard_size (`int` or `str`, *optional*): + The maximum size of each shard, in bytes. Defaults to 5GB. + + Returns: + [`StateDictSplit`]: A `StateDictSplit` object containing the shards and the index to retrieve them. + + Example: + ```py + >>> import json + >>> import os + >>> from safetensors.torch import save_file as safe_save_file + >>> from huggingface_hub import split_torch_state_dict_into_shards + + >>> def save_state_dict(state_dict: Dict[str, torch.Tensor], save_directory: str): + ... state_dict_split = split_torch_state_dict_into_shards(state_dict) + ... for filename, tensors in state_dict_split.filename_to_tensors.values(): + ... shard = {tensor: state_dict[tensor] for tensor in tensors} + ... safe_save_file( + ... shard, + ... os.path.join(save_directory, filename), + ... metadata={"format": "pt"}, + ... ) + ... if state_dict_split.is_sharded: + ... index = { + ... "metadata": state_dict_split.metadata, + ... "weight_map": state_dict_split.tensor_to_filename, + ... } + ... with open(os.path.join(save_directory, "model.safetensors.index.json"), "w") as f: + ... f.write(json.dumps(index, indent=2)) + ``` + """ + return split_state_dict_into_shards_factory( + state_dict, + max_shard_size=max_shard_size, + filename_pattern=filename_pattern, + get_tensor_size=get_tensor_size, + get_storage_id=get_storage_id, + ) + + +def get_storage_id(tensor: "torch.Tensor") -> Tuple["torch.device", int, int]: + """ + Return unique identifier to a tensor storage. + + Multiple different tensors can share the same underlying storage. For + example, "meta" tensors all share the same storage, and thus their identifier will all be equal. This identifier is + guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with + non-overlapping lifetimes may have the same id. + + Taken from https://github.com/huggingface/transformers/blob/1ecf5f7c982d761b4daaa96719d162c324187c64/src/transformers/pytorch_utils.py#L278. + """ + if tensor.device.type == "xla" and is_torch_tpu_available(): + # NOTE: xla tensors dont have storage + # use some other unique id to distinguish. + # this is a XLA tensor, it must be created using torch_xla's + # device. So the following import is safe: + import torch_xla + + unique_id = torch_xla._XLAC._xla_get_tensor_id(tensor) + else: + unique_id = storage_ptr(tensor) + + return tensor.device, unique_id, get_storage_size(tensor) + + +def get_tensor_size(tensor: "torch.Tensor") -> int: + return tensor.numel() * tensor.element_size() + + +@lru_cache() +def is_torch_tpu_available(check_device=True): + """ + Checks if `torch_xla` is installed and potentially if a TPU is in the environment + + Taken from https://github.com/huggingface/transformers/blob/1ecf5f7c982d761b4daaa96719d162c324187c64/src/transformers/utils/import_utils.py#L463. + """ + if importlib.util.find_spec("torch_xla") is not None: + if check_device: + # We need to check if `xla_device` can be found, will raise a RuntimeError if not + try: + import torch_xla.core.xla_model as xm + + _ = xm.xla_device() + return True + except RuntimeError: + return False + return True + return False + + +def storage_ptr(tensor: "torch.Tensor") -> int: + """ + Taken from https://github.com/huggingface/safetensors/blob/08db34094e9e59e2f9218f2df133b7b4aaff5a99/bindings/python/py_src/safetensors/torch.py#L11C1-L20C21. + """ + try: + return tensor.untyped_storage().data_ptr() + except Exception: + # Fallback for torch==1.10 + try: + return tensor.storage().data_ptr() + except NotImplementedError: + # Fallback for meta storage + return 0 + + +def get_storage_size(tensor: "torch.Tensor") -> int: + """ + Taken from https://github.com/huggingface/safetensors/blob/08db34094e9e59e2f9218f2df133b7b4aaff5a99/bindings/python/py_src/safetensors/torch.py#L31C1-L41C59 + """ + try: + return tensor.untyped_storage().nbytes() + except AttributeError: + # Fallback for torch==1.10 + try: + return tensor.storage().size() * _get_dtype_size(tensor.dtype) + except NotImplementedError: + # Fallback for meta storage + # On torch >=2.0 this is the tensor size + return tensor.nelement() * _get_dtype_size(tensor.dtype) + + +@lru_cache() +def _get_dtype_size(dtype: "torch.dtype") -> int: + """ + Taken from https://github.com/huggingface/safetensors/blob/08db34094e9e59e2f9218f2df133b7b4aaff5a99/bindings/python/py_src/safetensors/torch.py#L344 + """ + import torch + + # torch.float8 formats require 2.1; we do not support these dtypes on earlier versions + _float8_e4m3fn = getattr(torch, "float8_e4m3fn", None) + _float8_e5m2 = getattr(torch, "float8_e5m2", None) + _SIZE = { + torch.int64: 8, + torch.float32: 4, + torch.int32: 4, + torch.bfloat16: 2, + torch.float16: 2, + torch.int16: 2, + torch.uint8: 1, + torch.int8: 1, + torch.bool: 1, + torch.float64: 8, + _float8_e4m3fn: 1, + _float8_e5m2: 1, + } + return _SIZE[dtype] diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be8a3b1641a79c6fb527704ece3999618f63813a Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_cache_assets.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_cache_assets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1531117fac12a73b971ecc4269efc2af5434679e Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_cache_assets.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_cache_manager.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_cache_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17627042fe6ab45e8fffb9d048253389d26985a7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_cache_manager.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_chunk_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_chunk_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cca13004c86cf9858fe4502c33cb7d80cc5dddcd Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_chunk_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_datetime.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_datetime.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..664ae4f529a9dcc9ef02fe02dc6597eede029804 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_datetime.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_deprecation.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16695f3bd737f17b839867eb73dd230eab71bf65 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_deprecation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_errors.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_errors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fb3ce134b7c3d900b672cb96800ad1690b9025a Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_errors.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_experimental.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_experimental.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5550f02e787ef6dc89611ff32f34f4c8f811bf6b Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_experimental.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd77c62345d45ed172e74927e41c1e83bfe0e14f Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_git_credential.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_git_credential.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75bf989296e45ab373d2ec6640fb5e96d09193e8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_git_credential.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_hf_folder.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_hf_folder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfdd43066226fa561cf58a0939d81c82966661c7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_hf_folder.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_http.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_http.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2037d5f0993e2ebf7cbdd93154dc75f80af438b5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_http.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_runtime.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_runtime.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..680c563b9b3bdb3b2056ec87191ffa95dbbb479f Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_runtime.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_safetensors.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_safetensors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8549527d7a6a4e60314776b959adf93b4f17586a Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_safetensors.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_subprocess.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_subprocess.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc8e7165ee906cc3fb4066ef10aa8fdf5611b78d Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_subprocess.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_telemetry.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_telemetry.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75c011abb988f62c5049474dcf6cc909178c3e94 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_telemetry.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d15e9964309906b02f3101fe08401071c8583ec9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_typing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8da2e35ccefc214c56b13960ff7516402f7649c9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_typing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_validators.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_validators.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b00a86a6a6b6e796d62520b3483356d3ff35b870 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/_validators.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/endpoint_helpers.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/endpoint_helpers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c95ab158ed76f7c9794001d0218ecc461dcc39e Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/endpoint_helpers.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28ae22315cac98fb9f955b84c6e7712b11074367 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/sha.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/sha.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a9344c69f86b859dc238c53164f9aed21a4a8d9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/sha.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/tqdm.cpython-310.pyc b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/tqdm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3db6495bdef6c2c861ad64742916ebaac54a3e15 Binary files /dev/null and b/venv/lib/python3.10/site-packages/huggingface_hub/utils/__pycache__/tqdm.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/__init__.py b/venv/lib/python3.10/site-packages/sacrebleu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d7fa3d7dd3835568205cce19933a793c8fe9660 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/__init__.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Copyright 2017--2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You may not +# use this file except in compliance with the License. A copy of the License +# is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is distributed on +# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +# express or implied. See the License for the specific language governing +# permissions and limitations under the License. + +__version__ = '2.4.2' +__description__ = 'Hassle-free computation of shareable, comparable, and reproducible BLEU, chrF, and TER scores' + + +from .utils import smart_open, SACREBLEU_DIR, download_test_set +from .utils import get_source_file, get_reference_files +from .utils import get_available_testsets, get_langpairs_for_testset +from .metrics.helpers import extract_word_ngrams, extract_char_ngrams +from .dataset import DATASETS +from .metrics import BLEU, CHRF, TER + +# Backward compatibility functions for old style API access (<= 1.4.10) +from .compat import corpus_bleu, raw_corpus_bleu, sentence_bleu +from .compat import corpus_chrf, sentence_chrf +from .compat import corpus_ter, sentence_ter + +__all__ = [ + 'smart_open', 'SACREBLEU_DIR', 'download_test_set', + 'get_source_file', 'get_reference_files', + 'get_available_testsets', 'get_langpairs_for_testset', + 'extract_word_ngrams', 'extract_char_ngrams', + 'DATASETS', + 'BLEU', 'CHRF', 'TER', + 'corpus_bleu', 'raw_corpus_bleu', 'sentence_bleu', + 'corpus_chrf', 'sentence_chrf', + 'corpus_ter', 'sentence_ter' +] diff --git a/venv/lib/python3.10/site-packages/sacrebleu/__main__.py b/venv/lib/python3.10/site-packages/sacrebleu/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..3833741e8076dbac776a383f8e05ce8cafaac92e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/__main__.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Copyright 2017--2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You may not +# use this file except in compliance with the License. A copy of the License +# is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is distributed on +# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +# express or implied. See the License for the specific language governing +# permissions and limitations under the License. + +""" +SacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores. +Inspired by Rico Sennrich's `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text. +It also knows all the standard test sets and handles downloading, processing, and tokenization for you. + +See the [README.md] file for more information. +""" +from .sacrebleu import main + +if __name__ == '__main__': + main() diff --git a/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24d386d261557968d27d495c37cf8d86863d941d Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/__main__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e31fa89472b18cb0b89059a63bfd0a8cad1a78c6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/__main__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/compat.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/compat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38d27fab56d4fa0b760789aa3e67efe6d1aff6df Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/compat.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/sacrebleu.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/sacrebleu.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70b322e4a261f5b148623bf009e69e3464a9f30a Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/sacrebleu.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/significance.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/significance.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ceb0e5ec982ec9eee8881a3efe7470ee69c8cdd2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/significance.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bf60f497a3ca71c953550393f6234a7a4c98e93 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/compat.py b/venv/lib/python3.10/site-packages/sacrebleu/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..573596037928ddc5b8c5b8df99202c13f0681943 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/compat.py @@ -0,0 +1,205 @@ +from typing import Sequence, Optional + +from .metrics import BLEU, CHRF, TER, BLEUScore, CHRFScore, TERScore + + +###################################################################### +# Backward compatibility functions for old style API access (< 1.4.11) +###################################################################### +def corpus_bleu(hypotheses: Sequence[str], + references: Sequence[Sequence[str]], + smooth_method='exp', + smooth_value=None, + force=False, + lowercase=False, + tokenize=BLEU.TOKENIZER_DEFAULT, + use_effective_order=False) -> BLEUScore: + """Computes BLEU for a corpus against a single (or multiple) reference(s). + This is the main CLI entry point for computing BLEU between a system output + and a reference sentence. + + :param hypotheses: A sequence of hypothesis strings. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. + :param smooth_method: The smoothing method to use ('floor', 'add-k', 'exp' or 'none') + :param smooth_value: The smoothing value for `floor` and `add-k` methods. `None` falls back to default value. + :param force: Ignore data that looks already tokenized + :param lowercase: Lowercase the data + :param tokenize: The tokenizer to use + :param use_effective_order: Don't take into account n-gram orders without any match. + :return: a `BLEUScore` object + """ + metric = BLEU( + lowercase=lowercase, force=force, tokenize=tokenize, + smooth_method=smooth_method, smooth_value=smooth_value, + effective_order=use_effective_order) + + return metric.corpus_score(hypotheses, references) + + +def raw_corpus_bleu(hypotheses: Sequence[str], + references: Sequence[Sequence[str]], + smooth_value: Optional[float] = BLEU.SMOOTH_DEFAULTS['floor']) -> BLEUScore: + """Computes BLEU for a corpus against a single (or multiple) reference(s). + This convenience function assumes a particular set of arguments i.e. + it disables tokenization and applies a `floor` smoothing with value `0.1`. + + This convenience call does not apply any tokenization at all, + neither to the system output nor the reference. It just computes + BLEU on the "raw corpus" (hence the name). + + :param hypotheses: A sequence of hypothesis strings. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. + :param smooth_value: The smoothing value for `floor`. If not given, the default of 0.1 is used. + :return: Returns a `BLEUScore` object. + + """ + return corpus_bleu( + hypotheses, references, smooth_method='floor', + smooth_value=smooth_value, force=True, tokenize='none', + use_effective_order=True) + + +def sentence_bleu(hypothesis: str, + references: Sequence[str], + smooth_method: str = 'exp', + smooth_value: Optional[float] = None, + lowercase: bool = False, + tokenize=BLEU.TOKENIZER_DEFAULT, + use_effective_order: bool = True) -> BLEUScore: + """ + Computes BLEU for a single sentence against a single (or multiple) reference(s). + + Disclaimer: Computing BLEU at the sentence level is not its intended use as + BLEU is a corpus-level metric. + + :param hypothesis: A single hypothesis string. + :param references: A sequence of reference strings. + :param smooth_method: The smoothing method to use ('floor', 'add-k', 'exp' or 'none') + :param smooth_value: The smoothing value for `floor` and `add-k` methods. `None` falls back to default value. + :param lowercase: Lowercase the data + :param tokenize: The tokenizer to use + :param use_effective_order: Don't take into account n-gram orders without any match. + :return: Returns a `BLEUScore` object. + """ + metric = BLEU( + lowercase=lowercase, tokenize=tokenize, force=False, + smooth_method=smooth_method, smooth_value=smooth_value, + effective_order=use_effective_order) + + return metric.sentence_score(hypothesis, references) + + +def corpus_chrf(hypotheses: Sequence[str], + references: Sequence[Sequence[str]], + char_order: int = CHRF.CHAR_ORDER, + word_order: int = CHRF.WORD_ORDER, + beta: int = CHRF.BETA, + remove_whitespace: bool = True, + eps_smoothing: bool = False) -> CHRFScore: + """ + Computes chrF for a corpus against a single (or multiple) reference(s). + If `word_order` equals to 2, the metric is referred to as chrF++. + + :param hypotheses: A sequence of hypothesis strings. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. + :param char_order: Character n-gram order. + :param word_order: Word n-gram order. If equals to 2, the metric is referred to as chrF++. + :param beta: Determine the importance of recall w.r.t precision. + :param eps_smoothing: If `True`, applies epsilon smoothing similar + to reference chrF++.py, NLTK and Moses implementations. Otherwise, + it takes into account effective match order similar to sacreBLEU < 2.0.0. + :param remove_whitespace: If `True`, removes whitespaces prior to character n-gram extraction. + :return: A `CHRFScore` object. + """ + metric = CHRF( + char_order=char_order, + word_order=word_order, + beta=beta, + whitespace=not remove_whitespace, + eps_smoothing=eps_smoothing) + return metric.corpus_score(hypotheses, references) + + +def sentence_chrf(hypothesis: str, + references: Sequence[str], + char_order: int = CHRF.CHAR_ORDER, + word_order: int = CHRF.WORD_ORDER, + beta: int = CHRF.BETA, + remove_whitespace: bool = True, + eps_smoothing: bool = False) -> CHRFScore: + """ + Computes chrF for a single sentence against a single (or multiple) reference(s). + If `word_order` equals to 2, the metric is referred to as chrF++. + + :param hypothesis: A single hypothesis string. + :param references: A sequence of reference strings. + :param char_order: Character n-gram order. + :param word_order: Word n-gram order. If equals to 2, the metric is referred to as chrF++. + :param beta: Determine the importance of recall w.r.t precision. + :param eps_smoothing: If `True`, applies epsilon smoothing similar + to reference chrF++.py, NLTK and Moses implementations. Otherwise, + it takes into account effective match order similar to sacreBLEU < 2.0.0. + :param remove_whitespace: If `True`, removes whitespaces prior to character n-gram extraction. + :return: A `CHRFScore` object. + """ + metric = CHRF( + char_order=char_order, + word_order=word_order, + beta=beta, + whitespace=not remove_whitespace, + eps_smoothing=eps_smoothing) + return metric.sentence_score(hypothesis, references) + + +def corpus_ter(hypotheses: Sequence[str], + references: Sequence[Sequence[str]], + normalized: bool = False, + no_punct: bool = False, + asian_support: bool = False, + case_sensitive: bool = False) -> TERScore: + """ + Computes TER for a corpus against a single (or multiple) reference(s). + + :param hypotheses: A sequence of hypothesis strings. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. + :param normalized: Enable character normalization. + :param no_punct: Remove punctuation. + :param asian_support: Enable special treatment of Asian characters. + :param case_sensitive: Enables case-sensitivity. + :return: A `TERScore` object. + """ + metric = TER( + normalized=normalized, + no_punct=no_punct, + asian_support=asian_support, + case_sensitive=case_sensitive) + return metric.corpus_score(hypotheses, references) + + +def sentence_ter(hypothesis: str, + references: Sequence[str], + normalized: bool = False, + no_punct: bool = False, + asian_support: bool = False, + case_sensitive: bool = False) -> TERScore: + """ + Computes TER for a single hypothesis against a single (or multiple) reference(s). + + :param hypothesis: A single hypothesis string. + :param references: A sequence of reference strings. + :param normalized: Enable character normalization. + :param no_punct: Remove punctuation. + :param asian_support: Enable special treatment of Asian characters. + :param case_sensitive: Enable case-sensitivity. + :return: A `TERScore` object. + """ + metric = TER( + normalized=normalized, + no_punct=no_punct, + asian_support=asian_support, + case_sensitive=case_sensitive) + return metric.sentence_score(hypothesis, references) diff --git a/venv/lib/python3.10/site-packages/sacrebleu/dataset/__init__.py b/venv/lib/python3.10/site-packages/sacrebleu/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..247839551770ff8ae24a7f51c282d1e07fbe8d77 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/dataset/__init__.py @@ -0,0 +1,1961 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright 2017--2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You may not +# use this file except in compliance with the License. A copy of the License +# is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is distributed on +# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +# express or implied. See the License for the specific language governing +# permissions and limitations under the License. + + +# This defines data locations. +# Right below are test sets. +# Beneath each test set, we define the location to download the test data. +# The other keys are each language pair contained in the tarball, and the respective locations of the source and reference data within each. +# Many of these are *.sgm files, which are processed to produced plain text that can be used by this script. +# The canonical location of unpacked, processed data is $SACREBLEU_DIR/$TEST/$SOURCE-$TARGET.{$SOURCE,$TARGET} +from .fake_sgml import FakeSGMLDataset, WMTAdditionDataset +from .iwslt_xml import IWSLTXMLDataset +from .plain_text import PlainTextDataset +from .tsv import TSVDataset +from .wmt_xml import WMTXMLDataset + +# Detailed document metadata annotation in form DocumentID -> CountryCode - Domain - OptionalFinegrainedCountryCode +# While the annotation is subjective with many unclear cases, it may provide useful insights +# when applied on large data (TODO: annotate all documents from recent WMT years, at least for origlang=en, consider renaming "world" to "other"). +_SUBSETS = { + "wmt18": "rt.com.68098=US-crime guardian.181611=US-politics bbc.310963=GB-sport washpost.116881=US-politics scotsman.104228=GB-sport timemagazine.75207=OTHER-world-ID " + "euronews-en.117981=OTHER-crime-AE smh.com.au.242810=US-crime msnbc.53726=US-politics euronews-en.117983=US-politics msnbc.53894=US-crime theglobeandmail.com.62700=US-business " + "bbc.310870=OTHER-world-AF reuters.196698=US-politics latimes.231739=US-sport thelocal.51929=OTHER-world-SE cbsnews.198694=US-politics reuters.196718=OTHER-sport-RU " + "abcnews.255599=EU-sport nytimes.127256=US-entertainment scotsman.104225=GB-politics dailymail.co.uk.233026=GB-scitech independent.181088=GB-entertainment " + "brisbanetimes.com.au.181614=OTHER-business-AU washpost.116837=US-politics dailymail.co.uk.232928=GB-world thelocal.51916=OTHER-politics-IT bbc.310871=US-crime " + "nytimes.127392=EU-business-DE euronews-en.118001=EU-scitech-FR washpost.116866=OTHER-crime-MX dailymail.co.uk.233025=OTHER-scitech-CA latimes.231829=US-crime " + "guardian.181662=US-entertainment msnbc.53731=US-crime rt.com.68127=OTHER-sport-RU latimes.231782=US-business latimes.231840=US-sport reuters.196711=OTHER-scitech " + "guardian.181666=GB-entertainment novinite.com.24019=US-politics smh.com.au.242750=OTHER-scitech guardian.181610=US-politics telegraph.364393=OTHER-crime-ZA " + "novinite.com.23995=EU-world dailymail.co.uk.233028=GB-scitech independent.181071=GB-sport telegraph.364538=GB-scitech timemagazine.75193=US-politics " + "independent.181096=US-entertainment upi.140602=OTHER-world-AF bbc.310946=GB-business independent.181052=EU-sport ", + "wmt19": "bbc.381790=GB-politics rt.com.91337=OTHER-politics-MK nytimes.184853=US-world upi.176266=US-crime guardian.221754=GB-business dailymail.co.uk.298595=GB-business " + "cnbc.com.6790=US-politics nytimes.184837=OTHER-world-ID upi.176249=GB-sport euronews-en.153835=OTHER-world-ID dailymail.co.uk.298732=GB-crime telegraph.405401=GB-politics " + "newsweek.51331=OTHER-crime-CN abcnews.306815=US-world cbsnews.248384=US-politics reuters.218882=GB-politics cbsnews.248387=US-crime abcnews.306764=OTHER-world-MX " + "reuters.218888=EU-politics bbc.381780=GB-crime bbc.381746=GB-sport euronews-en.153800=EU-politics bbc.381679=GB-crime bbc.381735=GB-crime newsweek.51338=US-world " + "bbc.381765=GB-crime cnn.304489=US-politics reuters.218863=OTHER-world-ID nytimes.184860=OTHER-world-ID cnn.304404=US-crime bbc.381647=US-entertainment " + "abcnews.306758=OTHER-politics-MX cnbc.com.6772=US-business reuters.218932=OTHER-politics-MK upi.176251=GB-sport reuters.218921=US-sport cnn.304447=US-politics " + "guardian.221679=GB-politics scotsman.133765=GB-sport scotsman.133804=GB-entertainment guardian.221762=OTHER-politics-BO cnbc.com.6769=US-politics " + "dailymail.co.uk.298692=EU-entertainment scotsman.133744=GB-world reuters.218911=US-sport newsweek.51310=US-politics independent.226301=US-sport reuters.218923=EU-sport " + "reuters.218861=US-politics dailymail.co.uk.298759=US-world scotsman.133791=GB-sport cbsnews.248484=EU-scitech dailymail.co.uk.298630=US-scitech " + "newsweek.51329=US-entertainment bbc.381701=GB-crime dailymail.co.uk.298738=GB-entertainment bbc.381669=OTHER-world-CN foxnews.94512=US-politics " + "guardian.221718=GB-entertainment dailymail.co.uk.298686=GB-politics cbsnews.248471=US-politics newsweek.51318=US-entertainment rt.com.91335=US-politics " + "newsweek.51300=US-politics cnn.304478=US-politics upi.176275=US-politics telegraph.405422=OTHER-world-ID reuters.218933=US-politics newsweek.51328=US-politics " + "newsweek.51307=US-business bbc.381692=GB-world independent.226346=GB-entertainment bbc.381646=GB-sport reuters.218914=US-sport scotsman.133758=EU-sport " + "rt.com.91350=EU-world scotsman.133773=GB-scitech rt.com.91334=EU-crime bbc.381680=GB-politics guardian.221756=US-politics scotsman.133783=GB-politics cnn.304521=US-sport " + "dailymail.co.uk.298622=GB-politics bbc.381789=GB-sport dailymail.co.uk.298644=GB-business dailymail.co.uk.298602=GB-world scotsman.133753=GB-sport " + "independent.226317=GB-entertainment nytimes.184862=US-politics thelocal.65969=OTHER-world-SY nytimes.184825=US-politics cnbc.com.6784=US-politics nytimes.184804=US-politics " + "nytimes.184830=US-politics scotsman.133801=GB-sport cnbc.com.6770=US-business bbc.381760=GB-crime reuters.218865=OTHER-world-ID newsweek.51339=US-crime " + "euronews-en.153797=OTHER-world-ID abcnews.306774=US-crime dailymail.co.uk.298696=GB-politics abcnews.306755=US-politics reuters.218909=US-crime " + "independent.226349=OTHER-sport-RU newsweek.51330=US-politics bbc.381705=GB-sport newsweek.51340=OTHER-world-ID cbsnews.248411=OTHER-world-FM abcnews.306776=US-crime " + "bbc.381694=GB-entertainment rt.com.91356=US-world telegraph.405430=GB-entertainment telegraph.405404=EU-world bbc.381749=GB-world telegraph.405413=US-politics " + "bbc.381736=OTHER-politics-KP cbsnews.248394=US-politics nytimes.184822=US-world telegraph.405408=US-politics euronews-en.153799=OTHER-politics-SY " + "euronews-en.153826=EU-sport cnn.304400=US-world", +} + +SUBSETS = { + k: {d.split("=")[0]: d.split("=")[1] for d in v.split()} + for (k, v) in _SUBSETS.items() +} +COUNTRIES = sorted(list({v.split("-")[0] for v in SUBSETS["wmt19"].values()})) +DOMAINS = sorted(list({v.split("-")[1] for v in SUBSETS["wmt19"].values()})) + +DATASETS = { + # wmt + "wmt23": WMTXMLDataset( + "wmt23", + data=["https://github.com/wmt-conference/wmt23-news-systems/archive/refs/tags/v.0.1.tar.gz"], + description="Official evaluation and system data for WMT23.", + md5=["63576405e4ce07130a19ad76ba7eb75b"], + langpairs={ + "cs-uk": ["wmt23-news-systems-v.0.1/xml/wmttest2023.cs-uk.all.xml"], + "de-en": ["wmt23-news-systems-v.0.1/xml/wmttest2023.de-en.all.xml"], + "en-cs": ["wmt23-news-systems-v.0.1/xml/wmttest2023.en-cs.all.xml"], + "en-de": ["wmt23-news-systems-v.0.1/xml/wmttest2023.en-de.all.xml"], + "en-he": { + "path": "wmt23-news-systems-v.0.1/xml/wmttest2023.en-he.all.xml", + "refs": ["refB"], + }, + "en-ja": ["wmt23-news-systems-v.0.1/xml/wmttest2023.en-ja.all.xml"], + "en-ru": ["wmt23-news-systems-v.0.1/xml/wmttest2023.en-ru.all.xml"], + "en-uk": ["wmt23-news-systems-v.0.1/xml/wmttest2023.en-uk.all.xml"], + "en-zh": ["wmt23-news-systems-v.0.1/xml/wmttest2023.en-zh.all.xml"], + "he-en": { + "path": "wmt23-news-systems-v.0.1/xml/wmttest2023.he-en.all.xml", + "refs": ["refB"], + }, + "ja-en": ["wmt23-news-systems-v.0.1/xml/wmttest2023.ja-en.all.xml"], + "ru-en": ["wmt23-news-systems-v.0.1/xml/wmttest2023.ru-en.all.xml"], + "uk-en": ["wmt23-news-systems-v.0.1/xml/wmttest2023.uk-en.all.xml"], + "zh-en": ["wmt23-news-systems-v.0.1/xml/wmttest2023.zh-en.all.xml"], + }, + refs=["refA"], + ), + "wmt22": WMTXMLDataset( + "wmt22", + data=["https://github.com/wmt-conference/wmt22-news-systems/archive/refs/tags/v1.1.tar.gz"], + description="Official evaluation and system data for WMT22.", + md5=["0840978b9b50b9ac3b2b081e37d620b9"], + langpairs={ + "cs-en": { + "path": "wmt22-news-systems-1.1/xml/wmttest2022.cs-en.all.xml", + "refs": ["B"], + }, + "cs-uk": ["wmt22-news-systems-1.1/xml/wmttest2022.cs-uk.all.xml"], + "de-en": ["wmt22-news-systems-1.1/xml/wmttest2022.de-en.all.xml"], + "de-fr": ["wmt22-news-systems-1.1/xml/wmttest2022.de-fr.all.xml"], + "en-cs": { + "path": "wmt22-news-systems-1.1/xml/wmttest2022.en-cs.all.xml", + "refs": ["B"], + }, + "en-de": ["wmt22-news-systems-1.1/xml/wmttest2022.en-de.all.xml"], + "en-hr": ["wmt22-news-systems-1.1/xml/wmttest2022.en-hr.all.xml"], + "en-ja": ["wmt22-news-systems-1.1/xml/wmttest2022.en-ja.all.xml"], + "en-liv": ["wmt22-news-systems-1.1/xml/wmttest2022.en-liv.all.xml"], + "en-ru": ["wmt22-news-systems-1.1/xml/wmttest2022.en-ru.all.xml"], + "en-uk": ["wmt22-news-systems-1.1/xml/wmttest2022.en-uk.all.xml"], + "en-zh": ["wmt22-news-systems-1.1/xml/wmttest2022.en-zh.all.xml"], + "fr-de": ["wmt22-news-systems-1.1/xml/wmttest2022.fr-de.all.xml"], + "ja-en": ["wmt22-news-systems-1.1/xml/wmttest2022.ja-en.all.xml"], + "liv-en": { + "path": "wmt22-news-systems-1.1/xml/wmttest2022.liv-en.all.xml", + # no translator because data is English-original + "refs": [""], + }, + "ru-en": ["wmt22-news-systems-1.1/xml/wmttest2022.ru-en.all.xml"], + "ru-sah": { + "path": "wmt22-news-systems-1.1/xml/wmttest2022.ru-sah.all.xml", + # no translator because data is Yakut-original + "refs": [""], + }, + "sah-ru": ["wmt22-news-systems-1.1/xml/wmttest2022.sah-ru.all.xml"], + "uk-cs": ["wmt22-news-systems-1.1/xml/wmttest2022.uk-cs.all.xml"], + "uk-en": ["wmt22-news-systems-1.1/xml/wmttest2022.uk-en.all.xml"], + "zh-en": ["wmt22-news-systems-1.1/xml/wmttest2022.zh-en.all.xml"], + }, + # the default reference to use with this dataset + refs=["A"], + ), + "wmt21/systems": WMTXMLDataset( + "wmt21/systems", + data=["https://github.com/wmt-conference/wmt21-news-systems/archive/refs/tags/v1.3.tar.gz"], + description="WMT21 system output.", + md5=["a6aee4099da58f98f71eb3fac1694237"], + langpairs={ + "de-fr": ["wmt21-news-systems-1.3/xml/newstest2021.de-fr.all.xml"], + "en-de": ["wmt21-news-systems-1.3/xml/newstest2021.en-de.all.xml"], + "en-ha": ["wmt21-news-systems-1.3/xml/newstest2021.en-ha.all.xml"], + "en-is": ["wmt21-news-systems-1.3/xml/newstest2021.en-is.all.xml"], + "en-ja": ["wmt21-news-systems-1.3/xml/newstest2021.en-ja.all.xml"], + "fr-de": ["wmt21-news-systems-1.3/xml/newstest2021.fr-de.all.xml"], + "ha-en": ["wmt21-news-systems-1.3/xml/newstest2021.ha-en.all.xml"], + "is-en": ["wmt21-news-systems-1.3/xml/newstest2021.is-en.all.xml"], + "ja-en": ["wmt21-news-systems-1.3/xml/newstest2021.ja-en.all.xml"], + "zh-en": ["wmt21-news-systems-1.3/xml/newstest2021.zh-en.all.xml"], + "en-zh": ["wmt21-news-systems-1.3/xml/newstest2021.en-zh.all.xml"], + "cs-en": ["wmt21-news-systems-1.3/xml/newstest2021.cs-en.all.xml"], + "de-en": ["wmt21-news-systems-1.3/xml/newstest2021.de-en.all.xml"], + "en-cs": ["wmt21-news-systems-1.3/xml/newstest2021.en-cs.all.xml"], + "en-ru": ["wmt21-news-systems-1.3/xml/newstest2021.en-ru.all.xml"], + "ru-en": ["wmt21-news-systems-1.3/xml/newstest2021.ru-en.all.xml"], + "bn-hi": ["wmt21-news-systems-1.3/xml/florestest2021.bn-hi.all.xml"], + "hi-bn": ["wmt21-news-systems-1.3/xml/florestest2021.hi-bn.all.xml"], + "xh-zu": ["wmt21-news-systems-1.3/xml/florestest2021.xh-zu.all.xml"], + "zu-xh": ["wmt21-news-systems-1.3/xml/florestest2021.zu-xh.all.xml"], + }, + # the reference to use with this dataset + refs=["A"], + ), + "wmt21": WMTXMLDataset( + "wmt21", + data=["https://data.statmt.org/wmt21/translation-task/test.tgz"], + description="Official evaluation data for WMT21.", + md5=["32e7ab995bc318414375d60f0269af92"], + langpairs={ + "de-fr": ["test/newstest2021.de-fr.xml"], + "en-de": ["test/newstest2021.en-de.xml"], + "en-ha": ["test/newstest2021.en-ha.xml"], + "en-is": ["test/newstest2021.en-is.xml"], + "en-ja": ["test/newstest2021.en-ja.xml"], + "fr-de": ["test/newstest2021.fr-de.xml"], + "ha-en": ["test/newstest2021.ha-en.xml"], + "is-en": ["test/newstest2021.is-en.xml"], + "ja-en": ["test/newstest2021.ja-en.xml"], + "zh-en": ["test/newstest2021.zh-en.xml"], + "en-zh": ["test/newstest2021.en-zh.xml"], + "cs-en": ["test/newstest2021.cs-en.xml"], + "de-en": ["test/newstest2021.de-en.xml"], + "en-cs": ["test/newstest2021.en-cs.xml"], + "en-ru": ["test/newstest2021.en-ru.xml"], + "ru-en": ["test/newstest2021.ru-en.xml"], + "bn-hi": ["test/florestest2021.bn-hi.xml"], + "hi-bn": ["test/florestest2021.hi-bn.xml"], + "xh-zu": ["test/florestest2021.xh-zu.xml"], + "zu-xh": ["test/florestest2021.zu-xh.xml"], + }, + # the reference to use with this dataset + refs=["A"], + ), + "wmt21/B": WMTXMLDataset( + "wmt21/B", + data=["https://data.statmt.org/wmt21/translation-task/test.tgz"], + description="Official evaluation data for WMT21 with reference B.", + md5=["32e7ab995bc318414375d60f0269af92"], + langpairs={ + "cs-en": ["test/newstest2021.cs-en.xml"], + "de-en": ["test/newstest2021.de-en.xml"], + "en-cs": ["test/newstest2021.en-cs.xml"], + "en-ru": ["test/newstest2021.en-ru.xml"], + "en-zh": ["test/newstest2021.en-zh.xml"], + "ru-en": ["test/newstest2021.ru-en.xml"], + }, + # the reference to use with this dataset + refs=["B"], + ), + "wmt21/AB": WMTXMLDataset( + "wmt21/AB", + data=["https://data.statmt.org/wmt21/translation-task/test.tgz"], + description="Official evaluation data for WMT21 with references A and B.", + md5=["32e7ab995bc318414375d60f0269af92"], + langpairs={ + "cs-en": ["test/newstest2021.cs-en.xml"], + "de-en": ["test/newstest2021.de-en.xml"], + "en-de": ["test/newstest2021.en-de.xml"], + "en-cs": ["test/newstest2021.en-cs.xml"], + "en-ru": ["test/newstest2021.en-ru.xml"], + "en-zh": ["test/newstest2021.en-zh.xml"], + "ru-en": ["test/newstest2021.ru-en.xml"], + }, + # the reference to use with this dataset + refs=["A", "B"], + ), + "wmt21/C": WMTXMLDataset( + "wmt21/C", + data=["https://data.statmt.org/wmt21/translation-task/test.tgz"], + description="Official evaluation data for WMT21 with reference C", + md5=["32e7ab995bc318414375d60f0269af92"], + langpairs={ + "en-de": ["test/newstest2021.en-de.xml"], + }, + # the reference to use with this dataset + refs=["C"], + ), + "wmt21/AC": WMTXMLDataset( + "wmt21/AC", + data=["https://data.statmt.org/wmt21/translation-task/test.tgz"], + description="Official evaluation data for WMT21 with references A and C", + md5=["32e7ab995bc318414375d60f0269af92"], + langpairs={ + "en-de": ["test/newstest2021.en-de.xml"], + }, + # the reference to use with this dataset + refs=["A", "C"], + ), + "wmt21/D": WMTXMLDataset( + "wmt21/D", + data=["https://data.statmt.org/wmt21/translation-task/test.tgz"], + description="Official evaluation data for WMT21 with reference D", + md5=["32e7ab995bc318414375d60f0269af92"], + langpairs={ + "en-de": ["test/newstest2021.en-de.xml"], + }, + # the reference to use with this dataset + refs=["D"], + ), + "wmt21/dev": WMTXMLDataset( + "wmt21/dev", + data=["https://data.statmt.org/wmt21/translation-task/dev.tgz"], + description="Development data for WMT21,if multiple references are available, the first one is used.", + md5=["165da59ac8dfb5b7cafd7e90b1cac672"], + langpairs={ + "en-ha": ["dev/xml/newsdev2021.en-ha.xml"], + "ha-en": ["dev/xml/newsdev2021.ha-en.xml"], + "en-is": ["dev/xml/newsdev2021.en-is.xml"], + "is-en": ["dev/xml/newsdev2021.is-en.xml"], + }, + # datasets are bidirectional in origin, so use both refs + refs=["A", ""], + ), + "wmt20/tworefs": FakeSGMLDataset( + "wmt20/tworefs", + data=["https://data.statmt.org/wmt20/translation-task/test.tgz"], + description="WMT20 news test sets with two references", + md5=["3b1f777cfd2fb15ccf66e9bfdb2b1699"], + langpairs={ + "de-en": [ + "sgm/newstest2020-deen-src.de.sgm", + "sgm/newstest2020-deen-ref.en.sgm", + "sgm/newstestB2020-deen-ref.en.sgm", + ], + "en-de": [ + "sgm/newstest2020-ende-src.en.sgm", + "sgm/newstest2020-ende-ref.de.sgm", + "sgm/newstestB2020-ende-ref.de.sgm", + ], + "en-zh": [ + "sgm/newstest2020-enzh-src.en.sgm", + "sgm/newstest2020-enzh-ref.zh.sgm", + "sgm/newstestB2020-enzh-ref.zh.sgm", + ], + "ru-en": [ + "sgm/newstest2020-ruen-src.ru.sgm", + "sgm/newstest2020-ruen-ref.en.sgm", + "sgm/newstestB2020-ruen-ref.en.sgm", + ], + "zh-en": [ + "sgm/newstest2020-zhen-src.zh.sgm", + "sgm/newstest2020-zhen-ref.en.sgm", + "sgm/newstestB2020-zhen-ref.en.sgm", + ], + }, + ), + "wmt20": FakeSGMLDataset( + "wmt20", + data=["https://data.statmt.org/wmt20/translation-task/test.tgz"], + description="Official evaluation data for WMT20", + md5=["3b1f777cfd2fb15ccf66e9bfdb2b1699"], + langpairs={ + "cs-en": [ + "sgm/newstest2020-csen-src.cs.sgm", + "sgm/newstest2020-csen-ref.en.sgm", + ], + "de-en": [ + "sgm/newstest2020-deen-src.de.sgm", + "sgm/newstest2020-deen-ref.en.sgm", + ], + "de-fr": [ + "sgm/newstest2020-defr-src.de.sgm", + "sgm/newstest2020-defr-ref.fr.sgm", + ], + "en-cs": [ + "sgm/newstest2020-encs-src.en.sgm", + "sgm/newstest2020-encs-ref.cs.sgm", + ], + "en-de": [ + "sgm/newstest2020-ende-src.en.sgm", + "sgm/newstest2020-ende-ref.de.sgm", + ], + "en-iu": [ + "sgm/newstest2020-eniu-src.en.sgm", + "sgm/newstest2020-eniu-ref.iu.sgm", + ], + "en-ja": [ + "sgm/newstest2020-enja-src.en.sgm", + "sgm/newstest2020-enja-ref.ja.sgm", + ], + "en-km": [ + "sgm/newstest2020-enkm-src.en.sgm", + "sgm/newstest2020-enkm-ref.km.sgm", + ], + "en-pl": [ + "sgm/newstest2020-enpl-src.en.sgm", + "sgm/newstest2020-enpl-ref.pl.sgm", + ], + "en-ps": [ + "sgm/newstest2020-enps-src.en.sgm", + "sgm/newstest2020-enps-ref.ps.sgm", + ], + "en-ru": [ + "sgm/newstest2020-enru-src.en.sgm", + "sgm/newstest2020-enru-ref.ru.sgm", + ], + "en-ta": [ + "sgm/newstest2020-enta-src.en.sgm", + "sgm/newstest2020-enta-ref.ta.sgm", + ], + "en-zh": [ + "sgm/newstest2020-enzh-src.en.sgm", + "sgm/newstest2020-enzh-ref.zh.sgm", + ], + "fr-de": [ + "sgm/newstest2020-frde-src.fr.sgm", + "sgm/newstest2020-frde-ref.de.sgm", + ], + "iu-en": [ + "sgm/newstest2020-iuen-src.iu.sgm", + "sgm/newstest2020-iuen-ref.en.sgm", + ], + "ja-en": [ + "sgm/newstest2020-jaen-src.ja.sgm", + "sgm/newstest2020-jaen-ref.en.sgm", + ], + "km-en": [ + "sgm/newstest2020-kmen-src.km.sgm", + "sgm/newstest2020-kmen-ref.en.sgm", + ], + "pl-en": [ + "sgm/newstest2020-plen-src.pl.sgm", + "sgm/newstest2020-plen-ref.en.sgm", + ], + "ps-en": [ + "sgm/newstest2020-psen-src.ps.sgm", + "sgm/newstest2020-psen-ref.en.sgm", + ], + "ru-en": [ + "sgm/newstest2020-ruen-src.ru.sgm", + "sgm/newstest2020-ruen-ref.en.sgm", + ], + "ta-en": [ + "sgm/newstest2020-taen-src.ta.sgm", + "sgm/newstest2020-taen-ref.en.sgm", + ], + "zh-en": [ + "sgm/newstest2020-zhen-src.zh.sgm", + "sgm/newstest2020-zhen-ref.en.sgm", + ], + }, + ), + "wmt20/dev": FakeSGMLDataset( + "wmt20/dev", + data=["https://data.statmt.org/wmt20/translation-task/dev.tgz"], + description="Development data for tasks new to 2020.", + md5=["037f2b37aab74febbb1b2307dc2afb54"], + langpairs={ + "iu-en": [ + "dev/newsdev2020-iuen-src.iu.sgm", + "dev/newsdev2020-iuen-ref.en.sgm", + ], + "en-iu": [ + "dev/newsdev2020-eniu-src.en.sgm", + "dev/newsdev2020-eniu-ref.iu.sgm", + ], + "ja-en": [ + "dev/newsdev2020-jaen-src.ja.sgm", + "dev/newsdev2020-jaen-ref.en.sgm", + ], + "en-ja": [ + "dev/newsdev2020-enja-src.en.sgm", + "dev/newsdev2020-enja-ref.ja.sgm", + ], + "pl-en": [ + "dev/newsdev2020-plen-src.pl.sgm", + "dev/newsdev2020-plen-ref.en.sgm", + ], + "en-pl": [ + "dev/newsdev2020-enpl-src.en.sgm", + "dev/newsdev2020-enpl-ref.pl.sgm", + ], + "ta-en": [ + "dev/newsdev2020-taen-src.ta.sgm", + "dev/newsdev2020-taen-ref.en.sgm", + ], + "en-ta": [ + "dev/newsdev2020-enta-src.en.sgm", + "dev/newsdev2020-enta-ref.ta.sgm", + ], + }, + ), + "wmt20/robust/set1": PlainTextDataset( + "wmt20/robust/set1", + data=["https://data.statmt.org/wmt20/robustness-task/robustness20-3-sets.zip"], + md5=["a12ac9ebe89b72195041518dffc4a9d5"], + description="WMT20 robustness task, set 1", + langpairs={ + "en-ja": [ + "robustness20-3-sets/robustness20-set1-enja.en", + "robustness20-3-sets/robustness20-set1-enja.ja", + ], + "en-de": [ + "robustness20-3-sets/robustness20-set1-ende.en", + "robustness20-3-sets/robustness20-set1-ende.de", + ], + }, + ), + "wmt20/robust/set2": PlainTextDataset( + "wmt20/robust/set2", + data=["https://data.statmt.org/wmt20/robustness-task/robustness20-3-sets.zip"], + md5=["a12ac9ebe89b72195041518dffc4a9d5"], + description="WMT20 robustness task, set 2", + langpairs={ + "en-ja": [ + "robustness20-3-sets/robustness20-set2-enja.en", + "robustness20-3-sets/robustness20-set2-enja.ja", + ], + "ja-en": [ + "robustness20-3-sets/robustness20-set2-jaen.ja", + "robustness20-3-sets/robustness20-set2-jaen.en", + ], + }, + ), + "wmt20/robust/set3": PlainTextDataset( + "wmt20/robust/set3", + data=["https://data.statmt.org/wmt20/robustness-task/robustness20-3-sets.zip"], + md5=["a12ac9ebe89b72195041518dffc4a9d5"], + description="WMT20 robustness task, set 3", + langpairs={ + "de-en": [ + "robustness20-3-sets/robustness20-set3-deen.de", + "robustness20-3-sets/robustness20-set3-deen.en", + ], + }, + ), + "wmt19": FakeSGMLDataset( + "wmt19", + data=["https://data.statmt.org/wmt19/translation-task/test.tgz"], + description="Official evaluation data.", + md5=["84de7162d158e28403103b01aeefc39a"], + citation=r"""@proceedings{ws-2019-machine, + title = "Proceedings of the Fourth Conference on Machine Translation (Volume 1: Research Papers)", + editor = "Bojar, Ond{\v{r}}ej and + Chatterjee, Rajen and + Federmann, Christian and + Fishel, Mark and + Graham, Yvette and + Haddow, Barry and + Huck, Matthias and + Yepes, Antonio Jimeno and + Koehn, Philipp and + Martins, Andr{\'e} and + Monz, Christof and + Negri, Matteo and + N{\'e}v{\'e}ol, Aur{\'e}lie and + Neves, Mariana and + Post, Matt and + Turchi, Marco and + Verspoor, Karin", + month = aug, + year = "2019", + address = "Florence, Italy", + publisher = "Association for Computational Linguistics", + url = "https://www.aclweb.org/anthology/W19-5200", +}""", + langpairs={ + "cs-de": [ + "sgm/newstest2019-csde-src.cs.sgm", + "sgm/newstest2019-csde-ref.de.sgm", + ], + "de-cs": [ + "sgm/newstest2019-decs-src.de.sgm", + "sgm/newstest2019-decs-ref.cs.sgm", + ], + "de-en": [ + "sgm/newstest2019-deen-src.de.sgm", + "sgm/newstest2019-deen-ref.en.sgm", + ], + "de-fr": [ + "sgm/newstest2019-defr-src.de.sgm", + "sgm/newstest2019-defr-ref.fr.sgm", + ], + "en-cs": [ + "sgm/newstest2019-encs-src.en.sgm", + "sgm/newstest2019-encs-ref.cs.sgm", + ], + "en-de": [ + "sgm/newstest2019-ende-src.en.sgm", + "sgm/newstest2019-ende-ref.de.sgm", + ], + "en-fi": [ + "sgm/newstest2019-enfi-src.en.sgm", + "sgm/newstest2019-enfi-ref.fi.sgm", + ], + "en-gu": [ + "sgm/newstest2019-engu-src.en.sgm", + "sgm/newstest2019-engu-ref.gu.sgm", + ], + "en-kk": [ + "sgm/newstest2019-enkk-src.en.sgm", + "sgm/newstest2019-enkk-ref.kk.sgm", + ], + "en-lt": [ + "sgm/newstest2019-enlt-src.en.sgm", + "sgm/newstest2019-enlt-ref.lt.sgm", + ], + "en-ru": [ + "sgm/newstest2019-enru-src.en.sgm", + "sgm/newstest2019-enru-ref.ru.sgm", + ], + "en-zh": [ + "sgm/newstest2019-enzh-src.en.sgm", + "sgm/newstest2019-enzh-ref.zh.sgm", + ], + "fi-en": [ + "sgm/newstest2019-fien-src.fi.sgm", + "sgm/newstest2019-fien-ref.en.sgm", + ], + "fr-de": [ + "sgm/newstest2019-frde-src.fr.sgm", + "sgm/newstest2019-frde-ref.de.sgm", + ], + "gu-en": [ + "sgm/newstest2019-guen-src.gu.sgm", + "sgm/newstest2019-guen-ref.en.sgm", + ], + "kk-en": [ + "sgm/newstest2019-kken-src.kk.sgm", + "sgm/newstest2019-kken-ref.en.sgm", + ], + "lt-en": [ + "sgm/newstest2019-lten-src.lt.sgm", + "sgm/newstest2019-lten-ref.en.sgm", + ], + "ru-en": [ + "sgm/newstest2019-ruen-src.ru.sgm", + "sgm/newstest2019-ruen-ref.en.sgm", + ], + "zh-en": [ + "sgm/newstest2019-zhen-src.zh.sgm", + "sgm/newstest2019-zhen-ref.en.sgm", + ], + }, + ), + "wmt19/dev": FakeSGMLDataset( + "wmt19/dev", + data=["https://data.statmt.org/wmt19/translation-task/dev.tgz"], + description="Development data for tasks new to 2019.", + md5=["f2ec7af5947c19e0cacb3882eb208002"], + langpairs={ + "lt-en": [ + "dev/newsdev2019-lten-src.lt.sgm", + "dev/newsdev2019-lten-ref.en.sgm", + ], + "en-lt": [ + "dev/newsdev2019-enlt-src.en.sgm", + "dev/newsdev2019-enlt-ref.lt.sgm", + ], + "gu-en": [ + "dev/newsdev2019-guen-src.gu.sgm", + "dev/newsdev2019-guen-ref.en.sgm", + ], + "en-gu": [ + "dev/newsdev2019-engu-src.en.sgm", + "dev/newsdev2019-engu-ref.gu.sgm", + ], + "kk-en": [ + "dev/newsdev2019-kken-src.kk.sgm", + "dev/newsdev2019-kken-ref.en.sgm", + ], + "en-kk": [ + "dev/newsdev2019-enkk-src.en.sgm", + "dev/newsdev2019-enkk-ref.kk.sgm", + ], + }, + ), + "wmt19/google/ar": WMTAdditionDataset( + "wmt19/google/ar", + data=[ + "https://data.statmt.org/wmt19/translation-task/test.tgz", + "https://raw.githubusercontent.com/google/wmt19-paraphrased-references/master/wmt19/ende/wmt19-ende-ar.ref", + ], + description="Additional high-quality reference for WMT19/en-de.", + md5=["84de7162d158e28403103b01aeefc39a", "d66d9e91548ced0ac476f2390e32e2de"], + citation="@misc{freitag2020bleu,\n title={{BLEU} might be Guilty but References are not Innocent},\n author={Markus Freitag and David Grangier and Isaac Caswell},\n year={2020},\n eprint={2004.06063},\n archivePrefix={arXiv},\n primaryClass={cs.CL}", + langpairs={ + "en-de": ["sgm/newstest2019-ende-src.en.sgm", "wmt19_google_ar.wmt19-ende-ar.ref"], + }, + ), + "wmt19/google/arp": WMTAdditionDataset( + "wmt19/google/arp", + data=[ + "https://data.statmt.org/wmt19/translation-task/test.tgz", + "https://raw.githubusercontent.com/google/wmt19-paraphrased-references/master/wmt19/ende/wmt19-ende-arp.ref", + ], + description="Additional paraphrase of wmt19/google/ar.", + md5=["84de7162d158e28403103b01aeefc39a", "c70ea808cf2bff621ad7a8fddd4deca9"], + citation="@misc{freitag2020bleu,\n title={{BLEU} might be Guilty but References are not Innocent},\n author={Markus Freitag and David Grangier and Isaac Caswell},\n year={2020},\n eprint={2004.06063},\n archivePrefix={arXiv},\n primaryClass={cs.CL}", + langpairs={ + "en-de": ["sgm/newstest2019-ende-src.en.sgm", "wmt19_google_arp.wmt19-ende-arp.ref"], + }, + ), + "wmt19/google/wmtp": WMTAdditionDataset( + "wmt19/google/wmtp", + data=[ + "https://data.statmt.org/wmt19/translation-task/test.tgz", + "https://raw.githubusercontent.com/google/wmt19-paraphrased-references/master/wmt19/ende/wmt19-ende-wmtp.ref", + ], + description="Additional paraphrase of the official WMT19 reference.", + md5=["84de7162d158e28403103b01aeefc39a", "587c660ee5fd44727f0db025b71c6a82"], + citation="@misc{freitag2020bleu,\n title={{BLEU} might be Guilty but References are not Innocent},\n author={Markus Freitag and David Grangier and Isaac Caswell},\n year={2020},\n eprint={2004.06063},\n archivePrefix={arXiv},\n primaryClass={cs.CL}", + langpairs={ + "en-de": ["sgm/newstest2019-ende-src.en.sgm", "wmt19_google_wmtp.wmt19-ende-wmtp.ref"], + }, + ), + "wmt19/google/hqr": WMTAdditionDataset( + "wmt19/google/hqr", + data=[ + "https://data.statmt.org/wmt19/translation-task/test.tgz", + "https://raw.githubusercontent.com/google/wmt19-paraphrased-references/master/wmt19/ende/wmt19-ende-hqr.ref", + ], + description="Best human selected-reference between wmt19 and wmt19/google/ar.", + md5=["84de7162d158e28403103b01aeefc39a", "d9221135f62d7152de041f5bfc8efaea"], + citation="@misc{freitag2020bleu,\n title={{BLEU} might be Guilty but References are not Innocent},\n author={Markus Freitag and David Grangier and Isaac Caswell},\n year={2020},\n eprint={2004.06063},\n archivePrefix={arXiv},\n primaryClass={cs.CL}", + langpairs={ + "en-de": ["sgm/newstest2019-ende-src.en.sgm", "wmt19_google_hqr.wmt19-ende-hqr.ref"], + }, + ), + "wmt19/google/hqp": WMTAdditionDataset( + "wmt19/google/hqp", + data=[ + "https://data.statmt.org/wmt19/translation-task/test.tgz", + "https://raw.githubusercontent.com/google/wmt19-paraphrased-references/master/wmt19/ende/wmt19-ende-hqp.ref", + ], + description="Best human-selected reference between wmt19/google/arp and wmt19/google/wmtp.", + md5=["84de7162d158e28403103b01aeefc39a", "b7c3a07a59c8eccea5367e9ec5417a8a"], + citation="@misc{freitag2020bleu,\n title={{BLEU} might be Guilty but References are not Innocent},\n author={Markus Freitag and David Grangier and Isaac Caswell},\n year={2020},\n eprint={2004.06063},\n archivePrefix={arXiv},\n primaryClass={cs.CL}", + langpairs={ + "en-de": ["sgm/newstest2019-ende-src.en.sgm", "wmt19_google_hqp.wmt19-ende-hqp.ref"], + }, + ), + "wmt19/google/hqall": WMTAdditionDataset( + "wmt19/google/hqall", + data=[ + "https://data.statmt.org/wmt19/translation-task/test.tgz", + "https://raw.githubusercontent.com/google/wmt19-paraphrased-references/master/wmt19/ende/wmt19-ende-hqall.ref", + ], + description="Best human-selected reference among original official reference and the Google reference and paraphrases.", + md5=["84de7162d158e28403103b01aeefc39a", "edecf10ced59e10b703a6fbcf1fa9dfa"], + citation="@misc{freitag2020bleu,\n title={{BLEU} might be Guilty but References are not Innocent},\n author={Markus Freitag and David Grangier and Isaac Caswell},\n year={2020},\n eprint={2004.06063},\n archivePrefix={arXiv},\n primaryClass={cs.CL}", + langpairs={ + "en-de": ["sgm/newstest2019-ende-src.en.sgm", "wmt19_google_hqall.wmt19-ende-hqall.ref"], + }, + ), + "wmt18": FakeSGMLDataset( + "wmt18", + data=["https://data.statmt.org/wmt18/translation-task/test.tgz"], + md5=["f996c245ecffea23d0006fa4c34e9064"], + description="Official evaluation data.", + citation='@inproceedings{bojar-etal-2018-findings,\n title = "Findings of the 2018 Conference on Machine Translation ({WMT}18)",\n author = "Bojar, Ond{\v{r}}ej and\n Federmann, Christian and\n Fishel, Mark and\n Graham, Yvette and\n Haddow, Barry and\n Koehn, Philipp and\n Monz, Christof",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Shared Task Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6401",\n pages = "272--303",\n}', + langpairs={ + "cs-en": [ + "test/newstest2018-csen-src.cs.sgm", + "test/newstest2018-csen-ref.en.sgm", + ], + "de-en": [ + "test/newstest2018-deen-src.de.sgm", + "test/newstest2018-deen-ref.en.sgm", + ], + "en-cs": [ + "test/newstest2018-encs-src.en.sgm", + "test/newstest2018-encs-ref.cs.sgm", + ], + "en-de": [ + "test/newstest2018-ende-src.en.sgm", + "test/newstest2018-ende-ref.de.sgm", + ], + "en-et": [ + "test/newstest2018-enet-src.en.sgm", + "test/newstest2018-enet-ref.et.sgm", + ], + "en-fi": [ + "test/newstest2018-enfi-src.en.sgm", + "test/newstest2018-enfi-ref.fi.sgm", + ], + "en-ru": [ + "test/newstest2018-enru-src.en.sgm", + "test/newstest2018-enru-ref.ru.sgm", + ], + "et-en": [ + "test/newstest2018-eten-src.et.sgm", + "test/newstest2018-eten-ref.en.sgm", + ], + "fi-en": [ + "test/newstest2018-fien-src.fi.sgm", + "test/newstest2018-fien-ref.en.sgm", + ], + "ru-en": [ + "test/newstest2018-ruen-src.ru.sgm", + "test/newstest2018-ruen-ref.en.sgm", + ], + "en-tr": [ + "test/newstest2018-entr-src.en.sgm", + "test/newstest2018-entr-ref.tr.sgm", + ], + "tr-en": [ + "test/newstest2018-tren-src.tr.sgm", + "test/newstest2018-tren-ref.en.sgm", + ], + "en-zh": [ + "test/newstest2018-enzh-src.en.sgm", + "test/newstest2018-enzh-ref.zh.sgm", + ], + "zh-en": [ + "test/newstest2018-zhen-src.zh.sgm", + "test/newstest2018-zhen-ref.en.sgm", + ], + }, + ), + "wmt18/test-ts": FakeSGMLDataset( + "wmt18/test-ts", + data=["https://data.statmt.org/wmt18/translation-task/test-ts.tgz"], + md5=["5c621a34d512cc2dd74162ae7d00b320"], + description="Official evaluation sources with extra test sets interleaved.", + langpairs={ + "cs-en": ["test-ts/newstest2018-csen-src-ts.cs.sgm", "test-ts/newstest2018-csen-ref-ts.en.sgm"], + "de-en": ["test-ts/newstest2018-deen-src-ts.de.sgm", "test-ts/newstest2018-deen-ref-ts.en.sgm"], + "en-cs": ["test-ts/newstest2018-encs-src-ts.en.sgm", "test-ts/newstest2018-encs-ref-ts.cs.sgm"], + "en-de": ["test-ts/newstest2018-ende-src-ts.en.sgm", "test-ts/newstest2018-ende-ref-ts.de.sgm"], + "en-et": ["test-ts/newstest2018-enet-src-ts.en.sgm", "test-ts/newstest2018-enet-ref-ts.et.sgm"], + "en-fi": ["test-ts/newstest2018-enfi-src-ts.en.sgm", "test-ts/newstest2018-enfi-ref-ts.fi.sgm"], + "en-ru": ["test-ts/newstest2018-enru-src-ts.en.sgm", "test-ts/newstest2018-enru-ref-ts.ru.sgm"], + "et-en": ["test-ts/newstest2018-eten-src-ts.et.sgm", "test-ts/newstest2018-eten-ref-ts.en.sgm"], + "fi-en": ["test-ts/newstest2018-fien-src-ts.fi.sgm", "test-ts/newstest2018-fien-ref-ts.en.sgm"], + "ru-en": ["test-ts/newstest2018-ruen-src-ts.ru.sgm", "test-ts/newstest2018-ruen-ref-ts.en.sgm"], + "en-tr": ["test-ts/newstest2018-entr-src-ts.en.sgm", "test-ts/newstest2018-entr-ref-ts.tr.sgm"], + "tr-en": ["test-ts/newstest2018-tren-src-ts.tr.sgm", "test-ts/newstest2018-tren-ref-ts.en.sgm"], + "en-zh": ["test-ts/newstest2018-enzh-src-ts.en.sgm", "test-ts/newstest2018-enzh-ref-ts.zh.sgm"], + "zh-en": ["test-ts/newstest2018-zhen-src-ts.zh.sgm", "test-ts/newstest2018-zhen-ref-ts.en.sgm"], + }, + ), + "wmt18/dev": FakeSGMLDataset( + "wmt18/dev", + data=["https://data.statmt.org/wmt18/translation-task/dev.tgz"], + md5=["486f391da54a7a3247f02ebd25996f24"], + description="Development data (Estonian<>English).", + langpairs={ + "et-en": [ + "dev/newsdev2018-eten-src.et.sgm", + "dev/newsdev2018-eten-ref.en.sgm", + ], + "en-et": [ + "dev/newsdev2018-enet-src.en.sgm", + "dev/newsdev2018-enet-ref.et.sgm", + ], + }, + ), + "wmt17": FakeSGMLDataset( + "wmt17", + data=["https://data.statmt.org/wmt17/translation-task/test.tgz"], + md5=["86a1724c276004aa25455ae2a04cef26"], + description="Official evaluation data.", + citation="@InProceedings{bojar-EtAl:2017:WMT1,\n author = {Bojar, Ond\\v{r}ej and Chatterjee, Rajen and Federmann, Christian and Graham, Yvette and Haddow, Barry and Huang, Shujian and Huck, Matthias and Koehn, Philipp and Liu, Qun and Logacheva, Varvara and Monz, Christof and Negri, Matteo and Post, Matt and Rubino, Raphael and Specia, Lucia and Turchi, Marco},\n title = {Findings of the 2017 Conference on Machine Translation (WMT17)},\n booktitle = {Proceedings of the Second Conference on Machine Translation, Volume 2: Shared Task Papers},\n month = {September},\n year = {2017},\n address = {Copenhagen, Denmark},\n publisher = {Association for Computational Linguistics},\n pages = {169--214},\n url = {http://www.aclweb.org/anthology/W17-4717}\n}", + langpairs={ + "cs-en": [ + "test/newstest2017-csen-src.cs.sgm", + "test/newstest2017-csen-ref.en.sgm", + ], + "de-en": [ + "test/newstest2017-deen-src.de.sgm", + "test/newstest2017-deen-ref.en.sgm", + ], + "en-cs": [ + "test/newstest2017-encs-src.en.sgm", + "test/newstest2017-encs-ref.cs.sgm", + ], + "en-de": [ + "test/newstest2017-ende-src.en.sgm", + "test/newstest2017-ende-ref.de.sgm", + ], + "en-fi": [ + "test/newstest2017-enfi-src.en.sgm", + "test/newstest2017-enfi-ref.fi.sgm", + ], + "en-lv": [ + "test/newstest2017-enlv-src.en.sgm", + "test/newstest2017-enlv-ref.lv.sgm", + ], + "en-ru": [ + "test/newstest2017-enru-src.en.sgm", + "test/newstest2017-enru-ref.ru.sgm", + ], + "en-tr": [ + "test/newstest2017-entr-src.en.sgm", + "test/newstest2017-entr-ref.tr.sgm", + ], + "en-zh": [ + "test/newstest2017-enzh-src.en.sgm", + "test/newstest2017-enzh-ref.zh.sgm", + ], + "fi-en": [ + "test/newstest2017-fien-src.fi.sgm", + "test/newstest2017-fien-ref.en.sgm", + ], + "lv-en": [ + "test/newstest2017-lven-src.lv.sgm", + "test/newstest2017-lven-ref.en.sgm", + ], + "ru-en": [ + "test/newstest2017-ruen-src.ru.sgm", + "test/newstest2017-ruen-ref.en.sgm", + ], + "tr-en": [ + "test/newstest2017-tren-src.tr.sgm", + "test/newstest2017-tren-ref.en.sgm", + ], + "zh-en": [ + "test/newstest2017-zhen-src.zh.sgm", + "test/newstest2017-zhen-ref.en.sgm", + ], + }, + ), + "wmt17/B": FakeSGMLDataset( + "wmt17/B", + data=["https://data.statmt.org/wmt17/translation-task/test.tgz"], + md5=["86a1724c276004aa25455ae2a04cef26"], + description="Additional reference for EN-FI and FI-EN.", + langpairs={ + "en-fi": [ + "test/newstestB2017-enfi-src.en.sgm", + "test/newstestB2017-enfi-ref.fi.sgm", + ], + }, + ), + "wmt17/tworefs": FakeSGMLDataset( + "wmt17/tworefs", + data=["https://data.statmt.org/wmt17/translation-task/test.tgz"], + md5=["86a1724c276004aa25455ae2a04cef26"], + description="Systems with two references.", + langpairs={ + "en-fi": [ + "test/newstest2017-enfi-src.en.sgm", + "test/newstest2017-enfi-ref.fi.sgm", + "test/newstestB2017-enfi-ref.fi.sgm", + ], + }, + ), + "wmt17/improved": FakeSGMLDataset( + "wmt17/improved", + data=["https://data.statmt.org/wmt17/translation-task/test-update-1.tgz"], + md5=["91dbfd5af99bc6891a637a68e04dfd41"], + description="Improved zh-en and en-zh translations.", + langpairs={ + "en-zh": ["newstest2017-enzh-src.en.sgm", "newstest2017-enzh-ref.zh.sgm"], + "zh-en": ["newstest2017-zhen-src.zh.sgm", "newstest2017-zhen-ref.en.sgm"], + }, + ), + "wmt17/dev": FakeSGMLDataset( + "wmt17/dev", + data=["https://data.statmt.org/wmt17/translation-task/dev.tgz"], + md5=["9b1aa63c1cf49dccdd20b962fe313989"], + description="Development sets released for new languages in 2017.", + langpairs={ + "en-lv": [ + "dev/newsdev2017-enlv-src.en.sgm", + "dev/newsdev2017-enlv-ref.lv.sgm", + ], + "en-zh": [ + "dev/newsdev2017-enzh-src.en.sgm", + "dev/newsdev2017-enzh-ref.zh.sgm", + ], + "lv-en": [ + "dev/newsdev2017-lven-src.lv.sgm", + "dev/newsdev2017-lven-ref.en.sgm", + ], + "zh-en": [ + "dev/newsdev2017-zhen-src.zh.sgm", + "dev/newsdev2017-zhen-ref.en.sgm", + ], + }, + ), + "wmt17/ms": WMTAdditionDataset( + "wmt17/ms", + data=[ + "https://github.com/MicrosoftTranslator/Translator-HumanParityData/archive/master.zip", + "https://data.statmt.org/wmt17/translation-task/test-update-1.tgz", + ], + md5=["18fdaa7a3c84cf6ef688da1f6a5fa96f", "91dbfd5af99bc6891a637a68e04dfd41"], + description="Additional Chinese-English references from Microsoft Research.", + citation="@inproceedings{achieving-human-parity-on-automatic-chinese-to-english-news-translation,\n author = {Hassan Awadalla, Hany and Aue, Anthony and Chen, Chang and Chowdhary, Vishal and Clark, Jonathan and Federmann, Christian and Huang, Xuedong and Junczys-Dowmunt, Marcin and Lewis, Will and Li, Mu and Liu, Shujie and Liu, Tie-Yan and Luo, Renqian and Menezes, Arul and Qin, Tao and Seide, Frank and Tan, Xu and Tian, Fei and Wu, Lijun and Wu, Shuangzhi and Xia, Yingce and Zhang, Dongdong and Zhang, Zhirui and Zhou, Ming},\n title = {Achieving Human Parity on Automatic Chinese to English News Translation},\n booktitle = {},\n year = {2018},\n month = {March},\n abstract = {Machine translation has made rapid advances in recent years. Millions of people are using it today in online translation systems and mobile applications in order to communicate across language barriers. The question naturally arises whether such systems can approach or achieve parity with human translations. In this paper, we first address the problem of how to define and accurately measure human parity in translation. We then describe Microsoft’s machine translation system and measure the quality of its translations on the widely used WMT 2017 news translation task from Chinese to English. We find that our latest neural machine translation system has reached a new state-of-the-art, and that the translation quality is at human parity when compared to professional human translations. We also find that it significantly exceeds the quality of crowd-sourced non-professional translations.},\n publisher = {},\n url = {https://www.microsoft.com/en-us/research/publication/achieving-human-parity-on-automatic-chinese-to-english-news-translation/},\n address = {},\n pages = {},\n journal = {},\n volume = {},\n chapter = {},\n isbn = {},\n}", + langpairs={ + "zh-en": [ + "newstest2017-zhen-src.zh.sgm", + "newstest2017-zhen-ref.en.sgm", + "Translator-HumanParityData-master/Translator-HumanParityData/References/Translator-HumanParityData-Reference-HT.txt", + "Translator-HumanParityData-master/Translator-HumanParityData/References/Translator-HumanParityData-Reference-PE.txt", + ], + }, + ), + "wmt16": FakeSGMLDataset( + "wmt16", + data=["https://data.statmt.org/wmt16/translation-task/test.tgz"], + md5=["3d809cd0c2c86adb2c67034d15c4e446"], + description="Official evaluation data.", + citation="@InProceedings{bojar-EtAl:2016:WMT1,\n author = {Bojar, Ond\\v{r}ej and Chatterjee, Rajen and Federmann, Christian and Graham, Yvette and Haddow, Barry and Huck, Matthias and Jimeno Yepes, Antonio and Koehn, Philipp and Logacheva, Varvara and Monz, Christof and Negri, Matteo and Neveol, Aurelie and Neves, Mariana and Popel, Martin and Post, Matt and Rubino, Raphael and Scarton, Carolina and Specia, Lucia and Turchi, Marco and Verspoor, Karin and Zampieri, Marcos},\n title = {Findings of the 2016 Conference on Machine Translation},\n booktitle = {Proceedings of the First Conference on Machine Translation},\n month = {August},\n year = {2016},\n address = {Berlin, Germany},\n publisher = {Association for Computational Linguistics},\n pages = {131--198},\n url = {http://www.aclweb.org/anthology/W/W16/W16-2301}\n}", + langpairs={ + "cs-en": [ + "test/newstest2016-csen-src.cs.sgm", + "test/newstest2016-csen-ref.en.sgm", + ], + "de-en": [ + "test/newstest2016-deen-src.de.sgm", + "test/newstest2016-deen-ref.en.sgm", + ], + "en-cs": [ + "test/newstest2016-encs-src.en.sgm", + "test/newstest2016-encs-ref.cs.sgm", + ], + "en-de": [ + "test/newstest2016-ende-src.en.sgm", + "test/newstest2016-ende-ref.de.sgm", + ], + "en-fi": [ + "test/newstest2016-enfi-src.en.sgm", + "test/newstest2016-enfi-ref.fi.sgm", + ], + "en-ro": [ + "test/newstest2016-enro-src.en.sgm", + "test/newstest2016-enro-ref.ro.sgm", + ], + "en-ru": [ + "test/newstest2016-enru-src.en.sgm", + "test/newstest2016-enru-ref.ru.sgm", + ], + "en-tr": [ + "test/newstest2016-entr-src.en.sgm", + "test/newstest2016-entr-ref.tr.sgm", + ], + "fi-en": [ + "test/newstest2016-fien-src.fi.sgm", + "test/newstest2016-fien-ref.en.sgm", + ], + "ro-en": [ + "test/newstest2016-roen-src.ro.sgm", + "test/newstest2016-roen-ref.en.sgm", + ], + "ru-en": [ + "test/newstest2016-ruen-src.ru.sgm", + "test/newstest2016-ruen-ref.en.sgm", + ], + "tr-en": [ + "test/newstest2016-tren-src.tr.sgm", + "test/newstest2016-tren-ref.en.sgm", + ], + }, + ), + "wmt16/B": FakeSGMLDataset( + "wmt16/B", + data=["https://data.statmt.org/wmt16/translation-task/test.tgz"], + md5=["3d809cd0c2c86adb2c67034d15c4e446"], + description="Additional reference for EN-FI.", + langpairs={ + "en-fi": [ + "test/newstest2016-enfi-src.en.sgm", + "test/newstestB2016-enfi-ref.fi.sgm", + ], + }, + ), + "wmt16/tworefs": FakeSGMLDataset( + "wmt16/tworefs", + data=["https://data.statmt.org/wmt16/translation-task/test.tgz"], + md5=["3d809cd0c2c86adb2c67034d15c4e446"], + description="EN-FI with two references.", + langpairs={ + "en-fi": [ + "test/newstest2016-enfi-src.en.sgm", + "test/newstest2016-enfi-ref.fi.sgm", + "test/newstestB2016-enfi-ref.fi.sgm", + ], + }, + ), + "wmt16/dev": FakeSGMLDataset( + "wmt16/dev", + data=["https://data.statmt.org/wmt16/translation-task/dev.tgz"], + md5=["4a3dc2760bb077f4308cce96b06e6af6"], + description="Development sets released for new languages in 2016.", + langpairs={ + "en-ro": [ + "dev/newsdev2016-enro-src.en.sgm", + "dev/newsdev2016-enro-ref.ro.sgm", + ], + "en-tr": [ + "dev/newsdev2016-entr-src.en.sgm", + "dev/newsdev2016-entr-ref.tr.sgm", + ], + "ro-en": [ + "dev/newsdev2016-roen-src.ro.sgm", + "dev/newsdev2016-roen-ref.en.sgm", + ], + "tr-en": [ + "dev/newsdev2016-tren-src.tr.sgm", + "dev/newsdev2016-tren-ref.en.sgm", + ], + }, + ), + "wmt15": FakeSGMLDataset( + "wmt15", + data=["https://statmt.org/wmt15/test.tgz"], + md5=["67e3beca15e69fe3d36de149da0a96df"], + description="Official evaluation data.", + citation="@InProceedings{bojar-EtAl:2015:WMT,\n author = {Bojar, Ond\\v{r}ej and Chatterjee, Rajen and Federmann, Christian and Haddow, Barry and Huck, Matthias and Hokamp, Chris and Koehn, Philipp and Logacheva, Varvara and Monz, Christof and Negri, Matteo and Post, Matt and Scarton, Carolina and Specia, Lucia and Turchi, Marco},\n title = {Findings of the 2015 Workshop on Statistical Machine Translation},\n booktitle = {Proceedings of the Tenth Workshop on Statistical Machine Translation},\n month = {September},\n year = {2015},\n address = {Lisbon, Portugal},\n publisher = {Association for Computational Linguistics},\n pages = {1--46},\n url = {http://aclweb.org/anthology/W15-3001}\n}", + langpairs={ + "en-fr": [ + "test/newsdiscusstest2015-enfr-src.en.sgm", + "test/newsdiscusstest2015-enfr-ref.fr.sgm", + ], + "fr-en": [ + "test/newsdiscusstest2015-fren-src.fr.sgm", + "test/newsdiscusstest2015-fren-ref.en.sgm", + ], + "cs-en": [ + "test/newstest2015-csen-src.cs.sgm", + "test/newstest2015-csen-ref.en.sgm", + ], + "de-en": [ + "test/newstest2015-deen-src.de.sgm", + "test/newstest2015-deen-ref.en.sgm", + ], + "en-cs": [ + "test/newstest2015-encs-src.en.sgm", + "test/newstest2015-encs-ref.cs.sgm", + ], + "en-de": [ + "test/newstest2015-ende-src.en.sgm", + "test/newstest2015-ende-ref.de.sgm", + ], + "en-fi": [ + "test/newstest2015-enfi-src.en.sgm", + "test/newstest2015-enfi-ref.fi.sgm", + ], + "en-ru": [ + "test/newstest2015-enru-src.en.sgm", + "test/newstest2015-enru-ref.ru.sgm", + ], + "fi-en": [ + "test/newstest2015-fien-src.fi.sgm", + "test/newstest2015-fien-ref.en.sgm", + ], + "ru-en": [ + "test/newstest2015-ruen-src.ru.sgm", + "test/newstest2015-ruen-ref.en.sgm", + ], + }, + ), + "wmt14": FakeSGMLDataset( + "wmt14", + data=["https://statmt.org/wmt14/test-filtered.tgz"], + md5=["84c597844c1542e29c2aff23aaee4310"], + description="Official evaluation data.", + citation="@InProceedings{bojar-EtAl:2014:W14-33,\n author = {Bojar, Ondrej and Buck, Christian and Federmann, Christian and Haddow, Barry and Koehn, Philipp and Leveling, Johannes and Monz, Christof and Pecina, Pavel and Post, Matt and Saint-Amand, Herve and Soricut, Radu and Specia, Lucia and Tamchyna, Ale\\v{s}},\n title = {Findings of the 2014 Workshop on Statistical Machine Translation},\n booktitle = {Proceedings of the Ninth Workshop on Statistical Machine Translation},\n month = {June},\n year = {2014},\n address = {Baltimore, Maryland, USA},\n publisher = {Association for Computational Linguistics},\n pages = {12--58},\n url = {http://www.aclweb.org/anthology/W/W14/W14-3302}\n}", + langpairs={ + "cs-en": [ + "test/newstest2014-csen-src.cs.sgm", + "test/newstest2014-csen-ref.en.sgm", + ], + "en-cs": [ + "test/newstest2014-csen-src.en.sgm", + "test/newstest2014-csen-ref.cs.sgm", + ], + "de-en": [ + "test/newstest2014-deen-src.de.sgm", + "test/newstest2014-deen-ref.en.sgm", + ], + "en-de": [ + "test/newstest2014-deen-src.en.sgm", + "test/newstest2014-deen-ref.de.sgm", + ], + "en-fr": [ + "test/newstest2014-fren-src.en.sgm", + "test/newstest2014-fren-ref.fr.sgm", + ], + "fr-en": [ + "test/newstest2014-fren-src.fr.sgm", + "test/newstest2014-fren-ref.en.sgm", + ], + "en-hi": [ + "test/newstest2014-hien-src.en.sgm", + "test/newstest2014-hien-ref.hi.sgm", + ], + "hi-en": [ + "test/newstest2014-hien-src.hi.sgm", + "test/newstest2014-hien-ref.en.sgm", + ], + "en-ru": [ + "test/newstest2014-ruen-src.en.sgm", + "test/newstest2014-ruen-ref.ru.sgm", + ], + "ru-en": [ + "test/newstest2014-ruen-src.ru.sgm", + "test/newstest2014-ruen-ref.en.sgm", + ], + }, + ), + "wmt14/full": FakeSGMLDataset( + "wmt14/full", + data=["https://statmt.org/wmt14/test-full.tgz"], + md5=["a8cd784e006feb32ac6f3d9ec7eb389a"], + description="Evaluation data released after official evaluation for further research.", + langpairs={ + "cs-en": [ + "test-full/newstest2014-csen-src.cs.sgm", + "test-full/newstest2014-csen-ref.en.sgm", + ], + "en-cs": [ + "test-full/newstest2014-csen-src.en.sgm", + "test-full/newstest2014-csen-ref.cs.sgm", + ], + "de-en": [ + "test-full/newstest2014-deen-src.de.sgm", + "test-full/newstest2014-deen-ref.en.sgm", + ], + "en-de": [ + "test-full/newstest2014-deen-src.en.sgm", + "test-full/newstest2014-deen-ref.de.sgm", + ], + "en-fr": [ + "test-full/newstest2014-fren-src.en.sgm", + "test-full/newstest2014-fren-ref.fr.sgm", + ], + "fr-en": [ + "test-full/newstest2014-fren-src.fr.sgm", + "test-full/newstest2014-fren-ref.en.sgm", + ], + "en-hi": [ + "test-full/newstest2014-hien-src.en.sgm", + "test-full/newstest2014-hien-ref.hi.sgm", + ], + "hi-en": [ + "test-full/newstest2014-hien-src.hi.sgm", + "test-full/newstest2014-hien-ref.en.sgm", + ], + "en-ru": [ + "test-full/newstest2014-ruen-src.en.sgm", + "test-full/newstest2014-ruen-ref.ru.sgm", + ], + "ru-en": [ + "test-full/newstest2014-ruen-src.ru.sgm", + "test-full/newstest2014-ruen-ref.en.sgm", + ], + }, + ), + "wmt13": FakeSGMLDataset( + "wmt13", + data=["https://statmt.org/wmt13/test.tgz"], + md5=["48eca5d02f637af44e85186847141f67"], + description="Official evaluation data.", + citation="@InProceedings{bojar-EtAl:2013:WMT,\n author = {Bojar, Ond\\v{r}ej and Buck, Christian and Callison-Burch, Chris and Federmann, Christian and Haddow, Barry and Koehn, Philipp and Monz, Christof and Post, Matt and Soricut, Radu and Specia, Lucia},\n title = {Findings of the 2013 {Workshop on Statistical Machine Translation}},\n booktitle = {Proceedings of the Eighth Workshop on Statistical Machine Translation},\n month = {August},\n year = {2013},\n address = {Sofia, Bulgaria},\n publisher = {Association for Computational Linguistics},\n pages = {1--44},\n url = {http://www.aclweb.org/anthology/W13-2201}\n}", + langpairs={ + "cs-en": ["test/newstest2013-src.cs.sgm", "test/newstest2013-src.en.sgm"], + "en-cs": ["test/newstest2013-src.en.sgm", "test/newstest2013-src.cs.sgm"], + "de-en": ["test/newstest2013-src.de.sgm", "test/newstest2013-src.en.sgm"], + "en-de": ["test/newstest2013-src.en.sgm", "test/newstest2013-src.de.sgm"], + "es-en": ["test/newstest2013-src.es.sgm", "test/newstest2013-src.en.sgm"], + "en-es": ["test/newstest2013-src.en.sgm", "test/newstest2013-src.es.sgm"], + "fr-en": ["test/newstest2013-src.fr.sgm", "test/newstest2013-src.en.sgm"], + "en-fr": ["test/newstest2013-src.en.sgm", "test/newstest2013-src.fr.sgm"], + "ru-en": ["test/newstest2013-src.ru.sgm", "test/newstest2013-src.en.sgm"], + "en-ru": ["test/newstest2013-src.en.sgm", "test/newstest2013-src.ru.sgm"], + }, + ), + "wmt12": FakeSGMLDataset( + "wmt12", + data=["https://statmt.org/wmt12/test.tgz"], + md5=["608232d34ebc4ba2ff70fead45674e47"], + description="Official evaluation data.", + citation="@InProceedings{callisonburch-EtAl:2012:WMT,\n author = {Callison-Burch, Chris and Koehn, Philipp and Monz, Christof and Post, Matt and Soricut, Radu and Specia, Lucia},\n title = {Findings of the 2012 Workshop on Statistical Machine Translation},\n booktitle = {Proceedings of the Seventh Workshop on Statistical Machine Translation},\n month = {June},\n year = {2012},\n address = {Montr{'e}al, Canada},\n publisher = {Association for Computational Linguistics},\n pages = {10--51},\n url = {http://www.aclweb.org/anthology/W12-3102}\n}", + langpairs={ + "cs-en": ["test/newstest2012-src.cs.sgm", "test/newstest2012-src.en.sgm"], + "en-cs": ["test/newstest2012-src.en.sgm", "test/newstest2012-src.cs.sgm"], + "de-en": ["test/newstest2012-src.de.sgm", "test/newstest2012-src.en.sgm"], + "en-de": ["test/newstest2012-src.en.sgm", "test/newstest2012-src.de.sgm"], + "es-en": ["test/newstest2012-src.es.sgm", "test/newstest2012-src.en.sgm"], + "en-es": ["test/newstest2012-src.en.sgm", "test/newstest2012-src.es.sgm"], + "fr-en": ["test/newstest2012-src.fr.sgm", "test/newstest2012-src.en.sgm"], + "en-fr": ["test/newstest2012-src.en.sgm", "test/newstest2012-src.fr.sgm"], + }, + ), + "wmt11": FakeSGMLDataset( + "wmt11", + data=["https://statmt.org/wmt11/test.tgz"], + md5=["b0c9680adf32d394aefc2b24e3a5937e"], + description="Official evaluation data.", + citation="@InProceedings{callisonburch-EtAl:2011:WMT,\n author = {Callison-Burch, Chris and Koehn, Philipp and Monz, Christof and Zaidan, Omar},\n title = {Findings of the 2011 Workshop on Statistical Machine Translation},\n booktitle = {Proceedings of the Sixth Workshop on Statistical Machine Translation},\n month = {July},\n year = {2011},\n address = {Edinburgh, Scotland},\n publisher = {Association for Computational Linguistics},\n pages = {22--64},\n url = {http://www.aclweb.org/anthology/W11-2103}\n}", + langpairs={ + "cs-en": ["newstest2011-src.cs.sgm", "newstest2011-src.en.sgm"], + "en-cs": ["newstest2011-src.en.sgm", "newstest2011-src.cs.sgm"], + "de-en": ["newstest2011-src.de.sgm", "newstest2011-src.en.sgm"], + "en-de": ["newstest2011-src.en.sgm", "newstest2011-src.de.sgm"], + "fr-en": ["newstest2011-src.fr.sgm", "newstest2011-src.en.sgm"], + "en-fr": ["newstest2011-src.en.sgm", "newstest2011-src.fr.sgm"], + "es-en": ["newstest2011-src.es.sgm", "newstest2011-src.en.sgm"], + "en-es": ["newstest2011-src.en.sgm", "newstest2011-src.es.sgm"], + }, + ), + "wmt10": FakeSGMLDataset( + "wmt10", + data=["https://statmt.org/wmt10/test.tgz"], + md5=["491cb885a355da5a23ea66e7b3024d5c"], + description="Official evaluation data.", + citation="@InProceedings{callisonburch-EtAl:2010:WMT,\n author = {Callison-Burch, Chris and Koehn, Philipp and Monz, Christof and Peterson, Kay and Przybocki, Mark and Zaidan, Omar},\n title = {Findings of the 2010 Joint Workshop on Statistical Machine Translation and Metrics for Machine Translation},\n booktitle = {Proceedings of the Joint Fifth Workshop on Statistical Machine Translation and MetricsMATR},\n month = {July},\n year = {2010},\n address = {Uppsala, Sweden},\n publisher = {Association for Computational Linguistics},\n pages = {17--53},\n note = {Revised August 2010},\n url = {http://www.aclweb.org/anthology/W10-1703}\n}", + langpairs={ + "cs-en": ["test/newstest2010-src.cz.sgm", "test/newstest2010-src.en.sgm"], + "en-cs": ["test/newstest2010-src.en.sgm", "test/newstest2010-src.cz.sgm"], + "de-en": ["test/newstest2010-src.de.sgm", "test/newstest2010-src.en.sgm"], + "en-de": ["test/newstest2010-src.en.sgm", "test/newstest2010-src.de.sgm"], + "es-en": ["test/newstest2010-src.es.sgm", "test/newstest2010-src.en.sgm"], + "en-es": ["test/newstest2010-src.en.sgm", "test/newstest2010-src.es.sgm"], + "fr-en": ["test/newstest2010-src.fr.sgm", "test/newstest2010-src.en.sgm"], + "en-fr": ["test/newstest2010-src.en.sgm", "test/newstest2010-src.fr.sgm"], + }, + ), + "wmt09": FakeSGMLDataset( + "wmt09", + data=["https://statmt.org/wmt09/test.tgz"], + md5=["da227abfbd7b666ec175b742a0d27b37"], + description="Official evaluation data.", + citation="@InProceedings{callisonburch-EtAl:2009:WMT-09,\n author = {Callison-Burch, Chris and Koehn, Philipp and Monz, Christof and Schroeder, Josh},\n title = {Findings of the 2009 {W}orkshop on {S}tatistical {M}achine {T}ranslation},\n booktitle = {Proceedings of the Fourth Workshop on Statistical Machine Translation},\n month = {March},\n year = {2009},\n address = {Athens, Greece},\n publisher = {Association for Computational Linguistics},\n pages = {1--28},\n url = {http://www.aclweb.org/anthology/W/W09/W09-0401}\n}", + langpairs={ + "cs-en": ["test/newstest2009-src.cz.sgm", "test/newstest2009-src.en.sgm"], + "en-cs": ["test/newstest2009-src.en.sgm", "test/newstest2009-src.cz.sgm"], + "de-en": ["test/newstest2009-src.de.sgm", "test/newstest2009-src.en.sgm"], + "en-de": ["test/newstest2009-src.en.sgm", "test/newstest2009-src.de.sgm"], + "es-en": ["test/newstest2009-src.es.sgm", "test/newstest2009-src.en.sgm"], + "en-es": ["test/newstest2009-src.en.sgm", "test/newstest2009-src.es.sgm"], + "fr-en": ["test/newstest2009-src.fr.sgm", "test/newstest2009-src.en.sgm"], + "en-fr": ["test/newstest2009-src.en.sgm", "test/newstest2009-src.fr.sgm"], + "hu-en": ["test/newstest2009-src.hu.sgm", "test/newstest2009-src.en.sgm"], + "en-hu": ["test/newstest2009-src.en.sgm", "test/newstest2009-src.hu.sgm"], + "it-en": ["test/newstest2009-src.it.sgm", "test/newstest2009-src.en.sgm"], + "en-it": ["test/newstest2009-src.en.sgm", "test/newstest2009-src.it.sgm"], + }, + ), + "wmt08": FakeSGMLDataset( + "wmt08", + data=["https://statmt.org/wmt08/test.tgz"], + md5=["0582e4e894a3342044059c894e1aea3d"], + description="Official evaluation data.", + citation="@InProceedings{callisonburch-EtAl:2008:WMT,\n author = {Callison-Burch, Chris and Fordyce, Cameron and Koehn, Philipp and Monz, Christof and Schroeder, Josh},\n title = {Further Meta-Evaluation of Machine Translation},\n booktitle = {Proceedings of the Third Workshop on Statistical Machine Translation},\n month = {June},\n year = {2008},\n address = {Columbus, Ohio},\n publisher = {Association for Computational Linguistics},\n pages = {70--106},\n url = {http://www.aclweb.org/anthology/W/W08/W08-0309}\n}", + langpairs={ + "cs-en": ["test/newstest2008-src.cz.sgm", "test/newstest2008-src.en.sgm"], + "en-cs": ["test/newstest2008-src.en.sgm", "test/newstest2008-src.cz.sgm"], + "de-en": ["test/newstest2008-src.de.sgm", "test/newstest2008-src.en.sgm"], + "en-de": ["test/newstest2008-src.en.sgm", "test/newstest2008-src.de.sgm"], + "es-en": ["test/newstest2008-src.es.sgm", "test/newstest2008-src.en.sgm"], + "en-es": ["test/newstest2008-src.en.sgm", "test/newstest2008-src.es.sgm"], + "fr-en": ["test/newstest2008-src.fr.sgm", "test/newstest2008-src.en.sgm"], + "en-fr": ["test/newstest2008-src.en.sgm", "test/newstest2008-src.fr.sgm"], + "hu-en": ["test/newstest2008-src.hu.sgm", "test/newstest2008-src.en.sgm"], + "en-hu": ["test/newstest2008-src.en.sgm", "test/newstest2008-src.hu.sgm"], + }, + ), + "wmt08/nc": FakeSGMLDataset( + "wmt08/nc", + data=["https://statmt.org/wmt08/test.tgz"], + md5=["0582e4e894a3342044059c894e1aea3d"], + description="Official evaluation data (news commentary).", + langpairs={ + "cs-en": ["test/nc-test2008-src.cz.sgm", "test/nc-test2008-src.en.sgm"], + "en-cs": ["test/nc-test2008-src.en.sgm", "test/nc-test2008-src.cz.sgm"], + }, + ), + "wmt08/europarl": FakeSGMLDataset( + "wmt08/europarl", + data=["https://statmt.org/wmt08/test.tgz"], + md5=["0582e4e894a3342044059c894e1aea3d"], + description="Official evaluation data (Europarl).", + langpairs={ + "de-en": ["test/test2008-src.de.sgm", "test/test2008-src.en.sgm"], + "en-de": ["test/test2008-src.en.sgm", "test/test2008-src.de.sgm"], + "es-en": ["test/test2008-src.es.sgm", "test/test2008-src.en.sgm"], + "en-es": ["test/test2008-src.en.sgm", "test/test2008-src.es.sgm"], + "fr-en": ["test/test2008-src.fr.sgm", "test/test2008-src.en.sgm"], + "en-fr": ["test/test2008-src.en.sgm", "test/test2008-src.fr.sgm"], + }, + ), + # iwslt + "iwslt17": IWSLTXMLDataset( + "iwslt17", + data=[ + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/en/fr/en-fr.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/fr/en/fr-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/en/de/en-de.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/de/en/de-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/en/ar/en-ar.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/ar/en/ar-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/en/ja/en-ja.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/ja/en/ja-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/en/ko/en-ko.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/ko/en/ko-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/en/zh/en-zh.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/zh/en/zh-en.tgz", + ], + md5=[ + "1849bcc3b006dc0642a8843b11aa7192", + "79bf7a2ef02d226875f55fb076e7e473", + "b68e7097b179491f6c466ef41ad72b9b", + "e3f5b2a075a2da1a395c8b60bf1e9be1", + "ecdc6bc4ab4c8984e919444f3c05183a", + "4b5141d14b98706c081371e2f8afe0ca", + "d957ee79de1f33c89077d37c5a2c5b06", + "c213e8bb918ebf843543fe9fd2e33db2", + "59f6a81c707378176e9ad8bb8d811f5f", + "7e580af973bb389ec1d1378a1850742f", + "975a858783a0ebec8c57d83ddd5bd381", + "cc51d9b7fe1ff2af858c6a0dd80b8815", + ], + description="Official evaluation data for IWSLT.", + citation="@InProceedings{iwslt2017,\n author = {Cettolo, Mauro and Federico, Marcello and Bentivogli, Luisa and Niehues, Jan and Stüker, Sebastian and Sudoh, Katsuitho and Yoshino, Koichiro and Federmann, Christian},\n title = {Overview of the IWSLT 2017 Evaluation Campaign},\n booktitle = {14th International Workshop on Spoken Language Translation},\n month = {December},\n year = {2017},\n address = {Tokyo, Japan},\n pages = {2--14},\n url = {http://workshop2017.iwslt.org/downloads/iwslt2017_proceeding_v2.pdf}\n}", + langpairs={ + "en-fr": [ + "en-fr/IWSLT17.TED.tst2017.en-fr.en.xml", + "fr-en/IWSLT17.TED.tst2017.fr-en.fr.xml", + ], + "fr-en": [ + "fr-en/IWSLT17.TED.tst2017.fr-en.fr.xml", + "en-fr/IWSLT17.TED.tst2017.en-fr.en.xml", + ], + "en-de": [ + "en-de/IWSLT17.TED.tst2017.en-de.en.xml", + "de-en/IWSLT17.TED.tst2017.de-en.de.xml", + ], + "de-en": [ + "de-en/IWSLT17.TED.tst2017.de-en.de.xml", + "en-de/IWSLT17.TED.tst2017.en-de.en.xml", + ], + "en-zh": [ + "en-zh/IWSLT17.TED.tst2017.en-zh.en.xml", + "zh-en/IWSLT17.TED.tst2017.zh-en.zh.xml", + ], + "zh-en": [ + "zh-en/IWSLT17.TED.tst2017.zh-en.zh.xml", + "en-zh/IWSLT17.TED.tst2017.en-zh.en.xml", + ], + "en-ar": [ + "en-ar/IWSLT17.TED.tst2017.en-ar.en.xml", + "ar-en/IWSLT17.TED.tst2017.ar-en.ar.xml", + ], + "ar-en": [ + "ar-en/IWSLT17.TED.tst2017.ar-en.ar.xml", + "en-ar/IWSLT17.TED.tst2017.en-ar.en.xml", + ], + "en-ja": [ + "en-ja/IWSLT17.TED.tst2017.en-ja.en.xml", + "ja-en/IWSLT17.TED.tst2017.ja-en.ja.xml", + ], + "ja-en": [ + "ja-en/IWSLT17.TED.tst2017.ja-en.ja.xml", + "en-ja/IWSLT17.TED.tst2017.en-ja.en.xml", + ], + "en-ko": [ + "en-ko/IWSLT17.TED.tst2017.en-ko.en.xml", + "ko-en/IWSLT17.TED.tst2017.ko-en.ko.xml", + ], + "ko-en": [ + "ko-en/IWSLT17.TED.tst2017.ko-en.ko.xml", + "en-ko/IWSLT17.TED.tst2017.en-ko.en.xml", + ], + }, + ), + "iwslt17/tst2016": IWSLTXMLDataset( + "iwslt17/tst2016", + data=[ + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/en/fr/en-fr.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/fr/en/fr-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/en/de/en-de.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/de/en/de-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/en/zh/en-zh.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-ted-test/texts/zh/en/zh-en.tgz", + ], + md5=[ + "1849bcc3b006dc0642a8843b11aa7192", + "79bf7a2ef02d226875f55fb076e7e473", + "b68e7097b179491f6c466ef41ad72b9b", + "e3f5b2a075a2da1a395c8b60bf1e9be1", + "975a858783a0ebec8c57d83ddd5bd381", + "cc51d9b7fe1ff2af858c6a0dd80b8815", + ], + description="Development data for IWSLT 2017.", + langpairs={ + "en-fr": [ + "en-fr/IWSLT17.TED.tst2016.en-fr.en.xml", + "fr-en/IWSLT17.TED.tst2016.fr-en.fr.xml", + ], + "fr-en": [ + "fr-en/IWSLT17.TED.tst2016.fr-en.fr.xml", + "en-fr/IWSLT17.TED.tst2016.en-fr.en.xml", + ], + "en-de": [ + "en-de/IWSLT17.TED.tst2016.en-de.en.xml", + "de-en/IWSLT17.TED.tst2016.de-en.de.xml", + ], + "de-en": [ + "de-en/IWSLT17.TED.tst2016.de-en.de.xml", + "en-de/IWSLT17.TED.tst2016.en-de.en.xml", + ], + "en-zh": [ + "en-zh/IWSLT17.TED.tst2016.en-zh.en.xml", + "zh-en/IWSLT17.TED.tst2016.zh-en.zh.xml", + ], + "zh-en": [ + "zh-en/IWSLT17.TED.tst2016.zh-en.zh.xml", + "en-zh/IWSLT17.TED.tst2016.en-zh.en.xml", + ], + }, + ), + "iwslt17/tst2015": IWSLTXMLDataset( + "iwslt17/tst2015", + data=[ + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/de/en-de.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/de/en/de-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/fr/en-fr.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/fr/en/fr-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/zh/en-zh.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/zh/en/zh-en.tgz", + ], + md5=[ + "d8a32cfc002a4f12b17429cfa78050e6", + "ca2b94d694150d4d6c5dc64c200fa589", + "3cf07ebe305312b12f7f1a4d5f8f8377", + "19927da9de0f40348cad9c0fc61642ac", + "575b788dad6c5b9c5cee636f9ac1094a", + "1c0ae40171d52593df8a6963d3828116", + ], + description="Development data for IWSLT 2017.", + langpairs={ + "en-fr": [ + "en-fr/IWSLT17.TED.tst2015.en-fr.en.xml", + "fr-en/IWSLT17.TED.tst2015.fr-en.fr.xml", + ], + "fr-en": [ + "fr-en/IWSLT17.TED.tst2015.fr-en.fr.xml", + "en-fr/IWSLT17.TED.tst2015.en-fr.en.xml", + ], + "en-de": [ + "en-de/IWSLT17.TED.tst2015.en-de.en.xml", + "de-en/IWSLT17.TED.tst2015.de-en.de.xml", + ], + "de-en": [ + "de-en/IWSLT17.TED.tst2015.de-en.de.xml", + "en-de/IWSLT17.TED.tst2015.en-de.en.xml", + ], + "en-zh": [ + "en-zh/IWSLT17.TED.tst2015.en-zh.en.xml", + "zh-en/IWSLT17.TED.tst2015.zh-en.zh.xml", + ], + "zh-en": [ + "zh-en/IWSLT17.TED.tst2015.zh-en.zh.xml", + "en-zh/IWSLT17.TED.tst2015.en-zh.en.xml", + ], + }, + ), + "iwslt17/tst2014": IWSLTXMLDataset( + "iwslt17/tst2014", + data=[ + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/de/en-de.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/de/en/de-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/fr/en-fr.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/fr/en/fr-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/zh/en-zh.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/zh/en/zh-en.tgz", + ], + md5=[ + "d8a32cfc002a4f12b17429cfa78050e6", + "ca2b94d694150d4d6c5dc64c200fa589", + "3cf07ebe305312b12f7f1a4d5f8f8377", + "19927da9de0f40348cad9c0fc61642ac", + "575b788dad6c5b9c5cee636f9ac1094a", + "1c0ae40171d52593df8a6963d3828116", + ], + description="Development data for IWSLT 2017.", + langpairs={ + "en-fr": [ + "en-fr/IWSLT17.TED.tst2014.en-fr.en.xml", + "fr-en/IWSLT17.TED.tst2014.fr-en.fr.xml", + ], + "fr-en": [ + "fr-en/IWSLT17.TED.tst2014.fr-en.fr.xml", + "en-fr/IWSLT17.TED.tst2014.en-fr.en.xml", + ], + "en-de": [ + "en-de/IWSLT17.TED.tst2014.en-de.en.xml", + "de-en/IWSLT17.TED.tst2014.de-en.de.xml", + ], + "de-en": [ + "de-en/IWSLT17.TED.tst2014.de-en.de.xml", + "en-de/IWSLT17.TED.tst2014.en-de.en.xml", + ], + "en-zh": [ + "en-zh/IWSLT17.TED.tst2014.en-zh.en.xml", + "zh-en/IWSLT17.TED.tst2014.zh-en.zh.xml", + ], + "zh-en": [ + "zh-en/IWSLT17.TED.tst2014.zh-en.zh.xml", + "en-zh/IWSLT17.TED.tst2014.en-zh.en.xml", + ], + }, + ), + "iwslt17/tst2013": IWSLTXMLDataset( + "iwslt17/tst2013", + data=[ + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/de/en-de.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/de/en/de-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/fr/en-fr.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/fr/en/fr-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/zh/en-zh.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/zh/en/zh-en.tgz", + ], + md5=[ + "d8a32cfc002a4f12b17429cfa78050e6", + "ca2b94d694150d4d6c5dc64c200fa589", + "3cf07ebe305312b12f7f1a4d5f8f8377", + "19927da9de0f40348cad9c0fc61642ac", + "575b788dad6c5b9c5cee636f9ac1094a", + "1c0ae40171d52593df8a6963d3828116", + ], + description="Development data for IWSLT 2017.", + langpairs={ + "en-fr": [ + "en-fr/IWSLT17.TED.tst2013.en-fr.en.xml", + "fr-en/IWSLT17.TED.tst2013.fr-en.fr.xml", + ], + "fr-en": [ + "fr-en/IWSLT17.TED.tst2013.fr-en.fr.xml", + "en-fr/IWSLT17.TED.tst2013.en-fr.en.xml", + ], + "en-de": [ + "en-de/IWSLT17.TED.tst2013.en-de.en.xml", + "de-en/IWSLT17.TED.tst2013.de-en.de.xml", + ], + "de-en": [ + "de-en/IWSLT17.TED.tst2013.de-en.de.xml", + "en-de/IWSLT17.TED.tst2013.en-de.en.xml", + ], + "en-zh": [ + "en-zh/IWSLT17.TED.tst2013.en-zh.en.xml", + "zh-en/IWSLT17.TED.tst2013.zh-en.zh.xml", + ], + "zh-en": [ + "zh-en/IWSLT17.TED.tst2013.zh-en.zh.xml", + "en-zh/IWSLT17.TED.tst2013.en-zh.en.xml", + ], + }, + ), + "iwslt17/tst2012": IWSLTXMLDataset( + "iwslt17/tst2012", + data=[ + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/de/en-de.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/de/en/de-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/fr/en-fr.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/fr/en/fr-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/zh/en-zh.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/zh/en/zh-en.tgz", + ], + md5=[ + "d8a32cfc002a4f12b17429cfa78050e6", + "ca2b94d694150d4d6c5dc64c200fa589", + "3cf07ebe305312b12f7f1a4d5f8f8377", + "19927da9de0f40348cad9c0fc61642ac", + "575b788dad6c5b9c5cee636f9ac1094a", + "1c0ae40171d52593df8a6963d3828116", + ], + description="Development data for IWSLT 2017.", + langpairs={ + "en-fr": [ + "en-fr/IWSLT17.TED.tst2012.en-fr.en.xml", + "fr-en/IWSLT17.TED.tst2012.fr-en.fr.xml", + ], + "fr-en": [ + "fr-en/IWSLT17.TED.tst2012.fr-en.fr.xml", + "en-fr/IWSLT17.TED.tst2012.en-fr.en.xml", + ], + "en-de": [ + "en-de/IWSLT17.TED.tst2012.en-de.en.xml", + "de-en/IWSLT17.TED.tst2012.de-en.de.xml", + ], + "de-en": [ + "de-en/IWSLT17.TED.tst2012.de-en.de.xml", + "en-de/IWSLT17.TED.tst2012.en-de.en.xml", + ], + "en-zh": [ + "en-zh/IWSLT17.TED.tst2012.en-zh.en.xml", + "zh-en/IWSLT17.TED.tst2012.zh-en.zh.xml", + ], + "zh-en": [ + "zh-en/IWSLT17.TED.tst2012.zh-en.zh.xml", + "en-zh/IWSLT17.TED.tst2012.en-zh.en.xml", + ], + }, + ), + "iwslt17/tst2011": IWSLTXMLDataset( + "iwslt17/tst2011", + data=[ + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/de/en-de.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/de/en/de-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/fr/en-fr.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/fr/en/fr-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/zh/en-zh.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/zh/en/zh-en.tgz", + ], + md5=[ + "d8a32cfc002a4f12b17429cfa78050e6", + "ca2b94d694150d4d6c5dc64c200fa589", + "3cf07ebe305312b12f7f1a4d5f8f8377", + "19927da9de0f40348cad9c0fc61642ac", + "575b788dad6c5b9c5cee636f9ac1094a", + "1c0ae40171d52593df8a6963d3828116", + ], + description="Development data for IWSLT 2017.", + langpairs={ + "en-fr": [ + "en-fr/IWSLT17.TED.tst2011.en-fr.en.xml", + "fr-en/IWSLT17.TED.tst2011.fr-en.fr.xml", + ], + "fr-en": [ + "fr-en/IWSLT17.TED.tst2011.fr-en.fr.xml", + "en-fr/IWSLT17.TED.tst2011.en-fr.en.xml", + ], + "en-de": [ + "en-de/IWSLT17.TED.tst2011.en-de.en.xml", + "de-en/IWSLT17.TED.tst2011.de-en.de.xml", + ], + "de-en": [ + "de-en/IWSLT17.TED.tst2011.de-en.de.xml", + "en-de/IWSLT17.TED.tst2011.en-de.en.xml", + ], + "en-zh": [ + "en-zh/IWSLT17.TED.tst2011.en-zh.en.xml", + "zh-en/IWSLT17.TED.tst2011.zh-en.zh.xml", + ], + "zh-en": [ + "zh-en/IWSLT17.TED.tst2011.zh-en.zh.xml", + "en-zh/IWSLT17.TED.tst2011.en-zh.en.xml", + ], + }, + ), + "iwslt17/tst2010": IWSLTXMLDataset( + "iwslt17/tst2010", + data=[ + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/de/en-de.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/de/en/de-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/fr/en-fr.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/fr/en/fr-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/zh/en-zh.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/zh/en/zh-en.tgz", + ], + md5=[ + "d8a32cfc002a4f12b17429cfa78050e6", + "ca2b94d694150d4d6c5dc64c200fa589", + "3cf07ebe305312b12f7f1a4d5f8f8377", + "19927da9de0f40348cad9c0fc61642ac", + "575b788dad6c5b9c5cee636f9ac1094a", + "1c0ae40171d52593df8a6963d3828116", + ], + description="Development data for IWSLT 2017.", + langpairs={ + "en-fr": [ + "en-fr/IWSLT17.TED.tst2010.en-fr.en.xml", + "fr-en/IWSLT17.TED.tst2010.fr-en.fr.xml", + ], + "fr-en": [ + "fr-en/IWSLT17.TED.tst2010.fr-en.fr.xml", + "en-fr/IWSLT17.TED.tst2010.en-fr.en.xml", + ], + "en-de": [ + "en-de/IWSLT17.TED.tst2010.en-de.en.xml", + "de-en/IWSLT17.TED.tst2010.de-en.de.xml", + ], + "de-en": [ + "de-en/IWSLT17.TED.tst2010.de-en.de.xml", + "en-de/IWSLT17.TED.tst2010.en-de.en.xml", + ], + "en-zh": [ + "en-zh/IWSLT17.TED.tst2010.en-zh.en.xml", + "zh-en/IWSLT17.TED.tst2010.zh-en.zh.xml", + ], + "zh-en": [ + "zh-en/IWSLT17.TED.tst2010.zh-en.zh.xml", + "en-zh/IWSLT17.TED.tst2010.en-zh.en.xml", + ], + }, + ), + "iwslt17/dev2010": IWSLTXMLDataset( + "iwslt17/dev2010", + data=[ + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/de/en-de.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/de/en/de-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/fr/en-fr.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/fr/en/fr-en.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/en/zh/en-zh.tgz", + "https://raw.githubusercontent.com/hlt-mt/WIT3/master/archive/2017-01-trnted/texts/zh/en/zh-en.tgz", + ], + md5=[ + "d8a32cfc002a4f12b17429cfa78050e6", + "ca2b94d694150d4d6c5dc64c200fa589", + "3cf07ebe305312b12f7f1a4d5f8f8377", + "19927da9de0f40348cad9c0fc61642ac", + "575b788dad6c5b9c5cee636f9ac1094a", + "1c0ae40171d52593df8a6963d3828116", + ], + description="Development data for IWSLT 2017.", + langpairs={ + "en-fr": [ + "en-fr/IWSLT17.TED.dev2010.en-fr.en.xml", + "fr-en/IWSLT17.TED.dev2010.fr-en.fr.xml", + ], + "fr-en": [ + "fr-en/IWSLT17.TED.dev2010.fr-en.fr.xml", + "en-fr/IWSLT17.TED.dev2010.en-fr.en.xml", + ], + "en-de": [ + "en-de/IWSLT17.TED.dev2010.en-de.en.xml", + "de-en/IWSLT17.TED.dev2010.de-en.de.xml", + ], + "de-en": [ + "de-en/IWSLT17.TED.dev2010.de-en.de.xml", + "en-de/IWSLT17.TED.dev2010.en-de.en.xml", + ], + "en-zh": [ + "en-zh/IWSLT17.TED.dev2010.en-zh.en.xml", + "zh-en/IWSLT17.TED.dev2010.zh-en.zh.xml", + ], + "zh-en": [ + "zh-en/IWSLT17.TED.dev2010.zh-en.zh.xml", + "en-zh/IWSLT17.TED.dev2010.en-zh.en.xml", + ], + }, + ), + # mtedx + "mtedx/valid": PlainTextDataset( + "mtedx/valid", + data=[ + "https://raw.githubusercontent.com/esalesky/mtedx-eval/main/valid.tar.gz" + ], + description="mTEDx evaluation data, valid: http://openslr.org/100", + citation="@misc{salesky2021multilingual,\n title={The Multilingual TEDx Corpus for Speech Recognition and Translation}, \n author={Elizabeth Salesky and Matthew Wiesner and Jacob Bremerman and Roldano Cattoni and Matteo Negri and Marco Turchi and Douglas W. Oard and Matt Post},\n year={2021},\n eprint={2102.01757},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}", + md5=["40618171614c50e6cbb5e5bbceee0635"], + langpairs={ + "el-en": ["valid/mtedx-valid-elen.el", "valid/mtedx-valid-elen.en"], + "es-en": ["valid/mtedx-valid-esen.es", "valid/mtedx-valid-esen.en"], + "es-fr": ["valid/mtedx-valid-esfr.es", "valid/mtedx-valid-esfr.fr"], + "es-it": ["valid/mtedx-valid-esit.es", "valid/mtedx-valid-esit.it"], + "es-pt": ["valid/mtedx-valid-espt.es", "valid/mtedx-valid-espt.pt"], + "fr-en": ["valid/mtedx-valid-fren.fr", "valid/mtedx-valid-fren.en"], + "fr-es": ["valid/mtedx-valid-fres.fr", "valid/mtedx-valid-fres.es"], + "fr-pt": ["valid/mtedx-valid-frpt.fr", "valid/mtedx-valid-frpt.pt"], + "it-en": ["valid/mtedx-valid-iten.it", "valid/mtedx-valid-iten.en"], + "it-es": ["valid/mtedx-valid-ites.it", "valid/mtedx-valid-ites.es"], + "pt-en": ["valid/mtedx-valid-pten.pt", "valid/mtedx-valid-pten.en"], + "pt-es": ["valid/mtedx-valid-ptes.pt", "valid/mtedx-valid-ptes.es"], + "ru-en": ["valid/mtedx-valid-ruen.ru", "valid/mtedx-valid-ruen.en"], + }, + ), + "mtedx/test": PlainTextDataset( + "mtedx/test", + data=["https://raw.githubusercontent.com/esalesky/mtedx-eval/main/test.tar.gz"], + description="mTEDx evaluation data, test: http://openslr.org/100", + citation="@misc{salesky2021multilingual,\n title={The Multilingual TEDx Corpus for Speech Recognition and Translation}, \n author={Elizabeth Salesky and Matthew Wiesner and Jacob Bremerman and Roldano Cattoni and Matteo Negri and Marco Turchi and Douglas W. Oard and Matt Post},\n year={2021},\n eprint={2102.01757},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}", + md5=["fa4cb1548c210ec424d7d6bc9a3675a7"], + langpairs={ + "el-en": ["test/mtedx-test-elen.el", "test/mtedx-test-elen.en"], + "es-en": ["test/mtedx-test-esen.es", "test/mtedx-test-esen.en"], + "es-fr": ["test/mtedx-test-esfr.es", "test/mtedx-test-esfr.fr"], + "es-it": ["test/mtedx-test-esit.es", "test/mtedx-test-esit.it"], + "es-pt": ["test/mtedx-test-espt.es", "test/mtedx-test-espt.pt"], + "fr-en": ["test/mtedx-test-fren.fr", "test/mtedx-test-fren.en"], + "fr-es": ["test/mtedx-test-fres.fr", "test/mtedx-test-fres.es"], + "fr-pt": ["test/mtedx-test-frpt.fr", "test/mtedx-test-frpt.pt"], + "it-en": ["test/mtedx-test-iten.it", "test/mtedx-test-iten.en"], + "it-es": ["test/mtedx-test-ites.it", "test/mtedx-test-ites.es"], + "pt-en": ["test/mtedx-test-pten.pt", "test/mtedx-test-pten.en"], + "pt-es": ["test/mtedx-test-ptes.pt", "test/mtedx-test-ptes.es"], + "ru-en": ["test/mtedx-test-ruen.ru", "test/mtedx-test-ruen.en"], + }, + ), + # multi30k + "multi30k/2016": PlainTextDataset( + "multi30k/2016", + data=[ + "https://raw.githubusercontent.com/multi30k/dataset/master/data/task1/multi30k_test_sets_d3ec2a38.tar.gz" + ], + md5=["9cf8f22d57fee2ca2af3c682dfdc525b"], + description="2016 flickr test set of Multi30k dataset", + citation='@InProceedings{elliott-etal-2016-multi30k,\n title = "{M}ulti30{K}: Multilingual {E}nglish-{G}erman Image Descriptions",\n author = "Elliott, Desmond and Frank, Stella and Sima{\'}an, Khalil and Specia, Lucia",\n booktitle = "Proceedings of the 5th Workshop on Vision and Language",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W16-3210",\n doi = "10.18653/v1/W16-3210",\n pages = "70--74",\n}', + langpairs={ + "en-fr": ["test_2016_flickr.en", "test_2016_flickr.fr"], + "en-de": ["test_2016_flickr.en", "test_2016_flickr.de"], + "en-cs": ["test_2016_flickr.en", "test_2016_flickr.cs"], + }, + ), + "multi30k/2017": PlainTextDataset( + "multi30k/2017", + data=[ + "https://raw.githubusercontent.com/multi30k/dataset/master/data/task1/multi30k_test_sets_d3ec2a38.tar.gz" + ], + md5=["9cf8f22d57fee2ca2af3c682dfdc525b"], + description="2017 flickr test set of Multi30k dataset", + citation='@InProceedings{elliott-etal-2016-multi30k,\n title = "{M}ulti30{K}: Multilingual {E}nglish-{G}erman Image Descriptions",\n author = "Elliott, Desmond and Frank, Stella and Sima{\'}an, Khalil and Specia, Lucia",\n booktitle = "Proceedings of the 5th Workshop on Vision and Language",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W16-3210",\n doi = "10.18653/v1/W16-3210",\n pages = "70--74",\n}\n\n@InProceedings{elliott-etal-2017-findings,\n title = "Findings of the Second Shared Task on Multimodal Machine Translation and Multilingual Image Description",\n author = {Elliott, Desmond and Frank, Stella and Barrault, Lo{\\"\\i}c and Bougares, Fethi and Specia, Lucia},\n booktitle = "Proceedings of the Second Conference on Machine Translation",\n month = sep,\n year = "2017",\n address = "Copenhagen, Denmark",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W17-4718",\n doi = "10.18653/v1/W17-4718",\n pages = "215--233",\n}\n', + langpairs={ + "en-fr": ["test_2017_flickr.en", "test_2017_flickr.fr"], + "en-de": ["test_2017_flickr.en", "test_2017_flickr.de"], + }, + ), + "multi30k/2018": PlainTextDataset( + "multi30k/2018", + data=[ + "https://raw.githubusercontent.com/multi30k/dataset/master/data/task1/multi30k_test_sets_d3ec2a38.tar.gz", + "https://raw.githubusercontent.com/multi30k/dataset/master/data/task1/raw/test_2018_flickr.cs.gz", + "https://raw.githubusercontent.com/multi30k/dataset/master/data/task1/raw/test_2018_flickr.de.gz", + "https://raw.githubusercontent.com/multi30k/dataset/master/data/task1/raw/test_2018_flickr.fr.gz", + ], + md5=[ + "9cf8f22d57fee2ca2af3c682dfdc525b", + "4c6b6490e58107b2e397c5e3e1690abc", + "87e00327083dd69feaa029a8f7c1a047", + "a64563e986438ed731a6713027c36bfd", + ], + description="2018 flickr test set of Multi30k dataset. See https://competitions.codalab.org/competitions/19917 for evaluation.", + citation='@InProceedings{elliott-etal-2016-multi30k,\n title = "{M}ulti30{K}: Multilingual {E}nglish-{G}erman Image Descriptions",\n author = "Elliott, Desmond and Frank, Stella and Sima{\'}an, Khalil and Specia, Lucia",\n booktitle = "Proceedings of the 5th Workshop on Vision and Language",\n month = aug,\n year = "2016",\n address = "Berlin, Germany",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W16-3210",\n doi = "10.18653/v1/W16-3210",\n pages = "70--74",\n}\n\n@InProceedings{barrault-etal-2018-findings,\n title = "Findings of the Third Shared Task on Multimodal Machine Translation",\n author = {Barrault, Lo{\\"\\i}c and Bougares, Fethi and Specia, Lucia and Lala, Chiraag and Elliott, Desmond and Frank, Stella},\n booktitle = "Proceedings of the Third Conference on Machine Translation: Shared Task Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6402",\n doi = "10.18653/v1/W18-6402",\n pages = "304--323",\n}\n', + langpairs={ + "en-fr": ["test_2018_flickr.en", "multi30k_2018.test_2018_flickr.fr.gz"], + "en-de": ["test_2018_flickr.en", "multi30k_2018.test_2018_flickr.de.gz"], + "en-cs": ["test_2018_flickr.en", "multi30k_2018.test_2018_flickr.cs.gz"], + }, + ), + # mtnt + "mtnt2019": TSVDataset( + "mtnt2019", + data=["https://pmichel31415.github.io/hosting/MTNT2019.tar.gz"], + description="Test set for the WMT 19 robustness shared task", + md5=["78a672e1931f106a8549023c0e8af8f6"], + langpairs={ + "en-fr": ["2:MTNT2019/en-fr.final.tsv", "3:MTNT2019/en-fr.final.tsv"], + "fr-en": ["2:MTNT2019/fr-en.final.tsv", "3:MTNT2019/fr-en.final.tsv"], + "en-ja": ["2:MTNT2019/en-ja.final.tsv", "3:MTNT2019/en-ja.final.tsv"], + "ja-en": ["2:MTNT2019/ja-en.final.tsv", "3:MTNT2019/ja-en.final.tsv"], + }, + ), + "mtnt1.1/test": TSVDataset( + "mtnt1.1/test", + data=[ + "https://github.com/pmichel31415/mtnt/releases/download/v1.1/MTNT.1.1.tar.gz" + ], + description="Test data for the Machine Translation of Noisy Text task: http://www.cs.cmu.edu/~pmichel1/mtnt/", + citation='@InProceedings{michel2018a:mtnt,\n author = "Michel, Paul and Neubig, Graham",\n title = "MTNT: A Testbed for Machine Translation of Noisy Text",\n booktitle = "Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing",\n year = "2018",\n publisher = "Association for Computational Linguistics",\n pages = "543--553",\n location = "Brussels, Belgium",\n url = "http://aclweb.org/anthology/D18-1050"\n}', + md5=["8ce1831ac584979ba8cdcd9d4be43e1d"], + langpairs={ + "en-fr": ["1:MTNT/test/test.en-fr.tsv", "2:MTNT/test/test.en-fr.tsv"], + "fr-en": ["1:MTNT/test/test.fr-en.tsv", "2:MTNT/test/test.fr-en.tsv"], + "en-ja": ["1:MTNT/test/test.en-ja.tsv", "2:MTNT/test/test.en-ja.tsv"], + "ja-en": ["1:MTNT/test/test.ja-en.tsv", "2:MTNT/test/test.ja-en.tsv"], + }, + ), + "mtnt1.1/valid": TSVDataset( + "mtnt1.1/valid", + data=[ + "https://github.com/pmichel31415/mtnt/releases/download/v1.1/MTNT.1.1.tar.gz" + ], + description="Validation data for the Machine Translation of Noisy Text task: http://www.cs.cmu.edu/~pmichel1/mtnt/", + citation='@InProceedings{michel2018a:mtnt,\n author = "Michel, Paul and Neubig, Graham",\n title = "MTNT: A Testbed for Machine Translation of Noisy Text",\n booktitle = "Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing",\n year = "2018",\n publisher = "Association for Computational Linguistics",\n pages = "543--553",\n location = "Brussels, Belgium",\n url = "http://aclweb.org/anthology/D18-1050"\n}', + md5=["8ce1831ac584979ba8cdcd9d4be43e1d"], + langpairs={ + "en-fr": ["1:MTNT/valid/valid.en-fr.tsv", "2:MTNT/valid/valid.en-fr.tsv"], + "fr-en": ["1:MTNT/valid/valid.fr-en.tsv", "2:MTNT/valid/valid.fr-en.tsv"], + "en-ja": ["1:MTNT/valid/valid.en-ja.tsv", "2:MTNT/valid/valid.en-ja.tsv"], + "ja-en": ["1:MTNT/valid/valid.ja-en.tsv", "2:MTNT/valid/valid.ja-en.tsv"], + }, + ), + "mtnt1.1/train": TSVDataset( + "mtnt1.1/train", + data=[ + "https://github.com/pmichel31415/mtnt/releases/download/v1.1/MTNT.1.1.tar.gz" + ], + description="Validation data for the Machine Translation of Noisy Text task: http://www.cs.cmu.edu/~pmichel1/mtnt/", + citation='@InProceedings{michel2018a:mtnt,\n author = "Michel, Paul and Neubig, Graham",\n title = "MTNT: A Testbed for Machine Translation of Noisy Text",\n booktitle = "Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing",\n year = "2018",\n publisher = "Association for Computational Linguistics",\n pages = "543--553",\n location = "Brussels, Belgium",\n url = "http://aclweb.org/anthology/D18-1050"\n}', + md5=["8ce1831ac584979ba8cdcd9d4be43e1d"], + langpairs={ + "en-fr": ["1:MTNT/train/train.en-fr.tsv", "2:MTNT/train/train.en-fr.tsv"], + "fr-en": ["1:MTNT/train/train.fr-en.tsv", "2:MTNT/train/train.fr-en.tsv"], + "en-ja": ["1:MTNT/train/train.en-ja.tsv", "2:MTNT/train/train.en-ja.tsv"], + "ja-en": ["1:MTNT/train/train.ja-en.tsv", "2:MTNT/train/train.ja-en.tsv"], + }, + ), +} diff --git a/venv/lib/python3.10/site-packages/sacrebleu/dataset/__main__.py b/venv/lib/python3.10/site-packages/sacrebleu/dataset/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b13d59a4f896719cc73cee5343872e28f92af63 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/dataset/__main__.py @@ -0,0 +1,45 @@ +import sys + +from . import DATASETS + +try: + cmd = sys.argv[1] +except IndexError: + print(f"Usage: {sys.argv[0]} --check | --dump") + sys.exit(1) + +if cmd == "--check": + import hashlib + import urllib.request + + url_md5 = {} + + for item in DATASETS.values(): + if item.md5 is not None: + assert item.data + assert item.md5 + assert len(item.data) == len(item.md5) + pairs = zip(item.data, item.md5) + for url, md5_hash in pairs: + url_md5[url] = md5_hash + + for url, md5_hash in url_md5.items(): + try: + print("Downloading ", url) + with urllib.request.urlopen(url) as f: + data = f.read() + except Exception as exc: + raise (exc) + + if hashlib.md5(data).hexdigest() != md5_hash: + print("MD5 check failed for", url) +elif cmd == "--dump": + import re + + # Dumps a table in markdown format + print(f'| {"Dataset":<30} | {"Description":<115} |') + header = "| " + "-" * 30 + " | " + "-" * 115 + " |" + print(header) + for name, item in DATASETS.items(): + desc = re.sub(r"(http[s]?:\/\/\S+)", r"[URL](\1)", str(item.description)) + print(f"| {name:<30} | {desc:<115} |") diff --git a/venv/lib/python3.10/site-packages/sacrebleu/dataset/iwslt_xml.py b/venv/lib/python3.10/site-packages/sacrebleu/dataset/iwslt_xml.py new file mode 100644 index 0000000000000000000000000000000000000000..4381271d0ed69338e975f50eb0cf10977a9df96b --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/dataset/iwslt_xml.py @@ -0,0 +1,8 @@ +from .fake_sgml import FakeSGMLDataset + + +class IWSLTXMLDataset(FakeSGMLDataset): + """IWSLT dataset format. Can be parsed with the lxml parser.""" + + # Same as FakeSGMLDataset. Nothing to do here. + pass diff --git a/venv/lib/python3.10/site-packages/sacrebleu/dataset/plain_text.py b/venv/lib/python3.10/site-packages/sacrebleu/dataset/plain_text.py new file mode 100644 index 0000000000000000000000000000000000000000..7f7a93db5339cdfa563fff390d4fb246da8350b4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/dataset/plain_text.py @@ -0,0 +1,36 @@ +import os + +from ..utils import smart_open +from .base import Dataset + + +class PlainTextDataset(Dataset): + """ + The plain text format. Data is separated into source and reference files. + Each line of the two files is aligned. + """ + + def process_to_text(self, langpair=None): + """Processes raw files to plain text files. + + :param langpair: The language pair to process. e.g. "en-de". If None, all files will be processed. + """ + # ensure that the dataset is downloaded + self.maybe_download() + langpairs = self._get_langpair_metadata(langpair) + + for langpair in langpairs: + fieldnames = self.fieldnames(langpair) + origin_files = [ + os.path.join(self._rawdir, path) for path in langpairs[langpair] + ] + + for field, origin_file in zip(fieldnames, origin_files): + + origin_file = os.path.join(self._rawdir, origin_file) + output_file = self._get_txt_file_path(langpair, field) + + with smart_open(origin_file) as fin: + with smart_open(output_file, "wt") as fout: + for line in fin: + print(line.rstrip(), file=fout) diff --git a/venv/lib/python3.10/site-packages/sacrebleu/dataset/tsv.py b/venv/lib/python3.10/site-packages/sacrebleu/dataset/tsv.py new file mode 100644 index 0000000000000000000000000000000000000000..011bf20dd7e894a705d0327c44ceeb4faea5cc6b --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/dataset/tsv.py @@ -0,0 +1,61 @@ +import os + +from ..utils import smart_open +from .base import Dataset + + +class TSVDataset(Dataset): + """ + The format used by the MTNT datasets. Data is in a single TSV file. + """ + + @staticmethod + def _split_index_and_filename(meta, field): + """ + Splits the index and filename from a metadata string. + + e.g. meta="3:en-de.tsv", filed=[Any value] -> (3, "en-de.tsv") + "en-de.tsv", filed="src" -> (1, "en-de.tsv") + "en-de.tsv", filed="tgt" -> (2, "en-de.tsv") + """ + arr = meta.split(":") + if len(arr) == 2: + try: + index = int(arr[0]) + except ValueError: + raise Exception(f"Invalid meta for TSVDataset: {meta}") + return index, arr[1] + + else: + index = 0 if field == "src" else 1 + return index, meta + + def process_to_text(self, langpair=None): + """Processes raw files to plain text files. + + :param langpair: The language pair to process. e.g. "en-de". If None, all files will be processed. + """ + # ensure that the dataset is downloaded + self.maybe_download() + langpairs = self._get_langpair_metadata(langpair) + + for langpair in langpairs: + fieldnames = self.fieldnames(langpair) + origin_files = [ + os.path.join(self._rawdir, path) for path in langpairs[langpair] + ] + + for field, origin_file, meta in zip( + fieldnames, origin_files, langpairs[langpair] + ): + index, origin_file = self._split_index_and_filename(meta, field) + + origin_file = os.path.join(self._rawdir, origin_file) + output_file = self._get_txt_file_path(langpair, field) + + with smart_open(origin_file) as fin: + with smart_open(output_file, "wt") as fout: + for line in fin: + # be careful with empty source or reference lines + # MTNT2019/ja-en.final.tsv:632 `'1033\t718\t\t\n'` + print(line.rstrip("\n").split("\t")[index], file=fout) diff --git a/venv/lib/python3.10/site-packages/sacrebleu/py.typed b/venv/lib/python3.10/site-packages/sacrebleu/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/sacrebleu/sacrebleu.py b/venv/lib/python3.10/site-packages/sacrebleu/sacrebleu.py new file mode 100644 index 0000000000000000000000000000000000000000..d778e1db9fd55adf18e700876144c11b0e9f955d --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/sacrebleu.py @@ -0,0 +1,577 @@ +#!/usr/bin/env python3 + +# Copyright 2017--2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You may not +# use this file except in compliance with the License. A copy of the License +# is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is distributed on +# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +# express or implied. See the License for the specific language governing +# permissions and limitations under the License. + +""" +SacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores. +Inspired by Rico Sennrich's `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text. +It also knows all the standard test sets and handles downloading, processing, and tokenization for you. + +See the [README.md] file for more information. +""" + +import io +import os +import sys +import logging +import pathlib +import argparse +from collections import defaultdict + + +# Allows calling the script as a standalone utility +# See: https://github.com/mjpost/sacrebleu/issues/86 +if __package__ is None and __name__ == '__main__': + parent = pathlib.Path(__file__).absolute().parents[1] + sys.path.insert(0, str(parent)) + __package__ = 'sacrebleu' + +from .dataset import DATASETS +from .metrics import METRICS +from .utils import smart_open, filter_subset, get_langpairs_for_testset, get_available_testsets +from .utils import print_test_set, print_subset_results, get_reference_files, download_test_set +from .utils import args_to_dict, sanity_check_lengths, print_results_table, print_single_results +from .utils import get_available_testsets_for_langpair, Color + +from . import __version__ as VERSION + +sacrelogger = logging.getLogger('sacrebleu') + +try: + # SIGPIPE is not available on Windows machines, throwing an exception. + from signal import SIGPIPE # type: ignore + + # If SIGPIPE is available, change behaviour to default instead of ignore. + from signal import signal, SIG_DFL + signal(SIGPIPE, SIG_DFL) +except ImportError: + pass + + +def parse_args(): + arg_parser = argparse.ArgumentParser( + description='sacreBLEU: Hassle-free computation of shareable BLEU scores.\n' + 'Quick usage: score your detokenized output against WMT\'14 EN-DE:\n' + ' cat output.detok.de | sacrebleu -t wmt14 -l en-de', + formatter_class=argparse.RawDescriptionHelpFormatter) + + arg_parser.add_argument('--citation', '--cite', default=False, action='store_true', + help='Dump the bibtex citation and quit.') + arg_parser.add_argument('--list', default=False, action='store_true', + help='Print a list of all available test sets.') + arg_parser.add_argument('--test-set', '-t', type=str, default=None, + help='The test set to use (see also --list) or a comma-separated list of test sets to be concatenated.') + arg_parser.add_argument('--language-pair', '-l', dest='langpair', default=None, + help='Source-target language pair (2-char ISO639-1 codes).') + arg_parser.add_argument('--origlang', '-ol', dest='origlang', default=None, + help='Use a subset of sentences with a given original language (2-char ISO639-1 codes), "non-" prefix means negation.') + arg_parser.add_argument('--subset', dest='subset', default=None, + help='Use a subset of sentences whose document annotation matches a given regex (see SUBSETS in the source code).') + arg_parser.add_argument('--download', type=str, default=None, + help='Download a test set and quit.') + arg_parser.add_argument('--echo', nargs="+", type=str, default=None, + help='Output the source (src), reference (ref), or other available field (docid, ref:A, ref:1 for example) to STDOUT and quit. ' + 'You can get available fields with options `--list` and `-t`' 'For example: `sacrebleu -t wmt21 --list`. ' + 'If multiple fields are given, they are outputted with tsv format in the order they are given.' + 'You can also use `--echo all` to output all available fields.') + + # I/O related arguments + # Multiple input files can be provided for significance testing for example + arg_parser.add_argument('--input', '-i', type=str, nargs='*', default=None, + help='Read input from file(s) instead of STDIN.') + arg_parser.add_argument('refs', nargs='*', default=[], + help='Optional list of references. If given, it should preceed the -i/--input argument.') + arg_parser.add_argument('--num-refs', '-nr', type=int, default=1, + help='Split the reference stream on tabs, and expect this many references. (Default: %(default)s)') + arg_parser.add_argument('--encoding', '-e', type=str, default='utf-8', + help='Open text files with specified encoding (Default: %(default)s)') + + # Metric selection + avail_metrics = [m.lower() for m in METRICS] + arg_parser.add_argument('--metrics', '-m', choices=avail_metrics, nargs='+', default=['bleu'], + help='Space-delimited list of metrics to compute (Default: bleu)') + arg_parser.add_argument('--sentence-level', '-sl', action='store_true', help='Compute metric for each sentence.') + + # BLEU-related arguments + # since sacreBLEU had only support for BLEU initially, the argument names + # are not prefixed with 'bleu' as in chrF arguments for example. + # Let's do that manually here through dest= options, as otherwise + # things will get quite hard to maintain when other metrics are added. + bleu_args = arg_parser.add_argument_group('BLEU related arguments') + + bleu_args.add_argument('--smooth-method', '-s', choices=METRICS['BLEU'].SMOOTH_DEFAULTS.keys(), default='exp', + dest='bleu_smooth_method', + help='Smoothing method: exponential decay, floor (increment zero counts), add-k (increment num/denom by k for n>1), or none. (Default: %(default)s)') + bleu_args.add_argument('--smooth-value', '-sv', type=float, default=None, + dest='bleu_smooth_value', + help='The smoothing value. Only valid for floor and add-k. ' + f"(Defaults: floor: {METRICS['BLEU'].SMOOTH_DEFAULTS['floor']}, " + f"add-k: {METRICS['BLEU'].SMOOTH_DEFAULTS['add-k']})") + bleu_args.add_argument('--tokenize', '-tok', choices=METRICS['BLEU'].TOKENIZERS, default=None, + dest='bleu_tokenize', + help='Tokenization method to use for BLEU. If not provided, defaults to `zh` for Chinese, ' + '`ja-mecab` for Japanese, `ko-mecab` for Korean and `13a` (mteval) otherwise.') + bleu_args.add_argument('--lowercase', '-lc', dest='bleu_lowercase', action='store_true', default=False, + help='If True, enables case-insensitivity. (Default: %(default)s)') + bleu_args.add_argument('--force', default=False, action='store_true', + dest='bleu_force', help='Insist that your tokenized input is actually detokenized.') + + # ChrF-related arguments + chrf_args = arg_parser.add_argument_group('chrF related arguments') + chrf_args.add_argument('--chrf-char-order', '-cc', type=int, default=METRICS['CHRF'].CHAR_ORDER, + help='Character n-gram order. (Default: %(default)s)') + chrf_args.add_argument('--chrf-word-order', '-cw', type=int, default=METRICS['CHRF'].WORD_ORDER, + help='Word n-gram order (Default: %(default)s). If equals to 2, the metric is referred to as chrF++.') + chrf_args.add_argument('--chrf-beta', type=int, default=METRICS['CHRF'].BETA, + help='Determine the importance of recall w.r.t precision. (Default: %(default)s)') + chrf_args.add_argument('--chrf-whitespace', action='store_true', default=False, + help='Include whitespaces when extracting character n-grams. (Default: %(default)s)') + chrf_args.add_argument('--chrf-lowercase', action='store_true', default=False, + help='Enable case-insensitivity. (Default: %(default)s)') + chrf_args.add_argument('--chrf-eps-smoothing', action='store_true', default=False, + help='Enables epsilon smoothing similar to chrF++.py, NLTK and Moses; instead of effective order smoothing. (Default: %(default)s)') + + # TER related arguments + ter_args = arg_parser.add_argument_group("TER related arguments (The defaults replicate TERCOM's behavior)") + ter_args.add_argument('--ter-case-sensitive', action='store_true', + help='Enables case sensitivity. (Default: %(default)s)') + ter_args.add_argument('--ter-asian-support', action='store_true', + help='Enables special treatment of Asian characters. (Default: %(default)s)') + ter_args.add_argument('--ter-no-punct', action='store_true', + help='Removes punctuation. (Default: %(default)s)') + ter_args.add_argument('--ter-normalized', action='store_true', + help='Applies basic normalization and tokenization. (Default: %(default)s)') + + # Bootstrap resampling for confidence intervals + sign_args = arg_parser.add_argument_group('Confidence interval (CI) estimation for single-system evaluation') + sign_args.add_argument('--confidence', '-ci', action='store_true', + help='Report confidence interval using bootstrap resampling.') + sign_args.add_argument('--confidence-n', '-cin', type=int, default=1000, + help='Set the number of bootstrap resamples for CI estimation (Default: %(default)s).') + + # Paired significance testing + pair_args = arg_parser.add_argument_group('Paired significance testing for multi-system evaluation') + pair_args_choice = pair_args.add_mutually_exclusive_group() + + pair_args_choice.add_argument('--paired-ar', '-par', action='store_true', + help='Perform paired test using approximate randomization (AR). This option is ' + 'mutually exclusive with --paired-bs (Default: %(default)s).') + pair_args_choice.add_argument('--paired-bs', '-pbs', action='store_true', + help='Perform paired test using bootstrap resampling. This option is ' + 'mutually exclusive with --paired-ar (Default: %(default)s).') + + pair_args.add_argument('--paired-ar-n', '-parn', type=int, default=10000, + help='Number of trials for approximate randomization test (Default: %(default)s).') + + pair_args.add_argument('--paired-bs-n', '-pbsn', type=int, default=1000, + help='Number of bootstrap resamples for paired bootstrap resampling test (Default: %(default)s).') + + pair_args.add_argument('--paired-jobs', '-j', type=int, default=1, + help='If 0, launches as many workers as the number of systems. If > 0, sets the number of workers manually. ' + 'This feature is currently not supported on Windows.') + + # Reporting related arguments + report_args = arg_parser.add_argument_group('Reporting related arguments') + report_args.add_argument('--quiet', '-q', default=False, action='store_true', + help='Suppress verbose messages.') + report_args.add_argument('--short', '-sh', default=False, action='store_true', + help='Produce a shorter (less human readable) signature.') + report_args.add_argument('--score-only', '-b', default=False, action='store_true', + help='Print only the computed score.') + report_args.add_argument('--width', '-w', type=int, default=1, + help='Floating point width (Default: %(default)s).') + report_args.add_argument('--detail', '-d', default=False, action='store_true', + help='Print detailed information (split test sets based on origlang).') + report_args.add_argument('--no-color', '-nc', action='store_true', + help='Disable the occasional use of terminal colors.') + + output_formats = ['json', 'text', 'latex'] + report_args.add_argument('--format', '-f', default='json', choices=output_formats, + help='Set the output format. `latex` is only valid for multi-system mode whereas ' + '`json` and `text` apply to single-system mode only. This flag is overridden if the ' + 'SACREBLEU_FORMAT environment variable is set to one of the valid choices (Default: %(default)s).') + + arg_parser.add_argument('--version', '-V', action='version', version='%(prog)s {}'.format(VERSION)) + + args = arg_parser.parse_args() + + # Override the format from the environment, if any + if 'SACREBLEU_FORMAT' in os.environ: + _new_value = os.environ['SACREBLEU_FORMAT'].lower() + if _new_value in output_formats: + args.format = _new_value + + return args + + +def main(): + args = parse_args() + + # Is paired test requested? + paired_test_mode = args.paired_bs or args.paired_ar + + # Explicitly set the encoding + sys.stdin = open(sys.stdin.fileno(), mode='r', encoding='utf-8', buffering=True, newline="\n") + sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf-8', buffering=True) + + if os.environ.get('NO_COLOR', False) or args.no_color: + Color.ENABLE_COLORS = False + else: + # These should come after all stdout manipulations otherwise cause + # issues esp. on Windows + import colorama + colorama.init() + + if not args.quiet: + logging.basicConfig(level=logging.INFO, format='sacreBLEU: %(message)s') + + if args.download: + download_test_set(args.download, args.langpair) + sys.exit(0) + + if args.list: + if args.test_set: + langpairs = get_langpairs_for_testset(args.test_set) + for pair in langpairs: + fields = DATASETS[args.test_set].fieldnames(pair) + print(f'{pair}: {", ".join(fields)}') + else: + if args.langpair: + print(f'The available test sets for {args.langpair} are:') + testsets = get_available_testsets_for_langpair(args.langpair) + else: + print('The available test sets are:') + testsets = get_available_testsets() + for testset in sorted(testsets): + desc = DATASETS[testset].description.strip() + print(f'{testset:<30}: {desc}') + sys.exit(0) + + if args.sentence_level and len(args.metrics) > 1: + sacrelogger.error('Only one metric can be used in sentence-level mode.') + sys.exit(1) + + if args.citation: + if not args.test_set: + sacrelogger.error('I need a test set (-t).') + sys.exit(1) + for test_set in args.test_set.split(','): + if 'citation' not in DATASETS[test_set]: + sacrelogger.error(f'No citation found for {test_set}') + else: + print(DATASETS[test_set].citation) + sys.exit(0) + + if args.num_refs != 1 and (args.test_set is not None or len(args.refs) > 1): + sacrelogger.error('The --num-refs argument allows you to provide any number of tab-delimited references in a single file.') + sacrelogger.error('You can only use it with externally provided references, however (i.e., not with `-t`),') + sacrelogger.error('and you cannot then provide multiple reference files.') + sys.exit(1) + + if args.test_set is not None: + for test_set in args.test_set.split(','): + if test_set not in DATASETS: + sacrelogger.error(f'Unknown test set {test_set!r}') + sacrelogger.error('Please run with --list to see the available test sets.') + sys.exit(1) + + if args.test_set is None: + if len(args.refs) == 0: + sacrelogger.error('If manual references given, make sure to provide them ' + 'before the -i/--input argument to avoid confusion.') + sacrelogger.error('Otherwise, I need a predefined test set (-t) from the following list:') + sacrelogger.error(get_available_testsets()) + sys.exit(1) + elif len(args.refs) > 0: + sacrelogger.error('I need exactly one of (a) a predefined test set (-t) or (b) a list of references') + sys.exit(1) + elif args.langpair is None: + sacrelogger.error('I need a language pair (-l). Use --list to see available language pairs for this test set.') + sys.exit(1) + else: + for test_set in args.test_set.split(','): + langpairs = get_langpairs_for_testset(test_set) + if args.langpair not in langpairs: + sacrelogger.error(f'No such language pair {args.langpair!r}') + sacrelogger.error(f'Available language pairs for {test_set!r} are:') + for lp in langpairs: + sacrelogger.error(f' > {lp}') + sys.exit(1) + + if args.echo: + if args.langpair is None or args.test_set is None: + sacrelogger.warning("--echo requires a test set (--t) and a language pair (-l)") + sys.exit(1) + for test_set in args.test_set.split(','): + print_test_set(test_set, args.langpair, args.echo, args.origlang, args.subset) + sys.exit(0) + + # Hack: inject target language info for BLEU, so that it can + # select the tokenizer based on it + if args.langpair: + args.bleu_trg_lang = args.langpair.split('-')[1] + + if args.test_set is not None and args.bleu_tokenize == 'none': + sacrelogger.warning( + "You are turning off BLEU's internal tokenizer " + "presumably to supply your own tokenized files.") + sacrelogger.warning( + "Published numbers will not be comparable to other papers.") + + # concat_ref_files is a list of list of reference filenames + # (concatenation happens if multiple test sets are given through -t) + # Example: [[testset1_refA, testset1_refB], [testset2_refA, testset2_refB]] + concat_ref_files = [] + if args.test_set is None: + concat_ref_files.append(args.refs) + else: + # Multiple test sets can be given + for test_set in args.test_set.split(','): + ref_files = get_reference_files(test_set, args.langpair) + if len(ref_files) == 0: + sacrelogger.warning( + f'No references found for test set {test_set}/{args.langpair}.') + concat_ref_files.append(ref_files) + + ################# + # Read references + ################# + full_refs = [[] for x in range(max(len(concat_ref_files[0]), args.num_refs))] + for ref_files in concat_ref_files: + for refno, ref_file in enumerate(ref_files): + for lineno, line in enumerate(smart_open(ref_file, encoding=args.encoding), 1): + line = line.rstrip() + if args.num_refs == 1: + full_refs[refno].append(line) + else: + refs = line.split(sep='\t', maxsplit=args.num_refs - 1) + # We are strict in fixed number of references through CLI + # But the API supports having variable refs per each segment + # by simply having '' or None's as dummy placeholders + if len(refs) != args.num_refs: + sacrelogger.error(f'FATAL: line {lineno}: expected {args.num_refs} fields, but found {len(refs)}.') + sys.exit(17) + for refno, ref in enumerate(refs): + full_refs[refno].append(ref) + + # Decide on the number of final references, override the argument + args.num_refs = len(full_refs) + + # Read hypotheses + # Can't tokenize yet as each metric has its own way of tokenizing things + full_systems, sys_names = [], [] + + if args.input is None: + # Read from STDIN + inputfh = io.TextIOWrapper(sys.stdin.buffer, encoding=args.encoding) + + # guess the number of systems by looking at the first line + fields = inputfh.readline().rstrip().split('\t') + + # Set number of systems + num_sys = len(fields) + + # place the first lines already + full_systems = [[s] for s in fields] + + # Enumerate the systems + sys_names = [f'System {i + 1}' for i in range(num_sys)] + + # Read the rest + for line in inputfh: + fields = line.rstrip().split('\t') + if len(fields) != num_sys: + sacrelogger.error('FATAL: the number of tab-delimited fields in the input stream differ across lines.') + sys.exit(17) + # Place systems into the list + for sys_idx, sent in enumerate(fields): + full_systems[sys_idx].append(sent.rstrip()) + else: + # Separate files are given for each system output + # Ex: --input smt.txt nmt.txt + for fname in args.input: + sys_name = fname + + if sys_name in sys_names: + if paired_test_mode and sys_name == sys_names[0]: + # We skip loading a system, if it was already the baseline + sacrelogger.info(f'Ignoring {sys_name!r} as it was also given as the baseline.') + continue + else: + # To avoid ambiguities, we fail if two systems have same names + sacrelogger.error(f"{sys_name!r} already used to name a system.") + sacrelogger.error("Make sure to have a different basename for each system.") + sys.exit(1) + + # Read the system + lines = [] + for line in smart_open(fname, encoding=args.encoding): + lines.append(line.rstrip()) + full_systems.append(lines) + sys_names.append(sys_name) + + # Set final number of systems + num_sys = len(sys_names) + + # Add baseline prefix to the first system for clarity + if paired_test_mode: + if args.input is None: + # STDIN mode, no explicit system names + sys_names = ['Baseline'] + [f'System {i + 1}' for i in range(num_sys - 1)] + else: + # --input mode, we have names for the systems, just change the 1st one + sys_names[0] = f'Baseline: {sys_names[0]}' + + if args.sentence_level: + if num_sys > 1: + sacrelogger.error('Only one system can be evaluated in sentence-level mode.') + sys.exit(1) + if args.confidence or paired_test_mode: + sacrelogger.error('Statistical tests are unavailable in sentence-level mode.') + sys.exit(1) + + # >=2.0.0: effective_order is now part of BLEU class. For sentence-BLEU + # we now need to explicitly enable it without user's intervention + # for backward compatibility. + args.bleu_effective_order = True + + if paired_test_mode and num_sys == 1: + sacrelogger.error('Paired tests require multiple input systems given to --input (-i).') + sys.exit(1) + + if num_sys > 1 and args.confidence: + sacrelogger.error('Use paired tests (--paired) for multiple systems.') + sys.exit(1) + + # Filter subsets if requested + outputs = filter_subset( + [*full_systems, *full_refs], args.test_set, args.langpair, + args.origlang, args.subset) + + # Unpack systems & references back + systems, refs = outputs[:num_sys], outputs[num_sys:] + + # Perform some sanity checks + for system in systems: + if len(system) == 0: + message = f'Test set {args.test_set!r} contains no sentence' + if args.origlang is not None or args.subset is not None: + message += ' with' + if args.origlang: + message += f' origlang={args.origlang}' + if args.subset: + message += f' subset={args.subset}' + args.subset + sacrelogger.error(message) + sys.exit(1) + + # Check lengths + sanity_check_lengths(system, refs, test_set=args.test_set) + + # Create the metrics + metrics = {} + for name in args.metrics: + # Each metric's specific arguments are prefixed with `metricname_` + # for grouping. Filter accordingly and strip the prefixes prior to + # metric object construction. + metric_args = args_to_dict(args, name.lower(), strip_prefix=True) + + # This will cache reference stats for faster re-computation if required + metric_args['references'] = refs + + # Make it uppercase for the rest of the code + name = name.upper() + metrics[name] = METRICS[name](**metric_args) + + # Handle sentence level and quit + if args.sentence_level: + # one metric and one system in use for sentence-level + metric, system = list(metrics.values())[0], systems[0] + + for hypothesis, *references in zip(system, *refs): + score = metric.sentence_score(hypothesis, references) + sig = metric.get_signature().format(args.short) + print(score.format(args.width, args.score_only, sig)) + + sys.exit(0) + + if args.detail and args.format == 'json': + # The translationese info will interfere with JSON output, disable + args.format = 'text' + + ############################## + # Corpus level evaluation mode + ############################## + if num_sys == 1: + # Single system evaluation mode + results = [] + for name in sorted(metrics): + # compute the score + score = metrics[name].corpus_score( + system, references=None, + n_bootstrap=args.confidence_n if args.confidence else 1) + # get the signature + sig = metrics[name].get_signature().format( + args.short if args.format != 'json' else False) + results.append( + score.format(args.width, args.score_only, sig, args.format == 'json')) + + print_single_results(results, args) + + # Prints detailed information for translationese effect experiments + if args.detail: + print_subset_results(metrics, full_systems[0], full_refs, args) + else: + # Multi-system evaluation mode + named_systems = [(sys_names[i], systems[i]) for i in range(num_sys)] + sacrelogger.info(f'Found {num_sys} systems.') + + if not paired_test_mode: + # Bootstrap resampling or the usual single score computation mode + sigs = {} + scores = defaultdict(list) + scores['System'] = sys_names + + for sys_name, system in named_systems: + for name in sorted(metrics): + score = metrics[name].corpus_score(system, references=None) + sigs[score.name] = metrics[name].get_signature().format(args.short) + scores[score.name].append(score.format(args.width, True)) + + else: + # Paired significance testing mode + from .significance import PairedTest + + # Set params + test_type = 'bs' if args.paired_bs else 'ar' + n_samples = args.paired_bs_n if args.paired_bs else args.paired_ar_n + + ps = PairedTest(named_systems, metrics, references=None, + test_type=test_type, n_samples=n_samples, + n_jobs=args.paired_jobs) + + # Set back the number of trials + args.paired_n = ps.n_samples + + # Run the test + sigs, scores = ps() + + # Get signature strings + sigs = {k: v.format(args.short) for k, v in sigs.items()} + + # Dump the results + print_results_table(scores, sigs, args) + + +if __name__ == '__main__': + main() diff --git a/venv/lib/python3.10/site-packages/sacrebleu/significance.py b/venv/lib/python3.10/site-packages/sacrebleu/significance.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c71d0ab935d0eb195b68126bcad4bdf0facd6e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/significance.py @@ -0,0 +1,435 @@ +import os +import logging +import multiprocessing as mp +from typing import Sequence, Dict, Optional, Tuple, List, Union, Any, Mapping + +import numpy as np + +from .metrics.base import Metric, Score, Signature + +IS_WINDOWS = os.name == 'nt' + + +sacrelogger = logging.getLogger('sacrebleu') + + +class Result: + """A container to represent results from a particular statistical + significance test. + :param score: The floating point score for the system at hand. + :param p_value: If exists, represents the p-value when the system at + hand is compared to a baseline using a paired test. + :param mean: When paired bootstrap test is applied, this represents + the true mean score estimated from bootstrap resamples of the system. + :param ci: When paired bootstrap test is applied, this represents + the 95% confidence interval around the true mean score `sys_mean`. + """ + def __init__(self, score: float, p_value: Optional[float] = None, + mean: Optional[float] = None, ci: Optional[float] = None): + self.score = score + self.p_value = p_value + self.mean = mean + self.ci = ci + + def __repr__(self): + return ','.join([f'{k}={str(v)}' for k, v in self.__dict__.items()]) + + +def estimate_ci(scores: np.ndarray) -> Tuple[float, float]: + """Takes a list of scores and returns mean and 95% confidence + interval around the mean. + + :param scores: A list of floating point scores. + :return: A tuple of mean and the 95% CI. + """ + # Sort the scores + scores = np.sort(scores) + n = len(scores) + + # Get CI bounds (95%, i.e. 1/40 from left) + lower_idx = n // 40 + upper_idx = n - lower_idx - 1 + lower, upper = scores[lower_idx], scores[upper_idx] + ci = 0.5 * (upper - lower) + return (scores.mean(), ci) + + +def _bootstrap_resample(stats: List[List[Union[int, float]]], + metric: Metric, n_samples: int = 1000) -> Tuple[str, List[Score]]: + """Performs bootstrap resampling for a single system to estimate + a confidence interval around the true mean. + :param stats: A list of statistics extracted from the system's hypotheses. + :param metric: The `Metric` instance to be used for score computation. + :n_samples: Number of bootstrap resamples to use. + + :return: A tuple of the seed choice as string and the list of `Score` + instances for all bootstrap resamples. + """ + + # Set numpy RNG's seed + # If given -> Fix to the given value + # If given but =='[Nn]one', don't fix the seed i.e. pull entropy from OS + seed = os.environ.get('SACREBLEU_SEED', '12345') + _seed = None if seed.lower() == 'none' else int(seed) + rng = np.random.default_rng(_seed) + + # The indices that'll produce all bootstrap resamples at once + idxs = rng.choice(len(stats), size=(n_samples, len(stats)), replace=True) + + # convert to numpy array. float32 is more efficient + stats_np = np.array(stats, dtype='float32') + + # recompute scores for all resamples + scores = [ + metric._compute_score_from_stats(_s.sum(0)) for _s in stats_np[idxs]] + + return str(seed).lower(), scores + + +def _compute_p_value(stats: np.ndarray, real_difference: float) -> float: + """Computes the p-value given the sample statistics and the real statistic. + :param stats: A numpy array with the sample statistics. + :real_difference: The real statistic. + :return: The p-value. + """ + # Taken from: significance/StratifiedApproximateRandomizationTest.java + # https://github.com/jhclark/multeval.git + + # "the != is important. if we want to score the same system against itself + # having a zero difference should not be attributed to chance." + + c = np.sum(stats > real_difference).item() + + # "+1 applies here, though it only matters for small numbers of shufflings, + # which we typically never do. it's necessary to ensure the probability of + # falsely rejecting the null hypothesis is no greater than the rejection + # level of the test (see william and morgan on significance tests) + p = (c + 1) / (len(stats) + 1) + + return p + + +def _paired_ar_test(baseline_info: Dict[str, Tuple[np.ndarray, Result]], + sys_name: str, + hypotheses: Sequence[str], + references: Optional[Sequence[Sequence[str]]], + metrics: Dict[str, Metric], + n_samples: int = 10000, + n_ar_confidence: int = -1, + seed: Optional[int] = None) -> Tuple[str, Dict[str, Result]]: + """Paired two-sided approximate randomization (AR) test for MT evaluation. + + :param baseline_info: A dictionary with `Metric` instances as the keys, + that contains sufficient statistics and a `Result` instance for the baseline system. + :param sys_name: The name of the system to be evaluated. + :param hypotheses: A sequence of string hypotheses for the system. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. If `None`, references + will be used through each metric's internal cache. + :param metrics: A dictionary of `Metric` instances that will be computed + for each system. + :param n_samples: The number of AR trials. + :param n_ar_confidence: The number of bootstrap resamples to use for + confidence estimation. A value of -1 disables confidence estimation. + :param seed: The seed value for the RNG. If `None`, the RNG will not be + fixed to a particular seed. + + :return: A tuple with first element being the system name and the second + being a `Result` namedtuple. + """ + # Seed the RNG + rng = np.random.default_rng(seed) + + # Generate indices that'll select stats + pos_sel = rng.integers(2, size=(n_samples, len(hypotheses)), dtype=bool) + + # Flip mask to obtain selectors for system hypotheses + neg_sel = ~pos_sel + + if n_ar_confidence > 0: + # Perform confidence estimation as well + bs_idxs = rng.choice( + len(hypotheses), size=(n_ar_confidence, len(hypotheses)), replace=True) + + results = {} + + for name, metric in metrics.items(): + # Use pre-computed match stats for the baseline + bl_stats, bl_result = baseline_info[name] + + # Compute system's stats and score + sacrelogger.info(f'Computing {name} for {sys_name!r} and extracting sufficient statistics') + sys_stats = metric._extract_corpus_statistics(hypotheses, references) + sys_score = metric._aggregate_and_compute(sys_stats) + + # original test statistic: absolute difference between baseline and the system + diff = abs(bl_result.score - sys_score.score) + + sacrelogger.info(f' > Performing approximate randomization test (# trials: {n_samples})') + # get shuffled pseudo systems + shuf_a = pos_sel @ bl_stats + neg_sel @ sys_stats + shuf_b = neg_sel @ bl_stats + pos_sel @ sys_stats + + # Aggregate trial stats and compute scores for each + scores_a = np.array( + [metric._aggregate_and_compute(x).score for x in shuf_a[:, None]]) + scores_b = np.array( + [metric._aggregate_and_compute(x).score for x in shuf_b[:, None]]) + + # Count the statistical difference and compute the p-value + p = _compute_p_value( + np.abs(np.array(scores_a) - np.array(scores_b)), diff) + + res = Result(sys_score.score, p) + + if n_ar_confidence > 0: + sacrelogger.info(f' > Performing bootstrap resampling for confidence interval (# resamples: {n_ar_confidence})') + sys_stats = np.array(sys_stats, dtype='float32') + # recompute scores for all resamples + sys_scores = np.array([ + metric._compute_score_from_stats(_s.sum(0)).score for _s in sys_stats[bs_idxs] + ]) + res.mean, res.ci = estimate_ci(sys_scores) + + # Store the result + results[name] = res + + return sys_name, results + + +def _paired_bs_test(baseline_info: Dict[str, Tuple[np.ndarray, Result]], + sys_name: str, + hypotheses: Sequence[str], + references: Optional[Sequence[Sequence[str]]], + metrics: Dict[str, Metric], + n_samples: int = 1000, + n_ar_confidence: int = -1, + seed: Optional[int] = None) -> Tuple[str, Dict[str, Result]]: + """Paired bootstrap resampling test for MT evaluation. This function + replicates the behavior of the Moses script called + `bootstrap-hypothesis-difference-significance.pl`. + + :param baseline_info: A dictionary with `Metric` instances as the keys, + that contains sufficient statistics and a `Result` instance for the baseline system. + :param sys_name: The name of the system to be evaluated. + :param hypotheses: A sequence of string hypotheses for the system. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. If `None`, references + will be used through each metric's internal cache. + :param metrics: A dictionary of `Metric` instances that will be computed + for each system. + :param n_samples: The number of bootstrap resamples. + :param n_ar_confidence: This parameter is not used for this function but + is there for signature compatibility in the API. + :param seed: The seed value for the RNG. If `None`, the RNG will not be + fixed to a particular seed. + + :return: A tuple with first element being the system name and the second + being a `Result` namedtuple. + """ + # Seed the RNG + rng = np.random.default_rng(seed) + + results = {} + + # It takes ~10ms to generated the indices + idxs = rng.choice( + len(hypotheses), size=(n_samples, len(hypotheses)), replace=True) + + for name, metric in metrics.items(): + # Use pre-computed match stats for the baseline + bl_stats, bl_result = baseline_info[name] + + # Compute system's stats and score + sacrelogger.info(f'Computing {name} for {sys_name!r} and extracting sufficient statistics') + sys_stats = metric._extract_corpus_statistics(hypotheses, references) + sys_score = metric._aggregate_and_compute(sys_stats) + + # Convert to numpy arrays for efficient indexing + sys_stats = np.array(sys_stats, dtype='float32') + bl_stats = np.array(bl_stats, dtype='float32') + + # original test statistic: absolute difference between baseline and the system + diff = abs(bl_result.score - sys_score.score) + + sacrelogger.info(f' > Performing paired bootstrap resampling test (# resamples: {n_samples})') + scores_bl = np.array( + [metric._compute_score_from_stats(_s.sum(0)).score for _s in bl_stats[idxs]]) + scores_sys = np.array( + [metric._compute_score_from_stats(_s.sum(0)).score for _s in sys_stats[idxs]]) + + # Compute CI as well + sys_mean, sys_ci = estimate_ci(scores_sys) + + # Compute the statistics + sample_diffs = np.abs(scores_sys - scores_bl) + stats = sample_diffs - sample_diffs.mean() + + # Count the statistical difference and compute the p-value + p = _compute_p_value(stats, diff) + + results[name] = Result(sys_score.score, p, sys_mean, sys_ci) + + return sys_name, results + + +class PairedTest: + """This is the manager class that will call the actual standalone implementation + for approximate randomization or paired bootstrap resampling, based on the + `test_type` argument. + + :param named_systems: A lisf of (system_name, system_hypotheses) tuples on + which the test will be applied. + :param metrics: A dictionary of `Metric` instances that will be computed + for each system. + :param references: A sequence of reference documents with document being + defined as a sequence of reference strings. If `None`, already cached references + will be used through each metric's internal cache. + :param test_type: `ar` for approximate randomization, `bs` for paired bootstrap. + :param n_samples: The number of AR trials (for `ar`) or bootstrap resamples (for `bs`). + The defaults (10000 or 1000 respectively) will be used if 0 is passed. + :param n_ar_confidence: If `approximate randomization` is selected, the number + of bootstrap resamples to use for confidence estimation. A value of -1 disables + confidence estimation. 0 will use the default of 1000. + :param n_jobs: If 0, a worker process will be spawned for each system variant. + If > 0, the number of workers will be set accordingly. The default of 1 + does not use multi-processing. + """ + _DEFAULT_SAMPLES = { + 'ar': 10000, + 'bs': 1000, + } + + def __init__(self, named_systems: List[Tuple[str, Sequence[str]]], + metrics: Mapping[str, Metric], + references: Optional[Sequence[Sequence[str]]], + test_type: str = 'ar', + n_samples: int = 0, + n_ar_confidence: int = -1, + n_jobs: int = 1): + assert test_type in ('ar', 'bs'), f"Unknown test type {test_type!r}" + self.test_type = test_type + + # Set method + if self.test_type == 'ar': + self._fn = _paired_ar_test + elif self.test_type == 'bs': + self._fn = _paired_bs_test + + # Set numpy RNG's seed + # If given -> Fix to the given value + # If given but =='[Nn]one', don't fix the seed i.e. pull entropy from OS + seed = os.environ.get('SACREBLEU_SEED', '12345') + self._seed = None if seed.lower() == 'none' else int(seed) + self.n_jobs = n_jobs + self.references = references + self.named_systems = named_systems + + # Set the defaults if requested + self.n_ar_confidence = n_ar_confidence if n_ar_confidence != 0 else \ + self._DEFAULT_SAMPLES['bs'] + + self.n_samples = n_samples if n_samples > 0 else \ + self._DEFAULT_SAMPLES[self.test_type] + + # Number of systems (excluding the baseline) + self.n_systems = len(named_systems) - 1 + + # Decide on number of workers + if IS_WINDOWS: + sacrelogger.warning('Parallel tests are not supported on Windows.') + self.n_jobs = 1 + elif self.n_jobs == 0: + # Decide automatically + # Divide by two to ignore hyper-threading + n_max_jobs = mp.cpu_count() // 2 + if n_max_jobs == 0: + self.n_jobs = 1 + else: + # Don't use more workers than the number of CPUs + self.n_jobs = min(n_max_jobs, self.n_systems) + + self._signatures: Dict[str, Signature] = {} + self._baseline_info: Dict[str, Tuple[Any, Result]] = {} + + ################################################## + # Pre-compute and cache baseline system statistics + ################################################## + self.metrics = {} + + bl_name, bl_hyps = self.named_systems[0] + + for name, metric in metrics.items(): + sacrelogger.info(f'Pre-computing {name} statistics for {bl_name!r}') + bl_stats = metric._extract_corpus_statistics(bl_hyps, self.references) + bl_score = metric._aggregate_and_compute(bl_stats) + + # Compute CI for the baseline here once + confidence_n = self.n_samples if self.test_type == 'bs' \ + else self.n_ar_confidence + + bl_mean, bl_ci = None, None + if confidence_n > 0: + _, bl_scores = _bootstrap_resample(bl_stats, metric, confidence_n) + bl_mean, bl_ci = estimate_ci(np.array([x.score for x in bl_scores])) + + result = Result(bl_score.score, mean=bl_mean, ci=bl_ci) + # Use updated name for the metric + self._baseline_info[bl_score.name] = (bl_stats, result) + self.metrics[bl_score.name] = metric + + # Update metric signature as well + sig = metric.get_signature() + sig.update('seed', str(self._seed).lower()) + + # Num samples for bs, num trials for AR + sig.update(self.test_type, self.n_samples) + if self.n_ar_confidence > 0: + # Bootstrap is used for AR CI as well + sig.update('bs', self.n_ar_confidence) + self._signatures[bl_score.name] = sig + + def __call__(self) -> Tuple[Dict[str, Signature], Dict[str, List[Union[str, Result]]]]: + """Runs the paired test either on single or multiple worker processes.""" + tasks = [] + scores: Dict[str, List[Union[str, Result]]] = {} + + # Add the name column + scores['System'] = [ns[0] for ns in self.named_systems] + + # Store baseline results as the first position + for metric, (_, result) in self._baseline_info.items(): + scores[metric] = [result] + + # Prepare list of arguments for each comparison + # Skip the baseline (pos: 0) + for idx, (name, hyps) in enumerate(self.named_systems[1:]): + seed = self._seed if self._seed else None + + tasks.append( + (self._baseline_info, name, hyps, self.references, + self.metrics, self.n_samples, self.n_ar_confidence, seed)) + + # Run the test(s) + if self.n_jobs == 1: + results = [self._fn(*args) for args in tasks] + else: + # NOTE: The overhead of worker creation is not negligible + # but if you have many systems and TER enabled, this significantly + # speeds up the test. + # NOTE: This only works on Linux/Mac OS X but not Windows. Windows only + # supports `spawn` backend which requires things to be called + # from within __main__. + sacrelogger.info(f'Launching {self.n_jobs} parallel workers.') + with mp.get_context('fork').Pool(self.n_jobs) as pool: + jobs = [pool.apply_async(self._fn, args) for args in tasks] + + # wait for completion + results = [j.get() for j in jobs] + + # Keep the order deterministic + for sys_name, sys_results in results: + for metric, _result in sys_results.items(): + scores[metric].append(_result) + + return self._signatures, scores diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__init__.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d658a1ba847f7663a502f559fd5ed8ef1be4a013 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__init__.py @@ -0,0 +1,2 @@ +# Base tokenizer to derive from +from .tokenizer_base import BaseTokenizer # noqa: F401 diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5697da9147019683d94dee2d0e811b2d890e41e3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_13a.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_13a.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd91a303631574a583921b9f3bc47e7bc2ca4c9c Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_13a.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_base.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc4ed67946496450ece22e4fcb3e13df038d36b7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_char.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_char.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f60f987569c43e362d06ad89574df1bad4f7f537 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_char.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_intl.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_intl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7094cb474343f84d912d1a8e3cd8729cceff4da4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_intl.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_ja_mecab.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_ja_mecab.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..286cec517a5eee149309d70845a44c14e16d00df Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_ja_mecab.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_ko_mecab.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_ko_mecab.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c397b1321299cfd213a5dfde9db46316012fefb8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_ko_mecab.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_none.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_none.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04c85713062a26d5f09abe0ca3c39a0cfeeb5b07 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_none.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_re.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_re.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3984f963ed71a9ae48ac2a1c05d7716f5f9b9389 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_re.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_spm.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_spm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..804d71bf3588d21f35376dddfff7e7d58f88d158 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_spm.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_ter.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_ter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..716ac5ad36b0225d7dcede3fb535ed72760851d0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_ter.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_zh.cpython-310.pyc b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_zh.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d89e86c66102e1c35851bc6ff6daec038c26edd Binary files /dev/null and b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/__pycache__/tokenizer_zh.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_13a.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_13a.py new file mode 100644 index 0000000000000000000000000000000000000000..6441a7621882007faf99d261f7506550ee8164bd --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_13a.py @@ -0,0 +1,34 @@ +from functools import lru_cache +from .tokenizer_base import BaseTokenizer +from .tokenizer_re import TokenizerRegexp + + +class Tokenizer13a(BaseTokenizer): + + def signature(self): + return '13a' + + def __init__(self): + self._post_tokenizer = TokenizerRegexp() + + @lru_cache(maxsize=2**16) + def __call__(self, line): + """Tokenizes an input line using a relatively minimal tokenization + that is however equivalent to mteval-v13a, used by WMT. + + :param line: a segment to tokenize + :return: the tokenized line + """ + + # language-independent part: + line = line.replace('', '') + line = line.replace('-\n', '') + line = line.replace('\n', ' ') + + if '&' in line: + line = line.replace('"', '"') + line = line.replace('&', '&') + line = line.replace('<', '<') + line = line.replace('>', '>') + + return self._post_tokenizer(f' {line} ') diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_base.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_base.py new file mode 100644 index 0000000000000000000000000000000000000000..faf3de4ca6310bd879f1aa2e4c35df59210e280d --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_base.py @@ -0,0 +1,19 @@ +class BaseTokenizer: + """A base dummy tokenizer to derive from.""" + + def signature(self): + """ + Returns a signature for the tokenizer. + + :return: signature string + """ + raise NotImplementedError() + + def __call__(self, line): + """ + Tokenizes an input line with the tokenizer. + + :param line: a segment to tokenize + :return: the tokenized line + """ + raise NotImplementedError() diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_char.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_char.py new file mode 100644 index 0000000000000000000000000000000000000000..8b8f8c5d73d1dd6e27185c6cef88615bec919564 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_char.py @@ -0,0 +1,19 @@ +from functools import lru_cache +from .tokenizer_base import BaseTokenizer + + +class TokenizerChar(BaseTokenizer): + def signature(self): + return 'char' + + def __init__(self): + pass + + @lru_cache(maxsize=2**16) + def __call__(self, line): + """Tokenizes all the characters in the input line. + + :param line: a segment to tokenize + :return: the tokenized line + """ + return " ".join((char for char in line)) diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_intl.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_intl.py new file mode 100644 index 0000000000000000000000000000000000000000..bd980c6f3b47a80c2e5fbf92db45085cf7ed24ff --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_intl.py @@ -0,0 +1,50 @@ +from functools import lru_cache + +import regex + +from .tokenizer_base import BaseTokenizer + + +class TokenizerV14International(BaseTokenizer): + """Tokenizes a string following the official BLEU implementation. + + See github.com/moses-smt/mosesdecoder/blob/master/scripts/generic/mteval-v14.pl#L954-L983 + + In our case, the input string is expected to be just one line. + We just tokenize on punctuation and symbols, + except when a punctuation is preceded and followed by a digit + (e.g. a comma/dot as a thousand/decimal separator). + We do not recover escaped forms of punctuations such as ' or > + as these should never appear in MT system outputs (see issue #138) + + Note that a number (e.g., a year) followed by a dot at the end of + sentence is NOT tokenized, i.e. the dot stays with the number because + `s/(\\p{P})(\\P{N})/ $1 $2/g` does not match this case (unless we add a + space after each sentence). However, this error is already in the + original mteval-v14.pl and we want to be consistent with it. + The error is not present in the non-international version, + which uses `$norm_text = " $norm_text "`. + + :param line: the input string to tokenize. + :return: The tokenized string. + """ + + def signature(self): + return 'intl' + + def __init__(self): + self._re = [ + # Separate out punctuations preceeded by a non-digit + (regex.compile(r'(\P{N})(\p{P})'), r'\1 \2 '), + # Separate out punctuations followed by a non-digit + (regex.compile(r'(\p{P})(\P{N})'), r' \1 \2'), + # Separate out symbols + (regex.compile(r'(\p{S})'), r' \1 '), + ] + + @lru_cache(maxsize=2**16) + def __call__(self, line: str) -> str: + for (_re, repl) in self._re: + line = _re.sub(repl, line) + + return ' '.join(line.split()) diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_ja_mecab.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_ja_mecab.py new file mode 100644 index 0000000000000000000000000000000000000000..2844c5fca61804a3749d70870a142d5cb497740a --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_ja_mecab.py @@ -0,0 +1,52 @@ +from functools import lru_cache + +try: + import MeCab + import ipadic +except ImportError: + # Don't fail until the tokenizer is actually used + MeCab = None + +from .tokenizer_base import BaseTokenizer + +FAIL_MESSAGE = """ +Japanese tokenization requires extra dependencies, but you do not have them installed. +Please install them like so. + + pip install sacrebleu[ja] +""" + + +class TokenizerJaMecab(BaseTokenizer): + def __init__(self): + if MeCab is None: + raise RuntimeError(FAIL_MESSAGE) + self.tagger = MeCab.Tagger(ipadic.MECAB_ARGS + " -Owakati") + + # make sure the dictionary is IPA + d = self.tagger.dictionary_info() + assert d.size == 392126, \ + "Please make sure to use the IPA dictionary for MeCab" + # This asserts that no user dictionary has been loaded + assert d.next is None + + @lru_cache(maxsize=2**16) + def __call__(self, line): + """ + Tokenizes an Japanese input line using MeCab morphological analyzer. + + :param line: a segment to tokenize + :return: the tokenized line + """ + line = line.strip() + sentence = self.tagger.parse(line).strip() + return sentence + + def signature(self): + """ + Returns the MeCab parameters. + + :return: signature string + """ + signature = self.tagger.version() + "-IPA" + return 'ja-mecab-' + signature diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_ko_mecab.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_ko_mecab.py new file mode 100644 index 0000000000000000000000000000000000000000..7d880428376d4b4733a55e16714c9b75e1d8c81a --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_ko_mecab.py @@ -0,0 +1,52 @@ +from functools import lru_cache + +try: + import mecab_ko as MeCab + import mecab_ko_dic +except ImportError: + # Don't fail until the tokenizer is actually used + MeCab = None + +from .tokenizer_base import BaseTokenizer + +FAIL_MESSAGE = """ +Korean tokenization requires extra dependencies, but you do not have them installed. +Please install them like so. + + pip install sacrebleu[ko] +""" + + +class TokenizerKoMecab(BaseTokenizer): + def __init__(self): + if MeCab is None: + raise RuntimeError(FAIL_MESSAGE) + self.tagger = MeCab.Tagger(mecab_ko_dic.MECAB_ARGS + " -Owakati") + + # make sure the dictionary is mecab-ko-dic + d = self.tagger.dictionary_info() + assert d.size == 811795, \ + "Please make sure to use the mecab-ko-dic for MeCab-ko" + # This asserts that no user dictionary has been loaded + assert d.next is None + + @lru_cache(maxsize=2**16) + def __call__(self, line): + """ + Tokenizes an Korean input line using MeCab-ko morphological analyzer. + + :param line: a segment to tokenize + :return: the tokenized line + """ + line = line.strip() + sentence = self.tagger.parse(line).strip() + return sentence + + def signature(self): + """ + Returns the MeCab-ko parameters. + + :return: signature string + """ + signature = self.tagger.version() + "-KO" + return 'ko-mecab-' + signature diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_none.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_none.py new file mode 100644 index 0000000000000000000000000000000000000000..a204c0009f6920a587fbbf87ad611d546fbcffcd --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_none.py @@ -0,0 +1,10 @@ +from .tokenizer_base import BaseTokenizer + +class NoneTokenizer(BaseTokenizer): + """Don't apply any tokenization. Not recommended!.""" + + def signature(self): + return 'none' + + def __call__(self, line): + return line diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_re.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_re.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb67eb5126c4882d330387f662c0c865ce56f0c --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_re.py @@ -0,0 +1,38 @@ +from functools import lru_cache +import re + +from .tokenizer_base import BaseTokenizer + + +class TokenizerRegexp(BaseTokenizer): + + def signature(self): + return 're' + + def __init__(self): + self._re = [ + # language-dependent part (assuming Western languages) + (re.compile(r'([\{-\~\[-\` -\&\(-\+\:-\@\/])'), r' \1 '), + # tokenize period and comma unless preceded by a digit + (re.compile(r'([^0-9])([\.,])'), r'\1 \2 '), + # tokenize period and comma unless followed by a digit + (re.compile(r'([\.,])([^0-9])'), r' \1 \2'), + # tokenize dash when preceded by a digit + (re.compile(r'([0-9])(-)'), r'\1 \2 '), + # one space only between words + # NOTE: Doing this in Python (below) is faster + # (re.compile(r'\s+'), r' '), + ] + + @lru_cache(maxsize=2**16) + def __call__(self, line): + """Common post-processing tokenizer for `13a` and `zh` tokenizers. + + :param line: a segment to tokenize + :return: the tokenized line + """ + for (_re, repl) in self._re: + line = _re.sub(repl, line) + + # no leading or trailing spaces, single space within words + return ' '.join(line.split()) diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_spm.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_spm.py new file mode 100644 index 0000000000000000000000000000000000000000..92729b5be351622ccfc23d25b7f85e6221b56dd3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_spm.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- + +import os +import logging + +from functools import lru_cache +from ..utils import SACREBLEU_DIR, download_file +from .tokenizer_base import BaseTokenizer + +sacrelogger = logging.getLogger('sacrebleu') + + +SPM_MODELS = { + "spm": { + "url": "https://dl.fbaipublicfiles.com/fairseq/models/flores/sacrebleu_tokenizer_spm.model", + "signature": "flores101", + }, + # same as the default of "spm" + "flores101": { + "url": "https://dl.fbaipublicfiles.com/fairseq/models/flores/sacrebleu_tokenizer_spm.model", + "signature": "flores101", + }, + "flores200": { + "url": "https://tinyurl.com/flores200sacrebleuspm", + "signature": "flores200", + }, +} + +class TokenizerSPM(BaseTokenizer): + def signature(self): + return self.name + + def __init__(self, key="spm"): + self.name = SPM_MODELS[key]["signature"] + + if key == "spm": + sacrelogger.warn("Tokenizer 'spm' has been changed to 'flores101', and may be removed in the future.") + + try: + import sentencepiece as spm + except (ImportError, ModuleNotFoundError): + raise ImportError( + '\n\nPlease install the sentencepiece library for SPM tokenization:' + '\n\n pip install sentencepiece ' + ) + self.sp = spm.SentencePieceProcessor() + + model_path = os.path.join(SACREBLEU_DIR, "models", os.path.basename(SPM_MODELS[key]["url"])) + if not os.path.exists(model_path): + url = SPM_MODELS[self.name]["url"] + download_file(url, model_path) + self.sp.Load(model_path) + + @lru_cache(maxsize=2**16) + def __call__(self, line): + """Tokenizes all the characters in the input line. + + :param line: a segment to tokenize + :return: the tokenized line + """ + return " ".join(self.sp.EncodeAsPieces(line)) + + +class Flores200Tokenizer(TokenizerSPM): + def __init__(self): + super().__init__("flores200") + +class Flores101Tokenizer(TokenizerSPM): + def __init__(self): + super().__init__("flores101") diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_ter.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_ter.py new file mode 100644 index 0000000000000000000000000000000000000000..66c7cf238588bc9e3d0cc076ee3d4aa5566f1a96 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_ter.py @@ -0,0 +1,171 @@ +# Copyright 2020 Memsource +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import re +from functools import lru_cache + +from .tokenizer_base import BaseTokenizer + + +def _normalize_general_and_western(sent: str) -> str: + # language-independent (general) part + + # strip end-of-line hyphenation and join lines + sent = re.sub(r"\n-", "", sent) + + # join lines + sent = re.sub(r"\n", " ", sent) + + # handle XML escaped symbols + sent = re.sub(r""", "\"", sent) + sent = re.sub(r"&", "&", sent) + sent = re.sub(r"<", "<", sent) + sent = re.sub(r">", ">", sent) + + # language-dependent (Western) part + sent = f" {sent} " + + # tokenize punctuation + sent = re.sub(r"([{-~[-` -&(-+:-@/])", r" \1 ", sent) + + # handle possesives + sent = re.sub(r"'s ", r" 's ", sent) + sent = re.sub(r"'s$", r" 's", sent) + + # tokenize period and comma unless preceded by a digit + sent = re.sub(r"([^0-9])([\.,])", r"\1 \2 ", sent) + + # tokenize period and comma unless followed by a digit + sent = re.sub(r"([\.,])([^0-9])", r" \1 \2", sent) + + # tokenize dash when preceded by a digit + sent = re.sub(r"([0-9])(-)", r"\1 \2 ", sent) + + return sent + + +def _normalize_asian(sent: str) -> str: + # Split Chinese chars and Japanese kanji down to character level + + # 4E00—9FFF CJK Unified Ideographs + # 3400—4DBF CJK Unified Ideographs Extension A + sent = re.sub(r"([\u4e00-\u9fff\u3400-\u4dbf])", r" \1 ", sent) + + # 31C0—31EF CJK Strokes + # 2E80—2EFF CJK Radicals Supplement + sent = re.sub(r"([\u31c0-\u31ef\u2e80-\u2eff])", r" \1 ", sent) + + # 3300—33FF CJK Compatibility + # F900—FAFF CJK Compatibility Ideographs + # FE30—FE4F CJK Compatibility Forms + sent = re.sub( + r"([\u3300-\u33ff\uf900-\ufaff\ufe30-\ufe4f])", r" \1 ", sent) + + # 3200—32FF Enclosed CJK Letters and Months + sent = re.sub(r"([\u3200-\u3f22])", r" \1 ", sent) + + # Split Hiragana, Katakana, and KatakanaPhoneticExtensions + # only when adjacent to something else + # 3040—309F Hiragana + # 30A0—30FF Katakana + # 31F0—31FF Katakana Phonetic Extensions + sent = re.sub( + r"(^|^[\u3040-\u309f])([\u3040-\u309f]+)(?=$|^[\u3040-\u309f])", + r"\1 \2 ", sent) + sent = re.sub( + r"(^|^[\u30a0-\u30ff])([\u30a0-\u30ff]+)(?=$|^[\u30a0-\u30ff])", + r"\1 \2 ", sent) + sent = re.sub( + r"(^|^[\u31f0-\u31ff])([\u31f0-\u31ff]+)(?=$|^[\u31f0-\u31ff])", + r"\1 \2 ", sent) + + sent = re.sub(TercomTokenizer.ASIAN_PUNCT, r" \1 ", sent) + sent = re.sub(TercomTokenizer.FULL_WIDTH_PUNCT, r" \1 ", sent) + return sent + + +def _remove_punct(sent: str) -> str: + return re.sub(r"[\.,\?:;!\"\(\)]", "", sent) + + +def _remove_asian_punct(sent: str) -> str: + sent = re.sub(TercomTokenizer.ASIAN_PUNCT, r"", sent) + sent = re.sub(TercomTokenizer.FULL_WIDTH_PUNCT, r"", sent) + return sent + + +class TercomTokenizer(BaseTokenizer): + """Re-implementation of Tercom Tokenizer in Python 3. + + See src/ter/core/Normalizer.java in https://github.com/jhclark/tercom + + Note that Python doesn't support named Unicode blocks so the mapping for + relevant blocks was taken from here: + + https://unicode-table.com/en/blocks/ + """ + ASIAN_PUNCT = r"([\u3001\u3002\u3008-\u3011\u3014-\u301f\uff61-\uff65\u30fb])" + FULL_WIDTH_PUNCT = r"([\uff0e\uff0c\uff1f\uff1a\uff1b\uff01\uff02\uff08\uff09])" + + def __init__(self, + normalized: bool = False, + no_punct: bool = False, + asian_support: bool = False, + case_sensitive: bool = False): + """Initialize the tokenizer. + + :param normalized: Enable character normalization. By default, normalizes a couple of things such as + newlines being stripped, retrieving XML encoded characters, and fixing tokenization for punctuation. When + 'asian_support' is enabled, also normalizes specific Asian (CJK) character sequences, i.e. + split them down to the character level. + :param no_punct: Remove punctuation. Can be used in conjunction with 'asian_support' to also remove typical + punctuation markers in Asian languages (CJK). + :param asian_support: Enable special treatment of Asian characters. This option only has an effect when + 'normalized' and/or 'no_punct' is enabled. If 'normalized' is also enabled, then Asian (CJK) + characters are split down to the character level. If 'no_punct' is enabled alongside 'asian_support', + specific unicode ranges for CJK and full-width punctuations are also removed. + :param case_sensitive: Enable case sensitivity, i.e., do not lower case data. + """ + self._normalized = normalized + self._no_punct = no_punct + self._asian_support = asian_support + self._case_sensitive = case_sensitive + + @lru_cache(maxsize=2**16) + # Although the cache is shared across different instances, same sentence + # queries do not return invalid returns across different instances since + # `self` becomes part of the query as well. + def __call__(self, sent: str) -> str: + if not sent: + return "" + + if not self._case_sensitive: + sent = sent.lower() + + if self._normalized: + sent = _normalize_general_and_western(sent) + if self._asian_support: + sent = _normalize_asian(sent) + + if self._no_punct: + sent = _remove_punct(sent) + if self._asian_support: + sent = _remove_asian_punct(sent) + + # Strip extra whitespaces + return ' '.join(sent.split()) + + def signature(self): + return 'tercom' diff --git a/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_zh.py b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_zh.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec831aa34648006b52609ff03f049f9bafcb666 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/tokenizers/tokenizer_zh.py @@ -0,0 +1,119 @@ +# Copyright 2017--2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You may not +# use this file except in compliance with the License. A copy of the License +# is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is distributed on +# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +# express or implied. See the License for the specific language governing +# permissions and limitations under the License. + +############## + +# MIT License +# Copyright (c) 2017 - Shujian Huang + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# Author: Shujian Huang huangsj@nju.edu.cn + + +from functools import lru_cache + +from .tokenizer_base import BaseTokenizer +from .tokenizer_re import TokenizerRegexp + +_UCODE_RANGES = [ + (u'\u3400', u'\u4db5'), # CJK Unified Ideographs Extension A, release 3.0 + (u'\u4e00', u'\u9fa5'), # CJK Unified Ideographs, release 1.1 + (u'\u9fa6', u'\u9fbb'), # CJK Unified Ideographs, release 4.1 + (u'\uf900', u'\ufa2d'), # CJK Compatibility Ideographs, release 1.1 + (u'\ufa30', u'\ufa6a'), # CJK Compatibility Ideographs, release 3.2 + (u'\ufa70', u'\ufad9'), # CJK Compatibility Ideographs, release 4.1 + (u'\u20000', u'\u2a6d6'), # (UTF16) CJK Unified Ideographs Extension B, release 3.1 + (u'\u2f800', u'\u2fa1d'), # (UTF16) CJK Compatibility Supplement, release 3.1 + (u'\uff00', u'\uffef'), # Full width ASCII, full width of English punctuation, + # half width Katakana, half wide half width kana, Korean alphabet + (u'\u2e80', u'\u2eff'), # CJK Radicals Supplement + (u'\u3000', u'\u303f'), # CJK punctuation mark + (u'\u31c0', u'\u31ef'), # CJK stroke + (u'\u2f00', u'\u2fdf'), # Kangxi Radicals + (u'\u2ff0', u'\u2fff'), # Chinese character structure + (u'\u3100', u'\u312f'), # Phonetic symbols + (u'\u31a0', u'\u31bf'), # Phonetic symbols (Taiwanese and Hakka expansion) + (u'\ufe10', u'\ufe1f'), + (u'\ufe30', u'\ufe4f'), + (u'\u2600', u'\u26ff'), + (u'\u2700', u'\u27bf'), + (u'\u3200', u'\u32ff'), + (u'\u3300', u'\u33ff'), +] + + +class TokenizerZh(BaseTokenizer): + + def signature(self): + return 'zh' + + def __init__(self): + self._post_tokenizer = TokenizerRegexp() + + @staticmethod + @lru_cache(maxsize=2**16) + def _is_chinese_char(uchar): + """ + :param uchar: input char in unicode + :return: whether the input char is a Chinese character. + """ + for start, end in _UCODE_RANGES: + if start <= uchar <= end: + return True + return False + + @lru_cache(maxsize=2**16) + def __call__(self, line): + """The tokenization of Chinese text in this script contains two + steps: separate each Chinese characters (by utf-8 encoding); tokenize + the non Chinese part (following the `13a` i.e. mteval tokenizer). + + Author: Shujian Huang huangsj@nju.edu.cn + + :param line: input sentence + :return: tokenized sentence + """ + + line = line.strip() + line_in_chars = "" + + # TODO: the below code could probably be replaced with the following: + # @ozan: Gives slightly different scores, need to investigate + # import regex + # line = regex.sub(r'(\p{Han})', r' \1 ', line) + for char in line: + if self._is_chinese_char(char): + line_in_chars += " " + line_in_chars += char + line_in_chars += " " + else: + line_in_chars += char + + return self._post_tokenizer(line_in_chars) diff --git a/venv/lib/python3.10/site-packages/sacrebleu/utils.py b/venv/lib/python3.10/site-packages/sacrebleu/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..56e6fcab4e22ed13d9e7a33ab73e74304a67ed6f --- /dev/null +++ b/venv/lib/python3.10/site-packages/sacrebleu/utils.py @@ -0,0 +1,595 @@ +import json +import os +import re +import sys +import gzip +import math +import hashlib +import logging +import portalocker +from collections import defaultdict +from typing import List, Optional, Sequence, Dict +from argparse import Namespace + +from tabulate import tabulate +import colorama + + +# Where to store downloaded test sets. +# Define the environment variable $SACREBLEU, or use the default of ~/.sacrebleu. +# +# Querying for a HOME environment variable can result in None (e.g., on Windows) +# in which case the os.path.join() throws a TypeError. Using expanduser() is +# a safe way to get the user's home folder. +USERHOME = os.path.expanduser("~") +SACREBLEU_DIR = os.environ.get('SACREBLEU', os.path.join(USERHOME, '.sacrebleu')) + +sacrelogger = logging.getLogger('sacrebleu') + + +class Color: + ENABLE_COLORS = True + + @staticmethod + def format(msg: str, color: str) -> str: + """Returns a colored version of the given message string. + + :param msg: The string to Color.format. + :param color: The color specifier i.e. 'red', 'blue', 'green', etc. + :return: A colored version of the string if the output is a terminal. + """ + if not Color.ENABLE_COLORS: + return msg + _ansi_str = getattr(colorama.Fore, color.upper(), None) + if _ansi_str: + return f'{_ansi_str}{msg}{colorama.Style.RESET_ALL}' + + return msg + + +def _format_score_lines(scores: dict, + width: int = 2, + multiline: bool = True) -> Dict[str, List[str]]: + """Formats the scores prior to tabulating them.""" + new_scores = {'System': scores.pop('System')} + p_val_break_char = '\n' if multiline else ' ' + is_bootstrap = False + + def _color_p_value(p: float): + msg = f'(p = {p:.4f})' + if p > 0.05: + return Color.format(msg, 'red') + return msg + '*' + + for metric, vals in scores.items(): + new_vals = [] + + for result in vals: + if not isinstance(result, str): + # Format result instances + _str = f'{result.score:.{width}f}' + if result.mean is not None: + is_bootstrap = True + _str += f' ({result.mean:.{width}f} ± {result.ci:.{width}f})' + if result.p_value is not None: + _str += p_val_break_char + _color_p_value(result.p_value) + else: + # Already formatted in non paired-test mode + _str = result + + new_vals.append(_str) + + if is_bootstrap: + # Change titles + metric += ' (μ ± 95% CI)' + + new_scores[metric] = new_vals + + return new_scores + + +def print_results_table(results: dict, signatures: dict, args: Namespace): + """Prints out a nicely formatted table for multi-system evaluation mode.""" + + if args.format == 'json': + proper_json = [] + dict_keys = list(results.keys()) + for i in range(len(results['System'])): + value = {} + value['system'] = results['System'][i] + # parse metrics + for j in range(1, len(dict_keys)): + if isinstance(results[dict_keys[j]][i], str): + value[dict_keys[j]] = results[dict_keys[j]][i] + else: + # Values inside object as dict + value[dict_keys[j]] = results[dict_keys[j]][i].__dict__ + proper_json.append(value) + + print(json.dumps(proper_json, indent=4)) + return + + tablefmt = args.format + if tablefmt in ('text'): + tablefmt = 'fancy_grid' + elif tablefmt == 'latex': + # Use booktabs + tablefmt = 'latex_booktabs' + + # If paired testing has been given, this'll format the score lines + results = _format_score_lines( + results, args.width, multiline=tablefmt == 'fancy_grid') + + new_dict = {} + + # Color the column names and the baseline system name and scores + has_baseline = False + baseline_name = '' + for name in results.keys(): + val = results[name] + if val[0].startswith('Baseline:') or has_baseline: + if val[0].startswith('Baseline:'): + baseline_name = val[0] + has_baseline = True + val[0] = Color.format(val[0], 'yellow') + new_dict[Color.format(name, 'cyan')] = results[name] + + # Finally tabulate + table = tabulate( + new_dict, headers='keys', tablefmt=tablefmt, + colalign=('right', ), + stralign='center', + numalign='center', + floatfmt=f'.{args.width}f') + + print(table) + print() + + is_paired = args.paired_bs or args.paired_ar + + if is_paired: + test_type = 'bootstrap resampling' if args.paired_bs else 'approximate randomization' + n_samples_or_trials = args.paired_bs_n if args.paired_bs else args.paired_ar_n + test_sample_type = 'resampling trials' if args.paired_bs else 'trials' + msg = f'Paired {test_type} test with {n_samples_or_trials} {test_sample_type}' + + bline = Color.format('baseline', 'yellow') + bline_name = Color.format(baseline_name, 'yellow') + null_hyp = Color.format('Null hypothesis', 'green') + pval_color = Color.format('highlighted in red', 'red') + + # Print fancy header + print('-' * len(msg) + '\n' + msg + '\n' + '-' * len(msg)) + print(f' - Each system is pairwise compared to {bline_name}.') + if args.paired_bs: + print(' Actual system score / bootstrap estimated true mean / 95% CI are provided for each metric.') + else: + print(' Actual system score is provided for each metric.') + print() + print(f' - {null_hyp}: the system and the {bline} translations are essentially') + print(f' generated by the same underlying process. For a given system and the {bline},') + print(' the p-value is roughly the probability of the absolute score difference (delta)') + print(f' or higher occurring due to chance, under the assumption that the {null_hyp.lower()} is correct.') + print() + print(f' - Assuming a significance threshold of 0.05, the {null_hyp.lower()} can be rejected') + print(' for p-values < 0.05 (marked with "*"). This means that the delta is unlikely to be attributed') + print(f' to chance, hence the system is significantly "different" than the {bline}.') + print(f' Otherwise, the p-values are {pval_color}.') + print() + print(f' - NOTE: Significance does not tell whether a system is "better" than the {bline} but rather') + print(' emphasizes the "difference" of the systems in terms of the replicability of the delta.') + print() + + print('-----------------') + print('Metric signatures') + print('-----------------') + for name, sig in signatures.items(): + print(f' - {name:<10} {sig}') + + +def print_single_results(results: List[str], args: Namespace): + """Re-process metric strings to align them nicely.""" + if args.format == 'json': + if len(results) > 1: + proper_json = '[\n' + ',\n'.join(results) + '\n]' + print(proper_json) + else: + print(results[0]) + return + + # Color confidence strings for emphasis + if 'μ' in results[0]: + color_re = re.compile(r'(\(μ = [0-9\.]+ ± [0-9\.]+\))') + for idx in range(len(results)): + results[idx] = color_re.sub( + lambda m: Color.format(m.group(), 'cyan'), results[idx]) + + if len(results) == 1: + # Just one system, nothing to align. + print(results[0]) + return + + # Align by '=' character + lens = [] + for line in results: + # If not score_only, split lines from '=' for re-alignment + try: + lens.append(line.index('=') - 1) + except ValueError: + print(line) + + if len(lens) > 0: + w = max(lens) + for (_len, line) in zip(lens, results): + left, right = line[:_len], line[_len:] + print(f'{left:>{w}}{right}') + + +def sanity_check_lengths(system: Sequence[str], + refs: Sequence[Sequence[str]], + test_set: Optional[str] = None): + n_hyps = len(system) + if any(len(ref_stream) != n_hyps for ref_stream in refs): + sacrelogger.error("System and reference streams have different lengths.") + if test_set: + sacrelogger.error("This could be an issue with your system output " + "or with sacreBLEU's reference database if -t is given.") + sacrelogger.error("For the latter, try cleaning out the cache by typing:\n") + sacrelogger.error(f" rm -r {SACREBLEU_DIR}/{test_set}\n") + sacrelogger.error("The test sets will be re-downloaded the next time you run sacreBLEU.") + sys.exit(1) + + +def smart_open(file, mode='rt', encoding='utf-8'): + """Convenience function for reading compressed or plain text files. + :param file: The file to read. + :param mode: The file mode (read, write). + :param encoding: The file encoding. + """ + if file.endswith('.gz'): + return gzip.open(file, mode=mode, encoding=encoding, newline="\n") + return open(file, mode=mode, encoding=encoding, newline="\n") + + +def my_log(num: float) -> float: + """ + Floors the log function + + :param num: the number + :return: log(num) floored to a very low number + """ + + if num == 0.0: + return -9999999999 + return math.log(num) + + +def sum_of_lists(lists): + """Aggregates list of numeric lists by summing.""" + if len(lists) == 1: + return lists[0] + + # Preserve datatype + size = len(lists[0]) + init_val = type(lists[0][0])(0.0) + total = [init_val] * size + for ll in lists: + for i in range(size): + total[i] += ll[i] + return total + + +def args_to_dict(args, prefix: str, strip_prefix: bool = False): + """Filters argparse's `Namespace` into dictionary with arguments + beginning with the given prefix.""" + prefix += '_' + d = {} + for k, v in args.__dict__.items(): + if k.startswith(prefix): + k = k.replace(prefix, '') if strip_prefix else k + d[k] = v + return d + + +def print_test_set(test_set, langpair, requested_fields, origlang=None, subset=None): + """Prints to STDOUT the specified side of the specified test set. + + :param test_set: the test set to print + :param langpair: the language pair + :param requested_fields: the fields to print + :param origlang: print only sentences with a given original language (2-char ISO639-1 code), "non-" prefix means negation + :param subset: print only sentences whose document annotation matches a given regex + """ + if test_set not in DATASETS: + raise Exception(f"No such test set {test_set}") + + fieldnames = DATASETS[test_set].fieldnames(langpair) + all_files = DATASETS[test_set].get_files(langpair) + + if "all" in requested_fields and len(requested_fields) != 1: + sacrelogger.error("Cannot use --echo all with other fields") + sys.exit(1) + elif "all" in requested_fields: + requested_fields = fieldnames + + # backwards compatibility: allow "ref" even if not present (choose first) + if "ref" in requested_fields and "ref" not in fieldnames: + replacement_ref = min([f for f in fieldnames if f.startswith("ref")]) + requested_fields = [f if f != "ref" else replacement_ref for f in requested_fields] + + files = [] + for field in requested_fields: + if field not in fieldnames: + sacrelogger.error(f"No such field {field} in test set {test_set} for language pair {langpair}.") + sacrelogger.error(f"available fields for {test_set}/{langpair}: {', '.join(fieldnames)}") + if "ref" not in fieldnames: + subref = min([f for f in fieldnames if f.startswith("ref")]) + sacrelogger.error(f"'ref' also allowed for backwards compatibility (will return {subref})") + sys.exit(1) + index = fieldnames.index(field) + files.append(all_files[index]) + + streams = [smart_open(file) for file in files] + streams = filter_subset(streams, test_set, langpair, origlang, subset) + for lines in zip(*streams): + print('\t'.join(map(lambda x: x.rstrip(), lines))) + + +def get_source_file(test_set: str, langpair: str) -> str: + """ + Returns the source file for a given testset/langpair. + Downloads it first if it is not already local. + + :param test_set: The test set (e.g., "wmt19") + :param langpair: The language pair (e.g., "de-en") + :return: the path to the requested source file + """ + if test_set not in DATASETS: + raise Exception(f"No such test set {test_set}") + + return DATASETS[test_set].get_source_file(langpair) + + +def get_reference_files(test_set: str, langpair: str) -> List[str]: + """ + Returns a list of one or more reference file paths for the given testset/langpair. + Downloads the references first if they are not already local. + + :param test_set: The test set (e.g., "wmt19") + :param langpair: The language pair (e.g., "de-en") + :return: a list of one or more reference file paths + """ + if test_set not in DATASETS: + raise Exception(f"No such test set {test_set}") + return DATASETS[test_set].get_reference_files(langpair) + + +def get_files(test_set, langpair) -> List[str]: + """ + Returns the path of the source file and all reference files for + the provided test set / language pair. + Downloads the references first if they are not already local. + + :param test_set: The test set (e.g., "wmt19") + :param langpair: The language pair (e.g., "de-en") + :return: a list of the source file and all reference files + """ + + if test_set not in DATASETS: + raise Exception(f"No such test set {test_set}") + return DATASETS[test_set].get_files(langpair) + + +def extract_tarball(filepath, destdir): + sacrelogger.info(f'Extracting {filepath} to {destdir}') + if filepath.endswith('.tar.gz') or filepath.endswith('.tgz'): + import tarfile + with tarfile.open(filepath) as tar: + tar.extractall(path=destdir) + elif filepath.endswith('.zip'): + import zipfile + with zipfile.ZipFile(filepath, 'r') as zipfile: + zipfile.extractall(path=destdir) + + +def get_md5sum(dest_path): + # Check md5sum + md5 = hashlib.md5() + with open(dest_path, 'rb') as infile: + for line in infile: + md5.update(line) + return md5.hexdigest() + + +def download_file(source_path, dest_path, extract_to=None, expected_md5=None): + """Downloading utility. + + Downloads the specified test to the system location specified by the SACREBLEU environment variable. + + :param source_path: the remote uri to download + :param dest_path: where to save the file + :param extract_to: for tarballs, where to extract to + :param expected_md5: the MD5 sum + :return: the set of processed file names + """ + import urllib.request + import ssl + + outdir = os.path.dirname(dest_path) + os.makedirs(outdir, exist_ok=True) + + # Make sure to open in mode "a" + lockfile = f"{dest_path}.lock" + with portalocker.Lock(lockfile, timeout=60): + + if not os.path.exists(dest_path) or os.path.getsize(dest_path) == 0: + sacrelogger.info(f"Downloading {source_path} to {dest_path}") + + try: + with urllib.request.urlopen(source_path) as f, open(dest_path, 'wb') as out: + out.write(f.read()) + except ssl.SSLError: + sacrelogger.error('An SSL error was encountered in downloading the files. If you\'re on a Mac, ' + 'you may need to run the "Install Certificates.command" file located in the ' + '"Python 3" folder, often found under /Applications') + sys.exit(1) + + if expected_md5 is not None: + cur_md5 = get_md5sum(dest_path) + if cur_md5 != expected_md5: + sacrelogger.error(f'Fatal: MD5 sum of downloaded file was incorrect (got {cur_md5}, expected {expected_md5}).') + sacrelogger.error(f'Please manually delete {dest_path!r} and rerun the command.') + sacrelogger.error('If the problem persists, the tarball may have changed, in which case, please contact the SacreBLEU maintainer.') + sys.exit(1) + + # Extract the tarball + if extract_to is not None: + extract_tarball(dest_path, extract_to) + + +def download_test_set(test_set, langpair=None): + """Downloads the specified test to the system location specified by the SACREBLEU environment variable. + + :param test_set: the test set to download + :param langpair: the language pair (needed for some datasets) + :return: the set of processed file names + """ + if test_set not in DATASETS: + raise Exception(f"No such test set {test_set}") + dataset = DATASETS[test_set] + file_paths = dataset.get_files(langpair) + return file_paths + + +def get_langpairs_for_testset(testset: str) -> List[str]: + """Return a list of language pairs for a given test set.""" + if testset not in DATASETS: + return [] + return list(DATASETS[testset].langpairs.keys()) + + +def get_available_testsets() -> List[str]: + """Return a list of available test sets.""" + return sorted(DATASETS.keys(), reverse=True) + +def get_available_testsets_for_langpair(langpair: str) -> List[str]: + """Return a list of available test sets for a given language pair""" + parts = langpair.split('-') + srclang = parts[0] + trglang = parts[1] + + testsets = [] + for dataset in DATASETS.values(): + if f'{srclang}-{trglang}' in dataset.langpairs \ + or f'{trglang}-{srclang}' in dataset.langpairs: + testsets.append(dataset.name) + + return testsets + + +def get_available_origlangs(test_sets, langpair) -> List[str]: + """Return a list of origlang values in according to the raw SGM files.""" + if test_sets is None: + return [] + + origlangs = set() + for test_set in test_sets.split(','): + dataset = DATASETS[test_set] + rawfile = os.path.join(SACREBLEU_DIR, test_set, 'raw', dataset.langpairs[langpair][0]) + if rawfile.endswith('.sgm'): + with smart_open(rawfile) as fin: + for line in fin: + if line.startswith('