From 47e1a0cb2c2a430ad51071a31341134df2fae2bb Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 8 Jan 2026 00:15:40 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E6=A0=BC=E5=BC=8F=EF=BC=8C=E6=8F=90=E5=8D=87=E5=8F=AF?= =?UTF-8?q?=E8=AF=BB=E6=80=A7=E5=92=8C=E4=B8=80=E8=87=B4=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- douyin/core/douyin_fudai.py | 16 ++++-- douyin/fudai/douyin_fudai_core.py | 25 +++++---- douyin/fudai/douyin_fudai_finder.py | 45 ++++++++++------ test_reservation_backtrack.py | 63 +++++++++++++++++------ test_reservation_error_scenarios.py | 32 ++++++------ test_reservation_verify.py | 80 ++++++++++++++++++----------- 6 files changed, 172 insertions(+), 89 deletions(-) diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 9ac75c8..b72d9c6 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -2505,7 +2505,11 @@ class fudai_analyse: # 步骤1结束计时 step1_elapsed = (time.time() - step1_start) * 1000 - self._log_kv("详情处理", "步骤1[检查是否第二次打开]-完成", 总耗时毫秒=step1_elapsed) + self._log_kv( + "详情处理", + "步骤1[检查是否第二次打开]-完成", + 总耗时毫秒=step1_elapsed, + ) elapsed = time.time() - start_time self._log_kv( @@ -2556,7 +2560,11 @@ class fudai_analyse: # 步骤2结束计时 step2_elapsed = (time.time() - step2_start) * 1000 - self._log_kv("详情处理", "步骤2[读取福袋详情]-完成", 总耗时毫秒=step2_elapsed) + self._log_kv( + "详情处理", + "步骤2[读取福袋详情]-完成", + 总耗时毫秒=step2_elapsed, + ) elapsed = time.time() - start_time self._log_kv( @@ -3252,7 +3260,9 @@ class fudai_analyse: # 返回,让主循环只检测开奖结果,不执行其他操作 # 步骤4结束计时 step4_elapsed = (time.time() - step4_start) * 1000 - self._log_kv("详情处理", "步骤4[参与决策]-完成", 总耗时毫秒=step4_elapsed) + self._log_kv( + "详情处理", "步骤4[参与决策]-完成", 总耗时毫秒=step4_elapsed + ) return else: self._log_kv("参与", "参与成功但无法获取倒计时,跳过等待") diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index 7a69496..1764021 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -2190,7 +2190,9 @@ def attend_choujiang(analyser) -> bool: metric_type="success", run_id=getattr(analyser, "_run_id", ""), source="already_attended", - future_ts=int(getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0), + future_ts=int( + getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 + ), ) except Exception: pass @@ -3857,22 +3859,23 @@ def _is_short_countdown_text(time_text: str) -> bool: """检查倒计时文本是否表示剩余时间很短(应跳过)""" if not time_text: return False - + time_text = time_text.strip() - + # 匹配 00:00, 00:01, 00:02 等,表示剩余时间 <= 2秒 import re - if re.match(r'^00:0[0-2]$', time_text): + + if re.match(r"^00:0[0-2]$", time_text): return True - + # 匹配 0:00, 0:01, 0:02 等(有时没有前导零) - if re.match(r'^0:0[0-2]$', time_text): + if re.match(r"^0:0[0-2]$", time_text): return True - + # 匹配 "00秒", "01秒", "02秒" 等 - if re.match(r'^0[0-2]秒$', time_text): + if re.match(r"^0[0-2]秒$", time_text): return True - + return False @@ -4128,7 +4131,9 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str "倒计时文本过滤:丢弃(OCR识别到剩余时间很短)", 原因="countdown_text_short", 倒计时文本=time_text, - 实际剩余秒数=int(remain_seconds) if remain_seconds is not None else None, + 实际剩余秒数=( + int(remain_seconds) if remain_seconds is not None else None + ), ) except Exception: pass diff --git a/douyin/fudai/douyin_fudai_finder.py b/douyin/fudai/douyin_fudai_finder.py index 0af9680..aa72962 100644 --- a/douyin/fudai/douyin_fudai_finder.py +++ b/douyin/fudai/douyin_fudai_finder.py @@ -52,7 +52,9 @@ class FudaiImageAcquirer: ) except Exception: try: - self.analyser.operation.get_screenshot(self.analyser.device_id, use_service=False) + self.analyser.operation.get_screenshot( + self.analyser.device_id, use_service=False + ) except Exception: return None @@ -659,7 +661,10 @@ class FudaiDetector: # 保存模板匹配的调试图像(无论成功与否)- 使用完整截图 try: import importlib - douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) # Image 已在文件顶部导入 # 使用完整截图而不是搜索区域ROI @@ -1149,7 +1154,9 @@ class FudaiDetailVerifier: while checks < max_checks: # 刷新截图 try: - self.analyser.operation.get_screenshot(self.analyser.device_id, use_service=False) + self.analyser.operation.get_screenshot( + self.analyser.device_id, use_service=False + ) except Exception: pass @@ -1162,7 +1169,10 @@ class FudaiDetailVerifier: # 保存完整截图并标注OCR区域 try: import importlib - douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): @@ -1220,12 +1230,11 @@ class FudaiDetailVerifier: self.analyser.cut_pic( 238, 454, 847, 545, "", "验证邀你抢红包区域", y_pianyi ) - name_invite = preprocess_for_ocr(self.analyser, "验证邀你抢红包区域") + name_invite = preprocess_for_ocr( + self.analyser, "验证邀你抢红包区域" + ) ocr_text = str( - self.analyser.operation.analyse_pic_word( - name_invite, 0 - ) - or "" + self.analyser.operation.analyse_pic_word(name_invite, 0) or "" ) # 如果模式0未识别到,尝试模式1 @@ -1238,11 +1247,11 @@ class FudaiDetailVerifier: kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气") ) ): - name_invite1 = preprocess_for_ocr(self.analyser, "验证邀你抢红包区域") + name_invite1 = preprocess_for_ocr( + self.analyser, "验证邀你抢红包区域" + ) ocr_text = str( - self.analyser.operation.analyse_pic_word( - name_invite1, 1 - ) + self.analyser.operation.analyse_pic_word(name_invite1, 1) or "" ) @@ -1459,7 +1468,10 @@ class FudaiFinder: # 保存完整截图用于调试(检测前) try: import importlib - douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) pic_rgb_full = pic.convert("RGB") @@ -1527,7 +1539,10 @@ class FudaiFinder: # 保存完整截图(检测成功) try: import importlib - douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) pic_rgb_full = pic.convert("RGB") diff --git a/test_reservation_backtrack.py b/test_reservation_backtrack.py index 3578d27..97e1f42 100644 --- a/test_reservation_backtrack.py +++ b/test_reservation_backtrack.py @@ -26,7 +26,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from douyin.reservation.douyin_reservation_logic import ( process_reservation_attend_window, _sort_reservations_inplace, - ReservationItem + ReservationItem, ) from douyin.reservation.douyin_reservation_verify import validate_back_to_reservation @@ -92,7 +92,9 @@ class MockAnalyser: print(f"成功回退到位置 {target_pos}") return True else: - print(f"回退距离过大,限制在 {self.high_value_fudai_max_swipe_back} 次滑动内") + print( + f"回退距离过大,限制在 {self.high_value_fudai_max_swipe_back} 次滑动内" + ) return False @@ -136,17 +138,23 @@ def test_reservation_backtrack(): print("排序前:") for i, r in enumerate(reservations): - print(f" {i+1}. {r['room_title']} (位置{r['pos_seen']}) - {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元") + print( + f" {i+1}. {r['room_title']} (位置{r['pos_seen']}) - {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元" + ) _sort_reservations_inplace(reservations) print("排序后:") for i, r in enumerate(reservations): - print(f" {i+1}. {r['room_title']} (位置{r['pos_seen']}) - {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元") + print( + f" {i+1}. {r['room_title']} (位置{r['pos_seen']}) - {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元" + ) # 验证排序:时间优先,其次价值 - if (reservations[0]["future_ts"] <= reservations[1]["future_ts"] and - reservations[1]["future_ts"] <= reservations[2]["future_ts"]): + if ( + reservations[0]["future_ts"] <= reservations[1]["future_ts"] + and reservations[1]["future_ts"] <= reservations[2]["future_ts"] + ): print("✓ 测试1通过:预约队列排序正确") else: print("✗ 测试1失败:预约队列排序不正确") @@ -156,10 +164,26 @@ def test_reservation_backtrack(): print("-" * 40) test_cases = [ - {"pos_seen": 3, "expected_direction": "up", "expected_steps": 2}, # 从5到3,向上2步 - {"pos_seen": 7, "expected_direction": "down", "expected_steps": 2}, # 从5到7,向下2步 - {"pos_seen": 5, "expected_direction": "none", "expected_steps": 0}, # 已在目标位置 - {"pos_seen": 1, "expected_direction": "up", "expected_steps": 4}, # 从5到1,向上4步 + { + "pos_seen": 3, + "expected_direction": "up", + "expected_steps": 2, + }, # 从5到3,向上2步 + { + "pos_seen": 7, + "expected_direction": "down", + "expected_steps": 2, + }, # 从5到7,向下2步 + { + "pos_seen": 5, + "expected_direction": "none", + "expected_steps": 0, + }, # 已在目标位置 + { + "pos_seen": 1, + "expected_direction": "up", + "expected_steps": 4, + }, # 从5到1,向上4步 ] for i, case in enumerate(test_cases): @@ -185,7 +209,9 @@ def test_reservation_backtrack(): if direction == case["expected_direction"] and steps == case["expected_steps"]: print(f" ✓ 方向: {direction}, 步数: {steps}") else: - print(f" ✗ 期望: {case['expected_direction']}/{case['expected_steps']}, 实际: {direction}/{steps}") + print( + f" ✗ 期望: {case['expected_direction']}/{case['expected_steps']}, 实际: {direction}/{steps}" + ) print("✓ 测试2通过:位置计算和回退方向正确") @@ -240,10 +266,14 @@ def test_reservation_backtrack(): if result and analyser.room_pos == 3: print("✓ 测试3通过:成功回退到目标直播间") - print(f" 滑动统计: 向上{analyser.swipe_up_count}次, 向下{analyser.swipe_down_count}次") + print( + f" 滑动统计: 向上{analyser.swipe_up_count}次, 向下{analyser.swipe_down_count}次" + ) else: print("✗ 测试3失败:回退失败") - print(f" 当前位置: {analyser.room_pos}, 目标位置: {test_reservations[0]['pos_seen']}") + print( + f" 当前位置: {analyser.room_pos}, 目标位置: {test_reservations[0]['pos_seen']}" + ) # 测试4:回退校验 print("\n测试4:回退校验") @@ -260,8 +290,11 @@ def test_reservation_backtrack(): # 替换实际函数 import douyin.fudai.douyin_fudai_detail + original_func = douyin.fudai.douyin_fudai_detail.read_live_room_title_core - douyin.fudai.douyin_fudai_detail.read_live_room_title_core = mock_read_live_room_title_core + douyin.fudai.douyin_fudai_detail.read_live_room_title_core = ( + mock_read_live_room_title_core + ) try: # 测试校验通过的情况 @@ -317,4 +350,4 @@ def test_reservation_backtrack(): if __name__ == "__main__": - test_reservation_backtrack() \ No newline at end of file + test_reservation_backtrack() diff --git a/test_reservation_error_scenarios.py b/test_reservation_error_scenarios.py index 3f21dc9..87bdf42 100644 --- a/test_reservation_error_scenarios.py +++ b/test_reservation_error_scenarios.py @@ -33,14 +33,14 @@ from douyin.reservation.douyin_reservation_verify import validate_back_to_reserv class MockOperation: """模拟操作对象""" - + def __init__(self): self.mock_ocr_result = "美女主播在线" # 默认OCR结果 - + def get_screenshot(self, device_id): """模拟截图""" pass - + def analyse_pic_word(self, cut_name, change_color): """模拟OCR识别""" return self.mock_ocr_result @@ -179,26 +179,22 @@ def test_error_scenarios(): print("=" * 80) test_cases = [ - { - "name": "正常情况", - "scenario": None, - "description": "无错误情况下的正常回退" - }, + {"name": "正常情况", "scenario": None, "description": "无错误情况下的正常回退"}, { "name": "滑动失败", "scenario": "swipe_failure", - "description": "模拟滑动操作随机失败" + "description": "模拟滑动操作随机失败", }, { "name": "位置更新失败", "scenario": "position_update_failure", - "description": "模拟位置更新随机失败" + "description": "模拟位置更新随机失败", }, { "name": "组合错误", "scenario": "combined_errors", - "description": "同时模拟滑动和位置更新错误" - } + "description": "同时模拟滑动和位置更新错误", + }, ] # 测试预约项 @@ -240,8 +236,12 @@ def test_error_scenarios(): # 输出结果 print(f"回退结果: {'成功' if result else '失败'}") print(f"最终位置: {analyser.room_pos}") - print(f"滑动统计: 向上{analyser.swipe_up_count}次, 向下{analyser.swipe_down_count}次") - print(f"错误统计: 滑动失败{analyser.swipe_failures}次, 位置更新失败{analyser.position_update_failures}次") + print( + f"滑动统计: 向上{analyser.swipe_up_count}次, 向下{analyser.swipe_down_count}次" + ) + print( + f"错误统计: 滑动失败{analyser.swipe_failures}次, 位置更新失败{analyser.position_update_failures}次" + ) print(f"执行时间: {end_time - start_time:.2f}秒") # 验证结果 if result and analyser.room_pos == test_reservation["pos_seen"]: @@ -307,7 +307,7 @@ def test_error_scenarios(): # 修改映射表,使当前位置的标题与预约记录不一致 analyser._room_pos_to_title_map[2] = ("错误的直播间", "错误的直播间") - + # 设置OCR识别结果为错误的标题 analyser.operation.mock_ocr_result = "错误的直播间" @@ -324,4 +324,4 @@ def test_error_scenarios(): if __name__ == "__main__": - test_error_scenarios() \ No newline at end of file + test_error_scenarios() diff --git a/test_reservation_verify.py b/test_reservation_verify.py index 1a968b0..8934c33 100644 --- a/test_reservation_verify.py +++ b/test_reservation_verify.py @@ -28,7 +28,10 @@ import os # 添加项目根目录到路径 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -from douyin.reservation.douyin_reservation_verify import validate_back_to_reservation, match_reservation +from douyin.reservation.douyin_reservation_verify import ( + validate_back_to_reservation, + match_reservation, +) from douyin.reservation.douyin_reservation_logic import ReservationItem @@ -72,8 +75,11 @@ def test_reservation_verify(): # 模拟替换实际的读取函数 import douyin.fudai.douyin_fudai_detail + original_func = douyin.fudai.douyin_fudai_detail.read_live_room_title_core - douyin.fudai.douyin_fudai_detail.read_live_room_title_core = mock_read_live_room_title_core + douyin.fudai.douyin_fudai_detail.read_live_room_title_core = ( + mock_read_live_room_title_core + ) try: # 测试1:基本校验通过 @@ -90,9 +96,7 @@ def test_reservation_verify(): } # 设置运行时映射表 - analyser._room_pos_to_title_map = { - 1: ("测试直播间", "测试直播间") - } + analyser._room_pos_to_title_map = {1: ("测试直播间", "测试直播间")} result, detail = validate_back_to_reservation(analyser, reservation_item) print(f"校验结果: {result}") @@ -113,7 +117,9 @@ def test_reservation_verify(): """模拟读取到错误的直播间标题""" return "完全不同的直播间名称", "完全不同的直播间名称" - douyin.fudai.douyin_fudai_detail.read_live_room_title_core = mock_read_live_room_title_core_wrong + douyin.fudai.douyin_fudai_detail.read_live_room_title_core = ( + mock_read_live_room_title_core_wrong + ) result, detail = validate_back_to_reservation(analyser, reservation_item) print(f"校验结果: {result}") @@ -150,14 +156,16 @@ def test_reservation_verify(): # 模拟福袋详情 detail_tuple = ( "测试福袋", # content - "05:00", # time_text - 100, # participants - 10, # copies - 100.0, # prize_value_yuan - (time.time(), time.time() + 300) # countdown_tuple + "05:00", # time_text + 100, # participants + 10, # copies + 100.0, # prize_value_yuan + (time.time(), time.time() + 300), # countdown_tuple ) - match_result, reason, debug_info = match_reservation(reservation_item, detail_tuple) + match_result, reason, debug_info = match_reservation( + reservation_item, detail_tuple + ) print(f"匹配结果: {match_result}") print(f"原因: {reason}") print(f"调试信息: {debug_info}") @@ -176,14 +184,16 @@ def test_reservation_verify(): # 模拟不匹配的福袋详情 detail_tuple_mismatch = ( "不同的福袋", # content - "05:00", # time_text - 100, # participants - 10, # copies - 200.0, # prize_value_yuan (不匹配) - (time.time(), time.time() + 600) # countdown_tuple (时间不匹配) + "05:00", # time_text + 100, # participants + 10, # copies + 200.0, # prize_value_yuan (不匹配) + (time.time(), time.time() + 600), # countdown_tuple (时间不匹配) ) - match_result, reason, debug_info = match_reservation(reservation_item, detail_tuple_mismatch) + match_result, reason, debug_info = match_reservation( + reservation_item, detail_tuple_mismatch + ) print(f"匹配结果: {match_result}") print(f"原因: {reason}") print(f"调试信息: {debug_info}") @@ -197,14 +207,16 @@ def test_reservation_verify(): # 模拟观看任务的福袋详情 watch_task_detail = ( "观看5分钟领取福袋奖励", # content - "05:00", # time_text - 100, # participants - 10, # copies - 100.0, # prize_value_yuan - (time.time(), time.time() + 300) # countdown_tuple + "05:00", # time_text + 100, # participants + 10, # copies + 100.0, # prize_value_yuan + (time.time(), time.time() + 300), # countdown_tuple ) - match_result, reason, debug_info = match_reservation(reservation_item, watch_task_detail) + match_result, reason, debug_info = match_reservation( + reservation_item, watch_task_detail + ) print(f"匹配结果: {match_result}") print(f"原因: {reason}") print(f"调试信息: {debug_info}") @@ -218,7 +230,9 @@ def test_reservation_verify(): print("\n测试7:预约队列排序") print("-" * 30) - from douyin.reservation.douyin_reservation_logic import _sort_reservations_inplace + from douyin.reservation.douyin_reservation_logic import ( + _sort_reservations_inplace, + ) reservations = [ { @@ -240,18 +254,24 @@ def test_reservation_verify(): print("排序前:") for i, r in enumerate(reservations): - print(f" {i+1}. 时间: {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元") + print( + f" {i+1}. 时间: {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元" + ) _sort_reservations_inplace(reservations) print("排序后:") for i, r in enumerate(reservations): - print(f" {i+1}. 时间: {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元") + print( + f" {i+1}. 时间: {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元" + ) # 验证排序:时间优先,其次价值 expected_order = [1, 2, 0] # 索引顺序 - if (reservations[0]["future_ts"] <= reservations[1]["future_ts"] and - reservations[1]["future_ts"] <= reservations[2]["future_ts"]): + if ( + reservations[0]["future_ts"] <= reservations[1]["future_ts"] + and reservations[1]["future_ts"] <= reservations[2]["future_ts"] + ): print("✓ 测试7通过:预约队列排序正确") else: print("✗ 测试7失败:预约队列排序不正确") @@ -262,4 +282,4 @@ def test_reservation_verify(): if __name__ == "__main__": - test_reservation_verify() \ No newline at end of file + test_reservation_verify()