Files
sale/scripts/fix_product_desc_unit.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

145 lines
4.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""收尾两个内容字段:products.unit(计量单位)与 products.description(沿用旧中文名的行)。
背景:商品名与价格已经迁移过,但详情页还会露出两处中文——
· unit:'包 / 个 / 盒 / 套 / 件' 直接拼在价格后(¥1,040/包)
· description:多数行原本就是把旧中文名复制了一份,改完 name 后它还是中文
做法:
unit 用固定对照表(5 个取值);
description 用「旧中文名 → 日文名」的同一份映射(数据集 + 人工表)反查,
映射不到的行只列出来、不改库。
用法
python3 fix_product_desc_unit.py --db /path/sale.db --dry-run
python3 fix_product_desc_unit.py --db /path/sale.db --yes
"""
import argparse
import datetime as dt
import json
import os
import re
import shutil
import sqlite3
import sys
import unicodedata
from pathlib import Path
HERE = Path(__file__).resolve().parent
DATASET = Path('/root/ribenyan_products.json')
if not DATASET.exists():
DATASET = HERE.parent / "ribenyan_products.json"
MANUAL = HERE / "product_name_ja.json"
UNIT_MAP = {
"包": "パック",
"个": "個",
"盒": "箱",
"套": "セット",
"件": "点",
"支": "本",
"条": "カートン",
"罐": "缶",
"袋": "袋",
"瓶": "本",
"颗": "個",
"张": "枚",
}
def norm(s: str) -> str:
s = unicodedata.normalize("NFKC", s or "").lower()
return re.sub(r"[\s\-_//·,,.。()()\[\]【】]+", "", s)
def build_map() -> dict[str, str]:
m = {}
if DATASET.exists():
for d in json.loads(DATASET.read_text(encoding="utf-8")):
cn, jp = d.get("name_cn"), d.get("name_jp")
if cn and jp:
m[norm(cn)] = jp
if MANUAL.exists():
for cn, jp in json.loads(MANUAL.read_text(encoding="utf-8")).items():
m[norm(cn)] = jp
return m
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-descunit-{stamp}{suffix}"
shutil.copy2(src, dst)
made.append(dst)
return made
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")
con = sqlite3.connect(args.db, isolation_level=None)
con.execute("PRAGMA busy_timeout = 30000")
mapping = build_map()
unit_plan = []
for u, n in con.execute(
"SELECT unit, COUNT(*) FROM products WHERE deleted_at IS NULL AND unit <> '' GROUP BY unit"
).fetchall():
if u in UNIT_MAP and UNIT_MAP[u] != u:
unit_plan.append((u, UNIT_MAP[u], n))
desc_plan, desc_missing = [], []
for pid, name, desc in con.execute(
"SELECT id, name, description FROM products WHERE deleted_at IS NULL"
).fetchall():
if not desc or not re.search(r"[\u4e00-\u9fa5]", desc):
continue
ja = mapping.get(norm(desc))
if ja and ja != desc:
desc_plan.append((pid, desc, ja))
else:
desc_missing.append((pid, name, desc))
print(f"unit 需替换 {sum(n for _, _, n in unit_plan)} 行:")
for old, new, n in unit_plan:
print(f" {old} → {new} ({n} 行)")
print(f"\ndescription 可映射 {len(desc_plan)} 行,未覆盖 {len(desc_missing)} 行")
for pid, old, new in desc_plan[:6]:
print(f" #{pid} {old[:34]} → {new[:40]}")
if desc_missing:
print("\n未覆盖的 description(不改):")
for pid, name, desc in desc_missing[:8]:
print(f" #{pid} name={name[:24]} desc={desc[:40]}")
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:
for old, new, _ in unit_plan:
con.execute('UPDATE products SET unit = ? WHERE unit = ? AND deleted_at IS NULL', (new, old))
for pid, old, new in desc_plan:
con.execute('UPDATE products SET description = ? WHERE id = ?', (new, pid))
con.execute("COMMIT")
except Exception as exc: # noqa: BLE001
con.execute("ROLLBACK")
print("失败已回滚:", exc)
raise
print(f"已更新 unit {sum(n for _, _, n in unit_plan)} 行、description {len(desc_plan)} 行")
if __name__ == "__main__":
main()