diff --git a/Underlying_Operations.py b/Underlying_Operations.py index 0253200..a1b970d 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -815,6 +815,8 @@ class underlying_operations: text = self.extract_ocr_content(result) # 如果识别为空且图片较小,尝试放大重试(精度优化:使用更好的放大算法和增强处理) + img2 = None + text2 = None if (not text) and max(w, h) <= 1200: try: # 使用LANCZOS重采样算法(更高质量的放大) @@ -855,6 +857,37 @@ class underlying_operations: except Exception: pass + # 如果OCR识别成功(返回非空文本),保存一份图片到ocr文件夹(与cut_pic保存的图片区分开) + if text and text.strip() and picname: + try: + # 使用_find_pic_path获取ocr文件夹路径(写入模式) + base_dir = os.path.dirname(__file__) + pic_base = os.path.join(base_dir, 'pic') + ocr_dir = os.path.join(pic_base, 'ocr') + os.makedirs(ocr_dir, exist_ok=True) + + # 保存文件名:{picname}_success.png,与cut_pic保存的{picname}.png区分开 + success_path = os.path.join(ocr_dir, f'{picname}_success.png') + + # 保存识别成功时的图片(使用预处理后的图片,即实际用于OCR的图片) + try: + # 如果使用了放大后的图片且识别成功,保存放大后的图片 + if img2 is not None and text2 and text2.strip(): + img_to_save = img2 + else: + # 否则保存预处理后的图片(img1) + img_to_save = img1 + img_to_save.save(success_path) + except Exception: + # 如果保存预处理后的图片失败,保存原始图片 + try: + img.save(success_path) + except Exception: + pass + except Exception: + # 保存失败不影响OCR识别结果 + pass + return text def extract_ocr_content(self, content=[]): diff --git a/assets/fudai.png b/assets/fudai.png new file mode 100644 index 0000000..7eba9d2 Binary files /dev/null and b/assets/fudai.png differ diff --git a/assets/fudai1.png b/assets/fudai1.png new file mode 100644 index 0000000..7b7f832 Binary files /dev/null and b/assets/fudai1.png differ diff --git a/config.json b/config.json index c7c67bf..07dec22 100644 --- a/config.json +++ b/config.json @@ -22,7 +22,7 @@ "reservation_preempt_min_value": 0.0, "fudai_find_max_attempts": 10, "fudai_icon_retry_delay_seconds": 0.6, - "fudai_icon_max_wait_seconds": 5.0, + "fudai_icon_max_wait_seconds": 7.0, "yanghao_recommend_duration_seconds": 216, "yanghao_recommend_interval_seconds": 600, "yanghao_like_prob": 1.0, @@ -65,5 +65,7 @@ "yanghao_fav_keywords": [], "stage_diag_max_time": 15.0, "stage_diag_max_step_time": 4.0, - "live_room_match_threshold": 0.7 + "live_room_match_threshold": 0.7, + "enable_ocr_mode1": false, + "fudai_template_match_threshold": 0.2 } diff --git a/douyin_detection.py b/douyin_detection.py index b98f60b..2d14331 100644 --- a/douyin_detection.py +++ b/douyin_detection.py @@ -134,9 +134,9 @@ def check_detail_height(analyser: Any) -> int: def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool = False): """Check whether the live-room screen currently has a fudai icon. - 仅使用像素/颜色特征进行检测(无位置过滤、无 OCR): - - 先用 numpy/逐像素扫描找到疑似图标位置; - - 再通过颜色统计(粉紫/粉蓝 vs 橙色券)过滤误报。 + 使用模板匹配进行检测(暂时关闭像素检测): + - 使用 assets/fudai.png 作为模板进行匹配 + - 在指定区域内搜索福袋图标 """ func_start = time.time() path = os.path.join(os.path.dirname(__file__), "pic") @@ -157,11 +157,39 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool max_wait_s = 0.0 try: - analyser._log_kv("[找福袋图标] 开始", f"最大等待时间{max_wait_s}秒,复用截图={screenshot_ready}") + analyser._log_kv("[找福袋图标] 开始", f"最大等待时间{max_wait_s}秒,复用截图={screenshot_ready},使用模板匹配") except Exception: pass detected_any = False + detected_x = None + + # 检查OpenCV是否可用 + try: + import cv2 + import numpy as np + except Exception: + try: + analyser._log_kv("[找福袋图标] 错误", "OpenCV/numpy不可用,无法使用模板匹配") + except Exception: + pass + return False + + # 获取模板路径 + base_dir = os.path.dirname(__file__) + template_path = os.path.join(base_dir, "assets", "fudai.png") + if not os.path.exists(template_path): + try: + analyser._log_kv("[找福袋图标] 错误", f"模板文件不存在: {template_path}") + except Exception: + pass + return False + + # 获取匹配阈值 + try: + template_threshold = float(getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7) + except Exception: + template_threshold = 0.7 # 完全基于时间限制,不使用次数限制 while (time.time() - func_start) < max_wait_s: @@ -175,17 +203,27 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool pass try: - pic = Image.open(pic1_path) - pic.load() + screenshot_img = cv2.imread(pic1_path, cv2.IMREAD_COLOR) + if screenshot_img is None: + try: + analyser.operation.get_screenshot(analyser.device_id) + screenshot_img = cv2.imread(pic1_path, cv2.IMREAD_COLOR) + except Exception: + pass + if screenshot_img is None: + elapsed = time.time() - func_start + if elapsed < max_wait_s: + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + continue except Exception: - try: - analyser.operation.get_screenshot(analyser.device_id) - except Exception: - pass - # 检查是否还有剩余时间 elapsed = time.time() - func_start if elapsed < max_wait_s: - # 计算剩余时间,但至少等待 retry_delay_s remaining_time = max_wait_s - elapsed sleep_time = min(retry_delay_s, remaining_time) if sleep_time > 0: @@ -195,10 +233,6 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool time.sleep(sleep_time) continue - pic_new = pic.convert("RGBA") - detected = False - detected_x = None - # Resolution ratios try: rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) @@ -213,170 +247,238 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool except Exception: y_pianyi_val = 0 - # First try numpy-accelerated scan over a horizontal band - numpy_scan_start = time.time() + # 定义搜索区域 + # X范围:34-382(1080基准) + # Y范围:357-451(2400基准),福袋图标所在高度 + search_x1 = max(0, 34 * rx // 1080) + search_x2 = min(screenshot_img.shape[1], 382 * rx // 1080) + search_y1_base = 357 * ry // 2400 + y_pianyi_val + search_y2_base = 451 * ry // 2400 + y_pianyi_val + search_y1 = max(0, search_y1_base) + search_y2 = min(screenshot_img.shape[0], search_y2_base) + + if search_x1 >= search_x2 or search_y1 >= search_y2: + elapsed = time.time() - func_start + if elapsed < max_wait_s: + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + continue + + # 裁剪搜索区域 + search_roi = screenshot_img[search_y1:search_y2, search_x1:search_x2] + + # 读取模板 try: - import numpy as _np - - # 优惠券一般在左侧,这里将扫描区域整体右移: - # 原范围约为 x∈[41,410],现在改为 x∈[220,960](1080 基准), - # 既避开左侧券位,又覆盖更多右侧可能出现福袋的位置。 - # Y值检测范围扩大:从348到448并行检测(基于1080x2400分辨率) - x1 = max(0, 220 * rx // 1080) - x2 = min(pic_new.size[0], 960 * rx // 1080) - y_top_base = 348 * ry // 2400 + y_pianyi_val - y_bottom_base = 448 * ry // 2400 + y_pianyi_val - y_top = max(0, y_top_base) - y_bottom = min(pic_new.size[1], y_bottom_base) - - if x1 < x2 and y_top < y_bottom: - roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB") - arr = _np.array(roi) - if arr.size > 0: - r = arr[:, :, 0] - g = arr[:, :, 1] - b = arr[:, :, 2] - mask_center = ( - (r >= 190) - & (r <= 206) - & (g >= 173) - & (g <= 196) - & (b >= 234) - & (b <= 250) - ) - cols = _np.sum(mask_center, axis=0) - valid_cols = cols >= 2 - if valid_cols.any(): - col_idx = int(_np.argmax(valid_cols)) - detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx)) - detected = True - detected_any = True + template = cv2.imread(template_path, cv2.IMREAD_COLOR) + if template is None: + try: + analyser._log_kv("[找福袋图标] 错误", f"无法读取模板文件: {template_path}") + except Exception: + pass + elapsed = time.time() - func_start + if elapsed < max_wait_s: + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: try: - analyser.last_find_fudai_time = time.time() + analyser.operation.delay(sleep_time) except Exception: - pass - except Exception: - detected = False - numpy_scan_elapsed = time.time() - numpy_scan_start - if numpy_scan_elapsed > 0.01: + time.sleep(sleep_time) + continue + except Exception as e: try: - elapsed_time = time.time() - func_start - analyser._log_step_time( - f"numpy像素扫描(已用时{elapsed_time:.2f}秒)", numpy_scan_start, {"结果": "命中" if detected else "未命中"} + analyser._log_kv("[找福袋图标] 错误", f"读取模板文件异常: {str(e)}") + except Exception: + pass + elapsed = time.time() - func_start + if elapsed < max_wait_s: + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + continue + + # 检查模板和搜索区域尺寸 + th, tw = template.shape[:2] + rh, rw = search_roi.shape[:2] + + if th > rh or tw > rw: + # 模板太大,缩小模板 + scale = min(rh / max(th, 1), rw / max(tw, 1)) + if scale > 0: + template = cv2.resize(template, (max(1, int(tw * scale)), max(1, int(th * scale)))) + th, tw = template.shape[:2] + + # 执行模板匹配(使用彩色匹配) + try: + template_match_start = time.time() + + # 详细日志:记录搜索区域和模板信息 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配开始", + f"搜索区域", + search_x1=search_x1, + search_x2=search_x2, + search_y1=search_y1, + search_y2=search_y2, + search_width=search_x2 - search_x1, + search_height=search_y2 - search_y1, + template_width=tw, + template_height=th, + template_path=template_path, + 阈值=template_threshold, + 匹配模式="彩色(BGR)", + ) + except Exception: + pass + + # 使用彩色匹配(BGR三通道) + res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED) + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) + + template_match_elapsed = (time.time() - template_match_start) * 1000 + + # 详细日志:记录匹配结果 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配结果", + f"匹配分数={round(max_val, 4)},阈值={template_threshold}", + 耗时毫秒=round(template_match_elapsed, 2), + 是否通过=bool(max_val >= template_threshold), + 最小分数=round(_min_val, 4), + 最佳位置=f"({max_loc[0]}, {max_loc[1]})", ) except Exception: pass - # Fallback: per-pixel scan(第一步:只做颜色/像素级粗检测) - if not detected: - pixel_scan_start = time.time() - try: - pix = pic_new.load() - pic_width, pic_height = pic_new.size - # 与 numpy 扫描保持一致:整体右移,并尽量覆盖右侧大部分区域 - # Y值检测范围扩大:从348到448并行检测(基于1080x2400分辨率) - scan_x_start = 220 * rx // 1080 - scan_x_end = min(960 * rx // 1080, pic_width) - scan_y_start_base = 348 * ry // 2400 + y_pianyi_val - scan_y_end_base = 448 * ry // 2400 + y_pianyi_val - scan_y_start = max(0, scan_y_start_base) - scan_y_end = min(pic_height, scan_y_end_base) + if max_val >= template_threshold: + # 计算检测到的X坐标(1080基准) + detected_x_in_roi = max_loc[0] + detected_x = int((search_x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)) + detected_y_in_roi = max_loc[1] + detected_y = int((search_y1 + detected_y_in_roi + th // 2) * 2400.0 / max(1, ry)) + detected_any = True - # 并行检测348到448范围内的所有Y值 - for check_y in range(scan_y_start, scan_y_end): - if not (0 <= check_y < pic_height): - continue - for x_scaled in range(scan_x_start, scan_x_end): - try: - px = pix[x_scaled, check_y] - if ( - len(px) >= 3 - and 190 <= px[0] <= 206 - and 173 <= px[1] <= 196 - and 234 <= px[2] <= 250 - ): - detected_x = int(x_scaled * 1080.0 / max(1, rx)) - detected = True - detected_any = True - try: - analyser.last_find_fudai_time = time.time() - except Exception: - pass - break - except Exception: - continue - if detected: - break - except Exception: - pass - pixel_scan_elapsed = time.time() - pixel_scan_start - if pixel_scan_elapsed > 0.01: + # 保存匹配位置的图片 try: - elapsed_time = time.time() - func_start - analyser._log_step_time( - f"逐像素扫描(已用时{elapsed_time:.2f}秒)", pixel_scan_start, {"结果": "命中" if detected else "未命中"} - ) - except Exception: - pass - - if detected and detected_x is not None: - # 颜色分布过滤:在候选区域统计“粉紫/粉蓝”(福袋) vs “橙色”(券) 像素数量 - try: - base_y = 403 * ry // 2400 + y_pianyi_val - cx1 = max(0, int((detected_x - 45) * rx / 1080)) - cx2 = min(pic_new.size[0], int((detected_x + 45) * rx / 1080)) - cy1 = max(0, base_y - 45) - cy2 = min(pic_new.size[1], base_y + 45) - fudai_like = 0 - coupon_like = 0 - if cx1 < cx2 and cy1 < cy2: - pix2 = pic_new.load() - step = max(1, (cx2 - cx1) // 24) # 下采样防止太慢 - for yy in range(cy1, cy2, step): - for xx in range(cx1, cx2, step): - try: - p = pix2[xx, yy] - except Exception: - continue - if not (isinstance(p, tuple) and len(p) >= 3): - continue - r, g, b = int(p[0]), int(p[1]), int(p[2]) - # 福袋:粉/紫/粉蓝:R 高、B 也高,G 中等 - if r >= 200 and b >= 210 and 80 <= g <= 230: - fudai_like += 1 - # 券:偏黄橙色:R 高、G 中等、B 明显偏低 - if r >= 200 and 120 <= g <= 230 and b <= 180: - coupon_like += 1 - # 如果“橙券像素”明显多于“粉袋像素”,判定为优惠券,丢弃 - if coupon_like > fudai_like * 1.2: + # 计算匹配区域在原图中的坐标(扩大一些范围以便查看上下文) + margin = 20 # 扩大20像素的边距 + match_x1 = max(0, search_x1 + detected_x_in_roi - margin) + match_y1 = max(0, search_y1 + detected_y_in_roi - margin) + match_x2 = min(screenshot_img.shape[1], search_x1 + detected_x_in_roi + tw + margin) + match_y2 = min(screenshot_img.shape[0], search_y1 + detected_y_in_roi + th + margin) + + # 裁剪匹配区域 + match_roi = screenshot_img[match_y1:match_y2, match_x1:match_x2] + + # 保存到 pic/template_match/ 目录 + base_dir = os.path.dirname(__file__) + pic_base = os.path.join(base_dir, 'pic') + match_dir = os.path.join(pic_base, 'template_match') + os.makedirs(match_dir, exist_ok=True) + + # 文件名包含时间戳和匹配分数 + timestamp = int(time.time() * 1000) + score_str = f"{max_val:.4f}".replace('.', '_') + match_filename = f"fudai_match_{timestamp}_score_{score_str}.png" + match_path = os.path.join(match_dir, match_filename) + + # 检查裁剪区域是否有效 + if match_roi.size == 0: + analyser._log_kv( + "[找福袋图标] 警告", + "匹配区域裁剪后为空,跳过保存", + 区域坐标=f"({match_x1}, {match_y1}) - ({match_x2}, {match_y2})", + ) + else: + # 保存图片 + save_success = cv2.imwrite(match_path, match_roi) + + # 验证文件是否真的保存成功 + file_exists = os.path.exists(match_path) + file_size = os.path.getsize(match_path) if file_exists else 0 + + analyser._log_kv( + "[找福袋图标] 已保存匹配位置图片", + f"路径: {match_path}", + 匹配区域=f"({match_x1}, {match_y1}) - ({match_x2}, {match_y2})", + 区域大小=f"{match_x2 - match_x1}x{match_y2 - match_y1}", + ROI尺寸=f"{match_roi.shape[1]}x{match_roi.shape[0]}", + cv2保存返回值=save_success, + 文件存在=file_exists, + 文件大小字节=file_size, + ) + + if not file_exists or file_size == 0: + analyser._log_kv( + "[找福袋图标] 警告", + "保存的图片文件不存在或大小为0", + 路径=match_path, + ) + else: + # 保存成功,输出绝对路径方便查看 + abs_path = os.path.abspath(match_path) + analyser._log_kv( + "[找福袋图标] 图片保存成功", + f"绝对路径: {abs_path}", + ) + except Exception as e: try: analyser._log_kv( - "[找福袋图标] 颜色过滤未通过", - "区域颜色更接近优惠券,视为非福袋", - fudai_like=fudai_like, - coupon_like=coupon_like, - x=detected_x, + "[找福袋图标] 保存匹配位置图片失败", + f"异常: {str(e)}", ) except Exception: pass - detected = False - detected_x = None - except Exception: - detected = False - detected_x = None - - if detected and detected_x is not None: - # store last X if analyser expects it(此时已通过颜色过滤) + + try: + analyser.last_find_fudai_time = time.time() + analyser._log_kv( + "[找福袋图标] 模板匹配命中", + f"检测到福袋图标", + x=detected_x, + y=detected_y, + 匹配分数=round(max_val, 4), + x_in_roi=detected_x_in_roi, + y_in_roi=detected_y_in_roi, + 模板中心偏移=f"({tw//2}, {th//2})", + 实际屏幕坐标=f"({detected_x}, {detected_y})", + ) + except Exception: + pass + break + else: + # 未命中时也记录日志 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配未命中", + f"匹配分数={round(max_val, 4)} < 阈值={template_threshold}", + 差值=round(template_threshold - max_val, 4), + ) + except Exception: + pass + except Exception as e: try: - analyser._last_fudai_icon_x = detected_x + analyser._log_kv( + "[找福袋图标] 模板匹配异常", + f"异常: {str(e)}", + 异常类型=type(e).__name__, + ) except Exception: pass - break # 检查是否还有剩余时间 elapsed = time.time() - func_start if elapsed < max_wait_s: - # 计算剩余时间,但至少等待 retry_delay_s remaining_time = max_wait_s - elapsed sleep_time = min(retry_delay_s, remaining_time) if sleep_time > 0: @@ -401,6 +503,11 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool return int(detected_x) if detected_x is not None else False +# ========== 以下为旧的像素检测代码,已暂时禁用 ========== +# 像素检测代码已删除,使用模板匹配替代 +# 如需恢复像素检测,请参考 git 历史记录 + + def check_in_fudai_detail(analyser: Any) -> bool: """Detect whether we are currently on the fudai detail page.""" _ensure_detection_cache(analyser) diff --git a/douyin_flow_control.py b/douyin_flow_control.py index 6b8dc3a..455563c 100644 --- a/douyin_flow_control.py +++ b/douyin_flow_control.py @@ -196,4 +196,3 @@ def filter_fudai_detail( return True return False - diff --git a/douyin_fudai.py b/douyin_fudai.py index 1665754..4179c02 100644 --- a/douyin_fudai.py +++ b/douyin_fudai.py @@ -78,6 +78,8 @@ class fudai_analyse: # 直播间检测阈值(模板匹配阈值,0.0~1.0,默认0.8) self.live_room_match_threshold: float = 0.8 + # 福袋模板匹配阈值(0.0~1.0,默认0.7) + self.fudai_template_match_threshold: float = 0.7 # 初次加载配置 self.load_config() @@ -152,6 +154,16 @@ class fudai_analyse: self.live_room_match_threshold = 0.0 if self.live_room_match_threshold > 1.0: self.live_room_match_threshold = 1.0 + + self.fudai_template_match_threshold = _float( + "fudai_template_match_threshold", + self.fudai_template_match_threshold, + ) + # 确保阈值在合理范围内 + if self.fudai_template_match_threshold < 0.0: + self.fudai_template_match_threshold = 0.0 + if self.fudai_template_match_threshold > 1.0: + self.fudai_template_match_threshold = 1.0 # ========== 兼容旧入口:主循环 ========== def fudai_choujiang(self, device_id: str = "", y_pianyi: int = 0, needswitch: bool = False, wait_minutes: int = 15) -> None: @@ -173,14 +185,58 @@ class fudai_analyse: ) # 基础循环:在限定时间内反复执行单轮逻辑 - end_ts = time.time() + max(1, int(wait_minutes)) * 60 - while time.time() < end_ts: - self.run_once_basic() - # 为避免过于频繁截图,增加少量间隔 - try: - self.operation.delay(1.0) - except Exception: - time.sleep(1.0) + # 如果 wait_minutes <= 0,则无限循环运行 + if wait_minutes and wait_minutes > 0: + end_ts = time.time() + int(wait_minutes) * 60 + while time.time() < end_ts: + try: + self.run_once_basic() + except Exception as e: + # 捕获异常,记录日志,但继续循环 + try: + self._log_kv("循环", "run_once_basic 异常", error=str(e), error_type=type(e).__name__) + except Exception: + pass + # 异常后稍作延迟再继续 + try: + self.operation.delay(2.0) + except Exception: + time.sleep(2.0) + continue + + # 为避免过于频繁截图,增加少量间隔 + try: + self.operation.delay(1.0) + except Exception: + time.sleep(1.0) + else: + # 无限循环模式(wait_minutes <= 0) + self._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)") + while True: + try: + self.run_once_basic() + except KeyboardInterrupt: + # 允许 Ctrl+C 退出 + self._log_kv("循环", "收到中断信号,退出循环") + raise + except Exception as e: + # 捕获异常,记录日志,但继续循环 + try: + self._log_kv("循环", "run_once_basic 异常", error=str(e), error_type=type(e).__name__) + except Exception: + pass + # 异常后稍作延迟再继续 + try: + self.operation.delay(2.0) + except Exception: + time.sleep(2.0) + continue + + # 为避免过于频繁截图,增加少量间隔 + try: + self.operation.delay(1.0) + except Exception: + time.sleep(1.0) # ========== 阶段诊断 ========== def _diagnose_stage_from_current_screen(self) -> Tuple[str, str]: diff --git a/douyin_stage.py b/douyin_stage.py index 32d681c..50d98a3 100644 --- a/douyin_stage.py +++ b/douyin_stage.py @@ -23,6 +23,7 @@ def diagnose_stage_from_current_screen(self): diag_start = time.time() max_diag_time = getattr(self, "stage_diag_max_time", 10.0) # 最大诊断时间(可配置,默认10秒) max_step_time = getattr(self, "stage_diag_max_step_time", 2.0) # 每个步骤最大耗时(可配置,默认2秒) + enable_ocr_mode1 = bool(getattr(self, "enable_ocr_mode1", False)) # OCR模式1开关(二值化) _log("开始阶段诊断", 最大诊断时间秒=max_diag_time, 单步最大耗时秒=max_step_time) @@ -173,7 +174,7 @@ def diagnose_stage_from_current_screen(self): 文本预览=t_follow[:50] if t_follow else "", ) - if (time.time() - step_start < max_step_time) and ("关注" not in t_follow): + if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("关注" not in t_follow): ocr_start_1 = time.time() t_follow = str(self.operation.analyse_pic_word("关注列表标签", 1) or "") ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 @@ -226,7 +227,7 @@ def diagnose_stage_from_current_screen(self): 文本预览=t_list[:50] if t_list else "", ) - if (time.time() - step_start < max_step_time) and ("正在直播" not in t_list): + if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and ("正在直播" not in t_list): ocr_start_1 = time.time() t_list = str(self.operation.analyse_pic_word("直播列表标签", 1) or "") ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 @@ -340,7 +341,7 @@ def diagnose_stage_from_current_screen(self): 文本预览=result_text[:50] if result_text else "", ) - if (time.time() - step_result_start < max_step_time) and (not result_text or ("没有抽中" not in result_text and "抽中福袋" not in result_text)): + 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() result_text = str(self.operation.analyse_pic_word("抽奖结果", 1) or "") ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 @@ -475,7 +476,7 @@ def diagnose_stage_from_current_screen(self): 文本预览=coupon_text[:50] if coupon_text else "", ) - if (time.time() - step_coupon_start < max_step_time) and (not coupon_text or "开心收下" not in coupon_text): + if enable_ocr_mode1 and (time.time() - step_coupon_start < max_step_time) and (not coupon_text or "开心收下" not in coupon_text): ocr_start_1 = time.time() coupon_text = str(self.operation.analyse_pic_word("参与按钮", 1) or "") ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 @@ -532,7 +533,7 @@ def diagnose_stage_from_current_screen(self): 文本预览=t_button[:50] if t_button else "", ) - if (time.time() - step_start < max_step_time) and (not t_button or ("加入粉丝团" not in t_button and "一键" not in t_button and "发表" not in t_button and "评论" not in t_button)): + if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and (not t_button or ("加入粉丝团" not in t_button and "一键" not in t_button and "发表" not in t_button and "评论" not in t_button)): ocr_start_1 = time.time() t_button = str(self.operation.analyse_pic_word("粉丝团加入", 1) or "") ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 @@ -602,50 +603,63 @@ def diagnose_stage_from_current_screen(self): _log("步骤1[像素检测福袋详情]-异常", 耗时毫秒=elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) # 如果像素检测未命中,使用OCR兜底检测 + # 但是,如果所有像素检测都未命中(没有任何像素特征),则跳过OCR检测 + has_any_pixel_feature = ( + pixel_state.get("has_coupon_bg", False) or + pixel_state.get("has_redpacket_bg", False) or + pixel_state.get("has_lucky_draw_result", False) or + pixel_state.get("has_attend_button_red", False) or + pixel_state.get("has_fansclub_join_red", False) + ) + if not detail_detected: - step_ocr_detail_start = time.time() - remaining_time_before = max_diag_time - (time.time() - diag_start) - _log("步骤1[OCR兜底检测福袋详情]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测未命中,OCR兜底确认") - - try: - if time.time() - step_ocr_detail_start < max_step_time: - cut_start = time.time() - # 使用参与按钮区域进行OCR检测 (200, 1940)-(880, 2140) - self.cut_pic(200, 1940, 880, 2140, "", "参与按钮") - cut_elapsed = (time.time() - cut_start) * 1000 - _log("步骤1[OCR兜底检测福袋详情]-截图完成", 耗时毫秒=cut_elapsed) - + if not has_any_pixel_feature: + # 所有像素检测都未命中,跳过OCR检测 + _log("步骤1[OCR兜底检测福袋详情]-跳过", 说明="所有像素检测都未命中,跳过OCR检测") + else: + step_ocr_detail_start = time.time() + remaining_time_before = max_diag_time - (time.time() - diag_start) + _log("步骤1[OCR兜底检测福袋详情]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测未命中,OCR兜底确认") + + try: if time.time() - step_ocr_detail_start < max_step_time: - ocr_start = time.time() - detail_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "") - ocr_elapsed = (time.time() - ocr_start) * 1000 - _log( - "步骤1[OCR兜底检测福袋详情]-OCR模式0", - 耗时毫秒=ocr_elapsed, - 文本长度=len(detail_text), - 文本预览=detail_text[:50] if detail_text else "", - ) + cut_start = time.time() + # 使用参与按钮区域进行OCR检测 (200, 1940)-(880, 2140) + self.cut_pic(200, 1940, 880, 2140, "", "参与按钮") + cut_elapsed = (time.time() - cut_start) * 1000 + _log("步骤1[OCR兜底检测福袋详情]-截图完成", 耗时毫秒=cut_elapsed) - # 检测福袋详情页关键词 - detail_keywords = ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看", "一键", "发表") - if detail_text and any(kw in detail_text for kw in detail_keywords): - detail_detected = True - elif (time.time() - step_ocr_detail_start < max_step_time) and (not detail_text or not any(kw in detail_text for kw in detail_keywords)): - ocr_start_1 = time.time() - detail_text = str(self.operation.analyse_pic_word("参与按钮", 1) or "") - ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 + if time.time() - step_ocr_detail_start < max_step_time: + ocr_start = time.time() + detail_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "") + ocr_elapsed = (time.time() - ocr_start) * 1000 _log( - "步骤1[OCR兜底检测福袋详情]-OCR模式1", - 耗时毫秒=ocr_elapsed_1, + "步骤1[OCR兜底检测福袋详情]-OCR模式0", + 耗时毫秒=ocr_elapsed, 文本长度=len(detail_text), 文本预览=detail_text[:50] if detail_text else "", ) - + + # 检测福袋详情页关键词 + detail_keywords = ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看", "一键", "发表") if detail_text and any(kw in detail_text for kw in detail_keywords): detail_detected = True - except Exception as e: - detail_ocr_elapsed = (time.time() - step_ocr_detail_start) * 1000 - _log("步骤1[OCR兜底检测福袋详情]-异常", 耗时毫秒=detail_ocr_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) + elif enable_ocr_mode1 and (time.time() - step_ocr_detail_start < max_step_time) and (not detail_text or not any(kw in detail_text for kw in detail_keywords)): + ocr_start_1 = time.time() + detail_text = str(self.operation.analyse_pic_word("参与按钮", 1) or "") + ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000 + _log( + "步骤1[OCR兜底检测福袋详情]-OCR模式1", + 耗时毫秒=ocr_elapsed_1, + 文本长度=len(detail_text), + 文本预览=detail_text[:50] if detail_text else "", + ) + + if detail_text and any(kw in detail_text for kw in detail_keywords): + detail_detected = True + except Exception as e: + detail_ocr_elapsed = (time.time() - step_ocr_detail_start) * 1000 + _log("步骤1[OCR兜底检测福袋详情]-异常", 耗时毫秒=detail_ocr_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) if detail_detected: total_elapsed = (time.time() - diag_start) * 1000 diff --git a/gui_app.py b/gui_app.py index d69e030..39d0d73 100644 --- a/gui_app.py +++ b/gui_app.py @@ -179,6 +179,9 @@ def main(): # 阶段诊断时间参数(用于调试) stage_diag_max_time_var = tk.DoubleVar(value=float(cfg.get("stage_diag_max_time", 10.0) or 10.0)) stage_diag_max_step_time_var = tk.DoubleVar(value=float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)) + enable_ocr_mode1_var = tk.BooleanVar(value=bool(cfg.get("enable_ocr_mode1", False))) + # 福袋模板匹配阈值 + fudai_template_match_threshold_var = tk.DoubleVar(value=float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)) run_box = ttk.LabelFrame(left, text="运行设置") run_box.pack(fill=X, pady=(0, 10)) @@ -433,6 +436,14 @@ def main(): ttk.Label(diag_time_r1, text="每步最大耗时(秒):").pack(side=LEFT, padx=(12, 0)) ttk.Spinbox(diag_time_r1, from_=0.5, to=30.0, increment=0.5, textvariable=stage_diag_max_step_time_var, width=8).pack(side=LEFT) ttk.Label(diag_time_r1, text="(用于调试,延长检测时间)").pack(side=LEFT, padx=(6, 0)) + diag_time_r2 = ttk.Frame(diag_time_box) + diag_time_r2.pack(fill=X, padx=10, pady=(0, 6)) + ttk.Checkbutton(diag_time_r2, text="启用OCR模式1(二值化)", variable=enable_ocr_mode1_var).pack(side=LEFT) + diag_time_r3 = ttk.Frame(diag_time_box) + diag_time_r3.pack(fill=X, padx=10, pady=(0, 10)) + ttk.Label(diag_time_r3, text="福袋模板匹配阈值:").pack(side=LEFT) + ttk.Spinbox(diag_time_r3, from_=0.0, to=1.0, increment=0.01, textvariable=fudai_template_match_threshold_var, width=8).pack(side=LEFT) + ttk.Label(diag_time_r3, text="(0.0-1.0,彩色匹配)").pack(side=LEFT, padx=(6, 0)) kw_box = ttk.LabelFrame(left, text="关键词(每行一个)") kw_box.pack(fill=BOTH, expand=True) @@ -484,6 +495,8 @@ def main(): fudai_quiet_end_hour_var.set(int(cfg.get("fudai_quiet_end_hour", 7) or 7)) stage_diag_max_time_var.set(float(cfg.get("stage_diag_max_time", 10.0) or 10.0)) stage_diag_max_step_time_var.set(float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)) + enable_ocr_mode1_var.set(bool(cfg.get("enable_ocr_mode1", False))) + fudai_template_match_threshold_var.set(float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)) yg_like_prob_var.set(float(cfg.get("yanghao_like_prob", 0.0) or 0.0)) yg_fav_prob_var.set(float(cfg.get("yanghao_fav_prob", 0.0) or 0.0)) @@ -570,6 +583,8 @@ def main(): cfg2["fudai_quiet_end_hour"] = int(fudai_quiet_end_hour_var.get() or 0) cfg2["stage_diag_max_time"] = float(stage_diag_max_time_var.get() or 10.0) cfg2["stage_diag_max_step_time"] = float(stage_diag_max_step_time_var.get() or 2.0) + cfg2["enable_ocr_mode1"] = bool(enable_ocr_mode1_var.get()) + cfg2["fudai_template_match_threshold"] = float(fudai_template_match_threshold_var.get() or 0.7) cfg2["yanghao_enabled"] = bool(yg_enabled_var.get()) cfg2["yanghao_enable_actions"] = bool(yg_actions_enabled_var.get()) @@ -893,6 +908,7 @@ def main(): def get_params() -> RunParams: return RunParams( + enable_ocr_mode1=bool(enable_ocr_mode1_var.get()), device_id=device_var.get().strip(), y_pianyi=int(y_var.get()), needswitch=bool(needswitch_var.get()), @@ -912,6 +928,7 @@ def main(): reservation_back_swipe_delay=float(reservation_back_swipe_delay_var.get() or 0), reservation_preempt_min_value=float(reservation_preempt_min_value_var.get() or 0), fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 0), + fudai_template_match_threshold=float(fudai_template_match_threshold_var.get() or 0.7), ) def start_run(): diff --git a/gui_core.py b/gui_core.py index 5f04c2d..1650b07 100644 --- a/gui_core.py +++ b/gui_core.py @@ -89,6 +89,8 @@ class RunParams: reservation_back_swipe_delay: float reservation_preempt_min_value: float fudai_find_max_attempts: int + enable_ocr_mode1: bool + fudai_template_match_threshold: float class Runner: @@ -399,6 +401,15 @@ class Runner: # 找福袋最大尝试次数 if params.fudai_find_max_attempts > 0: cmd += ["--fudai-find-max-attempts", str(params.fudai_find_max_attempts)] + + # OCR模式1开关 + if params.enable_ocr_mode1: + cmd.append("--enable-ocr-mode1") + else: + cmd.append("--disable-ocr-mode1") + + # 添加福袋模板匹配阈值参数 + cmd.extend(["--fudai-template-threshold", str(params.fudai_template_match_threshold)]) # 继承当前环境,并确保 adb 在 PATH(即使用户没手动刷新 PATH) env = os.environ.copy() diff --git a/path_config.py b/path_config.py index f9404e3..ea66c9d 100644 --- a/path_config.py +++ b/path_config.py @@ -153,6 +153,13 @@ def ensure_dir(path: str) -> None: + + + + + + + diff --git a/run_cli.py b/run_cli.py index bef48d5..543cd3c 100644 --- a/run_cli.py +++ b/run_cli.py @@ -79,7 +79,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace: p.add_argument("--device-id", default="", help="ADB 设备 ID(为空则自动选择)") p.add_argument("--y-pianyi", type=int, default=0, help="y 轴偏移(通常 -50~50)") p.add_argument("--needswitch", action="store_true", help="是否允许上划切换直播间") - p.add_argument("--wait-minutes", type=int, default=5, help="倒计时超过该分钟则切换(needswitch 生效)") + p.add_argument("--wait-minutes", type=int, default=0, help="运行时长(分钟),0或负数表示无限运行,默认0(无限运行)") p.add_argument("--test-yanghao-flow", action="store_true", help="测试:只执行一次推荐页养号流程并退出") p.add_argument("--test-yanghao-flow-seconds", type=int, default=10, help="测试:推荐页养号停留秒数") @@ -115,6 +115,9 @@ def parse_args(argv: list[str]) -> argparse.Namespace: p.add_argument("--auto-join-fansclub", action="store_true", help="自动尝试加入粉丝团(可能消耗钻石)") p.add_argument("--fansclub-fail-action", choices=["stay", "switch"], default=None, help="粉丝团门槛无法处理时:stay=停留当前直播间;switch=切换下一个") + p.add_argument("--enable-ocr-mode1", action="store_true", help="启用OCR模式1(二值化模式,默认关闭)") + p.add_argument("--disable-ocr-mode1", action="store_true", help="禁用OCR模式1(默认已禁用)") + p.add_argument("--fudai-template-threshold", type=float, default=None, help="福袋模板匹配阈值(0.0-1.0,默认0.7)") return p.parse_args(argv) @@ -258,6 +261,19 @@ def main(argv: list[str]) -> int: analyser.fudai_find_max_attempts = max(1, int(args.fudai_find_max_attempts)) except Exception: pass + # OCR模式1开关(命令行优先) + if getattr(args, "enable_ocr_mode1", False): + analyser.enable_ocr_mode1 = True + if getattr(args, "disable_ocr_mode1", False): + analyser.enable_ocr_mode1 = False + # 福袋模板匹配阈值(命令行优先) + if getattr(args, "fudai_template_threshold", None) is not None: + try: + threshold = float(args.fudai_template_threshold) + if 0.0 <= threshold <= 1.0: + analyser.fudai_template_match_threshold = threshold + except Exception: + pass device_id = args.device_id.strip() if args.device_id else "" if not device_id: