feat: 在线翻译支持文档翻译 — 导入Word/PDF/TXT/MD/HTML/EPUB整篇AI翻译, calibre提取文本+分块LLM翻译保留段落格式, 独立目标语言选择, 译文可下载TXT/DOCX(calibre转换), ≤20MB/6万字符

This commit is contained in:
personal82555 committed 2026-10-12 23:54:27 +08:00
1 parent 6d1f0f80cb
commit 5797fed492
2 files changed
+501 -2

No files matched your search

+131
View File
@@ -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
+370 -2
View File
@@ -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<HTMLInputElement>();
const docFile = ref<File | null>(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<HTMLElement>();
const rootStyle = ref<Record<string, string>>({});
@@ -185,7 +275,63 @@ onUnmounted(() => {
</c-button>
</div>
<div class="body">
<div class="mode-row">
<button class="mode-chip" :class="{ on: mode === 'text' }" @click="mode = 'text'">
💬 文本翻译
</button>
<button class="mode-chip" :class="{ on: mode === 'doc' }" @click="mode = 'doc'">
📄 文档翻译
<span class="mode-new">新</span>
</button>
<span class="mode-hint">{{ mode === 'doc' ? '上传 Word / PDF / TXT 等文档,AI 整篇翻译并保留段落格式,可下载译文' : '输入文本自动翻译' }}</span>
</div>
<!-- 文档翻译面板 -->
<div v-if="mode === 'doc'" class="doc-panel">
<input ref="docInput" type="file" hidden accept=".txt,.md,.docx,.doc,.pdf,.html,.htm,.epub,.rtf,.odt" @change="onDocInput">
<div class="doc-top">
<div class="doc-drop" @click="pickDoc">
<template v-if="!docFile">
📁 点击选择文档<br><span>Word / PDF / TXT / MD / HTML / EPUB · ≤20MB</span>
</template>
<template v-else>
📄 {{ docFile.name }} <span class="doc-size">({{ (docFile.size / 1024 / 1024).toFixed(1) }} MB)</span>
<a href="javascript:;" class="doc-clear" @click.stop="docFile = null; docResult = ''">✕</a>
</template>
</div>
<div class="doc-side">
<div class="doc-lang">
译为:
<select v-model="docTo" class="doc-lang-sel">
<option v-for="l in docLangOptions" :key="l.value" :value="l.value">{{ l.label }}</option>
</select>
</div>
<button class="doc-go" :disabled="docLoading || !docFile" @click="translateDoc()">
{{ docLoading ? '⏳ AI 整篇翻译中…(长文档请耐心等待)' : '🚀 翻译文档' }}
</button>
</div>
</div>
<div v-if="docError" class="doc-error">⚠️ {{ docError }}</div>
<template v-if="docResult">
<div class="doc-bar">
<span class="doc-info">✓ {{ docInfo }}</span>
<span class="doc-acts">
<button class="doc-mini" @click="downloadDocTxt">⬇ 下载 TXT</button>
<button class="doc-mini" :disabled="docxDone" @click="downloadDocDocx">⬇ 下载 DOCX</button>
<button class="doc-mini" @click="navigator.clipboard.writeText(docResult)">📋 复制译文</button>
</span>
</div>
<div class="doc-out">
<pre class="doc-text">{{ docResult }}</pre>
</div>
</template>
<div v-else-if="!docLoading" class="doc-empty">
支持整篇文档翻译:AI 分块处理并保留原段落结构,翻译完成后可下载 TXT 或 Word(DOCX)译文。
</div>
<n-spin :show="docLoading" class="doc-spin" />
</div>
<div v-else class="body">
<div class="pane">
<div class="lang-row">
<c-select v-model:value="from" :options="langs.map(l => ({ ...l }))" w-140px />
@@ -236,6 +382,228 @@ onUnmounted(() => {
</template>
<style lang="less" scoped>
.mode-row {
display: flex;
align-items: center;
gap: 8px;
padding-bottom: 12px;
flex-shrink: 0;
}
.mode-chip {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 999px;
padding: 7px 16px;
font-size: 13px;
cursor: pointer;
transition: all 0.14s;
display: flex;
align-items: center;
gap: 6px;
&.on {
background: #18a058;
border-color: #18a058;
color: #fff;
font-weight: 700;
}
.mode-new {
font-size: 10px;
background: #e60012;
color: #fff;
border-radius: 4px;
padding: 0 5px;
}
}
.mode-hint {
font-size: 12px;
opacity: 0.55;
}
.doc-panel {
position: relative;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.doc-top {
display: flex;
gap: 14px;
align-items: stretch;
margin-bottom: 12px;
flex-shrink: 0;
.doc-side {
width: 300px;
flex-shrink: 0;
display: flex;
flex-direction: column;
gap: 9px;
.doc-lang {
font-size: 12.5px;
opacity: 0.85;
background: rgba(128, 128, 128, 0.06);
border-radius: 8px;
padding: 8px 12px;
display: flex;
align-items: center;
gap: 8px;
}
.doc-lang-sel {
flex: 1;
border: 1px solid rgba(128, 128, 128, 0.35);
border-radius: 7px;
padding: 5px 8px;
font-size: 12.5px;
background: #fff;
outline: none;
&:focus {
border-color: #18a058;
}
}
.doc-go {
border: none;
background: #18a058;
color: #fff;
border-radius: 9px;
padding: 11px;
font-size: 13.5px;
font-weight: 700;
cursor: pointer;
flex: 1;
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&:hover:not(:disabled) {
background: #15924e;
}
}
}
}
.doc-drop {
flex: 1;
border: 1.5px dashed rgba(128, 128, 128, 0.45);
border-radius: 10px;
padding: 22px 14px;
text-align: center;
cursor: pointer;
font-size: 14px;
font-weight: 600;
line-height: 1.8;
transition: border-color 0.15s;
word-break: break-all;
&:hover {
border-color: #18a058;
}
span {
font-size: 11.5px;
font-weight: 400;
opacity: 0.5;
}
.doc-size {
opacity: 0.55;
font-weight: 400;
}
.doc-clear {
color: #d03050;
margin-left: 8px;
text-decoration: none;
}
}
.doc-error {
color: #d03050;
font-size: 12.5px;
margin-bottom: 10px;
}
.doc-bar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
margin-bottom: 8px;
flex-wrap: wrap;
.doc-info {
font-size: 12.5px;
color: #18a058;
font-weight: 700;
}
.doc-acts {
display: flex;
gap: 7px;
}
.doc-mini {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 7px;
padding: 5px 12px;
font-size: 12px;
cursor: pointer;
&:hover:not(:disabled) {
border-color: #18a058;
color: #18a058;
}
&:disabled {
opacity: 0.5;
cursor: default;
}
}
}
.doc-out {
flex: 1;
min-height: 260px;
max-height: 55vh;
overflow-y: auto;
background: rgba(128, 128, 128, 0.05);
border: 1px solid rgba(128, 128, 128, 0.15);
border-radius: 10px;
padding: 14px 16px;
}
.doc-text {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-family: inherit;
font-size: 13.5px;
line-height: 1.85;
}
.doc-empty {
font-size: 12.5px;
opacity: 0.5;
line-height: 1.8;
padding: 20px 4px;
}
.doc-spin {
position: absolute;
inset: 0;
}
.tr-root {
display: flex;
flex-direction: column;