Spaces:
Sleeping
Sleeping
File size: 5,737 Bytes
8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 9e2b800 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 9e2b800 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 8b23ca3 1bf0b3b 9e2b800 1bf0b3b 8b23ca3 1bf0b3b |
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 |
import os
import shutil
from pathlib import Path
import gradio as gr
import tqdm
from pdf_translate import extract_text, pdf_preview
# 语言映射
lang_map = {
"Chinese": "zh",
"English": "en",
"French": "fr",
"German": "de",
"Japanese": "ja",
"Korean": "ko",
"Russian": "ru",
"Spanish": "es",
"Italian": "it",
}
# 页范围映射
page_map = {
"All Pages": "all",
"First Page": [0],
"First 5 Pages": list(range(5)),
}
# 服务映射
# Map service names to pdf2zh service options
service_map = {
#"Google": ("google", None, None),
#"DeepL": ("deepl", "DEEPL_AUTH_KEY", None),
#"DeepLX": ("deeplx", "DEEPLX_AUTH_KEY", None),
#"Ollama": ("ollama", None, "gemma2"),
"OpenAI": ("openai", "OPENAI_API_KEY", "gpt-4o"),
#"Azure": ("azure", "AZURE_APIKEY", None),
#"Tencent": ("tencent", "TENCENT_SECRET_KEY", None),
}
def download_with_limit(url, output_path, size_limit=None):
"""下载文件并限制大小"""
# 这里可以实现你的文件下载逻辑
raise NotImplementedError
# 核心翻译函数
def translate(
file_type,
file_input,
link_input,
service,
apikey,
model_id,
lang_from,
lang_to,
page_range,
progress=gr.Progress(),
):
progress(0, desc="Starting translation...")
output = Path("pdf2zh_files")
output.mkdir(parents=True, exist_ok=True)
if file_type == "File":
if not file_input:
raise gr.Error("No input")
file_path = shutil.copy(file_input, output)
else:
if not link_input:
raise gr.Error("No input")
file_path = download_with_limit(
link_input,
output,
5 * 1024 * 1024, # 限制为 5MB
)
filename = os.path.splitext(os.path.basename(file_path))[0]
file_en = output / f"{filename}.pdf"
file_zh = output / f"{filename}-zh.pdf"
file_dual = output / f"{filename}-dual.pdf"
selected_service = service_map[service][0]
if service_map[service][1]:
os.environ.setdefault(service_map[service][1], apikey)
selected_page = page_map[page_range]
lang_from = lang_map[lang_from]
lang_to = lang_map[lang_to]
if selected_service == "google":
lang_from = "zh-CN" if lang_from == "zh" else lang_from
lang_to = "zh-CN" if lang_to == "zh" else lang_to
print(f"Files before translation: {os.listdir(output)}")
def progress_bar(t: tqdm.tqdm):
progress(t.n / t.total, desc="Translating...")
param = {
"files": [file_en],
"pages": selected_page,
"lang_in": lang_from,
"lang_out": lang_to,
"service": f"{selected_service}:{model_id}",
"output": output,
"thread": 4,
"callback": progress_bar,
}
print(param)
extract_text(**param)
print(f"Files after translation: {os.listdir(output)}")
if not file_zh.exists() or not file_dual.exists():
raise gr.Error("No output")
try:
translated_preview = pdf_preview(str(file_zh))
except Exception:
raise gr.Error("No preview")
progress(1.0, desc="Translation complete!")
return (
str(file_zh),
translated_preview,
str(file_dual),
gr.update(visible=True),
gr.update(visible=True),
gr.update(visible=True),
)
# Gradio App 配置
with gr.Blocks(
title="PDFBestTranslate - PDF Translation with Preserved Formats",
theme=gr.themes.Default(),
) as demo:
with gr.Row():
with gr.Column(scale=1):
file_type = gr.Radio(
choices=["File", "Link"],
value="File",
label="Input Type",
)
file_input = gr.File(label="Upload PDF File")
link_input = gr.Textbox(label="Enter File URL", visible=False)
file_type.change(
lambda x: (gr.update(visible=x == "File"), gr.update(visible=x == "Link")),
file_type,
[file_input, link_input],
)
service = gr.Radio(
choices=["Google Translate", "DeepL"],
value="Google Translate",
label="Translation Service",
)
apikey = gr.Textbox(label="API Key (Optional)")
model_id = gr.Textbox(label="Model ID (Optional)", visible=False)
lang_from = gr.Dropdown(
choices=list(lang_map.keys()),
value="Auto",
label="From Language",
)
lang_to = gr.Dropdown(
choices=list(lang_map.keys()),
value="Chinese",
label="To Language",
)
page_range = gr.Radio(
choices=list(page_map.keys()),
value="All Pages",
label="Page Range",
)
translate_btn = gr.Button("Translate")
with gr.Column(scale=2):
output_file = gr.File(label="Translated PDF File", visible=False)
preview = gr.Textbox(label="Translated Preview", visible=False)
output_file_dual = gr.File(label="Dual-Language PDF File", visible=False)
translate_btn.click(
translate,
inputs=[
file_type,
file_input,
link_input,
service,
apikey,
model_id,
lang_from,
lang_to,
page_range,
],
outputs=[
output_file,
preview,
output_file_dual,
output_file,
output_file_dual,
preview,
],
)
# 启动 Gradio 应用
if __name__ == "__main__":
demo.launch()
|