mintlee commited on
Commit
ce94f1c
·
1 Parent(s): e146811

word update

Browse files
.env CHANGED
@@ -1 +1,2 @@
1
- GEMINI_API_KEY = AIzaSyAk1LTwWMZyTfPAKmsn6JzFtI1MpnI7FH8
 
 
1
+ GEMINI_API_KEY = AIzaSyAk1LTwWMZyTfPAKmsn6JzFtI1MpnI7FH8
2
+ MONGODB_URI = mongodb+srv://admin:[email protected]/?retryWrites=true&w=majority&appName=Cluster0
excel/__pycache__/excel_translate.cpython-310.pyc CHANGED
Binary files a/excel/__pycache__/excel_translate.cpython-310.pyc and b/excel/__pycache__/excel_translate.cpython-310.pyc differ
 
pages/upload.py CHANGED
@@ -4,7 +4,7 @@ from db.mongodb import save_file_to_mongodb, fetch_file_from_mongodb, detect_fil
4
  from powerpoint.pptx import translate_pptx
5
  from excel.xlsx import translate_xlsx
6
  from excel.excel_translate import translate_csv
7
- from word.word_translate import translate_docx
8
  import dotenv
9
  import os
10
 
@@ -33,7 +33,7 @@ def process_file(file, file_type):
33
  elif file_type == "CSV":
34
  final_id = translate_csv(file_id = file_id, source_lang = source_lang, target_lang = target_lang)
35
  elif file_type == "Word":
36
- final_id = translate_docx(file_id, source_lang = source_lang, target_lang = target_lang)
37
  else:
38
  st.error("❌ Loại file không hỗ trợ!")
39
  return
 
4
  from powerpoint.pptx import translate_pptx
5
  from excel.xlsx import translate_xlsx
6
  from excel.excel_translate import translate_csv
7
+ from word.word_helper import translate_docx
8
  import dotenv
9
  import os
10
 
 
33
  elif file_type == "CSV":
34
  final_id = translate_csv(file_id = file_id, source_lang = source_lang, target_lang = target_lang)
35
  elif file_type == "Word":
36
+ final_id = translate_docx(file_id = file_id, file_name = file_name , source_lang = source_lang, target_lang = target_lang)
37
  else:
38
  st.error("❌ Loại file không hỗ trợ!")
39
  return
translate/__pycache__/translator.cpython-310.pyc CHANGED
Binary files a/translate/__pycache__/translator.cpython-310.pyc and b/translate/__pycache__/translator.cpython-310.pyc differ
 
word/__pycache__/word_helper.cpython-310.pyc ADDED
Binary file (14.3 kB). View file
 
word/{word_translate.py → word_helper.py} RENAMED
@@ -5,16 +5,21 @@ import google.generativeai as genai
5
  import ast
6
  import json
7
  import re
 
8
  import dotenv
 
9
  from pymongo import MongoClient
10
- from gridfs import GridFS
11
- from docx import Document
12
  from io import BytesIO
13
 
14
-
15
  dotenv.load_dotenv(".env")
16
- api_key = os.getenv("GEMINI_API_KEY")
17
 
 
 
 
 
 
 
18
 
19
  def batch_translate(texts, source_lang = 'English', target_lang="Vietnamese"):
20
  """ Translates multiple text segments in a single API call. """
@@ -28,11 +33,12 @@ def batch_translate(texts, source_lang = 'English', target_lang="Vietnamese"):
28
  1. You will be given three inputs: source language, target language, and a JSON file.
29
  2. The JSON file contains a Python dictionary where each key is an integer, and each value is a string.
30
  3. Ensure one-to-one correspondence—each input item must correspond to exactly one output item with the same number of items.
31
- 4. Preserve spaces before or after strings. Do not remove, merge, split, or omit any strings.
32
- 5. Translate paragraphs and ensure the translation makes sense when text is put together.
33
- 6. Translate split words so that the word is not split in the translation.
34
- 7. Return a JSON object that is a Python dictionary containing as many items as the original JSON file, with keys and order preserved.
35
- 8. The output must be a syntactically correct Python dictionary.
 
36
 
37
  Additional Examples:
38
  **Input 1**:
@@ -230,7 +236,7 @@ def full_translate(texts, source_lang = 'English', target_lang="Vietnamese"):
230
  global time_spent_sleeping
231
 
232
  for string in texts:
233
- if len(string.split()) + word_count >= 1000:
234
  print('Translating a batch.')
235
 
236
  translated_batch = batch_translate_loop(batch, source_lang, target_lang)
@@ -368,35 +374,46 @@ def merge_elements(doc):
368
  current_run = [element]
369
  return doc
370
 
371
- def translate_docx(word_id, source_lang = "English", target_lang="Vietnamese", output_num = ''):
372
- """ Translates a Word document efficiently using batch processing. """
 
 
 
 
373
 
