-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_translator.py.backup
More file actions
274 lines (221 loc) · 9.36 KB
/
document_translator.py.backup
File metadata and controls
274 lines (221 loc) · 9.36 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
#!/usr/bin/env python3
"""
Document Translator - Translate DOCX documents while preserving structure, formatting, and images
This application translates Word documents while maintaining:
- Document structure and layout
- Text formatting (bold, italic, colors, fonts)
- Images and logos
- Tables and lists
- Headers and footers
- Addresses and other elements
"""
import sys
import os
import shutil
from deep_translator import GoogleTranslator
from defusedxml import minidom
import time
import re
# Add ooxml to path
sys.path.insert(0, os.path.dirname(__file__))
from ooxml.document import Document
class DocumentTranslator:
"""Translates DOCX documents while preserving structure"""
def __init__(self, source_lang='auto', target_lang='es'):
"""
Initialize the translator
Args:
source_lang: Source language code (default: 'auto' for auto-detect)
target_lang: Target language code (default: 'es' for Spanish)
"""
self.translator = Translator()
self.source_lang = source_lang
self.target_lang = target_lang
self.translation_cache = {}
def translate_text(self, text):
"""
Translate text with caching to avoid duplicate translations
Args:
text: Text to translate
Returns:
Translated text
"""
if not text or not text.strip():
return text
# Check cache first
if text in self.translation_cache:
return self.translation_cache[text]
try:
# Add small delay to avoid rate limiting
time.sleep(0.1)
result = self.translator.translate(
text,
src=self.source_lang,
dest=self.target_lang
)
translated = result.text
self.translation_cache[text] = translated
return translated
except Exception as e:
print(f"Warning: Translation failed for '{text[:50]}...': {e}")
return text
def should_translate_node(self, node):
"""
Determine if a node's text should be translated
Some elements like email addresses, URLs, or pure numbers
should not be translated
Args:
node: XML node to check
Returns:
Boolean indicating if node should be translated
"""
if node.nodeType != minidom.Node.TEXT_NODE:
return False
text = node.nodeValue.strip()
if not text:
return False
# Don't translate email addresses
if '@' in text and '.' in text:
return False
# Don't translate URLs
if text.startswith('http://') or text.startswith('https://') or text.startswith('www.'):
return False
# Don't translate pure numbers or dates in simple format
if re.match(r'^[\d\s\-/.,]+$', text):
return False
return True
def translate_xml_text_nodes(self, node):
"""
Recursively translate all text nodes in an XML structure
Args:
node: XML node to process
"""
# Process text nodes
if node.nodeType == minidom.Node.TEXT_NODE:
if self.should_translate_node(node):
original = node.nodeValue
translated = self.translate_text(original)
node.nodeValue = translated
print(f" Translated: '{original[:50]}...' -> '{translated[:50]}...'")
# Recursively process child nodes
if node.hasChildNodes():
for child in list(node.childNodes):
self.translate_xml_text_nodes(child)
def translate_document(self, input_docx, output_docx):
"""
Translate a DOCX document
Args:
input_docx: Path to input DOCX file
output_docx: Path to output DOCX file
"""
print(f"\n{'='*60}")
print(f"Document Translator")
print(f"{'='*60}")
print(f"Input: {input_docx}")
print(f"Output: {output_docx}")
print(f"Source Language: {self.source_lang}")
print(f"Target Language: {self.target_lang}")
print(f"{'='*60}\n")
# Create temporary directory for unpacking
temp_dir = '/tmp/doc_translate_temp'
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
os.makedirs(temp_dir)
try:
# Unpack the document
print("Step 1: Unpacking document...")
unpack_script = os.path.join(os.path.dirname(__file__), 'scripts', 'unpack.py')
os.system(f'python {unpack_script} "{input_docx}" "{temp_dir}"')
# Initialize Document object
print("\nStep 2: Loading document structure...")
doc = Document(temp_dir)
# Translate main document content
print("\nStep 3: Translating main document content...")
doc_xml = doc['word/document.xml']
self.translate_xml_text_nodes(doc_xml.dom.documentElement)
# Translate headers if they exist
header_files = [f for f in os.listdir(os.path.join(doc.unpacked_path, 'word'))
if f.startswith('header') and f.endswith('.xml')]
if header_files:
print("\nStep 4: Translating headers...")
for header_file in header_files:
header_path = f'word/{header_file}'
if header_path in doc.files:
header_xml = doc[header_path]
self.translate_xml_text_nodes(header_xml.dom.documentElement)
# Translate footers if they exist
footer_files = [f for f in os.listdir(os.path.join(doc.unpacked_path, 'word'))
if f.startswith('footer') and f.endswith('.xml')]
if footer_files:
print("\nStep 5: Translating footers...")
for footer_file in footer_files:
footer_path = f'word/{footer_file}'
if footer_path in doc.files:
footer_xml = doc[footer_path]
self.translate_xml_text_nodes(footer_xml.dom.documentElement)
# Save the modified document
print("\nStep 6: Saving translated document...")
doc.save()
# Pack the document
print("\nStep 7: Packing translated document...")
pack_script = os.path.join(os.path.dirname(__file__), 'scripts', 'pack.py')
os.system(f'python {pack_script} "{temp_dir}" "{output_docx}"')
print(f"\n{'='*60}")
print(f"Translation Complete!")
print(f"{'='*60}")
print(f"Translated {len(self.translation_cache)} unique text segments")
print(f"Output saved to: {output_docx}")
print(f"{'='*60}\n")
except Exception as e:
print(f"\nError during translation: {e}")
import traceback
traceback.print_exc()
raise
finally:
# Cleanup temporary directory
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
def main():
"""Main entry point for the application"""
if len(sys.argv) < 3:
print("Document Translator - Translate DOCX while preserving structure")
print("\nUsage:")
print(" python document_translator.py <input.docx> <output.docx> [target_lang] [source_lang]")
print("\nExamples:")
print(" python document_translator.py document.docx translated.docx es")
print(" python document_translator.py document.docx translated.docx fr en")
print("\nCommon language codes:")
print(" en - English")
print(" es - Spanish")
print(" fr - French")
print(" de - German")
print(" it - Italian")
print(" pt - Portuguese")
print(" ru - Russian")
print(" zh-cn - Chinese (Simplified)")
print(" ja - Japanese")
print(" ko - Korean")
print(" ar - Arabic")
print("\nFeatures:")
print(" ✓ Preserves document structure and formatting")
print(" ✓ Keeps images and logos intact")
print(" ✓ Maintains tables, lists, and styles")
print(" ✓ Preserves headers and footers")
print(" ✓ Skips emails, URLs, and pure numbers")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
target_lang = sys.argv[3] if len(sys.argv) > 3 else 'es'
source_lang = sys.argv[4] if len(sys.argv) > 4 else 'auto'
# Validate input file
if not os.path.exists(input_file):
print(f"Error: Input file '{input_file}' not found")
sys.exit(1)
if not input_file.endswith('.docx'):
print("Error: Input file must be a .docx file")
sys.exit(1)
# Create translator and translate document
translator = DocumentTranslator(source_lang=source_lang, target_lang=target_lang)
translator.translate_document(input_file, output_file)
if __name__ == '__main__':
main()