feat: 每日资讯英文标题自动翻译中文

- world/ai/it三个英文栏目抓取时用LLM批量翻译成中文后缓存
- 专有名词保留英文(BBC/Trump/Meta); 失败或数量不符保留英文兜底
- GitHub仓库名/股票中文名不翻; 每天8点翻译一次

验证: 三栏目首页全中文, 抓取含翻译36s(每日一次)

CHANGELOG记录
This commit is contained in:
personal82555 committed 2026-10-13 15:10:41 +08:00
1 parent 4c3c6a2f28
commit 7633368ffd
2 files changed
+58

No files matched your search

+6
View File
@@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. See [standa
## Version 2026.10.12-it-tools-pro
### 🌐 每日资讯英文标题自动翻译中文
- 国际新闻 / AI资讯 / IT最新技术三个英文栏目的标题,抓取时用 LLM 批量翻译成简体中文后再缓存
- 人名/机构/产品名保留英文(如 BBC、Trump、Meta、OpenAI);翻译失败或数量不符时保留英文原文兜底
- GitHub 仓库名与股票中文名不翻译;每天 8 点抓取时翻译一次,前端无需额外请求
### 🏠 首页推荐管理改为下拉选择
- 「首页推荐管理」去掉手动填写的 path / 名称输入框,改为**按分类分组的工具下拉框**(80+ 工具,11 个分组)
- 选中工具自动回填:名称、描述、图标(emoji),无需任何手填;描述可再微调
+52
View File
@@ -2505,6 +2505,45 @@ def _fetch_stock():
return out
def _llm_chat_nm(messages: list, model: str = "") -> str:
"""模块级 LLM 调用(新闻标题翻译用,NewAPI 本地)"""
key = os.environ.get("NEWAPI_KEY", "")
upstream = os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions")
model = (model or os.environ.get("NEWAPI_MODEL", "qwen3.8-flash"))[:60]
if not key:
raise RuntimeError("AI 服务未配置")
body = json.dumps({"model": model, "messages": messages, "temperature": 0.3, "max_tokens": 4096}).encode()
req = request.Request(upstream, data=body, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key})
resp = request.urlopen(req, timeout=120)
data = json.loads(resp.read())
if "error" in data:
raise RuntimeError(data["error"].get("message", "upstream error"))
return data["choices"][0]["message"]["content"]
def _translate_titles(titles: list) -> list:
"""批量把英文新闻标题翻译成中文;失败或数量不符则保留英文原文"""
if not titles:
return titles
try:
prompt = ("把下面 JSON 数组中的每条英文新闻标题翻译成简体中文,人名/机构/产品名保留英文(可跟中文意译)。"
"输出同样长度的 JSON 字符串数组,顺序完全一致,只输出 JSON(不要代码块标记、不要解释)。"
"已是中文的条目原样保留。\n" + json.dumps(list(titles), ensure_ascii=False))
out = _llm_chat_nm([{"role": "user", "content": prompt}])
s = out.strip()
if s.startswith("```"):
s = re.sub(r"^```[a-zA-Z]*\s*", "", s)
s = re.sub(r"\s*```$", "", s).strip()
arr = json.loads(s)
if isinstance(arr, list) and len(arr) == len(titles):
return [str(x) for x in arr]
print(f"[news] translate mismatch got={len(arr) if isinstance(arr, list) else 'non-list'} want={len(titles)}", flush=True)
return titles
except Exception as e: # noqa: BLE001
print(f"[news] translate failed: {e}", flush=True)
return titles
def _fetch_news():
cols = []
@@ -2524,6 +2563,19 @@ def _fetch_news():
_col("it", "IT\u6700\u65b0\u6280\u672f", "\U0001f4bb",
lambda: _parse_rss(_http_get(OPENER_PROXY, _HN_RSS)))
_col("stock", "\u5f53\u5929\u6700\u70ed\u80a1\u7968", "\U0001f4c8", _fetch_stock)
# 英文栏目标题翻译成中文(GitHub 仓库名/股票中文名不翻,仅 world/ai/it)
en_keys = {"world", "ai", "it"}
titles, idx = [], []
for ci, c in enumerate(cols):
if c["key"] in en_keys:
for ii, it in enumerate(c["items"]):
titles.append(it["title"])
idx.append((ci, ii))
if titles:
zh = _translate_titles(titles)
for (ci, ii), t in zip(idx, zh):
cols[ci]["items"][ii]["title"] = t
return cols