374
- client = MongoClient("mongodb+srv://admin:[email protected]/?retryWrites=true&w=majority&appName=Cluster0")
375
- db = client['pptx']
376
- fs = GridFS(db, collection='root_file')
377
- word_file = fs.get(word_id)
378
-
379
- doc = Document(BytesIO(word_file.read()))
380
- output_file = os.path.join(os.path.dirname(input_file), f"{output_num}{target_language}_translated_{os.path.basename(input_file)}")
381
 
 
382
  doc = merge_elements(doc)
383
-
384
  print('Translating paragraphs.')
385
  para_texts = get_text_elements_para(doc)
386
- translated_para = full_translate(para_texts, source_lang = source_lang, target_lang = target_lang)
387
- print('Done translating pararaphs.')
388
 
389
  print('Translating tables.')
390
  table_texts = get_text_elements_table(doc)
391
- translated_tables = full_translate(table_texts, source_lang = source_lang, target_lang = target_lang)
392
  print('Done translating tables.')
393
 
394
- print('Inserting paragaphs')
395
  doc, _ = translate_paragraphs(doc, translated_para)
 
396
  print('Inserting tables.')
397
  doc = translate_tables(doc, translated_tables)
398
 
399
  translate_header_footer(doc, source_lang, target_lang)
400
  print('Done translating headers & footers.')
401
 
402
- doc.save(output_file)
 
 
 
 
 
 
 
 
 
 
5
  import ast
6
  import json
7
  import re
8
+ import time
9
  import dotenv
10
+ import os
11
  from pymongo import MongoClient
12
+ import gridfs
 
13
  from io import BytesIO
14
 
 
15
  dotenv.load_dotenv(".env")
 
16
 
17
+ genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
18
+
19
+
20
+
21
+ time_spent_sleeping = 0
22
+ mismatches = 0
23
 
24
  def batch_translate(texts, source_lang = 'English', target_lang="Vietnamese"):
25
  """ Translates multiple text segments in a single API call. """
 
33
  1. You will be given three inputs: source language, target language, and a JSON file.
34
  2. The JSON file contains a Python dictionary where each key is an integer, and each value is a string.
35
  3. Ensure one-to-one correspondence—each input item must correspond to exactly one output item with the same number of items.
36
+ 4. The names of people, places, and organizations should be preserved in the translation.
37
+ 5. Preserve spaces before or after strings. Do not remove, merge, split, or omit any strings.
38
+ 6. Translate paragraphs and ensure the translation makes sense when text is put together.
39
+ 7. Translate split words so that the word is not split in the translation.
40
+ 8. Return a JSON object that is a Python dictionary containing as many items as the original JSON file, with keys and order preserved.
41
+ 9. The output must be a syntactically correct Python dictionary.
42
 
43
  Additional Examples:
44
  **Input 1**:
 
236
  global time_spent_sleeping
237
 
238
  for string in texts:
239
+ if len(string.split()) + word_count >= 2000:
240
  print('Translating a batch.')
241
 
242
  translated_batch = batch_translate_loop(batch, source_lang, target_lang)
 
374
  current_run = [element]
375
  return doc
376
 
377
+ def translate_docx(file_id, source_lang="English", target_lang="Vietnamese", file_name=''):
378
+ """Translates a Word document and saves the output to MongoDB."""
379
+ client = MongoClient(os.getenv("MONGODB_URI"))
380
+ db = client["word"]
381
+ fs_input = gridfs.GridFS(db, collection="root_file")
382
+ fs_output = gridfs.GridFS(db, collection="final_file")
383
 
384
+ # Lấy file gốc từ MongoDB
385
+ input_file = fs_input.get(file_id)
386
+ doc = Document(BytesIO(input_file.read()))
 
 
 
 
387
 
388
+ # Dịch nội dung
389
  doc = merge_elements(doc)
390
+
391
  print('Translating paragraphs.')
392
  para_texts = get_text_elements_para(doc)
393
+ translated_para = full_translate(para_texts, source_lang=source_lang, target_lang=target_lang)
394
+ print('Done translating paragraphs.')
395
 
396
  print('Translating tables.')
397
  table_texts = get_text_elements_table(doc)
398
+ translated_tables = full_translate(table_texts, source_lang=source_lang, target_lang=target_lang)
399
  print('Done translating tables.')
400
 
401
+ print('Inserting paragraphs.')
402
  doc, _ = translate_paragraphs(doc, translated_para)
403
+
404
  print('Inserting tables.')
405
  doc = translate_tables(doc, translated_tables)
406
 
407
  translate_header_footer(doc, source_lang, target_lang)
408
  print('Done translating headers & footers.')
409
 
