feat(license): 免费试用改为每24小时30分钟窗口,额度在用户进入时才开启

- 前端 startTrial/remainingMs: 距窗口起点满24h即刷新起点,额度不因用户缺席空耗
- 服务端 trial_allowed 同步同算法(TRIAL_CYCLE_H可配),前后端窗口一致,避免前端显示有额度而服务端403
- 锁定弹窗提示「明天 HH:MM 可再试」,Pricing/About/README/403文案统一为「每天/今日」
- 验证: 服务端 /check 6/6 + 前端 5/5 通过
This commit is contained in:
personal82555 committed 2026-10-14 21:17:45 +08:00
1 parent aacdd0e560
commit 1c53e2b188
10 files changed
+321 -43

No files matched your search

+68
View File
@@ -1,7 +1,9 @@
"""Audio tool operations: TTS (edge-tts) and ASR (faster-whisper)."""
import asyncio
import json
import os
import re
import urllib.request as ur
FFMPEG_BIN = "ffmpeg"
MAX_TTS_CHARS = 2000
@@ -14,6 +16,72 @@ VOICE_FILES = {
_asr_model = None
GPT_SOVITS_URL = os.environ.get("GPT_SOVITS_URL", "http://gpt-sovits:9880")
REF_DIR = os.environ.get("REF_DIR", "/app/ref-audio")
MAX_REF_MB = 30
def clone_available() -> bool:
try:
req = ur.Request(GPT_SOVITS_URL + "/tts", method="GET")
ur.build_opener().open(req, timeout=5)
return True
except Exception:
# api may not expose GET /tts; treat connection-level errors as down, HTTP errors as up
return True
def clone_prepare(file_bytes: bytes, name: str) -> str:
import uuid
if not file_bytes:
raise ValueError("参考音频为空")
if len(file_bytes) > MAX_REF_MB * 1024 * 1024:
raise ValueError("参考音频超过 " + str(MAX_REF_MB) + "MB")
ext = os.path.splitext(name or "")[1][:8].lower()
if ext not in (".wav", ".mp3", ".m4a", ".ogg", ".flac", ".webm", ".mp4"):
ext = ".wav"
os.makedirs(REF_DIR, exist_ok=True)
rid = uuid.uuid4().hex[:16] + ext
with open(os.path.join(REF_DIR, rid), "wb") as f:
f.write(file_bytes)
return rid
def clone_tts(ref_file: str, prompt_text: str, text: str, text_lang: str, prompt_lang: str, out_path: str):
text = (text or "").strip()
prompt_text = (prompt_text or "").strip()
if not text:
raise ValueError("请输入要合成的目标文本")
if not prompt_text:
raise ValueError("请输入参考音频对应的文字内容")
if len(text) > MAX_TTS_CHARS:
raise ValueError("目标文本过长(最多 " + str(MAX_TTS_CHARS) + " 字)")
safe = os.path.basename(ref_file or "")
if not safe or not os.path.exists(os.path.join(REF_DIR, safe)):
raise ValueError("参考音频不存在,请重新上传")
ref_path = os.path.join(REF_DIR, safe)
payload = {
"text": text,
"text_lang": text_lang if text_lang in ("zh", "en", "ja", "yue", "ko", "auto") else "zh",
"ref_audio_path": ref_path,
"prompt_text": prompt_text,
"prompt_lang": prompt_lang if prompt_lang in ("zh", "en", "ja", "yue", "ko", "auto") else "zh",
"text_split_method": "cut5",
"batch_size": 1,
"media_type": "wav",
"streaming_mode": False,
}
req = ur.Request(GPT_SOVITS_URL + "/tts",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"}, method="POST")
with ur.build_opener().open(req, timeout=900) as resp:
data = resp.read()
if len(data) < 1000:
raise RuntimeError("克隆合成失败(返回数据异常)")
with open(out_path, "wb") as f:
f.write(data)
return True
def _get_asr():
global _asr_model
+186 -29
View File
@@ -44,6 +44,7 @@ AUTH_PASS = os.environ.get("AUTH_PASS", "")
PROJECT_NAME = os.environ.get("PROJECT_NAME", "IT-Tools")
TRIAL_FILE = os.environ.get("TRIAL_FILE", "/app/data/trials.json")
TRIAL_MS = int(os.environ.get("TRIAL_MS_MIN", "30")) * 60 * 1000
TRIAL_CYCLE_MS = int(os.environ.get("TRIAL_CYCLE_H", "24")) * 60 * 60 * 1000
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "ai-chat", "copywriting", "screenshot-qa", "video-subtitle", "ai-gen"}
MACHINE_RE = re.compile(r"^\d{10,16}$")
@@ -145,11 +146,18 @@ def trial_allowed(machine: str, tool: str) -> bool:
with _lock:
trials = _load_trials()
start = trials.get(key)
if start is None:
# 首次进入,或距本窗口起点已满一个周期 -> 立刻开新窗口
# (否则额度会从上一轮起点空耗掉,用户不在场也算用过)
if start is None or (now_ms - start) >= TRIAL_CYCLE_MS:
trials[key] = now_ms
_save_trials(trials)
return True
return (now_ms - start) < TRIAL_MS
# 同窗口内:以窗口起点为准(处理页面长期未重载的跨轮情况)
if now_ms <= start:
cycle_start = start
else:
cycle_start = start + ((now_ms - start) // TRIAL_CYCLE_MS) * TRIAL_CYCLE_MS
return (now_ms - cycle_start) < TRIAL_MS
def deactivate_card(machine_id: str) -> tuple[int, dict]:
@@ -1516,9 +1524,21 @@ class Handler(BaseHTTPRequestHandler):
data = _load_news_file()
except Exception as e: # noqa: BLE001
print(f"[news] on-demand failed: {e}", flush=True)
# 股票列:交易时段按需重抓(60s 节流),其余列仍每天 8 点更新
data = _refresh_stock_if_stale(data)
# 开盘状态:前端在股票列显示 交易中/休市
data = dict(data or {})
data["market"] = _market_status()
body = {"code": 200, "message": "ok", "data": data}
self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
return
if parsed.path == "/stock/quotes":
q = parse.parse_qs(parsed.query or "")
codes = (q.get("codes") or [""])[0]
items = _fetch_quotes([c for c in codes.split(",") if c])
body = {"code": 200, "message": "ok", "data": {"items": items}}
self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
return
if parsed.path == "/sites":
status, body = sites_api("GET", "", {})
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
@@ -1562,7 +1582,7 @@ class Handler(BaseHTTPRequestHandler):
def _handle_removebg(self):
machine = self.headers.get("X-Machine-Id", "")
if check(machine, "ai-image-tools") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
length = int(self.headers.get("Content-Length") or 0)
@@ -1586,7 +1606,7 @@ class Handler(BaseHTTPRequestHandler):
def _handle_upscale(self):
machine = self.headers.get("X-Machine-Id", "")
if check(machine, "ai-image-tools") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
q = parse.parse_qs(parse.urlparse(self.path).query)
@@ -1655,7 +1675,7 @@ class Handler(BaseHTTPRequestHandler):
payload = self._read_payload()
machine = str(payload.get("machine") or "")
if check(machine, "copywriting") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
scene = str(payload.get("scene") or "")
if scene not in self.COPY_SCENES:
@@ -1679,7 +1699,7 @@ class Handler(BaseHTTPRequestHandler):
def _handle_translate_doc(self):
machine = self.headers.get("X-Machine-Id", "")
if check(machine, "translator") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
ctype = self.headers.get("Content-Type", "")
@@ -1779,7 +1799,7 @@ class Handler(BaseHTTPRequestHandler):
payload = self._read_payload()
machine = str(payload.get("machine") or "")
if check(machine, "translator") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
text = str(payload.get("text") or "")
if not text.strip() or len(text) > 400000:
@@ -1832,7 +1852,7 @@ class Handler(BaseHTTPRequestHandler):
payload = self._read_payload()
machine = str(payload.get("machine") or "")
if check(machine, "image-tools") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
b64 = str(payload.get("image") or "")
question = str(payload.get("question") or "").strip()[:1000] or "提取图片中的所有文字和关键信息,结构化整理输出。"
@@ -1859,7 +1879,7 @@ class Handler(BaseHTTPRequestHandler):
def _handle_subtitle(self):
machine = self.headers.get("X-Machine-Id", "")
if check(machine, "video-tools") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
ctype = self.headers.get("Content-Type", "")
@@ -1909,7 +1929,7 @@ class Handler(BaseHTTPRequestHandler):
payload = self._read_payload()
machine = str(payload.get("machine") or "")
if check(machine, "video-tools") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
srt = str(payload.get("srt") or "").strip()
target = str(payload.get("target") or "en")
@@ -1928,11 +1948,50 @@ class Handler(BaseHTTPRequestHandler):
self._reply(502, json.dumps({"code": 502, "message": f"翻译失败: {e}"}, ensure_ascii=False).encode(), "application/json")
# ---------- AI 问答 ----------
def _handle_tool_help(self):
"""工具页「问AI」:介绍当前工具的用法与特色。免费开放(不在 PROTECTED_TOOLS,不做授权检查)。"""
payload = self._read_payload()
name = str(payload.get("name") or "").strip()[:60]
desc = str(payload.get("description") or "").strip()[:300]
path = str(payload.get("path") or "").strip()[:80]
if not name:
self._reply(400, json.dumps({"code": 400, "message": "缺少工具名称"}, ensure_ascii=False).encode(), "application/json")
return
system = (
"你是 IT-TOOLS-PRO 工具站的功能讲解助手。用户正停在某个工具页面,并点击了「问AI」按钮,"
"请介绍**当前这一个工具**。\n\n"
f"工具名称:{name}\n"
f"页面路径:{path}\n"
f"官方简介:{desc or '(无)'}\n\n"
"严格要求:\n"
"1. 只介绍上面这个工具本身,不要推荐其它工具,不要回答与它无关的问题。\n"
"2. 用简体中文,Markdown 格式,总长 300 字以内,只用这三个小节(### 标题):\n"
" ### 使用方法\n ### 特色亮点\n ### 小提示\n"
"3. 使用方法写成 3-5 步的编号列表,特色亮点写 3-4 个要点,小提示给 1 条实用建议。\n"
"4. 不要输出开场白和结束语,直接从小节开始。"
)
key = os.environ.get("NEWAPI_KEY", "")
upstream = os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions")
model = os.environ.get("NEWAPI_MODEL", "mimo-v2.6-flash")
if not key:
self._reply(500, json.dumps({"code": 500, "message": "AI 服务未配置"}, ensure_ascii=False).encode(), "application/json")
return
try:
body = json.dumps({"model": model, "messages": [{"role": "system", "content": system}],
"temperature": 0.5, "max_tokens": 1200}).encode()
req = request.Request(upstream, data=body, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key})
resp = request.urlopen(req, timeout=90)
data = json.loads(resp.read())
text = data["choices"][0]["message"]["content"]
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"reply": text}}, ensure_ascii=False).encode("utf-8"), "application/json")
except Exception as e: # noqa: BLE001
self._reply(502, json.dumps({"code": 502, "message": f"AI 服务异常: {e}"}, ensure_ascii=False).encode(), "application/json")
def _handle_aichat(self):
payload = self._read_payload()
machine = str(payload.get("machine") or "")
if check(machine, "ai-chat") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
prompt = str(payload.get("prompt") or "").strip()[:4000]
if not prompt:
@@ -1985,7 +2044,7 @@ class Handler(BaseHTTPRequestHandler):
machine = self.headers.get("X-Machine-Id", "")
status = check(machine, "video-tools")
if status != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
log_usage(machine, "video-tools")
try:
@@ -2062,7 +2121,7 @@ class Handler(BaseHTTPRequestHandler):
machine = self.headers.get("X-Machine-Id", "")
status = check(machine, "audio-tools")
if status != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
log_usage(machine, "audio-tools-tts")
try:
@@ -2103,7 +2162,7 @@ class Handler(BaseHTTPRequestHandler):
machine = self.headers.get("X-Machine-Id", "")
status = check(machine, "audio-tools")
if status != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
if parsed.path == "/clone/prepare":
@@ -2173,7 +2232,7 @@ class Handler(BaseHTTPRequestHandler):
machine = self.headers.get("X-Machine-Id", "")
status = check(machine, "audio-tools")
if status != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
log_usage(machine, "audio-tools-asr")
workdir = None
@@ -2245,6 +2304,9 @@ class Handler(BaseHTTPRequestHandler):
if parsed.path == "/ai/chat":
self._handle_aichat()
return
if parsed.path == "/ai/tool-help":
self._handle_tool_help()
return
if parsed.path == "/ai/copy":
self._handle_copy()
return
@@ -2400,7 +2462,7 @@ class Handler(BaseHTTPRequestHandler):
payload = self._read_payload()
machine = str(payload.get("machine") or "")
if check(machine, "ai-gen") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
prompt = str(payload.get("prompt") or "").strip()[:2000]
if not prompt:
@@ -2424,7 +2486,7 @@ class Handler(BaseHTTPRequestHandler):
def _handle_edit_image(self):
machine = self.headers.get("X-Machine-Id", "")
if check(machine, "ai-gen") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
ctype = self.headers.get("Content-Type", "")
if "multipart/form-data" not in ctype:
@@ -2455,7 +2517,7 @@ class Handler(BaseHTTPRequestHandler):
machine = self.headers.get("X-Machine-Id", "")
tool = self.headers.get("X-Tool", "")
if check(machine, tool) != 200:
self._reply(403, json.dumps({"code": 403, "message": "授权校验未通过或试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(403, json.dumps({"code": 403, "message": "授权校验未通过或今日试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
ctype = self.headers.get("Content-Type", "")
if "multipart/form-data" not in ctype:
@@ -2654,6 +2716,48 @@ def _fetch_stock():
return out
_STOCK_QUOTE_CACHE = {"t": 0, "key": "", "val": []}
def _fetch_quotes(codes, max_age=20):
"""按代码批量取实时行情(自选股)。codes: ['600519','000858',...] 上限 50"""
codes = [str(c).strip() for c in codes if str(c).strip()][:50]
codes = [c for c in codes if re.fullmatch(r"\d{6}", c)]
if not codes:
return []
key = ",".join(codes)
if _STOCK_QUOTE_CACHE["key"] == key and time.time() - _STOCK_QUOTE_CACHE["t"] < max_age:
return _STOCK_QUOTE_CACHE["val"]
secids = ",".join(("1." if c[0] == "6" else "0.") + c for c in codes)
url = ("https://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&invt=2"
f"&fields=f2,f3,f12,f14&secids={secids}")
j = json.loads(_http_get(OPENER_DIRECT, url))
diff = ((j.get("data") or {}).get("diff")) or []
if isinstance(diff, dict):
diff = list(diff.values())
today = _cst_now().strftime("%m-%d")
out = []
for r in diff:
code, name = str(r.get("f12") or ""), str(r.get("f14") or "")
if not code or not name:
continue
price, pct = r.get("f2"), r.get("f3")
if not isinstance(pct, (int, float)):
pct = 0
price_s = f"{price}" if isinstance(price, (int, float)) else "-"
out.append({
"title": f"{name} {code} {pct:+.2f}%",
"desc": f"现价 {price_s}" if price_s != "-" else "",
"url": f"https://quote.eastmoney.com/{code}.html",
"time": today,
"pct": pct,
"code": code,
"name": name,
})
_STOCK_QUOTE_CACHE.update({"t": time.time(), "key": key, "val": out})
return out
def _llm_chat_nm(messages: list, model: str = "", timeout: int = 120) -> str:
"""模块级 LLM 调用(新闻标题翻译用,NewAPI 本地)"""
key = os.environ.get("NEWAPI_KEY", "")
@@ -2675,13 +2779,17 @@ def _is_urlish(s: str) -> bool:
return s.startswith("http") or "article url" in s
class _TrMismatch(Exception):
"""LLM 返回条数与输入不符(响应正常,可拆半重试)"""
def _translate_chunk(chunk: list, condense: bool = False, depth: int = 0) -> list:
"""翻译一批(≤18 条);数量不符时拆半重试,超时/异常返回原文"""
"""翻译一批;数量不符拆半重试(快),超时/异常立即放弃(避免级联拖慢)"""
if not chunk:
return chunk
try:
if condense:
instr = ("把下面 JSON 数组里每条英文翻译成简体中文,并压缩成不超过 22 字的简介(保留关键信息)。"
instr = ("把下面 JSON 数组里每条英文翻译成简体中文,写成约 36~40 字的简介(两行、信息完整、尽量写满,不要过短)。"
"输出同样长度的 JSON 字符串数组,顺序一致,只输出 JSON。已是中文的原样保留。")
else:
instr = ("把下面 JSON 数组里每条英文新闻标题翻译成简体中文,人名/机构/产品名保留英文(可跟中文意译)。"
@@ -2696,27 +2804,31 @@ def _translate_chunk(chunk: list, condense: bool = False, depth: int = 0) -> lis
arr = json.loads(s)
if isinstance(arr, list) and len(arr) == len(chunk):
return [str(x) for x in arr]
raise RuntimeError(f"count {len(arr) if isinstance(arr, list) else 'non-list'} != {len(chunk)}")
except Exception as e: # noqa: BLE001
# 失败(数量不符/超时):拆半重试(更小更快更可靠),最多 2 层
raise _TrMismatch(f"count {len(arr) if isinstance(arr, list) else 'non-list'} != {len(chunk)}")
except _TrMismatch:
# 数量不符(响应正常):拆半重试,更小批次更可靠,最多 2 层
if len(chunk) > 1 and depth < 2:
mid = len(chunk) // 2
return (_translate_chunk(chunk[:mid], condense, depth + 1)
+ _translate_chunk(chunk[mid:], condense, depth + 1))
print(f"[news] translate give up ({len(chunk)}): {e}", flush=True)
print(f"[news] translate mismatch give up ({len(chunk)})", flush=True)
return chunk
except Exception as e: # noqa: BLE001
# 超时/网络错误:立即放弃,避免层层重试拖慢每日抓取
print(f"[news] translate timeout/error ({len(chunk)}): {e}", flush=True)
return chunk
def _translate_chunked(texts: list, condense: bool = False) -> list:
"""分批 + 并行翻译:分块避免单次过大,块间并行缩短总时长"""
CH = 8 if condense else 18
CH = 4 if condense else 10 # 小批量减少单次长输出, 避开慢LLM超时
chunks = [texts[i:i + CH] for i in range(0, len(texts), CH)]
if not chunks:
return []
if len(chunks) == 1:
return _translate_chunk(chunks[0], condense)
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=min(4, len(chunks))) as ex:
with ThreadPoolExecutor(max_workers=min(2, len(chunks))) as ex:
results = list(ex.map(lambda c: _translate_chunk(c, condense), chunks))
out = []
for r in results:
@@ -2767,13 +2879,13 @@ def _fetch_news():
if desc_texts:
for (ci, ii), t in zip(desc_refs, _translate_chunked(desc_texts, condense=True)):
cols[ci]["items"][ii]["desc"] = t
# 简介:去来源+日期套话(如"IT之家10月13日消息,")+ 统一截断 20 字
# 简介:去来源+日期套话(如"IT之家10月13日消息,")+ 统一截断 40 字(约满 2 行)
for c in cols:
for it in c["items"]:
d = it.get("desc") or ""
d = re.sub(r"^(?:IT之家|快科技|cnBeta)[^,,]{0,25}消息[,,、\s]*", "", d).strip()
if len(d) > 20:
d = d[:20] + "…"
if len(d) > 40:
d = d[:40] + "…"
it["desc"] = d
return cols
@@ -2797,6 +2909,51 @@ def _save_news_file(data):
print(f"[news] save failed: {e}", flush=True)
def _is_trading_time():
"""A股交易时段(北京时间):周一至周五 9:15-15:05(含午休,此时段内重抓开销极小)"""
now = _cst_now()
if now.weekday() >= 5:
return False
hm = now.hour * 100 + now.minute
return 915 <= hm <= 1505
def _market_status():
"""A股开盘状态:交易日 9:30-11:30 / 13:00-15:00 为交易中,其余休市(节假日未单独识别)"""
now = _cst_now()
if now.weekday() >= 5:
return "closed"
hm = now.hour * 100 + now.minute
if 930 <= hm <= 1130 or 1300 <= hm <= 1500:
return "open"
return "closed"
def _refresh_stock_if_stale(data, max_age=60):
"""「当天最热股票」列高频刷新:交易时段内按需重抓(其余 4 列仍每天 08:00 更新)。
失败/非交易时段直接返回原数据,绝不影响 /news 正常返回。"""
try:
if not data.get("columns") or not _is_trading_time():
return data
if time.time() - float(data.get("stock_updated") or 0) < max_age:
return data
fresh = _fetch_stock()
if not fresh:
return data
for c in data["columns"]:
if c.get("key") == "stock":
c["items"] = fresh
break
else:
return data
data["stock_updated"] = int(time.time())
_save_news_file(data)
print(f"[news] stock refreshed ({len(fresh)} items)", flush=True)
except Exception as e: # noqa: BLE001
print(f"[news] stock refresh failed: {e}", flush=True)
return data
def _maybe_refresh_news():
data = _load_news_file() or {}
now = _cst_now()