diff --git a/docker/it-tools-relay/server.py b/docker/it-tools-relay/server.py index b73636e..2fe1666 100644 --- a/docker/it-tools-relay/server.py +++ b/docker/it-tools-relay/server.py @@ -1575,6 +1575,131 @@ class Handler(BaseHTTPRequestHandler): except Exception as e: # noqa: BLE001 self._reply(502, json.dumps({"code": 502, "message": f"AI 服务异常: {e}"}, ensure_ascii=False).encode(), "application/json") + # ---------- 文档翻译 ---------- + def _handle_translate_doc(self): + machine = self.headers.get("X-Machine-Id", "") + if check(machine, "translator") != 200: + self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + try: + ctype = self.headers.get("Content-Type", "") + length = int(self.headers.get("Content-Length") or 0) + if length > 20 * 1024 * 1024: + self._reply(413, json.dumps({"code": 413, "message": "文档超过 20MB 限制"}, ensure_ascii=False).encode(), "application/json") + return + raw = self.rfile.read(length) if length else b"" + if not raw: + self._reply(400, json.dumps({"code": 400, "message": "未收到文件"}, ensure_ascii=False).encode(), "application/json") + return + if "multipart" not in ctype: + self._reply(400, json.dumps({"code": 400, "message": "请用表单上传文件"}, ensure_ascii=False).encode(), "application/json") + return + env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)} + fs = cgi.FieldStorage(fp=io.BytesIO(raw), environ=env, keep_blank_values=True) + fitem = fs["file"] if "file" in fs.keys() else None + if fitem is None or not fitem.filename: + self._reply(400, json.dumps({"code": 400, "message": "缺少文件"}, ensure_ascii=False).encode(), "application/json") + return + to_lang = (fs["to"].value if "to" in fs.keys() else "") or "Chinese" + fname = os.path.basename(fitem.filename or "doc") + ext = os.path.splitext(fname)[1].lower() + allowed = {".txt", ".md", ".docx", ".doc", ".pdf", ".html", ".htm", ".epub", ".rtf", ".odt"} + if ext not in allowed: + self._reply(400, json.dumps({"code": 400, "message": f"不支持的格式 {ext}(支持 txt/md/docx/pdf/html/epub/rtf/odt)"}, ensure_ascii=False).encode(), "application/json") + return + wd = "/tmp/tdoc-" + uuid.uuid4().hex[:12] + os.makedirs(wd, exist_ok=True) + src = os.path.join(wd, "in" + ext) + with open(src, "wb") as f: + f.write(fitem.file.read()) + # 提取纯文本 + if ext in (".txt", ".md"): + rawb = open(src, "rb").read() + text = None + for enc in ("utf-8", "gb18030", "utf-16", "latin-1"): + try: + text = rawb.decode(enc) + break + except Exception: # noqa: BLE001 + continue + text = text or "" + else: + outtxt = os.path.join(wd, "out.txt") + r = subprocess.run(["ebook-convert", src, outtxt], capture_output=True, timeout=180) + if r.returncode != 0 or not os.path.exists(outtxt): + shutil.rmtree(wd, ignore_errors=True) + self._reply(400, json.dumps({"code": 400, "message": "文档解析失败,请确认文件未加密/损坏"}, ensure_ascii=False).encode(), "application/json") + return + text = open(outtxt, "r", encoding="utf-8", errors="ignore").read() + text = re.sub(r"\n{4,}", "\n\n\n", text or "").strip() + if not text: + shutil.rmtree(wd, ignore_errors=True) + self._reply(400, json.dumps({"code": 400, "message": "未从文档中提取到文字"}, ensure_ascii=False).encode(), "application/json") + return + if len(text) > 60000: + shutil.rmtree(wd, ignore_errors=True) + self._reply(413, json.dumps({"code": 413, "message": "文档过长(≤6万字符)"}, ensure_ascii=False).encode(), "application/json") + return + # 分块翻译(按段落聚合,每块约 1400 字) + paras = text.split("\n") + chunks = [] + cur = "" + for para in paras: + if len(cur) + len(para) + 1 > 1400 and cur: + chunks.append(cur) + cur = para + else: + cur = cur + "\n" + para if cur else para + if cur: + chunks.append(cur) + translated = [] + for i, ch in enumerate(chunks): + out = self._llm_chat([ + {"role": "system", "content": f"你是专业文档翻译。把用户提供的文档片段翻译成{to_lang}:保留原有换行、段落结构、编号和列表格式;专有名词、数字、日期原样保留;只输出译文,不要解释。"}, + {"role": "user", "content": ch}, + ]) + translated.append(out.strip()) + result_text = "\n\n".join(translated) + shutil.rmtree(wd, ignore_errors=True) + log_usage(machine, "translator") + self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"text": result_text, "chars": len(text), "blocks": len(chunks)}}, ensure_ascii=False).encode("utf-8"), "application/json") + except Exception as e: # noqa: BLE001 + self._reply(500, json.dumps({"code": 500, "message": f"文档翻译失败: {e}"}, ensure_ascii=False).encode(), "application/json") + + def _handle_txt_to_docx(self): + payload = self._read_payload() + machine = str(payload.get("machine") or "") + if check(machine, "translator") != 200: + self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") + return + text = str(payload.get("text") or "") + if not text.strip() or len(text) > 400000: + self._reply(400, json.dumps({"code": 400, "message": "文本内容无效"}, ensure_ascii=False).encode(), "application/json") + return + try: + wd = "/tmp/tdocx-" + uuid.uuid4().hex[:12] + os.makedirs(wd, exist_ok=True) + src = os.path.join(wd, "doc.txt") + dst = os.path.join(wd, "doc.docx") + with open(src, "w", encoding="utf-8") as f: + f.write(text) + r = subprocess.run(["ebook-convert", src, dst], capture_output=True, timeout=120) + if r.returncode != 0 or not os.path.exists(dst): + shutil.rmtree(wd, ignore_errors=True) + self._reply(500, json.dumps({"code": 500, "message": "DOCX 转换失败"}, ensure_ascii=False).encode(), "application/json") + return + with open(dst, "rb") as f: + out = f.read() + shutil.rmtree(wd, ignore_errors=True) + self.send_response(200) + self.send_header("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document") + self.send_header("Content-Disposition", "attachment; filename*=UTF-8''%E8%AF%91%E6%96%87.docx") + self.send_header("Content-Length", str(len(out))) + self.end_headers() + self.wfile.write(out) + except Exception as e: # noqa: BLE001 + self._reply(500, json.dumps({"code": 500, "message": f"转换失败: {e}"}, ensure_ascii=False).encode(), "application/json") + # ---------- 截图理解 ---------- def _handle_vision(self): payload = self._read_payload() @@ -1977,6 +2102,12 @@ class Handler(BaseHTTPRequestHandler): if parsed.path == "/ai/copy": self._handle_copy() return + if parsed.path == "/translate-doc": + self._handle_translate_doc() + return + if parsed.path == "/txt-to-docx": + self._handle_txt_to_docx() + return if parsed.path == "/ai/vision": self._handle_vision() return diff --git a/src/tools/translator/translator.vue b/src/tools/translator/translator.vue index bf52708..7e8cd65 100644 --- a/src/tools/translator/translator.vue +++ b/src/tools/translator/translator.vue @@ -27,7 +27,7 @@ const langs: Lang[] = [ { label: '印尼语', value: 'id' }, ]; -import { licenseHeaders } from '../license/license'; +import { getMachineId, licenseHeaders } from '../license/license'; const source = ref('Hello! This is a handy developer tools website with barcode generation, OCR and translation.\n欢迎使用在线翻译工具,支持中英日韩等16种语言互译。'); const from = ref('auto'); @@ -136,6 +136,96 @@ watch([source, from, to], () => { }); // fit viewport: no page scroll +// ============ 文档翻译 ============ +const mode = ref<'text' | 'doc'>('text'); +const docTo = ref('zh-CN'); +const docLangOptions = langs.filter(l => l.value !== 'auto'); +const docInput = ref(); +const docFile = ref(null); +const docLoading = ref(false); +const docResult = ref(''); +const docError = ref(''); +const docInfo = ref(''); +const docxDone = ref(false); + +function pickDoc() { + docInput.value?.click(); +} + +function onDocInput(e: Event) { + const input = e.target as HTMLInputElement; + docFile.value = input.files?.[0] ?? null; + input.value = ''; + docResult.value = ''; + docError.value = ''; + docInfo.value = ''; +} + +async function translateDoc() { + if (!docFile.value || docLoading.value) { + return; + } + docLoading.value = true; + docError.value = ''; + docResult.value = ''; + docxDone.value = false; + try { + const fd = new FormData(); + fd.append('file', docFile.value); + fd.append('to', langName(docTo.value)); + const res = await fetch('/relay/translate-doc', { method: 'POST', body: fd, headers: licenseHeaders('translator') }); + const j = await res.json().catch(() => ({})); + if (!res.ok || j.code !== 200) { + throw new Error(j.message || `HTTP ${res.status}`); + } + docResult.value = j.data.text; + docInfo.value = `原文 ${j.data.chars} 字符 · 分 ${j.data.blocks} 块翻译 · 译文 ${j.data.text.length} 字`; + genHist.add({ title: `文档翻译: ${docFile.value.name}`, detail: `${j.data.chars} 字 → ${langName(docTo.value)}` }); + } + catch (e: any) { + docError.value = String(e?.message || e); + } + finally { + docLoading.value = false; + } +} + +function downloadDocTxt() { + const blob = new Blob([docResult.value], { type: 'text/plain;charset=utf-8' }); + const a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = (docFile.value?.name.replace(/\.[^.]+$/, '') || '译文') + '-译文.txt'; + a.click(); + URL.revokeObjectURL(a.href); +} + +async function downloadDocDocx() { + if (!docResult.value) { + return; + } + try { + const res = await fetch('/relay/txt-to-docx', { + method: 'POST', + headers: { ...licenseHeaders('translator'), 'Content-Type': 'application/json' }, + body: JSON.stringify({ machine: getMachineId(), text: docResult.value }), + }); + if (!res.ok) { + const j = await res.json().catch(() => ({})); + throw new Error(j.message || `HTTP ${res.status}`); + } + const blob = await res.blob(); + const a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = (docFile.value?.name.replace(/\.[^.]+$/, '') || '译文') + '-译文.docx'; + a.click(); + URL.revokeObjectURL(a.href); + docxDone.value = true; + } + catch (e: any) { + docError.value = String(e?.message || e); + } +} + const rootEl = ref(); const rootStyle = ref>({}); @@ -185,7 +275,63 @@ onUnmounted(() => { -
+
+ + + {{ mode === 'doc' ? '上传 Word / PDF / TXT 等文档,AI 整篇翻译并保留段落格式,可下载译文' : '输入文本自动翻译' }} +
+ + +
+ +
+
+ + +
+
+
+ 译为: + +
+ +
+
+
⚠️ {{ docError }}
+ +
+ 支持整篇文档翻译:AI 分块处理并保留原段落结构,翻译完成后可下载 TXT 或 Word(DOCX)译文。 +
+ +
+ +
@@ -236,6 +382,228 @@ onUnmounted(() => {