i18n.py 6.0 KB

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