From 4f74a5e95a97281f7c71c5119423e729b9235b39 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 3 Jan 2026 11:22:41 +0800 Subject: [PATCH] chore: remove generated reports and logs from repo, update .gitignore --- config/config.json | 2 +- docs/完整技术文档.md | 101 +++++- douyin/core/douyin_flow_control.py | 38 ++- douyin/core/fudai_modules/fudai_main_logic.py | 260 +++++++++------ douyin/core/state/reservations.json | 2 +- .../reservation/douyin_reservation_handler.py | 63 ++-- .../reservation/douyin_reservation_logic.py | 286 +++++++++++++---- .../reservation/douyin_reservation_verify.py | 301 +++++++++++++----- douyin/utils/douyin_helpers.py | 5 +- gui/gui_app.py | 8 +- 10 files changed, 765 insertions(+), 301 deletions(-) diff --git a/config/config.json b/config/config.json index a173eb5..7cc24ba 100644 --- a/config/config.json +++ b/config/config.json @@ -149,4 +149,4 @@ "fansclub_auto_join_wait_seconds": 5.0, "fansclub_manual_wait_seconds": 3.0, "enable_streaming_screenshot": false -} \ No newline at end of file +} diff --git a/docs/完整技术文档.md b/docs/完整技术文档.md index b5ec8da..c43aa25 100644 --- a/docs/完整技术文档.md +++ b/docs/完整技术文档.md @@ -56,6 +56,32 @@ python run_cli.py --device-id --wait-minutes 0 示例:通过命令行临时指定设备优先于 `config/config.json` 中的默认设备。 +实现建议与样例: + +- 在 `douyin/utils/douyin_config.py` 中实现 `load_config_from_file(path)` 返回 dict,主流程使用该 dict 初始化分析器并在 `run_cli.py` 中用命令行覆盖字段。 +- 推荐在 `config/config.json` 中采用明确分组,例如: + +```json +{ + "device": { "default_device": "emulator-5554" }, + "logging": { "level": "INFO", "file_path": "logs/unified.log" }, + "debug_captures": { "enabled": false, "max_files": 100 } +} +``` + +- 命令行覆盖示例(`run_cli.py` 中解析后合并): + +```python +# pseudo +config = load_config() +if args.device_id: + config['device']['default_device'] = args.device_id +``` + +错误处理与回退策略:当 `config/config.json` 不存在或字段缺失时: +- 使用代码内默认值并在日志中写 warning; +- 在关键字段(如 `device`、`ocr_engine`)缺失时中断并提示用户。 + 关联文件:`config/config.json`,`douyin/utils/douyin_config.py`,`path_config.py`,`run_cli.py`。 ## 截图 / OCR / 日志 / 状态(实现细节与故障采样) @@ -81,26 +107,61 @@ python run_cli.py --device-id --wait-minutes 0 - `debug_captures`:`enabled`、`keep_days`、`max_files`、`auto_cleanup` 用于调试图片的保存与清理。 - 建议:生产默认禁用大量 debug captures,CI/调试时开启并限制 `max_files`。日志需包含 `traceId/device_id/stage` 字段以便聚合分析。 +常见日志/截图故障与排查命令: + +- 截图失败(设备无法连接或 `adb` 权限问题): + +```powershell +adb devices +adb -s shell screencap -p /sdcard/test.png && adb -s pull /sdcard/test.png .\ +``` + +- 截图文件被占用/半写入(Windows 文件锁问题):检查进程并清理临时文件: + +```powershell +Get-Process | Where-Object { $_.Path -like '*python*' } +Remove-Item pic\screenshot.png.tmp -Force -ErrorAction SilentlyContinue +``` + +- OCR 未初始化或识别异常: + +```python +from Underlying_Operations import underlying_operations +op = underlying_operations() +op._ensure_ocr() +print(op.analyse_pic_word('pic/screenshot.png')) +``` + 4) 状态文件(预约) - 持久化路径:通过 `path_config.get_reservations_path()` 返回 `state/reservations.json`。 -- 行为说明:当前实现“首次运行清空内存预约以避免历史污染,后续运行以内存队列为主并在变更时写回文件以供外部查看”。请在运维手册中明确该语义并在需要保留历史时修改启动策略。 +- 行为说明:当前实现“首次运行清空内存预约以避免历史污染,后续运行使用内存队列并在变更时写回文件以供外部查看”。若需保留历史,可添加 `--preserve-reservations` 启动开关或修改加载逻辑。 -5) 故障采样与自动化收集(建议步骤与脚本) +5) 故障采样与自动化收集(建议步骤) - 已提供:`tools/scan_coords.py`(扫描仓库中疑似硬编码坐标/ROI,输出 `tools/coords_report.csv`)。 -- 建议采样流程(手动或自定义脚本): - 1. 运行短时主流程以产生调试图片: + +推荐采样流程(避免自动大量归档): + +1) 在短时间窗口运行主流程以生成调试图片和日志(注意 `debug_captures.enabled`): ```powershell python run_cli.py --device-id --wait-minutes 1 ``` - 2. 手动或使用团队自定义脚本筛选 `pic/` 目录下的异常输出(例如包含 `ocr`/`analyse` 关键字或根据日志时间窗口),并将样本复制到团队约定的样本目录(例如 `tools/samples/`)。 +2) 基于日志时间戳筛选 `pic/` 下的候选图片(示例:按文件修改时间): - 3. 记录对应的运行日志与 `pic` 路径以便人工复核或用于训练样本。 +```powershell +Get-ChildItem -Recurse pic\*.png | Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-1) } +``` -- 快速检查命令(采样与诊断): +3) 根据识别结果或文件名(包含 `ocr`、`digits`、`预处理` 等关键词)手动或用小脚本筛选出低置信度或异常样本,复制到团队约定目录(例如 `tools/samples/`)。 + +4) 生成小型清单(CSV)记录样本来源与日志行号,便于人工复核。 + +注:避免一次性将大量样本提交到仓库,建议只保留小样本或使用内部 artifact 存储。 + +快速检查命令: ```powershell # 扫描仓库硬编码坐标 @@ -110,6 +171,32 @@ python tools/scan_coords.py powershell -Command "Get-Content tools/coords_report.csv -TotalCount 200 | Out-File -Encoding utf8 tools/coords_report_head.csv" ``` +--- + +## 验证清单(可纳入 CI) + +最小验证覆盖: + +- 语法检查(所有 Python 文件): + +```bash +python -m py_compile $(git ls-files "**/*.py") +``` + +- 关键文件存在性检查:确保 `run_cli.py`、`Underlying_Operations.py`、`config/config.json`、`path_config.py` 存在并可被导入。 + +示例 CI 脚本片段: + +```bash +python -m py_compile $(git ls-files "**/*.py") || exit 1 +python - <<'PY' +from path_config import get_reservations_path +import os +print('reservations path', get_reservations_path()) +assert os.path.isdir(os.path.dirname(get_reservations_path())) +PY +``` + 6) 参考实现与文件链接 - 截图与裁剪:`Underlying_Operations.get_screenshot()`、`Underlying_Operations.cut_pic()`。 diff --git a/douyin/core/douyin_flow_control.py b/douyin/core/douyin_flow_control.py index b93b500..4bb05c5 100644 --- a/douyin/core/douyin_flow_control.py +++ b/douyin/core/douyin_flow_control.py @@ -142,7 +142,9 @@ def find_and_open_fudai_detail( cur = int(getattr(analyser, "_consecutive_no_fudai_count", 0) or 0) cur += 1 setattr(analyser, "_consecutive_no_fudai_count", cur) - threshold = int(getattr(analyser, "fudai_exit_after_misses", 0) or 0) or None + threshold = ( + int(getattr(analyser, "fudai_exit_after_misses", 0) or 0) or None + ) if threshold is None or threshold <= 0: # 如果未配置阈值,则尝试读取配置属性(兼容性) try: @@ -152,7 +154,9 @@ def find_and_open_fudai_detail( if cfg_path and os.path.exists(cfg_path): with open(cfg_path, "r", encoding="utf-8") as f: cfg = json.load(f) - threshold = int(cfg.get("fudai_exit_after_misses", 30) or 30) + threshold = int( + cfg.get("fudai_exit_after_misses", 30) or 30 + ) except Exception: threshold = 30 # 如果计数达到阈值,执行返回键退出直播间并重置计数 @@ -331,7 +335,7 @@ def find_and_open_fudai_detail( setattr(analyser, "_consecutive_no_fudai_count", 0) except Exception: pass - + elapsed = time.time() - func_start_time analyser._log_kv( "流程", @@ -521,7 +525,9 @@ def handle_no_fudai_situation( handled_reservation = False seek_callback = seek_reservation_room_callback or (lambda item: False) reservation_after_action_pending_ref = ( - reservation_after_action_pending_ref if reservation_after_action_pending_ref else [False] + reservation_after_action_pending_ref + if reservation_after_action_pending_ref + else [False] ) reservation_back_swipe_delay_s = ( reservation_back_swipe_delay_s @@ -532,17 +538,19 @@ def handle_no_fudai_situation( try: from douyin.reservation import douyin_reservation_logic - handled_reservation = douyin_reservation_logic.process_reservation_attend_window( - analyser, - reservations, - room_pos, - reservation_focus_until_ts_ref, - reservation_after_action_pending_ref, - reservation_back_swipe_delay_s, - swipe_down_back_callback, - seek_callback, - sort_reservations_callback, - write_state_callback, + handled_reservation = ( + douyin_reservation_logic.process_reservation_attend_window( + analyser, + reservations, + room_pos, + reservation_focus_until_ts_ref, + reservation_after_action_pending_ref, + reservation_back_swipe_delay_s, + swipe_down_back_callback, + seek_callback, + sort_reservations_callback, + write_state_callback, + ) ) except Exception: handled_reservation = False diff --git a/douyin/core/fudai_modules/fudai_main_logic.py b/douyin/core/fudai_modules/fudai_main_logic.py index 0374056..7147720 100644 --- a/douyin/core/fudai_modules/fudai_main_logic.py +++ b/douyin/core/fudai_modules/fudai_main_logic.py @@ -21,6 +21,7 @@ class MainLogicMixin(BaseFudaiMixin): """增强版日志记录:自动添加时间戳、设备ID等通用字段。""" try: from douyin.logging import douyin_logging_wrapper + douyin_logging_wrapper.LoggingWrapper.enhanced_log_kv(self, *args, **fields) except Exception: # 兜底:如果增强日志失败,使用标准日志 @@ -34,7 +35,7 @@ class MainLogicMixin(BaseFudaiMixin): "性能", f"{step_name} 耗时", elapsed_seconds=round(elapsed, 2), - step=step_name + step=step_name, ) except Exception: pass @@ -47,8 +48,8 @@ class MainLogicMixin(BaseFudaiMixin): wait_minutes: int = 15, ) -> None: """兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。""" - self.device_id = device_id or getattr(self, 'device_id', "") - self.y_pianyi = int(y_pianyi or getattr(self, 'y_pianyi', 0)) + self.device_id = device_id or getattr(self, "device_id", "") + self.y_pianyi = int(y_pianyi or getattr(self, "y_pianyi", 0)) # 保存是否允许切换直播间的配置,供后续所有逻辑统一使用 try: self.needswitch = bool(needswitch) @@ -56,8 +57,8 @@ class MainLogicMixin(BaseFudaiMixin): # 兜底:若赋值失败,则保持原有行为(默认允许切换) self.needswitch = True try: - operation = getattr(self, 'operation', None) - if operation and hasattr(operation, 'get_device_resolution'): + operation = getattr(self, "operation", None) + if operation and hasattr(operation, "get_device_resolution"): rx, ry = operation.get_device_resolution(self.device_id) self.resolution_ratio_x, self.resolution_ratio_y = int(rx or 1080), int( ry or 2400 @@ -74,43 +75,67 @@ class MainLogicMixin(BaseFudaiMixin): import json import time as time_module from path_config import get_debug_log_path + current_ts = int(time_module.time() * 1000) - with open(get_debug_log_path(), 'a', encoding='utf-8') as f: - f.write(json.dumps({ - "id": f"log_{current_ts}_load_config_call", - "timestamp": current_ts, - "location": "fudai_main_logic.py:73", - "message": "调用 load_config 方法", - "data": {"method": "load_config", "action": "call"}, - "sessionId": "debug-session", - "runId": "call_check_run1", - "hypothesisId": "call_check_hyp2" - }) + '\n') + with open(get_debug_log_path(), "a", encoding="utf-8") as f: + f.write( + json.dumps( + { + "id": f"log_{current_ts}_load_config_call", + "timestamp": current_ts, + "location": "fudai_main_logic.py:73", + "message": "调用 load_config 方法", + "data": {"method": "load_config", "action": "call"}, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp2", + } + ) + + "\n" + ) # #endregion self._safe_operation_call("load_config") # 主循环 # #region agent log - with open(get_debug_log_path(), 'a', encoding='utf-8') as f: - f.write(json.dumps({ - "id": f"log_{current_ts}_run_once_basic_call", - "timestamp": current_ts, - "location": "fudai_main_logic.py:76", - "message": "调用 run_once_basic 方法", - "data": {"method": "run_once_basic", "action": "call"}, - "sessionId": "debug-session", - "runId": "call_check_run1", - "hypothesisId": "call_check_hyp2" - }) + '\n') + with open(get_debug_log_path(), "a", encoding="utf-8") as f: + f.write( + json.dumps( + { + "id": f"log_{current_ts}_run_once_basic_call", + "timestamp": current_ts, + "location": "fudai_main_logic.py:76", + "message": "调用 run_once_basic 方法", + "data": {"method": "run_once_basic", "action": "call"}, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp2", + } + ) + + "\n" + ) # #endregion self._safe_operation_call("run_once_basic") def _handle_reservation_direct_attend(self) -> None: """预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。""" - from douyin.reservation import douyin_reservation_handler - douyin_reservation_handler.ReservationHandler.handle_reservation_direct_attend( - self - ) + try: + from douyin.reservation.douyin_reservation_handler import ( + ReservationHandler, + ) + + ReservationHandler.handle_reservation_direct_attend(self) + except Exception: + # 兜底导入:尝试旧式导入以兼容不同包结构 + try: + from douyin.reservation import douyin_reservation_handler + + douyin_reservation_handler.ReservationHandler.handle_reservation_direct_attend( + self + ) + except Exception: + # 最终兜底不抛异常 + pass def _handle_in_fudai_detail(self) -> None: """已经在福袋详情页:执行点击参与福袋的核心逻辑。""" @@ -119,17 +144,26 @@ class MainLogicMixin(BaseFudaiMixin): # #region agent log import json from path_config import get_debug_log_path - with open(get_debug_log_path(), 'a', encoding='utf-8') as f: - f.write(json.dumps({ - "id": f"log_{int(start_time * 1000)}_call_check", - "timestamp": int(start_time * 1000), - "location": "fudai_main_logic.py:85", - "message": "开始检查 _handle_in_fudai_detail 方法调用", - "data": {"method": "_handle_in_fudai_detail", "action": "start"}, - "sessionId": "debug-session", - "runId": "call_check_run1", - "hypothesisId": "call_check_hyp1" - }) + '\n') + + with open(get_debug_log_path(), "a", encoding="utf-8") as f: + f.write( + json.dumps( + { + "id": f"log_{int(start_time * 1000)}_call_check", + "timestamp": int(start_time * 1000), + "location": "fudai_main_logic.py:85", + "message": "开始检查 _handle_in_fudai_detail 方法调用", + "data": { + "method": "_handle_in_fudai_detail", + "action": "start", + }, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp1", + } + ) + + "\n" + ) # #endregion try: @@ -137,51 +171,78 @@ class MainLogicMixin(BaseFudaiMixin): from douyin.fudai import douyin_fudai_core # #region agent log - with open(get_debug_log_path(), 'a', encoding='utf-8') as f: - f.write(json.dumps({ - "id": f"log_{int(start_time * 1000)}_import_check", - "timestamp": int(start_time * 1000), - "location": "fudai_main_logic.py:91", - "message": "导入 douyin_fudai_core 模块成功", - "data": {"module": "douyin.fudai.douyin_fudai_core", "status": "imported"}, - "sessionId": "debug-session", - "runId": "call_check_run1", - "hypothesisId": "call_check_hyp1" - }) + '\n') + with open(get_debug_log_path(), "a", encoding="utf-8") as f: + f.write( + json.dumps( + { + "id": f"log_{int(start_time * 1000)}_import_check", + "timestamp": int(start_time * 1000), + "location": "fudai_main_logic.py:91", + "message": "导入 douyin_fudai_core 模块成功", + "data": { + "module": "douyin.fudai.douyin_fudai_core", + "status": "imported", + }, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp1", + } + ) + + "\n" + ) # #endregion # 检查方法是否存在 # #region agent log - with open(get_debug_log_path(), 'a', encoding='utf-8') as f: - f.write(json.dumps({ - "id": f"log_{int(start_time * 1000)}_method_check", - "timestamp": int(start_time * 1000), - "location": "fudai_main_logic.py:93", - "message": "检查 attend_choujiang 方法存在性", - "data": { - "method_exists": hasattr(douyin_fudai_core, 'attend_choujiang'), - "module_attrs": [attr for attr in dir(douyin_fudai_core) if 'attend' in attr.lower()] - }, - "sessionId": "debug-session", - "runId": "call_check_run1", - "hypothesisId": "call_check_hyp1" - }) + '\n') + with open(get_debug_log_path(), "a", encoding="utf-8") as f: + f.write( + json.dumps( + { + "id": f"log_{int(start_time * 1000)}_method_check", + "timestamp": int(start_time * 1000), + "location": "fudai_main_logic.py:93", + "message": "检查 attend_choujiang 方法存在性", + "data": { + "method_exists": hasattr( + douyin_fudai_core, "attend_choujiang" + ), + "module_attrs": [ + attr + for attr in dir(douyin_fudai_core) + if "attend" in attr.lower() + ], + }, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp1", + } + ) + + "\n" + ) # #endregion attend_result = douyin_fudai_core.attend_choujiang(self) # #region agent log - with open(get_debug_log_path(), 'a', encoding='utf-8') as f: - f.write(json.dumps({ - "id": f"log_{int(start_time * 1000)}_method_call", - "timestamp": int(start_time * 1000), - "location": "fudai_main_logic.py:93", - "message": "调用 attend_choujiang 方法完成", - "data": {"method": "attend_choujiang", "result": attend_result}, - "sessionId": "debug-session", - "runId": "call_check_run1", - "hypothesisId": "call_check_hyp1" - }) + '\n') + with open(get_debug_log_path(), "a", encoding="utf-8") as f: + f.write( + json.dumps( + { + "id": f"log_{int(start_time * 1000)}_method_call", + "timestamp": int(start_time * 1000), + "location": "fudai_main_logic.py:93", + "message": "调用 attend_choujiang 方法完成", + "data": { + "method": "attend_choujiang", + "result": attend_result, + }, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp1", + } + ) + + "\n" + ) # #endregion if attend_result: @@ -191,17 +252,22 @@ class MainLogicMixin(BaseFudaiMixin): except Exception as e: # #region agent log - with open(get_debug_log_path(), 'a', encoding='utf-8') as f: - f.write(json.dumps({ - "id": f"log_{int(start_time * 1000)}_error", - "timestamp": int(start_time * 1000), - "location": "fudai_main_logic.py:100", - "message": "_handle_in_fudai_detail 执行异常", - "data": {"error": str(e), "error_type": type(e).__name__}, - "sessionId": "debug-session", - "runId": "call_check_run1", - "hypothesisId": "call_check_hyp1" - }) + '\n') + with open(get_debug_log_path(), "a", encoding="utf-8") as f: + f.write( + json.dumps( + { + "id": f"log_{int(start_time * 1000)}_error", + "timestamp": int(start_time * 1000), + "location": "fudai_main_logic.py:100", + "message": "_handle_in_fudai_detail 执行异常", + "data": {"error": str(e), "error_type": type(e).__name__}, + "sessionId": "debug-session", + "runId": "call_check_run1", + "hypothesisId": "call_check_hyp1", + } + ) + + "\n" + ) # #endregion self._safe_log("错误", "_handle_in_fudai_detail 执行失败", error=str(e)) @@ -214,7 +280,7 @@ class MainLogicMixin(BaseFudaiMixin): self._safe_log( "性能", "_handle_in_fudai_detail 耗时", - elapsed_seconds=round(elapsed, 2) + elapsed_seconds=round(elapsed, 2), ) self._last_perf_log_time = current_time @@ -223,6 +289,7 @@ class MainLogicMixin(BaseFudaiMixin): try: # 使用 flow_control 来查找和打开福袋 import douyin.core.douyin_flow_control as douyin_flow_control + room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)] opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref) @@ -233,7 +300,9 @@ class MainLogicMixin(BaseFudaiMixin): except Exception: pass self._handle_in_fudai_detail() - self._safe_log("流程", "_handle_live_room_has_or_not_fudai:成功处理福袋") + self._safe_log( + "流程", "_handle_live_room_has_or_not_fudai:成功处理福袋" + ) else: # 无福袋,交给 flow_control 的"无福袋处理"逻辑 # 根据配置决定是否允许切换直播间(needswitch=False 时只等待不切房) @@ -267,7 +336,12 @@ class MainLogicMixin(BaseFudaiMixin): reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref, swipe_times_ref=swipe_times_ref, ) - self._safe_log("流程", "_handle_live_room_has_or_not_fudai:未找到福袋,已处理切换逻辑") + self._safe_log( + "流程", + "_handle_live_room_has_or_not_fudai:未找到福袋,已处理切换逻辑", + ) except Exception as e: - self._safe_log("错误", "_handle_live_room_has_or_not_fudai 执行失败", error=str(e)) + self._safe_log( + "错误", "_handle_live_room_has_or_not_fudai 执行失败", error=str(e) + ) diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index cababdb..d093919 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,5 +1,5 @@ { - "updated_ts": 1767383746.067418, + "updated_ts": 1767410552.1208727, "reason": "startup_clear", "room_pos": 0, "current_room_title": "", diff --git a/douyin/reservation/douyin_reservation_handler.py b/douyin/reservation/douyin_reservation_handler.py index 07af78c..51fd466 100644 --- a/douyin/reservation/douyin_reservation_handler.py +++ b/douyin/reservation/douyin_reservation_handler.py @@ -198,31 +198,8 @@ class ReservationHandler: pass # 记录到映射表 - if room_pos not in analyser._room_pos_to_title_map: - analyser._room_pos_to_title_map[room_pos] = ( - room_title, - room_title_raw, - ) - try: - analyser._log_kv( # type: ignore[attr-defined] - "预约", - "[预约] 记录直播间标题和位置到运行时映射表", - log_type="OP", - room_pos=room_pos, - room_title=room_title[:50] if room_title else "", - room_title_raw=( - room_title_raw[:50] if room_title_raw else "" - ), - map_size=len(analyser._room_pos_to_title_map), - ) - except Exception: - pass - except Exception: - pass - else: - # 如果已存在,更新标题(可能标题有变化) - old_title, old_title_raw = analyser._room_pos_to_title_map[room_pos] - if old_title != room_title or old_title_raw != room_title_raw: + try: + if room_pos not in getattr(analyser, "_room_pos_to_title_map", {}): analyser._room_pos_to_title_map[room_pos] = ( room_title, room_title_raw, @@ -230,23 +207,41 @@ class ReservationHandler: try: analyser._log_kv( # type: ignore[attr-defined] "预约", - "[预约] 更新直播间标题和位置到运行时映射表", + "[预约] 记录直播间标题和位置到运行时映射表", log_type="OP", room_pos=room_pos, - old_room_title=old_title[:50] if old_title else "", - new_room_title=room_title[:50] if room_title else "", + room_title=room_title[:50] if room_title else "", + room_title_raw=(room_title_raw[:50] if room_title_raw else ""), + map_size=len(getattr(analyser, "_room_pos_to_title_map", {})), ) except Exception: pass + else: + # 如果已存在,更新标题(可能标题有变化) + old_title, old_title_raw = analyser._room_pos_to_title_map[room_pos] + if old_title != room_title or old_title_raw != room_title_raw: + analyser._room_pos_to_title_map[room_pos] = ( + room_title, + room_title_raw, + ) + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 更新直播间标题和位置到运行时映射表", + log_type="OP", + room_pos=room_pos, + old_room_title=old_title[:50] if old_title else "", + new_room_title=room_title[:50] if room_title else "", + ) + except Exception: + pass + except Exception: + pass except Exception as e: # 如果读取标题失败,尝试使用缓存的标题 try: - room_title = str( - getattr(analyser, "current_room_title", "") or "" - ) - room_title_raw = str( - getattr(analyser, "current_room_title_raw", "") or "" - ) + room_title = str(getattr(analyser, "current_room_title", "") or "") + room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "") if room_title or room_title_raw: analyser._room_pos_to_title_map[room_pos] = ( room_title, diff --git a/douyin/reservation/douyin_reservation_logic.py b/douyin/reservation/douyin_reservation_logic.py index 5adb128..3289c32 100644 --- a/douyin/reservation/douyin_reservation_logic.py +++ b/douyin/reservation/douyin_reservation_logic.py @@ -28,6 +28,7 @@ if TYPE_CHECKING: format_reservation_context, validate_reservation_item, ) + _RESERVATION_ERROR_UTILS_AVAILABLE = True else: try: @@ -37,6 +38,7 @@ else: format_reservation_context, validate_reservation_item, ) + _RESERVATION_ERROR_UTILS_AVAILABLE = True except Exception: # 运行时回退到通用占位实现(使用宽松签名以兼容各种调用) @@ -56,6 +58,7 @@ else: # 为兼容类型检查,将实际导入或占位函数转换为 Any(避免赋值/导入时的类型不匹配报错) from typing import Any as _Any, cast + log_reservation_error = cast(_Any, log_reservation_error) safe_write_state = cast(_Any, safe_write_state) format_reservation_context = cast(_Any, format_reservation_context) @@ -80,7 +83,18 @@ def _normalize_room_title_for_matching(title: str) -> str: s = str(title).replace("\r", " ").replace("\n", " ").strip() s = re.sub(r"\s+", "", s) # 去除常见无关词 - for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"): + for w in ( + "点赞", + "赞", + "关注", + "粉丝", + "直播中", + "正在直播", + "进入直播间", + "推荐", + "在线", + "人在线", + ): s = s.replace(w, "") # 去除数字和特殊字符,只保留中文、英文、数字(但去除末尾的数字) # 先去除末尾的数字(如 "王媛媛2" -> "王媛媛") @@ -113,7 +127,11 @@ def _calculate_string_similarity(s1: str, s2: str) -> float: jaccard = intersection / union # 如果长度相近,额外加分 - len_ratio = min(len(s1), len(s2)) / max(len(s1), len(s2)) if max(len(s1), len(s2)) > 0 else 0.0 + len_ratio = ( + min(len(s1), len(s2)) / max(len(s1), len(s2)) + if max(len(s1), len(s2)) > 0 + else 0.0 + ) # 综合相似度(Jaccard占70%,长度比例占30%) similarity = jaccard * 0.7 + len_ratio * 0.3 @@ -181,7 +199,12 @@ def add_reservation_core_logic( # 添加函数入口日志 try: from datetime import datetime - ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" + + ft_str = ( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "无效" + ) analyser._log_kv( "预约", "[预约] add_reservation_core_logic 函数入口", @@ -205,7 +228,9 @@ def add_reservation_core_logic( ) else: try: - analyser._log_kv("预约", "[预约] 记录函数入口日志失败", log_type="ERR", error=str(e)) + analyser._log_kv( + "预约", "[预约] 记录函数入口日志失败", log_type="ERR", error=str(e) + ) except Exception: pass @@ -222,7 +247,7 @@ def add_reservation_core_logic( # 1. (future_ts, content) 相同,且直播间名字相同(规范化后) # 2. 或者 (future_ts, content) 相同(兼容旧数据,没有直播间名字的情况) # 3. 或者通过相似度匹配:直播间名称相似 + 开奖时间相近 + 奖品价值相同 + 内容核心部分相似 - is_same_future_and_content = (r_ft == ft and r_content == content) + is_same_future_and_content = r_ft == ft and r_content == content is_same_room_title = ( room_title_normalized and r_room_title_normalized @@ -259,7 +284,9 @@ def add_reservation_core_logic( content_core = _extract_content_core(content) r_content_core = _extract_content_core(r_content) if content_core and r_content_core: - content_similarity = _calculate_string_similarity(content_core, r_content_core) + content_similarity = _calculate_string_similarity( + content_core, r_content_core + ) is_similar_content = content_similarity >= 0.7 # 判断是否为同一个预约 @@ -274,7 +301,9 @@ def add_reservation_core_logic( same_idx = idx break # 如果只有一个有直播间名字,也视为同一个预约(兼容旧数据) - elif (room_title_normalized and not r_room_title_normalized) or (not room_title_normalized and r_room_title_normalized): + elif (room_title_normalized and not r_room_title_normalized) or ( + not room_title_normalized and r_room_title_normalized + ): same_idx = idx break # 如果直播间名称相同(规范化后)且价值相同,即使时间差稍大也视为重复 @@ -285,8 +314,8 @@ def add_reservation_core_logic( if analyser: analyser._log_kv( "预约", - "[预约] 通过直播间名称和价值匹配识别为重复预约", - log_type="OP", + "[预约] 通过直播间名称和价值匹配识别为重复预约", + log_type="OP", room_title_normalized=room_title_normalized, time_diff=round(time_diff, 2), prize_value_yuan=prize_value, @@ -294,15 +323,20 @@ def add_reservation_core_logic( except Exception: pass break - elif is_similar_room_title and is_similar_time and is_same_prize_value and is_similar_content: + elif ( + is_similar_room_title + and is_similar_time + and is_same_prize_value + and is_similar_content + ): # 通过相似度匹配判断为同一个预约(处理OCR误差) same_idx = idx try: if analyser: analyser._log_kv( "预约", - "[预约] 通过相似度匹配识别为重复预约", - log_type="OP", + "[预约] 通过相似度匹配识别为重复预约", + log_type="OP", room_title_normalized=room_title_normalized, r_room_title_normalized=r_room_title_normalized, time_diff=round(time_diff, 2), @@ -466,7 +500,9 @@ def add_reservation_core_logic( ) else: try: - analyser._log_kv("预约", "[预约] 记录函数完成日志失败", log_type="ERR", error=str(e)) + analyser._log_kv( + "预约", "[预约] 记录函数完成日志失败", log_type="ERR", error=str(e) + ) except Exception: pass @@ -510,12 +546,14 @@ def cleanup_expired_reservations( try: r_ft = float(r.get("future_ts") or 0.0) if r_ft <= now_ts_drop: - dropped_items_detail.append({ - "future_ts": int(r_ft), - "prize_value_yuan": float(r.get("prize_value_yuan", 0)), - "content": str(r.get("content", ""))[:50], - "room_title": str(r.get("room_title", ""))[:30], - }) + dropped_items_detail.append( + { + "future_ts": int(r_ft), + "prize_value_yuan": float(r.get("prize_value_yuan", 0)), + "content": str(r.get("content", ""))[:50], + "room_title": str(r.get("room_title", ""))[:30], + } + ) except Exception: pass @@ -527,7 +565,10 @@ def cleanup_expired_reservations( if dropped: try: from datetime import datetime - now_str = datetime.fromtimestamp(now_ts_drop).strftime("%Y-%m-%d %H:%M:%S") + + now_str = datetime.fromtimestamp(now_ts_drop).strftime( + "%Y-%m-%d %H:%M:%S" + ) analyser._log_kv( "预约", "[预约] cleanup_expired_reservations:清理过期预约", @@ -646,7 +687,10 @@ def handle_queue_full_wait_at_earliest( if focus_until > 0 and now_ts < focus_until: try: from datetime import datetime - focus_until_str = datetime.fromtimestamp(focus_until).strftime("%Y-%m-%d %H:%M:%S") + + focus_until_str = datetime.fromtimestamp(focus_until).strftime( + "%Y-%m-%d %H:%M:%S" + ) analyser._log_kv( "预约", "[预约] handle_queue_full_wait_at_earliest:已在锁定期内,跳过回退", @@ -708,7 +752,9 @@ def handle_queue_full_wait_at_earliest( time.sleep(0.5) # 重新截图并再次诊断,确保已处理 try: - analyser.operation.get_screenshot(analyser.device_id, use_service=False) + analyser.operation.get_screenshot( + analyser.device_id, use_service=False + ) except Exception: pass result = douyin_stage.diagnose_stage_from_current_screen(analyser) @@ -802,7 +848,12 @@ def handle_queue_full_wait_at_earliest( try: from datetime import datetime - ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" + + ft_str = ( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "无效" + ) analyser._log_kv( "预约", "[预约] 已回退到最早开奖的预约直播间,立即参与(不等待开奖窗口)", @@ -922,7 +973,9 @@ def process_reservation_attend_window( # 检查是否已经参与过该预约(通过 _participated_fudai_future_ts) try: - participated_fudai_ts = getattr(analyser, "_participated_fudai_future_ts", set()) + participated_fudai_ts = getattr( + analyser, "_participated_fudai_future_ts", set() + ) if not isinstance(participated_fudai_ts, set): participated_fudai_ts = set() # 检查是否已经参与过(允许5秒误差) @@ -976,7 +1029,12 @@ def process_reservation_attend_window( # 添加目标预约的详细信息日志 try: from datetime import datetime - ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" + + ft_str = ( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "无效" + ) analyser._log_kv( "预约", "[预约] process_reservation_attend_window 获取目标预约", @@ -1055,12 +1113,25 @@ def process_reservation_attend_window( # 添加详细的调试日志:记录锁定期状态和时间窗口检查结果 try: from datetime import datetime + now_str = datetime.fromtimestamp(now_ts).strftime("%Y-%m-%d %H:%M:%S") time_window_start_ts = ft - dynamic_ahead - time_window_start_str = datetime.fromtimestamp(time_window_start_ts).strftime("%Y-%m-%d %H:%M:%S") if time_window_start_ts > 0 else "无效" + time_window_start_str = ( + datetime.fromtimestamp(time_window_start_ts).strftime("%Y-%m-%d %H:%M:%S") + if time_window_start_ts > 0 + else "无效" + ) time_window_end_ts = ft + max(0.0, poll_before) - time_window_end_str = datetime.fromtimestamp(time_window_end_ts).strftime("%Y-%m-%d %H:%M:%S") if time_window_end_ts > 0 else "无效" - ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" + time_window_end_str = ( + datetime.fromtimestamp(time_window_end_ts).strftime("%Y-%m-%d %H:%M:%S") + if time_window_end_ts > 0 + else "无效" + ) + ft_str = ( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "无效" + ) analyser._log_kv( "预约", @@ -1079,7 +1150,11 @@ def process_reservation_attend_window( time_window_end=int(time_window_end_ts), time_window_end_str=time_window_end_str, remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, - remain_seconds_to_window=int(time_window_start_ts - now_ts) if time_window_start_ts > now_ts else 0, + remain_seconds_to_window=( + int(time_window_start_ts - now_ts) + if time_window_start_ts > now_ts + else 0 + ), in_lock_period=bool(focus_until > 0 and now_ts < focus_until), in_time_window=bool(now_ts >= time_window_start_ts), passed_time_window=bool(now_ts > time_window_end_ts), @@ -1097,13 +1172,20 @@ def process_reservation_attend_window( # 先检查是否是队列满立即参与模式 is_queue_full_immediate_attend_check = False try: - queue_full_waiting_check = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False) + queue_full_waiting_check = bool( + getattr(analyser, "queue_full_waiting_at_earliest", False) or False + ) if queue_full_waiting_check: is_queue_full_immediate_attend_check = True except Exception: pass - if focus_until > 0 and now_ts < focus_until and abs(focus_until - now_ts) > 1.0 and not is_queue_full_immediate_attend_check: + if ( + focus_until > 0 + and now_ts < focus_until + and abs(focus_until - now_ts) > 1.0 + and not is_queue_full_immediate_attend_check + ): # 锁定期还没结束,检查是否是同一个预约(允许5秒误差) expected_focus_until = ft + max(0.0, poll_before) if abs(focus_until - expected_focus_until) > 5.0: @@ -1124,7 +1206,9 @@ def process_reservation_attend_window( # 但这里通常已经在目标直播间了,需要检查是否已经在目标位置 # 获取当前实际的 room_pos(可能已经被更新) try: - current_room_pos_check = int(getattr(analyser, "room_pos", room_pos) or room_pos) + current_room_pos_check = int( + getattr(analyser, "room_pos", room_pos) or room_pos + ) except Exception: current_room_pos_check = int(room_pos) @@ -1142,14 +1226,18 @@ def process_reservation_attend_window( # 检查是否是队列满立即参与模式 is_queue_full_immediate_attend_pos = False try: - queue_full_waiting_pos = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False) + queue_full_waiting_pos = bool( + getattr(analyser, "queue_full_waiting_at_earliest", False) or False + ) if queue_full_waiting_pos: is_queue_full_immediate_attend_pos = True except Exception: pass # 检查时间窗口是否到达,或者是队列满立即参与模式 - if is_queue_full_immediate_attend_pos or (now_ts >= ft - dynamic_ahead and now_ts <= ft + max(0.0, poll_before)): + if is_queue_full_immediate_attend_pos or ( + now_ts >= ft - dynamic_ahead and now_ts <= ft + max(0.0, poll_before) + ): # 时间窗口已到达或队列满立即参与模式,虽然已在目标位置,但需要参与,返回 True try: analyser._log_kv( @@ -1226,7 +1314,9 @@ def process_reservation_attend_window( is_queue_full_immediate_attend = False try: # 检查队列满等待标志 - queue_full_waiting = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False) + queue_full_waiting = bool( + getattr(analyser, "queue_full_waiting_at_earliest", False) or False + ) if queue_full_waiting: is_queue_full_immediate_attend = True try: @@ -1245,8 +1335,15 @@ def process_reservation_attend_window( # 还没到窗口(非队列满立即参与模式) try: from datetime import datetime + time_window_start_ts = ft - dynamic_ahead - time_window_start_str = datetime.fromtimestamp(time_window_start_ts).strftime("%Y-%m-%d %H:%M:%S") if time_window_start_ts > 0 else "无效" + time_window_start_str = ( + datetime.fromtimestamp(time_window_start_ts).strftime( + "%Y-%m-%d %H:%M:%S" + ) + if time_window_start_ts > 0 + else "无效" + ) analyser._log_kv( "预约", "[预约] 时间窗口未到,跳过回退", @@ -1369,11 +1466,15 @@ def process_reservation_attend_window( "[预约] process_reservation_attend_window:回退操作成功,准备进行回退校验", target_pos=int(target.get("pos_seen", 0)), target_room_title=target_room_title[:50] if target_room_title else "", - target_room_title_raw=target_room_title_raw[:50] if target_room_title_raw else "", + target_room_title_raw=( + target_room_title_raw[:50] if target_room_title_raw else "" + ), target_content=target_content[:50] if target_content else "", target_value_yuan=target_value, current_room_pos=int(room_pos), - reservation_back_verify_enabled=bool(getattr(analyser, "reservation_back_verify_enabled", True)), + reservation_back_verify_enabled=bool( + getattr(analyser, "reservation_back_verify_enabled", True) + ), level="DEBUG", ) except Exception: @@ -1383,7 +1484,9 @@ def process_reservation_attend_window( verify_ok = True verify_detail = None try: - verify_enabled = bool(getattr(analyser, "reservation_back_verify_enabled", True)) + verify_enabled = bool( + getattr(analyser, "reservation_back_verify_enabled", True) + ) try: analyser._log_kv( "预约", @@ -1401,18 +1504,23 @@ def process_reservation_attend_window( "预约", "[预约] process_reservation_attend_window:开始调用回退校验函数", target_pos=int(target.get("pos_seen", 0)), - target_room_title=target_room_title[:50] if target_room_title else "", + target_room_title=( + target_room_title[:50] if target_room_title else "" + ), level="DEBUG", ) except Exception: pass from douyin.reservation import douyin_reservation_verify - verify_ok, verify_detail = douyin_reservation_verify.validate_back_to_reservation( - analyser=analyser, - item=target, - quick=False, - max_checks=3, + + verify_ok, verify_detail = ( + douyin_reservation_verify.validate_back_to_reservation( + analyser=analyser, + item=target, + quick=False, + max_checks=3, + ) ) try: @@ -1435,7 +1543,11 @@ def process_reservation_attend_window( reservations=reservations, verify_detail=verify_detail, target_pos=int(target.get("pos_seen", 0)), - target_room_title=target_room_title[:50] if target_room_title else "", + target_room_title=( + target_room_title[:50] + if target_room_title + else "" + ), ), level="WARNING", stage="回退校验", @@ -1446,7 +1558,11 @@ def process_reservation_attend_window( "预约", "[预约] 回退校验失败:回退操作成功但校验未通过,尝试根据映射表自动回退到正确位置", target_pos=int(target.get("pos_seen", 0)), - target_room_title=target_room_title[:50] if target_room_title else "", + target_room_title=( + target_room_title[:50] + if target_room_title + else "" + ), ) except Exception: pass @@ -1457,14 +1573,22 @@ def process_reservation_attend_window( correct_pos = analyser._find_room_pos_by_title( target_room_title, target_room_title_raw ) - if correct_pos is not None and correct_pos != int(target.get("pos_seen", 0)): + if correct_pos is not None and correct_pos != int( + target.get("pos_seen", 0) + ): try: analyser._log_kv( "预约", "[预约] 根据映射表找到正确位置,自动回退", - original_target_pos=int(target.get("pos_seen", 0)), + original_target_pos=int( + target.get("pos_seen", 0) + ), correct_pos=correct_pos, - target_room_title=target_room_title[:50] if target_room_title else "", + target_room_title=( + target_room_title[:50] + if target_room_title + else "" + ), ) except Exception: pass @@ -1472,15 +1596,19 @@ def process_reservation_attend_window( # 更新目标位置并重新回退 target["pos_seen"] = correct_pos try: - retry_ok = bool(seek_reservation_room_callback(target)) + retry_ok = bool( + seek_reservation_room_callback(target) + ) if retry_ok: # 重新进行校验 try: - verify_ok_retry, verify_detail_retry = douyin_reservation_verify.validate_back_to_reservation( - analyser=analyser, - item=target, - quick=False, - max_checks=3, + verify_ok_retry, verify_detail_retry = ( + douyin_reservation_verify.validate_back_to_reservation( + analyser=analyser, + item=target, + quick=False, + max_checks=3, + ) ) if verify_ok_retry: try: @@ -1488,7 +1616,11 @@ def process_reservation_attend_window( "预约", "[预约] 根据映射表自动回退后校验通过", correct_pos=correct_pos, - target_room_title=target_room_title[:50] if target_room_title else "", + target_room_title=( + target_room_title[:50] + if target_room_title + else "" + ), ) except Exception: pass @@ -1501,7 +1633,11 @@ def process_reservation_attend_window( "预约", "[预约] 根据映射表自动回退后校验仍失败", correct_pos=correct_pos, - target_room_title=target_room_title[:50] if target_room_title else "", + target_room_title=( + target_room_title[:50] + if target_room_title + else "" + ), ) except Exception: pass @@ -1543,7 +1679,11 @@ def process_reservation_attend_window( analyser._log_kv( "预约", "[预约] 映射表中未找到目标直播间,无法自动回退", - target_room_title=target_room_title[:50] if target_room_title else "", + target_room_title=( + target_room_title[:50] + if target_room_title + else "" + ), ) except Exception: pass @@ -1577,7 +1717,9 @@ def process_reservation_attend_window( "预约", "[预约] 回退校验通过:已成功回退到目标直播间并验证福袋详情", target_pos=int(target.get("pos_seen", 0)), - target_room_title=target_room_title[:50] if target_room_title else "", + target_room_title=( + target_room_title[:50] if target_room_title else "" + ), ) except Exception: pass @@ -1645,7 +1787,12 @@ def process_reservation_attend_window( try: from datetime import datetime - ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" + + ft_str = ( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "无效" + ) # 运行日志 analyser._log_kv( @@ -1669,7 +1816,11 @@ def process_reservation_attend_window( action="回退到预约直播间", result="成功", detail={ - "目标直播间": target_room_title if target_room_title else target_room_title_raw, + "目标直播间": ( + target_room_title + if target_room_title + else target_room_title_raw + ), "目标直播间原始": target_room_title_raw, "福袋内容": target_content, "福袋价值": target_value, @@ -1690,6 +1841,7 @@ def process_reservation_attend_window( # 添加函数完成日志 try: from datetime import datetime + elapsed = time.time() - start_time analyser._log_kv( "预约", @@ -1727,6 +1879,7 @@ def process_reservation_attend_window( # 添加函数完成日志 try: from datetime import datetime + elapsed = time.time() - start_time analyser._log_kv( "预约", @@ -1844,7 +1997,9 @@ def record_high_value_reservation( if not isinstance(reservations, list): if _RESERVATION_ERROR_UTILS_AVAILABLE: try: - raise TypeError(f"reservations 不是列表类型,而是 {type(reservations).__name__}") + raise TypeError( + f"reservations 不是列表类型,而是 {type(reservations).__name__}" + ) except TypeError as e: log_reservation_error( analyser, @@ -1997,7 +2152,10 @@ def record_high_value_reservation( # 记录成功日志 try: from datetime import datetime - created_str = datetime.fromtimestamp(item["created_ts"]).strftime("%Y-%m-%d %H:%M:%S") + + created_str = datetime.fromtimestamp(item["created_ts"]).strftime( + "%Y-%m-%d %H:%M:%S" + ) analyser._log_kv( "预约", "[预约] record_high_value_reservation:已记录高价值福袋", diff --git a/douyin/reservation/douyin_reservation_verify.py b/douyin/reservation/douyin_reservation_verify.py index 66fdc2d..95fe608 100644 --- a/douyin/reservation/douyin_reservation_verify.py +++ b/douyin/reservation/douyin_reservation_verify.py @@ -22,6 +22,7 @@ try: log_reservation_error, format_reservation_context, ) + _RESERVATION_ERROR_UTILS_AVAILABLE = True except ImportError: # 如果导入失败,提供占位符函数 @@ -42,7 +43,9 @@ def _compact_text(text: str) -> str: return "" -def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, Dict[str, Any]]: +def match_reservation( + item: Dict[str, Any], detail: Tuple +) -> Tuple[bool, str, Dict[str, Any]]: """校验回退后的福袋详情是否匹配预约。返回 (ok, reason, debug_dict) 参数: @@ -63,11 +66,15 @@ def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, D expected_content = _compact_text(item.get("content") or "") if not isinstance(detail, tuple) or len(detail) < 6: - return False, "detail_invalid", { - "expected_future": expected_future, - "expected_value": expected_value, - "expected_content": expected_content, - } + return ( + False, + "detail_invalid", + { + "expected_future": expected_future, + "expected_value": expected_value, + "expected_content": expected_content, + }, + ) fc, _tt, _participants, _copies, pv, cd = detail[:6] actual_content = _compact_text(fc or "") @@ -76,7 +83,9 @@ def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, D except Exception: actual_value = 0.0 try: - actual_future = float(cd[1] if (isinstance(cd, (tuple, list)) and len(cd) >= 2) else 0.0) + actual_future = float( + cd[1] if (isinstance(cd, (tuple, list)) and len(cd) >= 2) else 0.0 + ) except Exception: actual_future = 0.0 @@ -86,27 +95,35 @@ def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, D chinese_num_chars = "零一二三四五六七八九十百千两" patt = rf"(?:观看|看)(?:直播)?\s*(?:\d+|[{chinese_num_chars}]+)\s*分钟" if re.search(patt, fc_full): - return False, "watch_task_detected", { + return ( + False, + "watch_task_detected", + { + "expected_future": expected_future, + "actual_future": actual_future, + "expected_value": expected_value, + "actual_value": actual_value, + "expected_content": expected_content, + "actual_content": actual_content, + }, + ) + except Exception: + pass + + # future 必须可验证(否则无法确认回退成功) + if not (expected_future > 0 and actual_future > 0): + return ( + False, + "future_missing", + { "expected_future": expected_future, "actual_future": actual_future, "expected_value": expected_value, "actual_value": actual_value, "expected_content": expected_content, "actual_content": actual_content, - } - except Exception: - pass - - # future 必须可验证(否则无法确认回退成功) - if not (expected_future > 0 and actual_future > 0): - return False, "future_missing", { - "expected_future": expected_future, - "actual_future": actual_future, - "expected_value": expected_value, - "actual_value": actual_value, - "expected_content": expected_content, - "actual_content": actual_content, - } + }, + ) future_diff = abs(expected_future - actual_future) @@ -118,24 +135,15 @@ def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, D content_ok = False if expected_content and actual_content: - content_ok = (expected_content in actual_content) or (actual_content in expected_content) + content_ok = (expected_content in actual_content) or ( + actual_content in expected_content + ) if not (value_ok or content_ok): - return False, "content_or_value_mismatch", { - "expected_future": expected_future, - "actual_future": actual_future, - "future_diff_s": int(future_diff), - "expected_value": expected_value, - "actual_value": actual_value, - "expected_content": expected_content, - "actual_content": actual_content, - } - - # 优先用 future 精确匹配;但在"内容+价值都一致"时,允许一定范围的 future 偏差,避免 OCR 倒计时误读导致误判。 - # 说明:正常情况下 future_diff 应该很小;若 future_diff 过大仍会判不匹配。 - if future_diff > 180: - if value_ok and content_ok and future_diff <= 1200: - return True, "future_mismatch_relaxed", { + return ( + False, + "content_or_value_mismatch", + { "expected_future": expected_future, "actual_future": actual_future, "future_diff_s": int(future_diff), @@ -143,8 +151,44 @@ def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, D "actual_value": actual_value, "expected_content": expected_content, "actual_content": actual_content, - } - return False, "future_mismatch", { + }, + ) + + # 优先用 future 精确匹配;但在"内容+价值都一致"时,允许一定范围的 future 偏差,避免 OCR 倒计时误读导致误判。 + # 说明:正常情况下 future_diff 应该很小;若 future_diff 过大仍会判不匹配。 + if future_diff > 180: + if value_ok and content_ok and future_diff <= 1200: + return ( + True, + "future_mismatch_relaxed", + { + "expected_future": expected_future, + "actual_future": actual_future, + "future_diff_s": int(future_diff), + "expected_value": expected_value, + "actual_value": actual_value, + "expected_content": expected_content, + "actual_content": actual_content, + }, + ) + return ( + False, + "future_mismatch", + { + "expected_future": expected_future, + "actual_future": actual_future, + "future_diff_s": int(future_diff), + "expected_value": expected_value, + "actual_value": actual_value, + "expected_content": expected_content, + "actual_content": actual_content, + }, + ) + + return ( + True, + "ok", + { "expected_future": expected_future, "actual_future": actual_future, "future_diff_s": int(future_diff), @@ -152,17 +196,8 @@ def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, D "actual_value": actual_value, "expected_content": expected_content, "actual_content": actual_content, - } - - return True, "ok", { - "expected_future": expected_future, - "actual_future": actual_future, - "future_diff_s": int(future_diff), - "expected_value": expected_value, - "actual_value": actual_value, - "expected_content": expected_content, - "actual_content": actual_content, - } + }, + ) def validate_back_to_reservation( @@ -200,10 +235,17 @@ def validate_back_to_reservation( # 若开关关闭,则跳过复杂校验,直接认为回退成功以加速流程 try: - verify_enabled = bool(getattr(analyser, "reservation_back_verify_enabled", True)) + verify_enabled = bool( + getattr(analyser, "reservation_back_verify_enabled", True) + ) if not verify_enabled: try: - analyser._log_kv("预约", "回退校验已被禁用:跳过校验", log_type="DEBUG", level="DEBUG") + analyser._log_kv( + "预约", + "回退校验已被禁用:跳过校验", + log_type="DEBUG", + level="DEBUG", + ) except Exception: pass return True, None @@ -214,7 +256,8 @@ def validate_back_to_reservation( try: # 使用 douyin_high_value_room 中的规范化函数 from douyin.other import douyin_high_value_room - if hasattr(douyin_high_value_room, '_normalize_room_title'): + + if hasattr(douyin_high_value_room, "_normalize_room_title"): expected_title = douyin_high_value_room._normalize_room_title(item.get("room_title") or "") # type: ignore[attr-defined] else: expected_title = str(item.get("room_title") or "").strip() @@ -224,7 +267,18 @@ def validate_back_to_reservation( # 简单的规范化:去除空格和特殊字符 expected_title = re.sub(r"\s+", "", expected_title_raw_text).strip() # 去掉常见无关词 - for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"): + for w in ( + "点赞", + "赞", + "关注", + "粉丝", + "直播中", + "正在直播", + "进入直播间", + "推荐", + "在线", + "人在线", + ): expected_title = expected_title.replace(w, "") expected_title = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", expected_title) except Exception: @@ -244,8 +298,12 @@ def validate_back_to_reservation( target_pos=target_pos_seen, expected_room_title=expected_title[:50] if expected_title else "", recorded_room_title=recorded_title[:50] if recorded_title else "", - expected_room_title_raw=expected_title_raw[:50] if expected_title_raw else "", - recorded_room_title_raw=recorded_title_raw[:50] if recorded_title_raw else "", + expected_room_title_raw=( + expected_title_raw[:50] if expected_title_raw else "" + ), + recorded_room_title_raw=( + recorded_title_raw[:50] if recorded_title_raw else "" + ), ) except Exception: pass @@ -254,10 +312,15 @@ def validate_back_to_reservation( if expected_title and recorded_title: try: from douyin.other import douyin_high_value_room - if hasattr(douyin_high_value_room, '_normalize_room_title'): + + if hasattr(douyin_high_value_room, "_normalize_room_title"): expected_norm = douyin_high_value_room._normalize_room_title(expected_title) # type: ignore[attr-defined] recorded_norm = douyin_high_value_room._normalize_room_title(recorded_title) # type: ignore[attr-defined] - if expected_norm == recorded_norm or expected_norm in recorded_norm or recorded_norm in expected_norm: + if ( + expected_norm == recorded_norm + or expected_norm in recorded_norm + or recorded_norm in expected_norm + ): try: analyser._log_kv( "预约", @@ -275,7 +338,9 @@ def validate_back_to_reservation( "回退校验:运行时映射表中未找到目标位置", target_pos=target_pos_seen, map_size=len(room_pos_map), - available_positions=list(room_pos_map.keys())[:10] if room_pos_map else [], + available_positions=( + list(room_pos_map.keys())[:10] if room_pos_map else [] + ), ) except Exception: pass @@ -304,8 +369,8 @@ def validate_back_to_reservation( if expected_title: try: y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) - current_title, current_title_raw = douyin_fudai_detail.read_live_room_title_core( - analyser, y_pianyi_val + current_title, current_title_raw = ( + douyin_fudai_detail.read_live_room_title_core(analyser, y_pianyi_val) ) try: # 计算预期标题与当前标题的相似度 @@ -313,7 +378,9 @@ def validate_back_to_reservation( if current_title and expected_title: import difflib as _difflib - ratio = _difflib.SequenceMatcher(None, expected_title, current_title).ratio() + ratio = _difflib.SequenceMatcher( + None, expected_title, current_title + ).ratio() analyser._log_kv( "预约", @@ -329,12 +396,19 @@ def validate_back_to_reservation( pass # 强不匹配:根据映射表找到正确位置并回退 - if current_title and (expected_title not in current_title) and (current_title not in expected_title) and ratio < 0.45: + if ( + current_title + and (expected_title not in current_title) + and (current_title not in expected_title) + and ratio < 0.45 + ): try: analyser._log_kv( "预约", "回退校验:直播间标题不匹配,尝试根据映射表找到正确位置", - expected_title=expected_title[:50] if expected_title else "", + expected_title=( + expected_title[:50] if expected_title else "" + ), current_title=current_title[:50] if current_title else "", ratio=round(ratio, 3), ) @@ -344,15 +418,23 @@ def validate_back_to_reservation( # 根据映射表找到正确位置 try: if hasattr(analyser, "_find_room_pos_by_title"): - correct_pos = analyser._find_room_pos_by_title(expected_title, expected_title_raw) + correct_pos = analyser._find_room_pos_by_title( + expected_title, expected_title_raw + ) if correct_pos is not None: try: analyser._log_kv( "预约", "回退校验:在映射表中找到正确位置,准备回退", correct_pos=correct_pos, - current_pos=int(getattr(analyser, "room_pos", 0) or 0), - expected_title=expected_title[:50] if expected_title else "", + current_pos=int( + getattr(analyser, "room_pos", 0) or 0 + ), + expected_title=( + expected_title[:50] + if expected_title + else "" + ), ) except Exception: pass @@ -367,25 +449,50 @@ def validate_back_to_reservation( if seek_ok: # 重新读取标题验证 try: - y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) - new_title, _new_title_raw = douyin_fudai_detail.read_live_room_title_core( - analyser, y_pianyi_val + y_pianyi_val = int( + getattr(analyser, "y_pianyi", 0) + or 0 + ) + new_title, _new_title_raw = ( + douyin_fudai_detail.read_live_room_title_core( + analyser, y_pianyi_val + ) ) if new_title: new_ratio = 0.0 try: - new_ratio = float(difflib.SequenceMatcher(None, expected_title, new_title).ratio()) + new_ratio = float( + difflib.SequenceMatcher( + None, + expected_title, + new_title, + ).ratio() + ) except Exception: pass - if (expected_title in new_title) or (new_title in expected_title) or new_ratio >= 0.45: + if ( + (expected_title in new_title) + or (new_title in expected_title) + or new_ratio >= 0.45 + ): try: analyser._log_kv( "预约", "回退校验:根据映射表回退后,标题匹配成功", - expected_title=expected_title[:50] if expected_title else "", - new_title=new_title[:50] if new_title else "", - new_ratio=round(new_ratio, 3), + expected_title=( + expected_title[:50] + if expected_title + else "" + ), + new_title=( + new_title[:50] + if new_title + else "" + ), + new_ratio=round( + new_ratio, 3 + ), ) except Exception: pass @@ -395,9 +502,19 @@ def validate_back_to_reservation( analyser._log_kv( "预约", "回退校验:根据映射表回退后,标题仍不匹配", - expected_title=expected_title[:50] if expected_title else "", - new_title=new_title[:50] if new_title else "", - new_ratio=round(new_ratio, 3), + expected_title=( + expected_title[:50] + if expected_title + else "" + ), + new_title=( + new_title[:50] + if new_title + else "" + ), + new_ratio=round( + new_ratio, 3 + ), ) except Exception: pass @@ -409,7 +526,11 @@ def validate_back_to_reservation( e, format_reservation_context( item=item, - expected_title=expected_title[:50] if expected_title else "", + expected_title=( + expected_title[:50] + if expected_title + else "" + ), ), level="WARNING", stage="根据映射表回退后重新读取标题", @@ -440,7 +561,11 @@ def validate_back_to_reservation( e, format_reservation_context( item=item, - expected_title=expected_title[:50] if expected_title else "", + expected_title=( + expected_title[:50] + if expected_title + else "" + ), ), level="WARNING", stage="根据映射表回退", @@ -461,7 +586,11 @@ def validate_back_to_reservation( analyser._log_kv( "预约", "回退校验:映射表中未找到匹配的标题", - expected_title=expected_title[:50] if expected_title else "", + expected_title=( + expected_title[:50] + if expected_title + else "" + ), ) except Exception: pass @@ -482,7 +611,9 @@ def validate_back_to_reservation( e, format_reservation_context( item=item, - expected_title=expected_title[:50] if expected_title else "", + expected_title=( + expected_title[:50] if expected_title else "" + ), ), level="WARNING", stage="根据映射表查找位置", @@ -511,7 +642,9 @@ def validate_back_to_reservation( ) else: try: - analyser._log_kv("预约", "回退校验:读取直播间标题失败", error=str(e)) + analyser._log_kv( + "预约", "回退校验:读取直播间标题失败", error=str(e) + ) except Exception: pass diff --git a/douyin/utils/douyin_helpers.py b/douyin/utils/douyin_helpers.py index 1fe1fe5..9c1c92e 100644 --- a/douyin/utils/douyin_helpers.py +++ b/douyin/utils/douyin_helpers.py @@ -349,7 +349,10 @@ class HelperFunctions: shutil.copy(src, dst) analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] - "开奖结果", "已保存立即领取奖品截图", log_type="SCREENSHOT", path=dst + "开奖结果", + "已保存立即领取奖品截图", + log_type="SCREENSHOT", + path=dst, ) except Exception as e: analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] diff --git a/gui/gui_app.py b/gui/gui_app.py index 5ef620c..8747685 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -319,6 +319,10 @@ def main(): ttk.Spinbox(top, from_=-200, to=200, textvariable=y_var, width=6).pack( side=LEFT, padx=(0, 12) ) + # 连续无福袋退出阈值变量(提前声明,避免后续使用前未绑定) + fudai_exit_after_misses_var = tk.IntVar( + value=int(cfg.get("fudai_exit_after_misses", 30) or 30) + ) # 连续无福袋退出阈值(在直播间连续未找到福袋达到该次数时按返回键退出) ttk.Label(top, text="连续无福袋退出阈值:").pack(side=LEFT) ttk.Spinbox( @@ -1596,7 +1600,9 @@ def main(): bool(cfg.get("fudai_disable_content_recognition", False)) ) try: - fudai_exit_after_misses_var.set(int(cfg.get("fudai_exit_after_misses", 30) or 30)) + fudai_exit_after_misses_var.set( + int(cfg.get("fudai_exit_after_misses", 30) or 30) + ) except Exception: fudai_exit_after_misses_var.set(30) switch_room_wait_after_stage_diag_seconds_var.set(