| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- # -*- coding: utf-8 -*-
- """服务端多语言:按 Accept-Language 翻译 API 错误文案。
- 前端 api.js 会随请求带上 Accept-Language: en / zh-CN。
- 中文为源文案,英文通过整串精确匹配翻译;未收录的原文透传。
- """
- import json
- import re
- def get_lang(request) -> str:
- try:
- header = (request.headers.get("accept-language") or "").lower()
- except Exception:
- return "zh"
- # en 优先于 zh:仅当英文权重出现在中文之前才判为 en
- first = None
- for part in header.split(","):
- tag = part.strip().split(";")[0]
- if tag and tag != "*":
- first = tag
- break
- if first and first.startswith("en"):
- return "en"
- return "zh"
- ERRORS_EN = {
- "AI 排版次数已用完,请联系管理员增加额度": "AI layout quota exhausted — contact an admin to top up",
- "AI 服务未配置(PL_AI_API_KEY)": "AI service not configured (PL_AI_API_KEY)",
- "AI 服务未配置(后台 → AI 设置)": "AI service not configured (Admin → AI Settings)",
- "AI 次数已用完,请联系管理员增加额度": "AI quota exhausted — contact an admin to top up",
- "AI 生成失败,请换个说法重试": "AI generation failed — try rephrasing",
- "Base URL 需以 http(s):// 开头": "Base URL must start with http(s)://",
- "CAD 图纸生成失败": "CAD drawing generation failed",
- "CAD 预览生成失败": "CAD preview generation failed",
- "EPS 生成失败": "EPS generation failed",
- "上一个设计任务还在进行中,稍等一下": "Previous design task is still running — hold on a moment",
- "不能禁用自己": "You cannot disable yourself",
- "会话 id 不合法": "Invalid session id",
- "反馈不存在": "Feedback not found",
- "发送太频繁,请稍后再试": "Sending too frequently — please try again later",
- "密码至少 6 位": "Password must be at least 6 characters",
- "工厂账号不存在": "Factory account not found",
- "工厂账号专用接口": "Factory-account-only endpoint",
- "已支付订单请联系客服处理": "Paid order — please contact support",
- "当前状态不可取消": "Cannot cancel in the current status",
- "支付状态不合法": "Invalid payment status",
- "无权查看该订单": "You are not allowed to view this order",
- "模型名过长": "Model name too long",
- "状态不合法": "Invalid status",
- "生产图纸生成失败": "Production drawing generation failed",
- "用户不存在": "User not found",
- "用户名已存在": "Username already exists",
- "用户名或密码错误": "Incorrect username or password",
- "用户名需 3-30 位字母/数字/下划线": "Username must be 3-30 letters, digits or underscores",
- "登录已失效,请重新登录": "Session expired — please sign in again",
- "矢量刀版生成失败": "Vector dieline generation failed",
- "管理员未给你开放 AI 排版额度": "Admin has not granted you AI layout quota",
- "管理员未给你开放 AI 额度": "Admin has not granted you AI quota",
- "类型不合法": "Invalid type",
- "订单不存在": "Order not found",
- "订单不是待支付状态": "Order is not pending payment",
- "订单已取消,不能发货": "Order cancelled — cannot ship",
- "订单状态不允许支付": "Order status does not allow payment",
- "订单状态不合法": "Invalid order status",
- "订单类型不合法": "Invalid order type",
- "订单金额不合法": "Invalid order amount",
- "该订单尚未进入生产流程": "This order has not entered production yet",
- "该订单没有刀版数据": "This order has no dieline data",
- "该订单没有设计数据": "This order has no design data",
- "请先登录": "Please sign in first",
- "请填写反馈内容": "Please fill in the feedback",
- "请填写回复内容": "Please fill in the reply",
- "请填写快递公司和运单号": "Please enter the carrier and tracking number",
- "请填写收货地址": "Please enter the shipping address",
- "请填写联系人和手机号": "Please enter the contact name and phone",
- "请填写邮件主题与内容": "Please enter the email subject and body",
- "请描述你的排版需求": "Describe your layout needs",
- "请输入正确的手机号": "Enter a valid phone number",
- "请输入消息": "Please enter a message",
- "账号不存在": "Account not found",
- "账号已被禁用": "Account disabled",
- "账号已被禁用,请联系客服": "Account disabled — please contact support",
- "需要工作人员权限": "Staff permission required",
- "需要管理员权限": "Admin permission required",
- "预览图不存在": "Preview image not found",
- "额度需在 0-100000 之间": "Quota must be between 0 and 100000",
- "验证码错误或已过期": "Incorrect or expired verification code",
- }
- _HAS_CN = re.compile(r"[\u4e00-\u9fff]")
- def translate_detail(text):
- """整串精确匹配;未命中且含中文时尝试去尾部动态括注后匹配。"""
- if not isinstance(text, str) or not _HAS_CN.search(text):
- return text
- out = ERRORS_EN.get(text)
- if out:
- return out
- base = re.sub(r"[((][^()()]*[))]\s*$", "", text).strip()
- if base and base != text:
- out = ERRORS_EN.get(base)
- if out:
- return out
- return text
- def translate_json_body(body: bytes, lang: str) -> bytes:
- """把 JSON 响应里的 detail/message 中文文案翻译为英文。"""
- if lang != "en":
- return body
- try:
- data = json.loads(body.decode("utf-8"))
- except Exception:
- return body
- changed = False
- if isinstance(data, dict):
- for key in ("detail", "message", "msg", "error"):
- v = data.get(key)
- if isinstance(v, str):
- t = translate_detail(v)
- if t != v:
- data[key] = t
- changed = True
- if not changed:
- return body
- return json.dumps(data, ensure_ascii=False).encode("utf-8")
|