410
+ # Lưu tài liệu đã dịch vào MongoDB
411
+ output_stream = BytesIO()
412
+ doc.save(output_stream)
413
+ output_stream.seek(0)
414
+
415
+ translated_file_id = fs_output.put(output_stream, filename=file_name)
416
+ client.close()
417
+
418
+ print(f"Translation complete! Saved to MongoDB with id: {translated_file_id}")
419
+ return translated_file_id
word/word_translate.ipynb DELETED
@@ -1,580 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "code",
5
- "execution_count": 14,
6
- "metadata": {},
7
- "outputs": [],
8
- "source": [
9
- "import os\n",
10
- "import docx\n",
11
- "from docx import Document\n",
12
- "import google.generativeai as genai\n",
13
- "import ast\n",
14
- "import json\n",
15
- "import re\n",
16
- "import time\n",
17
- "\n",
18
- "genai.configure(api_key=\"AIzaSyAk1LTwWMZyTfPAKmsn6JzFtI1MpnI7FH8\")\n",
19
- "target_language = 'English' \n",
20
- "source_language = 'VietNamese'\n",
21
- "\n",
22
- "time_spent_sleeping = 0\n",
23
- "mismatches = 0\n",
24
- "\n",
25
- "def batch_translate(texts, source_lang = 'English', target_lang=\"Vietnamese\"):\n",
26
- " \"\"\" Translates multiple text segments in a single API call. \"\"\"\n",
27
- " if not texts:\n",
28
- " return texts # Skip if empty\n",
29
- " \n",
30
- " system_prompt = \"\"\"\n",
31
- " Translate the contents of a JSON file from the specified source language to the specified target language while preserving the structure, spaces, and context of the original text.\n",
32
- "\n",
33
- " Instructions:\n",
34
- " 1. You will be given three inputs: source language, target language, and a JSON file.\n",
35
- " 2. The JSON file contains a Python dictionary where each key is an integer, and each value is a string.\n",
36
- " 3. Ensure one-to-one correspondence—each input item must correspond to exactly one output item with the same number of items.\n",
37
- " 4. Preserve spaces before or after strings. Do not remove, merge, split, or omit any strings.\n",
38
- " 5. Translate paragraphs and ensure the translation makes sense when text is put together.\n",
39
- " 6. Translate split words so that the word is not split in the translation.\n",
40
- " 7. Return a JSON object that is a Python dictionary containing as many items as the original JSON file, with keys and order preserved.\n",
41
- " 8. The output must be a syntactically correct Python dictionary.\n",
42
- "\n",
43
- " Additional Examples:\n",
44
- " **Input 1**: \n",
45
- " - Source language: English\n",
46
- " - Target language: Vietnamese\n",
47
- " - JSON file: \n",
48
- " ```json\n",
49
- " {\"0\": \"My name is \", \"1\": \"Huy\", \"2\": \".\", \"3\": \" Today is \", \"4\": \"a \", \"5\": \"good day\", \"6\": \".\", \"7\": \"\"}\n",
50
- " ```\n",
51
- " **Output 1**:\n",
52
- " ```json\n",
53
- " {\"0\": \"Tên tôi là \", \"1\": \"Huy\", \"2\": \".\", \"3\": \" Hôm nay là \", \"4\": \"một \", \"5\": \"ngày đẹp\", \"6\": \".\", \"7\": \"\"}\n",
54
- " ```\n",
55
- "\n",
56
- " **Input 2**: \n",
57
- " - Source language: English\n",
58
- " - Target language: Spanish\n",
59
- " - JSON file: \n",
60
- " ```json\n",
61
- " {\"0\": \"The sky is \", \"1\": \"blue\", \"2\": \".\", \"3\": \" Water is \", \"4\": \"essential\", \"5\": \" for \", \"6\": \"life\", \"7\": \".\"}\n",
62
- " ```\n",
63
- " **Output 2**:\n",
64
- " ```json\n",
65
- " {\"0\": \"El cielo es \", \"1\": \"azul\", \"2\": \".\", \"3\": \" El agua es \", \"4\": \"esencial\", \"5\": \" para \", \"6\": \"la vida\", \"7\": \".\"}\n",
66
- " ```\n",
67
- "\n",
68
- " **Input 3**: \n",
69
- " - Source language: English\n",
70
- " - Target language: French \n",
71
- " - JSON file: \n",
72
- " ```json\n",
73
- " {\"0\": \"The quick brown \", \"1\": \"fox \", \"2\": \"jumps \", \"3\": \"over \", \"4\": \"the \", \"5\": \"lazy \", \"6\": \"dog\", \"7\": \".\"}\n",
74
- " ```\n",
75
- " **Output 3**:\n",
76
- " ```json\n",
77
- " {\"0\": \"Le renard brun \", \"1\": \"rapide \", \"2\": \"saute \", \"3\": \"par-dessus \", \"4\": \"le \", \"5\": \"chien \", \"6\": \"paresseux\", \"7\": \".\"}\n",
78
- " ```\n",
79
- "\n",
80
- " Perform the translation and return the result as specified above. Do not include any additional text other than the translated JSON object.\n",
81
- " \"\"\"\n",
82
- " json_data = json.dumps({i: t for i, t in enumerate(texts)})\n",
83
- " user_prompt = f\"Source language: {source_lang}. Target language: {target_lang}. JSON file: {json_data}\" \n",
84
- " \n",
85
- " model = genai.GenerativeModel('gemini-2.0-flash')\n",
86
- " response = model.generate_content(contents = system_prompt.strip() + \"\\n\" + user_prompt.strip(), generation_config={\n",
87
- " 'temperature': 1, # Adjust temperature for desired creativity\n",
88
- " 'top_p': 1,\n",
89
- " 'top_k': 1,})\n",
90
- " # response_dict = ast.literal_eval(response.text.strip().strip(\"json```\").strip(\"```\").strip().strip(\"\\\"\"))\n",
91
- " # print(len(texts), len(list(response_dict.values())))\n",
92
- " # return list(response_dict.values())\n",
93
- "\n",
94
- " return response\n",
95
- "\n",
96
- "def response_to_dict(response):\n",
97
- " return list(ast.literal_eval(response.text.strip().strip(\"json```\").strip(\"```\").strip().strip(\"\\\"\")).values())\n",
98
- "\n",
99
- "def fix_translate(texts, translated_text):\n",
100
- " \"\"\" Translates multiple text segments in a single API call. \"\"\"\n",
101
- " if not texts:\n",
102
- " return texts # Skip if empty\n",
103
- " \n",
104
- " system_prompt = \"\"\"\n",
105
- " You are given the original JSON dictionary and the translated response text. Your task is to ensure that the translated text is in the correct format and has the same number of items as the original JSON dictionary.\n",
106
- "\n",
107
- " Steps to follow:\n",
108
- " 1. Parse the original and translated JSON dictionaries.\n",
109
- " 2. Ensure that the keys in both dictionaries are strings (i.e., \"1\" instead of 1).\n",
110
- " 3. Compare the number of items in both dictionaries.\n",
111
- " 4. If the number of items in the translated dictionary is not equal to the number of items in the original dictionary, adjust the translated dictionary by:\n",
112
- " a. Adding missing items with empty strings if there are fewer items.\n",
113
- " b. Merging or splitting items to ensure correspondence with the original items if there are more items.\n",
114
- " 5. Ensure that each item in the translated dictionary is in the correct order, with the same key as the original item.\n",
115
- " 6. Preserve any leading or trailing spaces in the original strings.\n",
116
- " 7. Ensure the output is a syntactically correct Python dictionary, with proper opening and closing braces.\n",
117
- " 8. If the translated dictionary is already correct, return it as is.\n",
118
- " 9. Return the corrected JSON dictionary in proper Python dictionary format.\n",
119
- "\n",
120
- " Example Inputs and Outputs:\n",
121
- "\n",
122
- " **Input:**\n",
123
- " - Original JSON dictionary:\n",
124
- " ```json\n",
125
- " {\"0\": \"My name is \", \"1\": \"Huy\", \"2\": \".\", \"3\": \" Today is \", \"4\": \"a \", \"5\": \"good day\", \"6\": \".\", \"7\": \"\"}\n",
126
- " ```\n",
127
- " - Translated response text with fewer items:\n",
128
- " ```json\n",
129
- " {\"0\": \"Tên tôi là \", \"1\": \"Huy\", \"2\": \".\", \"3\": \"Hôm nay \", \"4\": \"là một \", \"5\": \"ngày đẹp\", \"6\": \".\"}\n",
130
- " ```\n",
131
- "\n",
132
- " **Output:**\n",
133
- " ```json\n",
134
- " {\"0\": \"Tên tôi là \", \"1\": \"Huy\", \"2\": \".\", \"3\": \"Hôm nay \", \"4\": \"là một \", \"5\": \"ngày đẹp\", \"6\": \".\", \"7\": \"\"}\n",
135
- " ```\n",
136
- "\n",
137
- " **Input:**\n",
138
- " - Original JSON dictionary:\n",
139
- " ```json\n",
140
- " {\"0\": \"The sky is \", \"1\": \"blue\", \"2\": \".\", \"3\": \" Water is \", \"4\": \"essential\", \"5\": \" for \", \"6\": \"life\", \"7\": \".\"}\n",
141
- " ```\n",
142
- " - Translated response text with more items:\n",
143
- " ```json\n",
144
- " {\"0\": \"El cielo es \", \"1\": \"azul\", \"2\": \".\", \"3\": \" El agua es \", \"4\": \"esencial\", \"5\": \" para \", \"6\": \"la\", \"7\": \" vida\", \"8\": \".\"}\n",
145
- " ```\n",
146
- "\n",
147
- " **Output:**\n",
148
- " ```json\n",
149
- " {\"0\": \"El cielo es \", \"1\": \"azul\", \"2\": \".\", \"3\": \" El agua es \", \"4\": \"esencial\", \"5\": \" para \", \"6\": \"la vida\", \"7\": \".\"}\n",
150
- " ```\n",
151
- "\n",
152
- " **Input:**\n",
153
- " - Original JSON dictionary:\n",
154
- " ```json\n",
155
- " {\"0\": \"The quick brown \", \"1\": \"fox \", \"2\": \"jumps \", \"3\": \"over \", \"4\": \"the \", \"5\": \"lazy \", \"6\": \"dog\", \"7\": \".\"}\n",
156
- " ```\n",
157
- " - Translated response text with issues:\n",
158
- " ```json\n",
159
- " {\"0\": \"Le renard \", \"1\": \"brun \", 2: \"rapide \", 3: \"saute \", 4: \"par-dessus \", \"5\": \"le \", \"6\": \"chien \", \"7\": \"paresseux\", 8: \".\"}\n",
160
- " ```\n",
161
- "\n",
162
- " **Output:**\n",
163
- " ```json\n",
164
- " {\"0\": \"Le renard brun \", \"1\": \"rapide \", \"2\": \"saute \", \"3\": \"par-dessus \", \"4\": \"le \", \"5\": \"chien \", \"6\": \"paresseux\", \"7\": \".\"}\n",
165
- " ```\n",
166
- "\n",
167
- " **Input:**\n",
168
- " - Original JSON dictionary:\n",
169
- " ```json\n",
170
- " {\"0\": \"The quick brown \", \"1\": \"fox \", \"2\": \"jumps \", \"3\": \"over \", \"4\": \"the \", \"5\": \"lazy \", \"6\": \"dog.\"}\n",
171
- " ```\n",
172
- " - Translated response text with wrong formatting:\n",
173
- " ```json\n",
174
- " {\"0\": \"Le renard brun \", \"1\": \"rapide \", \"2\": \"saute \", \"3\": \"par-dessus \", \"4\": \"le \", \"5\": \"chien \", \"6\": \"paresseux\".}\n",
175
- " ```\n",
176
- "\n",
177
- " **Output:**\n",
178
- " ```json\n",
179
- " {\"0\": \"Le renard brun \", \"1\": \"rapide \", \"2\": \"saute \", \"3\": \"par-dessus \", \"4\": \"le \", \"5\": \"chien \", \"6\": \"paresseux.\"}\n",
180
- " ```\n",
181
- "\n",
182
- " Perform the corrections and return the result as a properly formatted Python dictionary.\n",
183
- "\"\"\"\n",
184
- " json_data = json.dumps({i: t for i, t in enumerate(texts)})\n",
185
- " user_prompt = f\"Original JSON dictionary: {json_data}. Translated response text: {translated_text}\" \n",
186
- " \n",
187
- " model = genai.GenerativeModel('gemini-2.0-flash')\n",
188
- " response = model.generate_content(contents = system_prompt.strip() + \"\\n\" + user_prompt.strip(), generation_config={\n",
189
- " 'temperature': 1, # Adjust temperature for desired creativity\n",
190
- " 'top_p': 1,\n",
191
- " 'top_k': 1,})\n",
192
- " return response_to_dict(response)\n",
193
- " # return response \n",
194
- "\n",
195
- "def brute_force_fix(batch, translated_batch):\n",
196
- " if len(batch) > len(translated_batch):\n",
197
- " translated_batch += [\"\"] * (len(batch) - len(translated_batch))\n",
198
- " elif len(batch) < len(translated_batch):\n",
199
- " translated_batch = translated_batch[:len(batch)]\n",
200
- " return translated_batch\n",
201
- "\n",
202
- "def batch_translate_loop(batch, source_lang, target_lang):\n",
203
- " translated_batch_response = batch_translate(batch, source_lang, target_lang)\n",
204
- " try:\n",
205
- " translated_batch = response_to_dict(translated_batch_response)\n",
206
- " assert(len(translated_batch) == len(batch))\n",
207
- "\n",
208
- " except:\n",
209
- " for i in range(10):\n",
210
- " print(f'I am ChatGPT and I am retarded, retrying translation time {i}:')\n",
211
- " try: \n",
212
- " translated_batch = fix_translate(batch, translated_batch_response.text.strip().strip(\"json```\").strip(\"```\").strip().strip(\"\\\"\"))\n",
213
- " assert(len(translated_batch) == len(batch))\n",
214
- " break\n",
215
- " except:\n",
216
- " pass\n",
217
- " try: \n",
218
- " translated_batch = fix_translate(batch, translated_batch_response.text.strip().strip(\"json```\").strip(\"```\").strip().strip(\"\\\"\"))\n",
219
- " except:\n",
220
- " try:\n",
221
- " translated_batch = response_to_dict(translated_batch_response)\n",
222
- " except:\n",
223
- " raise ValueError(\"The translated batch is not a list.\")\n",
224
- " if len(translated_batch) != len(batch):\n",
225
- " print(\"Length mismatch after translation. Brute Force Fixing...\")\n",
226
- " translated_batch = brute_force_fix(batch, translated_batch)\n",
227
- " global mismatches\n",
228
- " mismatches += 1\n",
229
- " print(len(batch), len(translated_batch))\n",
230
- " return translated_batch\n",
231
- "\n",
232
- "def full_translate(texts, source_lang = 'English', target_lang=\"Vietnamese\"):\n",
233
- " full_translated_texts = []\n",
234
- " batch = []\n",
235
- " word_count = 0\n",
236
- " global time_spent_sleeping\n",
237
- "\n",
238
- " for string in texts:\n",
239
- " if len(string.split()) + word_count >= 2000:\n",
240
- " print('Translating a batch.')\n",
241
- "\n",
242
- " translated_batch = batch_translate_loop(batch, source_lang, target_lang)\n",
243
- " full_translated_texts += translated_batch\n",
244
- " \n",
245
- " time.sleep(1)\n",
246
- " time_spent_sleeping += 1\n",
247
- " batch = []\n",
248
- " word_count = 0\n",
249
- " batch.append(string)\n",
250
- " word_count += len(string)\n",
251
- " \n",
252
- " print('Translating a batch.')\n",
253
- " if len(batch) == 0:\n",
254
- " return full_translated_texts\n",
255
- " \n",
256
- " translated_batch = batch_translate_loop(batch, source_lang, target_lang)\n",
257
- " full_translated_texts += translated_batch\n",
258
- " \n",
259
- " return full_translated_texts\n",
260
- "\n",
261
- "def merge_runs(runs):\n",
262
- " \"\"\" Merges adjacent runs with the same style. \"\"\"\n",
263
- " merged_runs = []\n",
264
- " for run in runs:\n",
265
- " if (merged_runs and isinstance(run, docx.text.run.Run) and isinstance(merged_runs[-1], docx.text.run.Run) and \n",
266
- " run.style == merged_runs[-1].style and \n",
267
- " merged_runs[-1].bold == run.bold and\n",
268
- " merged_runs[-1].italic == run.italic and\n",
269
- " merged_runs[-1].underline == run.underline and \n",
270
- " merged_runs[-1].font.size == run.font.size and\n",
271
- " merged_runs[-1].font.color.rgb == run.font.color.rgb and\n",
272
- " merged_runs[-1].font.name == run.font.name):\n",
273
- " merged_runs[-1].text += run.text\n",
274
- " else:\n",
275
- " merged_runs.append(run)\n",
276
- " return merged_runs\n",
277
- "\n",
278
- "NS_W = \"{http://schemas.openxmlformats.org/wordprocessingml/2006/main}\"\n",
279
- "def translate_header_footer(doc, source_lang, target_lang):\n",
280
- " head_foot = []\n",
281
- " for section in doc.sections:\n",
282
- " for header in section.header.paragraphs:\n",
283
- " for run in header.runs:\n",
284
- " head_foot.append(run.text) \n",
285
- " for footer in section.footer.paragraphs:\n",
286
- " for run in footer.runs:\n",
287
- " head_foot.append(run.text) \n",
288
- " translated_head_foot = full_translate(head_foot, source_lang, target_lang)\n",
289
- "\n",
290
- " i = 0\n",
291
- " for section in doc.sections:\n",
292
- " for header in section.header.paragraphs:\n",
293
- " for run in header.runs:\n",
294
- " run.text = translated_head_foot[i]\n",
295
- " i += 1\n",
296
- " for footer in section.footer.paragraphs:\n",
297
- " for run in footer.runs:\n",
298
- " run.text = translated_head_foot[i]\n",
299
- " i += 1 \n",
300
- "\n",
301
- "def get_text_elements_para(doc):\n",
302
- " para_texts = []\n",
303
- " for para in doc.paragraphs:\n",
304
- " for element in para._element.iter():\n",
305
- " if element.tag.endswith('t'):\n",
306
- " if element.text:\n",
307
- " emoji_pattern = r'[\\U00010000-\\U0010FFFF]' \n",
308
- " # Split the text but keep emojis as separate elements\n",
309
- " parts = re.split(f'({emoji_pattern})', element.text)\n",
310
- " for part in parts:\n",
311
- " if re.match(emoji_pattern, part):\n",
312
- " continue\n",
313
- " if len(part.strip()) != 0:\n",
314
- " para_texts.append(part)\n",
315
- "\n",
316
- " return para_texts\n",
317
- "\n",
318
- "def get_text_elements_table(doc):\n",
319
- " table_texts = []\n",
320
- " for table in doc.tables:\n",
321
- " for row in table.rows:\n",
322
- " for cell in row.cells:\n",
323
- " table_texts += get_text_elements_para(cell)\n",
324
- " return table_texts\n",
325
- "\n",
326
- "def translate_paragraphs(doc, translated_texts, i = 0):\n",
327
- " for para in doc.paragraphs:\n",
328
- " for element in para._element.iter():\n",
329
- " if element.tag.endswith('t'):\n",
330
- " if element.text:\n",
331
- " emoji_pattern = r'[\\U00010000-\\U0010FFFF]' \n",
332
- " # Split the text but keep emojis as separate elements\n",
333
- " parts = re.split(f'({emoji_pattern})', element.text)\n",
334
- " for j in range(len(parts)):\n",
335
- " if re.match(emoji_pattern, parts[j]):\n",
336
- " continue\n",
337
- " if len(parts[j].strip()) != 0: \n",
338
- " translated_text = translated_texts[i]\n",
339
- " i += 1\n",
340
- " parts[j] = translated_text\n",
341
- " element.text = \"\".join(parts) \n",
342
- " return doc, i\n",
343
- "\n",
344
- "def translate_tables(doc, translated_texts):\n",
345
- " i = 0\n",
346
- " for table in doc.tables:\n",
347
- " for row in table.rows:\n",
348
- " for cell in row.cells:\n",
349
- " cell, i = translate_paragraphs(cell, translated_texts, i)\n",
350
- " return doc\n",
351
- "\n",
352
- "def is_same_formatting(text1, text2):\n",
353
- " \"\"\"\n",
354
- " Check if two texts have the same formatting.\n",
355
- " \"\"\"\n",
356
- " return (text1.bold == text2.bold \\\n",
357
- " and text1.italic == text2.italic \\\n",
358
- " and text1.underline == text2.underline \\\n",
359
- " and text1.font.size == text2.font.size \\\n",
360
- " and text1.font.color.rgb == text2.font.color.rgb \\\n",
361
- " and text1.font.name == text2.font.name)\n",
362
- " \n",
363
- "def merge_elements(doc):\n",
364
- " for para in doc.paragraphs:\n",
365
- " current_run = []\n",
366
- " for element in para.iter_inner_content():\n",
367
- " if isinstance(element, docx.text.run.Run):\n",
368
- " if current_run == []:\n",
369
- " current_run = [element]\n",
370
- " elif is_same_formatting(current_run[0], element):\n",
371
- " current_run[0].text += element.text\n",
372
- " element.text = \"\"\n",
373
- " else:\n",
374
- " current_run = [element]\n",
375
- " return doc\n",
376
- "\n",
377
- "def translate_docx(input_file, source_lang = \"English\", target_lang=\"Vietnamese\", output_num = ''):\n",
378
- " \"\"\" Translates a Word document efficiently using batch processing. \"\"\"\n",
379
- " doc = Document(input_file)\n",
380
- " output_file = os.path.join(os.path.dirname(input_file), f\"{output_num}{target_language}_translated_{os.path.basename(input_file)}\")\n",
381
- "\n",
382
- " doc = merge_elements(doc)\n",
383
- " \n",
384
- " print('Translating paragraphs.')\n",
385
- " para_texts = get_text_elements_para(doc)\n",
386
- " translated_para = full_translate(para_texts, source_lang = source_lang, target_lang = target_lang)\n",
387
- " print('Done translating pararaphs.')\n",
388
- "\n",
389
- " print('Translating tables.')\n",
390
- " table_texts = get_text_elements_table(doc)\n",
391
- " translated_tables = full_translate(table_texts, source_lang = source_lang, target_lang = target_lang)\n",
392
- " print('Done translating tables.')\n",
393
- "\n",
394
- " print('Inserting paragaphs')\n",
395
- " doc, _ = translate_paragraphs(doc, translated_para)\n",
396
- " print('Inserting tables.')\n",
397
- " doc = translate_tables(doc, translated_tables)\n",
398
- "\n",
399
- " translate_header_footer(doc, source_lang, target_lang)\n",
400
- " print('Done translating headers & footers.')\n",
401
- "\n",
402
- " doc.save(output_file)\n",
403
- " print(f\"Translation complete! Saved as {output_file}\")\n",
404
- "\n",
405
- " # return para_texts, translated_para\n",
406
- "\n",
407
- "\n",
408
- "# input_file = r\"C:\\Users\\huyvu\\Downloads\\wordnet-an-electronic-lexical-database-language-speech-and-communication.9780262061971.33119-1.docx\"\n",
409
- "input_file = r\"D:\\Show_me_everything\\Machine Translation\\input\\test1.docx\"\n",
410
- "# input_file = r\"C:\\Users\\huyvu\\Documents\\Machine Translation\\Machine-Translation\\data\\input\\Data Engineering Practice.docx\""
411
- ]
412
- },
413
- {
414
- "cell_type": "code",
415
- "execution_count": 11,
416
- "metadata": {},
417
- "outputs": [],
418
- "source": [
419
- "input_file = r\"D:\\Show_me_everything\\Machine Translation\\input\\Tổng quan cuộc thi_ Data Unlock.docx\""
420
- ]
421
- },
422
- {
423
- "cell_type": "code",
424
- "execution_count": 15,
425
- "metadata": {},
426
- "outputs": [
427
- {
428
- "name": "stdout",
429
- "output_type": "stream",
430
- "text": [
431
- "Translating paragraphs.\n",
432
- "Translating a batch.\n",
433
- "37 37\n",
434
- "Translating a batch.\n",
435
- "27 27\n",
436
- "Translating a batch.\n",
437
- "28 28\n",
438
- "Translating a batch.\n",
439
- "20 20\n",
440
- "Translating a batch.\n",
441
- "16 16\n",
442
- "Translating a batch.\n",
443
- "23 23\n",
444
- "Translating a batch.\n",
445
- "37 37\n",
446
- "Translating a batch.\n",
447
- "32 32\n",
448
- "Translating a batch.\n",
449
- "28 28\n",
450
- "Translating a batch.\n",
451
- "13 13\n",
452
- "Translating a batch.\n",
453
- "36 36\n",
454
- "Translating a batch.\n",
455
- "23 23\n",
456
- "Translating a batch.\n",
457
- "25 25\n",
458
- "Translating a batch.\n",
459
- "10 10\n",
460
- "Translating a batch.\n",
461
- "14 14\n",
462
- "Translating a batch.\n",
463
- "13 13\n",
464
- "Translating a batch.\n",
465
- "11 11\n",
466
- "Translating a batch.\n",
467
- "18 18\n",
468
- "Translating a batch.\n",
469
- "14 14\n",
470
- "Translating a batch.\n",
471
- "23 23\n",
472
- "Translating a batch.\n",
473
- "24 24\n",
474
- "Translating a batch.\n",
475
- "21 21\n",
476
- "Translating a batch.\n",
477
- "10 10\n",
478
- "Translating a batch.\n",
479
- "23 23\n",
480
- "Translating a batch.\n",
481
- "12 12\n",
482
- "Translating a batch.\n",
483
- "18 18\n",
484
- "Translating a batch.\n",
485
- "17 17\n",
486
- "Translating a batch.\n",
487
- "29 29\n",
488
- "Translating a batch.\n",
489
- "15 15\n",
490
- "Translating a batch.\n",
491
- "21 21\n",
492
- "Translating a batch.\n",
493
- "2 2\n",
494
- "Done translating pararaphs.\n",
495
- "Translating tables.\n",
496
- "Translating a batch.\n",
497
- "21 21\n",
498
- "Done translating tables.\n",
499
- "Inserting paragaphs\n",
500
- "Inserting tables.\n",
501
- "Translating a batch.\n",
502
- "Done translating headers & footers.\n",
503
- "Translation complete! Saved as D:\\Show_me_everything\\Machine Translation\\input\\English_translated_test1.docx\n"
504
- ]
505
- }
506
- ],
507
- "source": [
508
- "translate_docx(input_file, source_lang = source_language, target_lang = target_language)"
509
- ]
510
- },
511
- {
512
- "cell_type": "code",
513
- "execution_count": 16,
514
- "metadata": {},
515
- "outputs": [
516
- {
517
- "data": {
518
- "text/plain": [
519
- "30"
520
- ]
521
- },
522
- "execution_count": 16,
523
- "metadata": {},
524
- "output_type": "execute_result"
525
- }
526
- ],
527
- "source": [
528
- "time_spent_sleeping"
529
- ]
530
- },
531
- {
532
- "cell_type": "code",
533
- "execution_count": 5,
534
- "metadata": {},
535
- "outputs": [
536
- {
537
- "data": {
538
- "text/plain": [
539
- "0"
540
- ]
541
- },
542
- "execution_count": 5,
543
- "metadata": {},
544
- "output_type": "execute_result"
545
- }
546
- ],
547
- "source": [
548
- "mismatches"
549
- ]
550
- },
551
- {
552
- "cell_type": "code",
553
- "execution_count": null,
554
- "metadata": {},
555
- "outputs": [],
556
- "source": []
557
- }
558
- ],
559
- "metadata": {
560
- "kernelspec": {
561
- "display_name": "machine_translate",
562
- "language": "python",
563
- "name": "python3"
564
- },
565
- "language_info": {
566
- "codemirror_mode": {
567
- "name": "ipython",
568
- "version": 3
569
- },
570
- "file_extension": ".py",
571
- "mimetype": "text/x-python",
572
- "name": "python",
573
- "nbconvert_exporter": "python",
574
- "pygments_lexer": "ipython3",
575
- "version": "3.10.16"
576
- }
577
- },
578
- "nbformat": 4,
579
- "nbformat_minor": 2
580
- }