|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import os |
| 4 | +import random |
| 5 | +import time |
| 6 | +from typing import Generator, Tuple |
| 7 | + |
| 8 | +from docx import Document |
| 9 | +from googletrans import Translator |
| 10 | + |
| 11 | +# Language codes used across the app |
| 12 | +LANG_SOURCE_CODES = ["auto", "zh-cn", "en", "fr", "es"] |
| 13 | +LANG_TARGET_CODES = ["zh-cn", "en", "fr", "es"] |
| 14 | + |
| 15 | + |
| 16 | +def load_or_initialize_state(state_file: str, num_paragraphs: int) -> dict: |
| 17 | + if os.path.exists(state_file): |
| 18 | + with open(state_file, "r", encoding="utf-8") as f: |
| 19 | + return json.load(f) |
| 20 | + return { |
| 21 | + "translated_count": 0, |
| 22 | + "paragraphs": [], |
| 23 | + "order": [], |
| 24 | + "translated_paragraphs": [None] * num_paragraphs, |
| 25 | + } |
| 26 | + |
| 27 | + |
| 28 | +def save_state(state_file: str, state: dict) -> None: |
| 29 | + with open(state_file, "w", encoding="utf-8") as f: |
| 30 | + json.dump(state, f, ensure_ascii=False, indent=4) |
| 31 | + |
| 32 | + |
| 33 | +class DocumentTranslator: |
| 34 | + """Translate a Word document paragraph by paragraph with resumable state.""" |
| 35 | + |
| 36 | + def __init__( |
| 37 | + self, |
| 38 | + input_file: str, |
| 39 | + output_file: str, |
| 40 | + state_file: str, |
| 41 | + src_lang: str = "auto", |
| 42 | + dest_lang: str = "zh-cn", |
| 43 | + ) -> None: |
| 44 | + self.input_file = input_file |
| 45 | + self.output_file = output_file |
| 46 | + self.state_file = state_file |
| 47 | + self.src_lang = src_lang |
| 48 | + self.dest_lang = dest_lang |
| 49 | + |
| 50 | + def translate(self) -> Generator[Tuple[int, dict], None, None]: |
| 51 | + """ |
| 52 | + Run the translation and yield (progress_percent, status_payload). |
| 53 | +
|
| 54 | + Progress updates can be consumed by a GUI thread without blocking the UI. |
| 55 | + """ |
| 56 | + doc = Document(self.input_file) |
| 57 | + paragraphs = [(i, para.text) for i, para in enumerate(doc.paragraphs)] |
| 58 | + |
| 59 | + state = load_or_initialize_state(self.state_file, len(paragraphs)) |
| 60 | + |
| 61 | + if not state["paragraphs"]: |
| 62 | + state["paragraphs"] = paragraphs |
| 63 | + state["order"] = list(range(len(paragraphs))) |
| 64 | + random.shuffle(state["order"]) |
| 65 | + save_state(self.state_file, state) |
| 66 | + |
| 67 | + translator = Translator() |
| 68 | + loop = asyncio.new_event_loop() |
| 69 | + asyncio.set_event_loop(loop) |
| 70 | + |
| 71 | + try: |
| 72 | + total = len(state["order"]) |
| 73 | + for i in range(state["translated_count"], total): |
| 74 | + original_index = state["order"][i] |
| 75 | + index, text = state["paragraphs"][original_index] |
| 76 | + |
| 77 | + if not text.strip(): |
| 78 | + state["translated_paragraphs"][index] = text |
| 79 | + status = { |
| 80 | + "event": "skip_empty", |
| 81 | + "index": i + 1, |
| 82 | + "total": total, |
| 83 | + } |
| 84 | + else: |
| 85 | + result = translator.translate( |
| 86 | + text, src=self.src_lang, dest=self.dest_lang |
| 87 | + ) |
| 88 | + # googletrans 3.4.0+ returns a coroutine; handle both sync/async |
| 89 | + if asyncio.iscoroutine(result): |
| 90 | + result = loop.run_until_complete(result) |
| 91 | + translated_text = result.text |
| 92 | + state["translated_paragraphs"][index] = translated_text |
| 93 | + status = { |
| 94 | + "event": "translated", |
| 95 | + "index": i + 1, |
| 96 | + "total": total, |
| 97 | + "src": self.src_lang, |
| 98 | + "dest": self.dest_lang, |
| 99 | + } |
| 100 | + time.sleep(random.uniform(3, 5)) |
| 101 | + |
| 102 | + state["translated_count"] = i + 1 |
| 103 | + save_state(self.state_file, state) |
| 104 | + progress = int(((i + 1) / total) * 100) |
| 105 | + yield progress, status |
| 106 | + |
| 107 | + translated_doc = Document() |
| 108 | + for para in state["translated_paragraphs"]: |
| 109 | + if para: |
| 110 | + translated_doc.add_paragraph(para) |
| 111 | + |
| 112 | + translated_doc.save(self.output_file) |
| 113 | + yield 100, { |
| 114 | + "event": "completed", |
| 115 | + "output": self.output_file, |
| 116 | + "src": self.src_lang, |
| 117 | + "dest": self.dest_lang, |
| 118 | + } |
| 119 | + finally: |
| 120 | + # clean up async client |
| 121 | + try: |
| 122 | + loop.run_until_complete(translator.client.aclose()) |
| 123 | + except Exception: |
| 124 | + pass |
| 125 | + loop.close() |
| 126 | + |
| 127 | + # clean state only when translation completes |
| 128 | + if ( |
| 129 | + os.path.exists(self.state_file) |
| 130 | + and state.get("translated_count") == len(state.get("order", [])) |
| 131 | + ): |
| 132 | + try: |
| 133 | + os.remove(self.state_file) |
| 134 | + except OSError: |
| 135 | + pass |
0 commit comments