-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathextract_untranslated.py
More file actions
executable file
·323 lines (266 loc) · 11.2 KB
/
extract_untranslated.py
File metadata and controls
executable file
·323 lines (266 loc) · 11.2 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#!/usr/bin/env python3
"""
Extract untranslated messages from a .po file for translation.
Usage: python extract_untranslated.py <locale> [limit] [--include-excluded] [--module=ModuleName]
Example: python extract_untranslated.py fr_FR
Example: python extract_untranslated.py fr_FR --module=ZoneImportExport
"""
import sys
import os
import re
import json
from pathlib import Path
class PoEntry:
def __init__(self):
self.comments = []
self.locations = []
self.flags = []
self.msgid = ""
self.msgid_plural = ""
self.msgstr = ""
self.msgstr_plural = {}
self.is_fuzzy = False
self.is_untranslated = False
class PoParser:
def __init__(self, file_path, exclusions=None):
self.file_path = file_path
self.entries = []
self.exclusions = exclusions or []
def parse(self):
with open(self.file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Split by double newlines to separate entries
blocks = re.split(r'\n\s*\n', content)
for block in blocks:
if not block.strip():
continue
entry = self._parse_block(block)
if entry and entry.msgid: # Skip header entry (empty msgid)
self.entries.append(entry)
return self.entries
def _parse_block(self, block):
entry = PoEntry()
lines = block.strip().split('\n')
i = 0
while i < len(lines):
line = lines[i].strip()
# Comments and metadata
if line.startswith('#.'): # Translator comment
entry.comments.append(line)
elif line.startswith('#:'): # Location
entry.locations.append(line[2:].strip())
elif line.startswith('#,'): # Flags
flags = line[2:].strip().split(',')
entry.flags = [f.strip() for f in flags]
if 'fuzzy' in entry.flags:
entry.is_fuzzy = True
elif line.startswith('#'): # Other comments
entry.comments.append(line)
# Message ID
elif line.startswith('msgid '):
msgid_lines = [self._extract_string(line[6:])]
i += 1
while i < len(lines) and lines[i].strip().startswith('"'):
msgid_lines.append(self._extract_string(lines[i].strip()))
i += 1
entry.msgid = ''.join(msgid_lines)
i -= 1
# Message ID plural
elif line.startswith('msgid_plural '):
msgid_plural_lines = [self._extract_string(line[13:])]
i += 1
while i < len(lines) and lines[i].strip().startswith('"'):
msgid_plural_lines.append(self._extract_string(lines[i].strip()))
i += 1
entry.msgid_plural = ''.join(msgid_plural_lines)
i -= 1
# Message string
elif line.startswith('msgstr '):
msgstr_lines = [self._extract_string(line[7:])]
i += 1
while i < len(lines) and lines[i].strip().startswith('"'):
msgstr_lines.append(self._extract_string(lines[i].strip()))
i += 1
entry.msgstr = ''.join(msgstr_lines)
i -= 1
# Message string plural
elif re.match(r'msgstr\[\d+\] ', line):
match = re.match(r'msgstr\[(\d+)\] (.+)', line)
if match:
index = int(match.group(1))
msgstr_lines = [self._extract_string(match.group(2))]
i += 1
while i < len(lines) and lines[i].strip().startswith('"'):
msgstr_lines.append(self._extract_string(lines[i].strip()))
i += 1
entry.msgstr_plural[index] = ''.join(msgstr_lines)
i -= 1
i += 1
# Check if untranslated
if entry.msgid:
if entry.msgid_plural:
# For plural forms, check if any msgstr[n] is empty or same as msgid
entry.is_untranslated = any(
not msgstr or msgstr == entry.msgid or msgstr == entry.msgid_plural
for msgstr in entry.msgstr_plural.values()
)
else:
# For singular forms
entry.is_untranslated = (
not entry.msgstr or
entry.msgstr == entry.msgid
)
return entry
def _extract_string(self, s):
"""Extract string content from quoted string."""
s = s.strip()
if s.startswith('"') and s.endswith('"'):
s = s[1:-1]
# Unescape common sequences
s = s.replace('\\n', '\n')
s = s.replace('\\t', '\t')
s = s.replace('\\"', '"')
s = s.replace('\\\\', '\\')
return s
def is_excluded(self, msgid):
"""Check if a message ID should be excluded from translation."""
if not self.exclusions:
return False
# Direct match
if msgid in self.exclusions:
return True
# Check if msgid is purely technical (only contains excluded terms)
words = re.findall(r'\b\w+\b', msgid)
if words and all(word.upper() in [e.upper() for e in self.exclusions] for word in words):
return True
# Check if msgid is very short and looks technical
if len(msgid) <= 5 and msgid.isupper():
return True
return False
def load_exclusions():
"""Load technical exclusions from JSON file."""
exclusions_file = Path(__file__).parent / "technical_exclusions.json"
if not exclusions_file.exists():
print(f"Warning: Exclusions file {exclusions_file} not found. Continuing without exclusions.")
return []
try:
with open(exclusions_file, 'r', encoding='utf-8') as f:
data = json.load(f)
return data.get('exclusions', [])
except (json.JSONDecodeError, FileNotFoundError) as e:
print(f"Warning: Could not load exclusions file: {e}")
return []
def main():
if len(sys.argv) < 2 or len(sys.argv) > 5:
print("Usage: python extract_untranslated.py <locale> [limit] [--include-excluded] [--module=ModuleName]")
print("Example: python extract_untranslated.py fr_FR")
print("Example: python extract_untranslated.py fr_FR 50")
print("Example: python extract_untranslated.py fr_FR 200 --include-excluded")
print("Example: python extract_untranslated.py fr_FR --module=ZoneImportExport")
sys.exit(1)
locale = sys.argv[1]
limit = None
include_excluded = False
module_name = None
# Parse additional arguments
for arg in sys.argv[2:]:
if arg == "--include-excluded":
include_excluded = True
elif arg.startswith("--module="):
module_name = arg.split("=", 1)[1]
elif arg.isdigit():
limit = int(arg)
if module_name:
po_file = Path(f"lib/Module/{module_name}/locale/{locale}/messages.po")
else:
po_file = Path(f"locale/{locale}/LC_MESSAGES/messages.po")
if not po_file.exists():
print(f"Error: File {po_file} does not exist")
sys.exit(1)
# Load exclusions unless explicitly disabled
exclusions = [] if include_excluded else load_exclusions()
print(f"Parsing {po_file}...")
if exclusions and not include_excluded:
print(f"Loaded {len(exclusions)} technical exclusions")
parser = PoParser(po_file, exclusions)
entries = parser.parse()
# Separate untranslated and fuzzy entries
untranslated = []
fuzzy = []
excluded_count = 0
for entry in entries:
if entry.is_fuzzy:
if not parser.is_excluded(entry.msgid):
fuzzy.append(entry)
else:
excluded_count += 1
elif entry.is_untranslated:
if not parser.is_excluded(entry.msgid):
untranslated.append(entry)
else:
excluded_count += 1
# Apply limit if specified
if limit:
untranslated = untranslated[:limit]
fuzzy = fuzzy[:limit]
# Prepare output data
total_untranslated = len([e for e in entries if e.is_untranslated and not parser.is_excluded(e.msgid)])
output_data = {
'locale': locale,
'untranslated_count': len(untranslated),
'fuzzy_count': len(fuzzy),
'total_untranslated': total_untranslated,
'excluded_count': excluded_count,
'entries': []
}
# Add untranslated entries
for entry in untranslated:
entry_data = {
'locations': entry.locations,
'msgid': entry.msgid,
'translation': ''
}
if entry.msgid_plural:
entry_data['msgid_plural'] = entry.msgid_plural
entry_data['translations'] = {} # For plural forms
if entry.comments:
entry_data['comments'] = entry.comments
output_data['entries'].append(entry_data)
# Add fuzzy entries in a separate section
if fuzzy:
output_data['fuzzy_entries'] = []
for entry in fuzzy:
entry_data = {
'locations': entry.locations,
'msgid': entry.msgid,
'current_translation': entry.msgstr,
'translation': ''
}
if entry.msgid_plural:
entry_data['msgid_plural'] = entry.msgid_plural
entry_data['current_translations'] = entry.msgstr_plural
entry_data['translations'] = {}
if entry.comments:
entry_data['comments'] = entry.comments
output_data['fuzzy_entries'].append(entry_data)
# Write output file
output_file = f"{module_name}_{locale}_untranslated.json" if module_name else f"{locale}_untranslated.json"
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(output_data, f, indent=2, ensure_ascii=False)
print(f"\nExtraction complete!")
if limit and 'total_untranslated' in output_data:
print(f"- Untranslated entries: {len(untranslated)} (limited from {output_data['total_untranslated']})")
else:
print(f"- Untranslated entries: {len(untranslated)}")
print(f"- Fuzzy entries: {len(fuzzy)}")
if excluded_count > 0:
print(f"- Excluded technical terms: {excluded_count}")
print(f"- Output saved to: {output_file}")
# Show a few examples
if untranslated:
print("\nExample untranslated entries:")
for i, entry in enumerate(untranslated[:3]):
print(f"\n{i+1}. {entry.locations[0] if entry.locations else 'No location'}")
print(f" msgid: {entry.msgid[:80]}{'...' if len(entry.msgid) > 80 else ''}")
if __name__ == "__main__":
main()