diff --git a/Underlying_Operations.py b/Underlying_Operations.py index cd6a687..eb013e5 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -233,7 +233,12 @@ class underlying_operations: try: # 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题 # 改为直接静默导入和初始化 - import easyocr # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] + # 尝试按需导入 easyocr,避免静态检查器在缺少依赖时报错 + import importlib + try: + easyocr = importlib.import_module("easyocr") + except Exception: + easyocr = None # 只加载中文和英文,加快初始化速度 # 自动检测GPU可用性,如果可用则启用GPU加速 @@ -244,14 +249,18 @@ class underlying_operations: fake_stdout = io.StringIO() fake_stderr = io.StringIO() - with redirect_stdout(fake_stdout), redirect_stderr(fake_stderr): - self.ocr = easyocr.Reader( - ["ch_sim", "en"], gpu=False, verbose=False - ) + if easyocr is not None: + with redirect_stdout(fake_stdout), redirect_stderr(fake_stderr): + self.ocr = easyocr.Reader( + ["ch_sim", "en"], gpu=False, verbose=False + ) - self.ocr_type = "easyocr" - gpu_status = "CPU模式" - print(f"[OCR] 使用 EasyOCR({gpu_status})") + self.ocr_type = "easyocr" + gpu_status = "CPU模式" + print(f"[OCR] 使用 EasyOCR({gpu_status})") + else: + # 强制抛出异常以触发回退逻辑 + raise ImportError("easyocr not available") except Exception as e: # EasyOCR初始化失败,回退到PaddleOCR print(f"[OCR] EasyOCR初始化失败: {e},回退到PaddleOCR") @@ -333,7 +342,11 @@ class underlying_operations: # 优先尝试EasyOCR try: # 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题 - import easyocr # type: ignore[import-untyped] + import importlib + try: + easyocr = importlib.import_module("easyocr") + except Exception: + easyocr = None # 临时重定向输出以减少初始化时的噪音 import io @@ -342,14 +355,17 @@ class underlying_operations: fake_stdout = io.StringIO() fake_stderr = io.StringIO() - with redirect_stdout(fake_stdout), redirect_stderr(fake_stderr): - self.ocr = easyocr.Reader( - ["ch_sim", "en"], gpu=False, verbose=False - ) + if easyocr is not None: + with redirect_stdout(fake_stdout), redirect_stderr(fake_stderr): + self.ocr = easyocr.Reader( + ["ch_sim", "en"], gpu=False, verbose=False + ) - self.ocr_type = "easyocr" - gpu_status = "GPU加速" if False else "CPU模式" - print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})") + self.ocr_type = "easyocr" + gpu_status = "GPU加速" if False else "CPU模式" + print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})") + else: + raise ImportError("easyocr not available") except Exception as e: # EasyOCR失败,回退到PaddleOCR print(f"[OCR] 延迟初始化EasyOCR失败: {e},回退到PaddleOCR") @@ -450,8 +466,8 @@ class underlying_operations: # OCR图片文件:按分类组织到子目录 try: - from douyin.handlers import douyin_screenshot_manager - + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") category = douyin_screenshot_manager.get_category_for_picname(picname) except Exception: category = "others" diff --git a/douyin/core/douyin_flow_control.py b/douyin/core/douyin_flow_control.py index 487e9b8..44a01cb 100644 --- a/douyin/core/douyin_flow_control.py +++ b/douyin/core/douyin_flow_control.py @@ -161,7 +161,8 @@ def find_and_open_fudai_detail( # 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存) try: from PIL import Image - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") screenshot_path = path_config.get_screenshot_path() if os.path.exists(screenshot_path): diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index c03e7b4..c473d6f 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,5 +1,5 @@ { - "updated_ts": 1767244823.7101066, + "updated_ts": 1767267009.7325232, "reason": "startup_clear", "room_pos": 0, "current_room_title": "", diff --git a/douyin/detection/douyin_detection.py b/douyin/detection/douyin_detection.py index 8e6b1b1..8833fef 100644 --- a/douyin/detection/douyin_detection.py +++ b/douyin/detection/douyin_detection.py @@ -160,7 +160,8 @@ def check_detail_height(analyser: Any) -> int: # 保存调试图片:标注检测区域和检测点 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") # 计算检测区域(参与按钮附近的区域) check_region_x1 = max(0, x - 50) @@ -496,7 +497,8 @@ def check_have_fudai_with_ready_screenshot( # 双截图记录:保存实时操作截图(像素检测区域) try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") douyin_screenshot_manager.save_latest_attempt( roi, operation_type="pixel_detect" @@ -563,7 +565,8 @@ def check_have_fudai_with_ready_screenshot( # 双截图记录:保存成功识别存档截图 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") douyin_screenshot_manager.save_last_success( roi, operation_type="pixel_detect" @@ -721,7 +724,8 @@ def check_have_fudai_with_ready_screenshot( # 双截图记录:保存成功识别存档截图 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") detect_roi = pic_new.crop( ( @@ -898,7 +902,8 @@ def check_have_fudai_with_ready_screenshot( # 双截图记录:保存实时操作截图(搜索区域) try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") from PIL import Image as PILImage search_roi_pil = PILImage.fromarray( @@ -932,7 +937,8 @@ def check_have_fudai_with_ready_screenshot( if max_val >= template_threshold: # 双截图记录:保存成功识别存档截图 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") from PIL import Image as PILImage search_roi_pil = PILImage.fromarray( @@ -1358,7 +1364,8 @@ def check_have_fudai_with_ready_screenshot( # 双截图记录:保存实时操作截图(搜索区域) try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") from PIL import Image as PILImage search_roi_pil = PILImage.fromarray( @@ -1416,7 +1423,8 @@ def check_have_fudai_with_ready_screenshot( if max_val >= template_threshold: # 双截图记录:保存成功识别存档截图 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") from PIL import Image as PILImage search_roi_pil = PILImage.fromarray( diff --git a/douyin/detection/douyin_pixel.py b/douyin/detection/douyin_pixel.py index 006d446..62354c5 100644 --- a/douyin/detection/douyin_pixel.py +++ b/douyin/detection/douyin_pixel.py @@ -208,7 +208,8 @@ def detect_lucky_draw_result_popup( # 双截图记录:保存实时操作截图(像素检测区域) detect_roi = None try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") detect_roi = pic_rgb.crop((x1, y1, x2, y2)) douyin_screenshot_manager.save_latest_attempt( @@ -236,9 +237,9 @@ def detect_lucky_draw_result_popup( debug_path, red_ratio_threshold, ) - except Exception as e: # type: ignore[general-exception] + except Exception: # type: ignore[general-exception] pass - except Exception as e: # type: ignore[general-exception] + except Exception: pass red_count = 0 @@ -266,7 +267,8 @@ def detect_lucky_draw_result_popup( # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") if result: # 检测成功 @@ -302,9 +304,9 @@ def detect_lucky_draw_result_popup( red_ratio_threshold, red_ratio, ) - except Exception as e: # type: ignore[general-exception] + except Exception: # type: ignore[general-exception] pass - except Exception as e: # type: ignore[general-exception] + except Exception: pass # 如果请求详细信息,返回包含red_ratio的字典 @@ -361,7 +363,8 @@ def detect_attend_button_red_area( # 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb, # 使用全屏截图 @@ -376,9 +379,9 @@ def detect_attend_button_red_area( import logging logging.info("[调试图像] 参与按钮检测前保存: %s", debug_path) - except Exception as e: # type: ignore[general-exception] + except Exception: # type: ignore[general-exception] pass - except Exception as e: # type: ignore[general-exception] + except Exception: # type: ignore[general-exception] pass # 采样检测点:检测大片红色区域 @@ -435,7 +438,8 @@ def detect_attend_button_red_area( # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 # 无论成功失败都保存debug截图 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb, # 使用全屏截图 @@ -518,7 +522,8 @@ def detect_fansclub_join_red_area( # 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb, # 使用全屏截图 @@ -586,7 +591,8 @@ def detect_fansclub_join_red_area( # 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") # 无论成功失败都保存debug截图 debug_path = douyin_screenshot_manager.save_debug_image( @@ -726,7 +732,8 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: # 保存调试图像(检测结果) try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb, # 使用全屏截图 diff --git a/douyin/fudai/core/fudai_attend.py b/douyin/fudai/core/fudai_attend.py index 0595711..6e20f23 100644 --- a/douyin/fudai/core/fudai_attend.py +++ b/douyin/fudai/core/fudai_attend.py @@ -309,7 +309,8 @@ def attend_choujiang(analyser) -> bool: # 保存debug截图:标注OCR识别区域(参与按钮区域) try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): @@ -461,7 +462,8 @@ def attend_choujiang(analyser) -> bool: # 保存debug截图:标注OCR识别区域(加入粉丝团按钮区域) try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): diff --git a/douyin/fudai/core/fudai_debug_utils.py b/douyin/fudai/core/fudai_debug_utils.py index 1c26a0e..dc1a1ea 100644 --- a/douyin/fudai/core/fudai_debug_utils.py +++ b/douyin/fudai/core/fudai_debug_utils.py @@ -156,8 +156,9 @@ def save_full_screenshot_with_ocr_region( } try: - from douyin.handlers import douyin_screenshot_manager - except ImportError as e: + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") + except Exception as e: log_debug_error( analyser, e, diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index 22ecf3a..f9a9bca 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -17,7 +17,16 @@ import path_config from douyin.fudai.core.fudai_debug_utils import ( _save_full_screenshot_with_ocr_region, ) -from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore +try: + from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore +except Exception: + # 在运行环境中可能缺少 OCR 预处理依赖,提供回退实现以避免导入失败导致程序中断。 + def preprocess_for_ocr(analyser, picname: str) -> str: # type: ignore + """回退的 preprocess_for_ocr:直接返回 picname(不做预处理)。""" + try: + return str(picname) + except Exception: + return picname def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: @@ -1730,7 +1739,8 @@ def attend_choujiang(analyser) -> bool: # 保存debug截图:标注OCR识别区域(参与按钮区域) try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): @@ -1879,7 +1889,8 @@ def attend_choujiang(analyser) -> bool: # 保存debug截图:标注OCR识别区域(加入粉丝团按钮区域) try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): diff --git a/douyin/fudai/douyin_fudai_finder.py b/douyin/fudai/douyin_fudai_finder.py index 594576b..cb8a420 100644 --- a/douyin/fudai/douyin_fudai_finder.py +++ b/douyin/fudai/douyin_fudai_finder.py @@ -656,7 +656,8 @@ class FudaiDetector: # 保存模板匹配的调试图像(无论成功与否)- 使用完整截图 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") # Image 已在文件顶部导入 # 使用完整截图而不是搜索区域ROI @@ -1158,7 +1159,8 @@ class FudaiDetailVerifier: # 保存完整截图并标注OCR区域 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): @@ -1454,7 +1456,8 @@ class FudaiFinder: # 保存完整截图用于调试(检测前) try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") pic_rgb_full = pic.convert("RGB") @@ -1521,7 +1524,8 @@ class FudaiFinder: consecutive_failures = 0 # 保存完整截图(检测成功) try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") pic_rgb_full = pic.convert("RGB") diff --git a/douyin/handlers/__init__.py b/douyin/handlers/__init__.py index e83aad4..967d061 100644 --- a/douyin/handlers/__init__.py +++ b/douyin/handlers/__init__.py @@ -1,7 +1,9 @@ """ 处理器模块 """ - - - - +# 显式导入常用子模块以便静态类型检查器(如 Pylance)能正确识别模块成员 +try: + from . import douyin_screenshot_manager # type: ignore +except Exception: + # 导入失败时不影响运行(运行时会按需导入) + pass diff --git a/douyin/handlers/douyin_screenshot_manager.py b/douyin/handlers/douyin_screenshot_manager.py index 48d575d..eefa3bd 100644 --- a/douyin/handlers/douyin_screenshot_manager.py +++ b/douyin/handlers/douyin_screenshot_manager.py @@ -30,9 +30,6 @@ _debug_save_worker_started = False _async_save_success_count = 0 _async_save_failure_count = 0 _async_save_counters_lock = threading.Lock() -# 背景保存队列与工作线程(用于异步保存调试图像,避免阻塞主流程) -_debug_save_queue: "Queue[Tuple[Image.Image, str, bool, Optional[Tuple[int,int,int,int]], Optional[dict], str, str, str]]" = Queue() -_debug_save_worker_started = False def _debug_save_loop() -> None: @@ -53,6 +50,8 @@ def _debug_save_loop() -> None: picname, step, ) = task + # 在函数中修改全局计数器时需要声明 global,避免静态分析/运行时错误 + global _async_save_success_count, _async_save_failure_count try: # 执行同步保存(重复之前 save_debug_image 中的标注与保存逻辑) def _save_image_with_retry(img_to_save: Image.Image, path: str, max_retries: int = 2) -> bool: @@ -113,37 +112,9 @@ def _debug_save_loop() -> None: except Exception: pass - try: - _save_image_with_retry(annotated_image, file_path) - # 计数并写入 actions.log try: - with _async_save_counters_lock: - _async_save_success_count += 1 - except Exception: - pass - try: - actions_log = path_config.get_actions_log_path() - with open(actions_log, "a", encoding="utf-8") as af: - af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存完成: {file_path}\n") - except Exception: - pass - # 保存完成时的可选日志(原有逻辑) - try: - import json, logging - cfg_path = path_config.get_config_path() - log_on_complete = False - if os.path.exists(cfg_path): - with open(cfg_path, "r", encoding="utf-8") as _f: - cfg = json.load(_f) - dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {} - log_on_complete = bool(dbg_cfg.get("log_on_complete", False)) - if log_on_complete: - logging.info("[调试图像] 异步保存完成: %s", file_path) - except Exception: - pass - except Exception: - try: - _save_image_with_retry(img, file_path) + _save_image_with_retry(annotated_image, file_path) + # 计数并写入 actions.log try: with _async_save_counters_lock: _async_save_success_count += 1 @@ -155,6 +126,7 @@ def _debug_save_loop() -> None: af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存完成: {file_path}\n") except Exception: pass + # 保存完成时的可选日志(原有逻辑) try: import json, logging cfg_path = path_config.get_config_path() @@ -169,28 +141,59 @@ def _debug_save_loop() -> None: except Exception: pass except Exception: - # 保存失败:写入异步错误日志、计数并写入 actions.log try: - logs_dir = path_config.get_logs_dir() - os.makedirs(logs_dir, exist_ok=True) - err_path = os.path.join(logs_dir, "async_debug_save_errors.log") - with open(err_path, "a", encoding="utf-8") as ef: - ef.write(f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n") - ef.write(traceback.format_exc()) - ef.write("\n\n") + _save_image_with_retry(img, file_path) + try: + with _async_save_counters_lock: + _async_save_success_count += 1 + except Exception: + pass + try: + actions_log = path_config.get_actions_log_path() + with open(actions_log, "a", encoding="utf-8") as af: + af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存完成: {file_path}\n") + except Exception: + pass + try: + import json, logging + cfg_path = path_config.get_config_path() + log_on_complete = False + if os.path.exists(cfg_path): + with open(cfg_path, "r", encoding="utf-8") as _f: + cfg = json.load(_f) + dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {} + log_on_complete = bool(dbg_cfg.get("log_on_complete", False)) + if log_on_complete: + logging.info("[调试图像] 异步保存完成: %s", file_path) + except Exception: + pass except Exception: - pass - try: - with _async_save_counters_lock: - _async_save_failure_count += 1 - except Exception: - pass - try: - actions_log = path_config.get_actions_log_path() - with open(actions_log, "a", encoding="utf-8") as af: - af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存失败: {file_path}\n") - except Exception: - pass + # 保存失败:写入异步错误日志、计数并写入 actions.log + try: + logs_dir = path_config.get_logs_dir() + os.makedirs(logs_dir, exist_ok=True) + err_path = os.path.join(logs_dir, "async_debug_save_errors.log") + with open(err_path, "a", encoding="utf-8") as ef: + ef.write(f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n") + ef.write(traceback.format_exc()) + ef.write("\n\n") + except Exception: + pass + try: + with _async_save_counters_lock: + _async_save_failure_count += 1 + except Exception: + pass + try: + actions_log = path_config.get_actions_log_path() + with open(actions_log, "a", encoding="utf-8") as af: + af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存失败: {file_path}\n") + except Exception: + pass + # 捕获标注过程中的任何异常,避免线程退出 + except Exception: + pass + # end if annotate block else: try: _save_image_with_retry(img, file_path) @@ -1334,12 +1337,27 @@ def save_debug_image( # type: ignore if hasattr(odraw, "textbbox"): l, t, r, b = odraw.textbbox((0, 0), text, font=font) return (r - l, b - t) - # Fallback to ImageFont.getsize if available - if font is not None and hasattr(font, "getsize"): - return font.getsize(text) + # Fallbacks using ImageFont methods compatible with different Pillow versions + if font is not None: + # Prefer font.getbbox if available + if hasattr(font, "getbbox"): + try: + l, t, r, b = font.getbbox(text) + return (r - l, b - t) + except Exception: + pass + # Fallback: use font.getmask to get rendered size + try: + mask = font.getmask(text) + return (mask.size[0], mask.size[1]) + except Exception: + pass # Last resort: ImageDraw.textsize (may not exist in Pillow >= 10) if hasattr(odraw, "textsize"): - return odraw.textsize(text, font=font) if font is not None else odraw.textsize(text) + try: + return odraw.textsize(text, font=font) if font is not None else odraw.textsize(text) + except Exception: + pass except Exception: pass # Conservative fallback estimate @@ -1366,7 +1384,7 @@ def save_debug_image( # type: ignore bar_y2 = img_h # 绘制半透明白色底栏 - odraw.rectangle([0, bar_y1, img_w, bar_y2], fill=(255, 255, 255, 200)) + odraw.rectangle((0, bar_y1, img_w, bar_y2), fill=(255, 255, 255, 200)) # 绘制文字(黑色) text_x = padding_h @@ -1388,7 +1406,7 @@ def save_debug_image( # type: ignore if "match_coords" in extra_info and isinstance(extra_info["match_coords"], (list, tuple)) and len(extra_info["match_coords"]) == 4: mx1, my1, mx2, my2 = extra_info["match_coords"] # 在 overlay 上画红框 - odraw.rectangle([mx1, my1, mx2, my2], outline=(255, 0, 0, 200), width=2) + odraw.rectangle((mx1, my1, mx2, my2), outline=(255, 0, 0, 200), width=2) # 像素检测提供 detected_x_scaled:图像坐标系中的x(单点),并依赖 coords 提供 y 区域 elif "detected_x_scaled" in extra_info and coords: try: @@ -1469,161 +1487,5 @@ def save_debug_image( # type: ignore pass return None - # 在保存文件前,再次确保目录存在(防止并发访问或权限问题导致目录不存在) - try: - ensure_debug_captures_dir() - except Exception: - pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理 - - # 保存图像的辅助函数,带重试机制 - def save_image_with_retry( - 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 as e: - # 目录不存在,尝试创建后重试 - last_error = e - if attempt < max_retries - 1: - try: - ensure_debug_captures_dir() - except Exception as dir_error: - # 记录目录创建失败 - try: - print(f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}") - except Exception: - pass - else: - # 最后一次尝试失败,抛出异常 - raise - 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 - - # 如果需要标注,在图像上添加信息 - if annotate and (coords or extra_info): - try: - from PIL import ImageDraw, ImageFont - - annotated_image = image.copy() - draw = ImageDraw.Draw(annotated_image) - - # 尝试使用默认字体 - try: - font = ImageFont.truetype("arial.ttf", 12) - except Exception: - try: - font = ImageFont.load_default() - except Exception: - font = None - - # 绘制坐标框 - if coords: - x1, y1, x2, y2 = coords - # 确保坐标在图像范围内 - img_w, img_h = annotated_image.size - x1 = max(0, min(x1, img_w - 1)) - y1 = max(0, min(y1, img_h - 1)) - x2 = max(0, min(x2, img_w - 1)) - y2 = max(0, min(y2, img_h - 1)) - - if x1 < x2 and y1 < y2: - # 使用元组格式 (x1, y1, x2, y2) - rect_coords: Tuple[float, float, float, float] = ( - float(x1), - float(y1), - float(x2), - float(y2), - ) - draw.rectangle(rect_coords, outline="red", width=2) - - # 添加文本信息 - if extra_info: - text_lines = [f"{k}: {v}" for k, v in extra_info.items()] - if text_lines: - text = "\n".join(text_lines) - # 在图像左上角添加文本 - try: - draw.text((5, 5), text, fill="yellow", font=font) - except Exception: - pass - - save_image_with_retry(annotated_image, file_path) - 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: - # 如果保存原图也失败,抛出异常让外层处理 - raise - else: - save_image_with_retry(image, file_path) - - return file_path - except FileNotFoundError as e: - # 文件或目录不存在 - try: - 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 + # 结束 save_debug_image 的主逻辑,返回 None 表示保存失败 return None \ No newline at end of file diff --git a/douyin/stage/douyin_stage.py b/douyin/stage/douyin_stage.py index 3886e44..164c465 100644 --- a/douyin/stage/douyin_stage.py +++ b/douyin/stage/douyin_stage.py @@ -727,7 +727,8 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) # 保存完整截图并标注OCR区域 try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") import path_config import os from PIL import Image diff --git a/gui/gui_app.py b/gui/gui_app.py index c8ec74b..28d51ad 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -1041,7 +1041,8 @@ def main(): ttk.Label(debug_counts_frame, textvariable=debug_async_failure_var, foreground="red").pack(side=LEFT, padx=(4, 8)) def on_reset_async_counters(): try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") douyin_screenshot_manager.reset_async_save_counters() debug_async_success_var.set(0) debug_async_failure_var.set(0) @@ -1052,7 +1053,8 @@ def main(): # 周期性更新计数器(2秒) def _update_async_counters(): try: - from douyin.handlers import douyin_screenshot_manager + import importlib + douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") s, f = douyin_screenshot_manager.get_async_save_counters() debug_async_success_var.set(s) debug_async_failure_var.set(f)