|
| 1 | +# NOTE: this is a temporary solution to be able to use the eflomal aligner inside of machine.py. |
| 2 | +# The vast majority of this code is taken from the silnlp repository. |
| 3 | + |
| 4 | +import os |
| 5 | +import subprocess |
| 6 | +from contextlib import ExitStack |
| 7 | +from math import sqrt |
| 8 | +from pathlib import Path |
| 9 | +from tempfile import TemporaryDirectory |
| 10 | +from typing import IO, Iterable, List, Sequence, Tuple |
| 11 | + |
| 12 | +from eflomal import read_text, write_text |
| 13 | + |
| 14 | +from ..corpora import AlignedWordPair |
| 15 | +from ..corpora.token_processors import escape_spaces, lowercase, normalize |
| 16 | +from ..tokenization import LatinWordTokenizer |
| 17 | +from ..translation import SymmetrizationHeuristic, WordAlignmentMatrix |
| 18 | + |
| 19 | +# may have to make more dynamic, look at silnlp get_wsl_path, is there something equivalent in machine? |
| 20 | +EFLOMAL_PATH = Path(os.getenv("EFLOMAL_PATH", "."), "eflomal") |
| 21 | +TOKENIZER = LatinWordTokenizer() |
| 22 | + |
| 23 | + |
| 24 | +# From silnlp.alignment.tools |
| 25 | +def execute_eflomal( |
| 26 | + source_path: Path, |
| 27 | + target_path: Path, |
| 28 | + forward_links_path: Path, |
| 29 | + reverse_links_path: Path, |
| 30 | + n_iterations: Tuple[int, int, int], |
| 31 | +) -> None: |
| 32 | + if not EFLOMAL_PATH.is_file(): |
| 33 | + raise RuntimeError("eflomal is not installed.") |
| 34 | + |
| 35 | + args = [ |
| 36 | + str(EFLOMAL_PATH), |
| 37 | + "-s", |
| 38 | + str(source_path), |
| 39 | + "-t", |
| 40 | + str(target_path), |
| 41 | + "-f", |
| 42 | + str(forward_links_path), |
| 43 | + "-r", |
| 44 | + str(reverse_links_path), |
| 45 | + # "-q", |
| 46 | + "-m", |
| 47 | + "3", |
| 48 | + "-n", |
| 49 | + "3", |
| 50 | + "-N", |
| 51 | + "0.2", |
| 52 | + "-1", |
| 53 | + str(n_iterations[0]), |
| 54 | + "-2", |
| 55 | + str(n_iterations[1]), |
| 56 | + "-3", |
| 57 | + str(n_iterations[2]), |
| 58 | + ] |
| 59 | + subprocess.run(args, stderr=subprocess.DEVNULL) |
| 60 | + |
| 61 | + |
| 62 | +# From silnlp.alignment.eflomal |
| 63 | +def to_word_alignment_matrix(alignment_str: str) -> WordAlignmentMatrix: |
| 64 | + word_pairs = AlignedWordPair.from_string(alignment_str) |
| 65 | + row_count = 0 |
| 66 | + column_count = 0 |
| 67 | + for pair in word_pairs: |
| 68 | + if pair.source_index + 1 > row_count: |
| 69 | + row_count = pair.source_index + 1 |
| 70 | + if pair.target_index + 1 > column_count: |
| 71 | + column_count = pair.target_index + 1 |
| 72 | + return WordAlignmentMatrix.from_word_pairs(row_count, column_count, word_pairs) |
| 73 | + |
| 74 | + |
| 75 | +# From silnlp.alignment.eflomal |
| 76 | +def to_eflomal_text_file(input: Iterable[str], output_file: IO[bytes], prefix_len: int = 0, suffix_len: int = 0) -> int: |
| 77 | + sents, index = read_text(input, True, prefix_len, suffix_len) |
| 78 | + n_sents = len(sents) |
| 79 | + voc_size = len(index) |
| 80 | + write_text(output_file, tuple(sents), voc_size) |
| 81 | + return n_sents |
| 82 | + |
| 83 | + |
| 84 | +# From silnlp.alignment.eflomal |
| 85 | +def prepare_files( |
| 86 | + src_input: Iterable[str], src_output_file: IO[bytes], trg_input: Iterable[str], trg_output_file: IO[bytes] |
| 87 | +) -> int: |
| 88 | + n_src_sents = to_eflomal_text_file(src_input, src_output_file) |
| 89 | + n_trg_sents = to_eflomal_text_file(trg_input, trg_output_file) |
| 90 | + if n_src_sents != n_trg_sents: |
| 91 | + raise ValueError("Mismatched file sizes") |
| 92 | + return n_src_sents |
| 93 | + |
| 94 | + |
| 95 | +def tokenize(sent: str) -> Sequence[str]: |
| 96 | + return lowercase(normalize("NFC", escape_spaces(list(TOKENIZER.tokenize(sent))))) |
| 97 | + |
| 98 | + |
| 99 | +# From silnlp.alignment.eflomal |
| 100 | +class EflomalAligner: |
| 101 | + def __init__(self, model_dir: Path) -> None: |
| 102 | + self._model_dir = model_dir |
| 103 | + |
| 104 | + def train(self, src_toks: Sequence[Sequence[str]], trg_toks: Sequence[Sequence[str]]) -> None: |
| 105 | + self._model_dir.mkdir(exist_ok=True) |
| 106 | + with TemporaryDirectory() as temp_dir: |
| 107 | + src_eflomal_path = Path(temp_dir, "source") |
| 108 | + trg_eflomal_path = Path(temp_dir, "target") |
| 109 | + with ExitStack() as stack: |
| 110 | + src_output_file = stack.enter_context(src_eflomal_path.open("wb")) |
| 111 | + trg_output_file = stack.enter_context(trg_eflomal_path.open("wb")) |
| 112 | + # Write input files for the eflomal binary |
| 113 | + n_sentences = prepare_files( |
| 114 | + [" ".join(s) for s in src_toks], src_output_file, [" ".join(s) for s in trg_toks], trg_output_file |
| 115 | + ) |
| 116 | + |
| 117 | + iters = max(2, int(round(1.0 * 5000 / sqrt(n_sentences)))) |
| 118 | + iters4 = max(1, iters // 4) |
| 119 | + n_iterations = (max(2, iters4), iters4, iters) |
| 120 | + |
| 121 | + # Run wrapper for the eflomal binary |
| 122 | + execute_eflomal( |
| 123 | + src_eflomal_path, |
| 124 | + trg_eflomal_path, |
| 125 | + self._model_dir / "forward-align.txt", |
| 126 | + self._model_dir / "reverse-align.txt", |
| 127 | + n_iterations, |
| 128 | + ) |
| 129 | + |
| 130 | + def align(self, sym_heuristic: str = "grow-diag-final-and") -> List[str]: |
| 131 | + forward_align_path = self._model_dir / "forward-align.txt" |
| 132 | + reverse_align_path = self._model_dir / "reverse-align.txt" |
| 133 | + |
| 134 | + alignments = [] |
| 135 | + heuristic = SymmetrizationHeuristic[sym_heuristic.upper().replace("-", "_")] |
| 136 | + with ExitStack() as stack: |
| 137 | + forward_file = stack.enter_context(forward_align_path.open("r", encoding="utf-8-sig")) |
| 138 | + reverse_file = stack.enter_context(reverse_align_path.open("r", encoding="utf-8-sig")) |
| 139 | + |
| 140 | + for forward_line, reverse_line in zip(forward_file, reverse_file): |
| 141 | + forward_matrix = to_word_alignment_matrix(forward_line.strip()) |
| 142 | + reverse_matrix = to_word_alignment_matrix(reverse_line.strip()) |
| 143 | + src_len = max(forward_matrix.row_count, reverse_matrix.row_count) |
| 144 | + trg_len = max(forward_matrix.column_count, reverse_matrix.column_count) |
| 145 | + |
| 146 | + forward_matrix.resize(src_len, trg_len) |
| 147 | + reverse_matrix.resize(src_len, trg_len) |
| 148 | + |
| 149 | + forward_matrix.symmetrize_with(reverse_matrix, heuristic) |
| 150 | + |
| 151 | + alignments.append(str(forward_matrix)) |
| 152 | + |
| 153 | + return alignments |
0 commit comments