Spaces:
Running
Running
import gradio as gr | |
import os | |
import shutil | |
from docx import Document | |
from pptx import Presentation | |
from deep_translator import GoogleTranslator | |
def translate_document(file, target_language, target_country, api_key): | |
log_messages = [] | |
try: | |
log_messages.append("開始翻譯過程...") | |
# 複製文件到新文件 | |
original_file_path = file.name | |
copied_file_path = "copy_" + os.path.basename(original_file_path) | |
shutil.copy(original_file_path, copied_file_path) | |
log_messages.append(f"已複製文件到 {copied_file_path}") | |
# 處理 .docx 文件 | |
if copied_file_path.endswith(".docx"): | |
doc = Document(copied_file_path) | |
# 翻譯並替換段落文本 | |
for paragraph in doc.paragraphs: | |
if paragraph.text.strip(): # 只翻譯非空段落 | |
translated_text = GoogleTranslator(source='auto', target=target_language).translate(paragraph.text) | |
paragraph.text = translated_text # 用翻譯後的文本替換原始文本 | |
# 處理表格中的文本 | |
for table in doc.tables: | |
for row in table.rows: | |
for cell in row.cells: | |
if cell.text.strip(): # 只翻譯非空單元格 | |
translated_text = GoogleTranslator(source='auto', target=target_language).translate(cell.text) | |
cell.text = translated_text # 用翻譯後的文本替換原始文本 | |
# 處理文本框和形狀中的文本 | |
for inline_shape in doc.inline_shapes: | |
if inline_shape.type == 3: # 3 表示文本框 | |
if inline_shape.text_frame and inline_shape.text_frame.text.strip(): | |
translated_text = GoogleTranslator(source='auto', target=target_language).translate(inline_shape.text_frame.text) | |
inline_shape.text_frame.text = translated_text # 替換文本框中的文本 | |
output_path = "translated_" + os.path.basename(original_file_path) | |
doc.save(output_path) | |
log_messages.append(f"已將翻譯後的文件儲存為 {output_path}.") | |
# 處理 .pptx 文件 | |
elif copied_file_path.endswith(".pptx"): | |
prs = Presentation(copied_file_path) | |
# 翻譯並替換文本 | |
for slide in prs.slides: | |
for shape in slide.shapes: | |
if hasattr(shape, "text") and shape.text.strip(): # 只翻譯非空文本框 | |
translated_text = GoogleTranslator(source='auto', target=target_language).translate(shape.text) | |
shape.text = translated_text # 用翻譯後的文本替換原始文本 | |
output_path = "translated_" + os.path.basename(original_file_path) | |
prs.save(output_path) | |
log_messages.append(f"已將翻譯後的簡報儲存為 {output_path}.") | |
return output_path, "\n".join(log_messages) # 返回文件路徑和日誌信息 | |
except Exception as e: | |
log_messages.append(f"發生錯誤: {e}") | |
return None, "\n".join(log_messages) # 返回 None 和日誌 | |
iface = gr.Interface( | |
fn=translate_document, | |
inputs=[ | |
gr.File(label="上傳文件 (.docx 或 .pptx)"), | |
gr.Dropdown(choices=["en", "es", "fr", "de", "ja", "ko"], label="目標語言"), | |
gr.Dropdown(choices=["US", "UK", "ES", "FR", "DE", "JP", "KR"], label="目標國家"), | |
gr.Textbox(label="API 金鑰(可選)", placeholder="如果需要,請輸入您的 API 金鑰") | |
], | |
outputs=[ | |
gr.File(label="下載翻譯後的文件"), | |
gr.Textbox(label="日誌輸出", lines=10) # 添加一個文本框來顯示日誌信息 | |
], | |
title="文件翻譯器", | |
description="翻譯您的文件,同時保留原始格式。", | |
) | |
iface.launch() |