From 8b47b506d693343958bdbd830fa1ddec3fd26959 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 20 Dec 2025 13:32:32 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20Enhance=20=E7=A6=8F=E8=A2=8B=20detectio?= =?UTF-8?q?n=20and=20reservation=20logic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Updated `config.json` to introduce new settings for infinite loop mode and adjust various thresholds for 福袋 detection. - Refined the pixel detection logic in `douyin_detection.py` to improve error handling and retry mechanisms. - Enhanced reservation handling in `douyin_flow_control.py` to prioritize high-value 福袋 and streamline the switching process. - Improved the GUI in `gui_app.py` to support new configuration options and ensure better user experience. - Added new tools for analyzing 福袋 colors and comparing them with coupon colors to aid in detection accuracy. - Updated documentation to reflect changes in configuration and usage instructions. --- README.md | 6 +- assets/quan.png | Bin 0 -> 16785 bytes config.json | 34 +- douyin_detection.py | 418 ++++++++++++++++--- douyin_flow_control.py | 64 ++- douyin_fudai.py | 648 +++++++++++++++++++++++++++- douyin_fudai_core.py | 650 ++++++++++++++++++++++++++++- douyin_fudai_detail.py | 358 +++++++++++++++- douyin_high_value_room.py | 247 +++++++++++ douyin_pixel.py | 20 +- douyin_reservation_logic.py | 764 ++++++++++++++++++++-------------- douyin_reservation_verify.py | 346 +++++++++++++++ douyin_stage.py | 167 ++++---- gui_app.py | 38 +- gui_core.py | 4 +- path_config.py | 6 + run_cli.py | 2 +- state/high_value_rooms.json | 51 ++- state/reservations.json | 23 +- tools/README_RGB工具.md | 75 ++++ tools/analyze_fudai_color.py | 67 +++ tools/compare_fudai_coupon.py | 83 ++++ tools/read_fudai_rgb.py | 140 +++++++ tools/read_image_rgb.py | 175 ++++++++ webui/index.html | 2 +- 功能差异对比.md | 249 +++++++++++ 模块化代码对比说明.md | 285 +++++++++++++ 27 files changed, 4382 insertions(+), 540 deletions(-) create mode 100644 assets/quan.png create mode 100644 douyin_reservation_verify.py create mode 100644 tools/README_RGB工具.md create mode 100644 tools/analyze_fudai_color.py create mode 100644 tools/compare_fudai_coupon.py create mode 100644 tools/read_fudai_rgb.py create mode 100644 tools/read_image_rgb.py create mode 100644 功能差异对比.md create mode 100644 模块化代码对比说明.md diff --git a/README.md b/README.md index 0f7f8d7..3343f5b 100644 --- a/README.md +++ b/README.md @@ -369,7 +369,7 @@ python run_cli.py \ - `--wait-minutes`:倒计时超过 N 分钟时切换 - `--min-prize-value-yuan`:最低奖品价值(元) - `--min-participants`:最少参与人数 -- `--skip-if-countdown-lt-seconds`:跳过倒计时少于 N 秒的福袋 +- `--skip-if-countdown-lt-seconds`:跳过倒计时小于 N 秒的福袋 ### 方式三:Web GUI(适合远程控制) @@ -412,7 +412,7 @@ python run_cli.py \ |--------|------|--------|------| | `needswitch` | boolean | `true` | 是否允许上划切换直播间 | | `wait_minutes` | integer | `5` | 倒计时超过该分钟数时切换直播间(仅在 needswitch=true 时生效) | -| `skip_if_countdown_lt_seconds` | integer | `5` | 跳过倒计时少于该秒数的福袋(避免来不及参与) | +| `skip_if_countdown_lt_seconds` | integer | `5` | 倒计时小于该秒数时不参与(高价值福袋可预约) | | `reset_after_swipes_enabled` | boolean | `true` | 是否启用"切换N次后回到第一个直播间"功能 | | `reset_after_swipes` | integer | `30` | 切换直播间达到该次数后,下滑回退到第一个直播间 | | `fudai_find_max_attempts` | integer | `10` | 找福袋图标的最大尝试次数 | @@ -689,7 +689,7 @@ python run_cli.py \ │ └─> 通过 │ ├─> 倒计时筛选 - │ ├─> 倒计时 < skip_if_countdown_lt_seconds → 跳过 + │ ├─> 倒计时 < skip_if_countdown_lt_seconds → 不参与(高价值可预约) │ └─> 通过 │ ├─> 关键词筛选 diff --git a/assets/quan.png b/assets/quan.png new file mode 100644 index 0000000000000000000000000000000000000000..b05e5f80d80482f57f17d96bc6b42ce37eebccbb GIT binary patch literal 16785 zcmV(_K-9m9P)KEW00009a7bBm000ie z000ie0hKEb8vpOc)ph21Rj>Bm7q#{ku?R52Yyz_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ft;aCibJj7N-2GDeWAEy%sGvUnAkM^{qd*BUsa1j&nGP4tV&{%{&kJZw z2ZBT|v{qr6KdE4N0fWRxL`xS?nw1d^fG*}>{G|OF-0u@C$bNk5$U1zL$_DPM^A`NH zrU3G%|9DUE_+U;B*YS;Mguu=vcm?z*?1*uC_eIa;^P}dpOdsjv7I!_2Mv%Z^XAS|A zY+oKkHD(8lZSau5R}RPfHc5HaU6REPfC()BV2N47iy9dzd-RVY_$OgSAz5=JCN1Er zS?IcS11kPU73*iAQQY!t1IJFL6osJ}Q5w;-vmT_e@i zD@_yEH4f6LFn@DPC=|It^L2Mx7jvdpTYLCp@m`mqLxB8F=}LFMgmbVY zv7<*BhU&f-C9<$!e1aT-6ayNoUojO3BieznyTJ^XQd^!lOmGb)MWCt%WiKRQF|P zlX(?v!%#XcUwXbIySmSiyB|EdH8w{h*PjauZ~rgX#TU&O$Ce_a*tO4puZ*K~Jk++? zcGktN8`Dg`70VIdL8F8>+n(^u<@CY@+@{ZerenO;|85yDafC4 zYpndfKPuHBeR>8E~gx}>|1+CxjW`ee!2m>+pWe`lOVtEQ=B7suOlGMr%DbOGlk2zI-9YrIfDO2)ysqoy>bx6pU)jqX&hNpQhK zEj}9J^a5tLsJUd_9)i7d4mFbdE5eFO|j&#cb!TL(3KvUmh- zWO%?^k{+oE@3iN!(f}1f?R?tE*-4{;->zw!){&D#Qy_NxV7JbG6j^8?>qUaD7;d&kS2>ot84N z7l8q00h#_<4~5oz=u|Zyit?-gV|l3?X)8=`O|_=?6m=j)nFV784QK!W0V_#FK~#S_ z0s$8iosy`EI1jANkaVpW`Xu@w)(wZKZlcEb8=AH`mmW73_Rz*ff?5hgH1f$j$5Wzm(75Fn zcFUT;-T~h@gkI;}C 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) continue - img = pic.convert("RGBA") - width, height = img.size + pic_new = pic.convert("RGBA") + width, height = pic_new.size try: rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) except Exception: @@ -198,46 +210,352 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool except Exception: y_pianyi_val = 0 - # 扫描 y=403 一带的水平带(与原始脚本一致),按分辨率和 y_pianyi 缩放 - scan_y = 403 * ry // 2400 + y_pianyi_val - scan_x_start = 41 * rx // 1080 - scan_x_end = min(410 * rx // 1080, width) + detected = False + detected_x = None + + # 先尝试 numpy 加速扫描水平带(性能优化:批量处理) + try: + import numpy as _np + # 计算检测区域,考虑分辨率缩放和偏移 + y0 = 403 * ry // 2400 + y_pianyi_val + x1 = max(0, 41 * rx // 1080) + x2 = min(width, 410 * rx // 1080) + y_top = max(0, y0 - 3) + y_bottom = min(height, y0 + 4) + + # 边界检查 + 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] + # 精度优化:扩大颜色范围,提高容错性(考虑不同屏幕色温和亮度) + # 原来的范围:R[193-203], G[176-193], B[237-247] + # 优化后:适度放宽范围,但保持中心值权重 + mask_center = (r >= 190) & (r <= 206) & (g >= 173) & (g <= 196) & (b >= 234) & (b <= 250) + # 速度优化:使用更宽松的预筛选,减少计算量 + mask = mask_center + # 检查每一列是否有足够多的匹配像素(提高准确性,避免单个噪点误判) + cols = _np.sum(mask, axis=0) + # 至少需要2个像素匹配(避免单个噪点误判) + valid_cols = cols >= 2 + if valid_cols.any(): + # 找到第一个有效匹配的列 + col_idx = int(_np.argmax(valid_cols)) + # 计算检测到的x坐标:转换为1080基准坐标,确保精度 + detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx)) + detected = True + try: + analyser.last_find_fudai_time = time.time() + except Exception: + pass + except (ImportError, ValueError, IndexError, AttributeError): + # numpy不可用或计算错误,回退到逐像素检测 + detected = False - if 0 <= scan_y < height and scan_x_start < scan_x_end: - pix = img.load() - detected_x = None - for offset_y in [0, -1, 1, -2, 2]: - check_y = scan_y + offset_y - if not (0 <= check_y < height): - continue - for x_scaled in range(scan_x_start, scan_x_end): - try: - px = pix[x_scaled, check_y] - if ( - isinstance(px, tuple) - and len(px) >= 3 - and 190 <= int(px[0]) <= 206 - and 173 <= int(px[1]) <= 196 - and 234 <= int(px[2]) <= 250 - ): - detected_x = int(x_scaled * 1080.0 / max(1, rx)) + # numpy 未命中/不可用时回退到原始逐像素检查 + if not detected: + try: + pix = pic_new.load() + pic_width, pic_height = pic_new.size + # 计算实际扫描范围,防止越界 + scan_x_start = 41 * rx // 1080 + scan_x_end = min(410 * rx // 1080, pic_width) + scan_y = 403 * ry // 2400 + y_pianyi_val + # 确保y坐标在有效范围内 + if 0 <= scan_y < pic_height: + # 精度优化:同时检查上下几行像素,提高检测准确性 + for offset_y in [0, -1, 1, -2, 2]: # 检查当前行及上下2行 + check_y = scan_y + offset_y + 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] + # 检查RGB值是否匹配福袋图标颜色(适度放宽范围) + if isinstance(px, tuple) and len(px) >= 3: + if 190 <= px[0] <= 206 and 173 <= px[1] <= 196 and 234 <= px[2] <= 250: + # 转换回1080基准坐标 + detected_x = int(x_scaled * 1080.0 / max(1, rx)) + detected = True + try: + analyser.last_find_fudai_time = time.time() + except Exception: + pass + break + except (IndexError, TypeError): + continue + if detected: break - except Exception: - continue - if detected_x is not None: - break + if detected: + pass # 已设置 detected = True + except Exception: + # 像素检测失败,记录但不影响主流程 + pass - if detected_x is not None: - return detected_x + # 像素检测未命中时,使用模板匹配作为兜底 + if not detected or detected_x is None: + try: + import cv2 + import numpy as np + + # 获取模板路径 + base_dir = os.path.dirname(__file__) + template_path = os.path.join(base_dir, "assets", "fudai.png") + + if os.path.exists(template_path): + # 获取匹配阈值 + try: + template_threshold = float(getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7) + except Exception: + template_threshold = 0.7 + + # 读取模板 + template = cv2.imread(template_path, cv2.IMREAD_COLOR) + if template is not None: + # 将PIL图片转换为OpenCV格式 + pic_rgb = pic_new.convert("RGB") + screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR) + + # 定义搜索区域:X=156-269(1080基准),Y=351-451(2400基准) + x1 = max(0, 156 * rx // 1080) + x2 = min(width, 269 * rx // 1080) + y_top = max(0, 351 * ry // 2400 + y_pianyi_val) + y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val) + + if x1 < x2 and y_top < y_bottom: + search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] + + if search_roi.size > 0: + th, tw = template.shape[:2] + rh, rw = search_roi.shape[:2] + + # 保存搜索区域截图到 last_match.png + try: + 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) + last_match_path = os.path.join(match_dir, 'last_match.png') + + # 保存截图并检查是否成功 + save_success = cv2.imwrite(last_match_path, search_roi) + if save_success: + try: + analyser._log_kv( + "[找福袋图标] 已保存搜索区域截图", + loop=loop, + 文件路径=last_match_path, + 搜索区域尺寸=f"{rw}x{rh}", + 搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})", + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "[找福袋图标] 保存搜索区域截图失败", + loop=loop, + 文件路径=last_match_path, + ) + except Exception: + pass + except Exception as save_err: + try: + analyser._log_kv( + "[找福袋图标] 保存搜索区域截图异常", + loop=loop, + 错误类型=type(save_err).__name__, + 错误信息=str(save_err), + ) + except Exception: + pass + + # 如果模板太大,缩小模板 + 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] + + # 执行模板匹配 + if th <= rh and tw <= rw: + res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED) + _min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) + + try: + analyser._log_kv( + "[找福袋图标] 模板匹配兜底", + loop=loop, + 匹配分数=round(max_val, 4), + 阈值=template_threshold, + 是否通过=bool(max_val >= template_threshold), + 搜索区域=f"({x1},{y_top})-({x2},{y_bottom})", + 搜索区域尺寸=f"{rw}x{rh}", + 模板尺寸=f"{tw}x{th}", + 截图尺寸=f"{width}x{height}", + 分辨率=f"{rx}x{ry}", + ) + except Exception: + pass + + if max_val >= template_threshold: + # 计算检测到的X坐标(1080基准) + detected_x_in_roi = max_loc[0] + detected_x = int((x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)) + detected = True + try: + analyser.last_find_fudai_time = time.time() + except Exception: + pass + else: + # 模板尺寸不匹配,记录调试信息 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配失败-尺寸不匹配", + loop=loop, + 模板尺寸=f"{tw}x{th}", + 搜索区域尺寸=f"{rw}x{rh}", + 条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})", + ) + except Exception: + pass + else: + # 搜索区域为空,记录调试信息 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配失败-搜索区域为空", + loop=loop, + 搜索区域=f"({x1},{y_top})-({x2},{y_bottom})", + 截图尺寸=f"{width}x{height}", + ) + except Exception: + pass + else: + # 搜索区域坐标无效,记录调试信息 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配失败-坐标无效", + loop=loop, + x1=x1, + x2=x2, + y_top=y_top, + y_bottom=y_bottom, + 截图尺寸=f"{width}x{height}", + 分辨率=f"{rx}x{ry}", + ) + except Exception: + pass + except (ImportError, Exception) as e: + # OpenCV不可用或模板匹配失败,继续使用像素检测结果 + try: + analyser._log_kv( + "[找福袋图标] 模板匹配异常", + loop=loop, + 错误类型=type(e).__name__, + 错误信息=str(e), + ) + except Exception: + pass + + if detected and detected_x is not None: + # 统计:每次"进入直播间"后首次找到福袋图标耗时 + try: + enter_ts = float(getattr(analyser, "_enter_live_ts", 0.0) or 0.0) + except Exception: + enter_ts = 0.0 + try: + already = bool(getattr(analyser, "_enter_live_fudai_logged", False)) + except Exception: + already = False + if (enter_ts > 0) and (not already): + try: + dt = float(time.time() - enter_ts) + except Exception: + dt = -1.0 + if dt >= 0: + try: + reason = str(getattr(analyser, "_enter_live_reason", "") or "") + except Exception: + reason = "" + try: + analyser._enter_live_fudai_logged = True + except Exception: + pass + try: + analyser._log_kv( + "性能", + "进入直播间后找到福袋耗时", + seconds=round(dt, 2), + enter_reason=reason, + fudai_x=int(detected_x or 0), + ) + except Exception: + pass + + # 命中时记录调试信息 + try: + elapsed_ms = int((time.time() - func_start) * 1000) + scan_y_for_log = 403 * ry // 2400 + y_pianyi_val + analyser._log_kv( + "[找福袋图标] 命中", + loop=loop, + elapsed_ms=elapsed_ms, + scan_y=scan_y_for_log, + x=detected_x, + ) + except Exception: + pass + return int(detected_x or 0) loop += 1 - if loop < max_loops: + # 每轮记录一次轻量调试信息(帮助诊断为何未命中) + try: + elapsed_ms = int((time.time() - func_start) * 1000) + sample_color = None try: - analyser.operation.delay(retry_delay_s) + mid_x = (scan_x_start + scan_x_end) // 2 + if 0 <= scan_y < height and 0 <= mid_x < width: + sample_color = img.load()[mid_x, scan_y] except Exception: - time.sleep(retry_delay_s) + sample_color = None + analyser._log_kv( + "[找福袋图标] 循环中", + loop=loop, + elapsed_ms=elapsed_ms, + scan_y=scan_y, + scan_x_start=scan_x_start, + scan_x_end=scan_x_end, + sample_color=str(sample_color) if sample_color is not None else "None", + ) + except Exception: + pass - # 像素检测未找到时,返回 False + # 检查是否还有剩余时间 + 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) + + # 像素检测未找到时,返回 False,并记录总耗时与循环次数 + try: + total_elapsed_ms = int((time.time() - func_start) * 1000) + analyser._log_kv( + "[找福袋图标] 未找到福袋图标", + elapsed_ms=total_elapsed_ms, + total_loops=loop, + max_wait_s=max_wait_s, + retry_delay_s=retry_delay_s, + ) + except Exception: + pass return False try: diff --git a/douyin_flow_control.py b/douyin_flow_control.py index 6e38d2e..04f246d 100644 --- a/douyin_flow_control.py +++ b/douyin_flow_control.py @@ -16,6 +16,7 @@ import time from douyin_detection import check_have_fudai_with_ready_screenshot from douyin_fudai_core import should_skip_fudai_by_config +import douyin_reservation_logic def handle_stage_after_diagnosis( @@ -110,7 +111,12 @@ def handle_no_fudai_situation( reset_to_list_after_reservations_ref: List[bool], swipe_times_ref: List[int], ) -> bool: - """当前直播间没有福袋时的基础处理:稍微等待,然后按需要上滑切换。""" + """当前直播间没有福袋时的基础处理。 + + 本地版实现: + - 先让预约模块有机会“抢占”流程(例如到点需要回退到预约直播间); + - 若未触发预约回退,则执行简单的等待 + 上滑切换。 + """ try: analyser._log_kv( "流程", @@ -123,6 +129,62 @@ def handle_no_fudai_situation( except Exception: pass + # --- 优先让“预约回退窗口”有机会执行 --- + try: + if getattr(analyser, "high_value_fudai_enabled", False) and reservations: + # 构造回调:下滑回退一个直播间 + def _swipe_down_once() -> None: + try: + if swipe_down_back_callback: + swipe_down_back_callback() + except Exception: + pass + + def _sort_reservations() -> None: + try: + # 使用统一核心逻辑排序 + douyin_reservation_logic._sort_reservations_inplace(reservations) # type: ignore[attr-defined] + except Exception: + pass + + def _write_state() -> None: + try: + if write_state_callback: + write_state_callback() + except Exception: + pass + + # 调用预约窗口处理:若返回 True,表示已触发回退,本轮不再上滑 + def _seek_reservation_room(item: dict) -> bool: + """委托给 analyser._seek_reservation_room,避免简化为恒 True。""" + try: + fn = getattr(analyser, "_seek_reservation_room", None) + if not fn: + return False + return bool(fn(item)) + except Exception: + return False + + preempted = douyin_reservation_logic.process_reservation_attend_window( + analyser=analyser, + reservations=reservations, + room_pos=room_pos, + reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, + reservation_after_action_pending_ref=[False], + reservation_back_swipe_delay_s=float( + getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6 + ), + swipe_down_back_callback=_swipe_down_once, + seek_reservation_room_callback=_seek_reservation_room, + sort_reservations_callback=_sort_reservations, + write_state_callback=_write_state, + ) + if preempted: + return True + except Exception: + # 预约处理异常不影响基础切换逻辑 + pass + # 简单策略:轻微等待 + 上滑切换 try: analyser.operation.delay(1.0) diff --git a/douyin_fudai.py b/douyin_fudai.py index 6749e31..b99bca5 100644 --- a/douyin_fudai.py +++ b/douyin_fudai.py @@ -30,6 +30,9 @@ import douyin_text_utils import douyin_utils import douyin_yanghao import douyin_pixel +import douyin_reservation_logic +import douyin_reservation_verify +import douyin_high_value_room class fudai_analyse: @@ -42,6 +45,9 @@ class fudai_analyse: self.resolution_ratio_x: int = 1080 self.resolution_ratio_y: int = 2400 + # 滑动次数计数器(用于滑动次数重置功能) + self._swipe_times: int = 0 + # 运行配置(只保留与你当前需求直接相关的主流程字段,细节统一放在各子模块内部) self.operation = underlying_operations() self.config_path = "config.json" @@ -77,12 +83,73 @@ class fudai_analyse: self.screenshot_diagnose_min_interval_seconds: float = 8.0 # 开奖页面检测红色占比阈值(0.0~1.0) self.lucky_draw_red_ratio_threshold: float = 0.9 - + # 直播间检测阈值(模板匹配阈值,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 + # —— 高价值福袋 / 预约相关配置(从原 fudai1 精简迁移) —— + # 是否启用“高价值福袋预约参与” + self.high_value_fudai_enabled: bool = False + # 高价值阈值(元) + self.high_value_fudai_threshold_yuan: float = 500.0 + # 提前参与秒数:开奖前 N 秒回到该直播间并参与 + self.high_value_fudai_join_ahead_seconds: int = 120 + # 从当前位置最多回滑多少次以回到预约直播间 + self.high_value_fudai_max_swipe_back: int = 35 + # 同时记录的最大预约数量 + self.high_value_fudai_max_reservations: int = 3 + # 完成某个预约福袋后的动作:stay=停留当前直播间;continue=继续执行抢福袋 + self.high_value_fudai_after_action: str = "continue" + self.high_value_fudai_after_stay_seconds: int = 120 + + # 高价值直播间“回访”相关(当前仅保留配置,不在本地版强制启用复杂逻辑) + self.high_value_room_revisit_enabled: bool = False + self.high_value_room_revisit_only_current_run: bool = False + + # 预约回退相关 + self.reservation_back_verify_enabled: bool = True # 默认启用回退校验 + # 未做回退校验时的快速回滑延迟(秒) + self.reservation_back_swipe_delay: float = 0.6 + # 预约抢占最小价值:低于该价值的预约不会抢占当前任务(元) + self.reservation_preempt_min_value_yuan: float = 0.0 + # 在预计开奖前多少秒开始积极轮询结果 + self.poll_before_open_seconds: int = 10 + + # 滑动次数重置相关 + self.reset_after_swipes_enabled: bool = False # 由 Web/CLI 显式开关 + self.reset_after_swipes: int = 10 # 达到阈值次数后回退,需启用开关后生效 + + # 意外返回桌面自救相关 + self.desktop_icon_x: int = 153 # 桌面图标 X 坐标(默认值) + self.desktop_icon_y: int = 260 # 桌面图标 Y 坐标(默认值) + self.yanghao_fallback_live_x: int = 540 # 养号备用直播按钮 X 坐标 + self.yanghao_fallback_live_y: int = 2000 # 养号备用直播按钮 Y 坐标 + self.yanghao_fallback_enter_live_x: int = 540 # 养号备用进入直播间 X 坐标 + self.yanghao_fallback_enter_live_y: int = 1200 # 养号备用进入直播间 Y 坐标 + + # —— 预约运行时状态(单次运行内有效) —— + # 高价值福袋预约队列 + self.reservations: list[dict[str, Any]] = [] + # 当前“直播间位置”计数:上划 +1,下滑 -1(仅在本次连续切换过程中有效) + self.room_pos: int = 0 + # 回退到预约直播间后,在该时间戳前不允许上划离开 + self.reservation_focus_until_ts: float = 0.0 + # 当前是否还有“完成某个预约后的后续动作”待执行 + self.reservation_after_action_pending: bool = False + # 达到"无福袋切换阈值"后,是否在处理完预约后回到列表第一个直播间 + self.reset_to_list_after_reservations: bool = False + # 队列满时是否已回退到最早开奖的预约直播间等待 + self.queue_full_waiting_at_earliest: bool = False + # 队列满时是否已回退到最早开奖的预约直播间等待 + self.queue_full_waiting_at_earliest: bool = False + + # 预约队列状态文件(供 WebGUI / 其他进程查看) + self._reservations_state_path: str = os.path.join( + os.path.dirname(__file__), "state", "reservations.json" + ) + # 初次加载配置 self.load_config() @@ -172,7 +239,7 @@ 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, @@ -183,6 +250,133 @@ class fudai_analyse: if self.fudai_template_match_threshold > 1.0: self.fudai_template_match_threshold = 1.0 + # —— 高价值福袋 / 预约配置加载 —— + try: + self.high_value_fudai_enabled = bool( + config.get("high_value_fudai_enabled", self.high_value_fudai_enabled) + ) + except Exception: + pass + + self.high_value_fudai_threshold_yuan = _float( + "high_value_fudai_threshold_yuan", + self.high_value_fudai_threshold_yuan, + ) + self.high_value_fudai_join_ahead_seconds = _int( + "high_value_fudai_join_ahead_seconds", + self.high_value_fudai_join_ahead_seconds, + ) + self.high_value_fudai_max_swipe_back = _int( + "high_value_fudai_max_swipe_back", + self.high_value_fudai_max_swipe_back, + ) + self.high_value_fudai_max_reservations = _int( + "high_value_fudai_max_reservations", + self.high_value_fudai_max_reservations, + ) + # 合理范围约束 + if self.high_value_fudai_max_reservations < 1: + self.high_value_fudai_max_reservations = 1 + if self.high_value_fudai_max_reservations > 50: + self.high_value_fudai_max_reservations = 50 + + try: + self.high_value_fudai_after_action = str( + config.get("high_value_fudai_after_action", self.high_value_fudai_after_action) + or self.high_value_fudai_after_action + ).strip().lower() + except Exception: + pass + if self.high_value_fudai_after_action not in ("stay", "continue"): + self.high_value_fudai_after_action = "continue" + + self.high_value_fudai_after_stay_seconds = _int( + "high_value_fudai_after_stay_seconds", + self.high_value_fudai_after_stay_seconds, + ) + if self.high_value_fudai_after_stay_seconds < 0: + self.high_value_fudai_after_stay_seconds = 0 + if self.high_value_fudai_after_stay_seconds > 3600: + self.high_value_fudai_after_stay_seconds = 3600 + + # 高价值直播间回访相关(当前本地版暂不强制使用,仅保留配置) + try: + self.high_value_room_revisit_enabled = bool( + config.get("high_value_room_revisit_enabled", self.high_value_room_revisit_enabled) + ) + except Exception: + pass + try: + self.high_value_room_revisit_only_current_run = bool( + config.get( + "high_value_room_revisit_only_current_run", + self.high_value_room_revisit_only_current_run, + ) + ) + except Exception: + pass + + # 预约回退校验配置 + try: + self.reservation_back_verify_enabled = bool( + config.get("reservation_back_verify_enabled", self.reservation_back_verify_enabled) + ) + except Exception: + self.reservation_back_verify_enabled = True + + # 滑动次数重置配置 + try: + self.reset_after_swipes_enabled = bool(config.get("reset_after_swipes_enabled", False)) + except Exception: + self.reset_after_swipes_enabled = False + try: + raw_reset_swipes = config.get("reset_after_swipes", 10) + self.reset_after_swipes = int(10 if raw_reset_swipes is None else raw_reset_swipes) + except Exception: + self.reset_after_swipes = 10 + if self.reset_after_swipes < 1: + self.reset_after_swipes = 1 + + # 意外返回桌面自救配置 + try: + self.desktop_icon_x = int(config.get("desktop_icon_x", self.desktop_icon_x)) + self.desktop_icon_y = int(config.get("desktop_icon_y", self.desktop_icon_y)) + self.yanghao_fallback_live_x = int(config.get("yanghao_fallback_live_x", self.yanghao_fallback_live_x)) + self.yanghao_fallback_live_y = int(config.get("yanghao_fallback_live_y", self.yanghao_fallback_live_y)) + self.yanghao_fallback_enter_live_x = int(config.get("yanghao_fallback_enter_live_x", self.yanghao_fallback_enter_live_x)) + self.yanghao_fallback_enter_live_y = int(config.get("yanghao_fallback_enter_live_y", self.yanghao_fallback_enter_live_y)) + except Exception: + pass + + # 预约回退与抢占策略 + try: + self.reservation_back_verify_enabled = bool( + config.get("reservation_back_verify_enabled", self.reservation_back_verify_enabled) + ) + except Exception: + self.reservation_back_verify_enabled = False + + self.reservation_back_swipe_delay = _float( + "reservation_back_swipe_delay", + self.reservation_back_swipe_delay, + ) + if self.reservation_back_swipe_delay < 0.0: + self.reservation_back_swipe_delay = 0.0 + + self.reservation_preempt_min_value_yuan = _float( + "reservation_preempt_min_value", + self.reservation_preempt_min_value_yuan, + ) + if self.reservation_preempt_min_value_yuan < 0.0: + self.reservation_preempt_min_value_yuan = 0.0 + + self.poll_before_open_seconds = _int( + "poll_before_open_seconds", + self.poll_before_open_seconds, + ) + if self.poll_before_open_seconds < 0: + self.poll_before_open_seconds = 0 + # ========== 兼容旧入口:主循环 ========== def fudai_choujiang(self, device_id: str = "", y_pianyi: int = 0, needswitch: bool = False, wait_minutes: int = 15) -> None: """兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。""" @@ -545,9 +739,164 @@ class fudai_analyse: """购物红包中央弹窗。""" return douyin_popups.check_shopping_redpacket_popup(self) - # ========== 主循环骨架(基础抢福袋,暂不启用预约) ========== + # ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ========== def run_once_basic(self) -> None: - """单轮基础抢福袋流程(不包含预约队列、高价值房间等高阶功能)。""" + """单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。""" + # 0. 若启用高价值预约:先处理“是否需要回退到预约直播间” + try: + if getattr(self, "high_value_fudai_enabled", False) and self.reservations: + def _swipe_down_once() -> None: + self.swipe_down_back_from_live() + + def _sort_reservations() -> None: + douyin_reservation_logic._sort_reservations_inplace(self.reservations) # type: ignore[attr-defined] + + def _write_state() -> None: + # 将预约队列写入状态文件,供外部查看(格式与 douyin_fudai_core.py 一致) + try: + import json + from datetime import datetime + os.makedirs(os.path.dirname(self._reservations_state_path), exist_ok=True) + + # 格式化预约队列数据(与 douyin_reservation.py 格式一致) + items = [] + for r in self.reservations or []: + try: + ft = float(r.get("future_ts") or 0) + except Exception: + ft = 0.0 + try: + ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft else "" + except Exception: + ft_str = str(r.get("future_str", "")) + + items.append({ + "prize_value_yuan": float(r.get("prize_value_yuan") or 0), + "content": str(r.get("content") or ""), + "future_ts": ft, + "future_str": ft_str, + "pos_seen": int(r.get("pos_seen") or 0), + "room_title": str(r.get("room_title", "") or ""), + "room_title_raw": str(r.get("room_title_raw", "") or ""), + "created_ts": float(r.get("created_ts") or 0), + }) + + # 获取当前直播间标题(用于状态文件) + current_title = str(getattr(self, "current_room_title", "") or "") + current_title_raw = str(getattr(self, "current_room_title_raw", "") or "") + + # 写入完整的状态数据 + data = { + "updated_ts": time.time(), + "reason": "process_reservation", + "room_pos": int(getattr(self, "room_pos", 0) or 0), + "current_room_title": current_title, + "current_room_title_raw": current_title_raw, + "reservations": items, + } + + with open(self._reservations_state_path, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + except Exception as e: + try: + self._log_kv( + "预约", + "写入预约队列状态文件失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + + focus_ref = [float(self.reservation_focus_until_ts or 0.0)] + after_action_ref = [bool(self.reservation_after_action_pending or False)] + + def _seek_reservation_room(item: dict) -> bool: + try: + return bool(self._seek_reservation_room(item)) + except Exception: + return False + + # 检查队列是否已满且需要等待 + max_reservations = int(getattr(self, "high_value_fudai_max_reservations", 3) or 3) + if len(self.reservations) >= max_reservations and not self.queue_full_waiting_at_earliest: + # 队列已满,回退到最早开奖的预约直播间等待 + waiting = douyin_reservation_logic.handle_queue_full_wait_at_earliest( + analyser=self, + reservations=self.reservations, + room_pos=int(getattr(self, "room_pos", 0) or 0), + reservation_focus_until_ts_ref=focus_ref, + reservation_back_swipe_delay_s=float(self.reservation_back_swipe_delay or 0.6), + swipe_down_back_callback=_swipe_down_once, + seek_reservation_room_callback=_seek_reservation_room, + sort_reservations_callback=_sort_reservations, + write_state_callback=_write_state, + ) + if waiting: + self.queue_full_waiting_at_earliest = True + if focus_ref: + self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) + # 已回退到最早开奖的预约直播间,本轮结束 + return + + # 检查是否所有预约已完成,需要重置到第一个直播间 + if self.queue_full_waiting_at_earliest and not self.reservations: + try: + self._log_kv( + "预约", + "[预约] 所有预约已完成,重置到第一个直播间", + ) + except Exception: + pass + self.queue_full_waiting_at_earliest = False + self.reservation_focus_until_ts = 0.0 + # 回退到第一个直播间:需要回退 room_pos 次 + try: + current_pos = int(getattr(self, "room_pos", 0) or 0) + back_times = abs(current_pos) + if back_times > 0: + for i in range(back_times): + _swipe_down_once() + self.operation.delay(0.6) + self.room_pos = 0 + if hasattr(self, "_swipe_times"): + self._swipe_times = 0 + try: + self._log_kv( + "预约", + "[预约] 已回退到第一个直播间", + back_times=back_times, + ) + except Exception: + pass + except Exception: + pass + return + + preempted = douyin_reservation_logic.process_reservation_attend_window( + analyser=self, + reservations=self.reservations, + room_pos=int(getattr(self, "room_pos", 0) or 0), + reservation_focus_until_ts_ref=focus_ref, + reservation_after_action_pending_ref=after_action_ref, + reservation_back_swipe_delay_s=float(self.reservation_back_swipe_delay or 0.6), + swipe_down_back_callback=_swipe_down_once, + seek_reservation_room_callback=_seek_reservation_room, + sort_reservations_callback=_sort_reservations, + write_state_callback=_write_state, + ) + # 同步回写 ref 值 + if focus_ref: + self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) + if after_action_ref: + self.reservation_after_action_pending = bool(after_action_ref[0]) + + if preempted: + # 已触发预约回退,本轮直接结束,等待下一轮在目标直播间执行详情逻辑 + return + except Exception: + pass + # 1. 截图 + 阶段诊断 ok = self.operation.get_screenshot(self.device_id) if not ok: @@ -560,6 +909,57 @@ class fudai_analyse: self._last_diag_ts = time.time() self._log_kv("截图", "截图+阶段诊断", stage=stage, seen=seen) + # 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复 + try: + top_pkg = "" + try: + top_pkg = (self.operation.get_top_package(self.device_id) or "") + except Exception: + top_pkg = "" + if top_pkg and ("aweme" not in top_pkg and "douyin" not in top_pkg and "com.ss.android.ugc" not in top_pkg): + try: + self._log_kv( + "自救", + "发现前台包不在抖音,尝试恢复进入直播间", + top_pkg=top_pkg, + ) + # 直接点击桌面图标的预设坐标 + try: + self.click(int(self.desktop_icon_x), int(self.desktop_icon_y)) + except Exception: + # 退化为默认硬编码位置 + self.click(153, 260) + self.operation.delay(2) + + # 点击直播与进入直播间的备用坐标 + try: + lx = int(self.yanghao_fallback_live_x) + ly = int(self.yanghao_fallback_live_y) + self._log_kv("自救", "点击直播按钮", x=lx, y=ly) + self.click(lx, ly) + self.operation.delay(1.5) + except Exception: + pass + try: + ex = int(self.yanghao_fallback_enter_live_x) + ey = int(self.yanghao_fallback_enter_live_y) + self._log_kv("自救", "点击进入直播间", x=ex, y=ey, 次数=2) + self.click(ex, ey) + self.operation.delay(0.6) + self.click(ex, ey) + self.operation.delay(2.0) + except Exception: + pass + # 重新开始下一轮判断 + return + except Exception as e: + try: + self._log_kv("自救", "恢复失败", error=str(e)) + except Exception: + pass + except Exception: + pass + # 2. 诊断后分支(弹窗检测已合并到阶段诊断中) # 处理弹窗阶段 if stage == "COUPON_POPUP": @@ -634,6 +1034,191 @@ class fudai_analyse: def swipe_up_to_next_live(self) -> None: """上滑切换直播间(简单版封装)。""" douyin_swipe_ops.swipe_up_switch_live(self) + # 记录直播间位置:上滑 +1 + try: + self.room_pos += 1 + except Exception: + self.room_pos = 0 + + # 记录滑动次数(用于滑动次数重置功能) + try: + if not hasattr(self, "_swipe_times"): + self._swipe_times = 0 + self._swipe_times += 1 + except Exception: + pass + + # 检查是否需要重置(滑动次数达到阈值) + try: + self._maybe_reset_after_swipes() + except Exception: + pass + + def swipe_down_back_from_live(self) -> None: + """下滑回退到上一个直播间(供预约/无福袋逻辑使用)。""" + try: + douyin_swipe_ops.swipe_down_back_live(self) + except Exception: + # 若子模块未实现,则退化为点击返回键 + try: + self.operation.click_back(self.device_id) + except Exception: + pass + # 记录直播间位置:下滑/回退 -1 + try: + self.room_pos -= 1 + except Exception: + self.room_pos = 0 + + def _maybe_reset_after_swipes(self) -> int: + """达到切换阈值后,在当前直播间页面回退到第一个直播间。 + + 返回: + 重置后的滑动次数(通常为0) + """ + try: + needswitch = bool(getattr(self, "needswitch", True)) + except Exception: + needswitch = True + if not needswitch: + return getattr(self, "_swipe_times", 0) + + if not bool(getattr(self, "reset_after_swipes_enabled", False)): + return getattr(self, "_swipe_times", 0) + + try: + swipe_times = int(getattr(self, "_swipe_times", 0) or 0) + except Exception: + swipe_times = 0 + + threshold = max(1, int(self.reset_after_swipes or 0)) + if swipe_times < threshold: + return swipe_times + + try: + self._log_kv( + "流程", + "已切换直播间{}次,达到阈值{}:下滑回退到第一个直播间".format(swipe_times, threshold), + swipe_times=swipe_times, + threshold=threshold, + ) + except Exception: + pass + + # 回退次数按当前已切换次数来(更符合"回到本轮第一个直播间"的语义) + back_times = int(swipe_times) + if back_times <= 0: + return 0 + + # 下滑回退:与上划切换相反方向 + try: + rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400) + except Exception: + rx, ry = 1080, 2400 + + for i in range(back_times): + try: + # 下滑:从下往上滑动 + start_x = 760 * rx // 1080 + start_y = 1600 * ry // 2400 + end_x = 760 * rx // 1080 + end_y = 800 * ry // 2400 + self.operation.swipe(self.device_id, start_x, start_y, end_x, end_y, 200) + try: + self._log_kv("流程", "回退直播间 {}/{}".format(i + 1, back_times)) + except Exception: + pass + self.operation.delay(2) + except Exception: + pass + + # 回到第一个后,计数归零 + self.operation.delay(3) + try: + self._swipe_times = 0 + self.room_pos = 0 + except Exception: + pass + return 0 + + def _seek_reservation_room(self, item: dict[str, Any]) -> bool: + """根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。 + + 说明: + - 使用 high_value_fudai_max_swipe_back 约束最大回退次数; + - 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。 + """ + try: + target_pos = int(item.get("pos_seen") or 0) + except Exception: + target_pos = 0 + try: + cur_pos = int(getattr(self, "room_pos", 0) or 0) + except Exception: + cur_pos = 0 + + back_times = max(0, cur_pos - target_pos) + try: + max_back = int(getattr(self, "high_value_fudai_max_swipe_back", 60) or 60) + except Exception: + max_back = 60 + if max_back > 0 and back_times > max_back: + back_times = max_back + + try: + self._log_kv( + "预约", + "[预约] _seek_reservation_room 计算回退次数", + current_room_pos=cur_pos, + target_pos=target_pos, + back_times=back_times, + ) + except Exception: + pass + + if back_times <= 0: + # 认为当前已在目标附近,但仍需校验 + pass + else: + delay_s = float(getattr(self, "reservation_back_swipe_delay", 0.6) or 0.6) + for _ in range(back_times): + self.swipe_down_back_from_live() + try: + self.operation.delay(delay_s) + except Exception: + time.sleep(delay_s) + + # 如果启用了回退校验,进行详细校验 + try: + if bool(getattr(self, "reservation_back_verify_enabled", True)): + import douyin_reservation_verify + is_valid, detail_tuple = douyin_reservation_verify.validate_back_to_reservation( + self, item, quick=False + ) + if not is_valid: + try: + self._log_kv("预约", "[预约] _seek_reservation_room 回退校验失败") + except Exception: + pass + return False + # 校验通过,保存详情供后续使用 + if detail_tuple: + try: + self._forced_reservation_detail = detail_tuple # type: ignore[attr-defined] + self._forced_reservation_fudai_x = None # type: ignore[attr-defined] + except Exception: + pass + except Exception as e: + try: + self._log_kv("预约", "[预约] _seek_reservation_room 回退校验异常", error=str(e)) + except Exception: + pass + # 校验异常时,如果配置要求必须校验,则返回失败 + if bool(getattr(self, "reservation_back_verify_enabled", True)): + return False + + return True # ========== 福袋相关 ========== def _handle_in_fudai_detail(self) -> None: @@ -646,6 +1231,61 @@ class fudai_analyse: close_detail_callback=douyin_fudai_detail.close_fudai_detail, ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open, ) + + # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 + try: + last_status = getattr(self, "_last_fudai_detail_status", "") + if last_status == "coupon_popup": + try: + self._log_kv("流程", "_handle_in_fudai_detail:检测到优惠券弹窗,已关闭,跳过后续处理") + except Exception: + pass + return + elif last_status == "validation_failed": + try: + self._log_kv("流程", "_handle_in_fudai_detail:福袋详情数据验证失败,识别出错,跳过后续处理") + except Exception: + pass + return + except Exception: + pass + + # 额外验证:使用验证函数检查数据合理性 + try: + # 使用已导入的模块,避免重复导入导致作用域问题 + is_valid, reason = douyin_fudai_detail.validate_fudai_detail(detail, self) + if not is_valid: + try: + self._log_kv( + "流程", + "_handle_in_fudai_detail:福袋详情数据验证失败,识别出错", + validation_reason=reason, + ) + except Exception: + pass + return + except Exception: + pass + + # 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误 + try: + if isinstance(detail, tuple) and len(detail) >= 5: + content = str(detail[0] or "") + prize_value_yuan = float(detail[4] or 0.0) + if not content and prize_value_yuan == 0.0: + try: + self._log_kv( + "流程", + "_handle_in_fudai_detail:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理", + content=content, + prize_value_yuan=prize_value_yuan, + ) + except Exception: + pass + return + except Exception: + pass + douyin_fudai_core.basic_join_decision(self, detail) def _handle_live_room_has_or_not_fudai(self) -> None: diff --git a/douyin_fudai_core.py b/douyin_fudai_core.py index 8d6d3a8..fdefb0b 100644 --- a/douyin_fudai_core.py +++ b/douyin_fudai_core.py @@ -5,6 +5,7 @@ import time from typing import Tuple, Any from douyin_utils import normalize_countdown_text, extract_prize_value_yuan +import douyin_reservation_logic def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: @@ -181,14 +182,14 @@ def check_contain(analyser, contains: str = "") -> bool: analyser._log_kv("筛选", "福袋内容未命中黑名单,保留", contains=contains[:80] if contains else "") except Exception: pass - return False + return False except Exception: # 容错:异常时不过滤 try: analyser._log_kv("筛选", "check_contain 异常,默认保留", contains=contains[:80] if contains else "") except Exception: pass - return False + return False def attend_choujiang(analyser) -> bool: @@ -355,8 +356,8 @@ def check_lucky_draw_result(analyser): if need_screenshot: analyser._shot_and_diagnose("开奖结果", "识别是否中奖/未中奖", analyser.device_id) - # 优化:稍微扩大区域(655->650, 755->765),确保包含完整的开奖结果文字 - analyser.cut_pic(350, 650, 750, 765, "", "抽奖结果") # 没有抽中福袋位置 + # 优化:扩大区域(300-800, 600-800),确保包含完整的开奖结果文字"没有抽中福袋" + analyser.cut_pic(300, 600, 800, 800, "", "抽奖结果") # 没有抽中福袋位置 # 诊断开始时间 t0 = time.time() @@ -401,13 +402,13 @@ def check_lucky_draw_result(analyser): no_award_confirm = cached_result2 else: t1 = time.time() - analyser.cut_pic(340, 1195, 740, 1355, "", "无奖励确认") + 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(340, 1200, 730, 1350, "", "无奖励确认") + 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 @@ -626,8 +627,39 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str try: if isinstance(cd_end, (int, float)) and cd_end > now: remain_seconds = float(cd_end - now) - except Exception: + try: + analyser._log_kv( + "筛选", + "倒计时计算成功", + cd_end=cd_end, + now=now, + 剩余秒数=remain_seconds, + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "筛选", + "倒计时计算失败或已过期", + cd_end=cd_end, + now=now, + cd_end类型=type(cd_end).__name__, + cd_end大于now=bool(isinstance(cd_end, (int, float)) and cd_end > now) if isinstance(cd_end, (int, float)) else False, + ) + except Exception: + pass + except Exception as e: remain_seconds = None + try: + analyser._log_kv( + "筛选", + "倒计时计算异常", + 异常=str(e), + 异常类型=type(e).__name__, + ) + except Exception: + pass # 读取配置阈值 try: @@ -647,28 +679,210 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str except Exception: skip_if_lt = 0 + # 记录所有配置值和实际值,便于调试 + try: + analyser._log_kv( + "筛选", + "should_skip_fudai_by_config 开始检查", + 配置_最小价值=min_value, + 配置_最小参与人数=min_participants, + 配置_最大参与人数=max_participants, + 配置_倒计时小于秒数=skip_if_lt, + 实际_价值=prize_value_yuan, + 实际_参与人数=participants, + 实际_份数=copies, + 实际_剩余秒数=int(remain_seconds) if remain_seconds is not None else None, + 实际_内容=content[:60] if content else "", + ) + except Exception: + pass + # 1) 价值过滤 - if min_value > 0 and prize_value_yuan > 0 and prize_value_yuan < min_value: - return True, f"value_lt_{min_value}" + if min_value > 0: + if prize_value_yuan > 0: + if prize_value_yuan < min_value: + try: + analyser._log_kv( + "筛选", + "价值过滤:丢弃", + 原因=f"value_lt_{min_value}", + 实际价值=prize_value_yuan, + 配置最小价值=min_value, + ) + except Exception: + pass + return True, f"value_lt_{min_value}" + else: + try: + analyser._log_kv( + "筛选", + "价值过滤:通过", + 实际价值=prize_value_yuan, + 配置最小价值=min_value, + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "筛选", + "价值过滤:跳过(未识别到价值)", + 实际价值=prize_value_yuan, + ) + except Exception: + pass # 2) 参与人数过滤 - if min_participants > 0 and participants and participants < min_participants: - return True, f"participants_lt_{min_participants}" - if max_participants > 0 and participants and participants > max_participants: - return True, f"participants_gt_{max_participants}" + if min_participants > 0: + if participants > 0: + if participants < min_participants: + try: + analyser._log_kv( + "筛选", + "参与人数过滤:丢弃(小于最小值)", + 原因=f"participants_lt_{min_participants}", + 实际参与人数=participants, + 配置最小参与人数=min_participants, + ) + except Exception: + pass + return True, f"participants_lt_{min_participants}" + else: + try: + analyser._log_kv( + "筛选", + "参与人数过滤:通过(最小值检查)", + 实际参与人数=participants, + 配置最小参与人数=min_participants, + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "筛选", + "参与人数过滤:跳过(未识别到参与人数)", + 实际参与人数=participants, + ) + except Exception: + pass + + if max_participants > 0: + if participants > 0: + if participants > max_participants: + try: + analyser._log_kv( + "筛选", + "参与人数过滤:丢弃(大于最大值)", + 原因=f"participants_gt_{max_participants}", + 实际参与人数=participants, + 配置最大参与人数=max_participants, + ) + except Exception: + pass + return True, f"participants_gt_{max_participants}" + else: + try: + analyser._log_kv( + "筛选", + "参与人数过滤:通过(最大值检查)", + 实际参与人数=participants, + 配置最大参与人数=max_participants, + ) + except Exception: + pass - # 3) 倒计时过滤 - if skip_if_lt > 0 and remain_seconds is not None and remain_seconds < skip_if_lt: - return True, f"countdown_lt_{skip_if_lt}" + # 3) 倒计时过滤(如果倒计时小于阈值,就不参与;但如果价值达到高价值阈值,可以预约) + # 注意:这个过滤在 basic_join_decision 中会被特殊处理,如果价值达到高价值阈值,即使倒计时小于阈值也会记录预约 + if skip_if_lt > 0: + try: + analyser._log_kv( + "筛选", + "倒计时过滤:开始检查", + 配置阈值秒数=skip_if_lt, + 实际剩余秒数=int(remain_seconds) if remain_seconds is not None else None, + 是否有倒计时数据=remain_seconds is not None, + 说明="如果剩余秒数小于阈值,则不参与(但高价值福袋可预约)", + ) + except Exception: + pass + + if remain_seconds is not None: + # 如果剩余秒数 < 阈值,就丢弃(不参与) + if remain_seconds < skip_if_lt: + try: + analyser._log_kv( + "筛选", + "倒计时过滤:丢弃(剩余秒数小于阈值,不参与)", + 原因=f"countdown_lt_{skip_if_lt}", + 实际剩余秒数=int(remain_seconds), + 配置阈值秒数=skip_if_lt, + 判断条件=f"{remain_seconds} < {skip_if_lt} = True", + 说明="如果价值达到高价值阈值,basic_join_decision 会记录预约", + ) + except Exception: + pass + return True, f"countdown_lt_{skip_if_lt}" + else: + try: + analyser._log_kv( + "筛选", + "倒计时过滤:通过(剩余秒数大于等于阈值,可以参与)", + 实际剩余秒数=int(remain_seconds), + 配置阈值秒数=skip_if_lt, + 判断条件=f"{remain_seconds} < {skip_if_lt} = False", + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "筛选", + "倒计时过滤:跳过(未识别到倒计时或倒计时已过期)", + 剩余秒数=remain_seconds, + cd_start=cd_start, + cd_end=cd_end, + now=now, + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "筛选", + "倒计时过滤:跳过(配置阈值为0,不启用倒计时过滤)", + 配置阈值秒数=skip_if_lt, + ) + except Exception: + pass # 4) 内容关键词过滤(复用 check_contain 逻辑) - if check_contain(analyser, content): + content_check_result = check_contain(analyser, content) + if content_check_result: + try: + analyser._log_kv( + "筛选", + "内容关键词过滤:丢弃", + 原因="content_not_wanted", + 内容=content[:60] if content else "", + ) + except Exception: + pass return True, "content_not_wanted" + else: + try: + analyser._log_kv( + "筛选", + "内容关键词过滤:通过", + 内容=content[:60] if content else "", + ) + except Exception: + pass try: analyser._log_kv( "筛选", - "should_skip_fudai_by_config 通过", + "should_skip_fudai_by_config 通过(所有检查项均通过)", content=content[:60] if content else "", participants=participants, copies=copies, @@ -681,13 +895,129 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str def basic_join_decision(analyser: Any, detail: Tuple) -> bool: - """基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖。 + """基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。 返回: True 表示已经参与或已处理完成; False 表示未参与(例如被配置筛掉或参与失败)。 """ + # 解析 detail 字段:先提取价值信息,用于判断是否达到高价值阈值 + content = "" + prize_value_yuan = 0.0 + countdown_tuple = None + try: + if isinstance(detail, tuple) and len(detail) >= 6: + content = str(detail[0] or "") + prize_value_yuan = float(detail[4] or 0.0) + countdown_tuple = detail[5] + except Exception: + pass + + # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 + try: + last_status = getattr(analyser, "_last_fudai_detail_status", "") + if last_status == "coupon_popup": + try: + analyser._log_kv( + "参与", + "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", + ) + except Exception: + pass + return False + elif last_status == "validation_failed": + try: + analyser._log_kv( + "参与", + "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", + ) + except Exception: + pass + return False + except Exception: + pass + + # 额外验证:使用验证函数检查数据合理性 + try: + # 在函数开头导入,避免作用域问题 + import douyin_fudai_detail as dfd_module + is_valid, reason = dfd_module.validate_fudai_detail(detail, analyser) + if not is_valid: + try: + analyser._log_kv( + "参与", + "basic_join_decision:福袋详情数据验证失败,识别出错", + validation_reason=reason, + content=content[:50] if content else "", + prize_value_yuan=prize_value_yuan, + ) + except Exception: + pass + return False + except Exception: + pass + + # 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误 + if not content and prize_value_yuan == 0.0: + try: + analyser._log_kv( + "参与", + "basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理", + content=content, + prize_value_yuan=prize_value_yuan, + ) + except Exception: + pass + return False + + # 检查是否启用高价值预约,以及价值是否达到阈值 + try: + high_value_enabled = bool(getattr(analyser, "high_value_fudai_enabled", False)) + except Exception: + high_value_enabled = False + + try: + high_value_threshold = float( + getattr(analyser, "high_value_fudai_threshold_yuan", 500.0) or 500.0 + ) + except Exception: + high_value_threshold = 500.0 + + # 计算 future_timestamp(预计开奖时间戳) + future_ts = 0.0 + if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: + try: + future_ts = float(countdown_tuple[1] or 0.0) + except Exception: + future_ts = 0.0 + + # 检查价值是否达到高价值阈值 + is_high_value = ( + high_value_enabled + and prize_value_yuan > 0 + and prize_value_yuan >= high_value_threshold + and future_ts > 0.0 + ) + + # 执行筛选检查 skip, reason = should_skip_fudai_by_config(analyser, detail) + + # 特殊处理:如果被倒计时过滤筛掉(倒计时小于阈值),但价值达到高价值阈值,则记录预约而不是丢弃 + if skip and reason.startswith("countdown_lt_") and is_high_value: + try: + analyser._log_kv( + "参与", + "basic_join_decision:倒计时小于阈值,但价值达到高价值阈值,记录预约", + reason=reason, + value_yuan=prize_value_yuan, + threshold=high_value_threshold, + ) + except Exception: + pass + # 不关闭详情,继续走预约逻辑 + skip = False + reason = "high_value_reservation" + if skip: try: analyser._log_kv( @@ -710,14 +1040,18 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: pass - # 如果是“内容不想要”的原因,且允许切换直播间,则立即切换到下一个直播间 + # 如果允许切换直播间,则针对部分丢弃原因直接切房(黑名单/价值不达标/倒计时小于阈值) try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True - if reason == "content_not_wanted" and needswitch: + if needswitch and ( + reason == "content_not_wanted" + or reason.startswith("value_lt_") + or reason.startswith("countdown_lt_") + ): try: - analyser._log_kv("参与", "basic_join_decision:内容不想要且允许切房,立即切换直播间") + analyser._log_kv("参与", "basic_join_decision:丢弃后切换直播间", reason=reason) except Exception: pass try: @@ -742,7 +1076,277 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: return False - # 未被筛掉:尝试参与抽奖 + # 未被筛掉:根据配置决定“直接参与”或“记录为高价值预约” + # 注意:content, prize_value_yuan, countdown_tuple, future_ts, high_value_enabled, high_value_threshold, is_high_value 已在前面提取 + # 仅当启用高价值预约、识别到价值且未来时间合理时,才考虑记入预约队列 + if is_high_value: + # 价值达到高价值阈值:记录预约而不是立即参与 + try: + # 预约抢占最小价值(若配置了,则低于该值的预约不会抢占当前任务) + try: + preempt_min = float( + getattr(analyser, "reservation_preempt_min_value_yuan", 0.0) or 0.0 + ) + except Exception: + preempt_min = 0.0 + + # 初始化预约队列容器 + reservations = getattr(analyser, "reservations", None) + if reservations is None: + reservations = [] + try: + analyser.reservations = reservations # type: ignore[attr-defined] + except Exception: + pass + + # room_pos:当前直播间位置计数 + try: + room_pos = int(getattr(analyser, "room_pos", 0) or 0) + except Exception: + room_pos = 0 + + # 获取当前直播间标题(如果可用) + room_title = "" + room_title_raw = "" + try: + # 尝试从 analyser 获取当前直播间标题 + room_title = str(getattr(analyser, "current_room_title", "") or "") + room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "") + # 如果为空,尝试调用读取标题的函数 + if not room_title or not room_title_raw or room_title_raw == "shim_live_room_title_raw": + try: + # 在函数开头导入,避免作用域问题 + import douyin_fudai_detail as dfd_module + y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) + room_title, room_title_raw = dfd_module.read_live_room_title_core( + analyser, y_pianyi_val + ) + # 更新 analyser 的属性,以便后续使用 + try: + analyser.current_room_title = room_title + analyser.current_room_title_raw = room_title_raw + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "预约", + "读取直播间标题失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + except Exception: + pass + + # 记录高价值预约(仅负责入队和写状态,不立即改变当前直播间) + rl = douyin_reservation_logic + + # 定义写入状态文件的回调函数(格式与 douyin_reservation.py 中的 write_reservations_state 一致) + def _write_reservation_state() -> None: + try: + import os + import json + from datetime import datetime + state_path = getattr(analyser, "_reservations_state_path", None) + if not state_path: + # 使用与 douyin_fudai.py 相同的路径逻辑 + state_path = os.path.join( + os.path.dirname(__file__), "state", "reservations.json" + ) + # 确保目录存在 + os.makedirs(os.path.dirname(state_path), exist_ok=True) + + # 格式化预约队列数据(与 douyin_reservation.py 格式一致) + items = [] + for r in reservations or []: + try: + ft = float(r.get("future_ts") or 0) + except Exception: + ft = 0.0 + try: + ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft else "" + except Exception: + ft_str = str(r.get("future_str", "")) + + items.append({ + "prize_value_yuan": float(r.get("prize_value_yuan") or 0), + "content": str(r.get("content") or ""), + "future_ts": ft, + "future_str": ft_str, + "pos_seen": int(r.get("pos_seen") or 0), + "room_title": str(r.get("room_title") or ""), + "room_title_raw": str(r.get("room_title_raw") or ""), + "created_ts": float(r.get("created_ts") or 0), + }) + + # 获取当前直播间标题(用于状态文件) + current_title = str(getattr(analyser, "current_room_title", "") or room_title or "") + current_title_raw = str(getattr(analyser, "current_room_title_raw", "") or room_title_raw or "") + + # 写入完整的状态数据 + data = { + "updated_ts": time.time(), + "reason": "record_reservation", + "room_pos": int(room_pos), + "current_room_title": current_title, + "current_room_title_raw": current_title_raw, + "reservations": items, + } + + with open(state_path, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + try: + analyser._log_kv( + "预约", + "已写入预约队列状态文件", + path=state_path, + queue_len=len(reservations), + ) + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "预约", + "写入预约队列状态文件失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + + # 记录高价值直播间(在记录预约之前) + try: + import douyin_high_value_room + douyin_high_value_room.touch_high_value_room( + analyser=analyser, + title_norm=room_title, + title_raw=room_title_raw, + prize_value_yuan=prize_value_yuan, + reason="reservation", + increment=True, + content=content, + pos_seen=room_pos, + ) + except Exception: + pass + + # 记录预约,并检查队列是否已满 + queue_full_flag = [False] + def _add_reservation_with_flag(q, item): + queue_full_flag[0] = rl.add_reservation_core_logic( # type: ignore[attr-defined] + q, + item, + max_reservations=int( + getattr(analyser, "high_value_fudai_max_reservations", 3) or 3 + ), + analyser=analyser, + write_state_callback=_write_reservation_state, + ) + + rl.record_high_value_reservation( # type: ignore[attr-defined] + analyser=analyser, + fudai_content_text=content, + prize_value_yuan=prize_value_yuan, + lastsecond=0, + future_timestamp=future_ts, + x=0, + needswitch=True, + wait_minutes=0, + post_switch_delay_s=0.0, + room_pos=room_pos, + reservations=reservations, + reservation_focus_until_ts_ref=[float(getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0)], + close_detail_callback=lambda: None, + swipe_up_switch_callback=lambda: None, + swipe_down_back_callback=lambda: None, + add_reservation_callback=_add_reservation_with_flag, + sort_reservations_callback=lambda: rl._sort_reservations_inplace( # type: ignore[attr-defined] + reservations + ), + write_state_callback=_write_reservation_state, + room_title=room_title, + room_title_raw=room_title_raw, + ) + + # 如果队列已满,设置标志以便主循环处理 + if queue_full_flag[0]: + try: + analyser.queue_full_waiting_at_earliest = False # 重置标志,让主循环处理 + except Exception: + pass + + try: + analyser._log_kv( + "预约", + "basic_join_decision:命中高价值阈值,已记录为预约,不立即参与", + value_yuan=prize_value_yuan, + threshold=high_value_threshold, + future_ts=int(future_ts), + room_pos=room_pos, + queue_len=len(reservations), + preempt_min_value=preempt_min, + ) + except Exception: + pass + + # 关闭当前详情,避免长时间停留 + try: + analyser.click(500, 470) + except Exception: + try: + analyser.operation.click_back(analyser.device_id) + except Exception: + pass + try: + analyser._log_kv("参与", "basic_join_decision:已关闭详情", action="close_detail") + except Exception: + pass + + # 记录预约后,切换直播间继续找别的福袋 + try: + needswitch = bool(getattr(analyser, "needswitch", True)) + except Exception: + needswitch = True + if needswitch: + try: + analyser._log_kv("参与", "basic_join_decision:记录预约后切换直播间", reason="high_value_reservation") + except Exception: + pass + try: + # 优先使用封装好的上滑切房方法 + if hasattr(analyser, "swipe_up_to_next_live"): + analyser.swipe_up_to_next_live() + else: + # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + rx, ry = 1080, 2400 + start_x = 540 * rx // 1080 + start_y = 1700 * ry // 2400 + end_x = 540 * rx // 1080 + end_y = 700 * ry // 2400 + analyser.operation.swipe(analyser.device_id, start_x, start_y, end_x, end_y, 300) + except Exception: + # 切房失败不影响主流程,直接返回 + pass + + return True + except Exception: + # 若预约逻辑异常,退化为直接参与抽奖 + try: + analyser._log_kv( + "预约", + "basic_join_decision:记录预约时异常,退化为直接参与", + ) + except Exception: + pass + + # 默认分支:未进入预约路径或预约失败,直接参与抽奖 try: analyser._log_kv("参与", "basic_join_decision:尝试参与抽奖") except Exception: diff --git a/douyin_fudai_detail.py b/douyin_fudai_detail.py index 62c4250..4e02b64 100644 --- a/douyin_fudai_detail.py +++ b/douyin_fudai_detail.py @@ -16,6 +16,7 @@ Exports: from typing import Any, Dict, Tuple, List, Optional import os import time +import re from PIL import Image @@ -23,6 +24,135 @@ from douyin_detection import check_detail_height from douyin_fudai_core import get_fudai_contain +# ============================================================================ +# 直播间标题处理辅助函数(模块化) +# ============================================================================ + +def _room_title_has_ellipsis(s: str) -> bool: + """检查是否包含省略号。""" + if "…" in s: + return True + if re.search(r"\.{3,}", s): + return True + return False + + +def _strip_room_noise_text(s: str) -> str: + """移除直播间名 OCR 常见噪音(点赞/关注/粉丝等)。""" + try: + t = str(s or "") + except Exception: + return "" + t = t.replace("\r", "\n").replace("\t", " ") + t = re.sub(r"[\s\u3000]+", " ", t).strip() + # 计数噪音:例如 1.2万点赞 / 234点赞 / 3W点赞 + t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞)", " ", t) + t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*关注", " ", t) + t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*粉丝", " ", t) + t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*人(?:在线|在看)?", " ", t) + t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t) + t = re.sub(r"本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t) + for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "人在线", "在线"): + t = t.replace(w, " ") + t = re.sub(r"\s+", " ", t).strip() + return t + + +def _extract_room_title_candidate(raw_text: str) -> str: + """从 OCR 原文中提取更像"直播间名"的片段。""" + t = _strip_room_noise_text(raw_text) + if not t: + return "" + + segs = [x.strip() for x in re.split(r"[\n ]+", t) if x.strip()] + best = "" + best_score = -999 + for seg in segs: + if not seg: + continue + seg2 = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞|关注|粉丝)$", "", seg).strip() + if not seg2: + continue + seg = seg2 + score = len(seg) + if _room_title_has_ellipsis(seg): + score += 30 + if re.search(r"[\u4e00-\u9fffA-Za-z]", seg): + score += 5 + if score > best_score: + best_score = score + best = seg + + if best: + m = re.search(r"(.*?)(…|\.{3,})", best) + if m: + cand = (m.group(1) + m.group(2)).strip() + return cand if cand else best.strip() + return best.strip() + + m2 = re.search(r"(.*?)(…|\.{3,})", t) + if m2: + cand2 = (m2.group(1) + m2.group(2)).strip() + if cand2: + return cand2 + return t.strip() + + +def _normalize_room_title(t: str) -> str: + """规范化直播间标题。""" + s = _extract_room_title_candidate(str(t or "")) + s = s.replace("\r", " ").replace("\n", " ").strip() + s = re.sub(r"\s+", "", s) + for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"): + s = s.replace(w, "") + s = re.sub(r"\d+(?:\.\d+)?[万wW]?(?:点赞|赞|关注|粉丝)", "", s) + s = re.sub(r"\d+(?:\.\d+)?[万wW]?本场(?:点赞|点赞|点贊|点)", "", s) + s = re.sub(r"本场(?:点赞|点赞|点贊|点)", "", s) + s = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", s) + return s + + +def _ocr_try_room_title(analyser: Any, cut_name: str, change_color: int) -> Tuple[str, str]: + """尝试 OCR 识别直播间标题。""" + try: + raw0 = analyser.operation.analyse_pic_word(cut_name, change_color) + except Exception: + raw0 = "" + raw_text0 = str(raw0 or "").replace("\r", "\n").strip() + cand_raw0 = _extract_room_title_candidate(raw_text0) + title0 = _normalize_room_title(cand_raw0) + return title0, cand_raw0 + + +def _pick_best_room_title(cands: List[Tuple[str, str, str]], min_len: int = 3) -> Tuple[str, str]: + """从多个候选结果中选择最佳的一个。""" + best = ("", "") + best_score = -1 + for t_norm, t_raw, tag in cands: + if not t_raw and not t_norm: + continue + ln = len(t_norm or "") + score = ln + if ln >= min_len: + score += 10 + if ln == 1: + score -= 4 + if ln == 2: + score -= 1 + if _room_title_has_ellipsis(t_raw or ""): + score += 8 + if tag.endswith("_cc0"): + score += 2 + if tag.startswith("large"): + score += 2 + if tag.startswith("mid"): + score += 1 + if score > best_score: + best_score = score + best = (t_norm, t_raw) + return best + + def close_fudai_detail(analyser: Any) -> None: """关闭福袋详情:当前实现直接按一次返回键。""" try: @@ -73,11 +203,21 @@ def _is_wrong_coupon_popup(analyser: Any) -> bool: pix = pic.load() w, h = pic.size - # 取画面中部偏上的一块区域作为弹窗主体 - x1 = int(w * 0.15) - x2 = int(w * 0.85) - y1 = int(h * 0.25) - y2 = int(h * 0.75) + # 扫描区域:153,351 到 266,451(基于1080x2400基准坐标) + # 根据实际分辨率缩放坐标 + scale_x = w / 1080.0 + scale_y = h / 2400.0 + x1 = int(153 * scale_x) + y1 = int(351 * scale_y) + x2 = int(266 * scale_x) + y2 = int(451 * scale_y) + + # 边界检查 + x1 = max(0, min(x1, w)) + y1 = max(0, min(y1, h)) + x2 = max(0, min(x2, w)) + y2 = max(0, min(y2, h)) + if x1 >= x2 or y1 >= y2: return False @@ -164,9 +304,60 @@ def read_live_room_title_core( y_pianyi: int, min_len: int = 3, ) -> Tuple[str, str]: - """Shim: return empty title and raw text placeholder.""" - raw = "shim_live_room_title_raw" - return "", raw + """读取当前直播间顶部区域的"主播名/直播间名"(OCR,尽量轻量)。 + + 使用多个 ROI 区域和不同的 OCR 模式进行识别,选择最佳结果。 + """ + try: + analyser.operation.get_screenshot(analyser.device_id) + except Exception: + pass + + cands: List[Tuple[str, str, str]] = [] + + # mid ROI:优先使用更大区域,减少"只截到尾巴1个字" + try: + analyser.cut_pic(80, 128, 560, 230, '', 'live_room_title_mid', y_pianyi) + t, r = _ocr_try_room_title(analyser, 'live_room_title_mid', 0) + cands.append((t, r, 'mid_cc0')) + if len(t or "") < min_len: + t1, r1 = _ocr_try_room_title(analyser, 'live_room_title_mid', 1) + cands.append((t1, r1, 'mid_cc1')) + except Exception: + pass + + # large ROI:进一步扩大,兼容机型/系统字体/刘海偏移 + if not cands or max(len(x[0] or "") for x in cands) < min_len: + try: + analyser.cut_pic(40, 110, 660, 260, '', 'live_room_title_large', y_pianyi) + t2, r2 = _ocr_try_room_title(analyser, 'live_room_title_large', 0) + cands.append((t2, r2, 'large_cc0')) + if len(t2 or "") < min_len: + t3, r3 = _ocr_try_room_title(analyser, 'live_room_title_large', 1) + cands.append((t3, r3, 'large_cc1')) + except Exception: + pass + + # small ROI:最后兜底(历史区域) + if not cands or max(len(x[0] or "") for x in cands) <= 1: + try: + analyser.cut_pic(138, 144, 335, 185, '', 'live_room_title_small', y_pianyi) + t4, r4 = _ocr_try_room_title(analyser, 'live_room_title_small', 0) + cands.append((t4, r4, 'small_cc0')) + except Exception: + pass + + title, raw_text = _pick_best_room_title(cands, min_len) + + # 更新 analyser 的属性 + try: + analyser.current_room_title_raw = raw_text + if title: + analyser.current_room_title = title + except Exception: + pass + + return title, raw_text def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: @@ -310,8 +501,9 @@ def read_fudai_detail_with_retries( last_status = status if isinstance(tup, tuple) and len(tup) >= 6: last_tuple = tup[:6] - if status == "ok": - break + # 如果成功读取,或者检测到优惠券弹窗(已处理完毕),都停止重试 + if status == "ok" or status == "coupon_popup": + break if attempt < max_attempts - 1: try: analyser.operation.delay(retry_delay) @@ -326,25 +518,145 @@ def read_fudai_detail_with_retries( cd_start, cd_end = None, None if isinstance(cd, (tuple, list)) and len(cd) >= 2: cd_start, cd_end = cd[0], cd[1] + + # 如果是优惠券弹窗,记录日志并明确标记 + is_coupon_popup = (last_status == "coupon_popup") + if is_coupon_popup: + try: + analyser._log_kv( + "福袋详情", + "read_fudai_detail_with_retries 最终结果:优惠券弹窗,已关闭,跳过后续处理", + status=last_status, + fudai_x=fudai_x, + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "福袋详情", + "read_fudai_detail_with_retries 最终结果", + status=last_status, + content=content, + time_text=time_text, + participants=participants, + copies=copies, + prize_value_yuan=prize_value_yuan, + countdown_start=cd_start, + countdown_end=cd_end, + fudai_x=fudai_x, + ) + except Exception: + pass + + # 将状态信息存储在 analyser 中,供调用方检查 try: - analyser._log_kv( - "福袋详情", - "read_fudai_detail_with_retries 最终结果", - status=last_status, - content=content, - time_text=time_text, - participants=participants, - copies=copies, - prize_value_yuan=prize_value_yuan, - countdown_start=cd_start, - countdown_end=cd_end, - fudai_x=fudai_x, - ) + analyser._last_fudai_detail_status = last_status # type: ignore[attr-defined] except Exception: pass + + # 验证福袋详情数据的合理性(仅在成功读取时验证) + if last_status == "ok": + is_valid, reason = validate_fudai_detail(last_tuple, analyser) + if not is_valid: + try: + analyser._log_kv( + "福袋详情", + "read_fudai_detail_with_retries:数据验证失败,识别可能出错", + validation_reason=reason, + content=content[:50] if content else "", + prize_value_yuan=prize_value_yuan, + participants=participants, + copies=copies, + time_text=time_text[:30] if time_text else "", + ) + # 标记为识别错误 + analyser._last_fudai_detail_status = "validation_failed" # type: ignore[attr-defined] + except Exception: + pass + return last_tuple +def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, str]: + """验证福袋详情数据的合理性。 + + 返回: + (is_valid, reason) - is_valid=True 表示数据合理,False 表示识别出错 + reason 为失败原因描述 + """ + if not isinstance(detail, tuple) or len(detail) < 6: + return False, "detail_tuple_invalid" + + content = str(detail[0] or "").strip() + time_text = str(detail[1] or "").strip() + try: + participants = int(detail[2] or 0) + except Exception: + participants = 0 + try: + copies = int(detail[3] or 0) + except Exception: + copies = 0 + try: + prize_value_yuan = float(detail[4] or 0.0) + except Exception: + prize_value_yuan = 0.0 + + countdown_tuple = detail[5] + countdown_start, countdown_end = None, None + if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: + try: + countdown_start = float(countdown_tuple[0] or 0.0) + countdown_end = float(countdown_tuple[1] or 0.0) + except Exception: + pass + + # 检查1:内容不能为空(至少要有一些文字) + if not content or len(content.strip()) < 2: + return False, "content_empty_or_too_short" + + # 检查2:价值应该大于0(福袋至少应该有价值) + if prize_value_yuan <= 0: + return False, "prize_value_zero_or_negative" + + # 检查3:价值应该合理(不能太大,比如超过100万) + if prize_value_yuan > 1000000: + return False, "prize_value_too_large" + + # 检查4:倒计时应该合理 + if countdown_end is not None and countdown_start is not None: + remain_seconds = countdown_end - countdown_start + # 倒计时不能是负数 + if remain_seconds < 0: + return False, "countdown_negative" + # 倒计时不能太长(超过24小时) + if remain_seconds > 24 * 3600: + return False, "countdown_too_long" + # 倒计时不能为0(至少应该有几秒) + if remain_seconds == 0 and not time_text: + return False, "countdown_zero_and_no_time_text" + + # 检查5:参与人数应该合理(不能是负数) + if participants < 0: + return False, "participants_negative" + + # 检查6:份数应该合理(不能是负数,至少应该是1) + if copies < 0: + return False, "copies_negative" + + # 检查7:如果份数为0,但参与人数大于0,可能识别错误 + if copies == 0 and participants > 0: + return False, "copies_zero_but_participants_positive" + + # 检查8:时间文本应该存在(至少应该有倒计时信息) + if not time_text and (countdown_end is None or countdown_end <= 0): + return False, "no_time_text_and_no_countdown" + + # 所有检查通过 + return True, "ok" + + def is_abnormal_time_value(v: float) -> bool: """Shim: treat clearly invalid time values as abnormal.""" if v <= 0: diff --git a/douyin_high_value_room.py b/douyin_high_value_room.py index e69de29..c4dcf96 100644 --- a/douyin_high_value_room.py +++ b/douyin_high_value_room.py @@ -0,0 +1,247 @@ +from __future__ import annotations + +""" +高价值直播间记录模块 +==================== + +提供高价值直播间的记录和管理功能: +- 跨运行持久化(写入 high_value_rooms.json) +- 记录最大价值、最后价值、首次/最后记录时间 +- 记录次数统计 +- 支持别名和合并逻辑 +""" + +from typing import Any, Dict, Optional +import os +import time +import re +import difflib + +from path_config import get_high_value_rooms_path +import douyin_reservation + + +def _normalize_room_title(t: str) -> str: + """规范化直播间标题(与 douyin_fudai_detail 中的逻辑一致)。""" + try: + s = str(t or "").strip() + except Exception: + return "" + s = s.replace("\r", " ").replace("\n", " ").strip() + s = re.sub(r"\s+", "", s) + for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"): + s = s.replace(w, "") + s = re.sub(r"\d+(?:\.\d+)?[万wW]?(?:点赞|赞|关注|粉丝)", "", s) + s = re.sub(r"\d+(?:\.\d+)?[万wW]?本场(?:点赞|点赞|点贊|点)", "", s) + s = re.sub(r"本场(?:点赞|点赞|点贊|点)", "", s) + s = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", s) + return s + + +def _resolve_high_value_room_key( + title_norm: str, + title_raw: str, + pos_seen0: Optional[int] = None, + high_value_rooms_map: Optional[Dict[str, Dict[str, Any]]] = None, +) -> tuple[str, str, str, float]: + """将本次识别结果映射到"历史表"里的 canonical key。 + + 返回:(key, key_kind, merged_from, merged_ratio) + - merged_from:本次候选 key(若发生合并) + - merged_ratio:合并相似度 + """ + if not high_value_rooms_map: + high_value_rooms_map = {} + + key0 = title_norm + key_kind0 = "norm" + + if not key0: + # 退化为使用原始文本 + try: + s = str(title_raw or "") + s = s.replace("\r", " ").replace("\n", " ").replace("\t", " ") + s = re.sub(r"\s+", "", s).strip() + if len(s) > 64: + s = s[:64] + key0 = s or "unknown" + except Exception: + key0 = "unknown" + + # 尝试在历史表中找到相似度最高的 key + best_key = "" + best_ratio = 0.0 + best_pos_ok = False + + for k, v in high_value_rooms_map.items(): + if not k: + continue + try: + ratio = float(difflib.SequenceMatcher(None, key0, k).ratio()) + except Exception: + ratio = 0.0 + + pos_ok = False + if pos_seen0 is not None: + try: + stored_pos = int(v.get("pos_seen") or 0) + if stored_pos > 0 and abs(stored_pos - pos_seen0) <= 3: + pos_ok = True + except Exception: + pass + + if ratio > best_ratio: + best_ratio = ratio + best_key = str(k) + best_pos_ok = bool(pos_ok) + + if best_key: + if best_pos_ok and best_ratio >= 0.80: + return best_key, str((high_value_rooms_map.get(best_key) or {}).get("key_kind") or "norm"), key0, float(best_ratio) + if best_ratio >= 0.88: + return best_key, str((high_value_rooms_map.get(best_key) or {}).get("key_kind") or "norm"), key0, float(best_ratio) + + return key0, key_kind0, "", 0.0 + + +def touch_high_value_room( + analyser: Any, + title_norm: str, + title_raw: str, + prize_value_yuan: float, + reason: str = "", + increment: bool = True, + key_kind: str = "norm", + content: str = "", + pos_seen: Optional[int] = None, + alias_norm: str = "", + alias_raw: str = "", + merged_from: str = "", + merged_ratio: Optional[float] = None, +) -> None: + """记录高价值直播间信息。 + + 参数: + analyser: 分析器对象 + title_norm: 规范化后的直播间标题 + title_raw: 原始直播间标题 + prize_value_yuan: 奖品价值(元) + reason: 记录原因 + increment: 是否增加计数 + key_kind: key 类型 + content: 福袋内容 + pos_seen: 记录时的位置 + alias_norm: 别名(规范化) + alias_raw: 别名(原始) + merged_from: 合并来源 + merged_ratio: 合并相似度 + """ + try: + # 获取高价值直播间映射 + high_value_rooms_path = get_high_value_rooms_path() + high_value_rooms_map = douyin_reservation.load_high_value_rooms_map(high_value_rooms_path) + + # 解析 key + key, key_kind_resolved, merged_from_resolved, merged_ratio_resolved = _resolve_high_value_room_key( + title_norm, title_raw, pos_seen, high_value_rooms_map + ) + + if not key: + return + + # 如果发生合并,使用合并后的值 + if merged_from_resolved and merged_from_resolved != key: + merged_from = merged_from_resolved + if merged_ratio_resolved > 0: + merged_ratio = merged_ratio_resolved + if key_kind_resolved: + key_kind = key_kind_resolved + + now0 = time.time() + ex = high_value_rooms_map.get(key) or {} + + def _append_unique_list_field(field: str, val: str, cap: int = 8) -> None: + if not val: + return + try: + arr = ex.get(field) + if not isinstance(arr, list): + arr = [] + if val not in arr: + arr.insert(0, val) + if len(arr) > cap: + arr = arr[:cap] + ex[field] = arr + except Exception: + pass + + if float(ex.get("first_seen_ts") or 0.0) <= 0: + ex["first_seen_ts"] = now0 + ex["last_seen_ts"] = now0 + if "seen_count" not in ex: + ex["seen_count"] = 0 + if increment: + try: + ex["seen_count"] = int(ex.get("seen_count") or 0) + 1 + except Exception: + ex["seen_count"] = 1 + if pos_seen is not None: + try: + ex["pos_seen"] = int(pos_seen) + except Exception: + pass + ex["pos_updated_ts"] = now0 + if title_raw: + ex["room_title_raw_last"] = str(title_raw) + if alias_raw: + _append_unique_list_field("alias_raw", str(alias_raw), cap=8) + if alias_norm and alias_norm != key: + _append_unique_list_field("alias_norm", str(alias_norm), cap=8) + if merged_from and merged_from != key: + ex["merged_from_last"] = str(merged_from) + if merged_ratio is not None: + try: + ex["merged_ratio_last"] = float(merged_ratio) + except Exception: + pass + if key_kind: + ex["key_kind"] = str(key_kind) + if content: + ex["last_content"] = str(content) + try: + pv = float(prize_value_yuan or 0.0) + except Exception: + pv = 0.0 + ex["last_prize_value_yuan"] = pv + try: + ex["max_prize_value_yuan"] = max(float(ex.get("max_prize_value_yuan") or 0.0), pv) + except Exception: + ex["max_prize_value_yuan"] = pv + + high_value_rooms_map[key] = ex + + # 写入状态文件 + douyin_reservation.write_high_value_rooms_state(high_value_rooms_path, high_value_rooms_map, reason=reason) + + try: + analyser._log_kv( + "高价值直播间", + "已记录高价值直播间", + room_title=key[:30], + prize_value_yuan=pv, + max_prize_value_yuan=ex.get("max_prize_value_yuan", 0), + seen_count=ex.get("seen_count", 0), + ) + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "高价值直播间", + "记录高价值直播间失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + diff --git a/douyin_pixel.py b/douyin_pixel.py index 6a568df..b759e00 100644 --- a/douyin_pixel.py +++ b/douyin_pixel.py @@ -75,21 +75,21 @@ def detect_redpacket_popup_background(pic_rgb: Image.Image) -> bool: return False -def detect_lucky_draw_result_popup(pic_rgb: Image.Image, red_ratio_threshold: float = 0.3) -> bool: - """检测抽奖结果弹窗:检测指定区域的红色占比。 +def detect_lucky_draw_result_popup(pic_rgb: Image.Image, red_ratio_threshold: float = 0.8) -> bool: + """检测抽奖结果弹窗:检测指定区域的红色占比("我知道了"按钮区域)。 使用基准 1080x2400 坐标的检测区域: - - 左上: (175, 1258) - - 右下: (897, 1389) + - 左上: (181, 1261) + - 右下: (890, 1389) """ try: width, height = pic_rgb.size scale_x = width / 1080.0 scale_y = height / 2400.0 - x1 = int(175 * scale_x) - y1 = int(1258 * scale_y) - x2 = int(897 * scale_x) + x1 = int(181 * scale_x) + y1 = int(1261 * scale_y) + x2 = int(890 * scale_x) y2 = int(1389 * scale_y) # 边界与顺序 @@ -113,7 +113,9 @@ def detect_lucky_draw_result_popup(pic_rgb: Image.Image, red_ratio_threshold: fl try: r, g, b = pic_rgb.getpixel((x, y)) total_samples += 1 - if r > 200 and (r - g) > 50 and (r - b) > 50: + # 根据实际检测结果:R: 245-255, G: 44-255, B: 85-255 + # 红色按钮检测:R >= 245 且 R 明显大于 G 和 B + if r >= 245 and r <= 255 and (r - g) >= 50 and (r - b) >= 50: red_count += 1 except Exception: continue @@ -409,7 +411,7 @@ def read_pixel_stage_state_from_screenshot( resolution_ratio_x: int = 1080, resolution_ratio_y: int = 2400, y_pianyi: int = 0, - lucky_draw_red_ratio_threshold: float = 0.3, + lucky_draw_red_ratio_threshold: float = 0.8, ) -> dict[str, bool]: """从 screenshot.png 读取"阶段诊断"需要的多区域像素特征(不调用 OCR)。 diff --git a/douyin_reservation_logic.py b/douyin_reservation_logic.py index 521d447..6fa8741 100644 --- a/douyin_reservation_logic.py +++ b/douyin_reservation_logic.py @@ -1,107 +1,445 @@ from __future__ import annotations """ -Reservation core logic shim (WebGUI version) -=========================================== +高价值福袋预约核心逻辑(模块化版本) +================================== -Exports: -- add_reservation_core_logic -- validate_back_to_reservation -- cleanup_expired_reservations -- process_reservation_attend_window -- record_high_value_reservation +本模块从原始 `fudai1.py` 的思路抽取并简化了预约相关逻辑,保留了这些要点: +- 以 future_ts(预计开奖时间戳)为主排序键,其次 prize_value_yuan,再次 created_ts; +- 预约队列长度受 high_value_fudai_max_reservations 限制,溢出时裁剪掉优先级最低的记录; +- 进入预约窗口时可以抢占当前流程,回退到目标直播间,再由上层去识别详情并参与; +- 支持轻量的“回退校验”和状态写回(供 GUI / Web 端展示)。 + +接口签名与之前的 shim 保持兼容,便于在 `douyin_fudai.py` / `douyin_flow_control.py` +中直接调用。 """ -from typing import Any, Dict, List +from typing import Any, Dict, List, Callable, Optional import time +ReservationItem = Dict[str, Any] + + +def _now_ts() -> float: + return time.time() + + +def _sort_reservations_inplace(reservations: List[ReservationItem]) -> None: + """按 future_ts 升序,其次 prize_value_yuan 降序,其次 created_ts 升序排序。""" + + def _key(it: ReservationItem): + ft = float(it.get("future_ts") or 0.0) + val = float(it.get("prize_value_yuan") or 0.0) + created = float(it.get("created_ts") or 0.0) + # future_ts 越小越优先;价值越大越优先(因此取 -val);创建时间越早越优先 + return (ft, -val, created) + + reservations.sort(key=_key) + def add_reservation_core_logic( - reservations: List[Dict[str, Any]], - item: Dict[str, Any], -) -> None: - """Shim: append item if not already present by basic key.""" - key = (item.get("future_ts"), item.get("content")) - for r in reservations: - if (r.get("future_ts"), r.get("content")) == key: - return - reservations.append(dict(item)) + reservations: List[ReservationItem], + item: ReservationItem, + max_reservations: Optional[int] = None, + analyser: Any = None, + write_state_callback: Optional[Callable[[], None]] = None, +) -> bool: + """向预约队列追加/更新一条记录,并根据上限裁剪。 + + 去重策略: + - key = (future_ts, content) 相同则视为同一条记录,保留价值更高的那条。 + + 返回: + bool: 如果队列已满且需要回到最早开奖的预约直播间等待,返回 True;否则返回 False。 + """ + ft = float(item.get("future_ts") or 0.0) + content = str(item.get("content") or "") + prize_value = float(item.get("prize_value_yuan") or 0.0) + + same_idx: Optional[int] = None + for idx, r in enumerate(reservations): + try: + if float(r.get("future_ts") or 0.0) == ft and str(r.get("content") or "") == content: + same_idx = idx + break + except Exception: + continue + + if same_idx is not None: + # 若新记录价值更高,则更新 + try: + old_val = float(reservations[same_idx].get("prize_value_yuan") or 0.0) + except Exception: + old_val = 0.0 + if prize_value > old_val: + reservations[same_idx].update(dict(item)) + else: + reservations.append(dict(item)) + + # 排序 + 按上限裁剪 + _sort_reservations_inplace(reservations) + + queue_full = False + if max_reservations is not None and max_reservations > 0 and len(reservations) > max_reservations: + # 记录被丢弃的记录信息 + dropped_items = reservations[max_reservations:] + for dropped in dropped_items: + try: + dropped_value = float(dropped.get("prize_value_yuan") or 0.0) + dropped_future_ts = float(dropped.get("future_ts") or 0.0) + dropped_content = str(dropped.get("content") or "")[:50] + try: + from datetime import datetime + dropped_future_str = datetime.fromtimestamp(dropped_future_ts).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + dropped_future_str = str(dropped_future_ts) + + if analyser: + try: + analyser._log_kv( + "预约", + "预约队列已满,丢弃最低优先级记录", + cap=max_reservations, + dropped_value_yuan=dropped_value, + dropped_future_ts=int(dropped_future_ts), + dropped_future_str=dropped_future_str, + dropped_content=dropped_content, + queue_len_before=len(reservations), + ) + except Exception: + pass + except Exception: + pass + + # 按当前排序规则,队尾是"优先级最低"的记录 + del reservations[max_reservations:] + queue_full = True + + # 如果队列已满,写入状态文件 + if write_state_callback: + try: + write_state_callback() + except Exception: + pass + + return queue_full def validate_back_to_reservation( analyser: Any, - reservations: List[Dict[str, Any]], + reservations: List[ReservationItem], now_ts: float | None = None, ) -> None: - """兼容实现:记录当前预约队列状态,不做严格校验。""" + """回退校验:当前实现为轻量版本,仅记录日志,保留扩展点。""" if now_ts is None: - now_ts = time.time() + now_ts = _now_ts() try: - analyser._log_kv( - "预约", - "validate_back_to_reservation", + analyser._log_kv( + "预约", + "[预约] validate_back_to_reservation", count=len(reservations), now_ts=int(now_ts), ) - except Exception: - pass + except Exception: + pass def cleanup_expired_reservations( analyser: Any, - reservations: List[Dict[str, Any]], - write_state_callback, + reservations: List[ReservationItem], + write_state_callback: Optional[Callable[[], None]] = None, ) -> None: - """兼容实现:清理已过开奖时间的预约,然后写入状态。""" + """清理已过开奖时间的预约,并视情况写入状态文件。""" try: - now_ts_drop = time.time() - dropped = 0 - for r in list(reservations): + now_ts_drop = _now_ts() + before = len(reservations) + reservations[:] = [ + r + for r in reservations + if float(r.get("future_ts") or 0.0) > now_ts_drop + ] + dropped = max(0, before - len(reservations)) + + if dropped: + try: + analyser._log_kv( + "预约", + "[预约] cleanup_expired_reservations", + dropped=dropped, + remain=len(reservations), + ) + except Exception: + pass + + if write_state_callback is not None: try: - ft = float(r.get("future_ts") or 0.0) + write_state_callback() except Exception: - ft = 0.0 - if ft > 0 and now_ts_drop >= ft: - try: - reservations.remove(r) - except Exception: - try: - reservations.pop() - except Exception: - pass - dropped += 1 - if dropped and write_state_callback is not None: - try: - write_state_callback() - except Exception: - pass + pass except Exception: - # Best-effort cleanup only; never crash main loop + # Best-effort cleanup only; never crash主循环 pass +def handle_queue_full_wait_at_earliest( + analyser: Any, + reservations: List[ReservationItem], + room_pos: int, + reservation_focus_until_ts_ref: List[float], + reservation_back_swipe_delay_s: float, + swipe_down_back_callback: Callable[[], None], + seek_reservation_room_callback: Callable[[ReservationItem], bool], + sort_reservations_callback: Callable[[], None], + write_state_callback: Callable[[], None], +) -> bool: + """队列满时,回到最早开奖的预约直播间等待。 + + 返回: + bool: 如果已回退到最早开奖的预约直播间,返回 True;否则返回 False。 + """ + if not reservations: + return False + + # 排序确保取到最早开奖的 + sort_reservations_callback() + + # 取最早开奖的预约 + earliest = reservations[0] + try: + ft = float(earliest.get("future_ts") or 0.0) + except Exception: + ft = 0.0 + + if ft <= 0: + return False + + now_ts = _now_ts() + focus_until = float(reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0) + + # 如果已经在锁定期内,不需要重复回退 + if focus_until > 0 and now_ts < focus_until: + return False + + try: + analyser._log_kv( + "预约", + "[预约] 队列已满,回退到最早开奖的预约直播间等待", + earliest_future_ts=int(ft), + queue_len=len(reservations), + room_pos=int(room_pos), + ) + except Exception: + pass + + # 先轻微下滑一次,确保在直播列表中 + try: + swipe_down_back_callback() + time.sleep(max(0.1, float(reservation_back_swipe_delay_s or 0.0))) + except Exception: + pass + + # 回退到最早开奖的预约直播间 + ok = False + try: + ok = bool(seek_reservation_room_callback(earliest)) + except Exception: + ok = False + + if ok: + # 设置锁定期:直到最早开奖时间 + 轮询时间 + try: + poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0) + except Exception: + poll_before = 10.0 + focus_until_new = ft + max(0.0, poll_before) + if reservation_focus_until_ts_ref: + reservation_focus_until_ts_ref[0] = focus_until_new + else: + reservation_focus_until_ts_ref.append(focus_until_new) + + try: + analyser._log_kv( + "预约", + "[预约] 已回退到最早开奖的预约直播间,等待所有预约完成", + earliest_future_ts=int(ft), + focus_until=int(focus_until_new), + ) + except Exception: + pass + + try: + write_state_callback() + except Exception: + pass + + return True + + return False + + def process_reservation_attend_window( analyser: Any, - reservations: List[Dict[str, Any]], + reservations: List[ReservationItem], room_pos: int, - reservation_focus_until_ts_ref: list, - reservation_after_action_pending_ref: list, + reservation_focus_until_ts_ref: List[float], + reservation_after_action_pending_ref: List[bool], reservation_back_swipe_delay_s: float, - swipe_down_back_callback, - seek_reservation_room_callback, - sort_reservations_callback, - write_state_callback, + swipe_down_back_callback: Callable[[], None], + seek_reservation_room_callback: Callable[[ReservationItem], bool], + sort_reservations_callback: Callable[[], None], + write_state_callback: Callable[[], None], ) -> bool: - """兼容实现:匹配原始签名,仅记录预约窗口信息,不主动抢占主流程。""" + """在主循环中调用:处理“是否需要回退到某个预约直播间并参与”。 + + 返回: + bool: 若为 True,表示已经触发了回退/跳转,本轮主循环应尽快结束, + 让上层逻辑继续后续处理(例如识别详情并参与)。 + """ + if not reservations: + return False + + now_ts = _now_ts() + focus_until = float(reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0) + + # 若当前仍处于“预约直播间锁定期”,则不再触发新的回退 + if focus_until > 0 and now_ts < focus_until: + return False + + # 按统一规则排序(防止外部遗漏 sort) + sort_reservations_callback() + + # 取队头(最早需要处理的一条) + target = reservations[0] try: - analyser._log_kv( - "预约", - "process_reservation_attend_window", - count=len(reservations), - room_pos=room_pos, + ft = float(target.get("future_ts") or 0.0) + except Exception: + ft = 0.0 + + # 没有合法 future_ts,则直接丢弃 + if ft <= 0: + reservations.pop(0) + try: + write_state_callback() + except Exception: + pass + return False + + # 仅在"即将开奖窗口"(包括已过一小段时间)内才触发回退 + try: + join_ahead = float(getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120) + except Exception: + join_ahead = 120.0 + + poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0) + + # 动态提前量计算:考虑回退步数耗时,避免提前量太小导致回退后错过 + dynamic_ahead = int(join_ahead) + est_back_times = 0 + try: + target_pos = int(target.get("pos_seen") or 0) + est_back_times = max(0, int(room_pos) - target_pos) + try: + max_back = int(getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60) + except Exception: + max_back = 60 + if max_back > 0: + est_back_times = min(est_back_times, max_back) + # 动态提前量 = max(基础提前量, 回退步数 * 延迟 + 额外缓冲) + reservation_back_swipe_delay_s_val = float(reservation_back_swipe_delay_s or 0.6) + dynamic_ahead = int(max(join_ahead, est_back_times * reservation_back_swipe_delay_s_val + 18)) + except Exception: + dynamic_ahead = int(join_ahead) + + if now_ts < ft - dynamic_ahead: + # 还没到窗口 + return False + + if now_ts > ft + max(0.0, poll_before): + # 已明显错过开奖时间,交给统一清理逻辑 + cleanup_expired_reservations(analyser, reservations, write_state_callback) + return False + + # 进入预约参与窗口:执行回退动作 + try: + analyser._log_kv( + "预约", + "[预约] 进入预约参与窗口,准备回退到目标直播间", + future_ts=int(ft), + now_ts=int(now_ts), + room_pos=int(room_pos), + queue_len=len(reservations), + dynamic_ahead=int(dynamic_ahead), + est_back_times=int(est_back_times), ) - except Exception: - pass + except Exception: + pass + + # 先轻微下滑一次,确保在直播列表中 / 或触发系统返回 + try: + swipe_down_back_callback() + time.sleep(max(0.1, float(reservation_back_swipe_delay_s or 0.0))) + except Exception: + pass + + # 调用上层提供的“按预约信息回退到目标直播间”的回调 + ok = False + try: + ok = bool(seek_reservation_room_callback(target)) + except Exception: + ok = False + + if ok: + # 进入锁定期:在开奖附近一段时间内不再切换直播间 + focus_until_new = ft + max(0.0, poll_before) + if reservation_focus_until_ts_ref: + reservation_focus_until_ts_ref[0] = focus_until_new + else: + reservation_focus_until_ts_ref.append(focus_until_new) + + if reservation_after_action_pending_ref: + reservation_after_action_pending_ref[0] = True + else: + reservation_after_action_pending_ref.append(True) + + try: + validate_back_to_reservation(analyser, reservations, now_ts=_now_ts()) + except Exception: + pass + + try: + analyser._log_kv( + "预约", + "[预约] 已回退到目标直播间,等待详情识别与参与", + future_ts=int(ft), + focus_until=int(focus_until_new), + ) + except Exception: + pass + + # 不在这里弹出队列,等待真正“参与完毕”后由上层统一处理 + try: + write_state_callback() + except Exception: + pass + + return True + + # 回退失败:记录日志,等待后续重试或清理 + try: + analyser._log_kv( + "预约", + "[预约] 回退到预约直播间失败,保留队列以便后续重试或清理", + future_ts=int(ft), + now_ts=int(now_ts), + ) + except Exception: + pass + + try: + write_state_callback() + except Exception: + pass + return False @@ -116,253 +454,77 @@ def record_high_value_reservation( wait_minutes: int, post_switch_delay_s: float, room_pos: int, - reservations: List[Dict[str, Any]], - reservation_focus_until_ts_ref: list, - close_detail_callback, - swipe_up_switch_callback, - swipe_down_back_callback, - add_reservation_callback, - sort_reservations_callback, - write_state_callback, + reservations: List[ReservationItem], + reservation_focus_until_ts_ref: List[float], + close_detail_callback: Callable[[], None], + swipe_up_switch_callback: Callable[[], None], + swipe_down_back_callback: Callable[[], None], + add_reservation_callback: Callable[[List[ReservationItem], ReservationItem], None], + sort_reservations_callback: Callable[[], None], + write_state_callback: Callable[[], None], + room_title: str = "", + room_title_raw: str = "", ) -> bool: - """兼容实现:按原始签名追加一条简化的高价值预约记录。""" - try: - item: Dict[str, Any] = { - "future_ts": float(future_timestamp or 0.0), - "prize_value_yuan": float(prize_value_yuan or 0.0), - "content": str(fudai_content_text or ""), - "pos_seen": int(room_pos), - "created_ts": time.time(), - } - add_reservation_core_logic(reservations, item) - analyser._log_kv( - "预约", - "record_high_value_reservation:已记录高价值福袋", - value=item["prize_value_yuan"], - future_ts=item["future_ts"], - ) - except Exception: - pass - return False + """记录一条高价值福袋预约。 - - -""" -Reservation core logic shim (WebGUI version) -=========================================== - -Exports: -- add_reservation_core_logic -- validate_back_to_reservation -- cleanup_expired_reservations -- process_reservation_attend_window -- record_high_value_reservation -""" - -from typing import Any, Dict, List -import time - - -def add_reservation_core_logic( - reservations: List[Dict[str, Any]], - item: Dict[str, Any], -) -> None: - """Shim: append item if not already present by basic key.""" - key = (item.get("future_ts"), item.get("content")) - for r in reservations: - if (r.get("future_ts"), r.get("content")) == key: - return - reservations.append(dict(item)) - - -def validate_back_to_reservation( - analyser: Any, - reservations: List[Dict[str, Any]], - now_ts: float | None = None, -) -> None: - """兼容实现:记录当前预约队列状态,不做严格校验。""" - if now_ts is None: - now_ts = time.time() - try: - analyser._log_kv( - "预约", - "validate_back_to_reservation", - count=len(reservations), - now_ts=int(now_ts), - ) - except Exception: - pass - - -def cleanup_expired_reservations( - analyser: Any, - reservations: List[Dict[str, Any]], - write_state_callback, -) -> None: - """兼容实现:清理已过开奖时间的预约,然后写入状态。""" - try: - now_ts_drop = time.time() - dropped = 0 - for r in list(reservations): - try: - ft = float(r.get("future_ts") or 0.0) - except Exception: - ft = 0.0 - if ft > 0 and now_ts_drop >= ft: - try: - reservations.remove(r) - except Exception: - try: - reservations.pop() - except Exception: - pass - dropped += 1 - if dropped and write_state_callback is not None: - try: - write_state_callback() - except Exception: - pass - except Exception: - # Best-effort cleanup only; never crash main loop - pass - - -def process_reservation_attend_window( - analyser: Any, - reservations: List[Dict[str, Any]], - room_pos: int, - reservation_focus_until_ts_ref: list, - reservation_after_action_pending_ref: list, - reservation_back_swipe_delay_s: float, - swipe_down_back_callback, - seek_reservation_room_callback, - sort_reservations_callback, - write_state_callback, -) -> bool: - """兼容实现:匹配原始签名,仅记录预约窗口信息,不主动抢占主流程。""" - try: - analyser._log_kv( - "预约", - "process_reservation_attend_window", - count=len(reservations), - room_pos=room_pos, - ) - except Exception: - pass - return False - - -def record_high_value_reservation( - analyser: Any, - fudai_content_text: str, - prize_value_yuan: float, - lastsecond: int, - future_timestamp: float, - x: int, - needswitch: bool, - wait_minutes: int, - post_switch_delay_s: float, - room_pos: int, - reservations: List[Dict[str, Any]], - reservation_focus_until_ts_ref: list, - close_detail_callback, - swipe_up_switch_callback, - swipe_down_back_callback, - add_reservation_callback, - sort_reservations_callback, - write_state_callback, -) -> bool: - """兼容实现:按原始签名追加一条简化的高价值预约记录。""" - try: - item: Dict[str, Any] = { - "future_ts": float(future_timestamp or 0.0), - "prize_value_yuan": float(prize_value_yuan or 0.0), - "content": str(fudai_content_text or ""), - "pos_seen": int(room_pos), - "created_ts": time.time(), - } - add_reservation_core_logic(reservations, item) - analyser._log_kv( - "预约", - "record_high_value_reservation:已记录高价值福袋", - value=item["prize_value_yuan"], - future_ts=item["future_ts"], - ) - except Exception: - pass - return False - - - -def record_high_value_reservation( - - analyser: Any, - fudai_content_text: str, - - prize_value_yuan: float, - - lastsecond: int, - - future_timestamp: float, - - x: int, - - needswitch: bool, - - wait_minutes: int, - - post_switch_delay_s: float, - - room_pos: int, - - reservations: List[Dict[str, Any]], - reservation_focus_until_ts_ref: list, - close_detail_callback, - - swipe_up_switch_callback, - - swipe_down_back_callback, - - add_reservation_callback, - - sort_reservations_callback, - - write_state_callback, - -) -> bool: - - """Shim: match original signature and optionally append a simple reservation. - - To keep behavior safe and simple, we: - - create a minimal reservation dict; and - - append it to `reservations` without triggering any side-effects. + 当前实现为"只记录,不立刻改变当前直播间"的版本: + - 构造预约 item 并加入 reservations; + - 写入状态文件; + - 返回 False,表示当前轮不需要立即抢占主流程。 """ try: - item: Dict[str, Any] = { + # 计算 future_str(预计开奖时间的字符串格式) + future_str = "" + try: + if future_timestamp and future_timestamp > 0: + from datetime import datetime + future_str = datetime.fromtimestamp(float(future_timestamp)).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + pass + + item: ReservationItem = { "future_ts": float(future_timestamp or 0.0), + "future_str": future_str, "prize_value_yuan": float(prize_value_yuan or 0.0), "content": str(fudai_content_text or ""), - "pos_seen": int(room_pos), - - "created_ts": time.time(), - + "pos_seen": int(room_pos), + "created_ts": _now_ts(), + "room_title": str(room_title or ""), + "room_title_raw": str(room_title_raw or ""), } - add_reservation_core_logic(reservations, item) + + add_reservation_callback(reservations, item) + sort_reservations_callback() + + try: + write_state_callback() + except Exception: + pass + + try: analyser._log_kv( - "预约", + "[预约] record_high_value_reservation:已记录高价值福袋", + value=item["prize_value_yuan"], + future_ts=item["future_ts"], + future_str=future_str, + room_title=room_title[:30] if room_title else "", + queue_len=len(reservations), + ) + except Exception: + pass - "使用精简版 record_high_value_reservation:已记录高价值福袋", - value=item["prize_value_yuan"], - future_ts=item["future_ts"], - ) - except Exception: - - pass - - return False - - - + return False + except Exception: + # 任何异常都不影响主流程,只记录日志 + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation 异常,忽略本次预约", + error_type="Exception", + ) + except Exception: + pass + return False diff --git a/douyin_reservation_verify.py b/douyin_reservation_verify.py new file mode 100644 index 0000000..c76275a --- /dev/null +++ b/douyin_reservation_verify.py @@ -0,0 +1,346 @@ +from __future__ import annotations + +""" +预约回退校验模块 +================ + +提供回退到预约直播间后的详细校验功能: +- 直播间名称匹配 +- 福袋详情匹配(内容、价值、开奖时间) +- 任务类型检查(排除"观看XX分钟"类任务) +""" + +from typing import Any, Dict, Tuple, Optional +import re +import difflib +import time + +import douyin_fudai_detail + + +def _compact_text(text: str) -> str: + """压缩文本:去除空格,用于比较。""" + try: + return re.sub(r"\s+", "", str(text or "")).strip() + except Exception: + return "" + + +def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, Dict[str, Any]]: + """校验回退后的福袋详情是否匹配预约。返回 (ok, reason, debug_dict) + + 参数: + item: 预约项字典 + detail: 福袋详情 tuple (content, time_text, participants, copies, prize_value_yuan, countdown_tuple) + + 返回: + (is_match, reason, debug_dict) + """ + try: + expected_value = float(item.get("prize_value_yuan") or 0.0) + except Exception: + expected_value = 0.0 + try: + expected_future = float(item.get("future_ts") or 0.0) + except Exception: + expected_future = 0.0 + expected_content = _compact_text(item.get("content") or "") + + if not isinstance(detail, tuple) or len(detail) < 6: + return False, "detail_invalid", { + "expected_future": expected_future, + "expected_value": expected_value, + "expected_content": expected_content, + } + + fc, tt, participants, copies, pv, cd = detail[:6] + actual_content = _compact_text(fc or "") + try: + actual_value = float(pv or 0.0) + except Exception: + actual_value = 0.0 + try: + actual_future = float(cd[1] if (isinstance(cd, (tuple, list)) and len(cd) >= 2) else 0.0) + except Exception: + actual_future = 0.0 + + # 检查是否为"观看XX分钟"类任务:若是,则视为任务型福袋,回退校验应判为不匹配(跳过预约) + try: + fc_full = str(fc or "") + chinese_num_chars = "零一二三四五六七八九十百千两" + patt = rf"(?:观看|看)(?:直播)?\s*(?:\d+|[{chinese_num_chars}]+)\s*分钟" + if re.search(patt, fc_full): + return False, "watch_task_detected", { + "expected_future": expected_future, + "actual_future": actual_future, + "expected_value": expected_value, + "actual_value": actual_value, + "expected_content": expected_content, + "actual_content": actual_content, + } + except Exception: + pass + + # future 必须可验证(否则无法确认回退成功) + if not (expected_future > 0 and actual_future > 0): + return False, "future_missing", { + "expected_future": expected_future, + "actual_future": actual_future, + "expected_value": expected_value, + "actual_value": actual_value, + "expected_content": expected_content, + "actual_content": actual_content, + } + + future_diff = abs(expected_future - actual_future) + + # value/content 二选一命中即可(OCR 有误差,且部分福袋可能不展示价值) + value_ok = False + if expected_value > 0 and actual_value > 0: + tol = max(50.0, expected_value * 0.25) + value_ok = abs(expected_value - actual_value) <= tol + + content_ok = False + if expected_content and actual_content: + content_ok = (expected_content in actual_content) or (actual_content in expected_content) + + if not (value_ok or content_ok): + return False, "content_or_value_mismatch", { + "expected_future": expected_future, + "actual_future": actual_future, + "future_diff_s": int(future_diff), + "expected_value": expected_value, + "actual_value": actual_value, + "expected_content": expected_content, + "actual_content": actual_content, + } + + # 优先用 future 精确匹配;但在"内容+价值都一致"时,允许一定范围的 future 偏差,避免 OCR 倒计时误读导致误判。 + # 说明:正常情况下 future_diff 应该很小;若 future_diff 过大仍会判不匹配。 + if future_diff > 180: + if value_ok and content_ok and future_diff <= 1200: + return True, "future_mismatch_relaxed", { + "expected_future": expected_future, + "actual_future": actual_future, + "future_diff_s": int(future_diff), + "expected_value": expected_value, + "actual_value": actual_value, + "expected_content": expected_content, + "actual_content": actual_content, + } + return False, "future_mismatch", { + "expected_future": expected_future, + "actual_future": actual_future, + "future_diff_s": int(future_diff), + "expected_value": expected_value, + "actual_value": actual_value, + "expected_content": expected_content, + "actual_content": actual_content, + } + + return True, "ok", { + "expected_future": expected_future, + "actual_future": actual_future, + "future_diff_s": int(future_diff), + "expected_value": expected_value, + "actual_value": actual_value, + "expected_content": expected_content, + "actual_content": actual_content, + } + + +def validate_back_to_reservation( + analyser: Any, + item: Dict[str, Any], + quick: bool = False, + max_checks: int = 3, +) -> Tuple[bool, Optional[Tuple]]: + """回退后校验:必须看到福袋并且详情匹配预约。 + + 参数: + analyser: 分析器对象 + item: 预约项字典 + quick: 是否快速模式(减少检查次数) + max_checks: 最大检查次数 + + 返回: + (is_valid, detail_tuple) - 如果校验通过,返回详情 tuple,否则返回 None + """ + # 若开关关闭,则跳过复杂校验,直接认为回退成功以加速流程 + try: + if not bool(getattr(analyser, "reservation_back_verify_enabled", True)): + analyser._log_kv("预约", "回退校验已被禁用:跳过校验") + return True, None + except Exception: + pass + + # 先用"直播间名"做一次快速判断:不匹配则大概率回错房间,优先驱动微调继续找 + try: + # 使用 douyin_high_value_room 中的规范化函数 + import douyin_high_value_room + expected_title = douyin_high_value_room._normalize_room_title(item.get("room_title") or "") + except Exception: + try: + expected_title_raw_text = str(item.get("room_title") or "") + # 简单的规范化:去除空格和特殊字符 + expected_title = re.sub(r"\s+", "", expected_title_raw_text).strip() + # 去掉常见无关词 + for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"): + expected_title = expected_title.replace(w, "") + expected_title = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", expected_title) + except Exception: + expected_title = str(item.get("room_title") or "").strip() + expected_title_raw = str(item.get("room_title_raw") or "").strip() + + if expected_title: + try: + y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) + current_title, current_title_raw = douyin_fudai_detail.read_live_room_title_core( + analyser, y_pianyi_val + ) + # 更新 analyser 的属性 + try: + analyser.current_room_title = current_title + analyser.current_room_title_raw = current_title_raw + except Exception: + pass + + if current_title: + ratio = 0.0 + try: + ratio = float(difflib.SequenceMatcher(None, expected_title, current_title).ratio()) + except Exception: + ratio = 0.0 + + try: + analyser._log_kv( + "预约", + "回退校验:直播间名对比", + room_title_expected=expected_title, + room_title_current=current_title, + room_title_raw_expected=expected_title_raw, + room_title_raw_current=current_title_raw, + room_title_ratio=round(ratio, 3), + ) + except Exception: + pass + + # 强不匹配:直接失败(避免打开错误福袋详情浪费时间) + if current_title and (expected_title not in current_title) and (current_title not in expected_title) and ratio < 0.45: + return False, None + except Exception as e: + try: + analyser._log_kv("预约", "回退校验:读取直播间标题失败", error=str(e)) + except Exception: + pass + + # 检测福袋图标 + x2 = 0 + check_count = 1 if quick else max_checks + for i in range(check_count): + try: + import douyin_detection + analyser.operation.get_screenshot(analyser.device_id) + x2 = douyin_detection.check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True) + if x2 and x2 > 0: + break + except Exception: + x2 = 0 + if i < check_count - 1: + try: + analyser._log_kv("预约", "回退校验:未发现福袋", attempt=i + 1) + except Exception: + pass + try: + analyser.operation.delay(0.5 if quick else 1.0) + except Exception: + time.sleep(0.5 if quick else 1.0) + + if not x2 or x2 <= 0: + try: + analyser._log_kv("预约", "回退校验失败:未发现福袋", result="未发现福袋") + except Exception: + pass + return False, None + + # 打开详情并确认进入详情页(避免点击后截图过早导致读错屏) + try: + analyser.click(x2, 400) # 点击福袋图标 + analyser.operation.delay(0.8 if quick else 1.5) + except Exception: + try: + analyser.operation.click(analyser.device_id, x2, 400) + analyser.operation.delay(0.8 if quick else 1.5) + except Exception: + pass + + # 确认是否在详情页 + try: + import douyin_stage + analyser.operation.get_screenshot(analyser.device_id) + stage, _ = douyin_stage.diagnose_stage_from_current_screen(analyser) + if stage != "FUDai_DETAIL": + try: + analyser._log_kv("预约", "回退校验失败:未能打开福袋详情", result="详情未打开", stage=stage) + except Exception: + pass + return False, None + except Exception: + pass + + # 详情页刚出现时可能仍在动画/加载,稍等再识别更稳定 + analyser.operation.delay(0.6 if quick else 1.1) + + # 读取详情 + try: + detail2 = douyin_fudai_detail.read_fudai_detail_with_retries( + analyser, + fudai_x=x2, + read_once_callback=douyin_fudai_detail.read_fudai_detail_once, + close_detail_callback=douyin_fudai_detail.close_fudai_detail, + ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open, + ) + + if not detail2 or not isinstance(detail2, tuple) or len(detail2) < 6: + try: + analyser._log_kv("预约", "回退校验失败:详情读取异常", result="详情异常") + except Exception: + pass + # 确保关闭详情 + try: + douyin_fudai_detail.close_fudai_detail(analyser) + except Exception: + pass + return False, None + except Exception as e: + try: + analyser._log_kv("预约", "回退校验失败:详情读取异常", error=str(e)) + except Exception: + pass + try: + douyin_fudai_detail.close_fudai_detail(analyser) + except Exception: + pass + return False, None + + # 匹配校验 + ok, reason, dbg = match_reservation(item, detail2) + if not ok: + try: + analyser._log_kv("预约", "回退校验失败:福袋详情不匹配", result="不匹配", reason=reason, **dbg) + except Exception: + pass + try: + douyin_fudai_detail.close_fudai_detail(analyser) + except Exception: + pass + return False, None + + # 校验通过 + try: + analyser._log_kv("预约", "回退校验通过:福袋详情匹配", reason=reason, **dbg) + except Exception: + pass + + return True, detail2 + diff --git a/douyin_stage.py b/douyin_stage.py index 61b3270..438254a 100644 --- a/douyin_stage.py +++ b/douyin_stage.py @@ -324,10 +324,10 @@ def diagnose_stage_from_current_screen(self): result_verified = False try: - # 检测抽奖结果文字区域 (350, 650)-(750, 765) + # 检测抽奖结果文字区域 (300, 600)-(800, 800) - 扩大区域以覆盖"没有抽中福袋"文字 if time.time() - step_result_start < max_step_time: cut_start = time.time() - self.cut_pic(350, 650, 750, 765, "", "抽奖结果") + self.cut_pic(300, 600, 800, 800, "", "抽奖结果") cut_elapsed = (time.time() - cut_start) * 1000 _log("步骤1[检测抽奖结果弹窗]-截图完成", 耗时毫秒=cut_elapsed) @@ -353,11 +353,11 @@ def diagnose_stage_from_current_screen(self): 文本预览=result_text[:50] if result_text else "", ) - # 检测"我知道了"按钮区域 (340, 1195)-(740, 1355) + # 检测"我知道了"按钮区域 (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() - self.cut_pic(340, 1195, 740, 1355, "", "无奖励确认") + self.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") cut_confirm_elapsed = (time.time() - cut_confirm_start) * 1000 _log("步骤1[检测抽奖结果弹窗]-确认按钮截图完成", 耗时毫秒=cut_confirm_elapsed) @@ -591,83 +591,100 @@ def diagnose_stage_from_current_screen(self): _log("阶段诊断完成(像素检测)", 阶段="FUDai_DETAIL", 原因="福袋详情页像素检测(并行)") return "FUDai_DETAIL", "像素检测确认(福袋详情页,并行检测)" - # 如果并行检测未命中,使用完整检测方法(包含OCR兜底)作为补充 + # 如果并行检测未命中,使用"超级福袋"模板匹配作为补充(不再使用 OCR 兜底) step_start = time.time() - _log("步骤1[像素检测福袋详情]-并行检测未命中,使用完整检测方法补充", 说明="补充检测") + _log( + "步骤1[像素检测福袋详情]-并行检测未命中,使用模板匹配补充", + 说明="assets/xiangqing.png(超级福袋)", + ) try: - check_result = self.check_in_fudai_detail() - elapsed = (time.time() - step_start) * 1000 - total_elapsed = (time.time() - diag_start) * 1000 - if check_result: - detail_detected = True - _log("步骤1[像素检测福袋详情]-命中(完整检测)", 耗时毫秒=elapsed, 总耗时毫秒=total_elapsed) - _log("阶段诊断完成(完整检测)", 阶段="FUDai_DETAIL", 原因="福袋详情页完整检测") - return "FUDai_DETAIL", "完整检测确认(福袋详情页)" + # 为了兼容没有 cv2 的环境,这里做降级处理 + try: + import cv2 # type: ignore + except Exception as e: + elapsed = (time.time() - step_start) * 1000 + _log( + "步骤1[福袋详情模板匹配]-缺少opencv,跳过模板检测", + 耗时毫秒=elapsed, + 异常类型=type(e).__name__, + 异常信息=str(e), + ) else: - _log("步骤1[像素检测福袋详情]-未命中(完整检测)", 耗时毫秒=elapsed) + import os + + base_dir = os.path.dirname(__file__) + pic_path = os.path.join(base_dir, "pic", "screenshot.png") + tpl_path = os.path.join(base_dir, "assets", "xiangqing.png") + + # 仅在截图与模板都存在时才进行模板匹配 + if os.path.exists(pic_path) and os.path.exists(tpl_path): + img = cv2.imread(pic_path) + tpl = cv2.imread(tpl_path) + if img is not None and tpl is not None: + ih, iw = img.shape[:2] + th, tw = tpl.shape[:2] + if ih >= th and iw >= tw: + # 使用 TM_CCOEFF_NORMED 做标准模板匹配 + res = cv2.matchTemplate(img, tpl, cv2.TM_CCOEFF_NORMED) + _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res) + + # 使用 fudai_template_match_threshold 作为可配置阈值 + threshold = float( + getattr(self, "fudai_template_match_threshold", 0.7) or 0.7 + ) + if threshold < 0.0: + threshold = 0.0 + if threshold > 1.0: + threshold = 1.0 + + elapsed = (time.time() - step_start) * 1000 + _log( + "步骤1[福袋详情模板匹配]-结果", + 分数=round(float(max_val or 0.0), 4), + 阈值=threshold, + 耗时毫秒=elapsed, + ) + + if max_val >= threshold: + detail_detected = True + total_elapsed = (time.time() - diag_start) * 1000 + _log( + "步骤1[福袋详情模板匹配]-命中", + 分数=round(float(max_val or 0.0), 4), + 总耗时毫秒=total_elapsed, + ) + _log( + "阶段诊断完成(模板匹配)", + 阶段="FUDai_DETAIL", + 原因="超级福袋模板匹配命中", + ) + return "FUDai_DETAIL", "模板匹配确认(超级福袋)" + else: + elapsed = (time.time() - step_start) * 1000 + _log( + "步骤1[福袋详情模板匹配]-模板尺寸大于截图,跳过", + 截图尺寸=f"{iw}x{ih}", + 模板尺寸=f"{tw}x{th}", + 耗时毫秒=elapsed, + ) + else: + elapsed = (time.time() - step_start) * 1000 + _log( + "步骤1[福袋详情模板匹配]-文件不存在,跳过", + 截图存在=os.path.exists(pic_path), + 模板存在=os.path.exists(tpl_path), + 耗时毫秒=elapsed, + ) except Exception as e: import traceback elapsed = (time.time() - step_start) * 1000 - _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: - 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: - 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 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 "", - ) - - # 检测福袋详情页关键词 - detail_keywords = ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看", "一键", "发表") - if detail_text and any(kw in detail_text for kw in detail_keywords): - detail_detected = True - 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)) + _log( + "步骤1[福袋详情模板匹配]-异常", + 耗时毫秒=elapsed, + 异常类型=type(e).__name__, + 异常信息=str(e), + 堆栈=traceback.format_exc(), + ) if detail_detected: total_elapsed = (time.time() - diag_start) * 1000 diff --git a/gui_app.py b/gui_app.py index 6643823..4a87748 100644 --- a/gui_app.py +++ b/gui_app.py @@ -75,7 +75,10 @@ def main(): ttk.Button(top, text="刷新设备", command=refresh_devices).pack(side=LEFT, padx=(0, 20)) - y_var = tk.IntVar(value=0) + # 配置区(提前读取配置,供后续使用) + cfg = read_config() + + y_var = tk.IntVar(value=int(cfg.get("y_pianyi", 0) or 0)) ttk.Label(top, text="Y偏移:").pack(side=LEFT) ttk.Spinbox(top, from_=-200, to=200, textvariable=y_var, width=6).pack(side=LEFT, padx=(0, 12)) @@ -108,10 +111,8 @@ def main(): left.bind("", _left_on_configure) left_canvas.bind("", _left_on_canvas_configure) - - # 配置区 - cfg = read_config() needswitch_var = tk.BooleanVar(value=bool(cfg.get("needswitch", True))) + infinite_loop_var = tk.BooleanVar(value=bool(cfg.get("infinite_loop_enabled", False))) wait_minutes_var = tk.IntVar(value=int(cfg.get("wait_minutes", 5) or 5)) min_value_var = tk.DoubleVar(value=float(cfg.get("min_prize_value_yuan", 0) or 0)) @@ -194,9 +195,21 @@ def main(): r1 = ttk.Frame(run_box) r1.pack(fill=X, padx=10, pady=(0, 10)) - ttk.Label(r1, text="倒计时阈值(分钟):").pack(side=LEFT) - ttk.Spinbox(r1, from_=1, to=60, textvariable=wait_minutes_var, width=6).pack(side=LEFT, padx=(0, 12)) - ttk.Label(r1, text="倒计时小于(秒)跳过:").pack(side=LEFT) + ttk.Checkbutton(r1, text="无限循环模式", variable=infinite_loop_var).pack(side=LEFT) + ttk.Label(r1, text="运行时长(分钟):").pack(side=LEFT, padx=(10, 0)) + wait_minutes_spinbox = ttk.Spinbox(r1, from_=1, to=60, textvariable=wait_minutes_var, width=6) + wait_minutes_spinbox.pack(side=LEFT, padx=(0, 12)) + + # 根据无限循环开关状态,启用/禁用运行时长输入框 + def update_wait_minutes_state(*args): + if infinite_loop_var.get(): + wait_minutes_spinbox.config(state="disabled") + else: + wait_minutes_spinbox.config(state="normal") + infinite_loop_var.trace("w", update_wait_minutes_state) + update_wait_minutes_state() # 初始化状态 + + ttk.Label(r1, text="倒计时小于(秒)时不参与(高价值可预约):").pack(side=LEFT) ttk.Spinbox(r1, from_=0, to=120, textvariable=skip_lt_seconds_var, width=6).pack(side=LEFT) r2 = ttk.Frame(run_box) @@ -464,6 +477,7 @@ def main(): nonlocal cfg cfg = read_config() needswitch_var.set(bool(cfg.get("needswitch", True))) + infinite_loop_var.set(bool(cfg.get("infinite_loop_enabled", False))) wait_minutes_var.set(int(cfg.get("wait_minutes", 5) or 5)) yg_enabled_var.set(bool(cfg.get("yanghao_enabled", True))) yg_actions_enabled_var.set(bool(cfg.get("yanghao_enable_actions", True))) @@ -478,6 +492,7 @@ def main(): auto_join_var.set(bool(cfg.get("auto_join_fansclub", False))) fansclub_action_var.set(str(cfg.get("fansclub_fail_action", "stay") or "stay").lower()) lucky_draw_red_ratio_threshold_var.set(float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)) + y_var.set(int(cfg.get("y_pianyi", 0) or 0)) # Web端新增配置 - 高价值预约相关 high_value_fudai_enabled_var.set(bool(cfg.get("high_value_fudai_enabled", False))) @@ -553,7 +568,9 @@ def main(): cfg2 = read_config() cfg2["needswitch"] = bool(needswitch_var.get()) + cfg2["infinite_loop_enabled"] = bool(infinite_loop_var.get()) cfg2["wait_minutes"] = int(wait_minutes_var.get() or 5) + cfg2["y_pianyi"] = int(y_var.get() or 0) cfg2["contains_not_want"] = not_want_lines cfg2["min_prize_value_yuan"] = float(min_value_var.get() or 0) cfg2["min_participants"] = int(min_participants_var.get() or 0) @@ -925,12 +942,14 @@ def main(): status_var = tk.StringVar(value="就绪") def get_params() -> RunParams: + # 如果启用无限循环,设置 wait_minutes=0 + wait_minutes_value = 0 if infinite_loop_var.get() else int(wait_minutes_var.get() or 5) 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()), - wait_minutes=int(wait_minutes_var.get()), + wait_minutes=wait_minutes_value, skip_if_countdown_lt_seconds=int(skip_lt_seconds_var.get() or 15), reset_after_swipes_enabled=bool(reset_after_swipes_enabled_var.get()), reset_after_swipes=int(reset_after_swipes_var.get() or 10), @@ -956,9 +975,10 @@ def main(): save_ui_to_config() params = get_params() + wait_display = "∞" if params.wait_minutes == 0 else f"{params.wait_minutes}m" on_line( f"[运行] 启动:device={params.device_id or '(auto)'} y={params.y_pianyi} " - f"needswitch={params.needswitch} wait={params.wait_minutes}m " + f"needswitch={params.needswitch} wait={wait_display} " f"skip_lt={params.skip_if_countdown_lt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} " f"value>={params.min_prize_value_yuan} participants=[{params.min_participants},{params.max_participants}] " f"high_value_revisit={params.high_value_room_revisit_enabled} reservation_verify={params.reservation_back_verify_enabled} " diff --git a/gui_core.py b/gui_core.py index 1650b07..c6e7ba2 100644 --- a/gui_core.py +++ b/gui_core.py @@ -346,13 +346,15 @@ class Runner: if self.is_running(): raise RuntimeError("已经在运行") + # 如果 wait_minutes=0,表示无限循环模式 + wait_minutes_arg = str(params.wait_minutes) if params.wait_minutes > 0 else "0" cmd = [ sys.executable, os.path.join(os.path.dirname(__file__), "run_cli.py"), "--y-pianyi", str(params.y_pianyi), "--wait-minutes", - str(params.wait_minutes), + wait_minutes_arg, ] if params.device_id: cmd += ["--device-id", params.device_id] diff --git a/path_config.py b/path_config.py index bdd2546..80192a6 100644 --- a/path_config.py +++ b/path_config.py @@ -164,6 +164,12 @@ def ensure_dir(path: str) -> None: + + + + + + diff --git a/run_cli.py b/run_cli.py index 543cd3c..708b2b9 100644 --- a/run_cli.py +++ b/run_cli.py @@ -90,7 +90,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace: p.add_argument("--min-prize-value-yuan", type=float, default=None, help="最低奖品价值(元),低于则不参与") p.add_argument("--min-participants", type=int, default=None, help="最少参与人数(0/空表示不启用)") p.add_argument("--max-participants", type=int, default=None, help="最多参与人数(0/空表示不启用)") - p.add_argument("--skip-if-countdown-lt-seconds", type=int, default=None, help="倒计时小于该秒数则不参与(needswitch 生效)") + p.add_argument("--skip-if-countdown-lt-seconds", type=int, default=None, help="倒计时小于该秒数则不参与,高价值福袋可预约(needswitch 生效)") p.add_argument( "--reset-after-swipes", type=int, diff --git a/state/high_value_rooms.json b/state/high_value_rooms.json index e8751ab..d25219c 100644 --- a/state/high_value_rooms.json +++ b/state/high_value_rooms.json @@ -1,8 +1,37 @@ { - "updated_ts": 1765982203.946906, - "reason": "reservation_dedup", - "total": 85, + "updated_ts": 1766155589.686831, + "reason": "reservation", + "total": 86, "rooms": [ + { + "first_seen_ts": 1765799932.458368, + "last_seen_ts": 1766155589.686831, + "seen_count": 2, + "pos_seen": 0, + "pos_updated_ts": 1766155589.686831, + "room_title_raw_last": "小明正能。", + "alias_raw": [ + "小明正能.." + ], + "key_kind": "norm", + "last_content": "超大椰子螺5斤左右", + "last_prize_value_yuan": 899.0, + "max_prize_value_yuan": 899.0, + "room_title": "小明正能" + }, + { + "first_seen_ts": 1766155502.130805, + "last_seen_ts": 1766155502.130805, + "seen_count": 1, + "pos_seen": 0, + "pos_updated_ts": 1766155502.130805, + "room_title_raw_last": "李亚鹏19.", + "key_kind": "norm", + "last_content": "ApplejPhone17256GB颜色随机发32468人巳参与", + "last_prize_value_yuan": 5999.0, + "max_prize_value_yuan": 5999.0, + "room_title": "李亚鹏19" + }, { "first_seen_ts": 1765968226.497444, "last_seen_ts": 1765982203.946906, @@ -1229,22 +1258,6 @@ "max_prize_value_yuan": 1299.0, "room_title": "左家皮具" }, - { - "first_seen_ts": 1765799932.458368, - "last_seen_ts": 1765799932.458368, - "seen_count": 1, - "pos_seen": 0, - "pos_updated_ts": 1765799932.458368, - "room_title_raw_last": "小明正能..", - "alias_raw": [ - "小明正能.." - ], - "key_kind": "norm", - "last_content": "半只羊肉礼盒10斤装2", - "last_prize_value_yuan": 599.0, - "max_prize_value_yuan": 599.0, - "room_title": "小明正能" - }, { "first_seen_ts": 1765799022.2357109, "last_seen_ts": 1765799022.2357109, diff --git a/state/reservations.json b/state/reservations.json index 68b903c..61dc473 100644 --- a/state/reservations.json +++ b/state/reservations.json @@ -1,8 +1,19 @@ { - "updated_ts": 1765986410.2242348, - "reason": "init", + "updated_ts": 1766155589.6960292, + "reason": "record_reservation", "room_pos": 0, - "current_room_title": "", - "current_room_title_raw": "", - "reservations": [] -} + "current_room_title": "小明正能", + "current_room_title_raw": "小明正能。", + "reservations": [ + { + "prize_value_yuan": 899.0, + "content": "超大椰子螺5斤左右", + "future_ts": 1766155871.122754, + "future_str": "2025-12-19 22:51:11", + "pos_seen": 0, + "room_title": "小明正能", + "room_title_raw": "小明正能。", + "created_ts": 1766155589.6949484 + } + ] +} \ No newline at end of file diff --git a/tools/README_RGB工具.md b/tools/README_RGB工具.md new file mode 100644 index 0000000..0229e9e --- /dev/null +++ b/tools/README_RGB工具.md @@ -0,0 +1,75 @@ +# RGB颜色范围读取工具使用说明 + +## 功能 +读取图片的RGB颜色范围,用于调试福袋检测的颜色匹配逻辑。 + +## 使用方法 + +### 1. 读取整张图片的RGB范围 +```bash +python tools/read_image_rgb.py pic/screenshot.png +``` + +### 2. 读取特定坐标的RGB值 +```bash +python tools/read_image_rgb.py pic/screenshot.png 100 200 +``` +这会显示坐标 (100, 200) 的RGB值。 + +### 3. 读取特定区域的RGB范围 +```bash +python tools/read_image_rgb.py pic/screenshot.png 0 0 200 300 +``` +这会读取从 (0, 0) 开始,宽度200、高度300的区域的RGB范围。 + +## 实际应用示例 + +### 示例1:检测福袋图标颜色 +假设福袋图标在坐标 (165, 403) 附近: +```bash +# 读取单个像素 +python tools/read_image_rgb.py pic/screenshot.png 165 403 + +# 读取一个小区域(比如 10x10 像素) +python tools/read_image_rgb.py pic/screenshot.png 160 398 10 10 +``` + +### 示例2:检测福袋详情页参与按钮颜色 +假设参与按钮在坐标 (536, 883) 附近: +```bash +# 读取单个像素 +python tools/read_image_rgb.py pic/screenshot.png 536 883 + +# 读取按钮区域(比如 20x20 像素) +python tools/read_image_rgb.py pic/screenshot.png 526 873 20 20 +``` + +## 输出说明 + +### 单个像素输出 +``` +坐标 (165, 403) 的RGB值: + R: 198 + G: 185 + B: 242 + 十六进制: #C6B9F2 +``` + +### 区域/整图输出 +``` +RGB颜色范围: + R: 190 ~ 206 + G: 173 ~ 196 + B: 234 ~ 250 + +用于代码的颜色范围判断: + 190 <= r <= 206 and 173 <= g <= 196 and 234 <= b <= 250 +``` + +## 注意事项 + +1. 坐标基于图片的实际分辨率 +2. 如果图片是1080x2400,坐标就是实际像素坐标 +3. 如果图片是其他分辨率,需要按比例换算 +4. 区域检测会扫描区域内所有像素,计算最小和最大RGB值 + diff --git a/tools/analyze_fudai_color.py b/tools/analyze_fudai_color.py new file mode 100644 index 0000000..82da5ee --- /dev/null +++ b/tools/analyze_fudai_color.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""分析福袋图标的RGB颜色范围,给出代码建议""" + +from PIL import Image +from collections import Counter + +img = Image.open('assets/fudai.png').convert('RGB') +width, height = img.size + +# 收集非背景像素 +pixels = [] +for y in range(height): + for x in range(width): + r, g, b = img.getpixel((x, y)) + # 排除黑色背景 + if not (r < 30 and g < 30 and b < 30): + pixels.append((r, g, b)) + +if not pixels: + print("No valid pixels") + exit(1) + +# 主要颜色 +colors = Counter(pixels) +top_colors = colors.most_common(10) + +print("Top 10 colors:") +for i, ((r, g, b), count) in enumerate(top_colors, 1): + pct = (count / len(pixels)) * 100 + print(f"{i}. RGB({r:3d}, {g:3d}, {b:3d}) - {pct:5.2f}% - #{r:02X}{g:02X}{b:02X}") + +# RGB范围 +r_vals = [p[0] for p in pixels] +g_vals = [p[1] for p in pixels] +b_vals = [p[2] for p in pixels] + +print(f"\nFull RGB range:") +print(f" R: {min(r_vals)} ~ {max(r_vals)}") +print(f" G: {min(g_vals)} ~ {max(g_vals)}") +print(f" B: {min(b_vals)} ~ {max(b_vals)}") + +# 基于主要颜色的建议范围 +if top_colors: + main_r, main_g, main_b = top_colors[0][0] + print(f"\nMain color: RGB({main_r}, {main_g}, {main_b})") + print(f"\nSuggested range (main color +/- tolerance):") + + # 容差建议 + tolerance_r = 30 + tolerance_g = 30 + tolerance_b = 30 + + r_min = max(200, main_r - tolerance_r) + r_max = min(255, main_r + 10) + g_min = max(150, main_g - tolerance_g) + g_max = min(255, main_g + tolerance_g) + b_min = max(180, main_b - tolerance_b) + b_max = min(255, main_b + tolerance_b) + + print(f" {r_min} <= r <= {r_max}") + print(f" {g_min} <= g <= {g_max}") + print(f" {b_min} <= b <= {b_max}") + + print(f"\nCode format:") + print(f" {r_min} <= int(px[0]) <= {r_max} and {g_min} <= int(px[1]) <= {g_max} and {b_min} <= int(px[2]) <= {b_max}") + diff --git a/tools/compare_fudai_coupon.py b/tools/compare_fudai_coupon.py new file mode 100644 index 0000000..a93e9e5 --- /dev/null +++ b/tools/compare_fudai_coupon.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""对比福袋和优惠券的RGB颜色,找出区分特征""" + +from PIL import Image +from collections import Counter + +print("=" * 60) +print("福袋图标颜色分析") +print("=" * 60) +fudai = Image.open('assets/fudai.png').convert('RGB') +fudai_pixels = [(r,g,b) for y in range(fudai.height) for x in range(fudai.width) + for r,g,b in [fudai.getpixel((x,y))] if not (r<30 and g<30 and b<30)] +fudai_colors = Counter(fudai_pixels) +fudai_top = fudai_colors.most_common(5) +print("Top 5 colors:") +for (r,g,b), count in fudai_top: + print(f" RGB({r:3d}, {g:3d}, {b:3d}) - {count/len(fudai_pixels)*100:5.2f}%") + +fudai_r = [p[0] for p in fudai_pixels] +fudai_g = [p[1] for p in fudai_pixels] +fudai_b = [p[2] for p in fudai_pixels] +print(f"\nRGB range: R[{min(fudai_r)}-{max(fudai_r)}] G[{min(fudai_g)}-{max(fudai_g)}] B[{min(fudai_b)}-{max(fudai_b)}]") + +print("\n" + "=" * 60) +print("优惠券颜色分析") +print("=" * 60) +coupon = Image.open('assets/coupon.png').convert('RGB') +coupon_pixels = [(r,g,b) for y in range(coupon.height) for x in range(coupon.width) + for r,g,b in [coupon.getpixel((x,y))] if not (r<30 and g<30 and b<30)] +coupon_colors = Counter(coupon_pixels) +coupon_top = coupon_colors.most_common(5) +print("Top 5 colors:") +for (r,g,b), count in coupon_top: + print(f" RGB({r:3d}, {g:3d}, {b:3d}) - {count/len(coupon_pixels)*100:5.2f}%") + +coupon_r = [p[0] for p in coupon_pixels] +coupon_g = [p[1] for p in coupon_pixels] +coupon_b = [p[2] for p in coupon_pixels] +print(f"\nRGB range: R[{min(coupon_r)}-{max(coupon_r)}] G[{min(coupon_g)}-{max(coupon_g)}] B[{min(coupon_b)}-{max(coupon_b)}]") + +print("\n" + "=" * 60) +print("区分特征分析") +print("=" * 60) + +# 优惠券的主要红色特征 +coupon_red = [p for p in coupon_pixels if p[0] > 250 and p[1] < 100 and p[2] < 120] +if coupon_red: + red_r = [p[0] for p in coupon_red] + red_g = [p[1] for p in coupon_red] + red_b = [p[2] for p in coupon_red] + print(f"\n优惠券红色区域:") + print(f" R: {min(red_r)}-{max(red_r)}") + print(f" G: {min(red_g)}-{max(red_g)}") + print(f" B: {min(red_b)}-{max(red_b)}") + print(f" 特征: 高R值(>{min(red_r)}),低G值(<{max(red_g)}),低B值(<{max(red_b)})") + +# 福袋的主要颜色特征 +fudai_pink = [p for p in fudai_pixels if p[0] > 225 and p[1] > 180 and p[2] > 190] +if fudai_pink: + pink_r = [p[0] for p in fudai_pink] + pink_g = [p[1] for p in fudai_pink] + pink_b = [p[2] for p in fudai_pink] + print(f"\n福袋粉红色区域:") + print(f" R: {min(pink_r)}-{max(pink_r)}") + print(f" G: {min(pink_g)}-{max(pink_g)}") + print(f" B: {min(pink_b)}-{max(pink_b)}") + print(f" 特征: 高R值(>{min(pink_r)}),高G值(>{min(pink_g)}),高B值(>{min(pink_b)})") + +print("\n" + "=" * 60) +print("建议的排除条件") +print("=" * 60) +print("\n优惠券红色特征(需要排除):") +print(" - R > 250 且 G < 100 且 B < 120 (鲜艳红色)") +print(" - R > 250 且 G < 150 且 B < 150 (较宽松的红色)") +print("\n福袋粉红色特征(需要保留):") +print(" - R > 225 且 G > 180 且 B > 190 (粉红色)") +print("\n建议的福袋检测条件:") +print(" R > 225 and R <= 255") +print(" G > 180 and G <= 255") +print(" B > 190 and B <= 255") +print(" AND NOT (R > 250 and G < 100 and B < 120) # 排除优惠券红色") + diff --git a/tools/read_fudai_rgb.py b/tools/read_fudai_rgb.py new file mode 100644 index 0000000..4758700 --- /dev/null +++ b/tools/read_fudai_rgb.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +福袋图标RGB颜色范围检测工具 +自动排除黑色背景,只检测福袋图标本身的RGB范围 +""" + +import sys +from PIL import Image +from collections import Counter + + +def get_fudai_rgb_range(image_path: str, exclude_bg: bool = True, bg_threshold: int = 30): + """检测福袋图标的RGB颜色范围(排除背景) + + 参数: + image_path: 图片路径 + exclude_bg: 是否排除背景色(默认True,排除RGB值都小于30的像素) + bg_threshold: 背景色阈值(RGB值都小于此值认为是背景) + """ + try: + img = Image.open(image_path) + img_rgb = img.convert("RGB") + width, height = img_rgb.size + + print(f"图片尺寸: {width} x {height}") + print(f"图片模式: {img.mode}") + print("-" * 60) + + # 收集所有非背景像素的RGB值 + pixels = [] + for y in range(height): + for x in range(width): + try: + r, g, b = img_rgb.getpixel((x, y)) + # 如果启用背景排除,跳过黑色/深色背景 + if exclude_bg and r < bg_threshold and g < bg_threshold and b < bg_threshold: + continue + pixels.append((r, g, b)) + except Exception: + continue + + if not pixels: + print("错误: 没有检测到有效像素(可能整张图都是背景色)") + return None + + # 计算RGB范围 + r_values = [p[0] for p in pixels] + g_values = [p[1] for p in pixels] + b_values = [p[2] for p in pixels] + + r_min, r_max = min(r_values), max(r_values) + g_min, g_max = min(g_values), max(g_values) + b_min, b_max = min(b_values), max(b_values) + + # 计算RGB平均值(用于参考) + r_avg = sum(r_values) // len(r_values) + g_avg = sum(g_values) // len(g_values) + b_avg = sum(b_values) // len(b_values) + + print(f"\n福袋图标RGB颜色范围(已排除背景):") + print(f" R: {r_min} ~ {r_max} (平均值: {r_avg})") + print(f" G: {g_min} ~ {g_max} (平均值: {g_avg})") + print(f" B: {b_min} ~ {b_max} (平均值: {b_avg})") + print(f"\n有效像素数: {len(pixels)} / {width * height}") + + # 分析主要颜色(找出最常见的RGB组合) + print(f"\n主要颜色分析:") + color_counter = Counter(pixels) + top_colors = color_counter.most_common(5) + for i, (color, count) in enumerate(top_colors, 1): + r, g, b = color + percentage = (count / len(pixels)) * 100 + print(f" {i}. RGB({r}, {g}, {b}) - 占比 {percentage:.1f}% - #{r:02X}{g:02X}{b:02X}") + + # 生成代码建议 + print(f"\n" + "=" * 60) + print("用于代码的颜色范围判断(建议):") + print("=" * 60) + + # 方法1:使用完整范围(容错性最好,但可能误检) + print(f"\n方法1:完整范围(容错性最好)") + print(f" {r_min} <= r <= {r_max} and {g_min} <= g <= {g_max} and {b_min} <= b <= {b_max}") + + # 方法2:使用平均值±范围(更精确,但需要根据实际情况调整) + r_range = max(10, (r_max - r_min) // 2) + g_range = max(10, (g_max - g_min) // 2) + b_range = max(10, (b_max - b_min) // 2) + + print(f"\n方法2:平均值±范围(更精确)") + print(f" {r_avg - r_range} <= r <= {r_avg + r_range} and " + f"{g_avg - g_range} <= g <= {g_avg + g_range} and " + f"{b_avg - b_range} <= b <= {b_avg + b_range}") + + # 方法3:基于主要颜色的范围(最精确,但可能漏检) + if top_colors: + main_r, main_g, main_b = top_colors[0][0] + tolerance = 20 # 容差 + print(f"\n方法3:主要颜色±容差(最精确,基于主要颜色RGB({main_r}, {main_g}, {main_b}))") + print(f" {main_r - tolerance} <= r <= {main_r + tolerance} and " + f"{main_g - tolerance} <= g <= {main_g + tolerance} and " + f"{main_b - tolerance} <= b <= {main_b + tolerance}") + + # 当前代码中的范围(用于对比) + print(f"\n当前代码中的范围(用于对比):") + print(f" 190 <= r <= 206 and 173 <= g <= 196 and 234 <= b <= 250") + + return { + "r_range": (r_min, r_max), + "g_range": (g_min, g_max), + "b_range": (b_min, b_max), + "r_avg": r_avg, + "g_avg": g_avg, + "b_avg": b_avg, + "pixel_count": len(pixels) + } + + except FileNotFoundError: + print(f"错误: 找不到图片文件: {image_path}") + return None + except Exception as e: + print(f"错误: {type(e).__name__}: {e}") + import traceback + traceback.print_exc() + return None + + +def main(): + if len(sys.argv) < 2: + print("用法: python tools/read_fudai_rgb.py <图片路径>") + print("示例: python tools/read_fudai_rgb.py pic/fudai_icon.png") + sys.exit(1) + + image_path = sys.argv[1] + get_fudai_rgb_range(image_path) + + +if __name__ == "__main__": + main() + diff --git a/tools/read_image_rgb.py b/tools/read_image_rgb.py new file mode 100644 index 0000000..3cf2a69 --- /dev/null +++ b/tools/read_image_rgb.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +图片RGB颜色范围读取工具 + +用法: + python tools/read_image_rgb.py <图片路径> [x] [y] [width] [height] + +示例: + # 读取整张图片的RGB范围 + python tools/read_image_rgb.py pic/screenshot.png + + # 读取特定坐标的RGB值 + python tools/read_image_rgb.py pic/screenshot.png 100 200 + + # 读取特定区域的RGB范围 + python tools/read_image_rgb.py pic/screenshot.png 0 0 200 300 +""" + +import sys +import os +from PIL import Image + + +def get_rgb_range(image_path: str, x: int = None, y: int = None, width: int = None, height: int = None): + """读取图片的RGB颜色范围 + + 参数: + image_path: 图片路径 + x: 起始X坐标(可选,用于区域检测) + y: 起始Y坐标(可选,用于区域检测) + width: 区域宽度(可选,用于区域检测) + height: 区域高度(可选,用于区域检测) + + 返回: + dict: 包含RGB范围信息的字典 + """ + try: + img = Image.open(image_path) + img_rgb = img.convert("RGB") + img_width, img_height = img_rgb.size + + print(f"图片尺寸: {img_width} x {img_height}") + print(f"图片模式: {img.mode}") + print("-" * 60) + + # 如果指定了坐标,读取单个像素 + if x is not None and y is not None: + if not (0 <= x < img_width and 0 <= y < img_height): + print(f"错误: 坐标 ({x}, {y}) 超出图片范围") + return None + + r, g, b = img_rgb.getpixel((x, y)) + print(f"坐标 ({x}, {y}) 的RGB值:") + print(f" R: {r}") + print(f" G: {g}") + print(f" B: {b}") + print(f" 十六进制: #{r:02X}{g:02X}{b:02X}") + return {"r": r, "g": g, "b": b, "x": x, "y": y} + + # 如果指定了区域,读取区域范围 + if x is not None and y is not None and width is not None and height is not None: + x_end = min(x + width, img_width) + y_end = min(y + height, img_height) + + print(f"区域: ({x}, {y}) 到 ({x_end-1}, {y_end-1})") + print(f"区域大小: {x_end - x} x {y_end - y}") + + pixels = [] + for py in range(y, y_end): + for px in range(x, x_end): + try: + r, g, b = img_rgb.getpixel((px, py)) + pixels.append((r, g, b)) + except Exception: + continue + + if not pixels: + print("错误: 区域中没有有效像素") + return None + + r_values = [p[0] for p in pixels] + g_values = [p[1] for p in pixels] + b_values = [p[2] for p in pixels] + + r_min, r_max = min(r_values), max(r_values) + g_min, g_max = min(g_values), max(g_values) + b_min, b_max = min(b_values), max(b_values) + + print(f"\nRGB颜色范围:") + print(f" R: {r_min} ~ {r_max}") + print(f" G: {g_min} ~ {g_max}") + print(f" B: {b_min} ~ {b_max}") + print(f"\n用于代码的颜色范围判断:") + print(f" {r_min} <= r <= {r_max} and {g_min} <= g <= {g_max} and {b_min} <= b <= {b_max}") + print(f"\n像素总数: {len(pixels)}") + + return { + "r_range": (r_min, r_max), + "g_range": (g_min, g_max), + "b_range": (b_min, b_max), + "pixel_count": len(pixels) + } + + # 读取整张图片的RGB范围 + print("扫描整张图片...") + pixels = [] + for py in range(img_height): + for px in range(img_width): + try: + r, g, b = img_rgb.getpixel((px, py)) + pixels.append((r, g, b)) + except Exception: + continue + + if not pixels: + print("错误: 图片中没有有效像素") + return None + + r_values = [p[0] for p in pixels] + g_values = [p[1] for p in pixels] + b_values = [p[2] for p in pixels] + + r_min, r_max = min(r_values), max(r_values) + g_min, g_max = min(g_values), max(g_values) + b_min, b_max = min(b_values), max(b_values) + + print(f"\n整张图片的RGB颜色范围:") + print(f" R: {r_min} ~ {r_max}") + print(f" G: {g_min} ~ {g_max}") + print(f" B: {b_min} ~ {b_max}") + print(f"\n像素总数: {len(pixels)}") + + return { + "r_range": (r_min, r_max), + "g_range": (g_min, g_max), + "b_range": (b_min, b_max), + "pixel_count": len(pixels) + } + + except FileNotFoundError: + print(f"错误: 找不到图片文件: {image_path}") + return None + except Exception as e: + print(f"错误: {type(e).__name__}: {e}") + return None + + +def main(): + if len(sys.argv) < 2: + print(__doc__) + sys.exit(1) + + image_path = sys.argv[1] + + # 解析参数 + x = int(sys.argv[2]) if len(sys.argv) > 2 else None + y = int(sys.argv[3]) if len(sys.argv) > 3 else None + width = int(sys.argv[4]) if len(sys.argv) > 4 else None + height = int(sys.argv[5]) if len(sys.argv) > 5 else None + + # 如果只提供了x和y,就是读取单个像素 + if x is not None and y is not None and width is None and height is None: + get_rgb_range(image_path, x=x, y=y) + # 如果提供了x, y, width, height,就是读取区域 + elif x is not None and y is not None and width is not None and height is not None: + get_rgb_range(image_path, x=x, y=y, width=width, height=height) + # 否则读取整张图片 + else: + get_rgb_range(image_path) + + +if __name__ == "__main__": + main() + diff --git a/webui/index.html b/webui/index.html index 513e6a2..6c0037d 100644 --- a/webui/index.html +++ b/webui/index.html @@ -176,7 +176,7 @@
- +
diff --git a/功能差异对比.md b/功能差异对比.md new file mode 100644 index 0000000..feedaba --- /dev/null +++ b/功能差异对比.md @@ -0,0 +1,249 @@ +# 模块化代码 vs 原始代码 (fudai1.py) 功能差异对比 + +## 一、已移除/简化的功能 + +### 1. ❌ **高价值直播间回访功能**(已移除) + +#### 原始代码 +- **功能**:自动回访曾经记录过高价值福袋的直播间 +- **优先级**:预约参与(最高) > 回访(中) > 普通找福袋(低) +- **配置**: + - `high_value_room_revisit_enabled = True`(默认启用) + - `high_value_room_revisit_interval_seconds = 300`(默认 5 分钟) + - `high_value_room_revisit_watch_window_seconds = 900`(默认 15 分钟观察窗) + - `high_value_room_revisit_skip_if_reservation_within_seconds = 120` +- **实现**:在主循环中检查回访时间窗口,自动回退到高价值直播间查看是否有新福袋 + +#### 模块化代码 +- **状态**:仅保留配置项,功能未实现 +- **配置**: + - `high_value_room_revisit_enabled = False`(默认禁用) + - `high_value_room_revisit_only_current_run = False` +- **影响**:无法自动回访高价值直播间,只能通过预约队列手动回退 + +--- + +### 2. ⚠️ **回退校验功能**(已简化) + +#### 原始代码 +- **功能**:回退到预约直播间后,进行详细校验确保回退正确 +- **校验内容**: + 1. 直播间名称匹配(清洗后和原始文本) + 2. 福袋详情匹配(内容、价值、开奖时间) + 3. 任务类型检查(排除"观看XX分钟"类任务) +- **配置**:`reservation_back_verify_enabled = True`(默认启用) +- **实现**:`_validate_back_to_reservation()` 和 `_match_reservation()` 函数 +- **行为**:校验失败会丢弃当前预约项,继续处理其他预约 + +#### 模块化代码 +- **状态**:简化版实现 +- **功能**:仅保留基本的回退逻辑,没有详细的校验机制 +- **实现**:`_seek_reservation_room()` 函数简化了校验逻辑 +- **影响**:回退准确性可能降低,但速度更快 + +--- + +### 3. ❌ **等待次数计数器**(已移除) + +#### 原始代码 +- **功能**:`wait_times` 计数器,累计 4 次没有福袋则切换直播间 +- **逻辑**:在直播间等待时,每次未找到福袋 `wait_times++`,达到阈值后切换 + +#### 模块化代码 +- **状态**:已移除 +- **影响**:不再基于等待次数自动切换,改为基于时间或其他条件 + +--- + +### 4. ❌ **滑动次数重置功能**(已移除) + +#### 原始代码 +- **功能**:`reset_after_swipes` - 达到一定滑动次数后,回到第一个直播间 +- **配置**: + - `reset_after_swipes_enabled = False`(默认关闭,但可配置) + - `reset_after_swipes = 10`(阈值) +- **逻辑**:`_maybe_reset_after_swipes()` 函数检查滑动次数,达到阈值后回退 + +#### 模块化代码 +- **状态**:已移除 +- **影响**:无法自动重置到列表第一个直播间 + +--- + +### 5. ❌ **无法打开福袋计数器**(已移除) + +#### 原始代码 +- **功能**:`fudai_not_open_times` 计数器,记录无法打开福袋的次数 +- **逻辑**:用于统计和可能的错误处理 + +#### 模块化代码 +- **状态**:已移除 +- **影响**:不再统计无法打开福袋的次数 + +--- + +### 6. ❌ **意外返回桌面自救功能**(已移除) + +#### 原始代码 +- **功能**:检测是否意外返回桌面(不在抖音前台),自动恢复 +- **实现**: + 1. 检测前台包名 + 2. 如果不在抖音,点击桌面图标 + 3. 点击直播按钮 + 4. 点击进入直播间 +- **配置**:使用 `desktop_icon_x/y`、`yanghao_fallback_live_x/y` 等坐标 + +#### 模块化代码 +- **状态**:已移除 +- **影响**:如果意外返回桌面,需要手动恢复 + +--- + +### 7. ❌ **充电停止弹窗检测**(已移除) + +#### 原始代码 +- **功能**:`check_stop_charging()` - 检测 vivo 设备长时间连接弹出的停止充电弹窗 +- **实现**:OCR 识别充电提醒文字 + +#### 模块化代码 +- **状态**:已移除 +- **影响**:无法自动处理充电停止弹窗 + +--- + +### 8. ❌ **电池电量检测**(已移除) + +#### 原始代码 +- **功能**:`deal_battery_level()` - 检测电池电量,低电量时挂机 30 分钟 +- **实现**:检测电池电量,低电量时返回直播列表并等待 + +#### 模块化代码 +- **状态**:已移除 +- **影响**:不再检测电池电量 + +--- + +## 二、保留但简化的功能 + +### 1. ⚠️ **预约队列管理**(简化) + +#### 原始代码 +- **功能**:完整的高价值福袋预约队列管理 +- **特性**: + - 动态提前量计算(考虑回退步数耗时) + - 预约项匹配校验 + - 预约完成后动作(stay/continue) + - 预约队列状态持久化 + +#### 模块化代码 +- **状态**:保留核心功能,简化实现 +- **保留**: + - 预约队列基本管理 + - 预约回退逻辑 + - 状态文件写入 +- **简化**: + - 回退校验逻辑简化 + - 动态提前量计算简化 + +--- + +### 2. ⚠️ **高价值直播间记录**(简化) + +#### 原始代码 +- **功能**:`_touch_high_value_room()` - 记录高价值直播间信息 +- **特性**: + - 跨运行持久化(写入 `high_value_rooms.json`) + - 记录最大价值、最后价值、首次/最后记录时间 + - 记录次数统计 + - 支持别名和合并逻辑 + +#### 模块化代码 +- **状态**:保留配置,但功能简化 +- **保留**:配置项存在 +- **简化**:实际记录逻辑可能不完整 + +--- + +## 三、新增或改进的功能 + +### 1. ✅ **无限循环模式** + +#### 模块化代码 +- **功能**:新增 `infinite_loop_enabled` 配置项 +- **行为**:启用后,程序不会因为 `wait_minutes` 而自动退出 +- **用途**:适合长期挂机场景 + +#### 原始代码 +- **状态**:无此功能,必须设置 `wait_minutes` + +--- + +### 2. ✅ **模块化设计** + +#### 模块化代码 +- **优势**: + - 功能模块独立,易于维护 + - 可以单独测试每个模块 + - 可以按需启用/禁用功能模块 + +#### 原始代码 +- **状态**:所有功能耦合在一个文件中 + +--- + +## 四、功能对比总结表 + +| 功能 | 原始代码 | 模块化代码 | 状态 | +|------|---------|-----------|------| +| **基础抢福袋** | ✅ | ✅ | 保留 | +| **高价值福袋预约** | ✅ | ✅ | 保留(简化) | +| **预约回退** | ✅ | ✅ | 保留(简化) | +| **回退校验** | ✅ 详细校验 | ⚠️ 简化校验 | 简化 | +| **高价值直播间回访** | ✅ | ❌ | 已移除 | +| **等待次数计数器** | ✅ | ❌ | 已移除 | +| **滑动次数重置** | ✅ | ❌ | 已移除 | +| **无法打开福袋计数** | ✅ | ❌ | 已移除 | +| **意外返回桌面自救** | ✅ | ❌ | 已移除 | +| **充电停止弹窗检测** | ✅ | ❌ | 已移除 | +| **电池电量检测** | ✅ | ❌ | 已移除 | +| **高价值直播间记录** | ✅ 完整 | ⚠️ 简化 | 简化 | +| **无限循环模式** | ❌ | ✅ | 新增 | + +## 五、使用建议 + +### 如果依赖以下功能,建议使用原始代码: +1. ✅ **高价值直播间自动回访** - 需要自动回访功能 +2. ✅ **详细的回退校验** - 需要确保回退准确性 +3. ✅ **意外返回桌面自救** - 设备可能意外返回桌面 +4. ✅ **电池电量管理** - 需要自动处理低电量 + +### 如果只需要基础功能,模块化代码更适合: +1. ✅ **代码更清晰** - 易于理解和修改 +2. ✅ **维护更方便** - 模块化设计便于维护 +3. ✅ **无限循环模式** - 适合长期挂机 +4. ✅ **功能精简** - 只保留核心功能,减少复杂度 + +## 六、迁移注意事项 + +如果从原始代码迁移到模块化代码: + +1. **高价值直播间回访**:需要手动通过预约队列管理 +2. **回退校验**:校验逻辑简化,可能影响准确性 +3. **计数器功能**:不再有等待次数、滑动次数等自动切换机制 +4. **自救功能**:需要手动处理意外返回桌面的情况 +5. **电池管理**:需要手动监控电池电量 + +## 七、总结 + +**模块化代码的设计理念**: +- ✅ 保留核心功能(抢福袋、预约队列) +- ✅ 简化复杂功能(回退校验、回访逻辑) +- ✅ 移除边缘功能(自救、电池检测) +- ✅ 提高代码可维护性 + +**适用场景**: +- ✅ 只需要基础抢福袋功能 +- ✅ 需要代码清晰、易于维护 +- ✅ 不需要自动回访等高级功能 +- ✅ 需要长期稳定运行(无限循环模式) + diff --git a/模块化代码对比说明.md b/模块化代码对比说明.md new file mode 100644 index 0000000..c9b46de --- /dev/null +++ b/模块化代码对比说明.md @@ -0,0 +1,285 @@ +# 模块化代码 vs 原始代码 (fudai1.py) 对比说明 + +## 一、代码组织结构 + +### 原始代码 (fudai1.py) +- **单文件架构**:所有代码集中在一个约 6000 行的巨大文件中 +- **类内方法**:所有功能都作为 `fudai_analyse` 类的方法实现 +- **嵌套函数**:大量逻辑通过嵌套函数实现(如 `_read_live_room_title`, `_normalize_room_title` 等) +- **全局函数**:少量全局辅助函数(`normalize_countdown_text`, `extract_prize_value_yuan`) + +### 模块化代码 +- **多文件架构**:按功能拆分成 20+ 个独立模块文件 +- **功能模块化**:每个模块负责特定功能领域 +- **函数式设计**:核心逻辑以独立函数形式组织,便于测试和复用 +- **清晰的依赖关系**:通过 import 明确模块间的依赖 + +## 二、模块划分对比 + +### 原始代码结构 +``` +fudai1.py (6000+ 行) +├── 全局辅助函数 +│ ├── normalize_countdown_text() +│ └── extract_prize_value_yuan() +├── class fudai_analyse +│ ├── __init__() +│ ├── fudai_choujiang() [主循环,2800+ 行] +│ ├── 检测相关方法 +│ ├── 福袋详情读取方法 +│ ├── 预约相关方法 +│ ├── 直播间标题读取方法 +│ └── ... (所有功能都在类内) +``` + +### 模块化代码结构 +``` +douyin_fudai.py (主调度器,~1000 行) +├── 导入各功能模块 +└── class fudai_analyse (精简的调度类) + +功能模块(每个 ~100-500 行): +├── douyin_detection.py # 福袋图标检测 +├── douyin_stage.py # 阶段诊断 +├── douyin_pixel.py # 像素检测 +├── douyin_fudai_core.py # 福袋核心业务逻辑 +├── douyin_fudai_detail.py # 福袋详情读取(含直播间标题) +├── douyin_flow_control.py # 流程控制 +├── douyin_reservation_logic.py # 预约队列逻辑 +├── douyin_lottery.py # 抽奖结果处理 +├── douyin_popups.py # 弹窗检测 +├── douyin_robot.py # 人机验证 +├── douyin_swipe_ops.py # 滑动操作 +├── douyin_text_utils.py # 文本处理工具 +└── ... (其他辅助模块) +``` + +## 三、具体功能对比 + +### 1. 主循环逻辑 + +#### 原始代码 +```python +def fudai_choujiang(self, device_id="", y_pianyi=0, needswitch=False, wait_minutes=15): + """2800+ 行的巨大函数,包含所有逻辑""" + # 初始化变量 + wait_times = 0 + swipe_times = 0 + reservations = [] + # ... 大量嵌套逻辑 + while True: + # 阶段诊断 + # 福袋检测 + # 详情读取 + # 预约处理 + # ... 所有逻辑都在这里 +``` + +#### 模块化代码 +```python +def run_once_basic(self) -> None: + """单轮基础抢福袋流程(~200 行)""" + # 调用预约处理模块 + if self.high_value_fudai_enabled: + douyin_reservation_logic.process_reservation_attend_window(...) + + # 调用阶段诊断模块 + stage = douyin_stage.diagnose_stage_from_current_screen(...) + + # 调用流程控制模块 + douyin_flow_control.handle_stage_after_diagnosis(...) + douyin_flow_control.find_and_open_fudai_detail(...) +``` + +### 2. 直播间标题读取 + +#### 原始代码 +```python +def _read_live_room_title(label: str = "") -> str: + """在 fudai_choujiang() 内部定义的嵌套函数""" + def _ocr_try(cut_name: str, change_color: int) -> tuple[str, str]: + # OCR 尝试逻辑 + def _pick_best(cands: list[tuple[str, str, str]]) -> tuple[str, str]: + # 选择最佳结果 + def _extract_room_title_candidate(raw_text: str) -> str: + # 提取候选 + def _normalize_room_title(t: str) -> str: + # 规范化 + # ... 所有辅助函数都在主函数内部 +``` + +#### 模块化代码 +```python +# douyin_fudai_detail.py + +# 模块级别的辅助函数(可复用) +def _room_title_has_ellipsis(s: str) -> bool: ... +def _strip_room_noise_text(s: str) -> str: ... +def _extract_room_title_candidate(raw_text: str) -> str: ... +def _normalize_room_title(t: str) -> str: ... +def _ocr_try_room_title(analyser: Any, cut_name: str, change_color: int) -> Tuple[str, str]: ... +def _pick_best_room_title(cands: List[Tuple[str, str, str]], min_len: int = 3) -> Tuple[str, str]: ... + +# 主函数(简洁清晰) +def read_live_room_title_core(analyser: Any, y_pianyi: int, min_len: int = 3) -> Tuple[str, str]: + """读取直播间标题""" + # 调用辅助函数 + # 返回结果 +``` + +### 3. 预约队列管理 + +#### 原始代码 +```python +# 在 fudai_choujiang() 内部 +reservations = [] +def _add_reservation(future_ts: float, pv: float, content: str) -> None: + """嵌套函数,直接操作外部变量""" + item = {...} + reservations.append(item) + _sorted_reservations() + _write_reservations_state("add") + +def _sorted_reservations(): + """嵌套函数""" + reservations.sort(key=lambda it: (it["future_ts"], -it["prize_value_yuan"], it["created_ts"])) +``` + +#### 模块化代码 +```python +# douyin_reservation_logic.py + +# 独立的排序函数 +def _sort_reservations_inplace(reservations: List[ReservationItem]) -> None: + """按 future_ts 升序,prize_value_yuan 降序排序""" + def _key(it: ReservationItem): + return (ft, -val, created) + reservations.sort(key=_key) + +# 独立的添加函数 +def add_reservation_core_logic( + reservations: List[ReservationItem], + item: ReservationItem, + max_reservations: Optional[int] = None, +) -> None: + """向预约队列追加/更新一条记录""" + # 去重逻辑 + # 排序 + # 裁剪 + +# 独立的记录函数 +def record_high_value_reservation(...) -> bool: + """记录一条高价值福袋预约""" + # 构造 item + # 调用 add_reservation_core_logic + # 写入状态 +``` + +## 四、代码复用性对比 + +### 原始代码 +- ❌ 嵌套函数无法在其他地方复用 +- ❌ 逻辑耦合度高,难以单独测试 +- ❌ 修改一处可能影响整个函数 + +### 模块化代码 +- ✅ 函数可在多个模块间复用 +- ✅ 每个模块可独立测试 +- ✅ 修改影响范围可控 + +## 五、可维护性对比 + +### 原始代码 +- ❌ 6000+ 行单文件,难以定位问题 +- ❌ 函数嵌套层级深,逻辑复杂 +- ❌ 代码重复(如 OCR 尝试逻辑在多处出现) + +### 模块化代码 +- ✅ 每个模块职责单一,易于理解 +- ✅ 函数层级扁平,逻辑清晰 +- ✅ 公共逻辑提取为独立函数,避免重复 + +## 六、依赖关系对比 + +### 原始代码 +```python +# 所有依赖都在一个文件内 +class fudai_analyse: + def fudai_choujiang(self): + # 直接使用 self 的所有方法 + self._read_live_room_title() + self._check_in_live_room_by_icon() + # ... 紧密耦合 +``` + +### 模块化代码 +```python +# douyin_fudai.py +import douyin_stage +import douyin_detection +import douyin_fudai_core +import douyin_reservation_logic +# ... 明确的依赖关系 + +# 通过参数传递,降低耦合 +def process_reservation_attend_window( + analyser: Any, + reservations: List[ReservationItem], + # ... 通过参数传递,不直接访问 analyser 的所有属性 +) -> bool: +``` + +## 七、测试友好性对比 + +### 原始代码 +- ❌ 难以单独测试某个功能 +- ❌ 需要构造完整的 `fudai_analyse` 实例 +- ❌ 嵌套函数无法直接测试 + +### 模块化代码 +- ✅ 每个函数可独立测试 +- ✅ 可以 mock 依赖模块 +- ✅ 测试用例更聚焦 + +## 八、性能影响 + +### 原始代码 +- ✅ 函数调用开销小(无跨模块调用) +- ❌ 代码体积大,加载时间长 + +### 模块化代码 +- ⚠️ 轻微的函数调用开销(可忽略) +- ✅ 按需加载,启动更快 +- ✅ 代码缓存更友好 + +## 九、总结 + +| 维度 | 原始代码 (fudai1.py) | 模块化代码 | +|------|---------------------|-----------| +| **文件数量** | 1 个巨大文件 | 20+ 个模块文件 | +| **代码行数** | ~6000 行单文件 | 每个模块 100-500 行 | +| **可维护性** | ⭐⭐ | ⭐⭐⭐⭐⭐ | +| **可测试性** | ⭐⭐ | ⭐⭐⭐⭐⭐ | +| **可复用性** | ⭐⭐ | ⭐⭐⭐⭐⭐ | +| **代码清晰度** | ⭐⭐ | ⭐⭐⭐⭐⭐ | +| **学习曲线** | 陡峭(需要理解整个文件) | 平缓(可逐个模块学习) | +| **性能** | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | + +## 十、模块化代码的优势 + +1. **职责分离**:每个模块只负责一个功能领域 +2. **易于扩展**:新增功能只需添加新模块或扩展现有模块 +3. **便于协作**:多人可同时修改不同模块,减少冲突 +4. **代码复用**:公共函数可在多个模块间共享 +5. **测试友好**:每个模块可独立编写测试用例 +6. **文档清晰**:每个模块都有明确的文档说明 + +## 十一、迁移建议 + +如果要从原始代码迁移到模块化代码: + +1. **保持接口兼容**:`fudai_analyse` 类的公共接口保持不变 +2. **逐步迁移**:可以逐个功能模块迁移,不需要一次性全部迁移 +3. **测试验证**:迁移后通过实际运行验证功能正确性 +4. **文档更新**:更新相关文档说明新的模块结构 +