Spaces:
Sleeping
Sleeping
moved scripts to src folder, created new create that hopefully should be able to work with any type of document
Browse files- requirements.txt +4 -1
- src/aligner.py +82 -0
- src/translate_any_doc.py +347 -0
- translate_docx.py → src/translate_docx.py +4 -83
requirements.txt
CHANGED
@@ -4,4 +4,7 @@ torch~=2.6.0
|
|
4 |
transformers~=4.51.2
|
5 |
iso-639~=0.4.5
|
6 |
protobuf~=6.30.2
|
7 |
-
sentencepiece~=0.2.0
|
|
|
|
|
|
|
|
4 |
transformers~=4.51.2
|
5 |
iso-639~=0.4.5
|
6 |
protobuf~=6.30.2
|
7 |
+
sentencepiece~=0.2.0
|
8 |
+
requests~=2.32.3
|
9 |
+
tqdm~=4.67.1
|
10 |
+
gradio~=5.25.1
|
src/aligner.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import fileinput
|
2 |
+
import os
|
3 |
+
import platform
|
4 |
+
from subprocess import Popen, PIPE
|
5 |
+
|
6 |
+
# Class to align original and translated sentences
|
7 |
+
# based on https://github.com/mtuoc/MTUOC-server/blob/main/GetWordAlignments_fast_align.py
|
8 |
+
class Aligner():
|
9 |
+
def __init__(self, config_folder, source_lang, target_lang, temp_folder):
|
10 |
+
forward_params_path = os.path.join(config_folder, f"{source_lang}-{target_lang}.params")
|
11 |
+
reverse_params_path = os.path.join(config_folder, f"{target_lang}-{source_lang}.params")
|
12 |
+
|
13 |
+
fwd_T, fwd_m = self.__read_err(os.path.join(config_folder, f"{source_lang}-{target_lang}.err"))
|
14 |
+
rev_T, rev_m = self.__read_err(os.path.join(config_folder, f"{target_lang}-{source_lang}.err"))
|
15 |
+
|
16 |
+
self.forward_alignment_file_path = os.path.join(temp_folder, "forward.align")
|
17 |
+
self.reverse_alignment_file_path = os.path.join(temp_folder, "reverse.align")
|
18 |
+
|
19 |
+
if platform.system().lower() == "windows":
|
20 |
+
fastalign_bin = "fast_align.exe"
|
21 |
+
atools_bin = "atools.exe"
|
22 |
+
else:
|
23 |
+
fastalign_bin = "./fast_align"
|
24 |
+
atools_bin = "./atools"
|
25 |
+
|
26 |
+
self.temp_file_path = os.path.join(temp_folder, "tokenized_sentences_to_align.txt")
|
27 |
+
|
28 |
+
self.forward_command = [fastalign_bin, "-i", self.temp_file_path, "-d", "-T", fwd_T, "-m", fwd_m, "-f",
|
29 |
+
forward_params_path]
|
30 |
+
self.reverse_command = [fastalign_bin, "-i", self.temp_file_path, "-d", "-T", rev_T, "-m", rev_m, "-f",
|
31 |
+
reverse_params_path, "r"]
|
32 |
+
|
33 |
+
self.symmetric_command = [atools_bin, "-i", self.forward_alignment_file_path, "-j",
|
34 |
+
self.reverse_alignment_file_path, "-c", "grow-diag-final-and"]
|
35 |
+
|
36 |
+
def __simplify_alignment_file(self, file):
|
37 |
+
with fileinput.FileInput(file, inplace=True, backup='.bak') as f:
|
38 |
+
for line in f:
|
39 |
+
print(line.split('|||')[2].strip())
|
40 |
+
|
41 |
+
def __read_err(self, err):
|
42 |
+
(T, m) = ('', '')
|
43 |
+
for line in open(err):
|
44 |
+
# expected target length = source length * N
|
45 |
+
if 'expected target length' in line:
|
46 |
+
m = line.split()[-1]
|
47 |
+
# final tension: N
|
48 |
+
elif 'final tension' in line:
|
49 |
+
T = line.split()[-1]
|
50 |
+
return T, m
|
51 |
+
|
52 |
+
def align(self, original_sentences, translated_sentences):
|
53 |
+
# create temporary file which fastalign will use
|
54 |
+
with open(self.temp_file_path, "w") as temp_file:
|
55 |
+
for original, translated in zip(original_sentences, translated_sentences):
|
56 |
+
temp_file.write(f"{original} ||| {translated}\n")
|
57 |
+
|
58 |
+
# generate forward alignment
|
59 |
+
with open(self.forward_alignment_file_path, 'w') as f_out, open(self.reverse_alignment_file_path, 'w') as r_out:
|
60 |
+
fw_process = Popen(self.forward_command, stdout=f_out)
|
61 |
+
# generate reverse alignment
|
62 |
+
r_process = Popen(self.reverse_command, stdout=r_out)
|
63 |
+
|
64 |
+
# wait for both to finish
|
65 |
+
fw_process.wait()
|
66 |
+
r_process.wait()
|
67 |
+
|
68 |
+
# for some reason the output file contains more information than needed, remove it
|
69 |
+
self.__simplify_alignment_file(self.forward_alignment_file_path)
|
70 |
+
self.__simplify_alignment_file(self.reverse_alignment_file_path)
|
71 |
+
|
72 |
+
# generate symmetrical alignment
|
73 |
+
process = Popen(self.symmetric_command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
|
74 |
+
process.wait()
|
75 |
+
|
76 |
+
# get final alignments and format them
|
77 |
+
alignments_str = process.communicate()[0].decode('utf-8')
|
78 |
+
alignments = []
|
79 |
+
for line in alignments_str.splitlines():
|
80 |
+
alignments.append([(int(i), int(j)) for i, j in [pair.split("-") for pair in line.strip("\n").split(" ")]])
|
81 |
+
|
82 |
+
return alignments
|
src/translate_any_doc.py
ADDED
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import shutil
|
2 |
+
import time
|
3 |
+
import json
|
4 |
+
|
5 |
+
import requests
|
6 |
+
import os
|
7 |
+
from itertools import groupby
|
8 |
+
from subprocess import Popen, PIPE
|
9 |
+
import re
|
10 |
+
|
11 |
+
from src.aligner import Aligner
|
12 |
+
|
13 |
+
import nltk
|
14 |
+
import glob
|
15 |
+
from nltk.tokenize import sent_tokenize, word_tokenize
|
16 |
+
|
17 |
+
nltk.download('punkt')
|
18 |
+
nltk.download('punkt_tab')
|
19 |
+
|
20 |
+
ip = "192.168.20.216"
|
21 |
+
port = "8000"
|
22 |
+
|
23 |
+
|
24 |
+
def translate(text, ip, port):
|
25 |
+
myobj = {
|
26 |
+
'id': '1',
|
27 |
+
'src': text,
|
28 |
+
}
|
29 |
+
port = str(int(port))
|
30 |
+
url = 'http://' + ip + ':' + port + '/translate'
|
31 |
+
x = requests.post(url, json=myobj)
|
32 |
+
json_response = json.loads(x.text)
|
33 |
+
return json_response['tgt']
|
34 |
+
|
35 |
+
|
36 |
+
def doc_to_plain_text(input_file: str, source_lang: str, target_lang: str, tikal_folder: str,
|
37 |
+
original_xliff_file_path: str) -> str:
|
38 |
+
"""
|
39 |
+
Given a document, this function generates an xliff file and then a plain text file with the text contents
|
40 |
+
while keeping style and formatting using tags like <g id=1> </g>
|
41 |
+
|
42 |
+
Parameters:
|
43 |
+
input_file: Path to document to process
|
44 |
+
source_lang: Source language of the document
|
45 |
+
target_lang: Target language of the document
|
46 |
+
tikal_folder: Folder where tikal.sh is located
|
47 |
+
original_xliff_file_path: Path to xliff file to generate, which will be use later
|
48 |
+
|
49 |
+
Returns:
|
50 |
+
string: Path to plain text file
|
51 |
+
"""
|
52 |
+
|
53 |
+
tikal_xliff_command = [os.path.join(tikal_folder, "tikal.sh"), "-x", input_file, "-nocopy", "-sl", source_lang,
|
54 |
+
"-tl", target_lang]
|
55 |
+
Popen(tikal_xliff_command).wait()
|
56 |
+
|
57 |
+
tikal_moses_command = [os.path.join(tikal_folder, "tikal.sh"), "-xm", original_xliff_file_path, "-sl", source_lang,
|
58 |
+
"-tl", target_lang]
|
59 |
+
Popen(tikal_moses_command).wait()
|
60 |
+
|
61 |
+
return os.path.join(original_xliff_file_path + f".{source_lang}")
|
62 |
+
|
63 |
+
|
64 |
+
def get_runs_from_paragraph(text: str, paragraph_index: int) -> list[dict[str, str]]:
|
65 |
+
"""
|
66 |
+
Given some text that may or may not contain some chunks tagged with something like <g id=1> </g>, extract each
|
67 |
+
of the runs of text and convert them into dictionaries to keep this information
|
68 |
+
|
69 |
+
Parameters:
|
70 |
+
text: Text to process
|
71 |
+
paragraph_index: Index of the paragraph in the file
|
72 |
+
|
73 |
+
Returns:
|
74 |
+
list[dict]: Where each element is a run with text, tag id (if any, if not None) and paragraph_index
|
75 |
+
"""
|
76 |
+
|
77 |
+
pattern = r'<g id="(\d+)">(.*?)</g>'
|
78 |
+
chunks = []
|
79 |
+
last_index = 0
|
80 |
+
|
81 |
+
for match in re.finditer(pattern, text):
|
82 |
+
start, end = match.span()
|
83 |
+
id_ = match.group(1)
|
84 |
+
content = match.group(2)
|
85 |
+
|
86 |
+
# Add plain text before the tag, if any
|
87 |
+
if start > last_index:
|
88 |
+
plain_text = text[last_index:start]
|
89 |
+
chunks.append({"text": plain_text, "id": None, "paragraph_index": paragraph_index})
|
90 |
+
|
91 |
+
# Add tagged content
|
92 |
+
if content != " ":
|
93 |
+
chunks.append({"text": content, "id": id_, "paragraph_index": paragraph_index})
|
94 |
+
last_index = end
|
95 |
+
|
96 |
+
# Add any remaining plain text after the last tag
|
97 |
+
if last_index < len(text):
|
98 |
+
chunks.append({"text": text[last_index:], "id": None, "paragraph_index": paragraph_index})
|
99 |
+
|
100 |
+
return chunks
|
101 |
+
|
102 |
+
|
103 |
+
def tokenize_with_runs(runs: list[dict[str, str]], detokenizer) -> list[list[dict[str, str]]]:
|
104 |
+
"""
|
105 |
+
Given a list of runs, we need to tokenize them by sentence and token while keeping the style of each token according
|
106 |
+
to its original run
|
107 |
+
|
108 |
+
Parameters:
|
109 |
+
runs: List of runs, where each item is a chunk of text (possibly various tokens) and some style/formatting information
|
110 |
+
detokenizer: Detokenizer object to merge tokens back together
|
111 |
+
|
112 |
+
Returns:
|
113 |
+
list[list[dict]]: A list of tokenized sentences where each token contains the style of its original run
|
114 |
+
"""
|
115 |
+
text_paragraph = detokenizer.detokenize([run["text"] for run in runs])
|
116 |
+
sentences = sent_tokenize(text_paragraph)
|
117 |
+
tokenized_sentences = [word_tokenize(sentence) for sentence in sentences]
|
118 |
+
|
119 |
+
tokens_with_style = []
|
120 |
+
for run in runs:
|
121 |
+
tokens = word_tokenize(run["text"])
|
122 |
+
for token in tokens:
|
123 |
+
tokens_with_style.append(run.copy())
|
124 |
+
tokens_with_style[-1]["text"] = token
|
125 |
+
|
126 |
+
token_index = 0
|
127 |
+
tokenized_sentences_with_style = []
|
128 |
+
for sentence in tokenized_sentences:
|
129 |
+
sentence_with_style = []
|
130 |
+
for word in sentence:
|
131 |
+
if word == tokens_with_style[token_index]["text"]:
|
132 |
+
sentence_with_style.append(tokens_with_style[token_index])
|
133 |
+
token_index += 1
|
134 |
+
else:
|
135 |
+
if word.startswith(tokens_with_style[token_index]["text"]):
|
136 |
+
# this token might be split into several runs
|
137 |
+
word_left = word
|
138 |
+
|
139 |
+
while word_left:
|
140 |
+
sentence_with_style.append(tokens_with_style[token_index])
|
141 |
+
word_left = word_left.removeprefix(tokens_with_style[token_index]["text"])
|
142 |
+
token_index += 1
|
143 |
+
else:
|
144 |
+
raise "Something unexpected happened I'm afraid"
|
145 |
+
tokenized_sentences_with_style.append(sentence_with_style)
|
146 |
+
return tokenized_sentences_with_style
|
147 |
+
|
148 |
+
|
149 |
+
def generate_alignments(original_paragraphs_with_runs: list[list[dict[str, str]]],
|
150 |
+
translated_paragraphs: list[str], aligner, temp_folder: str,
|
151 |
+
detokenizer) -> list[list[dict[str, str]]]:
|
152 |
+
"""
|
153 |
+
Given some original paragraphs with style and formatting and its translation without formatting, try to match
|
154 |
+
the translated text formatting with the original. Since we only want to run fastalign once we have to temporarily
|
155 |
+
forget about paragraphs and work only in sentences, so the output is a list of sentences but with information about
|
156 |
+
from which paragraph that sentence came from
|
157 |
+
|
158 |
+
Parameters:
|
159 |
+
original_paragraphs_with_runs: Original text split into paragraphs and runs
|
160 |
+
translated_paragraphs: Translated text, split into paragraphs
|
161 |
+
aligner: Object of the aligner class, uses fastalign
|
162 |
+
temp_folder: Path to folder where to put all the intermediate files
|
163 |
+
detokenizer: Detokenizer object to merge tokens back together
|
164 |
+
|
165 |
+
Returns:
|
166 |
+
list[list[dict]]: A list of tokenized sentences where each translated token contains the style of the associated
|
167 |
+
original token
|
168 |
+
"""
|
169 |
+
# clean temp folder
|
170 |
+
for f in glob.glob(os.path.join(temp_folder, "*align*")):
|
171 |
+
os.remove(f)
|
172 |
+
|
173 |
+
# tokenize the original text by sentence and words while keeping the style
|
174 |
+
original_tokenized_sentences_with_style = [tokenize_with_runs(runs, detokenizer) for runs in
|
175 |
+
original_paragraphs_with_runs]
|
176 |
+
|
177 |
+
# flatten all the runs so we can align with just one call instead of one per paragraph
|
178 |
+
original_tokenized_sentences_with_style = [item for sublist in original_tokenized_sentences_with_style for item in
|
179 |
+
sublist]
|
180 |
+
|
181 |
+
# tokenize the translated text by sentence and word
|
182 |
+
translated_tokenized_sentences = [word_tokenize(sentence) for
|
183 |
+
translated_paragraph in translated_paragraphs for sentence in
|
184 |
+
sent_tokenize(translated_paragraph)]
|
185 |
+
|
186 |
+
assert len(translated_tokenized_sentences) == len(
|
187 |
+
original_tokenized_sentences_with_style), "The original and translated texts contain a different number of sentence, likely due to a translation error"
|
188 |
+
|
189 |
+
original_sentences = []
|
190 |
+
translated_sentences = []
|
191 |
+
for original, translated in zip(original_tokenized_sentences_with_style, translated_tokenized_sentences):
|
192 |
+
original_sentences.append(' '.join(item['text'] for item in original))
|
193 |
+
translated_sentences.append(' '.join(translated))
|
194 |
+
|
195 |
+
alignments = aligner.align(original_sentences, translated_sentences)
|
196 |
+
|
197 |
+
# using the alignments generated by fastalign, we need to copy the style of the original token to the translated one
|
198 |
+
translated_sentences_with_style = []
|
199 |
+
for sentence_idx, sentence_alignments in enumerate(alignments):
|
200 |
+
|
201 |
+
# reverse the order of the alignments and build a dict with it
|
202 |
+
sentence_alignments = {target: source for source, target in sentence_alignments}
|
203 |
+
|
204 |
+
translated_sentence_with_style: list[dict[str, str]] = []
|
205 |
+
for token_idx, translated_token in enumerate(translated_tokenized_sentences[sentence_idx]):
|
206 |
+
# fastalign has found a token aligned with the translated one
|
207 |
+
if token_idx in sentence_alignments.keys():
|
208 |
+
# get the aligned token
|
209 |
+
original_idx = sentence_alignments[token_idx]
|
210 |
+
new_entry = original_tokenized_sentences_with_style[sentence_idx][original_idx].copy()
|
211 |
+
new_entry["text"] = translated_token
|
212 |
+
translated_sentence_with_style.append(new_entry)
|
213 |
+
else:
|
214 |
+
# WARNING this is a test
|
215 |
+
# since fastalign doesn't know from which word to reference this token, copy the style of the previous word
|
216 |
+
new_entry = translated_sentence_with_style[-1].copy()
|
217 |
+
new_entry["text"] = translated_token
|
218 |
+
translated_sentence_with_style.append(new_entry)
|
219 |
+
|
220 |
+
translated_sentences_with_style.append(translated_sentence_with_style)
|
221 |
+
|
222 |
+
return translated_sentences_with_style
|
223 |
+
|
224 |
+
|
225 |
+
def group_by_style(tokens: list[dict[str, str]], detokenizer) -> list[dict[str, str]]:
|
226 |
+
"""
|
227 |
+
To avoid having issues in the future, we group the contiguous tokens that have the same style. Basically, we
|
228 |
+
reconstruct the runs.
|
229 |
+
|
230 |
+
Parameters:
|
231 |
+
tokens: Tokens with style information
|
232 |
+
detokenizer: Detokenizer object to merge tokens back together
|
233 |
+
|
234 |
+
Returns:
|
235 |
+
list[dict]: A list of translated runs with format and style
|
236 |
+
"""
|
237 |
+
groups = []
|
238 |
+
for key, group in groupby(tokens, key=lambda x: (x["id"], x["paragraph_index"])):
|
239 |
+
text = detokenizer.detokenize([item['text'] for item in group])
|
240 |
+
|
241 |
+
if groups and not text.startswith((",", ";", ":", ".", ")", "!", "?")):
|
242 |
+
text = " " + text
|
243 |
+
|
244 |
+
groups.append({"text": text,
|
245 |
+
"id": key[0],
|
246 |
+
"paragraph_index": key[1]})
|
247 |
+
return groups
|
248 |
+
|
249 |
+
|
250 |
+
def runs_to_plain_text(paragraphs_with_style: dict[str, list[dict[str, str, str]]], out_file_path: str):
|
251 |
+
"""
|
252 |
+
Generate a plain text file restoring the original tag structure like <g id=1> </g>
|
253 |
+
|
254 |
+
Parameters:
|
255 |
+
paragraphs_with_style: Dictionary where each key is the paragraph_index and its contents are a list of runs
|
256 |
+
out_file_path: Path to the file where the plain text will be saved
|
257 |
+
"""
|
258 |
+
with open(out_file_path, "w") as out_file:
|
259 |
+
for key, paragraph in paragraphs_with_style.items():
|
260 |
+
text_paragraph = ""
|
261 |
+
for run in paragraph:
|
262 |
+
if run["id"]:
|
263 |
+
text_paragraph += f'<g id="{run["id"]}">{run["text"]}</g>'
|
264 |
+
else:
|
265 |
+
text_paragraph += run["text"]
|
266 |
+
out_file.write(text_paragraph + "\n")
|
267 |
+
|
268 |
+
|
269 |
+
def translate_document(input_file: str, source_lang: str, target_lang: str,
|
270 |
+
aligner: Aligner,
|
271 |
+
detokenizer,
|
272 |
+
ip: str = "192.168.20.216",
|
273 |
+
temp_folder: str = "tmp",
|
274 |
+
port: str = "8000",
|
275 |
+
tikal_folder: str = "okapi-apps_gtk2-linux-x86_64_1.47.0") -> str:
|
276 |
+
input_filename = input_file.split("/")[-1]
|
277 |
+
# copy the original file to the temporal folder to avoid common issues with tikal
|
278 |
+
temp_input_file = os.path.join(temp_folder, input_filename)
|
279 |
+
shutil.copy(input_file, temp_input_file)
|
280 |
+
|
281 |
+
original_xliff_file = os.path.join(temp_folder, input_filename + ".xlf")
|
282 |
+
plain_text_file = doc_to_plain_text(temp_input_file, source_lang, target_lang, tikal_folder, original_xliff_file)
|
283 |
+
|
284 |
+
# get paragraphs with runs
|
285 |
+
paragraphs_with_runs = [get_runs_from_paragraph(line.strip(), idx) for idx, line in
|
286 |
+
enumerate(open(plain_text_file).readlines())]
|
287 |
+
|
288 |
+
# translation = translate(open(original_moses_file).read(), ip, port)
|
289 |
+
|
290 |
+
# translate using plaintext file
|
291 |
+
# translated_paragraphs = []
|
292 |
+
# for paragraph in tqdm.tqdm(paragraphs_with_runs, desc="Translating paragraphs..."):
|
293 |
+
# paragraph_text = detokenizer.detokenize([run["text"] for run in paragraph])
|
294 |
+
# translated_paragraphs.append(translate(paragraph_text, ip, port))
|
295 |
+
|
296 |
+
translated_paragraphs = ["Catalan",
|
297 |
+
"Catalan (official name in Catalonia, the Balearic Islands, Andorra, the city of Alghero and traditional in Northern Catalonia) or Valencian (official name in the Valencian Community and traditional in Carxe) is a Romance language spoken in Catalonia, the Valencian Community (except for some regions and towns in the interior), the Balearic Islands (where it is also called Mallorcan, Menorcan, Ibizan or Formentera depending on the island), Andorra, the Franja de Ponent (in Aragon), the city of Alghero (on the island of Sardinia), Northern Catalonia, Carxe (a small territory of Murcia inhabited by Valencian settlers), and in communities around the world (among which Argentina stands out, with 200,000 speakers).",
|
298 |
+
"It has ten million speakers, of whom almost half are native speakers; Its linguistic domain, with an area of 68,730 km² and 13,992,625 inhabitants (2013-2015), includes 1,687 municipal districts. In 2023, it was spoken as a mother tongue by more than four million people (29% of the population of the linguistic territory), of whom 2,924,610 in Catalonia, 1,190,672 in the Valencian Community and 327,384 in the Balearic Islands. Like the other Romance languages, Catalan comes from Vulgar Latin spoken by the Romans who settled in Hispania during ancient times."]
|
299 |
+
|
300 |
+
# time to align the translation with the original
|
301 |
+
print("Generating alignments...")
|
302 |
+
start_time = time.time()
|
303 |
+
translated_sentences_with_style = generate_alignments(paragraphs_with_runs, translated_paragraphs, aligner,
|
304 |
+
temp_folder, detokenizer)
|
305 |
+
print(f"Finished alignments in {time.time() - start_time} seconds")
|
306 |
+
|
307 |
+
# flatten the sentences into a list of tokens
|
308 |
+
translated_tokens_with_style = [item for sublist in translated_sentences_with_style for item in sublist]
|
309 |
+
|
310 |
+
# group the tokens by style/run
|
311 |
+
translated_runs_with_style = group_by_style(translated_tokens_with_style, detokenizer)
|
312 |
+
|
313 |
+
# group the runs by original paragraph
|
314 |
+
translated_paragraphs_with_style = dict()
|
315 |
+
for item in translated_runs_with_style:
|
316 |
+
if item['paragraph_index'] in translated_paragraphs_with_style:
|
317 |
+
translated_paragraphs_with_style[item['paragraph_index']].append(item)
|
318 |
+
else:
|
319 |
+
# first item in the paragraph, remove starting blank space we introduced in group_by_style(), where we
|
320 |
+
# didn't know where paragraphs started and ended
|
321 |
+
first_item_in_paragraph = item.copy()
|
322 |
+
first_item_in_paragraph["text"] = first_item_in_paragraph["text"].lstrip(" ")
|
323 |
+
translated_paragraphs_with_style[item['paragraph_index']] = []
|
324 |
+
translated_paragraphs_with_style[item['paragraph_index']].append(first_item_in_paragraph)
|
325 |
+
|
326 |
+
# save to new plain text file
|
327 |
+
translated_moses_file = os.path.join(original_xliff_file + f".{target_lang}")
|
328 |
+
runs_to_plain_text(translated_paragraphs_with_style, translated_moses_file)
|
329 |
+
|
330 |
+
# put the translations into the xlf
|
331 |
+
tikal_moses_to_xliff_command = [os.path.join(tikal_folder, "tikal.sh"), "-lm", original_xliff_file, "-sl",
|
332 |
+
source_lang, "-tl", target_lang, "-from", translated_moses_file, "-totrg",
|
333 |
+
"-noalttrans", "-to", original_xliff_file]
|
334 |
+
Popen(tikal_moses_to_xliff_command).wait()
|
335 |
+
|
336 |
+
# merge into a docx again
|
337 |
+
tikal_merge_doc_command = [os.path.join(tikal_folder, "tikal.sh"), "-m", original_xliff_file]
|
338 |
+
final_process = Popen(tikal_merge_doc_command, stdout=PIPE, stderr=PIPE)
|
339 |
+
stdout, stderr = final_process.communicate()
|
340 |
+
final_process.wait()
|
341 |
+
|
342 |
+
# get the path to the output file
|
343 |
+
output = stdout.decode('utf-8')
|
344 |
+
translated_file_path = re.search(r'(?<=Output:\s)(.*)', output)[0]
|
345 |
+
|
346 |
+
print("Saved file")
|
347 |
+
return translated_file_path
|
translate_docx.py → src/translate_docx.py
RENAMED
@@ -8,17 +8,13 @@ from docx import Document
|
|
8 |
from docx.text.hyperlink import Hyperlink
|
9 |
from docx.text.run import Run
|
10 |
import nltk
|
11 |
-
import platform
|
12 |
|
13 |
nltk.download('punkt')
|
14 |
nltk.download('punkt_tab')
|
15 |
|
16 |
from nltk.tokenize import sent_tokenize, word_tokenize
|
17 |
|
18 |
-
from subprocess import Popen, PIPE
|
19 |
-
|
20 |
from itertools import groupby
|
21 |
-
import fileinput
|
22 |
|
23 |
ip = "192.168.20.216"
|
24 |
port = "8000"
|
@@ -36,85 +32,6 @@ def translate(text, ip, port):
|
|
36 |
return json_response['tgt']
|
37 |
|
38 |
|
39 |
-
# Class to align original and translated sentences
|
40 |
-
# based on https://github.com/mtuoc/MTUOC-server/blob/main/GetWordAlignments_fast_align.py
|
41 |
-
class Aligner():
|
42 |
-
def __init__(self, config_folder, source_lang, target_lang, temp_folder):
|
43 |
-
forward_params_path = os.path.join(config_folder, f"{source_lang}-{target_lang}.params")
|
44 |
-
reverse_params_path = os.path.join(config_folder, f"{target_lang}-{source_lang}.params")
|
45 |
-
|
46 |
-
fwd_T, fwd_m = self.__read_err(os.path.join(config_folder, f"{source_lang}-{target_lang}.err"))
|
47 |
-
rev_T, rev_m = self.__read_err(os.path.join(config_folder, f"{target_lang}-{source_lang}.err"))
|
48 |
-
|
49 |
-
self.forward_alignment_file_path = os.path.join(temp_folder, "forward.align")
|
50 |
-
self.reverse_alignment_file_path = os.path.join(temp_folder, "reverse.align")
|
51 |
-
|
52 |
-
if platform.system().lower() == "windows":
|
53 |
-
fastalign_bin = "fast_align.exe"
|
54 |
-
atools_bin = "atools.exe"
|
55 |
-
else:
|
56 |
-
fastalign_bin = "./fast_align"
|
57 |
-
atools_bin = "./atools"
|
58 |
-
|
59 |
-
self.temp_file_path = os.path.join(temp_folder, "tokenized_sentences.txt")
|
60 |
-
|
61 |
-
self.forward_command = [fastalign_bin, "-i", self.temp_file_path, "-d", "-T", fwd_T, "-m", fwd_m, "-f",
|
62 |
-
forward_params_path]
|
63 |
-
self.reverse_command = [fastalign_bin, "-i", self.temp_file_path, "-d", "-T", rev_T, "-m", rev_m, "-f",
|
64 |
-
reverse_params_path, "r"]
|
65 |
-
|
66 |
-
self.symmetric_command = [atools_bin, "-i", self.forward_alignment_file_path, "-j",
|
67 |
-
self.reverse_alignment_file_path, "-c", "grow-diag-final-and"]
|
68 |
-
|
69 |
-
def __simplify_alignment_file(self, file):
|
70 |
-
with fileinput.FileInput(file, inplace=True, backup='.bak') as f:
|
71 |
-
for line in f:
|
72 |
-
print(line.split('|||')[2].strip())
|
73 |
-
|
74 |
-
def __read_err(self, err):
|
75 |
-
(T, m) = ('', '')
|
76 |
-
for line in open(err):
|
77 |
-
# expected target length = source length * N
|
78 |
-
if 'expected target length' in line:
|
79 |
-
m = line.split()[-1]
|
80 |
-
# final tension: N
|
81 |
-
elif 'final tension' in line:
|
82 |
-
T = line.split()[-1]
|
83 |
-
return T, m
|
84 |
-
|
85 |
-
def align(self, original_sentences, translated_sentences):
|
86 |
-
# create temporary file which fastalign will use
|
87 |
-
with open(self.temp_file_path, "w") as temp_file:
|
88 |
-
for original, translated in zip(original_sentences, translated_sentences):
|
89 |
-
temp_file.write(f"{original} ||| {translated}\n")
|
90 |
-
|
91 |
-
# generate forward alignment
|
92 |
-
with open(self.forward_alignment_file_path, 'w') as f_out, open(self.reverse_alignment_file_path, 'w') as r_out:
|
93 |
-
fw_process = Popen(self.forward_command, stdout=f_out)
|
94 |
-
# generate reverse alignment
|
95 |
-
r_process = Popen(self.reverse_command, stdout=r_out)
|
96 |
-
|
97 |
-
# wait for both to finish
|
98 |
-
fw_process.wait()
|
99 |
-
r_process.wait()
|
100 |
-
|
101 |
-
# for some reason the output file contains more information than needed, remove it
|
102 |
-
self.__simplify_alignment_file(self.forward_alignment_file_path)
|
103 |
-
self.__simplify_alignment_file(self.reverse_alignment_file_path)
|
104 |
-
|
105 |
-
# generate symmetrical alignment
|
106 |
-
process = Popen(self.symmetric_command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
|
107 |
-
process.wait()
|
108 |
-
|
109 |
-
# get final alignments and format them
|
110 |
-
alignments_str = process.communicate()[0].decode('utf-8')
|
111 |
-
alignments = []
|
112 |
-
for line in alignments_str.splitlines():
|
113 |
-
alignments.append([(int(i), int(j)) for i, j in [pair.split("-") for pair in line.strip("\n").split(" ")]])
|
114 |
-
|
115 |
-
return alignments
|
116 |
-
|
117 |
-
|
118 |
# Function to extract paragraphs with their runs
|
119 |
def extract_paragraphs_with_runs(doc):
|
120 |
paragraphs_with_runs = []
|
@@ -200,6 +117,10 @@ def generate_alignments(original_paragraphs_with_runs, translated_paragraphs, al
|
|
200 |
translated_tokenized_sentences = [word_tokenize(sentence) for
|
201 |
translated_paragraph in translated_paragraphs for sentence in
|
202 |
sent_tokenize(translated_paragraph)]
|
|
|
|
|
|
|
|
|
203 |
original_sentences = []
|
204 |
translated_sentences = []
|
205 |
for original, translated in zip(original_tokenized_sentences_with_style, translated_tokenized_sentences):
|
|
|
8 |
from docx.text.hyperlink import Hyperlink
|
9 |
from docx.text.run import Run
|
10 |
import nltk
|
|
|
11 |
|
12 |
nltk.download('punkt')
|
13 |
nltk.download('punkt_tab')
|
14 |
|
15 |
from nltk.tokenize import sent_tokenize, word_tokenize
|
16 |
|
|
|
|
|
17 |
from itertools import groupby
|
|
|
18 |
|
19 |
ip = "192.168.20.216"
|
20 |
port = "8000"
|
|
|
32 |
return json_response['tgt']
|
33 |
|
34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
# Function to extract paragraphs with their runs
|
36 |
def extract_paragraphs_with_runs(doc):
|
37 |
paragraphs_with_runs = []
|
|
|
117 |
translated_tokenized_sentences = [word_tokenize(sentence) for
|
118 |
translated_paragraph in translated_paragraphs for sentence in
|
119 |
sent_tokenize(translated_paragraph)]
|
120 |
+
|
121 |
+
assert len(translated_tokenized_sentences) == len(
|
122 |
+
original_tokenized_sentences_with_style), "The original and translated texts contain a different number of sentence, likely due to a translation error"
|
123 |
+
|
124 |
original_sentences = []
|
125 |
translated_sentences = []
|
126 |
for original, translated in zip(original_tokenized_sentences_with_style, translated_tokenized_sentences):
|