diff --git a/app/services/document_processor.py b/app/services/document_processor.py index ddace95..92239d5 100644 --- a/app/services/document_processor.py +++ b/app/services/document_processor.py @@ -649,6 +649,43 @@ def _insert_docx_translations(doc: docx.Document, segs: List[Segment], log(f"[ERROR] 段落處理失敗: {e}, 跳過此段落") continue + elif seg.kind == "table_cell": + # 處理表格儲存格翻譯插入 + cell = seg.ref # cell 是 _Cell 對象 + + # 檢查儲存格是否已有翻譯 + existing_translations = [] + cell_paragraphs = list(cell.paragraphs) + + # 檢查儲存格末尾是否已有翻譯 + translation_start_index = len(cell_paragraphs) + for i in range(len(cell_paragraphs) - 1, -1, -1): + if _is_our_insert_block(cell_paragraphs[i]): + existing_translations.insert(0, _p_text_with_breaks(cell_paragraphs[i])) + translation_start_index = i + else: + break + + # 檢查是否所有翻譯都已存在且相同 + if len(existing_translations) >= len(translations): + if all(_normalize_text(e) == _normalize_text(t) for e, t in zip(existing_translations[:len(translations)], translations)): + skip_cnt += 1 + log(f"[SKIP] 表格儲存格已存在翻譯: {seg.text[:30]}...") + continue + + # 移除舊的翻譯段落(如果有的話) + for i in range(len(cell_paragraphs) - 1, translation_start_index - 1, -1): + if _is_our_insert_block(cell_paragraphs[i]): + cell._element.remove(cell_paragraphs[i]._element) + + # 添加新的翻譯到儲存格 + for t in translations: + new_p = cell.add_paragraph() + _add_formatted_run(new_p, t, italic=True, font_size_pt=INSERT_FONT_SIZE_PT) + + ok_cnt += 1 + log(f"[SUCCESS] 表格儲存格插入 {len(translations)} 個翻譯") + elif seg.kind == "txbx": tx = seg.ref # Check if textbox already has our translations at the end