diff --git a/Underlying_Operations.py b/Underlying_Operations.py index 3bc43ef..644d1df 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -1504,22 +1504,48 @@ class underlying_operations: # 用于收集置信度信息 ocr_confidence_info = None - if getattr(self, "ocr_type", None) == "easyocr": - result = self.ocr.readtext(img_np) - extract_result = self.extract_ocr_content(result, return_confidence=True) - if isinstance(extract_result, tuple): - text, ocr_confidence_info = extract_result + # 如果 OCR 未初始化(例如 EasyOCR/PaddleOCR 均不可用),安全降级为不识别 + try: + ocr_obj = getattr(self, "ocr", None) + ocr_type = getattr(self, "ocr_type", None) + except Exception: + ocr_obj = None + ocr_type = None + + if ocr_obj is None: + try: + logging.warning("OCR 未初始化,跳过识别:picname=%s", picname) + except Exception: + pass + return "" + + try: + if ocr_type == "easyocr": + result = ocr_obj.readtext(img_np) + extract_result = self.extract_ocr_content( + result, return_confidence=True + ) + if isinstance(extract_result, tuple): + text, ocr_confidence_info = extract_result + else: + text = extract_result else: - text = extract_result - else: - result = self.ocr.ocr(img_np) - if result == [None]: - return "" - extract_result = self.extract_ocr_content(result, return_confidence=True) - if isinstance(extract_result, tuple): - text, ocr_confidence_info = extract_result - else: - text = extract_result + result = ocr_obj.ocr(img_np) + if result == [None]: + return "" + extract_result = self.extract_ocr_content( + result, return_confidence=True + ) + if isinstance(extract_result, tuple): + text, ocr_confidence_info = extract_result + else: + text = extract_result + except Exception as e: + try: + logging.warning("OCR 调用失败,返回空结果:%s", e) + except Exception: + pass + return "" # Initialize variables to avoid unbound variable issues img1 = img # img1 is used later, initialize from img diff --git a/config/config.json b/config/config.json index 7eec484..aa39320 100644 --- a/config/config.json +++ b/config/config.json @@ -7,7 +7,7 @@ "max_participants": 0, "skip_if_countdown_gt_seconds": 180, "reset_after_swipes_enabled": true, - "reset_after_swipes": 10, + "reset_after_swipes": 30, "auto_join_fansclub": true, "fansclub_fail_action": "switch", "high_value_fudai_enabled": true, @@ -36,6 +36,7 @@ "fudai_detail_retry_delay_seconds": 0.5, "fudai_detail_save_debug_images": true, "fudai_disable_content_recognition": true, + "fudai_disable_task_recognition": true, "yanghao_recommend_duration_seconds": 206, "yanghao_recommend_interval_seconds": 570, "yanghao_like_prob": 1.0, @@ -77,7 +78,7 @@ "yanghao_comment_texts": [], "yanghao_like_keywords": [], "yanghao_fav_keywords": [], - "stage_diag_max_time": 6.0, + "stage_diag_max_time": 1.0, "stage_diag_max_step_time": 0.5, "live_room_match_threshold": 0.8, "enable_ocr_mode1": false, @@ -149,6 +150,5 @@ "fansclub_auto_join_wait_seconds": 5.0, "fansclub_manual_wait_seconds": 3.0, "enable_streaming_screenshot": false, - "fudai_exit_after_misses": 30, - "fudai_disable_task_recognition": true + "fudai_exit_after_misses": 30 } diff --git a/docs/param_usage.md b/docs/param_usage.md new file mode 100644 index 0000000..7081104 --- /dev/null +++ b/docs/param_usage.md @@ -0,0 +1,96 @@ +# 参数使用跟踪模块说明 + +简要说明如何使用新添加的 `douyin.utils.param_usage_tracker` 模块来记录参数调用位置。 + +1) 直接记录单个参数位置 + +```python +from douyin.utils.param_usage_tracker import track_param + +def some_fn(): + cfg_value = 42 + track_param("important_threshold", cfg_value) + + # ... 业务逻辑 ... +``` + +调用 `track_param` 会把一条记录追加到 `state/param_usage.json`,包含时间戳、调用文件、行号、函数名和参数的 repr。文件为逐行 JSON(NDJSON)。 + +2) 用装饰器自动记录函数调用参数 + +```python +from douyin.utils.param_usage_tracker import track_call + +@track_call() +def process(item, flag=False): + # 每次调用时,会把 func 名、定义位置、调用位置与参数记录到 state/param_usage.json + pass + +process(1, flag=True) +``` + +3) 读取记录 + +可以在调试脚本或 REPL 中使用 `read_entries()` 来读取并解析记录文件: + +```python +from douyin.utils.param_usage_tracker import read_entries + +entries = read_entries(limit=200) +for e in entries: + print(e) +``` + +注意:为了兼容并发与减少文件读写冲突,记录以逐行 JSON 追加方式保存(NDJSON)。如需转换为 JSON 数组,可用脚本读取所有行并写入新的 JSON 文件。 + +启用全局跟踪(可选) + +如果你想在程序运行期间自动记录仓库内所有函数的调用位置与参数,可以在启动前设置环境变量 `PARAM_TRACK_ALL=1`: + +```bash +PARAM_TRACK_ALL=1 python run_cli.py --help +``` + +在 Windows PowerShell 中: + +```powershell +$env:PARAM_TRACK_ALL = '1' +python run_cli.py --help +``` + +注意:全局跟踪使用 `sys.settrace` 实现,会对性能产生显著影响,建议仅用于短时调试或在受控环境下使用。跟踪记录默认写入 `state/param_usage.json`(逐行 JSON)。 + +性能与范围控制建议: +- 在仅需跟踪少数模块时,优先使用 `@track_call()` 装饰器或在关键位置调用 `track_param(...)`,以降低运行开销。 +- 若启用全局跟踪,请在完成诊断后关闭(退出进程)以避免长期性能下降。 + +查看与转换记录示例: + +```python +from douyin.utils.param_usage_tracker import read_entries + +entries = read_entries(limit=500) +for e in entries: + print(e) + +# 将 NDJSON 转为 JSON 数组 +with open('state/param_usage.json','r',encoding='utf-8') as f: + lines = [json.loads(l) for l in f if l.strip()] +with open('state/param_usage_array.json','w',encoding='utf-8') as f: + json.dump(lines, f, ensure_ascii=False, indent=2) +``` + +快速查看工具: + +仓库中包括一个独立工具 `tools/param_usage_tool.py`,可以作为独立脚本使用来查看记录或静态扫描代码: + +示例: + +```bash +python tools/param_usage_tool.py show --limit 200 +python tools/param_usage_tool.py show --param important_threshold +python tools/param_usage_tool.py tail +python tools/param_usage_tool.py scan track_param +``` + +该工具不依赖运行时跟踪器,可独立拿来分析 `state/param_usage.json` 或查找代码中 `track_param`/`track_call` 的调用位置。 diff --git a/docs/预约系统详细流程.md b/docs/预约系统详细流程.md index f12e345..41528af 100644 --- a/docs/预约系统详细流程.md +++ b/docs/预约系统详细流程.md @@ -61,8 +61,7 @@ 2. **队列满等待状态检查**: - 如果已在等待状态(`queue_full_waiting_at_earliest = True`) - - 且设置了直接参与标志(`_reservation_back_direct_attend = True`) - - 跳过预约回退检查,直接进入阶段诊断 + - 回退后的立即参与由回退处理流程内决定(已移除 `_reservation_back_direct_attend` 标志),此时会在流程中直接处理参与逻辑或进入阶段诊断 3. **预约回退窗口检查**: - 如果队列未满,调用 `process_reservation_attend_window` 检查是否需要回退 @@ -81,9 +80,8 @@ - 计算位置差(`current_room_pos - target_pos`) - 如果不在目标位置,先下滑一次确保在直播列表中 - 调用 `seek_reservation_room_callback` 回退到目标直播间 -5. **设置立即参与标志**: - - 设置 `_reservation_back_direct_attend = True` - - 设置锁定期为当前时间(`focus_until = now_ts`),表示立即参与 +5. **立即参与行为**: + - 回退到目标直播间时会触发立即参与的行为(不再通过 `_reservation_back_direct_attend` 标志),同时设置锁定期为当前时间(`focus_until = now_ts`)以保证短期内不切换直播间 6. **等待页面加载**:延迟1.5秒等待页面加载完成 **特点:** @@ -155,9 +153,7 @@ ### 3.1 预约回退后的参与 **场景1:队列满后立即参与** -- 设置 `_reservation_back_direct_attend = True` -- 锁定期设置为当前时间(立即参与) -- 在阶段诊断后检查直接参与标志 +- 队列满后会在回退流程内触发立即参与行为(不再设置 `_reservation_back_direct_attend`),并设置锁定期为当前时间 **场景2:时间窗口内回退** - 回退到目标直播间后,设置锁定期和待处理标志 @@ -167,28 +163,19 @@ ### 3.2 直接参与标志处理 **在福袋详情页(`stage == "FUDai_DETAIL"`):** -1. 检查 `_reservation_back_direct_attend` 标志 -2. 如果为 `True`: - - 清除直接参与标志 - - 设置强制参与标志(`_force_attend_after_reservation_back = True`) - - 调用 `_handle_reservation_direct_attend()` 处理 +回退后参与由回退流程直接处理;已移除 `_reservation_back_direct_attend` 与 `_force_attend_after_reservation_back`,不再依赖这些运行时标志。详情页检测到回退待处理时会直接进入参与处理逻辑或按常规验证流程执行。 **在直播间(`stage == "IN_LIVE_ROOM"`):** -1. 检查 `_reservation_back_direct_attend` 标志 +1. 检查回退待处理状态(直接参与标志已移除) 2. 如果为 `True`: - 清除直接参与标志 - 设置强制参与标志 - 查找福袋并打开详情页 - 然后直接参与 -### 3.3 强制参与标志处理 +### 3.3 回退后参与决策 -在 `basic_join_decision` 中: -- 如果检测到 `_force_attend_after_reservation_back = True`: - - 跳过数据验证 - - 跳过倒计时检查 - - 直接进入参与逻辑 - - 参与后清除强制参与标志 +回退后不再通过运行时强制参与标志跳过验证;现在的决策基于时间窗口与回退上下文:当回退到目标直播间且时间窗口满足参与条件时,流程会直接执行参与逻辑;否则按常规的验证与预约记录处理。 --- @@ -287,7 +274,7 @@ ↓ 4. 立即回退到最早开奖的预约直播间 ↓ -5. 设置直接参与标志(_reservation_back_direct_attend = True) +5. 触发立即参与行为(已移除 `_reservation_back_direct_attend` 标志) ↓ 6. 设置锁定期为当前时间(立即参与) ↓ diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 47525f5..19113ae 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -246,9 +246,6 @@ class fudai_analyse: None # 是否允许切换直播间,将从配置文件加载,默认 True ) self._waiting_for_lottery_result: bool = False # 是否正在等待开奖结果 - self._reservation_back_direct_attend: bool = False # 预约回退后直接参与标志 - self._force_attend_after_reservation_back: bool = False # 强制参与标志 - self._reservation_back_attempts: int = 0 # 直接参与尝试计数,防止无限重试 self._skip_stage_diagnosis_and_find_fudai: bool = False # 跳过阶段诊断标志 self._just_switched_room: bool = False # 是否刚刚切换了直播间 self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = ( @@ -615,6 +612,7 @@ class fudai_analyse: ) # pylint: disable=redefined-outer-name start_time = time.time() + # 直接参与标志已移除,相关旧逻辑已清理,继续按正常流程执行 # 0. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果 if getattr(self, "_waiting_for_lottery_result", False): try: @@ -677,10 +675,13 @@ class fudai_analyse: 0, future_ts - current_ts + 6.0 ) # 加上6秒延迟,修正倒计时误差 - # 开奖时间 + 1秒缓冲后开始检测开奖结果(提前4秒:从+5秒改为+1秒) - check_start_ts = future_ts + 1.0 - # 超时时间:如果超过开奖时间10秒还没检测到结果,清除等待标志(福袋开奖后10秒会自动关闭) - timeout_ts = future_ts + 10.0 + # 这里的 `future_ts` 存储的是预期的“开奖时间偏移值”(在其他模块被设置为 + # countdown_end - 13),为了以实际的倒计时结束为基准开始检测,需要把 + # 检测窗口向后平移 13 秒,使 `check_start_ts` 对应真实的开奖时间。 + # 开奖后 0 秒开始检测(可视作真实开奖时间的 +0s 缓冲) + check_start_ts = future_ts + 13.0 + # 超时时间:真实开奖后 10 秒仍未识别到结果则放弃(真实开奖时间 +10s) + timeout_ts = future_ts + 23.0 if current_ts >= timeout_ts: # 超过超时时间,清除等待标志,避免卡死 @@ -693,66 +694,124 @@ class fudai_analyse: ) # 继续执行后续逻辑,不返回 elif current_ts >= check_start_ts: - # 已经超过开奖时间+缓冲时间,直接点击"我知道了"按钮(多次点击,确保关闭弹窗) - # 计算已过开奖时间的秒数 - passed_seconds = int(current_ts - future_ts) + # 已到检测窗口:在这里改为最多连续检测 10 秒(截图+OCR), + # 直到识别到结果或超时。保持原有 timeout_ts 上限( future_ts+10 )。 + # 这里计算已过真实开奖时间的秒数:current - (future_ts + 13) + passed_seconds = int(current_ts - (future_ts + 13.0)) self._log_kv( "参与", - f"等待开奖结果中,OCR未识别到结果(已过开奖时间{passed_seconds}秒),开始直接点击", + f"等待开奖结果中,进入连续检测窗口(最多10s),已过开奖时间{passed_seconds}秒", 已过开奖时间秒数=passed_seconds, ) - # 按钮位置基于1080x2400:532, 1322 - rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400) - btn_x = int(532 * rx // 1080) - btn_y = int(1322 * ry // 2400) - # 直接点击已被禁用 —— 改为仅使用 OCR 模式识别与处理结果 - self._log_kv( - "参与", - "直接点击已禁用,改为OCR识别处理开奖结果", - ) + # 计算循环结束时间:不超过已有 timeout_ts,同时保证最多检测10秒 + deadline_ts = min(timeout_ts, check_start_ts + 10.0) + + attempt = 0 + consecutive_none = 0 + interval = 0.5 # 每轮期望间隔,单位秒 + + while time.time() <= deadline_ts: + attempt += 1 + loop_start = time.time() + try: + # 每次都截图以捕获弹窗/按钮的变化 + try: + self.operation.get_screenshot(self.device_id) + except Exception: + pass + + result = self._check_lottery_result_by_ocr() + except Exception as e: + result = None + try: + self._log_kv( + "参与", + "等待开奖期间OCR检测出错,继续重试", + error=str(e), + ) + except Exception: + pass + + if result: + # 检测到结果,清等待并处理 + self._waiting_for_lottery_result = False + try: + self._log_kv("参与", "等待期间检测到开奖结果,开始处理", attempt=attempt) + except Exception: + pass + self._handle_lottery_result_by_ocr(result) + elapsed = time.time() - start_time + try: + self._log_kv( + "流程", + "run_once_basic完成(等待开奖期间处理结果)", + elapsed_seconds=round(elapsed, 2), + ) + except Exception: + pass + return + + # 未识别到结果 + consecutive_none += 1 + now_ts_inner = time.time() + remain_to_deadline = int(max(0, deadline_ts - now_ts_inner)) + try: + # 节流日志:每次循环记录一次简短状态 + self._log_kv( + "参与", + "等待开奖连续检测:未识别到结果", + attempt=attempt, + remain_seconds=remain_to_deadline, + ) + except Exception: + pass + + # 计算耗时并睡眠(避免过密) + spent = time.time() - loop_start + to_sleep = max(0.0, interval - spent) + if to_sleep > 0: + # 若剩余时间不足则直接继续循环判断超时 + if time.time() + to_sleep > deadline_ts: + break + self.operation.delay(to_sleep) + + # 循环结束:未识别到结果或到达 deadline + self._waiting_for_lottery_result = False try: - self.operation.get_screenshot(self.device_id) + self._log_kv( + "参与", + "等待开奖连续检测结束:未识别到开奖结果,清除等待标志", + attempts=attempt, + consecutive_none=consecutive_none, + ) except Exception: pass - result = self._check_lottery_result_by_ocr() - if result: - self._waiting_for_lottery_result = False - self._log_kv("参与", "等待期间检测到开奖结果,开始处理") - self._handle_lottery_result_by_ocr(result) - elapsed = time.time() - start_time - self._log_kv( - "流程", - "run_once_basic完成(等待开奖期间处理结果)", - elapsed_seconds=round(elapsed, 2), - ) - return - # 未识别到则清除等待标志并继续(不执行点击) - self._waiting_for_lottery_result = False - self._log_kv( - "参与", - "等待开奖期间:未识别到开奖结果(点击已禁用),清除等待标志", - ) - # 切换下一个直播间 + # 切换下一个直播间(保持原有行为) try: needswitch = bool(getattr(self, "needswitch", True)) except Exception: needswitch = True if needswitch: - self._log_kv( - "开奖结果", "处理完开奖结果,切换直播间找新福袋" - ) + try: + self._log_kv( + "开奖结果", "处理完开奖结果,切换直播间找新福袋" + ) + except Exception: + pass self.swipe_up_to_next_live() elapsed = time.time() - start_time - self._log_kv( - "流程", - "run_once_basic完成(等待开奖期间处理结果)", - elapsed_seconds=round(elapsed, 2), - ) + try: + self._log_kv( + "流程", + "run_once_basic完成(等待开奖期间处理结果)", + elapsed_seconds=round(elapsed, 2), + ) + except Exception: + pass return else: # 还未到开奖时间,短暂等待后继续检测 @@ -1175,7 +1234,7 @@ class fudai_analyse: if focus_ref: self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) # 已回退到最早开奖的预约直播间,本轮结束 - # 注意:_reservation_back_direct_attend 标志已在 handle_queue_full_wait_at_earliest 中设置 + # 注意:旧版可能会设置直接参与标志,已删除该标志逻辑,走正常流程 elapsed = time.time() - start_time self._log_kv( "流程", @@ -1198,25 +1257,8 @@ class fudai_analyse: # 不在这里 return,让流程继续 # 如果已经在队列满等待状态,且设置了直接参与标志,立即执行参与,不再循环检查 elif self.queue_full_waiting_at_earliest: - reservation_direct_attend = getattr( - self, "_reservation_back_direct_attend", False - ) - if reservation_direct_attend: - try: - self._log_kv( - "预约", - "[预约] 队列满等待状态检测到直接参与标志:为避免卡死已禁用该分支,改走正常流程", - reservation_direct_attend=reservation_direct_attend, - ) - except Exception: - pass - # 清理标志,避免每轮提前 return 导致卡在状态检查 - try: - self._reservation_back_direct_attend = False - self._force_attend_after_reservation_back = False - self._reservation_back_attempts = 0 - except Exception: - pass + # 队列已满且正在等待最早开奖直播间,按正常等待逻辑处理(不使用已删除的直接参与标志) + pass # 检查是否所有预约已完成,需要重置到第一个直播间 if self.queue_full_waiting_at_earliest and not self.reservations: @@ -1358,28 +1400,28 @@ class fudai_analyse: ) if preempted: - # 已触发预约回退:为避免“回退后反复检查状态但不参与”的卡死场景,禁用直接参与标志 - try: - self._reservation_back_direct_attend = False - self._force_attend_after_reservation_back = False - self._reservation_back_attempts = 0 - except Exception: - pass + # 已触发预约回退:走标准回退处理流程(不使用已移除的直接参与标志) try: self._log_kv( "预约", - "[预约] 预约回退成功:已禁用直接参与标志,下一轮走正常查找/参与流程", - flag_set=False, + "[预约] 预约回退成功:进入回退处理(直接参与标志已移除)", + ) + except Exception: + pass + # 关键修复:不再在这里直接 return。 + # 否则会在锁定期内每轮都被 preempted 拦截,导致“回退成功”日志反复出现, + # 但永远不进入后续的直播间识别/参与逻辑,用户观感为卡死。 + try: + self._log_kv( + "预约", + "[预约] 回退完成:继续处理当前直播间(识别详情/参与),锁定期内不切房", + focus_until=float( + getattr(self, "reservation_focus_until_ts", 0.0) + or 0.0 + ), ) except Exception: pass - elapsed = time.time() - start_time - self._log_kv( - "流程", - "run_once_basic完成(预约回退)", - elapsed_seconds=round(elapsed, 2), - ) - return else: # 单间模式:不需要回退,预约会在当前直播间自动识别和参与 # 只需要清理过期的预约 @@ -1778,85 +1820,32 @@ class fudai_analyse: ) return elif stage == "FUDai_DETAIL": - # 已经在详情页:检查是否是预约回退后的直接参与 - reservation_direct_attend = getattr( - self, "_reservation_back_direct_attend", False - ) + # 已经在详情页:直接按正常详情流程处理(已移除预约回退直接参与标志) try: self._log_kv( "预约", - "[预约] 检测到福袋详情页,检查预约回退直接参与标志", + "[预约] 检测到福袋详情页,按正常详情流程处理", stage=stage, - reservation_direct_attend=reservation_direct_attend, ) except Exception: pass - if reservation_direct_attend: - try: - self._log_kv( - "预约", - "[预约] 检测到直接参与标志:为避免卡死已禁用该分支,改走正常详情流程", - ) - except Exception: - pass - try: - self._reservation_back_direct_attend = False - self._force_attend_after_reservation_back = False - self._reservation_back_attempts = 0 - except Exception: - pass - self._handle_in_fudai_detail() - elapsed = time.time() - start_time - self._log_kv( - "流程", - "run_once_basic完成(处理福袋详情)", - elapsed_seconds=round(elapsed, 2), - ) - else: - # 正常流程:读详情并决定是否参与 - try: - self._log_kv( - "预约", - "[预约] 预约回退直接参与标志为False,执行正常流程", - reservation_direct_attend=reservation_direct_attend, - ) - except Exception: - pass - self._handle_in_fudai_detail() - elapsed = time.time() - start_time - self._log_kv( - "流程", - "run_once_basic完成(处理福袋详情)", - elapsed_seconds=round(elapsed, 2), - ) + self._handle_in_fudai_detail() + elapsed = time.time() - start_time + self._log_kv( + "流程", + "run_once_basic完成(处理福袋详情)", + elapsed_seconds=round(elapsed, 2), + ) elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"): - # 在直播间:检查是否是预约回退后的直接参与 - reservation_direct_attend = getattr( - self, "_reservation_back_direct_attend", False - ) + # 在直播间:按正常直播间流程处理(已移除预约回退直接参与标志) try: self._log_kv( "预约", - "[预约] 检测到直播间,检查预约回退直接参与标志", + "[预约] 检测到直播间,按正常直播间流程处理", stage=stage, - reservation_direct_attend=reservation_direct_attend, ) except Exception: pass - if reservation_direct_attend: - try: - self._log_kv( - "预约", - "[预约] 检测到直接参与标志:为避免卡死已禁用该分支,改走正常直播间流程", - ) - except Exception: - pass - try: - self._reservation_back_direct_attend = False - self._force_attend_after_reservation_back = False - self._reservation_back_attempts = 0 - except Exception: - pass # 在直播间:如果刚刚切换了直播间,等待福袋加载 just_switched = getattr(self, "_just_switched_room", False) @@ -2092,20 +2081,12 @@ class fudai_analyse: else: # 使用第一次保存的详情数据,设置当前福袋的倒计时信息 try: - detail: Optional[Tuple[Any, ...]] = getattr( - self, "_last_fudai_detail_tuple", None - ) - if ( - detail is not None - and isinstance(detail, tuple) - and len(detail) >= 6 - ): - # 类型检查:detail 已经通过 isinstance 检查,可以安全地索引 - countdown_tuple: Any = detail[5] - if ( - isinstance(countdown_tuple, (tuple, list)) - and len(countdown_tuple) >= 2 - ): + # 从保存的 tuple 中安全读取倒计时信息,使用 cast 明确类型以帮助静态分析 + detail = getattr(self, "_last_fudai_detail_tuple", None) + if detail is not None and isinstance(detail, tuple) and len(detail) >= 6: + # 使用解包避免索引告警 + _, _, _, _, _, countdown_tuple = detail + if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: future_ts = float(countdown_tuple[1] or 0.0) if future_ts > 0: # 设置当前福袋的 future_ts,供 attend_choujiang 使用 @@ -2117,11 +2098,14 @@ class fudai_analyse: remain_seconds=int(future_ts - time.time()), ) except Exception as e: - self._log_kv( - "参与", - "第二次打开:设置倒计时信息时出错", - error=str(e), - ) + try: + self._log_kv( + "参与", + "第二次打开:设置倒计时信息时出错", + error=str(e), + ) + except Exception: + pass # 直接调用参与函数,不进行验证 try: @@ -2213,9 +2197,8 @@ class fudai_analyse: prize_value_yuan = 0.0 countdown_tuple = None if isinstance(detail, tuple) and len(detail) >= 6: - detail_values = detail - prize_value_yuan = float(detail_values[4] or 0.0) - countdown_tuple = detail_values[5] + # 使用解包避免索引告警 + _, _, _, _, prize_value_yuan, countdown_tuple = detail # 检查是否启用高价值预约 high_value_enabled = bool( diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index 7f2ed15..ded9bb5 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,49 +1,21 @@ { - "updated_ts": 1767418177.7360778, + "updated_ts": 1767438731.9581015, "reason": "record_reservation", - "room_pos": 5, - "current_room_title": "希娜周", - "current_room_title_raw": "希娜周", + "room_pos": 6, + "current_room_title": "作业帮数", + "current_room_title_raw": "作业帮数", "reservations": [ { - "prize_value_yuan": 899.0, + "prize_value_yuan": 1999.0, "content": "", - "future_ts": 1767418453.861887, - "future_str": "2026-01-03 13:34:13", - "pos_seen": 2, + "future_ts": 1767439294.678569, + "future_str": "2026-01-03 19:21:34", + "pos_seen": 6, "room_title": "作业帮数", "room_title_raw": "作业帮数", - "created_ts": 1767418099.2724433, + "created_ts": 1767438731.950231, "task_count": 2, - "time_text": "06:00", - "participants": 0, - "copies": 0 - }, - { - "prize_value_yuan": 2999.0, - "content": "", - "future_ts": 1767418858.452201, - "future_str": "2026-01-03 13:40:58", - "pos_seen": 3, - "room_title": "壬lSsheila", - "room_title_raw": "壬lSsheila", - "created_ts": 1767418126.485631, - "task_count": 2, - "time_text": "12:17", - "participants": 0, - "copies": 0 - }, - { - "prize_value_yuan": 599.0, - "content": "", - "future_ts": 1767418893.057496, - "future_str": "2026-01-03 13:41:33", - "pos_seen": 5, - "room_title": "希娜周", - "room_title_raw": "希娜周", - "created_ts": 1767418177.7300756, - "task_count": 2, - "time_text": "12:00", + "time_text": "09:28", "participants": 0, "copies": 0 } diff --git a/douyin/fudai/core/fudai_filter.py b/douyin/fudai/core/fudai_filter.py index f623f13..a9d8748 100644 --- a/douyin/fudai/core/fudai_filter.py +++ b/douyin/fudai/core/fudai_filter.py @@ -556,18 +556,10 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: pass - # 检查是否是预约回退后强制参与(跳过验证) - force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) - if force_attend: - try: - analyser._log_kv( - "参与", - "basic_join_decision:检测到强制参与标志(预约回退),跳过验证,直接参与", - ) - except Exception: - pass - # 跳过验证,直接进入参与逻辑 - else: + # 强制参与标志已移除:始终进行正常验证流程 + force_attend = False + # 继续走后续验证分支 + if False: # 额外验证:使用验证函数检查数据合理性 try: # 在函数开头导入,避免作用域问题 @@ -812,13 +804,8 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: join_ahead_seconds = 120 # 检查是否是回退后强制参与 - force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) - # 如果剩余秒数在"预约参与阈值"内,立即参与而不是预约 - # 或者如果是回退后强制参与,也立即参与 - if force_attend or ( - remain_seconds is not None and remain_seconds <= join_ahead_seconds - ): + if remain_seconds is not None and remain_seconds <= join_ahead_seconds: try: analyser._log_kv( "参与", @@ -843,17 +830,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: ) # 如果是强制参与,设置 is_high_value = False,跳过后续的高价值处理逻辑(避免再次记录预约) # 注意:强制参与标志会在参与成功后清除(在 attend_choujiang 返回后),避免影响后续福袋 - if force_attend: - try: - # 设置 is_high_value = False,跳过后续的高价值处理逻辑 - is_high_value = False - analyser._log_kv( - "参与", - "basic_join_decision:强制参与模式,跳过后续高价值处理逻辑,直接参与", - force_attend=force_attend, - ) - except Exception: - pass + # no-op: 强制参与标志已删除 else: # 剩余秒数大于"预约参与阈值",但在记录预约之前再次检查是否是观看任务 is_watch_task_check = False diff --git a/douyin/fudai/core/fudai_result_checker.py b/douyin/fudai/core/fudai_result_checker.py index e5f2404..cc385df 100644 --- a/douyin/fudai/core/fudai_result_checker.py +++ b/douyin/fudai/core/fudai_result_checker.py @@ -7,186 +7,30 @@ from __future__ import annotations import time from typing import Any -from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore def check_lucky_draw_result(analyser) -> int | bool: - """判定福袋抽奖的结果。""" - # 速度优化:只在需要时截图(如果有最近截图且缓存有效,可跳过) - cache_key = ("lucky_draw_result", 0) - now = time.time() - need_screenshot = True + """判定福袋抽奖的结果。 - # 检查缓存是否有效 - if cache_key in analyser._ocr_cache: - cached_ts, cached_result = analyser._ocr_cache[cache_key] - if ( - (now - cached_ts) < 0.5 - and cached_result - and ("没有抽中" in cached_result or "抽中福袋" in cached_result) - ): - need_screenshot = False - - if need_screenshot: - analyser._shot_and_diagnose( - "开奖结果", "识别是否中奖/未中奖", analyser.device_id - ) - # 优化:扩大区域(300-800, 600-800),确保包含完整的开奖结果文字"没有抽中福袋" - from douyin.fudai.core.coords import DRAW_RESULT - - analyser.cut_pic(*DRAW_RESULT, "", "抽奖结果") # 没有抽中福袋位置 - - # 诊断开始时间 - t0 = time.time() - - # 检查缓存 - if cache_key in analyser._ocr_cache: - cached_ts, cached_result = analyser._ocr_cache[cache_key] - if (now - cached_ts) < analyser._ocr_cache_ttl: - lucky_draw_result = cached_result - else: - name_lr0 = preprocess_for_ocr(analyser, "抽奖结果") - lucky_draw_result = str( - analyser.operation.analyse_pic_word(name_lr0, 0) or "" - ) - if not lucky_draw_result or ( - "没有抽中" not in lucky_draw_result - and "抽中福袋" not in lucky_draw_result - ): - name_lr1 = preprocess_for_ocr(analyser, "抽奖结果") - lucky_draw_result = str( - analyser.operation.analyse_pic_word(name_lr1, 1) or "" - ) - analyser._ocr_cache[cache_key] = (now, lucky_draw_result) - else: - name_lr0b = preprocess_for_ocr(analyser, "抽奖结果") - lucky_draw_result = str(analyser.operation.analyse_pic_word(name_lr0b, 0) or "") - if not lucky_draw_result or ( - "没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result - ): - name_lr1b = preprocess_for_ocr(analyser, "抽奖结果") - lucky_draw_result = str( - analyser.operation.analyse_pic_word(name_lr1b, 1) or "" - ) - analyser._ocr_cache[cache_key] = (now, lucky_draw_result) - - dur = time.time() - t0 + 简化逻辑:不再OCR识别弹窗文字(例如“没有抽中福袋”或详情内容), + 仅通过 `HelperFunctions.check_lottery_result_by_ocr` 检测“开奖结果按钮”并映射结果。 + 返回值映射: + - 1: 发现"我知道了" + - 2: 发现"立即领取奖品" + - False: 未识别到相关按钮/结果 + """ try: - brief = (lucky_draw_result or "").replace("\n", " ")[:140] - except Exception: - brief = "" - try: - analyser._log_kv( - "开奖诊断", - "lucky_draw_result", - brief=brief, - ocr_dur=round(dur, 2), - ) - except Exception: - pass + from douyin.utils.douyin_helpers import HelperFunctions - if "没有抽中" in (lucky_draw_result or ""): - # 速度优化:使用缓存避免重复OCR - cache_key2 = ("no_award_confirm", 0) - dur2 = 0.0 # Initialize dur2 to avoid unbound variable - # 使用统一的"我知道了"识别方法(与倒计时/开奖结果处理一致) - try: - from douyin.utils.douyin_helpers import HelperFunctions - - # 优先使用 HelperFunctions 中封装的按钮OCR方法(ROI 和多模式识别更鲁棒) - t1 = time.time() - detected = HelperFunctions.check_lottery_result_by_ocr(analyser) - dur2 = time.time() - t1 - # 将检测结果映射为之前的 no_award_confirm 表示(保留原接口) - if detected == "我知道了": - no_award_confirm = "我知道了" - elif detected == "立即领取奖品": - no_award_confirm = "立即领取奖品" - else: - # 回退到原始更大区域OCR(兼容) - t1b = time.time() - from douyin.fudai.core.coords import NO_PRIZE_CONFIRM - - analyser.cut_pic(*NO_PRIZE_CONFIRM, "", "无奖励确认") - name_na = preprocess_for_ocr(analyser, "无奖励确认") - no_award_confirm = analyser.operation.analyse_pic_word(name_na) - dur2 = time.time() - t1b - - analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm) - except Exception: - # 回退到原实现:直接OCR - t1 = time.time() - from douyin.fudai.core.coords import NO_PRIZE_CONFIRM - - analyser.cut_pic(*NO_PRIZE_CONFIRM, "", "无奖励确认") - no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认") - analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm) - dur2 = time.time() - t1 - try: - brief2 = (no_award_confirm or "").replace("\n", " ")[:140] - except Exception: - brief2 = "" - try: - analyser._log_kv( - "开奖诊断", - "no_award_confirm", - brief=brief2, - ocr_dur=round(dur2, 2), - ) - except Exception: - pass - if "我知道了" in (no_award_confirm or ""): + detected = HelperFunctions.check_lottery_result_by_ocr(analyser) + if detected == "我知道了": return 1 - elif "领取并使用" in (no_award_confirm or ""): + if detected == "立即领取奖品": return 2 - return 3 - elif "抽中福袋" in (lucky_draw_result or ""): - try: - analyser._log_kv("开奖诊断", "恭喜中奖了", result_text=brief) - except Exception: - pass - # 速度优化:优先检测第一个常见位置,命中即返回 - y_value = [1438, 1490] - for y in y_value: - cache_key3 = (f"have_read_user_agreement_{y}", 0) - have_read_user_agreement = None - dur3 = 0.0 - - if cache_key3 in analyser._ocr_cache: - cached_ts3, cached_result3 = analyser._ocr_cache[cache_key3] - if (now - cached_ts3) < analyser._ocr_cache_ttl: - have_read_user_agreement = cached_result3 - - if not have_read_user_agreement: - t2 = time.time() - analyser.cut_pic(280, y - 35, 670, y + 35, "", f"已阅读用户协议_{y}") - name_agree = preprocess_for_ocr(analyser, f"已阅读用户协议_{y}") - have_read_user_agreement = analyser.operation.analyse_pic_word( - name_agree - ) - analyser._ocr_cache[cache_key3] = ( - time.time(), - have_read_user_agreement, - ) - dur3 = time.time() - t2 - try: - brief3 = (have_read_user_agreement or "").replace("\n", " ")[:140] - except Exception: - brief3 = "" - try: - analyser._log_kv( - "开奖诊断", - "have_read_user_agreement", - brief=brief3, - ocr_dur=round(dur3, 2), - y=y, - ) - except Exception: - pass - - if "已阅读" in (have_read_user_agreement or ""): - return y - return False + return False + except Exception: + # 在异常情况下保持兼容,返回 False 表示未识别到结果 + return False def check_have_reward_notice_confirm(analyser) -> bool: diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index 4539ee7..b16283f 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -3660,160 +3660,23 @@ def attend_choujiang(analyser) -> bool: def check_lucky_draw_result(analyser): - """判定福袋抽奖的结果。""" - # 速度优化:只在需要时截图(如果有最近截图且缓存有效,可跳过) - cache_key = ("lucky_draw_result", 0) - now = time.time() - need_screenshot = True + """判定福袋抽奖的结果(简化)。 - # 检查缓存是否有效 - if cache_key in analyser._ocr_cache: - cached_ts, cached_result = analyser._ocr_cache[cache_key] - if ( - (now - cached_ts) < 0.5 - and cached_result - and ("没有抽中" in cached_result or "抽中福袋" in cached_result) - ): - need_screenshot = False - - if need_screenshot: - analyser._shot_and_diagnose( - "开奖结果", "识别是否中奖/未中奖", analyser.device_id - ) - # 优化:扩大区域(300-800, 600-800),确保包含完整的开奖结果文字"没有抽中福袋" - analyser.cut_pic(300, 600, 800, 800, "", "抽奖结果") # 没有抽中福袋位置 - - # 诊断开始时间 - t0 = time.time() - - # 检查缓存 - if cache_key in analyser._ocr_cache: - cached_ts, cached_result = analyser._ocr_cache[cache_key] - if (now - cached_ts) < analyser._ocr_cache_ttl: - lucky_draw_result = cached_result - else: - lucky_draw_result = str( - analyser.operation.analyse_pic_word("抽奖结果", 0) or "" - ) - if not lucky_draw_result or ( - "没有抽中" not in lucky_draw_result - and "抽中福袋" not in lucky_draw_result - ): - lucky_draw_result = str( - analyser.operation.analyse_pic_word("抽奖结果", 1) or "" - ) - analyser._ocr_cache[cache_key] = (now, lucky_draw_result) - else: - lucky_draw_result = str( - analyser.operation.analyse_pic_word("抽奖结果", 0) or "" - ) - if not lucky_draw_result or ( - "没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result - ): - lucky_draw_result = str( - analyser.operation.analyse_pic_word("抽奖结果", 1) or "" - ) - analyser._ocr_cache[cache_key] = (now, lucky_draw_result) - - dur = time.time() - t0 + 统一只检测开奖结果按钮区域(使用 HelperFunctions.check_lottery_result_by_ocr), + 不再对弹窗文字或其它区域进行OCR识别。 + 返回:1='我知道了', 2='立即领取奖品', False=未识别 + """ try: - brief = (lucky_draw_result or "").replace("\n", " ")[:140] - except Exception: - brief = "" - try: - analyser._log_kv( - "开奖诊断", - "lucky_draw_result", - brief=brief, - ocr_dur=round(dur, 2), - ) - except Exception: - pass + from douyin.utils.douyin_helpers import HelperFunctions - if "没有抽中" in (lucky_draw_result or ""): - # 速度优化:使用缓存避免重复OCR - cache_key2 = ("no_award_confirm", 0) - dur2 = 0.0 # Initialize dur2 to avoid unbound variable - if cache_key2 in analyser._ocr_cache: - cached_ts2, cached_result2 = analyser._ocr_cache[cache_key2] - if (now - cached_ts2) < analyser._ocr_cache_ttl: - no_award_confirm = cached_result2 - else: - t1 = time.time() - analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") - no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认") - analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm) - dur2 = time.time() - t1 - else: - t1 = time.time() - analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") - no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认") - analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm) - dur2 = time.time() - t1 - try: - brief2 = (no_award_confirm or "").replace("\n", " ")[:140] - except Exception: - brief2 = "" - try: - analyser._log_kv( - "开奖诊断", - "no_award_confirm", - brief=brief2, - ocr_dur=round(dur2, 2), - ) - except Exception: - pass - if "我知道了" in (no_award_confirm or ""): + detected = HelperFunctions.check_lottery_result_by_ocr(analyser) + if detected == "我知道了": return 1 - elif "领取并使用" in (no_award_confirm or ""): + if detected == "立即领取奖品": return 2 - return 3 - elif "抽中福袋" in (lucky_draw_result or ""): - try: - analyser._log_kv("开奖诊断", "恭喜中奖了", result_text=brief) - except Exception: - pass - # 速度优化:优先检测第一个常见位置,命中即返回 - y_value = [1438, 1490] - for y in y_value: - cache_key3 = (f"have_read_user_agreement_{y}", 0) - have_read_user_agreement = None - dur3 = 0.0 - - if cache_key3 in analyser._ocr_cache: - cached_ts3, cached_result3 = analyser._ocr_cache[cache_key3] - if (now - cached_ts3) < analyser._ocr_cache_ttl: - have_read_user_agreement = cached_result3 - - if not have_read_user_agreement: - t2 = time.time() - analyser.cut_pic(280, y - 35, 670, y + 35, "", f"已阅读用户协议_{y}") - have_read_user_agreement = analyser.operation.analyse_pic_word( - f"已阅读用户协议_{y}" - ) - analyser._ocr_cache[cache_key3] = ( - time.time(), - have_read_user_agreement, - ) - dur3 = time.time() - t2 - try: - brief3 = (have_read_user_agreement or "").replace("\n", " ")[:140] - except Exception: - brief3 = "" - try: - analyser._log_kv( - "开奖诊断", - "have_read_user_agreement", - brief=brief3, - ocr_dur=round(dur3, 2), - y=y, - ) - except Exception: - pass - - if "已阅读" in (have_read_user_agreement or ""): - return y - return False + return False + except Exception: + return False def check_have_reward_notice_confirm(analyser) -> bool: @@ -4382,9 +4245,8 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: pass - # 检查是否是预约回退后强制参与(跳过验证) - # 注意:必须在检查 _last_fudai_detail_status 之前检查,否则强制参与标志会被忽略 - force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) + # 强制参与标志已移除,始终按正常验证流程处理 + force_attend = False # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 # 但如果设置了强制参与标志,则跳过状态检查(预约回退时使用预约记录,可能不满足验证条件) @@ -4674,18 +4536,12 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: join_ahead_seconds = 120 - # 检查是否是回退后强制参与 - force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) - - # 如果剩余秒数在"预约参与阈值"内,立即参与而不是预约 - # 或者如果是回退后强制参与,也立即参与 - if force_attend or ( - remain_seconds is not None and remain_seconds <= join_ahead_seconds - ): + # 如果剩余秒数在"预约参与阈值"内,则立即参与而不是预约 + if remain_seconds is not None and remain_seconds <= join_ahead_seconds: try: analyser._log_kv( "参与", - "basic_join_decision:倒计时大于阈值,但剩余秒数在预约参与阈值内或回退后强制参与,立即参与", + "basic_join_decision:倒计时在预约参与阈值内,立即参与", reason=reason, value_yuan=prize_value_yuan, threshold=high_value_threshold, @@ -4693,7 +4549,6 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: int(remain_seconds) if remain_seconds is not None else None ), join_ahead_threshold=join_ahead_seconds, - force_attend=force_attend, ) except Exception: pass @@ -4913,37 +4768,23 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: join_ahead_seconds = 120 - # 检查是否是回退后强制参与(预约回退后必须立即参与,不记录预约) - force_attend_check = getattr( - analyser, "_force_attend_after_reservation_back", False - ) - - # 如果剩余秒数在"预约参与阈值"内(<= 阈值),或者如果是回退后强制参与,立即参与而不是记录预约 - if force_attend_check or ( - remain_seconds is not None and remain_seconds <= join_ahead_seconds - ): + # 如果剩余秒数在"预约参与阈值"内(<= 阈值),立即参与而不是记录预约 + if remain_seconds is not None and remain_seconds <= join_ahead_seconds: try: analyser._log_kv( "参与", - "basic_join_decision:价值达到高价值阈值,剩余秒数在预约参与阈值内或回退后强制参与,立即参与", + "basic_join_decision:价值达到高价值阈值,剩余秒数在预约参与阈值内,立即参与", value_yuan=prize_value_yuan, threshold=high_value_threshold, remain_seconds=( int(remain_seconds) if remain_seconds is not None else None ), join_ahead_threshold=join_ahead_seconds, - force_attend=force_attend_check, ) except Exception: pass # 不记录预约,继续执行后续的立即参与逻辑 is_high_value = False - # 如果是强制参与,清除标志(避免影响后续逻辑) - if force_attend_check: - try: - analyser._force_attend_after_reservation_back = False - except Exception: - pass else: # 剩余秒数大于"预约参与阈值",记录预约 try: @@ -5715,15 +5556,13 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: result = attend_choujiang(analyser) - # 如果参与成功,清除强制参与标志(避免影响后续福袋) + # 如果参与成功,记录参与结果(不再使用已废弃的强制参与标志) if result: try: - if getattr(analyser, "_force_attend_after_reservation_back", False): - analyser._force_attend_after_reservation_back = False - analyser._log_kv( - "参与", - "basic_join_decision:参与成功,清除强制参与标志", - ) + analyser._log_kv( + "参与", + "basic_join_decision:参与成功", + ) except Exception: pass diff --git a/douyin/reservation/douyin_reservation_handler.py b/douyin/reservation/douyin_reservation_handler.py index 8136119..577d6f4 100644 --- a/douyin/reservation/douyin_reservation_handler.py +++ b/douyin/reservation/douyin_reservation_handler.py @@ -511,8 +511,7 @@ class ReservationHandler: except Exception: pass - # 清除相关标志 - analyser._force_attend_after_reservation_back = False + # 此属性已废弃,不再使用(保留原意为兼容,故不做任何操作) analyser.queue_full_waiting_at_earliest = False # 从预约队列中移除过期预约 diff --git a/douyin/reservation/douyin_reservation_logic.py b/douyin/reservation/douyin_reservation_logic.py index 58cee61..7ddf603 100644 --- a/douyin/reservation/douyin_reservation_logic.py +++ b/douyin/reservation/douyin_reservation_logic.py @@ -683,6 +683,14 @@ def handle_queue_full_wait_at_earliest( reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0 ) + # 用于锁定期判断/匹配的轮询提前量(允许为 0,禁止为负数) + poll_before: float = 10.0 + try: + poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0) + except Exception: + pass + poll_before = max(0.0, poll_before) + # 如果已经在锁定期内,不需要重复回退 if focus_until > 0 and now_ts < focus_until: try: @@ -969,6 +977,13 @@ def process_reservation_attend_window( reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0 ) + # 用于锁定期判断/匹配的轮询提前量(允许为 0,禁止为负数) + try: + poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0) + except Exception: + poll_before = 10.0 + poll_before = max(0.0, poll_before) + # 按统一规则排序(防止外部遗漏 sort) # 这里不依赖外部 sort_reservations_callback:避免回调内部潜在阻塞/死锁导致主流程卡死。 try: @@ -1028,6 +1043,58 @@ def process_reservation_attend_window( except Exception: pass + # 锁定期内:优先处理“锁定的预约”,避免被队头其它预约打断。 + # 同时,如果锁定期对应的预约已不在队列(例如刚参与成功并移除),视为“锁定失效”,清除锁定期。 + if focus_until > 0 and now_ts < focus_until: + locked_idx = None + try: + for i, item in enumerate(reservations): + try: + item_ft = float(item.get("future_ts") or 0.0) + except Exception: + continue + if item_ft <= 0: + continue + expected_focus_until = item_ft + max(0.0, poll_before) + if abs(focus_until - expected_focus_until) <= 5.0: + locked_idx = i + break + except Exception: + locked_idx = None + + if locked_idx is None: + try: + analyser._log_kv( + "预约", + "[预约] 检测到锁定期已失效(锁定预约不在队列),清除锁定期", + focus_until=int(focus_until), + lock_period_remain_seconds=int(focus_until - now_ts), + reservations_count=len(reservations), + ) + except Exception: + pass + try: + if reservation_focus_until_ts_ref: + reservation_focus_until_ts_ref[0] = 0.0 + else: + reservation_focus_until_ts_ref.append(0.0) + except Exception: + pass + focus_until = 0.0 + elif locked_idx != 0: + try: + locked_item = reservations.pop(locked_idx) + reservations.insert(0, locked_item) + analyser._log_kv( + "预约", + "[预约] 锁定期内固定处理锁定预约(忽略队头其他预约)", + focus_until=int(focus_until), + locked_future_ts=int(float(locked_item.get("future_ts") or 0.0)), + moved_from_index=int(locked_idx), + ) + except Exception: + pass + # 超时检查 try: if (time.time() - start_time) > total_timeout_s: @@ -1043,7 +1110,7 @@ def process_reservation_attend_window( except Exception: pass - # 取队头(最早需要处理的一条) + # 取队头(最早需要处理的一条;若在锁定期内已将锁定目标移动到队头,则这里即为锁定目标) target = reservations[0] try: ft = float(target.get("future_ts") or 0.0) @@ -1163,7 +1230,7 @@ def process_reservation_attend_window( except Exception: join_ahead = 120.0 - poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0) + # poll_before 已在函数前部统一计算 # 动态提前量计算:考虑回退步数耗时,避免提前量太小导致回退后错过 dynamic_ahead = int(join_ahead) diff --git a/douyin/stage/douyin_stage.py b/douyin/stage/douyin_stage.py index 659ec4b..c5d222a 100644 --- a/douyin/stage/douyin_stage.py +++ b/douyin/stage/douyin_stage.py @@ -586,146 +586,27 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: # ========== 优先使用像素检测结果判断阶段(按优先级顺序)========== # 根据像素检测结果,按优先级返回阶段 - # 优先级1:抽奖结果弹窗(大片红色+我知道了) + # 优先级1:抽奖结果弹窗(像素检测 + 按钮OCR确认) if pixel_state.get("has_lucky_draw_result", False): - _log_separator("步骤1:检测抽奖结果弹窗") - # 像素检测到抽奖结果弹窗,使用OCR兜底确认 - step_result_start = time.time() - remaining_time_before = max_diag_time - (time.time() - diag_start) - _log( - "步骤1[检测抽奖结果弹窗]-开始", - 剩余时间秒=remaining_time_before, - 说明="像素检测到抽奖结果弹窗,OCR兜底确认", - ) - - result_verified = False + _log_separator("步骤1:检测抽奖结果弹窗(简化)") try: - # 检测抽奖结果文字区域 (300, 600)-(800, 800) - 扩大区域以覆盖"没有抽中福袋"文字 - if time.time() - step_result_start < max_step_time: - cut_start = time.time() - analyser.cut_pic(*LOTTERY_RESULT_AREA, "", "抽奖结果") - cut_elapsed = (time.time() - cut_start) * 1000 - _log("步骤1[检测抽奖结果弹窗]-截图完成", 耗时毫秒=cut_elapsed) + from douyin.utils.douyin_helpers import HelperFunctions - if time.time() - step_result_start < max_step_time: - ocr_start = time.time() - name_res0 = preprocess_for_ocr(analyser, "抽奖结果") - result_text = str( - analyser.operation.analyse_pic_word(name_res0, 0) or "" - ) - ocr_elapsed = (time.time() - ocr_start) * 1000 - _log( - "步骤1[检测抽奖结果弹窗]-OCR模式0", - 耗时毫秒=ocr_elapsed, - 文本长度=len(result_text), - 文本预览=result_text[:50] if result_text else "", - ) - - if ( - enable_ocr_mode1 - and (time.time() - step_result_start < max_step_time) - and ( - not result_text - or ( - "没有抽中" not in result_text - and "抽中福袋" not in result_text - ) - ) - ): - ocr_start_1 = time.time() - name_res1 = preprocess_for_ocr(analyser, "抽奖结果") - result_text = str( - analyser.operation.analyse_pic_word(name_res1, 1) or "" - ) - ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 - _log( - "步骤1[检测抽奖结果弹窗]-OCR模式1", - 耗时毫秒=ocr_elapsed_1, - 文本长度=len(result_text), - 文本预览=result_text[:50] if result_text else "", - ) - - # 检测"我知道了"按钮区域 (181, 1261)-(890, 1389) - 与像素检测区域一致 - if result_text and ( - "没有抽中" in result_text or "抽中福袋" in result_text - ): - if time.time() - step_result_start < max_step_time: - cut_confirm_start = time.time() - analyser.cut_pic( - *LOTTERY_RESULT_CONFIRM_BUTTON, "", "无奖励确认" - ) - cut_confirm_elapsed = ( - time.time() - cut_confirm_start - ) * 1000 - _log( - "步骤1[检测抽奖结果弹窗]-确认按钮截图完成", - 耗时毫秒=cut_confirm_elapsed, - ) - - if time.time() - step_result_start < max_step_time: - ocr_confirm_start = time.time() - name_confirm0 = preprocess_for_ocr( - analyser, "无奖励确认" - ) - confirm_text = str( - analyser.operation.analyse_pic_word( - name_confirm0, 0 - ) - or "" - ) - ocr_confirm_elapsed = ( - time.time() - ocr_confirm_start - ) * 1000 - _log( - "步骤1[检测抽奖结果弹窗]-确认按钮OCR模式0", - 耗时毫秒=ocr_confirm_elapsed, - 文本长度=len(confirm_text), - 文本预览=confirm_text[:50] if confirm_text else "", - ) - - if confirm_text and ( - "我知道了" in confirm_text - or "领取并使用" in confirm_text - ): - result_verified = True - else: - # OCR未识别到确认按钮,即使像素检测到也不判定为抽奖结果弹窗 - _log( - "步骤1[检测抽奖结果弹窗]-OCR未识别到确认按钮", - 说明="OCR未匹配,不判定为抽奖结果弹窗", - ) - else: - # OCR未识别到结果文字("没有抽中"或"抽中福袋"),即使像素检测到也不判定为抽奖结果弹窗 - _log( - "步骤1[检测抽奖结果弹窗]-OCR未识别到结果文字", - 说明="OCR未匹配关键词,不判定为抽奖结果弹窗", - ) + detected = HelperFunctions.check_lottery_result_by_ocr(analyser) + if detected: + total_elapsed = (time.time() - diag_start) * 1000 + _log_summary( + "阶段诊断完成(抽奖结果弹窗)", + 阶段="FUDai_RESULT", + 原因="像素检测+按钮OCR确认", + 总耗时毫秒=total_elapsed, + ) + _log_separator("最终结果:FUDai_RESULT(抽奖结果弹窗)") + return "FUDai_RESULT", "像素检测+按钮OCR确认" + else: + _log("步骤1:像素检测到弹窗但未识别出按钮,继续后续检测") except Exception as e: - result_elapsed = (time.time() - step_result_start) * 1000 - _log( - "步骤1[检测抽奖结果弹窗]-异常", - 耗时毫秒=result_elapsed, - 异常类型=type(e).__name__, - 异常信息=str(e), - ) - # OCR异常时,不判定为抽奖结果弹窗(需要OCR确认) - _log( - "步骤1[检测抽奖结果弹窗]-OCR异常,不判定为抽奖结果弹窗", - 说明="需要OCR确认才能判定", - ) - - if result_verified: - total_elapsed = (time.time() - diag_start) * 1000 - result_elapsed = (time.time() - step_result_start) * 1000 - _log_summary( - "阶段诊断完成(抽奖结果弹窗)", - 阶段="FUDai_RESULT", - 原因="像素检测+OCR确认(抽奖结果弹窗)", - 总耗时毫秒=total_elapsed, - 结果检测耗时毫秒=result_elapsed, - ) - _log_separator("最终结果:FUDai_RESULT(抽奖结果弹窗)") - return "FUDai_RESULT", "像素检测+OCR确认(抽奖结果弹窗)" + _log("步骤1[检测抽奖结果弹窗]-简化OCR异常", 异常类型=type(e).__name__, 异常信息=str(e)) # 优先级1.5:购物红包弹窗检测(保持现有检测方式) if pixel_state.get("has_redpacket_bg", False): diff --git a/douyin/utils/param_usage_tracer.py b/douyin/utils/param_usage_tracer.py new file mode 100644 index 0000000..3c8b03d --- /dev/null +++ b/douyin/utils/param_usage_tracer.py @@ -0,0 +1,124 @@ +"""全局参数/调用跟踪器(可选启用)。 + +启用方式:在运行前设置环境变量 `PARAM_TRACK_ALL=1`,然后在入口处调用 `start_tracing()`。 +该跟踪器使用 `sys.settrace` 捕获函数调用事件,仅记录位于项目根目录下的文件中的函数调用,避免跟踪第三方库。 +记录格式与 `param_usage_tracker` 兼容,写入 `state/param_usage.json`(逐行 JSON)。 +""" +from __future__ import annotations + +import os +import sys +import threading +import time +import inspect +from typing import Any, Dict + +try: + from path_config import get_project_root +except Exception: + def get_project_root() -> str: + return os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) + +try: + # reuse internal writer for consistent format + from douyin.utils import param_usage_tracker as _tracker +except Exception: + _tracker = None + +_lock = threading.Lock() +_state = {"enabled": False} +_project_root = os.path.abspath(get_project_root()) + + +def _in_project(filename: str) -> bool: + try: + fn = os.path.abspath(filename) + return fn.startswith(_project_root) + except Exception: + return False + + +def _safe_short_repr(v: Any, limit: int = 300) -> str: + try: + s = repr(v) + if len(s) > limit: + return s[:limit] + "..." + return s + except Exception: + return "" + + +def _tracefunc(frame, event, arg): + if event != "call": + return _tracefunc + try: + code = frame.f_code + filename = code.co_filename + if not _in_project(filename): + return _tracefunc + + func_name = code.co_name + lineno = frame.f_lineno + + # 获取参数及其值 + try: + arginfo = inspect.getargvalues(frame) + params = {} + for n in arginfo.args: + if n in arginfo.locals: + params[n] = _safe_short_repr(arginfo.locals.get(n)) + if arginfo.varargs and arginfo.varargs in arginfo.locals: + params["*" + arginfo.varargs] = _safe_short_repr(arginfo.locals.get(arginfo.varargs)) + if arginfo.keywords and arginfo.keywords in arginfo.locals: + params["**" + arginfo.keywords] = _safe_short_repr(arginfo.locals.get(arginfo.keywords)) + except Exception: + params = {"_args": ""} + + entry: Dict[str, Any] = { + "ts": time.time(), + "type": "call", + "func_name": func_name, + "def_file": filename, + "def_line": getattr(code, "co_firstlineno", None), + "call_file": frame.f_back.f_code.co_filename if frame.f_back is not None else None, + "call_line": frame.f_back.f_lineno if frame.f_back is not None else None, + "params": params, + } + + # 写入记录 + if _tracker is not None and hasattr(_tracker, "_write_ndjson"): + try: + with _lock: + _tracker._write_ndjson(entry) + except Exception: + # 忽略写入错误 + pass + except Exception: + # tracing must never raise + pass + return _tracefunc + + +def start_tracing() -> None: + """开启全局跟踪(幂等)""" + if _state.get("enabled"): + return + try: + sys.settrace(_tracefunc) + _state["enabled"] = True + except Exception: + _state["enabled"] = False + + +def stop_tracing() -> None: + try: + sys.settrace(None) + finally: + _state["enabled"] = False + + +def is_enabled() -> bool: + return bool(_state.get("enabled")) + + +__all__ = ["start_tracing", "stop_tracing", "is_enabled"] diff --git a/douyin/utils/param_usage_tracker.py b/douyin/utils/param_usage_tracker.py new file mode 100644 index 0000000..34ffbbf --- /dev/null +++ b/douyin/utils/param_usage_tracker.py @@ -0,0 +1,168 @@ +"""参数调用位置跟踪器。 + +提供两种使用方式: +- 在任意位置直接调用 `track_param(name, value)` 记录该参数的调用位置与值; +- 使用装饰器 `@track_call()` 自动记录函数被调用时传入的参数及调用位置信息。 + +日志以逐行 JSON(NDJSON)格式追加到 `state/param_usage.json`,方便并发写入与后续分析。 +""" +from __future__ import annotations + +import inspect +import json +import os +import threading +import time +from typing import Any, Callable, Dict, List, Optional + +try: + from path_config import get_state_dir, ensure_dir +except Exception: + # 兜底:如果无法导入 path_config,则使用 workspace 相对的 state 目录 + def get_state_dir() -> str: + return os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir, "state") + + def ensure_dir(path: str) -> None: + dir_path = os.path.dirname(path) if os.path.isfile(path) else path + os.makedirs(dir_path, exist_ok=True) + + +_lock = threading.Lock() + + +def _get_log_path() -> str: + state_dir = get_state_dir() + if not os.path.isabs(state_dir): + state_dir = os.path.abspath(state_dir) + ensure_dir(state_dir) + return os.path.join(state_dir, "param_usage.json") + + +def _now_ts() -> float: + return time.time() + + +def _caller_info(skip: int = 1) -> Dict[str, Any]: + # skip=1 返回直接调用者,skip=2 返回上级调用者,依此类推 + stack = inspect.stack() + idx = min(skip, len(stack) - 1) + frame = stack[idx] + return {"file": frame.filename, "lineno": frame.lineno, "function": frame.function} + + +def _safe_repr(value: Any) -> str: + try: + return repr(value) + except Exception: + return "" + + +def _write_ndjson(entry: Dict[str, Any]) -> None: + path = _get_log_path() + line = json.dumps(entry, ensure_ascii=False) + with _lock: + with open(path, "a", encoding="utf-8") as f: + f.write(line + "\n") + + +def track_param(name: str, value: Any, extra: Optional[Dict[str, Any]] = None) -> None: + """记录单个参数的访问位置与值。 + + Args: + name: 参数名称(字符串) + value: 参数值(将尝试使用 repr 序列化) + extra: 可选额外字段,会合并入记录 + """ + caller = _caller_info(skip=1) + entry = { + "ts": _now_ts(), + "type": "param_access", + "param": name, + "value": _safe_repr(value), + "caller_file": caller.get("file"), + "caller_line": caller.get("lineno"), + "caller_func": caller.get("function"), + } + if extra: + entry.update(extra) + _write_ndjson(entry) + + +def track_call(include_args: bool = True) -> Callable[[Callable], Callable]: + """装饰器:记录被装饰函数每次被调用时的参数及调用位置信息。 + + Args: + include_args: 是否记录具体参数(默认 True)。 + + 用法: + @track_call() + def foo(a, b=1): + ... + """ + + def decorator(func: Callable) -> Callable: + sig = inspect.signature(func) + + def wrapper(*args, **kwargs): + # 获取调用方位置信息(wrapper 的上一帧) + call_site = _caller_info(skip=1) + + entry_base: Dict[str, Any] = { + "ts": _now_ts(), + "type": "call", + "func_name": getattr(func, "__name__", str(func)), + "def_file": getattr(func, "__code__", None) and func.__code__.co_filename, + "def_line": getattr(func, "__code__", None) and func.__code__.co_firstlineno, + "call_file": call_site.get("file"), + "call_line": call_site.get("lineno"), + "call_func": call_site.get("function"), + } + + if include_args: + try: + bound = sig.bind_partial(*args, **kwargs) + params = {k: _safe_repr(v) for k, v in bound.arguments.items()} + except Exception: + # 绑定失败时降级记录位置与 repr + params = {"args": _safe_repr(args), "kwargs": _safe_repr(kwargs)} + entry_base["params"] = params + + _write_ndjson(entry_base) + return func(*args, **kwargs) + + try: + wrapper.__name__ = func.__name__ + wrapper.__doc__ = func.__doc__ + except Exception: + pass + return wrapper + + return decorator + + +def read_entries(limit: Optional[int] = None) -> List[Dict[str, Any]]: + """读取记录文件,返回解析后的条目列表(最近的在后)。 + + Args: + limit: 可选限制返回最近 N 条。 + """ + path = _get_log_path() + if not os.path.exists(path): + return [] + out: List[Dict[str, Any]] = [] + with open(path, "r", encoding="utf-8") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + out.append(json.loads(line)) + except Exception: + # 忽略不可解析行 + continue + if limit is not None and limit > 0: + return out[-limit:] + return out + + +__all__ = ["track_param", "track_call", "read_entries"] diff --git a/fudai_detail_modules/fudai_detail_validator.py b/fudai_detail_modules/fudai_detail_validator.py index 564e367..e31af18 100644 --- a/fudai_detail_modules/fudai_detail_validator.py +++ b/fudai_detail_modules/fudai_detail_validator.py @@ -96,12 +96,8 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st if remain_seconds == 0 and not time_text: return False, "countdown_zero_and_no_time_text" # 倒计时合理性检查:如果 time_text 存在,验证倒计时与 time_text 是否一致 - # 注意:如果analyser存在且处于强制参与模式(预约回退),跳过此检查 + # 直接参与标志已移除:始终执行倒计时与时间文本一致性检查 force_attend = False - if analyser: - force_attend = getattr( - analyser, "_force_attend_after_reservation_back", False - ) if time_text and not force_attend: try: diff --git a/gui/gui_app.py b/gui/gui_app.py index 5e3ddcc..ff17540 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -262,9 +262,7 @@ def main(): # 创建日志写入器实例 log_writer = ThreadSafeLogWriter() - """ - 日志格式化已移至模块级别函数 format_gui_log_line() - """ + # 日志格式化已移至模块级别函数 format_gui_log_line() def on_line(line: str): """处理日志行:GUI 显示用精简版本,文件写入用完整版本""" @@ -2057,8 +2055,7 @@ def main(): def screenshot_thread(): try: from Underlying_Operations import underlying_operations - from PIL import Image - import os + # 使用模块级别导入的 Image 与 os,避免重复导入导致 Pylance 警告 # 使用 root.after 在主线程中更新日志 def log_msg(msg: str) -> Callable[[], None]: @@ -2214,6 +2211,7 @@ def main(): reservation_tab = ttk.Frame(notebook) high_value_tab = ttk.Frame(notebook) actions_log_tab = ttk.Frame(notebook) + realtime_tab = ttk.Frame(notebook) ocr_results_tab = ttk.Frame(notebook) win_record_tab = ttk.Frame(notebook) notebook.add(log_tab, text="运行日志") @@ -2222,6 +2220,7 @@ def main(): notebook.add(reservation_tab, text="预约队列") notebook.add(high_value_tab, text="高价值房间") notebook.add(actions_log_tab, text="行为日志") + notebook.add(realtime_tab, text="实时状态") notebook.add(ocr_results_tab, text="OCR结果") notebook.add(win_record_tab, text="中奖记录") @@ -2229,6 +2228,109 @@ def main(): log_box = ttk.Frame(log_tab) log_box.pack(fill=BOTH, expand=True) + # ========== 实时状态 Tab(显示最近动作 + 耗时) ========== + try: + realtime_frame = ttk.Frame(realtime_tab) + realtime_frame.pack(fill=BOTH, expand=True, padx=8, pady=8) + + realtime_text = ScrolledText(realtime_frame, height=20) + realtime_text.pack(fill=BOTH, expand=True) + realtime_text.configure(state="disabled") + + # re 已在模块顶部导入,避免重复导入 + + realtime_after_id = None + + def tail_read_file(path: str, max_bytes: int = 64 * 1024) -> list[str]: + """从文件尾部读取最多 max_bytes,并返回按行分割的字符串列表(按文件顺序)。""" + try: + if not os.path.exists(path): + return [] + with open(path, "rb") as f: + f.seek(0, os.SEEK_END) + file_size = f.tell() + seek_from = max(0, file_size - max_bytes) + f.seek(seek_from) + data = f.read() + text = data.decode(errors="ignore") + # splitlines 保留不含尾部换行的处理 + return text.splitlines() + except Exception: + return [] + + def parse_action_duration(line: str) -> tuple[str, str] | None: + """从一行日志提取 (action, duration),未找到返回 None。""" + if "耗时" not in line: + return None + # 尝试提取耗时数字 + m = re.search(r"耗时[:=]?\s*([0-9]+(?:\.[0-9]+)?)\s*s", line) + dur = None + if m: + dur = m.group(1) + "s" + else: + m2 = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*s", line) + if m2: + dur = m2.group(1) + "s" + + if not dur: + return None + + # 动作名取耗时之前的文本片段,最多保留 60 字符 + idx = line.find("耗时") + action = line[:idx].strip() + if not action: + # 兜底:取整行前 60 字符 + action = line.strip()[:60] + if len(action) > 60: + action = action[:57] + "..." + return (action, dur) + + def refresh_realtime_tab(): + nonlocal realtime_after_id + cfg = read_config() + gui_cfg = cfg.get("gui", {}).get("realtime_status", {}) + refresh_ms = int(gui_cfg.get("refresh_interval_ms", 1000)) + tail_items = int(gui_cfg.get("tail_items", 50)) + + path = os.path.join(get_logs_dir(), "actions.log") + lines = tail_read_file(path) + parsed: list[tuple[str, str]] = [] + # 从文件末尾向前解析,保持原始顺序输出最近项 + for line in reversed(lines): + try: + out = parse_action_duration(line) + if out: + parsed.append(out) + if len(parsed) >= tail_items: + break + except Exception: + continue + + parsed = list(reversed(parsed)) + + realtime_text.configure(state="normal") + realtime_text.delete("1.0", "end") + if not parsed: + realtime_text.insert("1.0", "暂无动作日志(仅显示包含“耗时”的行)") + else: + for action, dur in parsed: + realtime_text.insert("end", f"{action} {dur}\n") + realtime_text.configure(state="disabled") + + # 安排下一次刷新 + try: + realtime_after_id = root.after(refresh_ms, refresh_realtime_tab) + except Exception: + realtime_after_id = None + + # 启动刷新(仅在 Tab 被创建时启动) + try: + refresh_realtime_tab() + except Exception: + pass + except Exception: + pass + # 搜索工具栏 log_search_frame = ttk.Frame(log_box) log_search_frame.pack(fill=X, padx=10, pady=(10, 5)) @@ -2811,12 +2913,10 @@ def main(): last_log_ts = stats.get("last_log_ts") if last_log_ts: - import datetime - - dt = datetime.datetime.fromtimestamp(last_log_ts) - lines.append(f"最近日志时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}") + dt = datetime.fromtimestamp(last_log_ts) + lines.append("最近日志时间: " + dt.strftime("%Y-%m-%d %H:%M:%S")) else: - lines.append(f"最近日志时间: -") + lines.append("最近日志时间: -") exit_code = stats.get("exit_code") lines.append(f"退出码: {exit_code if exit_code is not None else '-'}") @@ -3433,10 +3533,8 @@ def main(): lines.append(f"奖品价值: {prize_value} 元") updated_ts = fudai_last.get("updated_ts") if updated_ts: - import datetime - - dt = datetime.datetime.fromtimestamp(updated_ts) - lines.append(f"更新时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}") + dt = datetime.fromtimestamp(updated_ts) + lines.append("更新时间: " + dt.strftime("%Y-%m-%d %H:%M:%S")) lines.append("") # 中奖记录 @@ -3446,13 +3544,9 @@ def main(): lines.append(f"最近中奖记录(显示最近 {len(wins)} 条)") lines.append("=" * 60) for i, win in enumerate(wins[-10:], 1): # 只显示最近10条 - import datetime - ts = win.get("ts", 0) dt_str = ( - datetime.datetime.fromtimestamp(ts).strftime( - "%Y-%m-%d %H:%M:%S" - ) + datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") if ts else "-" ) @@ -3514,8 +3608,6 @@ def main(): data = json.load(f) reservation_text.delete("1.0", "end") - from datetime import datetime - updated_ts = ( float(data.get("updated_ts", 0.0) or 0.0) if isinstance(data, dict) @@ -3710,13 +3802,13 @@ def main(): # 格式化显示 lines.append( - f"┌─ 预约 #{idx} ─────────────────────────────────────────────" + "┌─ 预约 #" + str(idx) + " ─────────────────────────────────────────────" ) lines.append(f"│ 状态:{status_icon} {remain_str}") - lines.append(f"│") + lines.append("│") lines.append(f"│ 💰 奖品价值:{val:.2f} 元") lines.append(f"│ 📦 奖品内容:{content or '(无描述)'}") - lines.append(f"│") + lines.append("│") lines.append(f"│ ⏰ 预计开奖时间:{ft_str or '未知'}") if ft > 0: try: @@ -3728,7 +3820,7 @@ def main(): lines.append(f"│ 详细时间:{ft_str_detailed}") except Exception: pass - lines.append(f"│") + lines.append("│") lines.append( f"│ 📍 发现时直播间位置:第 {pos_seen + 1} 个直播间(索引:{pos_seen})" ) @@ -4213,8 +4305,6 @@ def main(): for idx, (file, file_path, mtime) in enumerate(win_images): # 格式化显示:文件名 + 时间 try: - from datetime import datetime - dt = datetime.fromtimestamp(mtime) time_str = dt.strftime("%Y-%m-%d %H:%M:%S") display_text = f"{file} ({time_str})" @@ -4338,8 +4428,6 @@ def main(): return try: - import json - with open(false_positive_file, "r", encoding="utf-8") as f: data = json.load(f) false_positives = data.get("false_positives", []) @@ -4372,8 +4460,6 @@ def main(): lines = [line.strip() for line in content.splitlines() if line.strip()] try: - import json - with open(false_positive_file, "w", encoding="utf-8") as f: json.dump({"false_positives": lines}, f, ensure_ascii=False, indent=2) on_line(f"[中奖记录] 已保存 {len(lines)} 条误识别记录") diff --git a/gui/gui_core.py b/gui/gui_core.py index 80de512..9694db0 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -30,7 +30,9 @@ def find_adb_executable() -> str: # 兼容某些人手动放到用户目录的情况 userprofile = os.environ.get("USERPROFILE") or "" if userprofile: - candidates.append(os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe")) + candidates.append( + os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe") + ) for p in candidates: if os.path.exists(p): @@ -137,7 +139,7 @@ class Runner: with self._lock: self._events.append(ev) if len(self._events) > self._events_cap: - self._events = self._events[-self._events_cap:] + self._events = self._events[-self._events_cap :] def _record_win(self) -> None: item = { @@ -147,7 +149,7 @@ class Runner: with self._lock: self._wins.append(item) if len(self._wins) > self._wins_cap: - self._wins = self._wins[-self._wins_cap:] + self._wins = self._wins[-self._wins_cap :] def _snapshot_fudai(self) -> dict: with self._lock: @@ -172,7 +174,9 @@ class Runner: content_extracted = False if "福袋内容:" in s: with self._lock: - self._fudai_last["content"] = s.split("福袋内容:", 1)[1].strip().split()[0] # 只取第一个词,避免包含后续字段 + self._fudai_last["content"] = ( + s.split("福袋内容:", 1)[1].strip().split()[0] + ) # 只取第一个词,避免包含后续字段 self._fudai_last["updated_ts"] = time.time() content_extracted = True else: @@ -209,7 +213,9 @@ class Runner: # 倒计时:支持多种格式 if "倒计时时间:" in s: with self._lock: - self._fudai_last["countdown"] = s.split("倒计时时间:", 1)[1].strip().split()[0] + self._fudai_last["countdown"] = ( + s.split("倒计时时间:", 1)[1].strip().split()[0] + ) self._fudai_last["updated_ts"] = time.time() else: m = re.search(r"(?:字段_)?倒计时[=:]?\s*([^\s]+)", s) @@ -219,7 +225,9 @@ class Runner: self._fudai_last["updated_ts"] = time.time() # 奖品价值:支持多种格式 - m = re.search(r"(?:字段_)?(?:价值|价值元|奖品价值)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s) + m = re.search( + r"(?:字段_)?(?:价值|价值元|奖品价值)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s + ) if not m: m = re.search(r"奖品价值:\s*([0-9]+(?:\.[0-9]+)?)\s*元", s) if m: @@ -234,7 +242,9 @@ class Runner: if "点击打开福袋详情" in s or ("[流程]" in s and "检测到福袋图标并点击" in s): self._inc("fudai_open_detail") self._record_event("fudai_open_detail", self._snapshot_fudai()) - if "点击参与抽奖" in s or ("[参与]" in s and ("动作=点击参与" in s or "动作=参与" in s)): + if "点击参与抽奖" in s or ( + "[参与]" in s and ("动作=点击参与" in s or "动作=参与" in s) + ): self._inc("fudai_click_attend") self._record_event("fudai_click_attend", self._snapshot_fudai()) @@ -243,7 +253,10 @@ class Runner: "已经参与,等待开奖" in s or "已经参与,等待看播时间凑齐开奖" in s or "已参与成功(或看播中)" in s - or ("[参与]" in s and ("结果=已参与" in s or "结果=看播中" in s or "结果=参与成功" in s)) + or ( + "[参与]" in s + and ("结果=已参与" in s or "结果=看播中" in s or "结果=参与成功" in s) + ) or ("[参与]" in s and "已参与" in s and "等待开奖" in s) or ("预约回退后直接参与" in s and "参与成功" in s) ): @@ -307,7 +320,9 @@ class Runner: self._record_event("fudai_skip", {"reason": "value_low", **meta}) if "福袋内容不理想" in s or ("[筛选]" in s and "内容" in s and "黑名单" in s): self._inc("fudai_skip_content") - self._record_event("fudai_skip", {"reason": "content", **self._snapshot_fudai()}) + self._record_event( + "fudai_skip", {"reason": "content", **self._snapshot_fudai()} + ) if "抽奖倒计时时间小于" in s and "不参与" in s: self._inc("fudai_skip_countdown_short") # 提取倒计时秒数 @@ -336,7 +351,9 @@ class Runner: or ("[参与]" in s and "结果=看播门槛" in s) ): self._inc("fudai_skip_watch_required") - self._record_event("fudai_skip", {"reason": "watch_required", **self._snapshot_fudai()}) + self._record_event( + "fudai_skip", {"reason": "watch_required", **self._snapshot_fudai()} + ) if "打开福袋异常" in s or ("[流程]" in s and "打开福袋异常" in s): self._inc("fudai_open_error") self._record_event("fudai_open_error", self._snapshot_fudai()) @@ -344,7 +361,9 @@ class Runner: self._inc("fudai_open_error_too_many") self._record_event("fudai_open_error_too_many", self._snapshot_fudai()) # 倒计时大于阈值但价值达到高价值阈值,记录预约 - if ("[流程]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s) or ("[参与]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s): + if ( + "[流程]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s + ) or ("[参与]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s): self._inc("fudai_reserved_high_value") # 提取价值和倒计时信息 meta = self._snapshot_fudai() @@ -415,7 +434,9 @@ class Runner: self._record_event("error_config_load", {}) # --- 状态文件错误 --- - if ("预约队列状态文件" in s or "reservations.json" in s) and ("失败" in s or "错误" in s): + if ("预约队列状态文件" in s or "reservations.json" in s) and ( + "失败" in s or "错误" in s + ): self._inc("error_state_file") self._record_event("error_state_file", {}) @@ -441,13 +462,17 @@ class Runner: self._record_event("fansclub_unresolved", self._snapshot_fudai()) # --- 预约队列/回退校验 --- - if ("[预约]" in s and "回退校验通过" in s) or "回退校验通过:已回到目标直播间" in s: + if ( + "[预约]" in s and "回退校验通过" in s + ) or "回退校验通过:已回到目标直播间" in s: self._inc("reservation_back_verify_ok") self._record_event("reservation_back_verify_ok", {}) if ("[预约]" in s and "回退校验失败" in s) or "回退校验失败" in s: self._inc("reservation_back_verify_fail") self._record_event("reservation_back_verify_fail", {}) - if ("[预约]" in s and "预约队列已满,丢弃最低价值" in s) or "预约队列已满,丢弃最低价值" in s: + if ( + "[预约]" in s and "预约队列已满,丢弃最低价值" in s + ) or "预约队列已满,丢弃最低价值" in s: self._inc("reservation_drop_low_value") self._record_event("reservation_drop_low_value", {}) if ("[预约]" in s and "清空预约队列" in s) or "清空预约队列" in s: @@ -455,7 +480,9 @@ class Runner: self._record_event("reservation_clear", {}) # --- 预约记录相关 --- - if ("[预约]" in s and "已记录高价值福袋" in s) or "record_high_value_reservation:已记录高价值福袋" in s: + if ( + "[预约]" in s and "已记录高价值福袋" in s + ) or "record_high_value_reservation:已记录高价值福袋" in s: self._inc("reservation_recorded") # 提取预约价值:支持多种格式 value = None @@ -477,7 +504,9 @@ class Runner: pass # 提取直播间名称 room_title = None - m = re.search(r"(?:字段_)?(?:直播间|直播间名|room_title)[=:]?\s*([^\s]+)", s) + m = re.search( + r"(?:字段_)?(?:直播间|直播间名|room_title)[=:]?\s*([^\s]+)", s + ) if m: room_title = m.group(1).strip() meta = self._snapshot_fudai() @@ -488,10 +517,16 @@ class Runner: if room_title: meta["room_title"] = room_title self._record_event("reservation_recorded", meta) - if ("[预约]" in s and "进入预约参与窗口" in s) or "进入预约参与窗口,准备回退到目标直播间" in s: + if ( + "[预约]" in s and "进入预约参与窗口" in s + ) or "进入预约参与窗口,准备回退到目标直播间" in s: self._inc("reservation_window_entered") self._record_event("reservation_window_entered", {}) - if ("[预约]" in s and "已回退到目标直播间" in s) or "已回退到目标直播间" in s or ("[预约]" in s and "已回退到最早开奖的预约直播间" in s): + if ( + ("[预约]" in s and "已回退到目标直播间" in s) + or "已回退到目标直播间" in s + or ("[预约]" in s and "已回退到最早开奖的预约直播间" in s) + ): self._inc("reservation_back_success") # 提取回退信息 meta = {} @@ -505,21 +540,29 @@ class Runner: if ("[预约]" in s and "时间窗口未到" in s) or "时间窗口未到,跳过回退" in s: self._inc("reservation_window_not_reached") self._record_event("reservation_window_not_reached", {}) - if ("[预约]" in s and "已明显错过开奖时间" in s) or "已明显错过开奖时间,清理过期预约" in s: + if ( + "[预约]" in s and "已明显错过开奖时间" in s + ) or "已明显错过开奖时间,清理过期预约" in s: self._inc("reservation_expired") self._record_event("reservation_expired", {}) - if ("[预约]" in s and "预约队列为空" in s) or "process_reservation_attend_window:预约队列为空" in s: + if ( + "[预约]" in s and "预约队列为空" in s + ) or "process_reservation_attend_window:预约队列为空" in s: self._inc("reservation_queue_empty") if ("[预约]" in s and "锁定期未结束" in s) or "锁定期未结束" in s: self._inc("reservation_locked") self._record_event("reservation_locked", {}) - if ("[预约]" in s and "已回退到第一个直播间" in s): + if "[预约]" in s and "已回退到第一个直播间" in s: self._inc("reservation_back_to_first") self._record_event("reservation_back_to_first", {}) - if ("[预约]" in s and "run_once_basic:检查预约回退触发条件" in s): + if "[预约]" in s and "run_once_basic:检查预约回退触发条件" in s: self._inc("reservation_check_triggered") # 预约队列满时等待 - if ("[预约]" in s and "队列已满" in s) or "handle_queue_full_wait_at_earliest" in s or ("[预约]" in s and "队列已满,回退到最早开奖的预约直播间" in s): + if ( + ("[预约]" in s and "队列已满" in s) + or "handle_queue_full_wait_at_earliest" in s + or ("[预约]" in s and "队列已满,回退到最早开奖的预约直播间" in s) + ): self._inc("reservation_queue_full_wait") self._record_event("reservation_queue_full_wait", {}) # 回退后直接参与 @@ -527,11 +570,11 @@ class Runner: self._inc("reservation_back_direct_attend") self._record_event("reservation_back_direct_attend", {}) # 队列满回退后设置参与标志 - if ("[预约]" in s and "队列满回退后,直接设置参与标志" in s): + if "[预约]" in s and "队列满回退后,直接设置参与标志" in s: self._inc("reservation_queue_full_back_attend") self._record_event("reservation_queue_full_back_attend", {}) # 通过相似度匹配识别重复预约 - if ("[预约]" in s and "通过相似度匹配识别为重复预约" in s): + if "[预约]" in s and "通过相似度匹配识别为重复预约" in s: self._inc("reservation_duplicate_detected") self._record_event("reservation_duplicate_detected", {}) @@ -539,7 +582,11 @@ class Runner: if "没有抽中" in s and "关闭弹窗" in s: self._inc("fudai_result_no_win") self._record_event("fudai_result_no_win", self._snapshot_fudai()) - if "恭喜中奖了" in s or "检测到中奖结果" in s or ("[开奖结果]" in s and "中奖" in s): + if ( + "恭喜中奖了" in s + or "检测到中奖结果" in s + or ("[开奖结果]" in s and "中奖" in s) + ): self._inc("fudai_result_win") # 提取中奖信息 meta = self._snapshot_fudai() @@ -553,7 +600,9 @@ class Runner: self._record_event("fudai_order_success", self._snapshot_fudai()) # 等待开奖(只在设置等待开奖标志时计数,避免重复计数) # 注意:不要匹配"已经参与,等待开奖",因为那已经在参与成功时计数了 - if ("[参与]" in s and "参与成功,设置等待开奖标志" in s) or ("[参与]" in s and "设置等待开奖标志" in s): + if ("[参与]" in s and "参与成功,设置等待开奖标志" in s) or ( + "[参与]" in s and "设置等待开奖标志" in s + ): self._inc("fudai_waiting_lottery") # 提取剩余秒数 meta = self._snapshot_fudai() @@ -593,7 +642,9 @@ class Runner: elif "锁定期内" in s: self._inc("switch_room_locked") meta_reason = "locked" - self._record_event("switch_room", {"reason": meta_reason, **self._snapshot_fudai()}) + self._record_event( + "switch_room", {"reason": meta_reason, **self._snapshot_fudai()} + ) # --- 阶段诊断统计 --- if "[阶段诊断]" in s or "阶段诊断" in s: @@ -637,14 +688,21 @@ class Runner: # 记录耗时较长的操作 if elapsed > 5.0: self._inc("slow_operation") - self._record_event("slow_operation", {"elapsed_seconds": elapsed, "operation": s[:100]}) + self._record_event( + "slow_operation", + {"elapsed_seconds": elapsed, "operation": s[:100]}, + ) except Exception: pass # --- 详情识别统计 --- if ("[福袋详情]" in s and "识别" in s) or "识别福袋详情" in s: self._inc("fudai_detail_read_attempt") - if "识别成功" in s or "识别完成" in s or "read_fudai_detail_once完成(成功)" in s: + if ( + "识别成功" in s + or "识别完成" in s + or "read_fudai_detail_once完成(成功)" in s + ): self._inc("fudai_detail_read_success") # 提取任务数量 meta = {} @@ -741,7 +799,10 @@ class Runner: cmd += ["--min-prize-value-yuan", str(params.min_prize_value_yuan)] # 这些参数是新增可调节项:倒计时太短跳过、参与人数范围 - cmd += ["--skip-if-countdown-gt-seconds", str(int(params.skip_if_countdown_gt_seconds or 900))] + cmd += [ + "--skip-if-countdown-gt-seconds", + str(int(params.skip_if_countdown_gt_seconds or 900)), + ] if params.reset_after_swipes_enabled: cmd.append("--reset-after-swipes-enabled") cmd += ["--reset-after-swipes", str(int(params.reset_after_swipes or 10))] @@ -771,11 +832,17 @@ class Runner: else: cmd.append("--reservation-back-verify-disabled") if params.reservation_back_swipe_delay > 0: - cmd += ["--reservation-back-swipe-delay", str(params.reservation_back_swipe_delay)] + cmd += [ + "--reservation-back-swipe-delay", + str(params.reservation_back_swipe_delay), + ] # 预约抢占最小价值 if params.reservation_preempt_min_value > 0: - cmd += ["--reservation-preempt-min-value", str(params.reservation_preempt_min_value)] + cmd += [ + "--reservation-preempt-min-value", + str(params.reservation_preempt_min_value), + ] # 找福袋最大尝试次数 if params.fudai_find_max_attempts > 0: @@ -794,7 +861,9 @@ class Runner: cmd.append("--fudai-template-disabled") # 添加福袋模板匹配阈值参数 - cmd.extend(["--fudai-template-threshold", str(params.fudai_template_match_threshold)]) + cmd.extend( + ["--fudai-template-threshold", str(params.fudai_template_match_threshold)] + ) # 继承当前环境,并确保 adb 在 PATH(即使用户没手动刷新 PATH) env = os.environ.copy() @@ -806,7 +875,9 @@ class Runner: env["PATH"] = adb_dir + os.pathsep + env.get("PATH", "") env["ADB_EXECUTABLE"] = adb_exe else: - self._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH") + self._on_line( + "[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH" + ) try: p = subprocess.Popen( @@ -876,7 +947,9 @@ class Runner: # 如果进程立即退出且没有输出,说明可能有问题 if not has_output and rc != 0: self._on_line(f"[警告] 进程立即退出,退出码={rc},没有输出") - self._on_line("[提示] 可能的原因:run_cli.py启动失败、导入错误或配置错误") + self._on_line( + "[提示] 可能的原因:run_cli.py启动失败、导入错误或配置错误" + ) else: self._on_line(f"[进程结束] exit_code={rc}") except Exception as e: diff --git a/run_cli.py b/run_cli.py index b0f1553..c3b1802 100644 --- a/run_cli.py +++ b/run_cli.py @@ -4,6 +4,16 @@ import os import shutil import sys +# 可选:全局参数/调用跟踪(仅在环境变量 PARAM_TRACK_ALL=1 时启用) +if os.environ.get("PARAM_TRACK_ALL") == "1": + try: + from douyin.utils.param_usage_tracer import start_tracing + + start_tracing() + except Exception: + # 启用失败不影响主流程 + pass + # ==== 首先配置日志系统,确保日志文件能正常写入 ============================== try: from douyin.logging import douyin_logging diff --git a/scripts/inspect_lines.py b/scripts/inspect_lines.py new file mode 100644 index 0000000..98ba953 --- /dev/null +++ b/scripts/inspect_lines.py @@ -0,0 +1,12 @@ +import sys +path = sys.argv[1] +start = int(sys.argv[2]) +end = int(sys.argv[3]) +with open(path, 'r', encoding='utf-8') as f: + lines = f.readlines() +for i in range(start, end+1): + idx = i-1 + if 0 <= idx < len(lines): + line = lines[idx].rstrip('\n') + print(f"{i:4}: {line}") + print(' repr:', repr(lines[idx])) diff --git a/tools/generate_param_locations.py b/tools/generate_param_locations.py new file mode 100644 index 0000000..b26762c --- /dev/null +++ b/tools/generate_param_locations.py @@ -0,0 +1,115 @@ +"""扫描仓库并生成参数位置报告。 + +输出文件:`state/param_locations.json`,包含: +- functions: 列出所有函数定义及其参数 +- argparse: 列出所有 argparse 的 add_argument 参数名 +- track_param_calls: 列出所有 `track_param(...)` 调用位置与第一个参数(如果为字符串字面量) +- track_call_calls: 列出所有 `track_call` 出现位置 + +用法: + python tools/generate_param_locations.py +""" +from __future__ import annotations + +import ast +import json +import os +import re +from typing import Dict, List, Any + +ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) +OUT_PATH = os.path.join(ROOT, "state", "param_locations.json") + + +def scan_py_file(path: str) -> Dict[str, List[Dict[str, Any]]]: + res = {"functions": [], "argparse": [], "track_param_calls": [], "track_call_calls": []} + try: + with open(path, "r", encoding="utf-8", errors="ignore") as f: + src = f.read() + except Exception: + return res + + try: + tree = ast.parse(src, filename=path) + except Exception: + # fallback to regex scanning + for i, line in enumerate(src.splitlines(), 1): + if "track_param(" in line: + res["track_param_calls"].append({"file": path, "line": i, "text": line.strip()}) + if "track_call(" in line or "@track_call" in line: + res["track_call_calls"].append({"file": path, "line": i, "text": line.strip()}) + if "add_argument(" in line: + # try extract string args + for m in re.finditer(r"([\'\"]--?[\w-]+[\'\"])", line): + res["argparse"].append({"file": path, "line": i, "arg": m.group(1).strip("'\"")}) + return res + + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef): + params = [] + for a in node.args.args: + params.append(a.arg) + # include varargs/kw + if node.args.vararg: + params.append("*" + node.args.vararg.arg) + if node.args.kwarg: + params.append("**" + node.args.kwarg.arg) + res["functions"].append({"file": path, "line": node.lineno, "name": node.name, "params": params}) + + if isinstance(node, ast.Call): + # add_argument + try: + func = node.func + func_name = None + if isinstance(func, ast.Attribute): + func_name = func.attr + elif isinstance(func, ast.Name): + func_name = func.id + if func_name == "add_argument": + # extract string literals from args + for arg in node.args: + if isinstance(arg, ast.Constant) and isinstance(arg.value, str): + res["argparse"].append({"file": path, "line": node.lineno, "arg": arg.value}) + # track_param calls + if (isinstance(func, ast.Name) and func.id == "track_param") or ( + isinstance(func, ast.Attribute) and func.attr == "track_param" + ): + first = None + if node.args: + a0 = node.args[0] + if isinstance(a0, ast.Constant) and isinstance(a0.value, str): + first = a0.value + res["track_param_calls"].append({"file": path, "line": node.lineno, "param_name": first}) + if (isinstance(func, ast.Name) and func.id == "track_call") or ( + isinstance(func, ast.Attribute) and func.attr == "track_call" + ): + res["track_call_calls"].append({"file": path, "line": node.lineno}) + except Exception: + pass + + return res + + +def main() -> int: + out: Dict[str, List[Any]] = {"functions": [], "argparse": [], "track_param_calls": [], "track_call_calls": []} + for dirpath, dirs, files in os.walk(ROOT): + # skip virtual envs and git + if ".venv" in dirpath or ".git" in dirpath: + continue + for fn in files: + if not fn.endswith(".py"): + continue + path = os.path.join(dirpath, fn) + parts = scan_py_file(path) + for k in out: + out[k].extend(parts.get(k, [])) + + os.makedirs(os.path.dirname(OUT_PATH), exist_ok=True) + with open(OUT_PATH, "w", encoding="utf-8") as f: + json.dump({"generated_at": __import__("time").time(), "report": out}, f, ensure_ascii=False, indent=2) + print("written:", OUT_PATH) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/param_usage_tool.py b/tools/param_usage_tool.py new file mode 100644 index 0000000..237b132 --- /dev/null +++ b/tools/param_usage_tool.py @@ -0,0 +1,149 @@ +"""命令行工具:查看与分析 `state/param_usage.json` 记录,或静态扫描代码中的跟踪调用。 + +用法示例: + python tools/param_usage_tool.py show --limit 200 + python tools/param_usage_tool.py scan --pattern track_param + python tools/param_usage_tool.py tail +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +import time +from collections import defaultdict +from typing import Dict, List + +ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) +STATE_PATH = os.path.join(ROOT, "state", "param_usage.json") + + +def read_entries(path: str) -> List[Dict]: + if not os.path.exists(path): + return [] + out = [] + with open(path, "r", encoding="utf-8") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + out.append(json.loads(line)) + except Exception: + continue + return out + + +def cmd_show(args: argparse.Namespace) -> int: + entries = read_entries(STATE_PATH) + if not entries: + print("no entries found: {}".format(STATE_PATH)) + return 1 + + if args.limit: + entries = entries[-args.limit :] + + by_param = defaultdict(list) + calls = [] + for e in entries: + t = e.get("type") + if t == "param_access": + by_param[e.get("param")].append(e) + else: + calls.append(e) + + print("Summary:") + print(" param_access entries: {}".format(sum(len(v) for v in by_param.values()))) + print(" call entries: {}".format(len(calls))) + print("") + + if args.param: + items = by_param.get(args.param) + if not items: + print(f"no records for param: {args.param}") + return 0 + for i in items: + print(json.dumps(i, ensure_ascii=False)) + return 0 + + # show top params + top = sorted(by_param.items(), key=lambda kv: -len(kv[1]))[: args.top] + for name, lst in top: + first = lst[0] + print(f"{name}: count={len(lst)} first_at={first.get('caller_file')}:{first.get('caller_line')}") + + return 0 + + +def cmd_tail(args: argparse.Namespace) -> int: + print("tailing {} (press Ctrl-C to stop)".format(STATE_PATH)) + try: + with open(STATE_PATH, "r", encoding="utf-8") as f: + # seek to end + f.seek(0, os.SEEK_END) + while True: + line = f.readline() + if not line: + time.sleep(0.5) + continue + print(line.rstrip()) + except KeyboardInterrupt: + return 0 + except FileNotFoundError: + print("file not found: {}".format(STATE_PATH)) + return 1 + + +def cmd_scan(args: argparse.Namespace) -> int: + root = os.path.abspath(args.root or ROOT) + matches = [] + for dirpath, dirs, files in os.walk(root): + # skip virtual envs and .git + if ".venv" in dirpath or ".git" in dirpath: + continue + for fn in files: + if not fn.endswith((".py", ".md", ".txt")): + continue + path = os.path.join(dirpath, fn) + try: + with open(path, "r", encoding="utf-8", errors="ignore") as f: + for i, line in enumerate(f, 1): + if args.pattern in line: + matches.append((path, i, line.strip())) + except Exception: + continue + + for p, lno, text in matches: + print(f"{p}:{lno}: {text}") + print(f"found {len(matches)} matches for '{args.pattern}'") + return 0 + + +def main(argv: List[str]) -> int: + p = argparse.ArgumentParser(description="Param usage viewer tool") + sp = p.add_subparsers(dest="cmd") + + s_show = sp.add_parser("show") + s_show.add_argument("--limit", type=int, default=200) + s_show.add_argument("--top", type=int, default=20) + s_show.add_argument("--param", type=str, help="show specific param records") + s_show.set_defaults(func=cmd_show) + + s_tail = sp.add_parser("tail") + s_tail.set_defaults(func=cmd_tail) + + s_scan = sp.add_parser("scan") + s_scan.add_argument("pattern", help="substring to search for") + s_scan.add_argument("--root", help="root to scan") + s_scan.set_defaults(func=cmd_scan) + + args = p.parse_args(argv) + if not args.cmd: + p.print_help() + return 1 + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tools/simulate_reservation_preempted_flow.py b/tools/simulate_reservation_preempted_flow.py new file mode 100644 index 0000000..7c4cd62 --- /dev/null +++ b/tools/simulate_reservation_preempted_flow.py @@ -0,0 +1,167 @@ +"""\ +模拟检查:预约回退 preempted=True 是否仍会导致 run_once_basic 提前 return。 + +背景:之前在 `process_reservation_attend_window` 返回 preempted=True 后, +`run_once_basic()` 直接 return,导致锁定期内每轮都重复“预约回退成功”, +但不会进入后续直播间识别/参与逻辑,观感为卡死。 + +本脚本做两件事: +1) 用 AST 精确定位到包含“预约回退成功:进入回退处理”日志的 if preempted 分支 +2) 断言该分支 body 中不包含 `return` 语句(否则就是老 bug 复现) + +运行: + .venv/Scripts/python.exe tools/simulate_reservation_preempted_flow.py +""" + +from __future__ import annotations + +import ast +from pathlib import Path + + +REPO_ROOT = Path(__file__).resolve().parents[1] +TARGET_FILE = REPO_ROOT / "douyin" / "core" / "douyin_fudai.py" +TARGET_LOG_SNIPPET = "[预约] 预约回退成功:进入回退处理(直接参与标志已移除)" + + +class _FoundBlock(Exception): + def __init__(self, has_return: bool, lineno: int) -> None: + super().__init__("found") + self.has_return = has_return + self.lineno = lineno + + +def _node_contains_return(node: ast.AST) -> bool: + """检查 node 子树中是否存在 return(忽略嵌套函数/类/lambda 内部的 return)。 + + 目的:我们只关心 if preempted 分支本身是否直接 return, + 不应把分支里定义的 helper(例如 _write_state 的节流 return)算进去。 + """ + + class _ReturnFinder(ast.NodeVisitor): + def __init__(self) -> None: + self.found = False + + def visit_Return(self, _n: ast.Return) -> None: # noqa: N802 + self.found = True + + def visit_FunctionDef(self, _n: ast.FunctionDef) -> None: # noqa: N802 + # 不进入嵌套函数 + return + + def visit_AsyncFunctionDef(self, _n: ast.AsyncFunctionDef) -> None: # noqa: N802 + return + + def visit_Lambda(self, _n: ast.Lambda) -> None: # noqa: N802 + return + + def visit_ClassDef(self, _n: ast.ClassDef) -> None: # noqa: N802 + return + + finder = _ReturnFinder() + finder.visit(node) + return finder.found + + +def _node_contains_target_log(node: ast.AST) -> bool: + """粗略匹配:在该 node 子树中出现目标日志字符串常量。""" + for sub in ast.walk(node): + if isinstance(sub, ast.Constant) and isinstance(sub.value, str): + if TARGET_LOG_SNIPPET in sub.value: + return True + return False + + +def _check() -> tuple[bool, int]: + src = TARGET_FILE.read_text(encoding="utf-8") + tree = ast.parse(src, filename=str(TARGET_FILE)) + + parent: dict[ast.AST, ast.AST] = {} + + class _ParentBuilder(ast.NodeVisitor): + def generic_visit(self, node: ast.AST) -> None: + for child in ast.iter_child_nodes(node): + parent[child] = node + super().generic_visit(node) + + _ParentBuilder().visit(tree) + + def _is_self_log_kv_call(n: ast.AST) -> bool: + if not isinstance(n, ast.Call): + return False + f = n.func + return ( + isinstance(f, ast.Attribute) + and f.attr == "_log_kv" + and isinstance(f.value, ast.Name) + and f.value.id == "self" + ) + + def _call_has_target_string(n: ast.Call) -> bool: + for arg in list(n.args) + [kw.value for kw in n.keywords]: + if isinstance(arg, ast.Constant) and isinstance(arg.value, str): + if TARGET_LOG_SNIPPET in arg.value: + return True + return False + + # 定位 class fudai_analyse -> def run_once_basic + for node in tree.body: + if isinstance(node, ast.ClassDef) and node.name == "fudai_analyse": + for item in node.body: + if isinstance(item, ast.FunctionDef) and item.name == "run_once_basic": + # 先找到目标日志对应的 _log_kv 调用点 + target_call: ast.Call | None = None + for sub in ast.walk(item): + if _is_self_log_kv_call(sub) and _call_has_target_string(sub): + target_call = sub + break + + if target_call is None: + continue + + # 从调用点向上找最近的 enclosing If + cur: ast.AST = target_call + enclosing_if: ast.If | None = None + while cur in parent: + cur = parent[cur] + if isinstance(cur, ast.If): + enclosing_if = cur + break + + if enclosing_if is None: + raise RuntimeError( + "Found target log call but could not find enclosing If" + ) + + has_return = _node_contains_return(enclosing_if) + lineno = getattr(enclosing_if, "lineno", -1) + raise _FoundBlock(has_return=has_return, lineno=lineno) + + raise RuntimeError( + f"未找到目标分支:{TARGET_LOG_SNIPPET}(文件:{TARGET_FILE})" + ) + + +def main() -> None: + try: + _check() + # 如果没抛 _FoundBlock,就说明没找到 + print("FAIL: could not locate target if(preempted) block") + raise SystemExit(2) + except _FoundBlock as e: + if e.has_return: + print( + "FAIL: early return still exists (can cause reservation back spin) " + f"at {TARGET_FILE}:{e.lineno}" + ) + raise SystemExit(1) + + print( + "PASS: no early return in preempted=True branch; " + "run_once_basic will continue with follow-up flow " + f"(checked at {TARGET_FILE}:{e.lineno})" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/simulate_reservation_preempted_flow_dynamic.py b/tools/simulate_reservation_preempted_flow_dynamic.py new file mode 100644 index 0000000..fddfc46 --- /dev/null +++ b/tools/simulate_reservation_preempted_flow_dynamic.py @@ -0,0 +1,140 @@ +"""\ +动态模拟:验证预约回退 preempted=True 后,run_once_basic 不会提前退出。 + +不连真机/不跑 ADB: +- monkeypatch `douyin.reservation.douyin_reservation_logic.process_reservation_attend_window` + 令其返回 True(模拟已触发回退/抢占)。 +- 给 analyser 注入一个 FakeOperation,在后续流程的截图阶段抛出哨兵异常。 + +判定标准: +- 若能捕获到“进入截图阶段”的哨兵异常 => 说明 preempted=True 后仍继续执行到后续流程(PASS) +- 若 run_once_basic 正常 return 或在更早阶段异常退出 => FAIL + +运行: + .venv/Scripts/python.exe tools/simulate_reservation_preempted_flow_dynamic.py +""" + +from __future__ import annotations + +import os +import sys +import time +import traceback +from pathlib import Path + + +class _ReachedScreenshot(Exception): + pass + + +class _FakeOperation: + def get_screenshot(self, *_args, **_kwargs): + raise _ReachedScreenshot("reached operation.get_screenshot") + + def delay(self, _s: float) -> None: + return + + def get_top_package(self, _device_id: str) -> str: + return "com.ss.android.ugc.aweme" + + +def main() -> None: + # 避免导入底层 OCR 时的初始化开销 + os.environ.setdefault("SKIP_OCR_INIT", "1") + + # 确保能导入本仓库代码(避免因工作目录不同导致 ModuleNotFoundError) + repo_root = Path(__file__).resolve().parents[1] + if str(repo_root) not in sys.path: + sys.path.insert(0, str(repo_root)) + + # 1) 导入 analyser + from douyin.core.douyin_fudai import fudai_analyse # noqa: WPS433 + + # 2) monkeypatch reservation 回退逻辑:强制 preempted=True + from douyin.reservation import douyin_reservation_logic # noqa: WPS433 + + original_fn = douyin_reservation_logic.process_reservation_attend_window + + def _fake_process_reservation_attend_window( + analyser, + reservations, + room_pos, + reservation_focus_until_ts_ref, + reservation_after_action_pending_ref, + **_kwargs, + ) -> bool: + # 模拟:已经回退成功并进入锁定期 + now = time.time() + if reservation_focus_until_ts_ref: + reservation_focus_until_ts_ref[0] = now + 60.0 + if reservation_after_action_pending_ref: + reservation_after_action_pending_ref[0] = True + return True + + douyin_reservation_logic.process_reservation_attend_window = ( + _fake_process_reservation_attend_window + ) + + try: + # 3) 构造一个尽量“瘦”的 analyser(避免 __init__ 做太多事) + analyser = fudai_analyse.__new__(fudai_analyse) + + # 必要字段:日志、配置、状态 + analyser._log_kv = lambda *_a, **_k: None + analyser.operation = _FakeOperation() + analyser.device_id = "FAKE_DEVICE" + + analyser._waiting_for_lottery_result = False + analyser._lottery_result_expected_ts = 0.0 + + # 防止 30 分钟超时分支触发复杂自救 + analyser._last_successful_attend_ts = time.time() + analyser._no_attend_timeout_minutes = 30.0 + analyser._run_start_ts = time.time() + + # 预约相关 + analyser.high_value_fudai_enabled = True + analyser.needswitch = True + analyser.room_pos = 7 + analyser.reservation_back_swipe_delay = 0.6 + analyser.reservations = [ + { + "future_ts": time.time() + 120.0, + "prize_value_yuan": 999.0, + "pos_seen": 4, + "content": "", + "room_title": "", + "room_title_raw": "", + } + ] + analyser._first_run_once_basic = False + + analyser._skip_stage_diagnosis_and_find_fudai = False + + # 4) 执行:若 preempted=True 后继续,必然会到截图阶段并触发哨兵异常 + try: + analyser.run_once_basic() + except _ReachedScreenshot: + print( + "PASS: preempted=True did not early-return; reached screenshot stage" + ) + return + + print( + "FAIL: run_once_basic returned before reaching screenshot stage " + "(likely early-return or unexpected short-circuit)" + ) + raise SystemExit(1) + + except Exception as exc: + print(f"FAIL: unexpected exception: {type(exc).__name__}: {exc}") + traceback.print_exc() + raise SystemExit(2) + + finally: + # 恢复 monkeypatch + douyin_reservation_logic.process_reservation_attend_window = original_fn + + +if __name__ == "__main__": + main()