feat: 添加持久化映射加载和状态文件序列化功能,优化 GUI 显示

This commit is contained in:
Your Name committed 2026-01-15 14:25:54 +08:00
1 parent e39a984260
commit 2358682216
9 files changed
+417 -90

No files matched your search

+3 -3
View File
@@ -11,7 +11,7 @@
"reset_after_swipes_action": "back",
"auto_join_fansclub": true,
"fansclub_fail_action": "switch",
"high_value_fudai_enabled": false,
"high_value_fudai_enabled": true,
"high_value_fudai_threshold_yuan": 500.0,
"high_value_fudai_join_ahead_seconds": 100,
"high_value_fudai_max_swipe_back": 50,
@@ -31,7 +31,7 @@
"fudai_icon_max_wait_seconds": 5.0,
"fudai_icon_retry_delay_seconds": 0.1,
"fudai_exit_after_misses": 10,
"enable_back_on_misses": true,
"enable_back_on_misses": false,
"fudai_click_wait_seconds": 1.2,
"fudai_detail_initial_wait_seconds": 0.8,
"fudai_detail_verified_wait_seconds": 0.2,
@@ -69,7 +69,7 @@
"fudai_quiet_hours_enabled": true,
"fudai_quiet_start_hour": 2,
"fudai_quiet_end_hour": 9,
"yanghao_enabled": true,
"yanghao_enabled": false,
"yanghao_enable_actions": true,
"yanghao_like_icon_x": 988,
"yanghao_like_icon_y": 1218,
+29
View File
@@ -296,6 +296,35 @@ class fudai_analyse:
# 格式:{room_pos: (room_title, room_title_raw)}
self._room_pos_to_title_map: dict[int, tuple[str, str]] = {}
# 启动时尝试从持久化文件加载已有映射,便于 GUI 与重启后的可见性
try:
state_path = os.path.join(os.path.dirname(__file__), "state", "room_pos_map.json")
if os.path.exists(state_path):
try:
with open(state_path, "r", encoding="utf-8") as f:
import json as _json
parsed = _json.load(f)
# parsed 格式为 {"<pos>": [title, title_raw], ...}
tmp_map: dict[int, tuple[str, str]] = {}
for k, v in parsed.items():
try:
ik = int(k)
except Exception:
continue
try:
title = v[0] if isinstance(v, (list, tuple)) and len(v) > 0 else ""
title_raw = v[1] if isinstance(v, (list, tuple)) and len(v) > 1 else ""
tmp_map[ik] = (title, title_raw)
except Exception:
continue
if tmp_map:
self._room_pos_to_title_map = tmp_map
except Exception:
pass
except Exception:
pass
# 已记录统计的福袋跟踪(避免同一个直播间同一个福袋重复记录统计)
self._recorded_fudai_stats: set[tuple[str, str]] = (
set()
+74
View File
@@ -0,0 +1,74 @@
{
"1": [
"2",
"2&"
],
"2": [
"终火米",
"终*火米]"
],
"3": [
"隋心",
"隋心"
],
"4": [
"s",
"/s"
],
"5": [
"",
""
],
"6": [
"7L只",
"7]L只"
],
"7": [
"S",
"S^^^"
],
"8": [
"",
""
],
"9": [
"",
""
],
"10": [
"3",
"{3/"
],
"0": [
"AR黄龄",
"AR黄龄"
],
"11": [
"",
""
],
"12": [
"",
""
],
"13": [
"gITc",
"gITc"
],
"14": [
"",
""
],
"15": [
"",
""
],
"16": [
"交个朋友",
"交个朋友"
],
"17": [
"演员梁燹琪",
"演员梁燹琪"
]
}
+15 -2
View File
@@ -3904,8 +3904,6 @@ def _is_short_countdown_text(time_text: str) -> bool:
time_text = time_text.strip()
# 匹配 00:00, 00:01, 00:02 等,表示剩余时间 <= 2秒
import re
if re.match(r"^00:0[0-2]$", time_text):
return True
@@ -5364,6 +5362,21 @@ def basic_join_decision(
)
except Exception:
pass
# 尝试将映射序列化到状态文件,供 GUI 使用
try:
from douyin.reservation import (
douyin_reservation_handler as _rh,
)
if hasattr(_rh, "_dump_room_pos_map_to_state"):
try:
_rh._dump_room_pos_map_to_state(
analyser
)
except Exception:
pass
except Exception:
pass
except Exception as e_inner:
try:
analyser._log_kv(
+28
View File
@@ -307,6 +307,34 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
did_like = False
did_fav = False
# 定时禁抢(仅在养号动作启用时生效):根据配置跳过爱心/收藏/评论
try:
if bool(getattr(analyser, "fudai_quiet_hours_enabled", False)):
start_h = int(
getattr(analyser, "fudai_quiet_start_hour", 0) or 0
)
end_h = int(getattr(analyser, "fudai_quiet_end_hour", 0) or 0)
now_h = time.localtime().tm_hour
in_quiet = False
if start_h <= end_h:
in_quiet = start_h <= now_h < end_h
else:
# 跨天区间,例如 23-6
in_quiet = now_h >= start_h or now_h < end_h
if in_quiet:
print(
f"[养号] 定时禁抢生效({start_h}:00-{end_h}:00),当前小时={now_h},跳过爱心/收藏/评论"
)
# 避免频繁循环,做一次随机短等待再继续
try:
_human_delay(2.0, 6.0)
except Exception:
analyser.operation.delay(3.0)
continue
except Exception:
# 配置读取异常不应影响主循环
pass
try:
now = time.time()
if now - last_desktop_check_ts >= desktop_check_interval:
@@ -14,6 +14,9 @@ from __future__ import annotations
import time
import difflib
from typing import Any, Optional, Dict
import json
import os
import path_config
from douyin.fudai import douyin_fudai_detail
from douyin.reservation import douyin_reservation_logic
@@ -227,6 +230,11 @@ class ReservationHandler:
)
except Exception:
pass
# 序列化运行时映射表到文件,供 GUI 刷新使用
try:
_dump_room_pos_map_to_state(analyser)
except Exception:
pass
else:
# 如果已存在,更新标题(可能标题有变化)
old_title, old_title_raw = analyser._room_pos_to_title_map[
@@ -250,6 +258,11 @@ class ReservationHandler:
)
except Exception:
pass
# 序列化运行时映射表到文件,供 GUI 刷新使用
try:
_dump_room_pos_map_to_state(analyser)
except Exception:
pass
except Exception:
pass
except Exception as e:
@@ -275,6 +288,11 @@ class ReservationHandler:
)
except Exception:
pass
# 序列化运行时映射表到文件,供 GUI 刷新使用
try:
_dump_room_pos_map_to_state(analyser)
except Exception:
pass
except Exception:
pass
# 记录读取标题失败的错误
@@ -599,7 +617,6 @@ class ReservationHandler:
# 检测参与按钮
from PIL import Image
import path_config
try:
screenshot_path = path_config.get_screenshot_path()
@@ -846,3 +863,57 @@ class ReservationHandler:
pass
# 如果出错,回退到正常流程
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
def _dump_room_pos_map_to_state(analyser: Any) -> None:
"""将 analyser._room_pos_to_title_map 序列化到 douyin/core/state/room_pos_map.json。
结构为 {"<pos>": [title, title_raw], ...},Unicode保持原样。
"""
try:
room_pos_map = getattr(analyser, "_room_pos_to_title_map", {})
# 即使没有映射,也希望写入本次运行的元信息
state_dir = os.path.join(path_config.PROJECT_ROOT, "douyin", "core", "state")
os.makedirs(state_dir, exist_ok=True)
final_path = os.path.join(state_dir, "room_pos_map.json")
tmp_path = final_path + ".tmp"
# 过滤掉空条目,只保留本次运行有值的映射
filtered = {}
for k, v in room_pos_map.items():
try:
title = (v[0] or "").strip()
except Exception:
title = ""
try:
title_raw = (v[1] or "").strip()
except Exception:
title_raw = ""
if not title and not title_raw:
continue
filtered[str(k)] = [title, title_raw]
# 准备写入数据:保留原有 top-level 映射结构,同时添加一个保留的元信息字段
data = dict(filtered)
try:
data["_meta"] = {
"source": final_path,
"generated_ts": int(time.time()),
"run_id": getattr(analyser, "_run_id", ""),
}
except Exception:
data["_meta"] = {"generated_ts": int(time.time())}
# 使用漂亮的缩进写入文件(先写 tmp 再替换)
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
try:
os.replace(tmp_path, final_path)
except Exception:
# os.replace 在某些环境可能不可用,回退到重命名
os.rename(tmp_path, final_path)
except Exception:
try:
analyser._log_kv("预约", "[预约] 序列化映射表到文件失败")
except Exception:
pass
+185 -73
View File
@@ -383,6 +383,115 @@ def main():
mid.add(left_wrap, weight=0) # 左侧配置区域
mid.add(right, weight=1) # 右侧日志/预览区域
# 右侧 notebook(用于日志/预览/映射表)
right_notebook = ttk.Notebook(right)
right_notebook.pack(fill=BOTH, expand=True)
# 映射表标签页(右侧)
mapping_tab = ttk.Frame(right_notebook)
right_notebook.add(mapping_tab, text="映射表")
# 映射信息顶部:来源路径和操作按钮
mapping_top = ttk.Frame(mapping_tab)
mapping_top.pack(fill=X, padx=8, pady=(8, 4))
mapping_source_var = tk.StringVar(value="未加载")
ttk.Label(mapping_top, text="来源:").pack(side=LEFT)
ttk.Label(mapping_top, textvariable=mapping_source_var).pack(side=LEFT)
mapping_refresh_btn = ttk.Button(mapping_top, text="刷新映射表")
mapping_refresh_btn.pack(side=RIGHT)
mapping_auto_refresh_var = tk.BooleanVar(value=False)
mapping_auto_refresh_cb = ttk.Checkbutton(
mapping_top, text="自动刷新", variable=mapping_auto_refresh_var
)
mapping_auto_refresh_cb.pack(side=RIGHT, padx=(0, 8))
# 映射表格
mapping_tree = ttk.Treeview(
mapping_tab, columns=("pos", "title", "title_raw"), show="headings"
)
mapping_tree.heading("pos", text="位置")
mapping_tree.heading("title", text="标题")
mapping_tree.heading("title_raw", text="原始标题")
mapping_tree.column("pos", width=80, anchor="e")
mapping_tree.column("title", width=300, anchor="w")
mapping_tree.column("title_raw", width=300, anchor="w")
mapping_tree.pack(fill=BOTH, expand=True, padx=8, pady=(4, 8))
# 加载/刷新函数
def _find_room_map_path() -> str | None:
try:
import path_config as _pc
candidates = [
os.path.join(_pc.PROJECT_ROOT, "douyin", "core", "state", "room_pos_map.json"),
os.path.join(os.getcwd(), "douyin", "core", "state", "room_pos_map.json"),
]
except Exception:
candidates = [
os.path.join(os.getcwd(), "douyin", "core", "state", "room_pos_map.json"),
]
for p in candidates:
try:
if os.path.exists(p):
return p
except Exception:
pass
return None
def _load_mapping_to_tree():
path = _find_room_map_path()
if not path:
mapping_source_var.set("未找到 room_pos_map.json")
mapping_tree.delete(*mapping_tree.get_children())
return
mapping_source_var.set(path)
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
mapping_tree.delete(*mapping_tree.get_children())
return
# 删除元信息字段
meta = None
if isinstance(data, dict) and "_meta" in data:
meta = data.pop("_meta", None)
mapping_tree.delete(*mapping_tree.get_children())
try:
keys = sorted([k for k in data.keys()], key=lambda x: int(x) if str(x).isdigit() else x)
except Exception:
keys = list(data.keys())
for k in keys:
try:
v = data.get(k, ["", ""]) or ["", ""]
title = (v[0] or "").strip() or "-"
title_raw = (v[1] or "").strip() or "-"
except Exception:
title, title_raw = "-", "-"
mapping_tree.insert("", "end", values=(k, title, title_raw))
# 绑定刷新按钮与自动刷新
mapping_refresh_btn.config(command=_load_mapping_to_tree)
def _mapping_auto_refresh_loop():
try:
if mapping_auto_refresh_var.get():
_load_mapping_to_tree()
except Exception:
pass
try:
mapping_tab.after(2000, _mapping_auto_refresh_loop)
except Exception:
pass
try:
_mapping_auto_refresh_loop()
except Exception:
pass
# 左侧使用Notebook标签页组织配置
left_notebook = ttk.Notebook(left_wrap)
left_notebook.pack(fill=BOTH, expand=True)
@@ -1077,79 +1186,6 @@ def main():
width=8,
).pack(side=LEFT)
# 新增:映射表标签页(用于查看运行时/持久化的 room_pos -> title 映射)
mapping_tab = ttk.Frame(left_notebook)
left_notebook.add(mapping_tab, text="映射表")
map_box = ttk.LabelFrame(
mapping_tab, text="运行时映射表(room_pos -> (title, title_raw))"
)
map_box.pack(fill=X, padx=10, pady=(10, 10))
map_ctrl = ttk.Frame(map_box)
map_ctrl.pack(fill=X, padx=10, pady=(8, 6))
map_auto_refresh_var = tk.BooleanVar(value=False)
ttk.Checkbutton(
map_ctrl, text="自动刷新(5s)", variable=map_auto_refresh_var
).pack(side=LEFT)
ttk.Button(map_ctrl, text="刷新映射表", width=12).pack(side=LEFT, padx=(8, 6))
# 映射内容显示区
map_view = ScrolledText(mapping_tab, wrap="none", height=12)
map_view.pack(fill=BOTH, expand=True, padx=10, pady=(6, 10))
# 加载映射表的函数(尝试多个可能的路径)
def _load_mapping_to_view():
map_view.delete("1.0", "end")
possible_paths = [
os.path.join(os.getcwd(), "douyin", "core", "state", "room_pos_map.json"),
os.path.join(os.getcwd(), "douyin", "core", "state", "reservations.json"),
os.path.join(os.getcwd(), "douyin", "state", "room_pos_map.json"),
]
found = False
for p in possible_paths:
try:
if os.path.exists(p):
with open(p, "r", encoding="utf-8") as f:
data = f.read()
# 尝试格式化 JSON,否则原样显示
try:
import json as _json
parsed = _json.loads(data)
pretty = _json.dumps(parsed, ensure_ascii=False, indent=2)
map_view.insert("end", f"# 从: {p}\n")
map_view.insert("end", pretty)
except Exception:
map_view.insert("end", f"# 从: {p}(非JSON,原始内容)\n")
map_view.insert("end", data)
found = True
break
except Exception as e:
map_view.insert("end", f"读取 {p} 失败: {e}\n")
if not found:
map_view.insert(
"end",
"未找到映射表文件。可在运行端将 '_room_pos_to_title_map' 序列化到 'douyin/core/state/room_pos_map.json',然后点击刷新以查看内容。",
)
# 绑定刷新按钮与自动刷新
btns = map_ctrl.winfo_children()
if btns and isinstance(btns[-1], ttk.Button):
btns[-1].config(command=_load_mapping_to_view)
def _maybe_auto_refresh():
if map_auto_refresh_var.get():
try:
_load_mapping_to_view()
except Exception:
pass
root.after(5000, _maybe_auto_refresh)
# 启动自动刷新轮询(无害,如果开关关闭不会频繁IO)
root.after(5000, _maybe_auto_refresh)
# 养号设置标签(后续代码)
yanghao_tab = ttk.Frame(left_notebook)
left_notebook.add(yanghao_tab, text="养号设置")
@@ -2744,6 +2780,82 @@ def main():
notebook.add(realtime_tab, text="实时状态")
notebook.add(ocr_results_tab, text="OCR结果")
notebook.add(win_record_tab, text="中奖记录")
# 将运行时映射表加入右侧 Notebook
mapping_tab = ttk.Frame(notebook)
map_box = ttk.LabelFrame(
mapping_tab, text="运行时映射表(room_pos -> (title, title_raw))"
)
map_box.pack(fill=X, padx=10, pady=(10, 10))
map_ctrl = ttk.Frame(map_box)
map_ctrl.pack(fill=X, padx=10, pady=(8, 6))
map_auto_refresh_var = tk.BooleanVar(value=False)
ttk.Checkbutton(
map_ctrl, text="自动刷新(5s)", variable=map_auto_refresh_var
).pack(side=LEFT)
ttk.Button(map_ctrl, text="刷新映射表", width=12).pack(side=LEFT, padx=(8, 6))
# 映射内容显示区
map_view = ScrolledText(mapping_tab, wrap="none", height=12)
map_view.pack(fill=BOTH, expand=True, padx=10, pady=(6, 10))
# 加载映射表的函数(尝试多个可能的路径)
def _load_mapping_to_view():
map_view.delete("1.0", "end")
# 优先使用基于项目目录的固定路径,避免不同工作目录导致无法找到状态文件
try:
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
except Exception:
base_dir = os.getcwd()
possible_paths = [
os.path.join(base_dir, "douyin", "core", "state", "room_pos_map.json"),
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
os.path.join(base_dir, "douyin", "state", "room_pos_map.json"),
os.path.join(os.getcwd(), "douyin", "core", "state", "room_pos_map.json"),
]
found = False
for p in possible_paths:
try:
if os.path.exists(p):
with open(p, "r", encoding="utf-8") as f:
data = f.read()
# 尝试格式化 JSON,否则原样显示
try:
parsed = json.loads(data)
pretty = json.dumps(parsed, ensure_ascii=False, indent=2)
map_view.insert("end", f"# 从: {p}\n")
map_view.insert("end", pretty)
except Exception:
map_view.insert("end", f"# 从: {p}(非JSON,原始内容)\n")
map_view.insert("end", data)
found = True
break
except Exception as e:
map_view.insert("end", f"读取 {p} 失败: {e}\n")
if not found:
map_view.insert(
"end",
"未找到映射表文件。可在运行端将 '_room_pos_to_title_map' 序列化到 'douyin/core/state/room_pos_map.json',然后点击刷新以查看内容。",
)
# 绑定刷新按钮与自动刷新
btns = map_ctrl.winfo_children()
if btns and isinstance(btns[-1], ttk.Button):
btns[-1].config(command=_load_mapping_to_view)
def _maybe_auto_refresh():
if map_auto_refresh_var.get():
try:
_load_mapping_to_view()
except Exception:
pass
root.after(5000, _maybe_auto_refresh)
# 启动自动刷新轮询(无害,如果开关关闭不会频繁IO)
root.after(5000, _maybe_auto_refresh)
notebook.add(mapping_tab, text="映射表")
# 日志区
log_box = ttk.Frame(log_tab)
+1 -11
View File
@@ -455,17 +455,7 @@ def main(argv: list[str]) -> int:
seconds = int(getattr(args, "test_yanghao_flow_seconds", 10) or 10)
if seconds < 1:
seconds = 1
# 优先使用实例方法;若不存在或不可调用,则直接调用模块实现以保证向后兼容
try:
fn = getattr(analyser, "_yanghao_recommend_flow", None)
if callable(fn):
fn(seconds) # type: ignore[arg-type]
else:
from douyin.other import douyin_yanghao
douyin_yanghao.yanghao_recommend_flow(analyser, seconds)
except Exception as e:
print(f"[YANGHAO-ONLY] 调用养号流程失败: {e}")
getattr(analyser, "_yanghao_recommend_flow", lambda _: None)(seconds) # type: ignore[attr-defined]
print("[TEST] done")
return 0
+10
View File
@@ -0,0 +1,10 @@
from douyin.reservation import douyin_reservation_handler as rh
class A: pass
a = A()
a._room_pos_to_title_map = {1: ('测试直播间', '测试直播间_raw')}
try:
rh._dump_room_pos_map_to_state(a)
print('DUMP_OK')
except Exception as e:
print('DUMP_ERR', e)