feat: 在线翻译支持文档翻译 — 导入Word/PDF/TXT/MD/HTML/EPUB整篇AI翻译, calibre提取文本+分块LLM翻译保留段落格式, 独立目标语言选择, 译文可下载TXT/DOCX(calibre转换), ≤20MB/6万字符
This commit is contained in:
1 parent
6d1f0f80cb
commit
5797fed492
2 files changed
+501
-2
No files matched your search
@@ -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
|
||||
|
||||
Reference in new issue
Block a user