Files
sale/scripts/translate_content_ja.py
T
Hermes ae37085e25
Build and Push Docker Image / build-and-push (push) Successful in 8s
Build and Push Docker Image / deploy (push) Successful in 8s
i18n(content): 库里的运营内容日文化(分类/轮播/公告/活动/资讯/单位/描述)
代码里的界面文案日文化不等于站点日文化 —— 首页 banner、活动标题、资讯正文、
分类名、计量单位这些都在库里,改代码不会跟。

新增两个可重跑的内容迁移脚本(都默认 dry-run、写库前自动备份、未覆盖的行只列不改):

· scripts/translate_content_ja.py + content_ja.json
  分类 10 条、轮播 3 条(标题/描述/按钮)、公告、活动 2 场(含奖品「たばこ10パック」)、
  资讯 6 篇(标题/摘要/正文全译);品牌名 64 条去掉中文段
  (「AmericanSpirit/美国精神」→「AmericanSpirit」)。

· scripts/fix_product_desc_unit.py
  products.unit 818 行:包→パック、个→個、盒→箱、套→セット、件→点;
  products.description 41 行(原本是把旧中文名复制了一份)按同一份
  「旧名→日文名」映射反查替换。

生产已执行:内容 44 处 + 品牌 64 条 + 单位 818 行 + 描述 41 行,逐项 dry-run 后写入。
2026-12-02 00:15:33 +08:00

177 lines
6.4 KiB
Python

#!/usr/bin/env python3
"""把数据库里的「运营内容」改成日文:分类、轮播、公告、活动、奖品、资讯正文。
为什么需要这一步:代码里的界面文案已经 i18n/日文化,但首页 banner、活动标题、
资讯文章这些是**运营数据**,存在库里,改代码不会跟。
用法
python3 translate_content_ja.py --db /path/sale.db --dry-run
python3 translate_content_ja.py --db /path/sale.db --yes
翻译表在 content_ja.json(键为原文,值是日文)。品牌名单独处理:
「AmericanSpirit/美国精神」→ 保留拉丁部分;两边都是拉丁就原样保留。
没有翻译条目的行只列出来、不改库。
"""
import argparse
import datetime as dt
import json
import os
import re
import shutil
import sqlite3
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
TABLE = HERE / "content_ja.json"
# 简单字段:(表, id 是否按原文匹配, [(列, 是否用 id 索引)])
SIMPLE = [
("categories", "name"),
("announcements", "title"),
("announcements", "content"),
("purchase_groups", "name"),
]
def load_map():
return json.loads(TABLE.read_text(encoding="utf-8"))
def backup(db_path):
stamp = dt.datetime.now().strftime("%Y%m%d-%H%M%S")
made = []
for suffix in ("", "-wal", "-shm"):
src = db_path + suffix
if os.path.exists(src):
dst = f"{db_path}.bak-contentja-{stamp}{suffix}"
shutil.copy2(src, dst)
made.append(dst)
return made
def strip_brand(name: str) -> str:
"""品牌名去掉中文段:'AmericanSpirit/美国精神' → 'AmericanSpirit'。"""
if not name or "/" not in name:
return name
parts = [p.strip() for p in name.split("/") if p.strip()]
if not parts:
return name
latin = [p for p in parts if re.fullmatch(r"[A-Za-z0-9 .&'\-]+", p)]
return latin[0] if latin else parts[-1]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--db", required=True)
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--yes", action="store_true")
args = ap.parse_args()
if not args.dry_run and not args.yes:
sys.exit("写库需要 --yes")
m = load_map()
con = sqlite3.connect(args.db, isolation_level=None)
con.execute("PRAGMA busy_timeout = 30000")
plan = [] # (table, id, col, old, new)
missing = []
# 1) 分类 / 公告 / 购买分组:按原文映射
cat_map = m.get("categories", {})
for t, col in SIMPLE:
for rid, val in con.execute(f"SELECT id, {col} FROM {t}").fetchall():
if val is None:
continue
new = cat_map.get(val) if t == "categories" else m.get(t, {}).get(str(rid), {}).get(col)
if new and new != val:
plan.append((t, rid, col, val, new))
elif t == "categories" and val not in cat_map:
missing.append(f"categories#{rid} {val}")
# 2) 轮播:按 id 映射
for rid, title, desc, button in con.execute("SELECT id, title, desc, button FROM banners").fetchall():
tr = m.get("banners", {}).get(str(rid))
if not tr:
missing.append(f"banners#{rid} {title}")
continue
for col, old in (("title", title), ("desc", desc), ("button", button)):
new = tr.get(col)
if new and new != old:
plan.append(("banners", rid, col, old, new))
# 3) 活动:按 id 映射("__冒烟测试_可删__" 这类测试行不在表里,会被列为待处理)
for rid, name, desc in con.execute("SELECT id, name, description FROM lotteries").fetchall():
tr = m.get("lotteries", {}).get(str(rid))
if not tr:
missing.append(f"lotteries#{rid} {name}")
continue
for col, old in (("name", name), ("description", desc)):
new = tr.get(col)
if new and new != old:
plan.append(("lotteries", rid, col, old, new))
# 4) 奖品名:按原文映射
prize_map = m.get("lottery_prizes", {})
for rid, name in con.execute("SELECT id, name FROM lottery_prizes").fetchall():
new = prize_map.get(name)
if new and new != name:
plan.append(("lottery_prizes", rid, "name", name, new))
elif name not in prize_map and re.search(r"[\u4e00-\u9fa5]", name or ""):
missing.append(f"lottery_prizes#{rid} {name}")
# 5) 资讯:标题/摘要/正文
for rid, title, summary, content in con.execute("SELECT id, title, summary, content FROM articles").fetchall():
tr = m.get("articles", {}).get(str(rid))
if not tr:
missing.append(f"articles#{rid} {title}")
continue
for col, old in (("title", title), ("summary", summary), ("content", content)):
new = tr.get(col)
if new and new != old:
plan.append(("articles", rid, col, old, new))
# 6) 品牌名去中文段
brand_changes = []
for rid, name in con.execute("SELECT id, name FROM brands").fetchall():
new = strip_brand(name)
if new and new != name:
brand_changes.append((rid, name, new))
print(f"内容改动 {len(plan)} 处,品牌名去中文 {len(brand_changes)} 条")
for t, rid, col, old, new in plan[:14]:
print(f" {t}#{rid}.{col}: {str(old)[:40]} → {str(new)[:44]}")
if brand_changes:
for rid, old, new in brand_changes[:6]:
print(f" brands#{rid}: {old} → {new}")
if missing:
print(f"\n未覆盖 {len(missing)} 行(不改):")
for x in missing[:10]:
print(" " + x)
if args.dry_run:
print("\n[dry-run] 未写库")
return
backups = backup(args.db)
print("\n已备份:" + ", ".join(os.path.basename(b) for b in backups))
con.execute("BEGIN IMMEDIATE")
try:
now = dt.datetime.now().isoformat(" ", "seconds")
for t, rid, col, old, new in plan:
con.execute(f'UPDATE "{t}" SET "{col}" = ? WHERE id = ?', (new, rid))
for rid, old, new in brand_changes:
con.execute('UPDATE "brands" SET name = ? WHERE id = ?', (new, rid))
con.execute("COMMIT")
except Exception as exc: # noqa: BLE001
con.execute("ROLLBACK")
print("失败已回滚:", exc)
raise
print(f"已更新内容 {len(plan)} 处 + 品牌名 {len(brand_changes)} 条")
if __name__ == "__main__":
main()