From ee0511e327d09352ba1637aa49dad6ef91d2c2c4 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 3 Jan 2026 04:07:10 +0800 Subject: [PATCH] =?UTF-8?q?feat(logging):=20=E6=9B=B4=E6=96=B0=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E8=AE=B0=E5=BD=95=EF=BC=8C=E6=B7=BB=E5=8A=A0=E4=B8=8D?= =?UTF-8?q?=E5=90=8C=E6=97=A5=E5=BF=97=E7=B1=BB=E5=9E=8B=E4=BB=A5=E5=A2=9E?= =?UTF-8?q?=E5=BC=BA=E8=B0=83=E8=AF=95=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- douyin/core/state/reservations.json | 2 +- douyin/fudai/core/fudai_detail_reader.py | 8 +- douyin/fudai/douyin_fudai_core.py | 8 +- douyin/stage/douyin_stage.py | 6 +- douyin/stage/douyin_stage_handler.py | 271 ++++++++++++++---- .../fudai_detail_coupon_detection.py | 29 +- .../fudai_detail_operations.py | 26 +- fudai_detail_modules/fudai_detail_reader.py | 231 +++++++++------ gui/gui_app.py | 8 + 9 files changed, 432 insertions(+), 157 deletions(-) diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index adcb430..cababdb 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,5 +1,5 @@ { - "updated_ts": 1767383106.9903107, + "updated_ts": 1767383746.067418, "reason": "startup_clear", "room_pos": 0, "current_room_title": "", diff --git a/douyin/fudai/core/fudai_detail_reader.py b/douyin/fudai/core/fudai_detail_reader.py index 1a5c9ed..0090ebf 100644 --- a/douyin/fudai/core/fudai_detail_reader.py +++ b/douyin/fudai/core/fudai_detail_reader.py @@ -559,14 +559,18 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo optimal_workers = get_optimal_workers() with ThreadPoolExecutor(max_workers=optimal_workers) as executor: future_task_list = executor.submit(ocr_task_list) - future_content = executor.submit(ocr_content) + # 有条件地提交 content OCR,避免在配置启用时仍然调度任务 + if disable_content_recognition: + future_content = None + else: + future_content = executor.submit(ocr_content) future_countdown_mm = executor.submit(ocr_countdown_mm) future_countdown_ss = executor.submit(ocr_countdown_ss) future_value = executor.submit(ocr_value) # 等待所有操作完成 task_list_raw = future_task_list.result() - fudai_content_raw = future_content.result() + fudai_content_raw = future_content.result() if future_content else None countdown_mm_raw = future_countdown_mm.result() countdown_ss_raw = future_countdown_ss.result() value_raw = future_value.result() diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index 68f97f6..01dc6cf 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -935,12 +935,14 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo task_funcs = { "task_list": ocr_task_list, - "content": ocr_content, "countdown_mm": ocr_countdown_mm, "countdown_ss": ocr_countdown_ss, "value": ocr_value, "button": ocr_button, } + # 如果配置启用,避免把 content 任务加入并行队列,彻底不调度该OCR + if not disable_content_recognition: + task_funcs["content"] = ocr_content futures: Dict[str, Any] = {} start_ts: Dict[str, float] = {} @@ -1323,12 +1325,14 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo task_funcs = { "task_list": ocr_task_list_fallback, - "content": ocr_content_fallback, "countdown_mm": ocr_countdown_mm_fallback, "countdown_ss": ocr_countdown_ss_fallback, "value": ocr_value_fallback, "button": ocr_button_fallback, } + # 如果配置允许,则加入备用 content OCR,否则不调度 + if not disable_content_recognition: + task_funcs["content"] = ocr_content_fallback futures: Dict[str, Any] = {} start_ts: Dict[str, float] = {} for name, func in task_funcs.items(): diff --git a/douyin/stage/douyin_stage.py b/douyin/stage/douyin_stage.py index 4dbab64..659ec4b 100644 --- a/douyin/stage/douyin_stage.py +++ b/douyin/stage/douyin_stage.py @@ -37,6 +37,8 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: # _log_kv 会同时写入 actions.log 和输出到 stdout # 如果 verbose=False,我们需要控制 stdout 输出,但行为日志应该始终记录 # 由于 _log_kv 的设计,我们暂时让它始终调用,确保行为日志有完整记录 + # 默认将详细阶段诊断标记为 DEBUG 类型,允许调用点覆盖 + fields.setdefault("log_type", "DEBUG") analyser._log_kv("阶段诊断", msg, **fields) # type: ignore[attr-defined] except Exception: # 兜底:避免任何日志异常影响主流程 @@ -45,6 +47,8 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: def _log_summary(msg: str, **fields): """阶段诊断精简日志入口:始终输出,用于记录最终结果等关键信息。""" try: + # Summary 级别默认认为是操作/结果类日志,使用 OP 类型 + fields.setdefault("log_type", "OP") analyser._log_kv("阶段诊断", msg, **fields) except Exception: # 兜底:避免任何日志异常影响主流程 @@ -59,7 +63,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: msg = f"\n{char * 3} {title} {char * 3}\n" else: msg = f"\n{char * 10}\n" - analyser._log_kv("阶段诊断", msg) + analyser._log_kv("阶段诊断", msg, log_type="DEBUG") except Exception: pass diff --git a/douyin/stage/douyin_stage_handler.py b/douyin/stage/douyin_stage_handler.py index 07e72fd..ce28775 100644 --- a/douyin/stage/douyin_stage_handler.py +++ b/douyin/stage/douyin_stage_handler.py @@ -23,7 +23,9 @@ class StageHandler: """阶段处理器:统一管理阶段处理""" @staticmethod # type: ignore[misc] - def diagnose_stage_from_current_screen(analyser: Any, force_screenshot: bool = False) -> Tuple[str, str]: + def diagnose_stage_from_current_screen( + analyser: Any, force_screenshot: bool = False + ) -> Tuple[str, str]: """封装到子模块的阶段诊断入口。 参数: @@ -84,6 +86,7 @@ class StageHandler: analyser._log_kv( # type: ignore[attr-defined] "阶段诊断", "_check_in_live_room_by_icon 缺少opencv/numpy,跳过图形识别", + log_type="DEBUG", ) except Exception: pass @@ -94,6 +97,7 @@ class StageHandler: # 使用统一的模板路径配置 try: import path_config + assets_dir = path_config.get_assets_dir() except Exception: # 回退到旧路径(向后兼容) @@ -102,6 +106,7 @@ class StageHandler: # 使用统一的截图路径配置 try: import path_config + screenshot_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) @@ -117,6 +122,7 @@ class StageHandler: analyser._log_kv( # type: ignore[attr-defined] "阶段诊断", "_check_in_live_room_by_icon 获取截图失败", + log_type="SCREENSHOT", error=str(e), ) except Exception: @@ -127,6 +133,7 @@ class StageHandler: # 尝试从项目根目录的 pic 目录查找 try: import path_config + alt_path = path_config.get_screenshot_path() if os.path.exists(alt_path) and alt_path != screenshot_path: # 如果找到备用路径,使用它 @@ -140,6 +147,7 @@ class StageHandler: analyser._log_kv( # type: ignore[attr-defined] "阶段诊断", "_check_in_live_room_by_icon 截图不存在", + log_type="SCREENSHOT", path=screenshot_path, ) except Exception: @@ -159,16 +167,17 @@ class StageHandler: except Exception as e: try: analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", "_check_in_live_room_by_icon 读取截图失败", error=str(e) + "阶段诊断", + "_check_in_live_room_by_icon 读取截图失败", + log_type="SCREENSHOT", + error=str(e), ) except Exception: pass return False, 0.0 # 获取可配置的匹配阈值 - threshold = float( - getattr(analyser, "live_room_match_threshold", 0.8) or 0.8 - ) + threshold = float(getattr(analyser, "live_room_match_threshold", 0.8) or 0.8) template_threshold = threshold * 0.9 # 模板匹配阈值设为像素检测阈值的90% threshold = max(0.0, min(1.0, threshold)) template_threshold = max(0.0, min(1.0, template_threshold)) @@ -200,9 +209,15 @@ class StageHandler: if roi_x1 >= roi_x2 or roi_y1 >= roi_y2: try: analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", "_check_in_live_room_by_icon ROI区域无效", - roi_x1=roi_x1, roi_y1=roi_y1, roi_x2=roi_x2, roi_y2=roi_y2, - img_width=iw, img_height=ih + "阶段诊断", + "_check_in_live_room_by_icon ROI区域无效", + log_type="DEBUG", + roi_x1=roi_x1, + roi_y1=roi_y1, + roi_x2=roi_x2, + roi_y2=roi_y2, + img_width=iw, + img_height=ih, ) except Exception: pass @@ -231,6 +246,7 @@ class StageHandler: # 使用统一的 pic 目录配置 try: import path_config + pic_dir = path_config.get_pic_dir() except Exception: # 回退到旧路径(向后兼容) @@ -280,12 +296,15 @@ class StageHandler: for template_path, roi_path, icon_name in template_roi_pairs: try: # 调试日志:检查文件存在性 - template_exists = os.path.exists(template_path) and os.path.isfile(template_path) + template_exists = os.path.exists(template_path) and os.path.isfile( + template_path + ) roi_exists = os.path.exists(roi_path) and os.path.isfile(roi_path) try: analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", f"_check_in_live_room_by_icon 检查文件", + "阶段诊断", + f"_check_in_live_room_by_icon 检查文件", icon_name=icon_name, template_exists=template_exists, template_path=template_path, @@ -298,7 +317,8 @@ class StageHandler: if not template_exists: try: analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", f"_check_in_live_room_by_icon 模板文件不存在", + "阶段诊断", + f"_check_in_live_room_by_icon 模板文件不存在", icon_name=icon_name, template_path=template_path, ) @@ -310,7 +330,8 @@ class StageHandler: if os.path.getsize(template_path) == 0: try: analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", f"_check_in_live_room_by_icon 模板文件为空", + "阶段诊断", + f"_check_in_live_room_by_icon 模板文件为空", icon_name=icon_name, template_path=template_path, ) @@ -323,7 +344,8 @@ class StageHandler: if not roi_exists: try: analyser._log_kv( # type: ignore[attr-defined] - "阶段诊断", f"_check_in_live_room_by_icon ROI文件不存在", + "阶段诊断", + f"_check_in_live_room_by_icon ROI文件不存在", icon_name=icon_name, roi_path=roi_path, ) @@ -411,7 +433,10 @@ class StageHandler: tpl_edges_morph = cv2.morphologyEx(tpl_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined] # 使用固定阈值二值化图像作为主要匹配图像(针对白色x和深灰背景优化) - if roi_binary_fixed is not None and tpl_binary_fixed is not None: + if ( + roi_binary_fixed is not None + and tpl_binary_fixed is not None + ): roi_img_enhanced = roi_binary_fixed tpl_enhanced = tpl_binary_fixed else: @@ -469,11 +494,25 @@ class StageHandler: if icon_name == "x" and use_edges: try: - tpl_binary_adaptive_backup = cv2.resize(tpl_binary_adaptive_backup, (max(1, int(tw)), max(1, int(th)))) - tpl_binary_otsu_backup = cv2.resize(tpl_binary_otsu_backup, (max(1, int(tw)), max(1, int(th)))) - tpl_edges_backup = cv2.resize(tpl_edges_backup, (max(1, int(tw)), max(1, int(th)))) - tpl_edges_aggressive_backup = cv2.resize(tpl_edges_aggressive_backup, (max(1, int(tw)), max(1, int(th)))) - tpl_edges_morph_backup = cv2.resize(tpl_edges_morph_backup, (max(1, int(tw)), max(1, int(th)))) + tpl_binary_adaptive_backup = cv2.resize( + tpl_binary_adaptive_backup, + (max(1, int(tw)), max(1, int(th))), + ) + tpl_binary_otsu_backup = cv2.resize( + tpl_binary_otsu_backup, + (max(1, int(tw)), max(1, int(th))), + ) + tpl_edges_backup = cv2.resize( + tpl_edges_backup, (max(1, int(tw)), max(1, int(th))) + ) + tpl_edges_aggressive_backup = cv2.resize( + tpl_edges_aggressive_backup, + (max(1, int(tw)), max(1, int(th))), + ) + tpl_edges_morph_backup = cv2.resize( + tpl_edges_morph_backup, + (max(1, int(tw)), max(1, int(th))), + ) except Exception: pass @@ -482,77 +521,139 @@ class StageHandler: if icon_name == "x" and use_edges: try: - res1_fixed = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED) - _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1_fixed) - scores.append(("TM_CCOEFF_NORMED_固定阈值二值化", float(max_val1 or 0.0))) + res1_fixed = cv2.matchTemplate( + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED + ) + _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc( + res1_fixed + ) + scores.append( + ("TM_CCOEFF_NORMED_固定阈值二值化", float(max_val1 or 0.0)) + ) except Exception: pass try: - res2_adaptive = cv2.matchTemplate(roi_binary_adaptive_backup, tpl_binary_adaptive_backup, cv2.TM_CCOEFF_NORMED) - _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2_adaptive) - scores.append(("TM_CCOEFF_NORMED_自适应二值化", float(max_val2 or 0.0))) + res2_adaptive = cv2.matchTemplate( + roi_binary_adaptive_backup, + tpl_binary_adaptive_backup, + cv2.TM_CCOEFF_NORMED, + ) + _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc( + res2_adaptive + ) + scores.append( + ("TM_CCOEFF_NORMED_自适应二值化", float(max_val2 or 0.0)) + ) except Exception: pass try: - res3_otsu = cv2.matchTemplate(roi_binary_otsu_backup, tpl_binary_otsu_backup, cv2.TM_CCOEFF_NORMED) - _min_val3, max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3_otsu) - scores.append(("TM_CCOEFF_NORMED_Otsu二值化", float(max_val3 or 0.0))) + res3_otsu = cv2.matchTemplate( + roi_binary_otsu_backup, + tpl_binary_otsu_backup, + cv2.TM_CCOEFF_NORMED, + ) + _min_val3, max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc( + res3_otsu + ) + scores.append( + ("TM_CCOEFF_NORMED_Otsu二值化", float(max_val3 or 0.0)) + ) except Exception: pass try: - res4_edges = cv2.matchTemplate(roi_edges_backup, tpl_edges_backup, cv2.TM_CCOEFF_NORMED) - _min_val4, max_val4, _min_loc4, _max_loc4 = cv2.minMaxLoc(res4_edges) - scores.append(("TM_CCOEFF_NORMED_边缘检测", float(max_val4 or 0.0))) + res4_edges = cv2.matchTemplate( + roi_edges_backup, tpl_edges_backup, cv2.TM_CCOEFF_NORMED + ) + _min_val4, max_val4, _min_loc4, _max_loc4 = cv2.minMaxLoc( + res4_edges + ) + scores.append( + ("TM_CCOEFF_NORMED_边缘检测", float(max_val4 or 0.0)) + ) except Exception: pass try: - res5_edges_agg = cv2.matchTemplate(roi_edges_aggressive_backup, tpl_edges_aggressive_backup, cv2.TM_CCOEFF_NORMED) - _min_val5, max_val5, _min_loc5, _max_loc5 = cv2.minMaxLoc(res5_edges_agg) - scores.append(("TM_CCOEFF_NORMED_边缘检测激进", float(max_val5 or 0.0))) + res5_edges_agg = cv2.matchTemplate( + roi_edges_aggressive_backup, + tpl_edges_aggressive_backup, + cv2.TM_CCOEFF_NORMED, + ) + _min_val5, max_val5, _min_loc5, _max_loc5 = cv2.minMaxLoc( + res5_edges_agg + ) + scores.append( + ("TM_CCOEFF_NORMED_边缘检测激进", float(max_val5 or 0.0)) + ) except Exception: pass try: - res6_morph = cv2.matchTemplate(roi_edges_morph_backup, tpl_edges_morph_backup, cv2.TM_CCOEFF_NORMED) - _min_val6, max_val6, _min_loc6, _max_loc6 = cv2.minMaxLoc(res6_morph) - scores.append(("TM_CCOEFF_NORMED_形态学边缘", float(max_val6 or 0.0))) + res6_morph = cv2.matchTemplate( + roi_edges_morph_backup, + tpl_edges_morph_backup, + cv2.TM_CCOEFF_NORMED, + ) + _min_val6, max_val6, _min_loc6, _max_loc6 = cv2.minMaxLoc( + res6_morph + ) + scores.append( + ("TM_CCOEFF_NORMED_形态学边缘", float(max_val6 or 0.0)) + ) except Exception: pass try: - res7_contrast = cv2.matchTemplate(roi_contrast_backup, tpl_contrast_backup, cv2.TM_CCORR_NORMED) - _min_val7c, max_val7c, _min_loc7c, _max_loc7c = cv2.minMaxLoc(res7_contrast) - scores.append(("TM_CCORR_NORMED_强对比度", float(max_val7c or 0.0))) + res7_contrast = cv2.matchTemplate( + roi_contrast_backup, + tpl_contrast_backup, + cv2.TM_CCORR_NORMED, + ) + _min_val7c, max_val7c, _min_loc7c, _max_loc7c = cv2.minMaxLoc( + res7_contrast + ) + scores.append( + ("TM_CCORR_NORMED_强对比度", float(max_val7c or 0.0)) + ) except Exception: pass try: - res8_original = cv2.matchTemplate(roi_img, tpl, cv2.TM_CCOEFF_NORMED) - _min_val8, max_val8, _min_loc8, _max_loc8 = cv2.minMaxLoc(res8_original) + res8_original = cv2.matchTemplate( + roi_img, tpl, cv2.TM_CCOEFF_NORMED + ) + _min_val8, max_val8, _min_loc8, _max_loc8 = cv2.minMaxLoc( + res8_original + ) scores.append(("TM_CCOEFF_NORMED_原始", float(max_val8 or 0.0))) except Exception: pass else: try: - res1 = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED) + res1 = cv2.matchTemplate( + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED + ) _min_val1, max_val1, _min_loc1, _max_loc1 = cv2.minMaxLoc(res1) scores.append(("TM_CCOEFF_NORMED", float(max_val1 or 0.0))) except Exception: pass try: - res2 = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCORR_NORMED) + res2 = cv2.matchTemplate( + roi_img_enhanced, tpl_enhanced, cv2.TM_CCORR_NORMED + ) _min_val2, max_val2, _min_loc2, _max_loc2 = cv2.minMaxLoc(res2) scores.append(("TM_CCORR_NORMED", float(max_val2 or 0.0))) except Exception: pass try: - res3 = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_SQDIFF_NORMED) + res3 = cv2.matchTemplate( + roi_img_enhanced, tpl_enhanced, cv2.TM_SQDIFF_NORMED + ) min_val3, _max_val3, _min_loc3, _max_loc3 = cv2.minMaxLoc(res3) score3 = 1.0 - float(min_val3 or 0.0) scores.append(("TM_SQDIFF_NORMED", score3)) @@ -564,10 +665,22 @@ class StageHandler: if icon_name == "x" and use_edges: max_val = 0.0 best_method = "" - ccoeff_scores = [(m, s) for m, s in scores if "TM_CCOEFF_NORMED" in m] - ccoeff_max = max(ccoeff_scores, key=lambda x: x[1]) if ccoeff_scores else None - ccorr_scores = [(m, s) for m, s in scores if "TM_CCORR_NORMED" in m] - ccorr_max = max(ccorr_scores, key=lambda x: x[1]) if ccorr_scores else None + ccoeff_scores = [ + (m, s) for m, s in scores if "TM_CCOEFF_NORMED" in m + ] + ccoeff_max = ( + max(ccoeff_scores, key=lambda x: x[1]) + if ccoeff_scores + else None + ) + ccorr_scores = [ + (m, s) for m, s in scores if "TM_CCORR_NORMED" in m + ] + ccorr_max = ( + max(ccorr_scores, key=lambda x: x[1]) + if ccorr_scores + else None + ) if ccoeff_max and ccoeff_max[1] >= 0.50: best_method, max_val = ccoeff_max elif ccorr_max and ccorr_max[1] >= 0.75: @@ -580,24 +693,40 @@ class StageHandler: best_method, max_val = max(scores, key=lambda x: x[1]) if len(scores) >= 2: - sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True) + sorted_scores = sorted( + scores, key=lambda x: x[1], reverse=True + ) top_score = sorted_scores[0][1] second_score = sorted_scores[1][1] if top_score - second_score > 0.15: max_val = top_score best_method = sorted_scores[0][0] else: - ccoeff_scores = [s for s in sorted_scores if "TM_CCOEFF_NORMED" in s[0]] + ccoeff_scores = [ + s + for s in sorted_scores + if "TM_CCOEFF_NORMED" in s[0] + ] if len(ccoeff_scores) >= 2: - max_val = ccoeff_scores[0][1] * 0.7 + ccoeff_scores[1][1] * 0.3 + max_val = ( + ccoeff_scores[0][1] * 0.7 + + ccoeff_scores[1][1] * 0.3 + ) best_method = f"{ccoeff_scores[0][0]}+{ccoeff_scores[1][0]}_加权" elif len(ccoeff_scores) >= 1: - max_val = ccoeff_scores[0][1] * 0.7 + second_score * 0.3 + max_val = ( + ccoeff_scores[0][1] * 0.7 + second_score * 0.3 + ) best_method = f"{ccoeff_scores[0][0]}+{sorted_scores[1][0]}_加权" else: - binary_scores = [s for s in sorted_scores if "二值化" in s[0]] + binary_scores = [ + s for s in sorted_scores if "二值化" in s[0] + ] if len(binary_scores) >= 2: - max_val = binary_scores[0][1] * 0.7 + binary_scores[1][1] * 0.3 + max_val = ( + binary_scores[0][1] * 0.7 + + binary_scores[1][1] * 0.3 + ) best_method = f"{binary_scores[0][0]}+{binary_scores[1][0]}_加权" else: max_val = top_score * 0.7 + second_score * 0.3 @@ -630,7 +759,9 @@ class StageHandler: if total_weight > 0: max_val = weighted_sum / total_weight else: - res = cv2.matchTemplate(roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED) + res = cv2.matchTemplate( + roi_img_enhanced, tpl_enhanced, cv2.TM_CCOEFF_NORMED + ) _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) max_val = float(max_val or 0.0) best_method = "TM_CCOEFF_NORMED" @@ -699,7 +830,9 @@ class StageHandler: """ start_time = time.time() try: - already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False) + already_verified = bool( + getattr(analyser, "_fudai_detail_verified", False) or False + ) if already_verified: try: analyser._log_kv( # type: ignore[attr-defined] @@ -722,8 +855,12 @@ class StageHandler: # 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情 try: now_ts = time.time() - focus_until = float(getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0) - queue_full_waiting = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False) + focus_until = float( + getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0 + ) + queue_full_waiting = bool( + getattr(analyser, "queue_full_waiting_at_earliest", False) or False + ) if focus_until > 0 and now_ts < focus_until and queue_full_waiting: if analyser.reservations and len(analyser.reservations) > 0: @@ -731,8 +868,16 @@ class StageHandler: try: ft = float(earliest.get("future_ts") or 0.0) if ft > 0: - join_ahead = float(getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120) - poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0) + join_ahead = float( + getattr( + analyser, "high_value_fudai_join_ahead_seconds", 120 + ) + or 120 + ) + poll_before = float( + getattr(analyser, "poll_before_open_seconds", 10.0) + or 10.0 + ) time_window_start_ts = ft - join_ahead if now_ts < time_window_start_ts: try: @@ -742,7 +887,9 @@ class StageHandler: focus_until=int(focus_until), now_ts=int(now_ts), time_window_start=int(time_window_start_ts), - remain_seconds=int(time_window_start_ts - now_ts), + remain_seconds=int( + time_window_start_ts - now_ts + ), ) except Exception: pass diff --git a/fudai_detail_modules/fudai_detail_coupon_detection.py b/fudai_detail_modules/fudai_detail_coupon_detection.py index 0f6c5e5..eece14c 100644 --- a/fudai_detail_modules/fudai_detail_coupon_detection.py +++ b/fudai_detail_modules/fudai_detail_coupon_detection.py @@ -24,6 +24,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "错误", "获取截图失败(判断优惠券弹窗)", + log_type="ERR", error=str(e), error_type=type(e).__name__, level="WARNING", @@ -101,6 +102,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "弹窗", "弹窗颜色统计", + log_type="DEBUG", fudai_like=fudai_like, coupon_like=coupon_like, ) @@ -109,6 +111,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "错误", "记录弹窗颜色统计日志失败", + log_type="ERR", error=str(e), error_type=type(e).__name__, level="WARNING", @@ -154,6 +157,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "弹窗", "福袋详情检测结果", + log_type="DEBUG", has_fudai_detail=has_fudai_detail, detect_info=detect_info if detect_info else {}, ) @@ -162,6 +166,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "错误", "记录福袋详情检测日志失败", + log_type="ERR", error=str(e), error_type=type(e).__name__, level="WARNING", @@ -175,6 +180,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "错误", "福袋详情检测异常", + log_type="ERR", error=str(e), error_type=type(e).__name__, level="WARNING", @@ -186,11 +192,15 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: if not is_coupon_like_by_color: if not has_fudai_detail: analyser._log_kv( - "弹窗", "颜色统计不像优惠券,且未检测到福袋详情,判定为福袋详情页" + "弹窗", + "颜色统计不像优惠券,且未检测到福袋详情,判定为福袋详情页", + log_type="OP", ) else: analyser._log_kv( - "弹窗", "颜色统计不像优惠券,但检测到福袋详情,判定为福袋详情页" + "弹窗", + "颜色统计不像优惠券,但检测到福袋详情,判定为福袋详情页", + log_type="OP", ) return False @@ -199,14 +209,17 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "弹窗", "颜色统计像优惠券,但未检测到福袋详情,判定为福袋详情页(可能是误判)", + log_type="OP", ) return False # 步骤2:OCR确认"开心收下"按钮(模板匹配成功后) if has_fudai_detail: - analyser._log_kv("弹窗", "模板匹配成功,但检测到福袋详情,需要OCR确认") + analyser._log_kv( + "弹窗", "模板匹配成功,但检测到福袋详情,需要OCR确认", log_type="OP" + ) else: - analyser._log_kv("弹窗", "模板匹配成功,使用OCR确认") + analyser._log_kv("弹窗", "模板匹配成功,使用OCR确认", log_type="OP") # 使用参与按钮区域检测"开心收下"(与"粉丝团加入"相同的区域) # 保存完整截图并标注OCR区域 @@ -261,6 +274,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "[调试图像]", "OCR识别前保存完整截图(参与按钮-检测开心收下)", + log_type="SCREENSHOT", path=debug_path, ) except Exception as e: @@ -268,6 +282,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "错误", "记录调试图像日志失败", + log_type="ERR", error=str(e), error_type=type(e).__name__, level="WARNING", @@ -279,6 +294,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "错误", "保存参与按钮调试截图失败", + log_type="ERR", error=str(e), error_type=type(e).__name__, level="WARNING", @@ -325,6 +341,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "弹窗", "模板匹配+OCR确认:检测到'开心收下',判定为优惠券弹窗", + log_type="OP", OCR文本=coupon_text[:50], ) return True @@ -335,6 +352,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "弹窗", "模板匹配成功但OCR未确认'开心收下',且检测到福袋详情,判定为福袋详情页", + log_type="OP", OCR文本=coupon_text[:50] if coupon_text else "空", ) return False @@ -344,6 +362,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "弹窗", "模板匹配成功但OCR未确认'开心收下',不判定为优惠券弹窗", + log_type="OP", OCR文本=coupon_text[:50] if coupon_text else "空", 说明="可能是识别福袋位置失败,点击了错误位置", ) @@ -354,6 +373,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "错误", "优惠券确认过程异常,不判定为优惠券弹窗", + log_type="ERR", error=str(e), error_type=type(e).__name__, level="WARNING", @@ -370,6 +390,7 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: analyser._log_kv( "错误", "优惠券弹窗检测过程异常", + log_type="ERR", error=str(e), error_type=type(e).__name__, level="WARNING", diff --git a/fudai_detail_modules/fudai_detail_operations.py b/fudai_detail_modules/fudai_detail_operations.py index bf70ada..ecba0f6 100644 --- a/fudai_detail_modules/fudai_detail_operations.py +++ b/fudai_detail_modules/fudai_detail_operations.py @@ -26,7 +26,9 @@ def close_fudai_detail(analyser: Any) -> None: screen_width = rx screen_height = ry try: - if hasattr(analyser, 'operation') and hasattr(analyser.operation, 'get_screen_size'): + if hasattr(analyser, "operation") and hasattr( + analyser.operation, "get_screen_size" + ): try: screen_size = analyser.operation.get_screen_size(analyser.device_id) if screen_size: @@ -37,7 +39,12 @@ def close_fudai_detail(analyser: Any) -> None: pass # 验证坐标边界 - if close_x < 0 or close_x >= screen_width or close_y < 0 or close_y >= screen_height: + if ( + close_x < 0 + or close_x >= screen_width + or close_y < 0 + or close_y >= screen_height + ): try: analyser._log_kv( "验证", @@ -48,6 +55,7 @@ def close_fudai_detail(analyser: Any) -> None: screen_height=screen_height, base_x=500, base_y=470, + log_type="DEBUG", level="WARNING", ) except Exception: @@ -59,6 +67,7 @@ def close_fudai_detail(analyser: Any) -> None: analyser._log_kv( "详情", "close_fudai_detail:点击关闭详情页坐标", + log_type="OP", x=close_x, y=close_y, base_x=500, @@ -72,13 +81,16 @@ def close_fudai_detail(analyser: Any) -> None: "获取分辨率失败,使用默认坐标", error=str(e), error_type=type(e).__name__, + log_type="ERR", level="WARNING", ) except Exception: pass close_x, close_y = 500, 470 try: - analyser._log_kv("详情", "close_fudai_detail:使用默认坐标关闭详情页") + analyser._log_kv( + "详情", "close_fudai_detail:使用默认坐标关闭详情页", log_type="OP" + ) except Exception: pass @@ -92,6 +104,7 @@ def close_fudai_detail(analyser: Any) -> None: "使用operation.click关闭详情页失败,尝试备用方法", error=str(e1), error_type=type(e1).__name__, + log_type="ERR", level="WARNING", ) except Exception: @@ -106,6 +119,7 @@ def close_fudai_detail(analyser: Any) -> None: "使用analyser.click关闭详情页失败,使用返回键", error=str(e2), error_type=type(e2).__name__, + log_type="ERR", level="WARNING", ) except Exception: @@ -119,6 +133,7 @@ def close_fudai_detail(analyser: Any) -> None: "所有关闭详情页方法都失败", error=str(e3), error_type=type(e3).__name__, + log_type="ERR", level="ERROR", ) except Exception: @@ -132,6 +147,7 @@ def close_fudai_detail(analyser: Any) -> None: "operation.delay失败,使用time.sleep", error=str(e), error_type=type(e).__name__, + log_type="ERR", level="WARNING", ) except Exception: @@ -147,7 +163,9 @@ def ensure_fudai_detail_open(analyser: Any, fudai_x: int = 0) -> bool: fudai_x: 福袋的x坐标(可选,当前实现未使用) """ try: - analyser._log_kv("详情", "ensure_fudai_detail_open:假定已打开", fudai_x=fudai_x) + analyser._log_kv( + "详情", "ensure_fudai_detail_open:假定已打开", fudai_x=fudai_x + ) except Exception as e: try: analyser._log_kv( diff --git a/fudai_detail_modules/fudai_detail_reader.py b/fudai_detail_modules/fudai_detail_reader.py index 7eae62a..948ac6f 100644 --- a/fudai_detail_modules/fudai_detail_reader.py +++ b/fudai_detail_modules/fudai_detail_reader.py @@ -5,7 +5,6 @@ 执行福袋详情的OCR识别和读取,包括单次读取和重试读取。 """ - from __future__ import annotations from typing import Any, Dict, Tuple, Optional @@ -51,6 +50,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: analyser._log_kv( "性能", "福袋详情关键耗时(ms)", + log_type="PERF", total_ms=total_ms, screenshot_ms=screenshot_ms, ocr_ms=ocr_ms, @@ -60,7 +60,6 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: countdown_parse_ms=countdown_parse_ms, screenshot_reused=bool(screenshot_reused), tag=tag, - log_type="PERF", ) except Exception: pass @@ -69,15 +68,17 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: # 任务数量已在阶段检测中检测并保存到 analyser._fudai_detail_task_count_from_stage task_count = 0 try: - task_count_from_stage = getattr(analyser, "_fudai_detail_task_count_from_stage", None) + task_count_from_stage = getattr( + analyser, "_fudai_detail_task_count_from_stage", None + ) if task_count_from_stage is not None: task_count = int(task_count_from_stage or 0) try: analyser._log_kv( "福袋详情", "read_fudai_detail_once:从阶段检测获取任务数量(无需截图)", - task_count=task_count, log_type="OP", + task_count=task_count, ) except Exception: pass @@ -87,8 +88,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: analyser._log_kv( "福袋详情", "read_fudai_detail_once:警告:阶段检测未保存任务数量(可能为None)", + log_type="DEBUG", task_count_from_stage=task_count_from_stage, - log_type="OP", ) except Exception: pass @@ -111,7 +112,6 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "福袋详情", "read_fudai_detail_once:任务数量为0,不在福袋详情页,跳过截图和OCR", task_count=task_count, - log_type="OP", ) except Exception: pass @@ -125,7 +125,11 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: log_type="OP", ) _log_perf("taskcount_zero") - return "error", tup_err, {"reason": "not_in_fudai_detail", "task_count": task_count} + return ( + "error", + tup_err, + {"reason": "not_in_fudai_detail", "task_count": task_count}, + ) # 如果任务数不在(1,2,3)范围内,默认按2个任务处理 if task_count not in (1, 2, 3): @@ -135,6 +139,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: analyser._log_kv( "福袋详情", "read_fudai_detail_once:获取任务数量异常,使用默认值", + log_type="ERR", error=str(e), ) except Exception: @@ -148,12 +153,15 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: # 检查是否可以复用阶段诊断时的截图 screenshot_reused = False try: - if getattr(analyser, '_screenshot_ready_for_ocr', False): + if getattr(analyser, "_screenshot_ready_for_ocr", False): try: import path_config + pic_path = path_config.get_screenshot_path() except Exception: - pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + pic_path = os.path.join( + os.path.dirname(__file__), "pic", "screenshot.png" + ) if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024: analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用 @@ -162,9 +170,9 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: analyser._log_kv( "福袋详情", "read_fudai_detail_once:复用阶段诊断截图", + log_type="SCREENSHOT", reason="stage_diagnosed_task_count_gt_zero", path=pic_path, - log_type="SCREENSHOT", ) except Exception: pass @@ -173,9 +181,11 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: analyser._log_kv( "福袋详情", "read_fudai_detail_once:无法复用阶段诊断截图(文件不可用)", - path=pic_path, - size=os.path.getsize(pic_path) if os.path.exists(pic_path) else 0, log_type="SCREENSHOT", + path=pic_path, + size=( + os.path.getsize(pic_path) if os.path.exists(pic_path) else 0 + ), ) except Exception: pass @@ -191,9 +201,12 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: # 等待截图文件确实存在(最多等待3秒) try: import path_config + pic_path = path_config.get_screenshot_path() except Exception: - pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + pic_path = os.path.join( + os.path.dirname(__file__), "pic", "screenshot.png" + ) wait_start = time.time() while time.time() - wait_start < 3.0: @@ -215,10 +228,12 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: # 使用统一的截图路径配置 try: import path_config + pic_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) import path_config + pic_path = path_config.get_screenshot_path() pic_rgb = None try: @@ -233,21 +248,20 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: pass if pic_rgb is None: - try: try: analyser._log_kv( - "福袋详情", - "read_fudai_detail_once:无法读取截图,跳过识别", - log_type="SCREENSHOT", + "福袋详情", "read_fudai_detail_once:无法读取截图,跳过识别" ) except Exception: pass - except Exception: - pass now = time.time() tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time - analyser._log_kv("福袋详情", "read_fudai_detail_once完成(截图失败)", elapsed_seconds=round(elapsed, 2)) + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once完成(截图失败)", + elapsed_seconds=round(elapsed, 2), + ) _log_perf("screenshot_failed") return "error", tup_err, {"reason": "screenshot_failed"} @@ -260,6 +274,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: _ocr_screenshot_service_disabled = False try: from operations.screenshot_service import ScreenshotService + service = ScreenshotService.get_instance() if service.is_running(): _svc0 = time.time() @@ -269,35 +284,32 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: service_stop_ms = round((time.time() - _svc0) * 1000, 1) try: analyser._log_kv( - try: - import traceback - tb = traceback.format_exc() - # 先尝试通过 analyser._log_kv 输出完整 trace(如果可用) - try: - analyser._log_kv( # pyright: ignore[reportPrivateUsage] - "福袋详情", - "read_fudai_detail_once 异常", - error=str(e), - error_type=type(e).__name__, - traceback=tb, - log_type="ERR", - ) - except Exception: # pyright: ignore[reportTooBroadExceptionType] - # fallback: 将 traceback 写入统一错误日志 - try: - import path_config - err_log = path_config.get_error_log_path() - with open(err_log, "a", encoding="utf-8") as ef: - ef.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] read_fudai_detail_once 异常: {e}\n") - ef.write(tb) - ef.write("\n") - except Exception: - pass + "截图服务", + "OCR密集操作期间停止后台截图服务", + reason="prevent_background_screenshots_during_ocr", + ) + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( # pyright: ignore[reportPrivateUsage] + "截图服务", "停止后台截图服务失败", error=str(e), level="WARNING" + ) + except Exception: # pyright: ignore[reportTooBroadExceptionType] + pass + + try: + ocr_start = time.time() + content, time_text, participants, copies, prize_value_yuan = get_fudai_contain( + analyser, renwu=task_count + ) + ocr_end = time.time() _log_perf("after_get_fudai_contain") except Exception as e: # pyright: ignore[reportTooBroadExceptionType] # 出现异常时,记录详细错误和 traceback 并返回占位结果,便于排查 try: import traceback + tb = traceback.format_exc() # 先尝试通过 analyser._log_kv 输出完整 trace(如果可用) try: @@ -312,16 +324,23 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: # fallback: 将 traceback 写入统一错误日志 try: import path_config + err_log = path_config.get_error_log_path() with open(err_log, "a", encoding="utf-8") as ef: - ef.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] read_fudai_detail_once 异常: {e}\\n") + ef.write( + f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] read_fudai_detail_once 异常: {e}\\n" + ) ef.write(tb) ef.write("\\n") except Exception: pass except Exception: # pyright: ignore[reportTooBroadExceptionType] try: - analyser._log_kv("福袋详情", "read_fudai_detail_once 异常(无法格式化 traceback)", error=str(e)) # pyright: ignore[reportPrivateUsage] + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once 异常(无法格式化 traceback)", + error=str(e), + ) # pyright: ignore[reportPrivateUsage] except Exception: # pyright: ignore[reportTooBroadExceptionType] pass now = time.time() @@ -332,7 +351,6 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "福袋详情", "read_fudai_detail_once完成(识别异常)", elapsed_seconds=round(elapsed, 2), - log_type="ERR", ) # pyright: ignore[reportPrivateUsage] except Exception: # pyright: ignore[reportTooBroadExceptionType] pass @@ -347,7 +365,9 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: # 清除标志,避免影响后续调用 if is_watch_task: try: - analyser._is_watch_task_detected = False # pyright: ignore[reportPrivateUsage] + analyser._is_watch_task_detected = ( + False # pyright: ignore[reportPrivateUsage] + ) except Exception: # pyright: ignore[reportTooBroadExceptionType] pass except Exception: @@ -365,8 +385,16 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: now = time.time() tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time - analyser._log_kv("福袋详情", "read_fudai_detail_once完成(观看任务)", elapsed_seconds=round(elapsed, 2)) # pyright: ignore[reportPrivateUsage] - return "watch_task", tup_watch, {"reason": "watch_task_detected", "task_count": task_count} + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once完成(观看任务)", + elapsed_seconds=round(elapsed, 2), + ) # pyright: ignore[reportPrivateUsage] + return ( + "watch_task", + tup_watch, + {"reason": "watch_task_detected", "task_count": task_count}, + ) # 解析倒计时 -> (剩余秒数, 未来时间戳) countdown_start = time.time() @@ -406,7 +434,9 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: room_title_raw = "" try: room_title = str(getattr(analyser, "current_room_title", "") or "").strip() - room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "").strip() + room_title_raw = str( + getattr(analyser, "current_room_title_raw", "") or "" + ).strip() except Exception: pass @@ -420,9 +450,13 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: if countdown_start and countdown_end: try: if countdown_start > 0: - countdown_start_str = datetime.fromtimestamp(countdown_start).strftime("%Y-%m-%d %H:%M:%S") + countdown_start_str = datetime.fromtimestamp( + countdown_start + ).strftime("%Y-%m-%d %H:%M:%S") if countdown_end > 0: - countdown_end_str = datetime.fromtimestamp(countdown_end).strftime("%Y-%m-%d %H:%M:%S") + countdown_end_str = datetime.fromtimestamp(countdown_end).strftime( + "%Y-%m-%d %H:%M:%S" + ) except Exception: pass @@ -439,11 +473,10 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "福袋", f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析 level="DEBUG", - log_type="DEBUG", ) analyser._log_kv( "福袋详情", - f"read_fudai_detail_once 完整识別結果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒", + f"read_fudai_detail_once 完整识别结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒", status="ok", room_title=room_title, room_title_raw=room_title_raw, @@ -461,14 +494,13 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: remain_seconds=remain_seconds, elapsed_seconds=round(time.time() - start_time, 2), level="DEBUG", - log_type="DEBUG", ) # 输出到行为日志(使用更详细的格式) content_preview = (content or "")[:60] if content else "未识别到" analyser._log_kv( "行为", - f"识别福袋详情完成:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识別'},剩余{remain_seconds}秒", + f"识别福袋详情完成:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒", action="识别福袋详情", result="成功", detail={ @@ -480,12 +512,15 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "参与人数": int(participants or 0), "福袋份数": int(copies or 0), "奖品价值": float(prize_value_yuan or 0.0), - "倒计时开始时间": countdown_start_str if countdown_start_str else f"{countdown_start}", - "倒计时结束时间": countdown_end_str if countdown_end_str else f"{countdown_end}", + "倒计时开始时间": ( + countdown_start_str if countdown_start_str else f"{countdown_start}" + ), + "倒计时结束时间": ( + countdown_end_str if countdown_end_str else f"{countdown_end}" + ), "剩余秒数": remain_seconds, }, level="DEBUG", - log_type="OP", ) # 输出简化的运行日志(兼容原有格式) @@ -502,7 +537,6 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: countdown_end=countdown_end, task_count=task_count, level="DEBUG", - log_type="DEBUG", ) except Exception as e: # 如果详细日志输出失败,至少输出基本信息 @@ -527,7 +561,6 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "read_fudai_detail_once完成(成功)", elapsed_seconds=round(elapsed, 2), level="DEBUG", - log_type="DEBUG", ) _log_perf("success") return "ok", detail_tuple, extra @@ -596,7 +629,9 @@ def read_fudai_detail_with_retries( # 使用配置项,默认0.5秒(比之前的0.8秒更快) retry_delay = 0.5 try: - retry_delay = float(getattr(analyser, "fudai_detail_retry_delay_seconds", 0.5) or 0.5) + retry_delay = float( + getattr(analyser, "fudai_detail_retry_delay_seconds", 0.5) or 0.5 + ) except Exception: retry_delay = 0.5 if retry_delay < 0.3: @@ -628,7 +663,11 @@ def read_fudai_detail_with_retries( pass # 记录第一次成功读取的结果(作为基准) - if first_countdown_seconds is None and current_countdown_seconds is not None and status == "ok": + if ( + first_countdown_seconds is None + and current_countdown_seconds is not None + and status == "ok" + ): first_countdown_seconds = current_countdown_seconds first_tuple = current_tuple first_attempt_time = attempt_start_time @@ -642,9 +681,9 @@ def read_fudai_detail_with_retries( # 如果数据看起来合理(有内容或价值>0,倒计时合理),直接返回 is_data_reasonable = ( - (content and len(content.strip()) > 0) or - (prize_value and float(prize_value) > 0) or - (time_text and len(time_text.strip()) > 0) + (content and len(content.strip()) > 0) + or (prize_value and float(prize_value) > 0) + or (time_text and len(time_text.strip()) > 0) ) if is_data_reasonable and current_countdown_seconds > 0: @@ -663,7 +702,10 @@ def read_fudai_detail_with_retries( break # 倒计时一致性检查:如果后续读取的倒计时与第一次差异过大,判定为识别错误 - elif first_countdown_seconds is not None and current_countdown_seconds is not None: + elif ( + first_countdown_seconds is not None + and current_countdown_seconds is not None + ): # 计算时间流逝(从第一次读取到现在的时间差) time_elapsed = attempt_start_time - first_attempt_time if time_elapsed < 0: @@ -673,16 +715,24 @@ def read_fudai_detail_with_retries( expected_countdown = first_countdown_seconds - time_elapsed # 计算实际差异(与第一次相比) - diff_ratio = abs(current_countdown_seconds - first_countdown_seconds) / max(first_countdown_seconds, 1.0) + diff_ratio = abs( + current_countdown_seconds - first_countdown_seconds + ) / max(first_countdown_seconds, 1.0) # 计算与预期的差异(考虑时间流逝) - expected_diff_ratio = abs(current_countdown_seconds - expected_countdown) / max(expected_countdown, 1.0) if expected_countdown > 0 else 1.0 + expected_diff_ratio = ( + abs(current_countdown_seconds - expected_countdown) + / max(expected_countdown, 1.0) + if expected_countdown > 0 + else 1.0 + ) # 如果差异过大(超过30%)或与预期差异过大(超过20%),判定为识别错误 # 注意:如果当前倒计时明显大于第一次(时间应该减少),肯定是识别错误 is_inconsistent = ( - diff_ratio > 0.3 or - expected_diff_ratio > 0.2 or - current_countdown_seconds > first_countdown_seconds + 10 # 倒计时不应该增加 + diff_ratio > 0.3 + or expected_diff_ratio > 0.2 + or current_countdown_seconds + > first_countdown_seconds + 10 # 倒计时不应该增加 ) if is_inconsistent: @@ -722,7 +772,11 @@ def read_fudai_detail_with_retries( break # 如果任务数量为0,说明没有正确打开福袋详情页,尝试重新打开 - if status == "error" and isinstance(extra, dict) and extra.get("reason") == "task_count_zero": + if ( + status == "error" + and isinstance(extra, dict) + and extra.get("reason") == "task_count_zero" + ): if attempt < max_attempts - 1: try: analyser._log_kv( @@ -768,15 +822,17 @@ def read_fudai_detail_with_retries( cd_start, cd_end = cd[0], cd[1] # 如果是优惠券弹窗,记录日志并明确标记 - is_coupon_popup = (last_status == "coupon_popup") - is_watch_task = (last_status == "watch_task") + is_coupon_popup = last_status == "coupon_popup" + is_watch_task = last_status == "watch_task" # 获取直播间名字(所有情况都需要,用于日志输出) room_title = "" room_title_raw = "" try: room_title = str(getattr(analyser, "current_room_title", "") or "").strip() - room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "").strip() + room_title_raw = str( + getattr(analyser, "current_room_title_raw", "") or "" + ).strip() except Exception: pass @@ -785,6 +841,7 @@ def read_fudai_detail_with_retries( remain_seconds = 0 try: from datetime import datetime + if cd_end and isinstance(cd_end, (int, float)) and cd_end > 0: cd_end_str = datetime.fromtimestamp(cd_end).strftime("%Y-%m-%d %H:%M:%S") remain_seconds = int(cd_end - time.time()) if cd_end > time.time() else 0 @@ -817,7 +874,9 @@ def read_fudai_detail_with_retries( "福袋份数": int(copies or 0), "奖品价值": float(prize_value_yuan or 0.0), "倒计时开始时间": str(cd_start) if cd_start else "", - "倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "", + "倒计时结束时间": ( + cd_end_str if cd_end_str else str(cd_end) if cd_end else "" + ), "剩余秒数": remain_seconds, "状态": last_status, }, @@ -850,7 +909,9 @@ def read_fudai_detail_with_retries( "福袋份数": int(copies or 0), "奖品价值": float(prize_value_yuan or 0.0), "倒计时开始时间": str(cd_start) if cd_start else "", - "倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "", + "倒计时结束时间": ( + cd_end_str if cd_end_str else str(cd_end) if cd_end else "" + ), "剩余秒数": remain_seconds, "状态": last_status, }, @@ -940,7 +1001,9 @@ def read_fudai_detail_with_retries( "福袋份数": int(copies or 0), "奖品价值": float(prize_value_yuan or 0.0), "倒计时开始时间": str(cd_start) if cd_start else "", - "倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "", + "倒计时结束时间": ( + cd_end_str if cd_end_str else str(cd_end) if cd_end else "" + ), "剩余秒数": remain_seconds, "状态": last_status, }, @@ -990,5 +1053,11 @@ def read_fudai_detail_with_retries( pass elapsed = time.time() - start_time - analyser._log_kv("福袋详情", "read_fudai_detail_with_retries完成", elapsed_seconds=round(elapsed, 2), status=last_status, attempts=max_attempts) + analyser._log_kv( + "福袋详情", + "read_fudai_detail_with_retries完成", + elapsed_seconds=round(elapsed, 2), + status=last_status, + attempts=max_attempts, + ) return last_tuple diff --git a/gui/gui_app.py b/gui/gui_app.py index 99ddc5b..518dea8 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -319,6 +319,11 @@ def main(): ttk.Spinbox(top, from_=-200, to=200, textvariable=y_var, width=6).pack( side=LEFT, padx=(0, 12) ) + # 连续无福袋退出阈值(在直播间连续未找到福袋达到该次数时按返回键退出) + ttk.Label(top, text="连续无福袋退出阈值:").pack(side=LEFT) + ttk.Spinbox( + top, from_=1, to=99999, textvariable=fudai_exit_after_misses_var, width=6 + ).pack(side=LEFT, padx=(0, 12)) # 中部:左侧配置(使用Notebook标签页)+ 右侧日志/预览(支持拖拽调整宽度) mid = ttk.PanedWindow(root, orient="horizontal") @@ -415,6 +420,9 @@ def main(): fudai_disable_content_recognition_var = tk.BooleanVar( value=bool(cfg.get("fudai_disable_content_recognition", False)) ) + fudai_exit_after_misses_var = tk.IntVar( + value=int(cfg.get("fudai_exit_after_misses", 30) or 30) + ) fudai_click_wait_seconds_var = tk.DoubleVar( value=float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0) )