-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtranslation_manager.py
More file actions
205 lines (180 loc) · 6.18 KB
/
Copy pathtranslation_manager.py
File metadata and controls
205 lines (180 loc) · 6.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import os
import re
import polib
import itertools
import argparse
from typing import Dict, Tuple
from openpyxl import Workbook, load_workbook
_patterns = [
":c:func:`[^`]+`",
":c:type:`[^`]+`",
":c:macro:`[^`]+`",
":c:member:`[^`]+`",
":c:data:`[^`]+`",
":py:data:`[^`]+`",
":py:mod:`[^`]+`",
":func:`[^`]+`",
":mod:`[^`]+`",
":ref:`[^`]+`",
":class:`[^`]+`",
":pep:`[^`]+`",
":data:`[^`]+`",
":exc:`[^`]+`",
":term:`[^`]+`",
":meth:`[^`]+`",
":envvar:`[^`]+`",
":file:`[^`]+`",
":attr:`[^`]+`",
":const:`[^`]+`",
":issue:`[^`]+`",
":opcode:`[^`]+`",
":option:`[^`]+`",
":program:`[^`]+`",
":keyword:`[^`]+`",
":RFC:`[^`]+`",
":rfc:`[^`]+`",
":doc:`[^`]+`",
":source:`[^`]+`",
":manpage:`[^`]+`",
":mimetype:`[^`]+`",
":sup:`[^`]+`",
":kbd:`[^`]+`",
":const:`[^`]+`",
"``[^`]+``",
"`[^`]+`__",
"`[^`]+`_",
r"\*\*[^\*]+\*\*", # bold text between **
r"\*[^\*]+\*", # italic text between *
]
_exps = [re.compile(e) for e in _patterns]
class Normalizer:
@staticmethod
def protect_sphinx_directives(s: str) -> Tuple[Dict[str, str], str]:
"""
Replace Sphinx directives in the input string with placeholders.
Parameters:
s: The original string containing Sphinx directives.
Returns:
A tuple (placeholders, new_s) where 'placeholders' maps placeholders
to the original directives and 'new_s' is the string with placeholders.
"""
placeholders: Dict[str, str] = {}
counter = itertools.count()
def repl(match):
ph = f"XASDF{next(counter):02}"
placeholders[ph] = match.group(0)
return ph
combined_pattern = "|".join(f"({p})" for p in _patterns)
combined_regex = re.compile(combined_pattern)
new_s = combined_regex.sub(repl, s)
return placeholders, new_s
@staticmethod
def undo_sphinx_directives_protection(
placeholders: Dict[str, str], translated_text: str
) -> str:
"""
Restore the original Sphinx directives in the translated text.
"""
for ph, value in placeholders.items():
translated_text = translated_text.replace(ph, value)
return translated_text
class POExtractor:
"""Extracts unique strings from .po files in given directories and exports them to an Excel file."""
def __init__(self, directories):
self.directories = directories
self.strings = {}
def extract_strings_from_po(self, po_path: str) -> None:
po = polib.pofile(po_path)
for entry in po:
if entry.msgid:
self.strings[entry.msgid] = None
def process_directories(self) -> None:
for base_dir in self.directories:
for root, _, files in os.walk(base_dir):
for file in files:
if file.endswith(".po"):
po_path = os.path.join(root, file)
self.extract_strings_from_po(po_path)
def generate_excel(self, output_excel: str) -> None:
wb = Workbook()
ws = wb.active
ws.title = "Translations"
ws.append(["Original", "Placeholders", "Temp Text", "Translation"])
for original in self.strings:
placeholders, temp_text = Normalizer.protect_sphinx_directives(original)
ws.append([original, str(placeholders), temp_text, ""])
wb.save(output_excel)
print(f"Excel file saved to {output_excel}.")
class POUpdater:
"""Updates .po files with translations from an Excel file."""
def __init__(self, directories, excel_file: str):
self.directories = directories
self.excel_file = excel_file
self.translations = {}
def load_translations(self) -> None:
wb = load_workbook(self.excel_file)
ws = wb.active
for row in ws.iter_rows(min_row=2, values_only=True):
if row[0]:
original = row[0]
placeholders = eval(row[1])
translated = row[3]
translated = Normalizer.undo_sphinx_directives_protection(
placeholders, translated
)
self.translations[original] = translated
def update_po_file(self, po_path: str) -> None:
po = polib.pofile(po_path)
updated = False
for entry in po:
if entry.msgid in self.translations:
new_translation = self.translations[entry.msgid]
if new_translation != entry.msgstr:
entry.msgstr = new_translation
if "fuzzy" not in entry.flags:
entry.flags.append("fuzzy")
updated = True
if updated:
po.save()
print(f"Updated translations in {po_path}")
def update_directories(self) -> None:
self.load_translations()
if not self.translations:
print("No translations found in the Excel file.")
return
for base_dir in self.directories:
for root, _, files in os.walk(base_dir):
for file in files:
if file.endswith(".po"):
self.update_po_file(os.path.join(root, file))
def main():
parser = argparse.ArgumentParser(
description="Extract or update PO translations using an Excel file"
)
parser.add_argument(
"mode",
choices=["extract", "update"],
help="Choose to extract from or update PO files",
)
parser.add_argument(
"--dir",
nargs="+",
default=["./need_to_translate"],
help="Directories containing PO files",
)
parser.add_argument(
"--excel",
type=str,
default="translations.xlsx",
help="Excel file to read from or write to",
)
args = parser.parse_args()
if args.mode == "extract":
extractor = POExtractor(args.dir)
extractor.process_directories()
extractor.generate_excel(args.excel)
elif args.mode == "update":
updater = POUpdater(args.dir, args.excel)
updater.update_directories()
if __name__ == "__main__":
main()