diff --git a/MD_FILE_FIX_GUIDE.md b/MD_FILE_FIX_GUIDE.md deleted file mode 100644 index 167d9d2..0000000 --- a/MD_FILE_FIX_GUIDE.md +++ /dev/null @@ -1,72 +0,0 @@ -# Markdown文件修复指南 - -## 问题诊断 - -如果遇到 "无法打开 MODULARIZATION SUMMARY.md" 或 "Assertion Failed: Argument is 'undefined' or 'null" 错误,这通常是IDE的文件名解析问题。 - -## 已完成的修复 - -✅ 所有33个Markdown文件已统一为UTF-8编码(无BOM) -✅ 移除了所有BOM标记 -✅ 确保文件格式正确 - -## 解决方案 - -### 方案1:重启IDE -1. 完全关闭IDE(VS Code / Cursor) -2. 重新打开IDE -3. 重新打开项目 - -### 方案2:清除IDE缓存 -1. 关闭IDE -2. 删除以下目录(如果存在): - - `.vscode/` 目录 - - `.cursor/` 目录中的缓存文件 -3. 重新打开项目 - -### 方案3:手动打开文件 -1. 在文件资源管理器中找到文件 -2. 右键点击 `MODULARIZATION_SUMMARY.md` -3. 选择"打开方式" → 选择你的IDE - -### 方案4:检查文件路径 -确保文件路径中没有特殊字符或空格: -- ✅ 正确:`MODULARIZATION_SUMMARY.md` -- ❌ 错误:`MODULARIZATION SUMMARY.md`(有空格) - -### 方案5:重新索引项目 -在IDE中: -1. 打开命令面板(Ctrl+Shift+P) -2. 运行 "Reload Window" 或 "Developer: Reload Window" -3. 或者运行 "File: Reopen Folder" - -## 验证文件是否正常 - -运行以下命令检查文件: -```bash -python check_md_files.py -``` - -如果所有文件显示 `[OK]`,说明文件本身没有问题。 - -## 如果问题仍然存在 - -1. 检查IDE的日志文件,查看具体错误信息 -2. 尝试用其他编辑器(如Notepad++)打开文件,确认文件本身没问题 -3. 检查文件权限,确保有读取权限 -4. 如果是在Windows上,检查文件名是否包含保留字符 - -## 文件列表 - -已修复的主要Markdown文件: -- `MODULARIZATION_SUMMARY.md` - 模块化工作总结 -- `README.md` - 项目主文档 -- `douyin/README.md` - 核心模块文档 -- `douyin/fudai/core/MODULARIZATION_PLAN.md` - 模块化计划 -- `docs/` 目录下的所有文档 - -所有文件现在都使用UTF-8编码,应该可以在任何现代编辑器中正常打开。 - - - - diff --git a/Underlying_Operations.py b/Underlying_Operations.py index 4af5b7a..b61d70f 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -220,6 +220,8 @@ class underlying_operations: # 支持延迟初始化(测试流程/只做点击时不需要 OCR)。 self.ocr: Any = None self.ocr_type = None # 'easyocr' 或 'paddleocr' + # 用于存储OCR区域的坐标信息(key为picname,value为(left, top, right, bottom)) + self._ocr_coords_cache: dict[str, tuple[int, int, int, int]] = {} # 检测GPU是否可用(自动检测) self._gpu_available = self._detect_gpu_available() @@ -495,8 +497,12 @@ class underlying_operations: Returns: 图片的完整路径,如果找不到且for_reading=True则返回None """ - base_dir = os.path.dirname(__file__) - pic_base = os.path.join(base_dir, "pic") + try: + import path_config + pic_base = path_config.get_pic_dir() + except Exception: + import path_config + pic_base = path_config.get_pic_dir() # 运行时必需文件始终在根目录(不需要移动) runtime_files = {"screenshot", "cut"} @@ -536,7 +542,12 @@ class underlying_operations: def get_screenshot(self, device_id, path="pic"): """截图3个adb命令需要2S左右的时间""" if path == "pic": - out_dir = os.path.join(os.path.dirname(__file__), "pic") + try: + import path_config + out_dir = path_config.get_pic_dir() + except Exception: + import path_config + out_dir = path_config.get_pic_dir() else: out_dir = os.path.join(os.path.dirname(__file__), "target_pic") if not os.path.exists(out_dir): @@ -756,7 +767,12 @@ class underlying_operations: raise ValueError("Could not find resolution in adb output") def save_reward_pic(self, device_id): - out_dir = os.path.join(os.path.dirname(__file__), "pic") + try: + import path_config + out_dir = path_config.get_pic_dir() + except Exception: + import path_config + out_dir = path_config.get_pic_dir() if not os.path.exists(out_dir): os.makedirs(out_dir) timepic = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") @@ -891,6 +907,13 @@ class underlying_operations: except Exception: logging.exception("保存裁剪图片失败: %s", cut_pic_path) + # 存储坐标信息供analyse_pic_word使用 + if name: + try: + self._ocr_coords_cache[name] = (left, top, right, bottom) + except Exception: + pass + # 双截图记录:保存实时操作截图 try: from douyin.handlers import douyin_screenshot_manager @@ -899,9 +922,10 @@ class underlying_operations: cropped_img, operation_type="cut_pic" ) - # 保存调试图像(带详细信息) + # 保存调试图像(完整截图+区域标注) + pic_rgb = pic.convert("RGB") debug_path = douyin_screenshot_manager.save_debug_image( - cropped_img, + pic_rgb, operation_type="cut_pic", picname=name if name else "cut", step="before_ocr", @@ -987,12 +1011,20 @@ class underlying_operations: logging.exception("保存裁剪图片失败: %s", cut_pic_path) return False - # 保存调试图像 + # 存储坐标信息供analyse_pic_word使用 + if name: + try: + self._ocr_coords_cache[name] = (left, top, right, bottom) + except Exception: + pass + + # 保存调试图像(完整截图+区域标注) try: from douyin.handlers import douyin_screenshot_manager + pic_rgb = pic.convert("RGB") debug_path = douyin_screenshot_manager.save_debug_image( - cropped_img, + pic_rgb, operation_type="cut_pic", picname=name if name else "cut", step="before_ocr", @@ -1089,19 +1121,43 @@ class underlying_operations: except Exception: img1 = img # Fallback to original image - # 保存预处理后的调试图像(OCR前) + # 保存预处理后的调试图像(OCR前)- 使用完整截图 try: from douyin.handlers import douyin_screenshot_manager + import path_config + # 尝试获取OCR区域坐标 + ocr_coords = None + try: + ocr_coords = self._ocr_coords_cache.get(picname) + except Exception: + pass + + # 加载完整截图 + full_screenshot = None + try: + screenshot_path = path_config.get_screenshot_path() + if os.path.exists(screenshot_path): + full_screenshot = Image.open(screenshot_path) + full_screenshot.load() + full_screenshot = full_screenshot.convert("RGB") + except Exception: + pass + + # 如果成功加载完整截图,使用完整截图;否则使用预处理图像 + debug_image = full_screenshot if full_screenshot is not None else img1 debug_path = douyin_screenshot_manager.save_debug_image( - img1, + debug_image, operation_type="ocr", picname=picname, step="preprocessed", + coords=ocr_coords, extra_info={ "mode": change_color, "size": f"{w}x{h}", "source": pic_path if pic_path else picname, + "has_full_screenshot": full_screenshot is not None, + "has_coords": ocr_coords is not None, }, ) if debug_path: @@ -1202,7 +1258,7 @@ class underlying_operations: img_for_attempt, operation_type="ocr" ) - # 保存OCR结果后的调试图像(带OCR文本结果和置信度) + # 保存OCR结果后的调试图像(带OCR文本结果和置信度)- 使用完整截图 ocr_result_preview = ( (text or text2 or "").strip()[:50] if (text or text2) else "" ) @@ -1227,11 +1283,36 @@ class underlying_operations: "item_count", 0 ) + # 尝试获取OCR区域坐标 + ocr_coords = None + try: + ocr_coords = self._ocr_coords_cache.get(picname) + except Exception: + pass + + # 加载完整截图 + full_screenshot = None + try: + import path_config + screenshot_path = path_config.get_screenshot_path() + if os.path.exists(screenshot_path): + full_screenshot = Image.open(screenshot_path) + full_screenshot.load() + full_screenshot = full_screenshot.convert("RGB") + except Exception: + pass + + # 如果成功加载完整截图,使用完整截图;否则使用预处理图像 + debug_image = full_screenshot if full_screenshot is not None else img_for_attempt + extra_info_dict["has_full_screenshot"] = full_screenshot is not None + extra_info_dict["has_coords"] = ocr_coords is not None + debug_path = douyin_screenshot_manager.save_debug_image( - img_for_attempt, + debug_image, operation_type="ocr", picname=picname, step="after_ocr", + coords=ocr_coords, extra_info=extra_info_dict, ) @@ -1358,29 +1439,172 @@ class underlying_operations: # 锐化处理,提高数字识别准确率 from PIL import ImageEnhance + img1 = img try: img_sharpened = img.filter( ImageFilter.UnsharpMask(radius=1, percent=200, threshold=3) ) enhancer = ImageEnhance.Contrast(img_sharpened) - img = enhancer.enhance(1.3) # 更高的对比度 + img1 = enhancer.enhance(1.3) # 更高的对比度 except Exception: try: - img = img.filter(ImageFilter.SHARPEN) + img1 = img.filter(ImageFilter.SHARPEN) + except Exception: + img1 = img # Fallback to original image + + # 保存预处理后的调试图像(OCR前)- 使用完整截图 + try: + from douyin.handlers import douyin_screenshot_manager + import path_config + + # 尝试获取OCR区域坐标 + ocr_coords = None + try: + ocr_coords = self._ocr_coords_cache.get(picname) except Exception: pass - img_np = np.array(img) + # 加载完整截图 + full_screenshot = None + try: + screenshot_path = path_config.get_screenshot_path() + if os.path.exists(screenshot_path): + full_screenshot = Image.open(screenshot_path) + full_screenshot.load() + full_screenshot = full_screenshot.convert("RGB") + except Exception: + pass + + # 如果成功加载完整截图,使用完整截图;否则使用预处理图像 + debug_image = full_screenshot if full_screenshot is not None else img1 + debug_path = douyin_screenshot_manager.save_debug_image( + debug_image, + operation_type="ocr", + picname=picname, + step="preprocessed", + coords=ocr_coords, + extra_info={ + "mode": change_color, + "size": f"{w}x{h}", + "source": pic_path if pic_path else picname, + "has_full_screenshot": full_screenshot is not None, + "has_coords": ocr_coords is not None, + "type": "digits", + }, + ) + if debug_path: + try: + logging.info(f"[调试图像] OCR数字预处理保存: {debug_path}") + except Exception: + pass + except Exception: + pass + + img_np = np.array(img1) # 使用OCR识别(与analyse_pic_word相同的OCR引擎) + ocr_confidence_info = None if getattr(self, "ocr_type", None) == "easyocr": result = self.ocr.readtext(img_np) - text = self.extract_ocr_content(result) + extract_result = self.extract_ocr_content(result, return_confidence=True) + if isinstance(extract_result, tuple): + text, ocr_confidence_info = extract_result + else: + text = extract_result else: result = self.ocr.ocr(img_np) if result == [None]: return "" - text = self.extract_ocr_content(result) + extract_result = self.extract_ocr_content(result, return_confidence=True) + if isinstance(extract_result, tuple): + text, ocr_confidence_info = extract_result + else: + text = extract_result + + # 保存OCR结果后的调试图像(带OCR文本结果和置信度)- 使用完整截图 + try: + from douyin.handlers import douyin_screenshot_manager + import path_config + + # 尝试获取OCR区域坐标 + ocr_coords = None + try: + ocr_coords = self._ocr_coords_cache.get(picname) + except Exception: + pass + + # 加载完整截图 + full_screenshot = None + try: + screenshot_path = path_config.get_screenshot_path() + if os.path.exists(screenshot_path): + full_screenshot = Image.open(screenshot_path) + full_screenshot.load() + full_screenshot = full_screenshot.convert("RGB") + except Exception: + pass + + # 如果成功加载完整截图,使用完整截图;否则使用预处理图像 + debug_image = full_screenshot if full_screenshot is not None else img1 + + # 准备额外信息 + digits_result = "" + if text: + digits_result = "".join(ch for ch in str(text) if ch.isdigit()) + + extra_info_dict = { + "mode": change_color, + "text_len": len(text or ""), + "digits": digits_result, + "type": "digits", + } + # 添加置信度信息 + if ocr_confidence_info: + extra_info_dict["avg_confidence"] = round( + ocr_confidence_info.get("avg_confidence", 0.0), 4 + ) + extra_info_dict["min_confidence"] = round( + ocr_confidence_info.get("min_confidence", 0.0), 4 + ) + extra_info_dict["max_confidence"] = round( + ocr_confidence_info.get("max_confidence", 0.0), 4 + ) + extra_info_dict["confidence_items"] = ocr_confidence_info.get( + "item_count", 0 + ) + extra_info_dict["has_full_screenshot"] = full_screenshot is not None + extra_info_dict["has_coords"] = ocr_coords is not None + + debug_path = douyin_screenshot_manager.save_debug_image( + debug_image, + operation_type="ocr", + picname=picname, + step="after_ocr", + coords=ocr_coords, + extra_info=extra_info_dict, + ) + + # 记录OCR置信度到日志 + if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0: + try: + logging.info( + f"[OCR置信度] {picname}: " + f"平均={ocr_confidence_info.get('avg_confidence', 0.0):.4f}, " + f"最小={ocr_confidence_info.get('min_confidence', 0.0):.4f}, " + f"最大={ocr_confidence_info.get('max_confidence', 0.0):.4f}, " + f"项目数={ocr_confidence_info.get('item_count', 0)}" + ) + except Exception: + pass + if debug_path: + try: + logging.info( + f"[调试图像] OCR数字结果保存: {debug_path}, 数字: {digits_result}" + ) + except Exception: + pass + except Exception: + pass # 只提取数字字符,并进行智能过滤 if text: @@ -1817,14 +2041,14 @@ class underlying_operations: left_up_y=0, right_down_x=1080, right_down_y=1500, - steps=200, + steps=300, ): """划动屏幕 参数说明: - left_up_x, left_up_y: 滑动起始位置(手指按下位置) - right_down_x, right_down_y: 滑动结束位置(手指抬起位置) - - steps: 滑动步数(影响滑动速度,数值越大滑动越慢) + - steps: 滑动持续时间(毫秒),数值越大滑动越慢,默认300ms(已优化,比之前的200ms更快) 执行命令:adb shell input swipe """ @@ -2401,7 +2625,12 @@ class underlying_operations: if not text: return False - local_path = os.path.join(os.path.dirname(__file__), "pic", "window_dump.xml") + try: + import path_config + local_path = path_config.get_window_dump_path() + except Exception: + import path_config + local_path = path_config.get_window_dump_path() start = time.time() while True: if self._uiautomator_dump(device_id, local_path): @@ -2447,7 +2676,12 @@ class underlying_operations: 逻辑:从 uiautomator dump 里找顶部(较小 y)的可点击小图标,优先命中 content-desc/text 含“关闭/退出/返回”。 如果没有文字,就在顶部区域按“最像关闭”的位置进行启发式选择。 """ - local_path = os.path.join(os.path.dirname(__file__), "pic", "window_dump.xml") + try: + import path_config + local_path = path_config.get_window_dump_path() + except Exception: + import path_config + local_path = path_config.get_window_dump_path() start = time.time() def _score(node_attrib: dict, bounds_tuple) -> int: diff --git a/config.json b/config.json index 7b9d245..75c1833 100644 --- a/config.json +++ b/config.json @@ -1,5 +1,5 @@ { - "needswitch": false, + "needswitch": true, "infinite_loop_enabled": true, "wait_minutes": 5, "y_pianyi": 0, diff --git a/config/config.json b/config/config.json index 5dc3295..c321ff4 100644 --- a/config/config.json +++ b/config/config.json @@ -1,5 +1,5 @@ { - "needswitch": true, + "needswitch": false, "infinite_loop_enabled": true, "wait_minutes": 5, "min_prize_value_yuan": 200.0, @@ -19,7 +19,7 @@ "high_value_room_revisit_enabled": true, "high_value_room_revisit_only_current_run": true, "reservation_back_verify_enabled": true, - "reservation_back_swipe_delay": 0.5, + "reservation_back_swipe_delay": 0.1, "reservation_preempt_min_value": 0.0, "desktop_icon_x": 153, "desktop_icon_y": 260, @@ -31,6 +31,10 @@ "fudai_icon_retry_delay_seconds": 0.1, "fudai_icon_max_wait_seconds": 8.5, "fudai_click_wait_seconds": 1.7, + "fudai_detail_initial_wait_seconds": 0.8, + "fudai_detail_verified_wait_seconds": 0.2, + "fudai_detail_retry_delay_seconds": 0.5, + "fudai_detail_save_debug_images": false, "yanghao_recommend_duration_seconds": 206, "yanghao_recommend_interval_seconds": 570, "yanghao_like_prob": 1.0, @@ -45,7 +49,8 @@ "yanghao_fav_roi_offset_y": 0, "contains_want": [], "contains_not_want": [ - "首饰盒" + "首饰盒", + "袜子" ], "fudai_quiet_hours_enabled": true, "fudai_quiet_start_hour": 2, @@ -105,5 +110,7 @@ "coupon_template_match_threshold": 0.4, "attend_button_red_ratio_threshold": 0.25, "fansclub_join_red_ratio_threshold": 0.25, - "reservation_test_mode": false + "reservation_test_mode": false, + "swipe_duration_ms": 600, + "enable_whole_detail_ocr": true } diff --git a/config/pyrightconfig.json b/config/pyrightconfig.json index 11e8f89..5ac3e26 100644 --- a/config/pyrightconfig.json +++ b/config/pyrightconfig.json @@ -10,6 +10,7 @@ "reportPrivateImportUsage": false, "reportUnusedImport": "warning", "reportUnusedVariable": "warning", + "reportUnusedArgument": "none", "reportUnknownArgumentType": false, "reportUnknownLambdaType": false, "reportMissingTypeArgument": false, @@ -44,6 +45,8 @@ "reportPrivateUsage": false, "reportConstantRedefinition": false, "reportDeprecated": false, + "reportTooManyExceptionHandlers": false, + "reportTooBroadExceptionType": false, "typeCheckingMode": "basic", "stubPath": "./typings", "include": ["."], diff --git a/douyin/core/douyin_flow_control.py b/douyin/core/douyin_flow_control.py index 24385ae..59e9518 100644 --- a/douyin/core/douyin_flow_control.py +++ b/douyin/core/douyin_flow_control.py @@ -167,15 +167,38 @@ def find_and_open_fudai_detail( ) check_interval = 0.2 # 每次检测间隔(秒) + try: + analyser._log_kv( + "流程", + "find_and_open_fudai_detail:开始智能等待", + min_wait_seconds=min_wait_seconds, + max_wait_seconds=max_wait_seconds, + check_interval=check_interval, + ) + except Exception: + pass + # 先等待最小时间 analyser.operation.delay(min_wait_seconds) + try: + analyser._log_kv( + "流程", + "find_and_open_fudai_detail:最小等待时间已过,开始循环检测", + elapsed_seconds=min_wait_seconds, + ) + except Exception: + pass + # 智能等待:循环检测详情页是否已打开 from douyin.stage import douyin_stage wait_start = time.time() detail_opened = False + check_count = 0 while (time.time() - wait_start) < (max_wait_seconds - min_wait_seconds): + check_count += 1 + elapsed_in_loop = time.time() - wait_start try: analyser.operation.get_screenshot(device_id) pic_path = path_config.get_screenshot_path() @@ -183,7 +206,19 @@ def find_and_open_fudai_detail( # 快速检测是否已在详情页(只检测关键特征,不执行完整阶段诊断) result = douyin_stage.diagnose_stage_from_current_screen(analyser) if result is not None: - stage, _ = result + stage, reason = result + try: + analyser._log_kv( + "流程", + "find_and_open_fudai_detail:智能等待检测中", + check_count=check_count, + elapsed_in_loop=round(elapsed_in_loop, 2), + total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2), + current_stage=stage, + reason=reason[:50] if reason else "", + ) + except Exception: + pass if stage == "FUDai_DETAIL": detail_opened = True elapsed_wait = time.time() - wait_start @@ -191,13 +226,49 @@ def find_and_open_fudai_detail( analyser._log_kv( "流程", "find_and_open_fudai_detail:智能等待检测到详情页已打开", + check_count=check_count, wait_seconds=round(elapsed_wait + min_wait_seconds, 2), + elapsed_in_loop=round(elapsed_wait, 2), ) except Exception: pass break - except Exception: - pass + else: + try: + analyser._log_kv( + "流程", + "find_and_open_fudai_detail:智能等待检测中(阶段诊断返回None)", + check_count=check_count, + elapsed_in_loop=round(elapsed_in_loop, 2), + total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2), + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "流程", + "find_and_open_fudai_detail:智能等待检测中(截图文件不存在)", + check_count=check_count, + elapsed_in_loop=round(elapsed_in_loop, 2), + total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2), + pic_path=pic_path, + ) + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "流程", + "find_and_open_fudai_detail:智能等待检测中(检测异常)", + check_count=check_count, + elapsed_in_loop=round(elapsed_in_loop, 2), + total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2), + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass # 等待一小段时间后再次检测 try: @@ -205,6 +276,20 @@ def find_and_open_fudai_detail( except Exception: time.sleep(check_interval) + # 记录智能等待结束状态 + total_elapsed = time.time() - wait_start + min_wait_seconds + if not detail_opened: + try: + analyser._log_kv( + "流程", + "find_and_open_fudai_detail:智能等待超时,未检测到详情页", + check_count=check_count, + total_elapsed=round(total_elapsed, 2), + max_wait_seconds=max_wait_seconds, + ) + except Exception: + pass + # 如果智能等待已检测到详情页,直接返回成功,无需再次检测 if detail_opened: # 清除第一次读取标志,确保新打开的福袋会进行完整的OCR识别 diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index bdc1ff6..8fe8656 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -73,7 +73,12 @@ class fudai_analyse( # 运行配置(只保留与你当前需求直接相关的主流程字段,细节统一放在各子模块内部) self.operation = underlying_operations() - self.config_path = "config/config.json" + try: + import path_config + self.config_path = path_config.get_config_path() + except Exception: + import path_config + self.config_path = path_config.get_config_path() # 日志相关字段:完全独立的日志系统(不依赖原始代码) try: @@ -92,6 +97,31 @@ class fudai_analyse( self._last_log_tag = None # 预定义可在运行中动态创建的属性,避免 access-before-definition / attribute-defined-outside-init 警告 self._std_logger = None # type: ignore[assignment] + # 后台 tick:供等待循环期间执行轻量后台任务(可被覆盖) + # 示例用途:在等待直播间标题出现时处理弹窗、更新小状态等 + def _default_background_tick(): + try: + # 处理优惠券弹窗(如果存在) + if hasattr(self, "_check_coupon_popup") and callable(getattr(self, "_check_coupon_popup")): + try: + self._check_coupon_popup() + except Exception: + pass + # 处理购物红包弹窗(如果存在) + if hasattr(self, "_check_shopping_redpacket_popup") and callable(getattr(self, "_check_shopping_redpacket_popup")): + try: + self._check_shopping_redpacket_popup() + except Exception: + pass + except Exception: + pass + + # 绑定为实例方法 + try: + self.background_tick = _default_background_tick # type: ignore[assignment] + except Exception: + # 若绑定失败,保证属性存在 + self.background_tick = lambda: None # type: ignore[assignment] # 初始化统一日志系统和traceId # 确保日志系统已配置(在实例化之前) @@ -247,9 +277,14 @@ class fudai_analyse( self.queue_full_waiting_at_earliest: bool = False # 预约队列状态文件(供 WebGUI / 其他进程查看) - self._reservations_state_path: str = os.path.join( - os.path.dirname(__file__), "state", "reservations.json" - ) + try: + import path_config + self._reservations_state_path: str = path_config.get_reservations_path() + except Exception: + # 回退到旧路径(向后兼容) + self._reservations_state_path: str = os.path.join( + os.path.dirname(__file__), "state", "reservations.json" + ) # 运行时直播间标题和位置映射表(用于回退校验) # 格式:{room_pos: (room_title, room_title_raw)} @@ -311,10 +346,21 @@ class fudai_analyse( start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] try: - actions_log_path = os.path.join( - os.path.dirname(__file__), "logs", "actions.log" - ) - log_dir = os.path.dirname(actions_log_path) + try: + import path_config + actions_log_path = path_config.get_actions_log_path() + log_dir = path_config.get_logs_dir() + except Exception: + # 回退到旧路径(向后兼容) + try: + import path_config + actions_log_path = path_config.get_actions_log_path() + log_dir = path_config.get_logs_dir() + except Exception: + actions_log_path = os.path.join( + os.path.dirname(__file__), "logs", "actions.log" + ) + log_dir = os.path.dirname(actions_log_path) if log_dir: os.makedirs(log_dir, exist_ok=True) with open( @@ -371,10 +417,16 @@ class fudai_analyse( end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] - actions_log_path = os.path.join( - os.path.dirname(__file__), "logs", "actions.log" - ) - log_dir = os.path.dirname(actions_log_path) + try: + import path_config + actions_log_path = path_config.get_actions_log_path() + log_dir = path_config.get_logs_dir() + except Exception: + # 回退到旧路径(向后兼容) + actions_log_path = os.path.join( + os.path.dirname(__file__), "logs", "actions.log" + ) + log_dir = os.path.dirname(actions_log_path) if log_dir: os.makedirs(log_dir, exist_ok=True) with open( @@ -499,7 +551,23 @@ class fudai_analyse( from douyin.reservation import douyin_reservation_logic # 确保在函数作用域内可用 start_time = time.time() - # 0. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果 + + # 0.1. 优先检查预约回退直接参与标志(避免陷入循环) + reservation_direct_attend = getattr(self, "_reservation_back_direct_attend", False) + if reservation_direct_attend: + try: + self._log_kv( + "预约", + "[预约] 检测到预约回退直接参与标志,立即执行参与逻辑", + reservation_direct_attend=reservation_direct_attend, + ) + except Exception: + pass + # 执行直接参与逻辑(跳过其他检查) + self._handle_reservation_direct_attend() + return + + # 0.2. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果 if getattr(self, "_waiting_for_lottery_result", False): try: # 检查是否有高价值预约需要处理(除非遇到高价值预约,否则应该等待福袋开奖) @@ -782,31 +850,24 @@ class fudai_analyse( # 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间" try: - # 每次开始运行时丢弃旧的预约队列,不加载状态文件 + # 从状态文件加载预约队列,保持预约记录的持久化 try: + # 检查是否已经初始化预约队列 + if not hasattr(self, "reservations") or self.reservations is None: + self.reservations = [] - # 如果是第一次运行,清空预约队列,不加载状态文件 + # 如果是第一次运行,从状态文件加载预约队列 is_first_run = getattr(self, "_first_run_once_basic", True) - # 记录清空前的队列状态(用于调试) - old_reservations_count = 0 - try: - old_reservations_count = ( - len(self.reservations) - if hasattr(self, "reservations") and self.reservations - else 0 - ) - except Exception: - pass if is_first_run: try: self._log_kv( "预约", - "[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件", - old_reservations_count=old_reservations_count, + "[预约] 第一次运行:清空预约队列,确保每次启动都是干净状态", ) except Exception: pass + # 清空预约队列(强制清空,确保每次启动时队列为空) try: # 先记录清空前的状态 @@ -824,7 +885,6 @@ class fudai_analyse( # 同时清空状态文件,确保外部查看时也是空的 try: - state_path = getattr(self, "_reservations_state_path", None) if state_path: # 写入空队列到状态文件 @@ -870,13 +930,14 @@ class fudai_analyse( ) except Exception: pass + # 标记已运行过 try: self._first_run_once_basic = False except Exception: pass else: - # 如果不是第一次运行,也记录日志(用于调试) + # 如果不是第一次运行,保持当前内存中的预约队列 try: current_count = ( len(self.reservations) @@ -891,9 +952,6 @@ class fudai_analyse( ) except Exception: pass - - # 不再从状态文件加载预约数据,每次启动时都从空队列开始 - # 已移除从状态文件加载预约数据的逻辑,每次启动时预约队列为空 except Exception as exc: try: self._log_kv( @@ -2144,6 +2202,11 @@ class fudai_analyse( 次数=2, ) self.operation.delay(self.ENTER_LIVE_FINAL_DELAY) + # 标记刚刚切换直播间,后续读取标题时会等待标题出现 + try: + self._just_switched_room = True + except Exception: + pass except Exception as e: self._log_kv("流程", "处理推荐页面时出错", error=str(e)) # 如果出错,尝试回退 diff --git a/douyin/core/fudai_modules/base_interface.py b/douyin/core/fudai_modules/base_interface.py index 9124518..5e702e4 100644 --- a/douyin/core/fudai_modules/base_interface.py +++ b/douyin/core/fudai_modules/base_interface.py @@ -75,3 +75,8 @@ class BaseFudaiMixin: + + + + + diff --git a/douyin/core/fudai_modules/fudai_lottery_result.py b/douyin/core/fudai_modules/fudai_lottery_result.py index fa91df9..3a240c7 100644 --- a/douyin/core/fudai_modules/fudai_lottery_result.py +++ b/douyin/core/fudai_modules/fudai_lottery_result.py @@ -30,3 +30,8 @@ class LotteryResultMixin: + + + + + diff --git a/douyin/core/fudai_modules/fudai_room_utils.py b/douyin/core/fudai_modules/fudai_room_utils.py index abea3dc..35848c1 100644 --- a/douyin/core/fudai_modules/fudai_room_utils.py +++ b/douyin/core/fudai_modules/fudai_room_utils.py @@ -49,3 +49,8 @@ class RoomUtilsMixin: + + + + + diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index 3092cdb..4c0bf91 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,5 +1,5 @@ { - "updated_ts": 1766906682.4194293, + "updated_ts": 1766926120.0938337, "reason": "startup_clear", "room_pos": 0, "current_room_title": "", diff --git a/douyin/detection/core/__init__.py b/douyin/detection/core/__init__.py index 7d406a4..0a860ce 100644 --- a/douyin/detection/core/__init__.py +++ b/douyin/detection/core/__init__.py @@ -21,3 +21,8 @@ __all__ = [ + + + + + diff --git a/douyin/detection/douyin_detection.py b/douyin/detection/douyin_detection.py index a1e14c3..15adfd6 100644 --- a/douyin/detection/douyin_detection.py +++ b/douyin/detection/douyin_detection.py @@ -41,8 +41,8 @@ def check_detail_height(analyser: Any) -> int: pic1_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) - path = os.path.join(os.path.dirname(__file__), "pic") - pic1_path = os.path.join(path, "screenshot.png") + import path_config + pic1_path = path_config.get_screenshot_path() # 记录截图文件的时间戳(如果存在) screenshot_timestamp = None @@ -291,8 +291,8 @@ def check_have_fudai_with_ready_screenshot( pic1_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) - path = os.path.join(os.path.dirname(__file__), "pic") - pic1_path = os.path.join(path, "screenshot.png") + import path_config + pic1_path = path_config.get_screenshot_path() attempt_count = 0 # 仅用于日志记录,不影响循环控制 # ===== 像素检测版(优先使用),不依赖 OpenCV ===== @@ -1350,9 +1350,12 @@ def check_have_fudai_with_ready_screenshot( search_roi_pil, operation_type="template_match" ) - # 保存调试图像(匹配前) + # 保存调试图像(匹配前)- 使用完整截图 + screenshot_pil = PILImage.fromarray( + cv2.cvtColor(screenshot_img, cv2.COLOR_BGR2RGB) + ) debug_path = douyin_screenshot_manager.save_debug_image( - search_roi_pil, + screenshot_pil, operation_type="template_match", picname="fudai_icon", step="before_match", @@ -1405,14 +1408,33 @@ def check_have_fudai_with_ready_screenshot( search_roi_pil, operation_type="template_match" ) - # 保存带匹配结果的调试图像(带匹配框) - debug_path = douyin_screenshot_manager.save_debug_image_with_match_result( - search_roi_pil, + # 保存带匹配结果的调试图像(带匹配框)- 使用完整截图 + screenshot_pil = PILImage.fromarray( + cv2.cvtColor(screenshot_img, cv2.COLOR_BGR2RGB) + ) + # 计算匹配位置在完整截图中的坐标 + match_x_in_roi = max_loc[0] + match_y_in_roi = max_loc[1] + match_x1 = search_x1 + match_x_in_roi + match_y1 = search_y1 + match_y_in_roi + match_x2 = search_x1 + match_x_in_roi + tw + match_y2 = search_y1 + match_y_in_roi + th + match_coords = (match_x1, match_y1, match_x2, match_y2) + + debug_path = douyin_screenshot_manager.save_debug_image( + screenshot_pil, operation_type="template_match", - match_score=max_val, - match_location=max_loc, - template_size=(tw, th), - picname="fudai_icon" + picname="fudai_icon", + step="matched", + coords=(search_x1, search_y1, search_x2, search_y2), # 搜索区域坐标 + extra_info={ + "match_score": round(max_val, 4), + "match_location": f"({max_loc[0]},{max_loc[1]})", + "match_coords": match_coords, # 匹配位置坐标 + "template_size": f"{tw}x{th}", + "threshold": template_threshold, + "passed": True, + } ) if debug_path: try: diff --git a/douyin/detection/douyin_pixel.py b/douyin/detection/douyin_pixel.py index d529c21..3b32246 100644 --- a/douyin/detection/douyin_pixel.py +++ b/douyin/detection/douyin_pixel.py @@ -433,37 +433,39 @@ def detect_attend_button_red_area( } # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 - if result: - try: - from douyin.handlers import douyin_screenshot_manager + # 无论成功失败都保存debug截图 + try: + from douyin.handlers import douyin_screenshot_manager - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, # 使用全屏截图 - operation_type="pixel_detect", - picname="attend_button", - step="detected", - coords=(x1, y1, x2, y2), # 标注识别区域 - extra_info={ - "red_ratio": round(red_ratio, 4), - "red_count": red_count, - "total_samples": total_samples, - "result": "success", - }, - ) - if debug_path: - try: - import logging + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, # 使用全屏截图 + operation_type="pixel_detect", + picname="attend_button", + step="detected" if result else "not_detected", + coords=(x1, y1, x2, y2), # 标注识别区域 + extra_info={ + "red_ratio": round(red_ratio, 4), + "red_count": red_count, + "total_samples": total_samples, + "threshold": threshold, + "result": "success" if result else "failed", + }, + ) + if debug_path: + try: + import logging - logging.info( - "[调试图像] 参与按钮检测成功保存: %s, red_ratio=%.4f, score=%.4f", - debug_path, - red_ratio, - red_ratio, - ) - except Exception as e: # type: ignore[general-exception] - pass - except Exception as e: # type: ignore[general-exception] - pass + logging.info( + "[调试图像] 参与按钮检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s", + debug_path, + red_ratio, + threshold, + "success" if result else "failed", + ) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass return result except Exception: @@ -514,6 +516,31 @@ def detect_fansclub_join_red_area( } return False + # 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域 + try: + from douyin.handlers import douyin_screenshot_manager + + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, # 使用全屏截图 + operation_type="pixel_detect", + picname="fansclub_join", + step="before_detect", + coords=(x1, y1, x2, y2), # 标注识别区域 + extra_info={"region_size": f"{x2-x1}x{y2-y1}"}, + ) + if debug_path: + try: + import logging + + logging.info( + "[调试图像] 粉丝团加入检测前保存: %s", + debug_path, + ) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass + # 采样检测点:检测大片红色区域 red_count = 0 step_x = max(1, (x2 - x1) // 15) @@ -557,6 +584,41 @@ def detect_fansclub_join_red_area( threshold = 0.25 result = red_ratio >= threshold + # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 + try: + from douyin.handlers import douyin_screenshot_manager + + # 无论成功失败都保存debug截图 + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, # 使用全屏截图 + operation_type="pixel_detect", + picname="fansclub_join", + step="detected" if result else "not_detected", + coords=(x1, y1, x2, y2), # 标注识别区域 + extra_info={ + "red_ratio": round(red_ratio, 4), + "red_count": red_count, + "total_samples": total_samples, + "threshold": threshold, + "result": "success" if result else "failed", + }, + ) + if debug_path: + try: + import logging + + logging.info( + "[调试图像] 粉丝团加入检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s", + debug_path, + red_ratio, + threshold, + "success" if result else "failed", + ) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass + if return_info: reason_value: Optional[str] = ( None if result else "red_ratio_below_threshold" @@ -659,6 +721,43 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: # 计算置信度(基于检测到的像素比例) confidence = min(1.0, max(white_ratio * 10, pink_red_ratio * 15)) + # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 + try: + from douyin.handlers import douyin_screenshot_manager + + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, # 使用全屏截图 + operation_type="pixel_detect", + picname="live_room_icons", + step="detected" if detected else "not_detected", + coords=(x1, y1, x2, y2), # 标注识别区域 + extra_info={ + "white_ratio": round(white_ratio, 4), + "pink_red_ratio": round(pink_red_ratio, 4), + "white_count": white_count, + "pink_red_count": pink_red_count, + "total_samples": total_samples, + "confidence": round(confidence, 4), + "result": "success" if detected else "failed", + }, + ) + if debug_path: + try: + import logging + + logging.info( + "[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, pink_red_ratio=%.4f, confidence=%.4f, result=%s", + debug_path, + white_ratio, + pink_red_ratio, + confidence, + "success" if detected else "failed", + ) + except Exception as e: # type: ignore[general-exception] + pass + except Exception as e: # type: ignore[general-exception] + pass + return detected, confidence except Exception as e: # type: ignore[general-exception] return False, 0.0 diff --git a/douyin/fudai/core/MODULARIZATION_PLAN.md b/douyin/fudai/core/MODULARIZATION_PLAN.md index 23c7af5..3a35336 100644 --- a/douyin/fudai/core/MODULARIZATION_PLAN.md +++ b/douyin/fudai/core/MODULARIZATION_PLAN.md @@ -62,3 +62,8 @@ + + + + + diff --git a/douyin/fudai/core/fudai_debug_utils.py b/douyin/fudai/core/fudai_debug_utils.py index d9a2f8f..1c26a0e 100644 --- a/douyin/fudai/core/fudai_debug_utils.py +++ b/douyin/fudai/core/fudai_debug_utils.py @@ -1,96 +1,284 @@ """福袋调试工具模块 包含调试相关的工具函数,如截图保存和OCR区域标注。 +提供完善的错误处理和日志记录机制。 """ from __future__ import annotations import os -from typing import Any, Tuple -from PIL import Image +import traceback +from typing import Any, Tuple, Optional, Dict +from PIL import Image, UnidentifiedImageError import path_config +def log_debug_error( + analyser: Any, + error: Exception, + context: Dict[str, Any], + level: str = "WARNING", +) -> None: + """统一的错误日志记录函数。 + + 参数: + analyser: 分析器对象 + error: 异常对象 + context: 错误上下文信息字典 + level: 日志级别(ERROR/WARNING/INFO) + """ + try: + error_type = type(error).__name__ + error_msg = str(error) + + # 构建详细的错误信息 + error_info = { + "error": error_msg, + "error_type": error_type, + "level": level, + **context, + } + + # 对于严重错误,添加调用栈信息 + if level == "ERROR": + try: + stack_trace = "".join(traceback.format_tb(error.__traceback__)) + error_info["stack_trace"] = stack_trace[:500] # 限制长度 + except Exception: + pass + + analyser._log_kv( + "调试工具", + f"调试工具错误:{error_type}", + **error_info, + ) + except Exception: + # 如果日志记录也失败,至少尝试打印到控制台 + try: + print(f"[调试工具] 错误记录失败: {error}") + except Exception: + pass + + +def validate_coords( + coords: Tuple[int, int, int, int], + width: int, + height: int, +) -> Tuple[bool, Optional[str], Tuple[int, int, int, int]]: + """验证和修正坐标。 + + 参数: + coords: 原始坐标 (x1, y1, x2, y2) + width: 图像宽度 + height: 图像高度 + + 返回: + (是否有效, 错误信息, 修正后的坐标) + """ + x1, y1, x2, y2 = coords + + # 检查坐标是否有效 + if x1 >= x2: + return False, f"x1({x1}) >= x2({x2})", coords + if y1 >= y2: + return False, f"y1({y1}) >= y2({y2})", coords + + # 修正坐标到图像范围内 + x1_corrected = max(0, min(x1, width - 1)) + y1_corrected = max(0, min(y1, height - 1)) + x2_corrected = max(0, min(x2, width - 1)) + y2_corrected = max(0, min(y2, height - 1)) + + corrected_coords = (x1_corrected, y1_corrected, x2_corrected, y2_corrected) + + # 检查是否需要修正 + if (x1 != x1_corrected or y1 != y1_corrected or + x2 != x2_corrected or y2 != y2_corrected): + return True, "坐标已修正", corrected_coords + + return True, None, corrected_coords + + +def safe_image_load(image_path: str) -> Optional[Image.Image]: + """安全地加载图像,带详细的错误处理。 + + 参数: + image_path: 图像文件路径 + + 返回: + PIL Image 对象,失败返回 None + """ + if not os.path.exists(image_path): + return None + + try: + pic = Image.open(image_path) + pic.load() # 确保图像数据已加载 + return pic.convert("RGB") + except UnidentifiedImageError as e: + # 图像格式不支持 + raise ValueError(f"无法识别图像格式: {image_path}") from e + except OSError as e: + # 文件系统错误(权限、损坏等) + raise OSError(f"读取图像文件失败: {image_path}") from e + except Exception as e: + # 其他错误 + raise RuntimeError(f"加载图像时发生未知错误: {image_path}") from e + + def save_full_screenshot_with_ocr_region( - analyser: Any, picname: str, coords: Tuple[int, int, int, int], y_pianyi: int = 0 + analyser: Any, + picname: str, + coords: Tuple[int, int, int, int], + y_pianyi: int = 0 ) -> None: """保存完整截图并标注OCR区域(用于调试)。 - + 参数: analyser: 分析器对象 picname: 图片名称(如"福袋内容") coords: OCR区域坐标 (x1, y1, x2, y2) - 基准坐标(1080x2400) y_pianyi: Y轴偏移 + + 错误处理: + - FileNotFoundError: 截图文件不存在 + - PermissionError: 文件权限错误 + - OSError: 系统级错误 + - ValueError: 参数或坐标错误 + - 其他错误: 记录详细日志 """ + # 构建错误上下文 + context = { + "picname": picname, + "coords": coords, + "y_pianyi": y_pianyi, + } + try: from douyin.handlers import douyin_screenshot_manager - - # 读取完整截图 - pic_path = path_config.get_screenshot_path() - if not os.path.exists(pic_path): + except ImportError as e: + log_debug_error( + analyser, + e, + {**context, "stage": "导入截图管理模块"}, + level="ERROR", + ) + return + + # 读取完整截图 + pic_path = path_config.get_screenshot_path() + context["screenshot_path"] = pic_path + + if not os.path.exists(pic_path): + log_debug_error( + analyser, + FileNotFoundError(f"截图文件不存在: {pic_path}"), + {**context, "stage": "检查截图文件"}, + level="WARNING", + ) + return + + # 安全加载图像 + try: + pic_rgb = safe_image_load(pic_path) + if pic_rgb is None: return - - pic = Image.open(pic_path) - pic.load() - pic_rgb = pic.convert("RGB") - - # 缩放坐标到实际分辨率 - width, height = pic_rgb.size + except ValueError as e: + log_debug_error( + analyser, + e, + {**context, "stage": "加载图像"}, + level="ERROR", + ) + return + except OSError as e: + log_debug_error( + analyser, + e, + {**context, "stage": "读取图像文件"}, + level="ERROR", + ) + return + except Exception as e: + log_debug_error( + analyser, + e, + {**context, "stage": "加载图像(未知错误)"}, + level="ERROR", + ) + return + + # 获取分辨率信息 + width, height = pic_rgb.size + try: rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - + except Exception as e: + log_debug_error( + analyser, + e, + {**context, "stage": "获取分辨率", "image_size": f"{width}x{height}"}, + level="WARNING", + ) + rx, ry = 1080, 2400 # 使用默认值 + + context.update({ + "image_size": f"{width}x{height}", + "base_resolution": f"{rx}x{ry}", + }) + + # 缩放坐标到实际分辨率 + try: x1_base, y1_base, x2_base, y2_base = coords x1 = int(x1_base * width / rx) y1 = int((y1_base + y_pianyi) * height / ry) x2 = int(x2_base * width / rx) y2 = int((y2_base + y_pianyi) * height / ry) - - # 边界检查和验证 - x1_original = x1 - y1_original = y1 - x2_original = x2 - y2_original = y2 - - x1 = max(0, min(x1, width - 1)) - y1 = max(0, min(y1, height - 1)) - x2 = max(0, min(x2, width - 1)) - y2 = max(0, min(y2, height - 1)) - - # 记录坐标修正(如果坐标被修正) - if ( - x1_original != x1 - or y1_original != y1 - or x2_original != x2 - or y2_original != y2 - ): - try: - analyser._log_kv( - "验证", - "OCR区域坐标超出屏幕范围,已修正", - original_coords=f"({x1_original},{y1_original})-({x2_original},{y2_original})", - corrected_coords=f"({x1},{y1})-({x2},{y2})", - screen_size=f"{width}x{height}", - base_coords=coords, - level="WARNING", - ) - except Exception: - pass - - if x1 >= x2 or y1 >= y2: - try: - analyser._log_kv( - "验证", - "OCR区域坐标无效(x1>=x2或y1>=y2)", - coords=f"({x1},{y1})-({x2},{y2})", - base_coords=coords, - level="WARNING", - ) - except Exception: - pass - return - - # 保存调试图片 + + scaled_coords = (x1, y1, x2, y2) + except (ValueError, ZeroDivisionError) as e: + log_debug_error( + analyser, + e, + {**context, "stage": "坐标缩放"}, + level="ERROR", + ) + return + + # 验证和修正坐标 + is_valid, error_msg, corrected_coords = validate_coords( + scaled_coords, width, height + ) + + if not is_valid: + log_debug_error( + analyser, + ValueError(f"坐标无效: {error_msg}"), + {**context, "stage": "坐标验证", "scaled_coords": scaled_coords}, + level="WARNING", + ) + return + + x1, y1, x2, y2 = corrected_coords + + # 如果坐标被修正,记录警告 + if error_msg: + try: + analyser._log_kv( + "验证", + "OCR区域坐标超出屏幕范围,已修正", + original_coords=f"({x1_base},{y1_base})-({x2_base},{y2_base})", + corrected_coords=f"({x1},{y1})-({x2},{y2})", + screen_size=f"{width}x{height}", + base_coords=coords, + level="WARNING", + ) + except Exception: + pass + + # 保存调试图片 + try: debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb, operation_type="ocr", @@ -103,6 +291,7 @@ def save_full_screenshot_with_ocr_region( "y_offset": y_pianyi, }, ) + if debug_path: try: analyser._log_kv( @@ -112,35 +301,34 @@ def save_full_screenshot_with_ocr_region( region=f"({x1_base},{y1_base})-({x2_base},{y2_base})", ) except Exception as e: - try: - analyser._log_kv( - "错误", - "保存调试图像日志失败", - error=str(e), - error_type=type(e).__name__, - picname=picname, - level="WARNING", - ) - except Exception: - pass + log_debug_error( + analyser, + e, + {**context, "stage": "记录成功日志", "debug_path": debug_path}, + level="WARNING", + ) + except PermissionError as e: + log_debug_error( + analyser, + e, + {**context, "stage": "保存调试图像(权限错误)"}, + level="ERROR", + ) + except OSError as e: + log_debug_error( + analyser, + e, + {**context, "stage": "保存调试图像(系统错误)"}, + level="ERROR", + ) except Exception as e: - try: - analyser._log_kv( - "错误", - "保存完整截图并标注OCR区域失败", - error=str(e), - error_type=type(e).__name__, - picname=picname, - coords=coords, - level="WARNING", - ) - except Exception: - pass + log_debug_error( + analyser, + e, + {**context, "stage": "保存调试图像(未知错误)"}, + level="ERROR", + ) # 向后兼容:保留原函数名 _save_full_screenshot_with_ocr_region = save_full_screenshot_with_ocr_region - - - - diff --git a/douyin/fudai/core/fudai_detail_reader.py b/douyin/fudai/core/fudai_detail_reader.py index 5e02247..e3bc52e 100644 --- a/douyin/fudai/core/fudai_detail_reader.py +++ b/douyin/fudai/core/fudai_detail_reader.py @@ -219,12 +219,12 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo countdown_box = None if renwu == 2: # 如果是2个任务的 # 优化:扩大Y范围向上,确保包含任务描述(如"观看X分钟"等) - # 从1240向上扩展到1100,确保包含任务描述区域 + # 从1240向上扩展到1100,确保包含任务描述区域 _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", (390, 1100, 980, 1470), analyser.y_pianyi + analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi ) analyser.cut_pic( - 390, 1100, 980, 1470, "", "福袋内容", analyser.y_pianyi + 389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) # 优化:稍微扩大高度(1220->1230),确保包含完整的"后开奖"文字 countdown_box = (390, 1110, 690, 1230) @@ -248,20 +248,20 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) - # 优化:增加高度(1560->1580),确保包含"元"等单位文字 + # 优化:向上扩大范围(1460->1440),防止识别不完整 _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1460, 1000, 1580), analyser.y_pianyi + analyser, "福袋价值", (390, 1440, 1000, 1580), analyser.y_pianyi ) analyser.cut_pic( - 390, 1460, 1000, 1580, "", "福袋价值", analyser.y_pianyi + 390, 1440, 1000, 1580, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 elif renwu == 1: # 如果是1个任务的 # 优化:扩大Y范围向上,确保包含任务描述 _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", (390, 1160, 980, 1530), analyser.y_pianyi + analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi ) analyser.cut_pic( - 390, 1160, 980, 1530, "", "福袋内容", analyser.y_pianyi + 389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) # 优化:稍微扩大高度,确保完整 countdown_box = (390, 1180, 690, 1300) @@ -285,20 +285,20 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) - # 优化:增加高度,包含单位 + # 优化:向上扩大范围(1520->1500),防止识别不完整 _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1520, 1000, 1630), analyser.y_pianyi + analyser, "福袋价值", (390, 1500, 1000, 1630), analyser.y_pianyi ) analyser.cut_pic( - 390, 1520, 1000, 1630, "", "福袋价值", analyser.y_pianyi + 390, 1500, 1000, 1630, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 elif renwu == 3: # 如果是3个任务的 # 优化:扩大Y范围向上,确保包含任务描述 _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", (390, 1020, 980, 1390), analyser.y_pianyi + analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi ) analyser.cut_pic( - 390, 1020, 980, 1390, "", "福袋内容", analyser.y_pianyi + 389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) # 优化:稍微扩大高度 countdown_box = (390, 1010, 690, 1130) @@ -322,20 +322,20 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) - # 优化:增加高度 + # 优化:向上扩大范围(1380->1360),防止识别不完整 _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1380, 1000, 1490), analyser.y_pianyi + analyser, "福袋价值", (390, 1360, 1000, 1490), analyser.y_pianyi ) analyser.cut_pic( - 390, 1380, 1000, 1490, "", "福袋价值", analyser.y_pianyi + 390, 1360, 1000, 1490, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 else: # 优化:稍微缩小宽度,增加高度 _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", (390, 1600, 980, 1830), analyser.y_pianyi + analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi ) analyser.cut_pic( - 390, 1600, 980, 1830, "", "福袋内容", analyser.y_pianyi + 389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情 # 优化:稍微扩大高度 countdown_box = (390, 1460, 690, 1580) @@ -359,12 +359,12 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) - # 优化:增加高度 + # 优化:向上扩大范围(1820->1800),防止识别不完整 _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1820, 1000, 1930), analyser.y_pianyi + analyser, "福袋价值", (390, 1800, 1000, 1930), analyser.y_pianyi ) analyser.cut_pic( - 390, 1820, 1000, 1930, "", "福袋价值", analyser.y_pianyi + 390, 1800, 1000, 1930, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 # 准备任务列表区域的截图(用于并行OCR) diff --git a/douyin/fudai/core/fudai_filter.py b/douyin/fudai/core/fudai_filter.py index 55b6564..15d29db 100644 --- a/douyin/fudai/core/fudai_filter.py +++ b/douyin/fudai/core/fudai_filter.py @@ -520,44 +520,47 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: pass + # 检查是否是预约回退后强制参与(跳过验证) + # 注意:必须在检查 _last_fudai_detail_status 之前检查,否则强制参与标志会被忽略 + force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) + # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 + # 但如果设置了强制参与标志,则跳过状态检查(预约回退时使用预约记录,可能不满足验证条件) try: last_status = getattr(analyser, "_last_fudai_detail_status", "") - if last_status == "coupon_popup": - try: + if not force_attend: # 只有在非强制参与模式下才检查状态 + if last_status == "coupon_popup": + try: + analyser._log_kv( + "参与", + "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", + ) + except Exception: + pass + elapsed = time.time() - start_time analyser._log_kv( "参与", - "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", + "basic_join_decision完成(优惠券弹窗)", + elapsed_seconds=round(elapsed, 2), ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(优惠券弹窗)", - elapsed_seconds=round(elapsed, 2), - ) - return False - elif last_status == "validation_failed": - try: + return False + elif last_status == "validation_failed": + try: + analyser._log_kv( + "参与", + "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", + ) + except Exception: + pass + elapsed = time.time() - start_time analyser._log_kv( "参与", - "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", + "basic_join_decision完成(验证失败)", + elapsed_seconds=round(elapsed, 2), ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(验证失败)", - elapsed_seconds=round(elapsed, 2), - ) - return False + return False except Exception: pass - - # 检查是否是预约回退后强制参与(跳过验证) - force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) if force_attend: try: analyser._log_kv( diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index a781bc7..62e8dff 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -13,153 +13,17 @@ from douyin.utils.douyin_utils import normalize_countdown_text, extract_prize_va from douyin.reservation import douyin_reservation_logic import path_config -# 从新模块导入调试工具函数(如果可用) -try: - from douyin.fudai.core.fudai_debug_utils import ( - _save_full_screenshot_with_ocr_region, - ) - - # 如果成功导入,使用新模块的函数,跳过下面的定义 - _DEBUG_UTILS_IMPORTED = True -except ImportError: - # 如果新模块不可用,函数将在下面定义 - _DEBUG_UTILS_IMPORTED = False - - -# 如果新模块的函数不可用,定义原函数作为后备 -if not _DEBUG_UTILS_IMPORTED: - - def _save_full_screenshot_with_ocr_region( - analyser: Any, - picname: str, - coords: Tuple[int, int, int, int], - y_pianyi: int = 0, - ) -> None: - """保存完整截图并标注OCR区域(用于调试)。 - - 参数: - analyser: 分析器对象 - picname: 图片名称(如"福袋内容") - coords: OCR区域坐标 (x1, y1, x2, y2) - 基准坐标(1080x2400) - y_pianyi: Y轴偏移 - """ - try: - from douyin.handlers import douyin_screenshot_manager - - # 读取完整截图 - pic_path = path_config.get_screenshot_path() - if not os.path.exists(pic_path): - return - - pic = Image.open(pic_path) - pic.load() - pic_rgb = pic.convert("RGB") - - # 缩放坐标到实际分辨率 - width, height = pic_rgb.size - rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - - x1_base, y1_base, x2_base, y2_base = coords - x1 = int(x1_base * width / rx) - y1 = int((y1_base + y_pianyi) * height / ry) - x2 = int(x2_base * width / rx) - y2 = int((y2_base + y_pianyi) * height / ry) - - # 边界检查和验证 - x1_original = x1 - y1_original = y1 - x2_original = x2 - y2_original = y2 - - x1 = max(0, min(x1, width - 1)) - y1 = max(0, min(y1, height - 1)) - x2 = max(0, min(x2, width - 1)) - y2 = max(0, min(y2, height - 1)) - - # 记录坐标修正(如果坐标被修正) - if ( - x1_original != x1 - or y1_original != y1 - or x2_original != x2 - or y2_original != y2 - ): - try: - analyser._log_kv( - "验证", - "OCR区域坐标超出屏幕范围,已修正", - original_coords=f"({x1_original},{y1_original})-({x2_original},{y2_original})", - corrected_coords=f"({x1},{y1})-({x2},{y2})", - screen_size=f"{width}x{height}", - base_coords=coords, - level="WARNING", - ) - except Exception: - pass - - if x1 >= x2 or y1 >= y2: - try: - analyser._log_kv( - "验证", - "OCR区域坐标无效(x1>=x2或y1>=y2)", - coords=f"({x1},{y1})-({x2},{y2})", - base_coords=coords, - level="WARNING", - ) - except Exception: - pass - return - - # 保存调试图片 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, - operation_type="ocr", - picname=picname, - step="before_ocr", - coords=(x1, y1, x2, y2), - extra_info={ - "region": f"({x1_base},{y1_base})-({x2_base},{y2_base})", - "size": f"{x2_base-x1_base}x{y2_base-y1_base}", - "y_offset": y_pianyi, - }, - ) - if debug_path: - try: - analyser._log_kv( - "[调试图像]", - f"OCR识别前保存完整截图({picname})", - path=debug_path, - region=f"({x1_base},{y1_base})-({x2_base},{y2_base})", - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "保存调试图像日志失败", - error=str(e), - error_type=type(e).__name__, - picname=picname, - level="WARNING", - ) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "错误", - "保存完整截图并标注OCR区域失败", - error=str(e), - error_type=type(e).__name__, - picname=picname, - coords=coords, - level="WARNING", - ) - except Exception: - pass +# 从新模块导入调试工具函数 +from douyin.fudai.core.fudai_debug_utils import ( + _save_full_screenshot_with_ocr_region, +) def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: """获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。""" + + # 检查是否启用调试截图保存(默认False,正常运行时跳过以提升性能) + save_debug_images = bool(getattr(analyser, "fudai_detail_save_debug_images", False) or False) def _parse_mm_ss(text: str): m = re.search(r"(\d{1,2})[::](\d{2})", str(text or "")) @@ -207,32 +71,33 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - # 保存调试截图 - try: - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_分钟", - (x1, y1, x1 + seg1, y2), - analyser.y_pianyi, - ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) - except Exception as e: + # 保存调试截图(仅在配置启用时) + if save_debug_images: try: - analyser._log_kv( - "错误", - "保存倒计时调试截图失败", - error=str(e), - error_type=type(e).__name__, - box=box, - level="WARNING", + _save_full_screenshot_with_ocr_region( + analyser, + "福袋倒计时_分钟", + (x1, y1, x1 + seg1, y2), + analyser.y_pianyi, ) - except Exception: - pass + _save_full_screenshot_with_ocr_region( + analyser, + "福袋倒计时_秒", + (x1 + seg1, y1, x1 + seg1 + seg2, y2), + analyser.y_pianyi, + ) + except Exception as e: + try: + analyser._log_kv( + "错误", + "保存倒计时调试截图失败", + error=str(e), + error_type=type(e).__name__, + box=box, + level="WARNING", + ) + except Exception: + pass # 切割分钟区域(左侧) analyser.cut_pic( @@ -362,11 +227,12 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo if renwu == 2: # 如果是2个任务的 # 优化:扩大Y范围向上,确保包含任务描述(如"观看X分钟"等) # 从1240向上扩展到1100,确保包含任务描述区域 - _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", (390, 1100, 980, 1470), analyser.y_pianyi - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi + ) analyser.cut_pic( - 390, 1100, 980, 1470, "", "福袋内容", analyser.y_pianyi + 389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) # 优化:稍微扩大高度(1220->1230),确保包含完整的"后开奖"文字 countdown_box = (390, 1110, 690, 1230) @@ -375,35 +241,39 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo w = max(1, int(x2 - x1)) seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - _save_full_screenshot_with_ocr_region( - analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi + ) analyser.cut_pic( x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, + "福袋倒计时_秒", + (x1 + seg1, y1, x1 + seg1 + seg2, y2), + analyser.y_pianyi, + ) analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) - # 优化:增加高度(1560->1580),确保包含"元"等单位文字 - _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1460, 1000, 1580), analyser.y_pianyi - ) + # 优化:向上扩大范围(1460->1440),防止识别不完整 + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋价值", (390, 1440, 1000, 1580), analyser.y_pianyi + ) analyser.cut_pic( - 390, 1460, 1000, 1580, "", "福袋价值", analyser.y_pianyi + 390, 1440, 1000, 1580, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 elif renwu == 1: # 如果是1个任务的 # 优化:扩大Y范围向上,确保包含任务描述 - _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", (390, 1160, 980, 1530), analyser.y_pianyi - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi + ) analyser.cut_pic( - 390, 1160, 980, 1530, "", "福袋内容", analyser.y_pianyi + 389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) # 优化:稍微扩大高度,确保完整 countdown_box = (390, 1180, 690, 1300) @@ -412,35 +282,39 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo w = max(1, int(x2 - x1)) seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - _save_full_screenshot_with_ocr_region( - analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi + ) analyser.cut_pic( x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, + "福袋倒计时_秒", + (x1 + seg1, y1, x1 + seg1 + seg2, y2), + analyser.y_pianyi, + ) analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) - # 优化:增加高度,包含单位 - _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1520, 1000, 1630), analyser.y_pianyi - ) + # 优化:向上扩大范围(1520->1500),防止识别不完整 + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋价值", (390, 1500, 1000, 1630), analyser.y_pianyi + ) analyser.cut_pic( - 390, 1520, 1000, 1630, "", "福袋价值", analyser.y_pianyi + 390, 1500, 1000, 1630, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 elif renwu == 3: # 如果是3个任务的 # 优化:扩大Y范围向上,确保包含任务描述 - _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", (390, 1020, 980, 1390), analyser.y_pianyi - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi + ) analyser.cut_pic( - 390, 1020, 980, 1390, "", "福袋内容", analyser.y_pianyi + 389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情(包含任务描述) # 优化:稍微扩大高度 countdown_box = (390, 1010, 690, 1130) @@ -449,35 +323,39 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo w = max(1, int(x2 - x1)) seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - _save_full_screenshot_with_ocr_region( - analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi + ) analyser.cut_pic( x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, + "福袋倒计时_秒", + (x1 + seg1, y1, x1 + seg1 + seg2, y2), + analyser.y_pianyi, + ) analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) - # 优化:增加高度 - _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1380, 1000, 1490), analyser.y_pianyi - ) + # 优化:向上扩大范围(1380->1360),防止识别不完整 + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋价值", (390, 1360, 1000, 1490), analyser.y_pianyi + ) analyser.cut_pic( - 390, 1380, 1000, 1490, "", "福袋价值", analyser.y_pianyi + 390, 1360, 1000, 1490, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 else: # 优化:稍微缩小宽度,增加高度 - _save_full_screenshot_with_ocr_region( - analyser, "福袋内容", (390, 1600, 980, 1830), analyser.y_pianyi - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋内容", (389, 1273, 1000, 1534), analyser.y_pianyi + ) analyser.cut_pic( - 390, 1600, 980, 1830, "", "福袋内容", analyser.y_pianyi + 389, 1273, 1000, 1534, "", "福袋内容", analyser.y_pianyi ) # 福袋内容详情 # 优化:稍微扩大高度 countdown_box = (390, 1460, 690, 1580) @@ -486,36 +364,40 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo w = max(1, int(x2 - x1)) seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框 seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框 - _save_full_screenshot_with_ocr_region( - analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi + ) analyser.cut_pic( x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi ) - _save_full_screenshot_with_ocr_region( - analyser, - "福袋倒计时_秒", - (x1 + seg1, y1, x1 + seg1 + seg2, y2), - analyser.y_pianyi, - ) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, + "福袋倒计时_秒", + (x1 + seg1, y1, x1 + seg1 + seg2, y2), + analyser.y_pianyi, + ) analyser.cut_pic( x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi ) - # 优化:增加高度 - _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1820, 1000, 1930), analyser.y_pianyi - ) + # 优化:向上扩大范围(1820->1800),防止识别不完整 + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋价值", (390, 1800, 1000, 1930), analyser.y_pianyi + ) analyser.cut_pic( - 390, 1820, 1000, 1930, "", "福袋价值", analyser.y_pianyi + 390, 1800, 1000, 1930, "", "福袋价值", analyser.y_pianyi ) # 奖品价值/价格 # 准备任务列表区域的截图(用于并行OCR) # 任务列表区域(任务位置:50,1621到1032,1960),用于检测"观看X分钟"任务 try: - # 保存任务列表区域的调试截图 - _save_full_screenshot_with_ocr_region( - analyser, "福袋任务列表", (50, 1621, 1032, 1960), analyser.y_pianyi - ) + # 保存任务列表区域的调试截图(仅在配置启用时) + if save_debug_images: + _save_full_screenshot_with_ocr_region( + analyser, "福袋任务列表", (50, 1621, 1032, 1960), analyser.y_pianyi + ) analyser.cut_pic(50, 1621, 1032, 1960, "", "福袋任务列表", analyser.y_pianyi) except Exception as e: # 任务列表截图失败不影响后续流程,记录日志即可 @@ -3521,44 +3403,47 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: pass + # 检查是否是预约回退后强制参与(跳过验证) + # 注意:必须在检查 _last_fudai_detail_status 之前检查,否则强制参与标志会被忽略 + force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) + # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 + # 但如果设置了强制参与标志,则跳过状态检查(预约回退时使用预约记录,可能不满足验证条件) try: last_status = getattr(analyser, "_last_fudai_detail_status", "") - if last_status == "coupon_popup": - try: + if not force_attend: # 只有在非强制参与模式下才检查状态 + if last_status == "coupon_popup": + try: + analyser._log_kv( + "参与", + "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", + ) + except Exception: + pass + elapsed = time.time() - start_time analyser._log_kv( "参与", - "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", + "basic_join_decision完成(优惠券弹窗)", + elapsed_seconds=round(elapsed, 2), ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(优惠券弹窗)", - elapsed_seconds=round(elapsed, 2), - ) - return False - elif last_status == "validation_failed": - try: + return False + elif last_status == "validation_failed": + try: + analyser._log_kv( + "参与", + "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", + ) + except Exception: + pass + elapsed = time.time() - start_time analyser._log_kv( "参与", - "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", + "basic_join_decision完成(验证失败)", + elapsed_seconds=round(elapsed, 2), ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(验证失败)", - elapsed_seconds=round(elapsed, 2), - ) - return False + return False except Exception: pass - - # 检查是否是预约回退后强制参与(跳过验证) - force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) if force_attend: try: analyser._log_kv( @@ -4343,7 +4228,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: # 这样可以确保每个预约记录的是当时的真实直播间标题 try: # 在函数开头导入,避免作用域问题 - import douyin_fudai_detail as dfd_module + from douyin.fudai import douyin_fudai_detail as dfd_module y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) room_title, room_title_raw = ( @@ -4390,12 +4275,17 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: analyser, "_reservations_state_path", None ) if not state_path: - # 使用与 douyin_fudai.py 相同的路径逻辑 - state_path = os.path.join( - os.path.dirname(__file__), - "state", - "reservations.json", - ) + # 使用path_config统一路径 + try: + import path_config + state_path = path_config.get_reservations_path() + except Exception: + # 回退到旧路径(向后兼容) + state_path = os.path.join( + os.path.dirname(__file__), + "state", + "reservations.json", + ) # 确保目录存在 os.makedirs(os.path.dirname(state_path), exist_ok=True) @@ -4913,11 +4803,17 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: state_path = getattr(analyser, "_reservations_state_path", None) if not state_path: - state_path = os.path.join( - os.path.dirname(__file__), - "state", - "reservations.json", - ) + # 使用path_config统一路径 + try: + import path_config + state_path = path_config.get_reservations_path() + except Exception: + # 回退到旧路径(向后兼容) + state_path = os.path.join( + os.path.dirname(__file__), + "state", + "reservations.json", + ) os.makedirs(os.path.dirname(state_path), exist_ok=True) # 格式化预约队列数据 diff --git a/douyin/fudai/douyin_fudai_finder.py b/douyin/fudai/douyin_fudai_finder.py index 176b601..7717e68 100644 --- a/douyin/fudai/douyin_fudai_finder.py +++ b/douyin/fudai/douyin_fudai_finder.py @@ -653,47 +653,41 @@ class FudaiDetector: except Exception: pass - # 保存模板匹配的调试图像(无论成功与否) + # 保存模板匹配的调试图像(无论成功与否)- 使用完整截图 try: from douyin.handlers import douyin_screenshot_manager # Image 已在文件顶部导入 - # 保存搜索区域图像 - search_roi_pil = Image.fromarray( - cv2.cvtColor(search_roi_bgr, cv2.COLOR_BGR2RGB) - ) + # 使用完整截图而不是搜索区域ROI + pic_rgb = pic.convert("RGB") - # 如果匹配成功,在图像上标注匹配位置 + # 计算匹配位置在完整截图中的坐标(如果匹配成功) + match_coords = None if max_val >= threshold and best_x is not None: try: - from PIL import ImageDraw - - annotated_roi = search_roi_pil.copy() - draw = ImageDraw.Draw(annotated_roi) best_tw = int(tw * best_scale) if best_score >= 0 else tw best_th = int(th * best_scale) if best_score >= 0 else th - # 绘制匹配框 - match_x1 = best_x - match_y1 = 0 - match_x2 = best_x + best_tw - match_y2 = best_th - rect_coords: Tuple[float, float, float, float] = ( - float(match_x1), - float(match_y1), - float(match_x2), - float(match_y2), - ) - draw.rectangle(rect_coords, outline="green", width=2) - search_roi_pil = annotated_roi + # 匹配位置在ROI内的坐标 + match_x1_in_roi = best_x + match_y1_in_roi = 0 + match_x2_in_roi = best_x + best_tw + match_y2_in_roi = best_th + # 转换为完整截图坐标 + match_x1 = x1 + match_x1_in_roi + match_y1 = y_top + match_y1_in_roi + match_x2 = x1 + match_x2_in_roi + match_y2 = y_top + match_y2_in_roi + match_coords = (match_x1, match_y1, match_x2, match_y2) except Exception: pass + # 使用搜索区域坐标作为主要标注,匹配位置作为额外信息 debug_path = douyin_screenshot_manager.save_debug_image( - search_roi_pil, + pic_rgb, operation_type="template_match", picname="fudai_icon", step="matched" if max_val >= threshold else "failed", - coords=(x1, y_top, x2, y_bottom), + coords=(x1, y_top, x2, y_bottom), # 搜索区域坐标 extra_info={ "region": region.get("name", "unknown"), "score": round(max_val, 4), @@ -702,6 +696,7 @@ class FudaiDetector: "best_scale": round(best_scale, 2) if best_score >= 0 else None, "template_size": f"{tw}x{th}", "search_size": f"{rw}x{rh}", + "match_coords": match_coords, # 匹配位置坐标(如果匹配成功) }, ) if debug_path: diff --git a/douyin/fudai/finder/__init__.py b/douyin/fudai/finder/__init__.py index 71a5021..ba9fae3 100644 --- a/douyin/fudai/finder/__init__.py +++ b/douyin/fudai/finder/__init__.py @@ -26,3 +26,8 @@ __all__ = [ + + + + + diff --git a/douyin/handlers/douyin_screenshot_manager.py b/douyin/handlers/douyin_screenshot_manager.py index 755ae94..3ba1419 100644 --- a/douyin/handlers/douyin_screenshot_manager.py +++ b/douyin/handlers/douyin_screenshot_manager.py @@ -312,12 +312,26 @@ def ensure_debug_captures_dir() -> None: # 确保父目录也存在 parent_dir = os.path.dirname(debug_dir) if parent_dir and not os.path.exists(parent_dir): - os.makedirs(parent_dir, exist_ok=True) - os.makedirs(debug_dir, exist_ok=True) - except Exception as e: - # 如果目录创建失败,记录错误但不抛出异常(让调用方处理) + try: + os.makedirs(parent_dir, exist_ok=True) + except PermissionError as e: + raise PermissionError(f"无权限创建调试图像目录: {parent_dir}") from e + except OSError as e: + raise OSError(f"创建调试图像目录失败: {parent_dir}") from e try: - print(f"[截图管理] 创建调试图像目录失败: {e}") + os.makedirs(debug_dir, exist_ok=True) + except PermissionError as e: + raise PermissionError(f"无权限创建调试图像目录: {debug_dir}") from e + except OSError as e: + raise OSError(f"创建调试图像目录失败: {debug_dir}") from e + except (PermissionError, OSError): + # 权限或系统错误,重新抛出 + raise + except Exception as e: + # 其他未知错误 + error_type = type(e).__name__ + try: + print(f"[截图管理] 创建调试图像目录失败({error_type}): {e}") except Exception: pass raise @@ -802,23 +816,47 @@ def save_debug_image( img_to_save: Image.Image, path: str, max_retries: int = 2 ) -> bool: """保存图像,如果目录不存在则创建后重试""" + last_error = None for attempt in range(max_retries): try: img_to_save.save(path, "PNG") return True - except FileNotFoundError: + except FileNotFoundError as e: # 目录不存在,尝试创建后重试 + last_error = e if attempt < max_retries - 1: try: ensure_debug_captures_dir() - except Exception: - pass + except Exception as dir_error: + # 记录目录创建失败 + try: + print(f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}") + except Exception: + pass else: # 最后一次尝试失败,抛出异常 raise - except Exception: - # 其他异常直接抛出 + except PermissionError as e: + # 权限错误,不重试 + try: + print(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}") + except Exception: + pass raise + except OSError as e: + # 系统级错误(磁盘空间不足等),不重试 + try: + print(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}") + except Exception: + pass + raise + except Exception as e: + # 其他异常直接抛出 + last_error = e + raise + # 所有重试都失败 + if last_error: + raise last_error return False # 如果需要标注,在图像上添加信息 @@ -870,9 +908,24 @@ def save_debug_image( pass save_image_with_retry(annotated_image, file_path) - except Exception: - # 如果标注失败,直接保存原图 + except (PermissionError, OSError) as e: + # 权限或系统错误,尝试保存原图 try: + try: + print(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}") + except Exception: + pass + save_image_with_retry(image, file_path) + except Exception: + # 如果保存原图也失败,抛出异常让外层处理 + raise + except Exception as e: + # 其他标注错误,尝试保存原图 + try: + try: + print(f"[截图管理] 图像标注失败,尝试保存原图: {e}") + except Exception: + pass save_image_with_retry(image, file_path) except Exception: # 如果保存原图也失败,抛出异常让外层处理 @@ -881,9 +934,32 @@ def save_debug_image( save_image_with_retry(image, file_path) return file_path - except Exception as e: + except FileNotFoundError as e: + # 文件或目录不存在 try: - print(f"[截图管理] 保存调试图像失败: {e}") + print(f"[截图管理] 保存调试图像失败(文件/目录不存在): {e}") + except Exception: + pass + return None + except PermissionError as e: + # 权限错误 + try: + print(f"[截图管理] 保存调试图像失败(权限错误): {e}") + except Exception: + pass + return None + except OSError as e: + # 系统级错误(磁盘空间不足、路径过长等) + try: + print(f"[截图管理] 保存调试图像失败(系统错误): {e}") + except Exception: + pass + return None + except Exception as e: + # 其他未知错误 + try: + error_type = type(e).__name__ + print(f"[截图管理] 保存调试图像失败({error_type}): {e}") except Exception: pass return None diff --git a/douyin/handlers/douyin_swipe_handler.py b/douyin/handlers/douyin_swipe_handler.py index 0e024ac..b9b8ae4 100644 --- a/douyin/handlers/douyin_swipe_handler.py +++ b/douyin/handlers/douyin_swipe_handler.py @@ -204,6 +204,10 @@ class SwipeHandler: end_x = 760 * rx // 1080 end_y = 1600 * ry // 2400 # 下方结束位置 # 直接使用 ADB 内部滑动命令 + # 使用配置的滑动持续时间,如果没有配置则使用300ms(比之前的200ms更快) + swipe_duration_ms = int( + getattr(analyser, "swipe_duration_ms", 300) or 300 + ) try: if hasattr(analyser.operation, "_adb"): adb_cmd = analyser.operation._adb() @@ -215,7 +219,7 @@ class SwipeHandler: adb_cmd = f'"{adb_cmd}"' cmd = ( f"{adb_cmd} -s {analyser.device_id} shell input swipe " - f"{start_x} {start_y} {end_x} {end_y} 200" + f"{start_x} {start_y} {end_x} {end_y} {swipe_duration_ms}" ) subprocess.run( cmd, @@ -227,7 +231,7 @@ class SwipeHandler: except Exception: # 回退到 operation.swipe analyser.operation.swipe( - analyser.device_id, start_x, start_y, end_x, end_y, 200 + analyser.device_id, start_x, start_y, end_x, end_y, swipe_duration_ms ) try: analyser._log_kv( # type: ignore[attr-defined] @@ -369,6 +373,12 @@ class SwipeHandler: analyser._log_kv("超时", "已重新进入直播间") # type: ignore[attr-defined] + # 标记刚刚切换进入直播间,后续读取标题时会等待标题区域出现 + try: + analyser._just_switched_room = True + except Exception: + pass + # 重置超时相关时间戳(在成功重新进入直播间后重置,避免立即再次触发) try: analyser._last_successful_attend_ts = time.time() diff --git a/douyin/other/douyin_popups.py b/douyin/other/douyin_popups.py index 7f74421..5dec90d 100644 --- a/douyin/other/douyin_popups.py +++ b/douyin/other/douyin_popups.py @@ -28,7 +28,8 @@ def check_coupon_popup(analyser) -> bool: pic_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) - pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + import path_config + pic_path = path_config.get_screenshot_path() pic = Image.open(pic_path) pic.load() # Force load to catch truncated files early pic = pic.convert("RGB") @@ -192,7 +193,8 @@ def check_shopping_redpacket_popup(analyser) -> bool: pic_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) - pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + import path_config + pic_path = path_config.get_screenshot_path() pic = Image.open(pic_path) pic.load() # Force load to catch truncated files early pic = pic.convert("RGB") diff --git a/douyin/other/douyin_robot.py b/douyin/other/douyin_robot.py index 8851242..d3b0ad1 100644 --- a/douyin/other/douyin_robot.py +++ b/douyin/other/douyin_robot.py @@ -76,8 +76,12 @@ def deal_robot_analyse(analyser) -> None: def deal_robot_pic_change_color(analyser) -> None: """处理人机验证的图片,转为黑白图。""" analyser.cut_pic(143, 884, 936, 1380, "save", "机器人验证") - path = os.path.join(os.path.dirname(__file__), "pic", "save") - pic = os.path.join(path, "机器人验证.png") + try: + import path_config + pic = path_config.get_robot_verify_pic_path(save_subdir=True) + except Exception: + import path_config + pic = path_config.get_robot_verify_pic_path(save_subdir=True) img = Image.open(pic) img = img.convert("RGB") width, height = img.size diff --git a/douyin/other/douyin_yanghao.py b/douyin/other/douyin_yanghao.py index a9b0ed1..a4d3ad3 100644 --- a/douyin/other/douyin_yanghao.py +++ b/douyin/other/douyin_yanghao.py @@ -518,8 +518,12 @@ def maybe_reset_after_swipes(analyser, needswitch: bool, swipe_times: int) -> in return 0 # 下滑回退:与上划切换相反方向 + # 使用配置的滑动持续时间,如果没有配置则使用300ms(比之前的200ms更快) + swipe_duration_ms = int( + getattr(analyser, "swipe_duration_ms", 300) or 300 + ) for i in range(back_times): - analyser.swipe(760, 800, 760, 1600, 200) + analyser.swipe(760, 800, 760, 1600, swipe_duration_ms) print("回退直播间 {}/{}".format(i + 1, back_times)) analyser.operation.delay(2) diff --git a/douyin/reservation/core/__init__.py b/douyin/reservation/core/__init__.py index 72df0d6..289ff4c 100644 --- a/douyin/reservation/core/__init__.py +++ b/douyin/reservation/core/__init__.py @@ -36,3 +36,8 @@ __all__ = [ + + + + + diff --git a/douyin/reservation/core/reservation_error_utils.py b/douyin/reservation/core/reservation_error_utils.py new file mode 100644 index 0000000..4631e52 --- /dev/null +++ b/douyin/reservation/core/reservation_error_utils.py @@ -0,0 +1,226 @@ +"""预约错误处理工具模块 + +提供统一的预约相关错误处理和日志记录功能。 +""" + +from __future__ import annotations + +import traceback +from typing import Any, Dict, List, Optional, Callable, Tuple +from datetime import datetime + +ReservationItem = Dict[str, Any] + + +def format_reservation_context( + item: Optional[ReservationItem] = None, + reservations: Optional[List[ReservationItem]] = None, + **kwargs +) -> Dict[str, Any]: + """格式化预约上下文信息。 + + 参数: + item: 预约项字典(可选) + reservations: 预约队列列表(可选) + **kwargs: 其他上下文信息 + + 返回: + 格式化的上下文信息字典 + """ + context: Dict[str, Any] = {} + + # 添加预约项信息 + if item: + try: + context["reservation_item"] = { + "future_ts": int(item.get("future_ts", 0)) if item.get("future_ts") else 0, + "prize_value_yuan": float(item.get("prize_value_yuan", 0.0)), + "room_title": str(item.get("room_title", ""))[:50], + "room_title_raw": str(item.get("room_title_raw", ""))[:50], + "pos_seen": int(item.get("pos_seen", 0)), + "content": str(item.get("content", ""))[:50], + } + # 格式化时间戳 + future_ts = item.get("future_ts") + if future_ts: + try: + context["reservation_item"]["future_str"] = datetime.fromtimestamp( + float(future_ts) + ).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + pass + except Exception: + pass + + # 添加队列信息 + if reservations is not None: + try: + context["queue_info"] = { + "queue_len": len(reservations), + "queue_items": [ + { + "future_ts": int(r.get("future_ts", 0)) if r.get("future_ts") else 0, + "prize_value_yuan": float(r.get("prize_value_yuan", 0.0)), + "room_title": str(r.get("room_title", ""))[:30], + } + for r in reservations[:5] # 只取前5个 + ] if reservations else [], + } + except Exception: + pass + + # 添加其他上下文信息 + context.update(kwargs) + + return context + + +def log_reservation_error( + analyser: Any, + error: Exception, + context: Dict[str, Any], + level: str = "WARNING", + stage: str = "", +) -> None: + """统一的预约错误日志记录函数。 + + 参数: + analyser: 分析器对象 + error: 异常对象 + context: 错误上下文信息字典 + level: 日志级别(ERROR/WARNING/INFO) + stage: 操作阶段描述(如"添加预约"、"回退验证"等) + """ + try: + error_type = type(error).__name__ + error_msg = str(error) + + # 构建详细的错误信息 + error_info = { + "error": error_msg, + "error_type": error_type, + "level": level, + "stage": stage, + **context, + } + + # 对于严重错误,添加调用栈信息 + if level == "ERROR": + try: + stack_trace = "".join(traceback.format_tb(error.__traceback__)) + error_info["stack_trace"] = stack_trace[:500] # 限制长度 + except Exception: + pass + + analyser._log_kv( + "预约", + f"[预约] 错误:{stage or '未知操作'}" if stage else "[预约] 错误", + **error_info, + ) + except Exception: + # 如果日志记录也失败,至少尝试打印到控制台 + try: + print(f"[预约错误] {stage}: {error}") + except Exception: + pass + + +def safe_write_state( + write_callback: Callable[[], None], + analyser: Optional[Any] = None, + context: Optional[Dict[str, Any]] = None, +) -> bool: + """安全的状态文件写入,带详细的错误处理。 + + 参数: + write_callback: 写入状态的回调函数 + analyser: 分析器对象(可选,用于日志记录) + context: 上下文信息(可选) + + 返回: + bool: 是否成功写入 + """ + if context is None: + context = {} + + try: + write_callback() + return True + except PermissionError as e: + if analyser: + log_reservation_error( + analyser, + e, + {**context, "operation": "写入状态文件"}, + level="ERROR", + stage="状态文件写入(权限错误)", + ) + return False + except OSError as e: + if analyser: + log_reservation_error( + analyser, + e, + {**context, "operation": "写入状态文件"}, + level="ERROR", + stage="状态文件写入(系统错误)", + ) + return False + except (ValueError, TypeError) as e: + if analyser: + log_reservation_error( + analyser, + e, + {**context, "operation": "写入状态文件"}, + level="ERROR", + stage="状态文件写入(数据序列化错误)", + ) + return False + except Exception as e: + if analyser: + log_reservation_error( + analyser, + e, + {**context, "operation": "写入状态文件"}, + level="ERROR", + stage="状态文件写入(未知错误)", + ) + return False + + +def validate_reservation_item(item: ReservationItem) -> Tuple[bool, Optional[str]]: + """验证预约项数据的有效性。 + + 参数: + item: 预约项字典 + + 返回: + (是否有效, 错误信息) + """ + if not isinstance(item, dict): + return False, "预约项不是字典类型" + + # 检查必需字段 + required_fields = ["future_ts", "prize_value_yuan"] + for field in required_fields: + if field not in item: + return False, f"缺少必需字段: {field}" + + # 验证 future_ts + try: + future_ts = float(item.get("future_ts", 0)) + if future_ts <= 0: + return False, f"future_ts 无效: {future_ts}" + except (ValueError, TypeError) as e: + return False, f"future_ts 格式错误: {e}" + + # 验证 prize_value_yuan + try: + prize_value = float(item.get("prize_value_yuan", 0)) + if prize_value < 0: + return False, f"prize_value_yuan 无效: {prize_value}" + except (ValueError, TypeError) as e: + return False, f"prize_value_yuan 格式错误: {e}" + + return True, None + diff --git a/douyin/reservation/douyin_reservation.py b/douyin/reservation/douyin_reservation.py index 78573c9..896856a 100644 --- a/douyin/reservation/douyin_reservation.py +++ b/douyin/reservation/douyin_reservation.py @@ -4,15 +4,105 @@ import json import os import time from datetime import datetime +from typing import Any, Optional + +# 导入预约错误处理工具 +try: + from douyin.reservation.core.reservation_error_utils import ( + log_reservation_error, + format_reservation_context, + ) + _RESERVATION_ERROR_UTILS_AVAILABLE = True +except ImportError: + _RESERVATION_ERROR_UTILS_AVAILABLE = False -def _write_json_atomic(path: str, data: object, *, indent: int = 2) -> None: - os.makedirs(os.path.dirname(path), exist_ok=True) +def _write_json_atomic(path: str, data: object, *, indent: int = 2, analyser: Optional[Any] = None) -> None: + """原子写入 JSON 文件,带详细的错误处理。 + + 参数: + path: 文件路径 + data: 要写入的数据 + indent: JSON 缩进 + analyser: 分析器对象(可选,用于日志记录) + """ + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + except PermissionError as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser: + log_reservation_error( + analyser, + e, + format_reservation_context(path=path), + level="ERROR", + stage="创建状态文件目录(权限错误)", + ) + raise + except OSError as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser: + log_reservation_error( + analyser, + e, + format_reservation_context(path=path), + level="ERROR", + stage="创建状态文件目录(系统错误)", + ) + raise + tmp = path + ".tmp" - with open(tmp, "w", encoding="utf-8") as f: - json.dump(data, f, ensure_ascii=False, indent=indent) - f.write("\n") - os.replace(tmp, path) + try: + with open(tmp, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=indent) + f.write("\n") + except (ValueError, TypeError) as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser: + log_reservation_error( + analyser, + e, + format_reservation_context(path=path), + level="ERROR", + stage="序列化状态数据", + ) + raise + except PermissionError as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser: + log_reservation_error( + analyser, + e, + format_reservation_context(path=path), + level="ERROR", + stage="写入状态文件(权限错误)", + ) + raise + except OSError as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser: + log_reservation_error( + analyser, + e, + format_reservation_context(path=path), + level="ERROR", + stage="写入状态文件(系统错误)", + ) + raise + + try: + os.replace(tmp, path) + except OSError as e: + # 清理临时文件 + try: + if os.path.exists(tmp): + os.remove(tmp) + except Exception: + pass + if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser: + log_reservation_error( + analyser, + e, + format_reservation_context(path=path), + level="ERROR", + stage="原子替换状态文件", + ) + raise def write_reservations_state( @@ -23,8 +113,19 @@ def write_reservations_state( current_room_title: str, current_room_title_raw: str, reason: str = "", + analyser: Optional[Any] = None, ) -> None: - """寫入預約隊列狀態(跨進程可讀)。""" + """寫入預約隊列狀態(跨進程可讀)。 + + 参数: + state_path: 状态文件路径 + reservations: 预约队列列表 + room_pos: 当前房间位置 + current_room_title: 当前房间标题 + current_room_title_raw: 当前房间原始标题 + reason: 写入原因 + analyser: 分析器对象(可选,用于日志记录) + """ try: items: list[dict] = [] for r in reservations or []: @@ -60,12 +161,25 @@ def write_reservations_state( "current_room_title_raw": str(current_room_title_raw or ""), "reservations": items, } - _write_json_atomic(state_path, data, indent=2) + _write_json_atomic(state_path, data, indent=2, analyser=analyser) except Exception as e: - try: - print(f"[预约队列] 写入状态文件失败: {type(e).__name__}: {e}") - except Exception: - pass + if _RESERVATION_ERROR_UTILS_AVAILABLE and analyser: + log_reservation_error( + analyser, + e, + format_reservation_context( + reservations=reservations, + state_path=state_path, + reason=reason, + ), + level="ERROR", + stage="写入预约队列状态", + ) + else: + try: + print(f"[预约队列] 写入状态文件失败: {type(e).__name__}: {e}") + except Exception: + pass def load_high_value_rooms_map(path: str) -> dict[str, dict]: diff --git a/douyin/reservation/douyin_reservation_handler.py b/douyin/reservation/douyin_reservation_handler.py index 48c5ddd..aae1e7e 100644 --- a/douyin/reservation/douyin_reservation_handler.py +++ b/douyin/reservation/douyin_reservation_handler.py @@ -21,6 +21,16 @@ from douyin.reservation import douyin_reservation_logic from douyin.reservation import douyin_reservation_verify from douyin.handlers import douyin_swipe_handler +# 导入预约错误处理工具 +try: + from douyin.reservation.core.reservation_error_utils import ( + log_reservation_error, + format_reservation_context, + ) + _RESERVATION_ERROR_UTILS_AVAILABLE = True +except ImportError: + _RESERVATION_ERROR_UTILS_AVAILABLE = False + class ReservationHandler: """预约处理器:统一管理预约操作""" @@ -124,15 +134,27 @@ class ReservationHandler: return None except Exception as e: - try: - analyser._log_kv( # type: ignore[attr-defined] - "预约", - "[预约] _find_room_pos_by_title:查找时出错", - error=str(e), - error_type=type(e).__name__, + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + target_title=target_title[:50] if target_title else "", + target_title_raw=target_title_raw[:50] if target_title_raw else "", + ), + level="WARNING", + stage="根据标题查找位置", ) - except Exception: - pass + else: + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] _find_room_pos_by_title:查找时出错", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass return None @staticmethod # type: ignore[misc] @@ -224,8 +246,28 @@ class ReservationHandler: pass except Exception: pass - except Exception: - pass + # 记录读取标题失败的错误 + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + room_pos=room_pos, + ), + level="WARNING", + stage="读取直播间标题", + ) + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context(), + level="WARNING", + stage="记录直播间标题和位置", + ) + else: + pass @staticmethod # type: ignore[misc] def seek_reservation_room(analyser: Any, item: Dict[str, Any]) -> bool: diff --git a/douyin/reservation/douyin_reservation_logic.py b/douyin/reservation/douyin_reservation_logic.py index 9f98036..964a5eb 100644 --- a/douyin/reservation/douyin_reservation_logic.py +++ b/douyin/reservation/douyin_reservation_logic.py @@ -18,6 +18,18 @@ from typing import Any, Dict, List, Callable, Optional import time import re +# 导入预约错误处理工具 +try: + from douyin.reservation.core.reservation_error_utils import ( + log_reservation_error, + safe_write_state, + format_reservation_context, + validate_reservation_item, + ) + _RESERVATION_ERROR_UTILS_AVAILABLE = True +except ImportError: + _RESERVATION_ERROR_UTILS_AVAILABLE = False + ReservationItem = Dict[str, Any] @@ -150,8 +162,20 @@ def add_reservation_core_logic( queue_len_before=len(reservations), max_reservations=max_reservations, ) - except Exception: - pass + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context(item=item, reservations=reservations), + level="WARNING", + stage="记录函数入口日志", + ) + else: + try: + analyser._log_kv("预约", "[预约] 记录函数入口日志失败", error=str(e)) + except Exception: + pass same_idx: Optional[int] = None for idx, r in enumerate(reservations): @@ -361,10 +385,30 @@ def add_reservation_core_logic( # 如果队列已满,写入状态文件 if write_state_callback: - try: - write_state_callback() - except Exception: - pass + if _RESERVATION_ERROR_UTILS_AVAILABLE: + safe_write_state( + write_state_callback, + analyser, + format_reservation_context( + item=item, + reservations=reservations, + queue_full=True, + dropped_count=len(dropped_items) if dropped_items else 0, + ), + ) + else: + try: + write_state_callback() + except Exception as e: + try: + analyser._log_kv( + "预约", + "[预约] 写入状态文件失败(队列已满)", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass # 添加函数完成日志 try: @@ -376,8 +420,20 @@ def add_reservation_core_logic( queue_full=queue_full, elapsed_seconds=round(elapsed, 3), ) - except Exception: - pass + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context(item=item, reservations=reservations), + level="WARNING", + stage="记录函数完成日志", + ) + else: + try: + analyser._log_kv("预约", "[预约] 记录函数完成日志失败", error=str(e)) + except Exception: + pass return queue_full @@ -666,7 +722,7 @@ def handle_queue_full_wait_at_earliest( target_pos = int(earliest.get("pos_seen") or 0) except Exception: target_pos = 0 - pos_diff = current_room_pos - target_pos + _pos_diff = current_room_pos - target_pos # 位置差(用于调试,当前未使用) # 直接调用回退回调,不需要预先下滑 # 原因: @@ -784,8 +840,17 @@ def process_reservation_attend_window( reservations_count=len(reservations) if reservations else 0, room_pos=room_pos, ) - except Exception: - pass + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context(reservations=reservations), + level="WARNING", + stage="记录函数入口日志", + ) + else: + pass if not reservations: try: @@ -793,8 +858,17 @@ def process_reservation_attend_window( "预约", "[预约] process_reservation_attend_window:预约队列为空,跳过", ) - except Exception: - pass + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + {}, + level="WARNING", + stage="记录队列为空日志", + ) + else: + pass return False now_ts = _now_ts() @@ -834,13 +908,36 @@ def process_reservation_attend_window( except Exception: pass reservations.pop(0) - try: - write_state_callback() - except Exception: - pass + if _RESERVATION_ERROR_UTILS_AVAILABLE: + safe_write_state( + write_state_callback, + analyser, + format_reservation_context( + item=target, + reservations=reservations, + reason="已参与过", + ), + ) + else: + try: + write_state_callback() + except Exception: + pass return False - except Exception: - pass + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=target, + reservations=reservations, + ), + level="WARNING", + stage="检查是否已参与", + ) + else: + pass # 添加目标预约的详细信息日志 try: @@ -870,10 +967,21 @@ def process_reservation_attend_window( except Exception: pass reservations.pop(0) - try: - write_state_callback() - except Exception: - pass + if _RESERVATION_ERROR_UTILS_AVAILABLE: + safe_write_state( + write_state_callback, + analyser, + format_reservation_context( + item=target, + reservations=reservations, + reason="future_ts 无效", + ), + ) + else: + try: + write_state_callback() + except Exception: + pass return False # 仅在"即将开奖窗口"(包括已过一小段时间)内才触发回退 @@ -1192,15 +1300,30 @@ def process_reservation_attend_window( try: ok = bool(seek_reservation_room_callback(target)) except Exception as e: - try: - analyser._log_kv( - "预约", - "[预约] 执行回退时发生异常", - error=str(e), - error_type=type(e).__name__, + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=target, + reservations=reservations, + current_room_pos=current_room_pos, + target_pos=target_pos, + pos_diff=pos_diff, + ), + level="ERROR", + stage="执行回退操作", ) - except Exception: - pass + else: + try: + analyser._log_kv( + "预约", + "[预约] 执行回退时发生异常", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass ok = False if ok: @@ -1273,15 +1396,30 @@ def process_reservation_attend_window( except Exception: pass if not verify_ok: - try: - analyser._log_kv( - "预约", - "[预约] 回退校验失败:回退操作成功但校验未通过,尝试根据映射表自动回退到正确位置", - target_pos=int(target.get("pos_seen", 0)), - target_room_title=target_room_title[:50] if target_room_title else "", + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + Exception("回退校验失败:回退操作成功但校验未通过"), + format_reservation_context( + item=target, + reservations=reservations, + verify_detail=verify_detail, + target_pos=int(target.get("pos_seen", 0)), + target_room_title=target_room_title[:50] if target_room_title else "", + ), + level="WARNING", + stage="回退校验", ) - except Exception: - pass + else: + try: + analyser._log_kv( + "预约", + "[预约] 回退校验失败:回退操作成功但校验未通过,尝试根据映射表自动回退到正确位置", + target_pos=int(target.get("pos_seen", 0)), + target_room_title=target_room_title[:50] if target_room_title else "", + ) + except Exception: + pass # 校验失败,尝试根据映射表查找正确位置并自动回退 try: @@ -1650,27 +1788,55 @@ def record_high_value_reservation( "%Y-%m-%d %H:%M:%S" ) except Exception as e: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:计算 future_str 失败", - error=str(e), - error_type=type(e).__name__, + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + future_timestamp=future_timestamp, + prize_value_yuan=prize_value_yuan, + ), + level="WARNING", + stage="计算 future_str", ) - except Exception: - pass + else: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:计算 future_str 失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass # 验证 reservations 列表 if not isinstance(reservations, list): - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:reservations 不是列表", - reservations_type=type(reservations).__name__, - error_type="InvalidParameter", - ) - except Exception: - pass + if _RESERVATION_ERROR_UTILS_AVAILABLE: + try: + raise TypeError(f"reservations 不是列表类型,而是 {type(reservations).__name__}") + except TypeError as e: + log_reservation_error( + analyser, + e, + format_reservation_context( + reservations_type=type(reservations).__name__, + prize_value_yuan=prize_value_yuan, + future_timestamp=future_timestamp, + ), + level="ERROR", + stage="验证 reservations 列表", + ) + else: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:reservations 不是列表", + reservations_type=type(reservations).__name__, + error_type="InvalidParameter", + ) + except Exception: + pass return False # 构造预约项 @@ -1690,63 +1856,113 @@ def record_high_value_reservation( "copies": int(copies or 0), } except Exception as e: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:构造预约项失败", - error=str(e), - error_type=type(e).__name__, - prize_value_yuan=prize_value_yuan, - future_timestamp=future_timestamp, - room_pos=room_pos, + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + prize_value_yuan=prize_value_yuan, + future_timestamp=future_timestamp, + room_pos=room_pos, + room_title=room_title, + room_title_raw=room_title_raw, + ), + level="ERROR", + stage="构造预约项", ) - except Exception: - pass + else: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:构造预约项失败", + error=str(e), + error_type=type(e).__name__, + prize_value_yuan=prize_value_yuan, + future_timestamp=future_timestamp, + room_pos=room_pos, + ) + except Exception: + pass return False # 调用回调函数添加预约 try: add_reservation_callback(reservations, item) except Exception as e: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:add_reservation_callback 失败", - error=str(e), - error_type=type(e).__name__, - queue_len_before=len(reservations), + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=item, + reservations=reservations, + queue_len_before=len(reservations), + ), + level="ERROR", + stage="调用 add_reservation_callback", ) - except Exception: - pass + else: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:add_reservation_callback 失败", + error=str(e), + error_type=type(e).__name__, + queue_len_before=len(reservations), + ) + except Exception: + pass return False # 排序预约队列 try: sort_reservations_callback() except Exception as e: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:sort_reservations_callback 失败", - error=str(e), - error_type=type(e).__name__, + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=item, + reservations=reservations, + ), + level="WARNING", + stage="调用 sort_reservations_callback", ) - except Exception: - pass + else: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:sort_reservations_callback 失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass # 写入状态文件 - try: - write_state_callback() - except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + safe_write_state( + write_state_callback, + analyser, + format_reservation_context( + item=item, + reservations=reservations, + ), + ) + else: try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:write_state_callback 失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass + write_state_callback() + except Exception as e: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:write_state_callback 失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass # 记录成功日志 try: diff --git a/douyin/reservation/douyin_reservation_verify.py b/douyin/reservation/douyin_reservation_verify.py index a076bd4..08f05f2 100644 --- a/douyin/reservation/douyin_reservation_verify.py +++ b/douyin/reservation/douyin_reservation_verify.py @@ -13,10 +13,19 @@ from __future__ import annotations from typing import Any, Dict, Tuple, Optional import re import difflib -import time from douyin.fudai import douyin_fudai_detail +# 导入预约错误处理工具 +try: + from douyin.reservation.core.reservation_error_utils import ( + log_reservation_error, + format_reservation_context, + ) + _RESERVATION_ERROR_UTILS_AVAILABLE = True +except ImportError: + _RESERVATION_ERROR_UTILS_AVAILABLE = False + def _compact_text(text: str) -> str: """压缩文本:去除空格,用于比较。""" @@ -53,7 +62,7 @@ def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, D "expected_content": expected_content, } - fc, tt, participants, copies, pv, cd = detail[:6] + fc, _tt, _participants, _copies, pv, cd = detail[:6] actual_content = _compact_text(fc or "") try: actual_value = float(pv or 0.0) @@ -263,15 +272,26 @@ def validate_back_to_reservation( except Exception: pass except Exception as e: - try: - analyser._log_kv( - "预约", - "回退校验:运行时映射表验证时出错", - error=str(e), - error_type=type(e).__name__, + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=item, + ), + level="WARNING", + stage="运行时映射表验证", ) - except Exception: - pass + else: + try: + analyser._log_kv( + "预约", + "回退校验:运行时映射表验证时出错", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass if expected_title: try: @@ -346,7 +366,7 @@ def validate_back_to_reservation( # 重新读取标题验证 try: y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) - new_title, new_title_raw = douyin_fudai_detail.read_live_room_title_core( + new_title, _new_title_raw = douyin_fudai_detail.read_live_room_title_core( analyser, y_pianyi_val ) if new_title: @@ -381,14 +401,26 @@ def validate_back_to_reservation( pass return False, None except Exception as e: - try: - analyser._log_kv( - "预约", - "回退校验:根据映射表回退后,重新读取标题失败", - error=str(e), + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=item, + expected_title=expected_title[:50] if expected_title else "", + ), + level="WARNING", + stage="根据映射表回退后重新读取标题", ) - except Exception: - pass + else: + try: + analyser._log_kv( + "预约", + "回退校验:根据映射表回退后,重新读取标题失败", + error=str(e), + ) + except Exception: + pass return False, None else: try: @@ -400,15 +432,27 @@ def validate_back_to_reservation( pass return False, None except Exception as e: - try: - analyser._log_kv( - "预约", - "回退校验:根据映射表回退时出错", - error=str(e), - error_type=type(e).__name__, + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=item, + expected_title=expected_title[:50] if expected_title else "", + ), + level="WARNING", + stage="根据映射表回退", ) - except Exception: - pass + else: + try: + analyser._log_kv( + "预约", + "回退校验:根据映射表回退时出错", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass return False, None else: try: @@ -430,21 +474,44 @@ def validate_back_to_reservation( pass return False, None except Exception as e: - try: - analyser._log_kv( - "预约", - "回退校验:根据映射表查找位置时出错", - error=str(e), - error_type=type(e).__name__, + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=item, + expected_title=expected_title[:50] if expected_title else "", + ), + level="WARNING", + stage="根据映射表查找位置", ) - except Exception: - pass + else: + try: + analyser._log_kv( + "预约", + "回退校验:根据映射表查找位置时出错", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass return False, None except Exception as e: - try: - analyser._log_kv("预约", "回退校验:读取直播间标题失败", error=str(e)) - except Exception: - pass + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=item, + ), + level="WARNING", + stage="读取直播间标题(外层)", + ) + else: + try: + analyser._log_kv("预约", "回退校验:读取直播间标题失败", error=str(e)) + except Exception: + pass # 如果标题匹配或没有标题,校验通过 try: diff --git a/douyin/stage/douyin_stage.py b/douyin/stage/douyin_stage.py index 625580e..9cf8be3 100644 --- a/douyin/stage/douyin_stage.py +++ b/douyin/stage/douyin_stage.py @@ -85,7 +85,8 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90 pic_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) - pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + import path_config + pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): pic_rgb = douyin_pixel._safe_open_screenshot_rgb(pic_path) if pic_rgb is not None: diff --git a/douyin/utils/douyin_config.py b/douyin/utils/douyin_config.py index 70d41b5..c13da1c 100644 --- a/douyin/utils/douyin_config.py +++ b/douyin/utils/douyin_config.py @@ -26,7 +26,13 @@ class ConfigManager: config_path: 配置文件路径,如果为 None 则使用 analyser.config_path """ if config_path is None: - config_path = getattr(analyser, "config_path", "config/config.json") + try: + import path_config + default_config_path = path_config.get_config_path() + except Exception: + import path_config + default_config_path = path_config.get_config_path() + config_path = getattr(analyser, "config_path", default_config_path) # 如果 config_path 仍然为 None,直接返回(使用默认值) if config_path is None: diff --git a/douyin/utils/douyin_helpers.py b/douyin/utils/douyin_helpers.py index 647d550..5cfe1b5 100644 --- a/douyin/utils/douyin_helpers.py +++ b/douyin/utils/douyin_helpers.py @@ -70,7 +70,8 @@ class HelperFunctions: pic_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) - pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + import path_config + pic_path = path_config.get_screenshot_path() # 获取分辨率比例和y偏移参数 resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) diff --git a/douyin_guaji.code-workspace b/douyin_guaji.code-workspace index c2c3c5e..20d7215 100644 --- a/douyin_guaji.code-workspace +++ b/douyin_guaji.code-workspace @@ -39,3 +39,8 @@ + + + + + diff --git a/fudai_detail_modules/fudai_detail_coupon_detection.py b/fudai_detail_modules/fudai_detail_coupon_detection.py index bb7d077..b08370a 100644 --- a/fudai_detail_modules/fudai_detail_coupon_detection.py +++ b/fudai_detail_modules/fudai_detail_coupon_detection.py @@ -43,7 +43,8 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) - path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + import path_config + path = path_config.get_screenshot_path() try: pic = Image.open(path) pic.load() # Force load to catch truncated files early @@ -237,7 +238,8 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: pic_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) - pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + import path_config + pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): pic_check = Image.open(pic_path) pic_check.load() diff --git a/fudai_detail_modules/fudai_detail_reader.py b/fudai_detail_modules/fudai_detail_reader.py index 48a54a7..ad2c8d1 100644 --- a/fudai_detail_modules/fudai_detail_reader.py +++ b/fudai_detail_modules/fudai_detail_reader.py @@ -105,7 +105,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: pic_path = path_config.get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) - pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + import path_config + pic_path = path_config.get_screenshot_path() pic_rgb = None try: if os.path.exists(pic_path): @@ -345,7 +346,12 @@ def read_fudai_detail_with_retries( already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False) if already_verified: # 已经验证过,只需要短暂等待确保界面稳定 - initial_wait = 0.3 + # 使用配置项,默认0.2秒(比之前的0.3秒更快) + initial_wait = float( + getattr(analyser, "fudai_detail_verified_wait_seconds", 0.2) or 0.2 + ) + if initial_wait < 0.1: + initial_wait = 0.1 # 最小0.1秒 try: analyser._log_kv( "福袋详情", @@ -360,11 +366,12 @@ def read_fudai_detail_with_retries( except Exception: pass else: + # 未验证情况,使用配置项,默认0.8秒(比之前的1.2秒更快) initial_wait = float( - getattr(analyser, "fudai_detail_initial_wait_seconds", 1.2) or 1.2 + getattr(analyser, "fudai_detail_initial_wait_seconds", 0.8) or 0.8 ) - if initial_wait < 0.8: - initial_wait = 0.8 # 最小0.8秒 + if initial_wait < 0.5: + initial_wait = 0.5 # 最小0.5秒 try: analyser.operation.delay(initial_wait) except Exception: @@ -377,11 +384,14 @@ def read_fudai_detail_with_retries( max_attempts = 2 if max_attempts < 1: max_attempts = 1 - retry_delay = 0.8 + # 使用配置项,默认0.5秒(比之前的0.8秒更快) + retry_delay = 0.5 try: - retry_delay = float(getattr(analyser, "fudai_detail_retry_delay_seconds", 0.8) or 0.8) + retry_delay = float(getattr(analyser, "fudai_detail_retry_delay_seconds", 0.5) or 0.5) except Exception: - retry_delay = 0.8 + retry_delay = 0.5 + if retry_delay < 0.3: + retry_delay = 0.3 # 最小0.3秒 last_tuple: Optional[Tuple] = None last_status: str = "error" @@ -414,6 +424,34 @@ def read_fudai_detail_with_retries( first_tuple = current_tuple first_attempt_time = attempt_start_time last_tuple = current_tuple + + # 优化:如果第一次识别成功且数据合理,直接返回,不进行第二次重试 + # 检查数据是否合理(有内容、有价值、倒计时合理) + content = current_tuple[0] if len(current_tuple) > 0 else "" + prize_value = current_tuple[4] if len(current_tuple) > 4 else 0.0 + time_text = current_tuple[1] if len(current_tuple) > 1 else "" + + # 如果数据看起来合理(有内容或价值>0,倒计时合理),直接返回 + is_data_reasonable = ( + (content and len(content.strip()) > 0) or + (prize_value and float(prize_value) > 0) or + (time_text and len(time_text.strip()) > 0) + ) + + if is_data_reasonable and current_countdown_seconds > 0: + try: + analyser._log_kv( + "福袋详情", + "read_fudai_detail_with_retries:第一次识别成功且数据合理,跳过重试", + attempt=attempt + 1, + content_preview=content[:30] if content else "", + prize_value=prize_value, + countdown_seconds=int(current_countdown_seconds), + ) + except Exception: + pass + # 直接返回,不进行第二次重试 + break # 倒计时一致性检查:如果后续读取的倒计时与第一次差异过大,判定为识别错误 elif first_countdown_seconds is not None and current_countdown_seconds is not None: diff --git a/fudai_detail_modules/fudai_detail_room_title.py b/fudai_detail_modules/fudai_detail_room_title.py index 491be1f..661a385 100644 --- a/fudai_detail_modules/fudai_detail_room_title.py +++ b/fudai_detail_modules/fudai_detail_room_title.py @@ -9,6 +9,7 @@ from __future__ import annotations from typing import Any, Tuple, List import re +import time def _room_title_has_ellipsis(s: str) -> bool: @@ -170,7 +171,35 @@ def read_live_room_title_core( ) except Exception: pass - + # 如果是切换直播间后立即调用,等待标题区域出现(避免识别到空白或旧截图) + try: + if getattr(analyser, "_just_switched_room", False): + wait_seconds = float(getattr(analyser, "switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0) + poll_interval = 0.5 + start_ts = time.time() + while time.time() - start_ts < wait_seconds: + try: + # 先截图并切割 mid 区域做快速检测(使用临时名字,不覆盖正式裁剪) + analyser.operation.get_screenshot(analyser.device_id) + analyser.cut_pic(80, 128, 560, 230, "", "live_room_title_mid_tmp", y_pianyi) + txt = analyser.operation.analyse_pic_word("live_room_title_mid_tmp", 0) + if txt and str(txt).strip(): + break + except Exception: + pass + # 在等待期间执行可选的后台任务(例如处理弹窗等),以提高并发性 + try: + if hasattr(analyser, "background_tick") and callable(getattr(analyser, "background_tick")): + analyser.background_tick() + except Exception: + pass + time.sleep(poll_interval) + try: + analyser._just_switched_room = False + except Exception: + pass + except Exception: + pass cands: List[Tuple[str, str, str]] = [] # mid ROI:优先使用更大区域,减少"只截到尾巴1个字" @@ -208,7 +237,7 @@ def read_live_room_title_core( # small ROI:最后兜底(历史区域),使用优化后的坐标 if not cands or max(len(x[0] or "") for x in cands) <= 1: try: - analyser.cut_pic(147, 147, 320, 188, '', 'live_room_title_small', y_pianyi) + analyser.cut_pic(147, 160, 301, 191, '', '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: diff --git a/fudai_detail_modules/fudai_detail_validator.py b/fudai_detail_modules/fudai_detail_validator.py index 5611f44..36c2575 100644 --- a/fudai_detail_modules/fudai_detail_validator.py +++ b/fudai_detail_modules/fudai_detail_validator.py @@ -70,7 +70,12 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st if remain_seconds == 0 and not time_text: return False, "countdown_zero_and_no_time_text" # 倒计时合理性检查:如果 time_text 存在,验证倒计时与 time_text 是否一致 - if time_text: + # 注意:如果analyser存在且处于强制参与模式(预约回退),跳过此检查 + force_attend = False + if analyser: + force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) + + if time_text and not force_attend: try: # 解析 time_text 为秒数 m = re.search(r"(\d{1,2})[::](\d{1,2})", time_text) diff --git a/gui/components/__init__.py b/gui/components/__init__.py index 8fdcfc9..1f03c1c 100644 --- a/gui/components/__init__.py +++ b/gui/components/__init__.py @@ -6,3 +6,8 @@ + + + + + diff --git a/gui/components/actions_log_viewer.py b/gui/components/actions_log_viewer.py index 5e1595d..020046c 100644 --- a/gui/components/actions_log_viewer.py +++ b/gui/components/actions_log_viewer.py @@ -47,8 +47,8 @@ def create_actions_log_viewer( path = path_config.get_actions_log_path() except Exception: # 回退到旧路径(向后兼容) - path = os.path.join(os.path.dirname(__file__), "..", "logs", "actions.log") - path = os.path.abspath(path) + import path_config + path = path_config.get_actions_log_path() try: if os.path.exists(path): diff --git a/gui/components/config_manager.py b/gui/components/config_manager.py index 210f56f..349aafe 100644 --- a/gui/components/config_manager.py +++ b/gui/components/config_manager.py @@ -46,3 +46,8 @@ def save_ui_to_config( + + + + + diff --git a/gui/components/device_selector.py b/gui/components/device_selector.py index 8e93f0b..c970c32 100644 --- a/gui/components/device_selector.py +++ b/gui/components/device_selector.py @@ -56,3 +56,8 @@ def create_device_selector( + + + + + diff --git a/gui/components/image_viewer.py b/gui/components/image_viewer.py index 9fac6e9..2d88608 100644 --- a/gui/components/image_viewer.py +++ b/gui/components/image_viewer.py @@ -42,3 +42,8 @@ def create_image_viewer( + + + + + diff --git a/gui/components/main_window.py b/gui/components/main_window.py index d72f1a3..9a93b3c 100644 --- a/gui/components/main_window.py +++ b/gui/components/main_window.py @@ -38,3 +38,8 @@ def create_main_window( + + + + + diff --git a/gui/components/ocr_panel.py b/gui/components/ocr_panel.py index f284cf7..4a6debb 100644 --- a/gui/components/ocr_panel.py +++ b/gui/components/ocr_panel.py @@ -39,3 +39,8 @@ def create_ocr_panel( + + + + + diff --git a/gui/gui_app.py b/gui/gui_app.py index 4cd2f3b..4697fe1 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -8,6 +8,12 @@ import warnings from datetime import datetime from typing import Any, Callable +# 确保项目根目录在 Python 路径中(支持直接运行 gui/gui_app.py) +_script_dir = os.path.dirname(os.path.abspath(__file__)) +_project_root = os.path.dirname(_script_dir) +if _project_root not in sys.path: + sys.path.insert(0, _project_root) + from PIL import Image, ImageTk # 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化) @@ -1570,9 +1576,9 @@ def main(): # OCR区域配置:定义所有需要识别的区域(坐标基于1080x2400基准) OCR_REGIONS = [ # (区域名称, (x1, y1, x2, y2), 描述) - ("福袋内容", (390, 1240, 980, 1470), "福袋内容详情"), + ("福袋内容", (389, 1273, 1000, 1534), "福袋内容详情"), ("福袋倒计时", (390, 1470, 980, 1580), "福袋倒计时"), - ("福袋价值", (390, 1460, 1000, 1580), "奖品价值/价格"), + ("福袋价值", (390, 1440, 1000, 1580), "奖品价值/价格"), ("抽奖结果", (380, 660, 720, 755), "抽奖结果弹窗"), ("推荐页标签栏", (400, 140, 900, 200), "推荐/关注/直播标签"), ("推荐页标签栏快速检测", (400, 140, 900, 200), "推荐页快速检测"), @@ -1620,9 +1626,13 @@ def main(): root.after(0, log_msg("[截图] 截图成功,已保存到 pic/screenshot.png")) # type: ignore[arg-type] # 读取截图以获取实际尺寸 - screenshot_path = os.path.join( - os.path.dirname(__file__), "pic", "screenshot.png" - ) + try: + from path_config import get_screenshot_path + screenshot_path = get_screenshot_path() + except Exception: + # 回退到旧路径(向后兼容) + import path_config + screenshot_path = path_config.get_screenshot_path() if not os.path.exists(screenshot_path): root.after(0, log_msg("[OCR] 截图文件不存在")) # type: ignore[arg-type] return @@ -1886,7 +1896,13 @@ def main(): preview_top = ttk.Frame(preview_tab) preview_top.pack(fill=X, padx=10, pady=10) - images_dir = os.path.join(os.path.dirname(__file__), "pic") + try: + from path_config import get_pic_dir + images_dir = get_pic_dir() + except Exception: + # 回退到旧路径(向后兼容) + import path_config + images_dir = path_config.get_pic_dir() def scan_image_files(): """扫描pic文件夹及其子文件夹中的所有图片文件""" @@ -2905,7 +2921,13 @@ def main(): pass def refresh_reservations(): - path = os.path.join(os.path.dirname(__file__), "state", "reservations.json") + try: + from path_config import get_reservations_path + path = get_reservations_path() + except Exception: + # 回退到旧路径(向后兼容) + import path_config + path = path_config.get_reservations_path() try: if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: @@ -3133,7 +3155,13 @@ def main(): pass def refresh_high_value_rooms(): - path = os.path.join(os.path.dirname(__file__), "state", "high_value_rooms.json") + try: + from path_config import get_high_value_rooms_path + path = get_high_value_rooms_path() + except Exception: + # 回退到旧路径(向后兼容) + import path_config + path = path_config.get_high_value_rooms_path() try: if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: @@ -3173,7 +3201,9 @@ def main(): path = get_actions_log_path() except Exception: # 回退到旧路径(向后兼容) - path = os.path.join(os.path.dirname(__file__), "logs", "actions.log") + # 修正路径:GUI应该读取根目录的logs/actions.log + import path_config + path = path_config.get_actions_log_path() try: if os.path.exists(path): # 仿照 web_gui 的实现:只读最后一小段,避免文件巨大 @@ -3405,8 +3435,14 @@ def main(): def auto_refresh_actions_log() -> None: refresh_actions_log() root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type] - + + # 定期刷新预约队列(每5秒) + def auto_refresh_reservations() -> None: + refresh_reservations() + root.after(5000, auto_refresh_reservations) # type: ignore[arg-type] + root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type] + root.after(5000, auto_refresh_reservations) # type: ignore[arg-type] # 定期刷新统计信息(每3秒) def auto_refresh_stats() -> None: diff --git a/gui/gui_core.py b/gui/gui_core.py index 1e39773..b020716 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -10,8 +10,9 @@ import time from dataclasses import dataclass from typing import Optional +import path_config -CONFIG_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config", "config.json") +CONFIG_PATH = path_config.get_config_path() def find_adb_executable() -> str: @@ -717,9 +718,16 @@ class Runner: # 如果 wait_minutes=0,表示无限循环模式 wait_minutes_arg = str(params.wait_minutes) if params.wait_minutes > 0 else "0" + run_cli_path = path_config.get_run_cli_path() + if not os.path.exists(run_cli_path): + raise FileNotFoundError( + f"未找到 run_cli.py 文件。\n" + f"预期路径: {run_cli_path}\n" + f"请确保 run_cli.py 位于项目根目录。" + ) cmd = [ sys.executable, - os.path.join(os.path.dirname(__file__), "run_cli.py"), + run_cli_path, "--y-pianyi", str(params.y_pianyi), "--wait-minutes", @@ -808,7 +816,7 @@ class Runner: encoding="utf-8", errors="replace", env=env, - cwd=os.path.dirname(__file__), + cwd=path_config.PROJECT_ROOT, ) with self._lock: @@ -857,9 +865,16 @@ class Runner: if seconds <= 0: seconds = 90 + run_cli_path = path_config.get_run_cli_path() + if not os.path.exists(run_cli_path): + raise FileNotFoundError( + f"未找到 run_cli.py 文件。\n" + f"预期路径: {run_cli_path}\n" + f"请确保 run_cli.py 位于项目根目录。" + ) cmd = [ sys.executable, - os.path.join(os.path.dirname(__file__), "run_cli.py"), + run_cli_path, "--test-yanghao-flow", "--test-yanghao-flow-seconds", str(seconds), @@ -886,7 +901,7 @@ class Runner: encoding="utf-8", errors="replace", env=env, - cwd=os.path.dirname(__file__), + cwd=path_config.PROJECT_ROOT, ) with self._lock: @@ -932,9 +947,16 @@ class Runner: raise RuntimeError("已经在运行") text = str(text or "").strip() + run_cli_path = path_config.get_run_cli_path() + if not os.path.exists(run_cli_path): + raise FileNotFoundError( + f"未找到 run_cli.py 文件。\n" + f"预期路径: {run_cli_path}\n" + f"请确保 run_cli.py 位于项目根目录。" + ) cmd = [ sys.executable, - os.path.join(os.path.dirname(__file__), "run_cli.py"), + run_cli_path, "--test-comment", ] if text: @@ -961,7 +983,7 @@ class Runner: encoding="utf-8", errors="replace", env=env, - cwd=os.path.dirname(__file__), + cwd=path_config.PROJECT_ROOT, ) with self._lock: diff --git a/gui/web_components/__init__.py b/gui/web_components/__init__.py index 5b5ec84..dc9ed0f 100644 --- a/gui/web_components/__init__.py +++ b/gui/web_components/__init__.py @@ -6,3 +6,8 @@ + + + + + diff --git a/gui/web_components/proc_runner.py b/gui/web_components/proc_runner.py index d1cea86..4ede202 100644 --- a/gui/web_components/proc_runner.py +++ b/gui/web_components/proc_runner.py @@ -14,3 +14,8 @@ __all__ = ["ProcRunner"] + + + + + diff --git a/gui/web_gui.py b/gui/web_gui.py index cf07971..d8a4f81 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -11,9 +11,11 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Optional from urllib.parse import parse_qs, urlparse -BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -CONFIG_PATH = os.path.join(BASE_DIR, "config", "config.json") -WEBUI_DIR = os.path.join(BASE_DIR, "webui") +import path_config + +BASE_DIR = path_config.PROJECT_ROOT +CONFIG_PATH = path_config.get_config_path() +WEBUI_DIR = path_config.get_webui_dir() # ANSI转义序列清理正则表达式 _ANSI_ESCAPE_RE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") @@ -85,7 +87,7 @@ class ProcRunner: 10000 # 0=不限制(可能占用大量内存),增加到10000避免日志被过早截断 ) self._log_file_enabled: bool = True - self._log_file_path: str = os.path.join(BASE_DIR, "logs", "unified.log") + self._log_file_path: str = path_config.get_log_file_path() self._start_ts: Optional[float] = None self._last_log_ts: Optional[float] = None self._exit_code: Optional[int] = None @@ -124,7 +126,7 @@ class ProcRunner: path = str(cfg.get("log_unified_path") or "logs/unified.log") if not os.path.isabs(path): - path = os.path.join(BASE_DIR, path) + path = os.path.join(path_config.PROJECT_ROOT, path) self._log_file_path = path try: @@ -822,8 +824,13 @@ class ProcRunner: return self._proc is not None and self._proc.poll() is None def get_reservations(self) -> dict: - """获取当前预约队列信息(来自子进程写入的 state/reservations.json)。""" - path = os.path.join(BASE_DIR, "state", "reservations.json") + """获取当前预约队列信息(来自子进程写入的 douyin/core/state/reservations.json)。""" + try: + import path_config + path = path_config.get_reservations_path() + except Exception: + # 回退到旧路径(向后兼容) + path = path_config.get_reservations_path() try: if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: @@ -846,7 +853,7 @@ class ProcRunner: def get_high_value_rooms(self) -> dict: """获取永久记录的高价值直播间列表(来自 state/high_value_rooms.json)。""" - path = os.path.join(BASE_DIR, "state", "high_value_rooms.json") + path = path_config.get_high_value_rooms_path() try: if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: @@ -1080,9 +1087,16 @@ class ProcRunner: if seconds <= 0: seconds = 60 + run_cli_path = path_config.get_run_cli_path() + if not os.path.exists(run_cli_path): + raise FileNotFoundError( + f"run_cli.py not found.\n" + f"Expected path: {run_cli_path}\n" + f"Please ensure run_cli.py is in the project root directory." + ) cmd = [ sys.executable, - os.path.join(BASE_DIR, "run_cli.py"), + run_cli_path, "--test-yanghao-flow", "--test-yanghao-flow-seconds", str(seconds), @@ -1097,9 +1111,16 @@ class ProcRunner: raise RuntimeError("already running") text = str(text or "").strip() + run_cli_path = path_config.get_run_cli_path() + if not os.path.exists(run_cli_path): + raise FileNotFoundError( + f"run_cli.py not found.\n" + f"Expected path: {run_cli_path}\n" + f"Please ensure run_cli.py is in the project root directory." + ) cmd = [ sys.executable, - os.path.join(BASE_DIR, "run_cli.py"), + run_cli_path, "--test-comment", ] if text: @@ -1169,9 +1190,16 @@ class ProcRunner: str(_pick("fansclub_fail_action", "") or "").strip().lower() ) + run_cli_path = path_config.get_run_cli_path() + if not os.path.exists(run_cli_path): + raise FileNotFoundError( + f"run_cli.py not found.\n" + f"Expected path: {run_cli_path}\n" + f"Please ensure run_cli.py is in the project root directory." + ) cmd = [ sys.executable, - os.path.join(BASE_DIR, "run_cli.py"), + run_cli_path, "--y-pianyi", str(y_pianyi), "--wait-minutes", @@ -1295,7 +1323,7 @@ class ProcRunner: encoding="utf-8", errors="replace", env=env, - cwd=BASE_DIR, + cwd=path_config.PROJECT_ROOT, bufsize=1, # 行缓冲模式,确保实时输出 ) @@ -1524,7 +1552,7 @@ class Handler(BaseHTTPRequestHandler): path = ( RUNNER._log_file_path if hasattr(RUNNER, "_log_file_path") - else os.path.join(BASE_DIR, "logs", "unified.log") + else path_config.get_log_file_path() ) out_lines = [] try: @@ -1555,7 +1583,7 @@ class Handler(BaseHTTPRequestHandler): path = path_config.get_actions_log_path() except Exception: # 回退到旧路径(向后兼容) - path = os.path.join(BASE_DIR, "logs", "actions.log") + path = path_config.get_actions_log_path() out_lines: list[str] = [] try: if os.path.exists(path): @@ -1580,7 +1608,7 @@ class Handler(BaseHTTPRequestHandler): if not safe.startswith("pic/"): self.send_error(HTTPStatus.FORBIDDEN) return - full = os.path.join(BASE_DIR, safe) + full = os.path.join(path_config.PROJECT_ROOT, safe) if not os.path.isfile(full): self.send_error(HTTPStatus.NOT_FOUND) return diff --git a/ocr_compare_results.csv b/ocr_compare_results.csv new file mode 100644 index 0000000..6ecb6d8 --- /dev/null +++ b/ocr_compare_results.csv @@ -0,0 +1,2 @@ +path,whole_time,whole_text,crop_time,crop_text +pic\debug_captures\2025-12-28\20251228_190754_ocr_绂忚浠诲姟鍒楄〃_after_ocr_mode_0_used_img2_False_avg_confidence_0.9496.png,0.0,,0.0, diff --git a/operations/screenshot_operations.py b/operations/screenshot_operations.py index e264e34..334064b 100644 --- a/operations/screenshot_operations.py +++ b/operations/screenshot_operations.py @@ -38,7 +38,13 @@ class ScreenshotOperations: def get_screenshot(self, device_id, path="pic") -> bool: """截图3个adb命令需要2S左右的时间""" if path == "pic": - out_dir = os.path.join(os.path.dirname(__file__), "pic") + try: + import path_config + out_dir = path_config.get_pic_dir() + except Exception: + # 回退到旧路径(向后兼容) + import path_config + out_dir = path_config.get_pic_dir() else: out_dir = os.path.join(os.path.dirname(__file__), "target_pic") if not os.path.exists(out_dir): @@ -157,18 +163,25 @@ class ScreenshotOperations: 图片的完整路径,如果未找到则返回 None """ # 搜索目录优先级 + try: + import path_config + pic_dir = path_config.get_pic_dir() + except Exception: + import path_config + pic_dir = path_config.get_pic_dir() + search_dirs = [] if for_reading: # 读取时优先搜索当前目录的pic文件夹 search_dirs = [ - os.path.join(os.path.dirname(__file__), "pic"), + pic_dir, os.path.join(os.path.dirname(__file__), "target_pic"), os.path.dirname(__file__), # 当前目录 ] else: # 写入时优先使用pic目录 search_dirs = [ - os.path.join(os.path.dirname(__file__), "pic"), + pic_dir, ] # 尝试在每个目录中查找文件 diff --git a/path_config.py b/path_config.py index 32b95c2..7ea9647 100644 --- a/path_config.py +++ b/path_config.py @@ -49,8 +49,8 @@ def get_state_dir() -> str: def get_reservations_path() -> str: - """返回预约队列状态文件的路径""" - return os.path.join(PROJECT_ROOT, "state", "reservations.json") + """返回预约队列状态文件的路径(实际位置在douyin/core/state/reservations.json)""" + return os.path.join(PROJECT_ROOT, "douyin", "core", "state", "reservations.json") def get_high_value_rooms_path() -> str: @@ -117,6 +117,11 @@ def get_robot_verify_pic_path(save_subdir: bool = False) -> str: return os.path.join(PROJECT_ROOT, "pic", "机器人验证.png") +def get_run_cli_path() -> str: + """返回 run_cli.py 的路径(绝对路径)""" + return os.path.abspath(os.path.join(PROJECT_ROOT, "run_cli.py")) + + def ensure_dir(path: str) -> None: """确保目录存在,不存在则创建""" dir_path = os.path.dirname(path) if os.path.isfile(path) else path diff --git a/requirements.txt b/requirements.txt index 54a587c..1c32605 100644 --- a/requirements.txt +++ b/requirements.txt @@ -22,6 +22,10 @@ paddlepaddle>=2.5.0,<3.0.0 # 现代化GUI框架(可选,如果未安装会自动回退到原生tkinter) ttkbootstrap>=1.10.0 +# tkinter拖放支持(可选,用于pick_coords.py工具,支持拖放图片文件) +# 如需使用拖放功能,请安装:pip install tkinterdnd2 +# tkinterdnd2>=0.3.0 + # ========== 可选依赖(提升性能) ========== # EasyOCR(备选OCR引擎,比PaddleOCR更快,但需要更多内存) # 如需使用,取消下面的注释并安装: diff --git a/tools/check_gui_params_conflicts.py b/tools/check_gui_params_conflicts.py index ec85507..7917dce 100644 --- a/tools/check_gui_params_conflicts.py +++ b/tools/check_gui_params_conflicts.py @@ -15,7 +15,12 @@ if sys.platform == "win32": except Exception: pass -CONFIG_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config", "config.json") +try: + import path_config + CONFIG_PATH = path_config.get_config_path() +except Exception: + import path_config + CONFIG_PATH = path_config.get_config_path() def check_conflicts(cfg: dict) -> list: diff --git a/tools/pick_coords.py b/tools/pick_coords.py index 7073d86..241e0c9 100644 --- a/tools/pick_coords.py +++ b/tools/pick_coords.py @@ -10,6 +10,14 @@ try: except Exception as e: raise SystemExit(f"tkinter 不可用:{e}\n请安装带 tkinter 的 Python,或改用画图/PS/GIMP 取坐标。") +# 尝试导入拖放支持库 +try: + from tkinterdnd2 import DND_FILES, TkinterDnD + HAS_DND = True +except ImportError: + HAS_DND = False + TkinterDnD = None + def clamp(v: float, lo: float, hi: float) -> float: return lo if v < lo else hi if v > hi else v @@ -28,7 +36,11 @@ class CoordPicker: self.file_list: list[Path] = [] self.file_idx: int = -1 - self.root = tk.Tk() + # 使用 TkinterDnD 支持拖放(如果可用) + if HAS_DND: + self.root = TkinterDnD.Tk() + else: + self.root = tk.Tk() # 菜单 + 快捷键 menubar = tk.Menu(self.root) @@ -51,13 +63,25 @@ class CoordPicker: self._canvas_image_id = self.canvas.create_image(0, 0, anchor=tk.NW) self.status = tk.StringVar() - self.status.set("移动鼠标查看坐标;单击复制坐标;Ctrl+O 打开图片") + if HAS_DND: + self.status.set("移动鼠标查看坐标;单击复制坐标;Ctrl+O 打开图片;或直接拖放图片到窗口") + else: + self.status.set("移动鼠标查看坐标;单击复制坐标;Ctrl+O 打开图片(提示:安装 tkinterdnd2 可支持拖放)") self.label = tk.Label(self.root, textvariable=self.status, anchor="w") self.label.pack(fill=tk.X) self.canvas.bind("", self.on_move) self.canvas.bind("", self.on_click) + # 添加拖放支持 + if HAS_DND: + self.root.drop_target_register(DND_FILES) + self.root.dnd_bind('<>', self.on_drop) + self.canvas.drop_target_register(DND_FILES) + self.canvas.dnd_bind('<>', self.on_drop) + self.label.drop_target_register(DND_FILES) + self.label.dnd_bind('<>', self.on_drop) + if image_path is None: if not self.open_dialog(): raise SystemExit(2) @@ -181,6 +205,39 @@ class CoordPicker: if self._load_by_index(self.file_idx - 1): self.status.set(f"上一张: {self.image_path.name if self.image_path else ''}") + def on_drop(self, event) -> None: + """处理拖放事件""" + if not HAS_DND: + return + + try: + # 获取拖放的文件路径 + files = self.root.tk.splitlist(event.data) + if not files: + return + + # 取第一个文件 + file_path = files[0] + # 移除可能的花括号(Windows 拖放可能包含) + file_path = file_path.strip('{}') + + path = Path(file_path) + if not path.exists(): + self.status.set(f"文件不存在: {path}") + return + + # 检查是否为图片文件 + exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp"} + if path.suffix.lower() not in exts: + self.status.set(f"不是支持的图片格式: {path.suffix}") + return + + # 加载图片 + self.set_image(path, update_list=True) + self.status.set(f"已加载: {path.name}") + except Exception as e: + self.status.set(f"拖放失败: {e}") + def run(self): self.root.mainloop()