diff --git a/douyin/handlers/douyin_screenshot_manager.py b/douyin/handlers/douyin_screenshot_manager.py index 84d433d..f1ec1d2 100644 --- a/douyin/handlers/douyin_screenshot_manager.py +++ b/douyin/handlers/douyin_screenshot_manager.py @@ -1,1705 +1,79 @@ from __future__ import annotations -""" -截图管理模块:双截图记录机制 -============================ +"""douyin_screenshot_manager — 兼容入口(保留外部 import 路径)。 -功能: -1. 实时操作截图(latest_attempt.png):每次识别操作都覆盖保存 -2. 成功识别存档截图(last_success.png):仅在成功时保存,不会被覆盖 -3. OCR文件夹清理:自动清理旧的OCR图片 +实际实现位于子包 ``douyin.handlers.screenshot_manager``。 +本文件仅 re-export 公共符号;详见各子模块文档: +- ``screenshot_manager._common`` 共享 logger / 全局状态 / 异步计数器 +- ``screenshot_manager.paths`` OCR 目录、调试存档目录、各类路径 +- ``screenshot_manager.save_files`` 双截图记录的保存接口 +- ``screenshot_manager.async_save`` _debug_save_loop + 工作线程启停 +- ``screenshot_manager.cleanup`` debug_captures 目录清理与轮转 +- ``screenshot_manager.save_image`` save_debug_image 主入口 """ -import os -import shutil -from typing import Optional, Tuple - -import logging as _logging - -# 模块级 logger:原代码用 print 输出截图管理 / 调试图像清理日志,统一走 logging。 -# 保留消息中已有的 "[截图管理]"/"[调试图像清理]" 前缀,避免改变历史搜索习惯。 -_LOGGER = _logging.getLogger("douyin.handlers.douyin_screenshot_manager") - - -def _mgr_log(msg: str, level: str = "INFO") -> None: - """统一截图管理日志出口;失败兜底 stdout。""" - try: - lv = str(level or "INFO").upper() - if lv == "ERROR": - _LOGGER.error(str(msg)) - elif lv == "WARNING": - _LOGGER.warning(str(msg)) - elif lv == "DEBUG": - _LOGGER.debug(str(msg)) - else: - _LOGGER.info(str(msg)) - except Exception: - try: - _mgr_log(str(msg)) - except Exception: - pass - - -from PIL import Image -from douyin.core import path_config -import threading -from queue import Queue, Empty -from typing import Any - -# 计数与追踪 -from datetime import datetime -import traceback -import logging -import time - -# 背景保存队列与工作线程(用于异步保存调试图像,避免阻塞主流程) -_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 -_debug_save_worker_lock = threading.Lock() # 保护 worker 启动的双检查锁 -_debug_save_shutdown_event = threading.Event() # 用于优雅关闭 - -# 异步保存计数(用于 GUI 显示) -_async_save_success_count = 0 -_async_save_failure_count = 0 -_async_save_counters_lock = threading.Lock() - -# 环境开关:在高频路径中跳过调试图像保存以提升性能(默认启用跳过) -_SKIP_DEBUG_SAVE_IN_HOTLOOPS = bool( - os.environ.get("SKIP_DEBUG_SAVE_IN_HOTLOOPS", "1") == "1" +from douyin.handlers.screenshot_manager import ( + _LOGGER, + _SKIP_DEBUG_SAVE_IN_HOTLOOPS, + _async_save_counters_lock, + _debug_save_loop, + _debug_save_queue, + _debug_save_shutdown_event, + _debug_save_worker_lock, + _ensure_debug_save_worker_started, + _mgr_log, + _sanitize_filename_part, + cleanup_debug_captures, + cleanup_ocr_dir, + count_debug_captures_files, + ensure_debug_captures_dir, + ensure_ocr_dir, + get_async_save_counters, + get_category_for_picname, + get_debug_captures_base_dir, + get_debug_captures_dir, + get_last_success_path, + get_latest_attempt_path, + get_ocr_dir, + init_debug_captures_cleanup, + reset_async_save_counters, + save_attempt_from_file, + save_debug_image, + save_last_success, + save_latest_attempt, + save_success_from_file, + shutdown_debug_save_worker, ) - -def _debug_save_loop() -> None: - """后台线程循环,消费调试图像保存任务并执行同步保存。""" - while not _debug_save_shutdown_event.is_set(): - try: - task = _debug_save_queue.get(timeout=1.0) - if task is None: - _debug_save_queue.task_done() - break - ( - img, - file_path, - annotate, - coords, - extra_info, - operation_type, - 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: - 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: - pass - else: - raise - except PermissionError: - raise - except OSError: - raise - if last_error: - raise last_error - return False - - # 标注并保存 - if annotate and (coords or extra_info): - try: - from PIL import ImageDraw, ImageFont - - annotated_image = img.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: - rect_coords = ( - 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 - - 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: - import logging - - logging.getLogger("action_logger").info( - "[调试图像] 异步保存完成: %s", file_path - ) - 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) - try: - with _async_save_counters_lock: - _async_save_success_count += 1 - except Exception: - pass - try: - import logging - - logging.getLogger("action_logger").info( - "[调试图像] 异步保存完成: %s", file_path - ) - 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: - # 保存失败:写入异步错误日志、计数并写入 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: - import logging - - logging.getLogger("action_logger").info( - "[调试图像] 异步保存失败: %s", file_path - ) - except Exception: - pass - # 捕获标注过程中的任何异常,避免线程退出 - except Exception: - pass - # end if annotate block - else: - try: - _save_image_with_retry(img, file_path) - try: - with _async_save_counters_lock: - _async_save_success_count += 1 - except Exception: - pass - try: - import logging - - logging.getLogger("action_logger").info( - "[调试图像] 异步保存完成: %s", file_path - ) - 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: - # 保存失败:写入异步错误日志以便追踪,同时记录到 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: - import logging - - logging.getLogger("action_logger").info( - "[调试图像] 异步保存失败: %s", file_path - ) - except Exception: - pass - except Exception: - pass - finally: - _debug_save_queue.task_done() - except Empty: - continue - except Exception: - # 防止线程因异常退出 - try: - import time - - time.sleep(0.1) - except Exception: - pass - - -def shutdown_debug_save_worker(timeout: float = 5.0) -> None: - """优雅关闭调试保存工作线程""" - global _debug_save_worker_started - if not _debug_save_worker_started: - return - _debug_save_shutdown_event.set() - _debug_save_queue.put(None) # 毒丸信号 - try: - _debug_save_queue.join() - except Exception: - pass - _debug_save_worker_started = False - - -# 注册 atexit 清理函数 -import atexit -atexit.register(shutdown_debug_save_worker) - - -def _ensure_debug_save_worker_started() -> None: - global _debug_save_worker_started - if _debug_save_worker_started: - return - with _debug_save_worker_lock: - if _debug_save_worker_started: - return - t = threading.Thread(target=_debug_save_loop, name="debug-save-worker", daemon=True) - t.start() - _debug_save_worker_started = True - - -def get_async_save_counters() -> tuple[int, int]: - """返回 (success_count, failure_count)""" - try: - with _async_save_counters_lock: - return int(_async_save_success_count), int(_async_save_failure_count) - except Exception: - return 0, 0 - - -def reset_async_save_counters() -> None: - """重置计数器(GUI 可调用)""" - try: - with _async_save_counters_lock: - global _async_save_success_count, _async_save_failure_count - _async_save_success_count = 0 - _async_save_failure_count = 0 - except Exception: - pass - - -def get_ocr_dir() -> str: - """获取OCR目录路径""" - return os.path.join(path_config.get_pic_dir(), "ocr") - - -def get_category_for_picname(picname: str) -> str: - """根据图片名称判断应该保存到哪个分类目录 - - 参数: - picname: 图片名称(不含扩展名) - - 返回: - 分类目录名称,如 "fudai", "live_room", "popups", "buttons", "stage_diag", "others" - """ - picname_lower = picname.lower() - - # 福袋相关 - if any(keyword in picname_lower for keyword in ["福袋", "fudai"]): - return "fudai" - - # 直播间相关 - if any( - keyword in picname_lower - for keyword in [ - "live_room", - "直播间", - "直播列表", - "直播广场", - "直播状态", - "直播验证", - ] - ): - return "live_room" - - # 弹窗相关 - if any( - keyword in picname_lower - for keyword in [ - "抽奖结果", - "无奖励", - "优惠券", - "购物红包", - "奖励通知", - "订单确认", - "lucky_draw", - "coupon", - "redpacket", - "reward", - "order", - ] - ): - return "popups" - - # 按钮相关 - if any( - keyword in picname_lower - for keyword in ["参与按钮", "粉丝团", "attend_button", "fans_club"] - ): - return "buttons" - - # 阶段诊断相关 - if any( - keyword in picname_lower - for keyword in [ - "推荐页", - "关注列表", - "直播列表标签", - "recommend", - "follow", - "live_list", - ] - ): - return "stage_diag" - - # 其他 - return "others" - - -def get_latest_attempt_path(operation_type: str = "general") -> str: - """获取实时操作截图路径 - - 参数: - operation_type: 操作类型,可选值: - - "pixel" 或 "pixel_detect": 像素检测 - - "ocr": OCR识别 - - "template" 或 "template_match": 模板匹配 - - 其他: 通用操作 - """ - # 规范化操作类型 - if operation_type.startswith("pixel"): - type_key = "pixel" - elif operation_type.startswith("ocr") or operation_type.startswith("cut_pic"): - type_key = "ocr" - elif operation_type.startswith("template"): - type_key = "template" - else: - type_key = "general" - - return os.path.join(get_ocr_dir(), f"latest_attempt_{type_key}.png") - - -def get_last_success_path(operation_type: str = "general") -> str: - """获取成功识别存档截图路径 - - 参数: - operation_type: 操作类型,可选值: - - "pixel" 或 "pixel_detect": 像素检测 - - "ocr": OCR识别 - - "template" 或 "template_match": 模板匹配 - - 其他: 通用操作 - """ - # 规范化操作类型 - if operation_type.startswith("pixel"): - type_key = "pixel" - elif operation_type.startswith("ocr") or operation_type.startswith("cut_pic"): - type_key = "ocr" - elif operation_type.startswith("template"): - type_key = "template" - else: - type_key = "general" - - return os.path.join(get_ocr_dir(), f"last_success_{type_key}.png") - - -def ensure_ocr_dir() -> None: - """确保OCR目录存在""" - ocr_dir = get_ocr_dir() - os.makedirs(ocr_dir, exist_ok=True) - - -def cleanup_ocr_dir( - keep_latest_attempt: bool = True, - keep_last_success: bool = True, - keep_success_files: bool = True, - max_files: int = 50, -) -> int: - """清理OCR目录中的旧文件 - - 参数: - keep_latest_attempt: 是否保留所有 latest_attempt_*.png 文件 - keep_last_success: 是否保留所有 last_success_*.png 文件 - keep_success_files: 是否保留所有 _success.png 文件 - max_files: 最多保留的文件数(不包括特殊文件) - - 返回: - 清理的文件数量 - """ - try: - ocr_dir = get_ocr_dir() - if not os.path.exists(ocr_dir): - return 0 - - files = [] - for f in os.listdir(ocr_dir): - file_path = os.path.join(ocr_dir, f) - if os.path.isfile(file_path) and f.lower().endswith(".png"): - # 检查是否为特殊文件 - is_special = False - if f.startswith("latest_attempt_") and keep_latest_attempt: - is_special = True - elif f.startswith("last_success_") and keep_last_success: - is_special = True - elif f.endswith("_success.png") and keep_success_files: - is_special = True - - if not is_special: - files.append((file_path, os.path.getmtime(file_path))) - - # 按修改时间排序,保留最新的 - files.sort(key=lambda x: x[1], reverse=True) - - # 删除超出限制的文件 - deleted_count = 0 - for file_path, _ in files[max_files:]: - try: - os.remove(file_path) - deleted_count += 1 - except Exception: - pass - - return deleted_count - except Exception: - return 0 - - -def save_latest_attempt(image: Image.Image, operation_type: str = "") -> bool: - """保存实时操作截图(覆盖保存) - - 参数: - image: PIL Image 对象 - operation_type: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic") - - 返回: - 是否保存成功 - """ - try: - ensure_ocr_dir() - path = get_latest_attempt_path(operation_type) - image.save(path, "PNG") - return True - except Exception as e: - try: - _mgr_log(f"[截图管理] 保存 latest_attempt_{operation_type}.png 失败: {e}") - except Exception: - pass - return False - - -def save_last_success(image: Image.Image, operation_type: str = "") -> bool: - """保存成功识别存档截图(不覆盖,仅成功时保存) - - 参数: - image: PIL Image 对象 - operation_type: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic") - - 返回: - 是否保存成功 - """ - try: - ensure_ocr_dir() - path = get_last_success_path(operation_type) - image.save(path, "PNG") - return True - except Exception as e: - try: - _mgr_log(f"[截图管理] 保存 last_success_{operation_type}.png 失败: {e}") - except Exception: - pass - return False - - -def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool: - """从文件保存实时操作截图 - - 参数: - source_path: 源图片文件路径 - operation_type: 操作类型 - - 返回: - 是否保存成功 - """ - try: - if not os.path.exists(source_path): - return False - image = Image.open(source_path) - return save_latest_attempt(image, operation_type) - except Exception as e: - try: - _mgr_log(f"[截图管理] 从文件保存 latest_attempt.png 失败: {e}") - except Exception: - pass - return False - - -def save_success_from_file(source_path: str, operation_type: str = "") -> bool: - """从文件保存成功识别存档截图 - - 参数: - source_path: 源图片文件路径 - operation_type: 操作类型 - - 返回: - 是否保存成功 - """ - try: - if not os.path.exists(source_path): - return False - image = Image.open(source_path) - return save_last_success(image, operation_type) - except Exception as e: - try: - _mgr_log(f"[截图管理] 从文件保存 last_success.png 失败: {e}") - except Exception: - pass - return False - - -def get_debug_captures_dir() -> str: - """获取调试图像存档目录路径""" - pic_dir = path_config.get_pic_dir() - debug_dir = os.path.join(pic_dir, "debug_captures") - # 按日期分类:YYYY-MM-DD - from datetime import datetime - - date_str = datetime.now().strftime("%Y-%m-%d") - return os.path.join(debug_dir, date_str) - - -def ensure_debug_captures_dir() -> None: - """确保调试图像存档目录存在""" - try: - debug_dir = get_debug_captures_dir() - # 确保父目录也存在 - parent_dir = os.path.dirname(debug_dir) - if parent_dir and not os.path.exists(parent_dir): - 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: - 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: - _mgr_log(f"[截图管理] 创建调试图像目录失败({error_type}): {e}") - except Exception: - pass - raise - - -def get_debug_captures_base_dir() -> str: - """获取调试图像存档根目录路径(不包含日期)""" - pic_dir = path_config.get_pic_dir() - return os.path.join(pic_dir, "debug_captures") - - -def count_debug_captures_files() -> int: - """统计所有调试图像文件的总数量 - - 返回: - 文件总数 - """ - try: - debug_base_dir = get_debug_captures_base_dir() - if not os.path.exists(debug_base_dir): - return 0 - - total_count = 0 - # 遍历所有日期目录 - for item in os.listdir(debug_base_dir): - # 跳过隐藏文件和标记文件 - if item.startswith("."): - continue - - item_path = os.path.join(debug_base_dir, item) - if not os.path.isdir(item_path): - continue - - # 统计该目录下的所有PNG文件 - try: - for _root, _dirs, files in os.walk(item_path): - for f in files: - if f.lower().endswith(".png"): - total_count += 1 - except Exception: - pass - - return total_count - except Exception: - return 0 - - -def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: - """清理旧的调试图像存档目录 - - 参数: - keep_days: 保留天数,默认7天,超过此天数的目录将被删除 - max_files: 最大文件数量,默认2000,超过此数量时删除最旧的目录 - - 返回: - 清理的目录数量 - """ - try: - debug_base_dir = get_debug_captures_base_dir() - if not os.path.exists(debug_base_dir): - return 0 - - from datetime import datetime, timedelta - - # 计算截止日期 - cutoff_date = datetime.now() - timedelta(days=keep_days) - - deleted_count = 0 - deleted_dirs = [] - total_size_freed = 0 - - # 收集所有日期目录及其信息 - dirs_info = [] - for item in os.listdir(debug_base_dir): - # 跳过隐藏文件和标记文件 - if item.startswith("."): - continue - - item_path = os.path.join(debug_base_dir, item) - if not os.path.isdir(item_path): - continue - - # 尝试解析目录名为日期(格式:YYYY-MM-DD) - try: - dir_date = datetime.strptime(item, "%Y-%m-%d") - - # 统计该目录下的文件数量和大小 - file_count = 0 - dir_size = 0 - try: - for root, _dirs, files in os.walk(item_path): - for f in files: - if f.lower().endswith(".png"): - file_count += 1 - file_path = os.path.join(root, f) - try: - dir_size += os.path.getsize(file_path) - except Exception: - pass - except Exception: - pass - - dirs_info.append( - { - "name": item, - "path": item_path, - "date": dir_date, - "file_count": file_count, - "size": dir_size, - } - ) - except ValueError: - # 如果目录名不是日期格式,跳过 - continue - - # 按日期排序(最旧的在前) - dirs_info.sort(key=lambda x: x["date"]) - - # 先按天数清理:删除超过保留天数的目录 - for dir_info in dirs_info[:]: - if dir_info["date"] < cutoff_date: - try: - shutil.rmtree(dir_info["path"]) - deleted_count += 1 - deleted_dirs.append(dir_info["name"]) - total_size_freed += dir_info["size"] - dirs_info.remove(dir_info) - except Exception as e: - try: - _mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") - except Exception: - pass - - # 再按文件数量清理:如果文件总数超过max_files,删除最旧的目录 - total_files = sum(d["file_count"] for d in dirs_info) - if total_files > max_files: - # 计算需要删除的文件数量 - need_delete_count = total_files - max_files - - # 从最旧的目录开始删除,直到文件数量降到max_files以下 - deleted_files_count = 0 - for dir_info in dirs_info[:]: - if deleted_files_count >= need_delete_count: - break - - try: - shutil.rmtree(dir_info["path"]) - deleted_count += 1 - deleted_dirs.append(dir_info["name"]) - total_size_freed += dir_info["size"] - deleted_files_count += dir_info["file_count"] - dirs_info.remove(dir_info) - except Exception as e: - try: - _mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") - except Exception: - pass - - if deleted_count > 0: - try: - size_mb = total_size_freed / (1024 * 1024) - reason_parts = [] - if total_files > max_files: - reason_parts.append(f"文件数量超过{max_files}") - if any( - d["date"] < cutoff_date - for d in dirs_info - if d not in [{"name": name} for name in deleted_dirs] - ): - reason_parts.append(f"超过{keep_days}天") - reason = ",".join(reason_parts) if reason_parts else "自动清理" - - _mgr_log( - f"[调试图像清理] 已删除 {deleted_count} 个调试图像目录: {', '.join(deleted_dirs)}" - ) - _mgr_log(f"[调试图像清理] 清理原因: {reason}") - if size_mb > 0.1: # 只显示大于0.1MB的清理 - _mgr_log(f"[调试图像清理] 释放空间: {size_mb:.2f} MB") - except Exception: - pass - - return deleted_count - except Exception as e: - # 清理失败不应影响程序运行 - try: - _mgr_log(f"[调试图像清理] 清理旧调试图像时出错: {e}") - except Exception: - pass - return 0 - - -def init_debug_captures_cleanup() -> None: - """初始化调试图像清理(在程序启动时调用) - - 从 config.json 读取配置并执行清理 - """ - try: - import json - - config_path = path_config.get_config_path() - if not os.path.exists(config_path): - return - - with open(config_path, "r", encoding="utf-8") as f: - config = json.load(f) - - # 检查是否启用自动清理 - auto_cleanup = True - keep_days = 7 - max_files = 2000 - - if "debug_captures" in config and isinstance(config["debug_captures"], dict): - auto_cleanup = config["debug_captures"].get("auto_cleanup", True) - keep_days = int(config["debug_captures"].get("keep_days", 7)) - max_files = int(config["debug_captures"].get("max_files", 2000)) - - if auto_cleanup: - cleanup_debug_captures(keep_days=keep_days, max_files=max_files) - except Exception: - # 初始化失败不影响程序运行 - pass - - -# 操作类型和步骤的中文映射 -_OPERATION_TYPE_CN = { - "cut_pic": "裁剪图片", - "ocr": "ocr", # 保持ocr不变 - "pixel_detect": "像素检测", - "template_match": "模板匹配", -} - -_STEP_CN = { - "before_ocr": "识别前", - "preprocessed": "预处理后", - "after_ocr": "识别后", - "before_detect": "检测前", - "detected": "检测成功", - "not_detected": "未检测到", - "matched": "匹配成功", - "failed": "匹配失败", -} - -# picname 的中文映射 -_PICNAME_CN = { - "live_room_title_mid": "直播间标题", # 现在只使用一个区域,简化为"直播间标题" - "live_room_title_large": "直播间标题_大", # 保留以兼容旧代码 - "live_room_title_small": "直播间标题_小", # 保留以兼容旧代码 - "live_room_title_mid_tmp": "直播间标题_临时", # 保留以兼容旧代码 - "live_room_title_large_tmp": "直播间标题_大_临时", # 保留以兼容旧代码 - "fudai_icon": "福袋图标", - "lucky_draw_result": "抽奖结果", - "attend_button": "参与按钮", - "live_room_icons": "直播间图标", - "fudai_content": "福袋内容", - "fudai_countdown": "福袋倒计时", - "fudai_value": "福袋价值", - "fudai_task_list": "福袋任务列表", - "fudai_coupon": "优惠券", - "shopping_redpacket": "购物红包", -} - -# extra_info 键名的中文映射 -_EXTRA_INFO_KEY_CN = { - "mode": "模式", - "size": "尺寸", - "used_img2": "使用图片2", - "avg_confidence": "平均置信度", - "min_confidence": "最小置信度", - "max_confidence": "最大置信度", - "confidence_items": "置信度项数", - "text_preview": "文本预览", - "text_len": "文本长度", - "source": "来源", - "has_full_screenshot": "有完整截图", - "has_coords": "有坐标", - "digits": "数字", - "type": "类型", - "region": "区域", - "y_offset": "Y偏移", - "region_size": "区域尺寸", - "content": "内容", - "threshold": "阈值", - "score": "分数", - "loc": "位置", -} - - -def _sanitize_filename_part(text: str) -> str: - """清理文件名部分,移除Windows不允许的字符 - - 参数: - text: 要清理的文本 - - 返回: - 清理后的文本 - """ - if not text: - return "" - - # Windows文件名不允许的字符: < > : " / \ | ? * - # 同时移除路径分隔符和空格(用下划线替换) - invalid_chars = '<>:"/\\|?*' - sanitized = str(text) - - # 如果是路径,只保留文件名部分 - if os.sep in sanitized or "/" in sanitized: - sanitized = os.path.basename(sanitized) - - # 移除所有无效字符 - for char in invalid_chars: - sanitized = sanitized.replace(char, "_") - - # 移除连续的下划线,替换为单个下划线 - while "__" in sanitized: - sanitized = sanitized.replace("__", "_") - - # 移除首尾的下划线和空格 - sanitized = sanitized.strip("_").strip() - - # 如果清理后为空,返回默认值 - if not sanitized: - sanitized = "unknown" - - return sanitized - - -def save_debug_image( # type: ignore - image: Image.Image, - operation_type: str = "", - picname: str = "", - step: str = "", - coords: Optional[Tuple[int, int, int, int]] = None, - extra_info: Optional[dict] = None, - session_id: Optional[str] = None, # noqa: ARG001 - annotate: bool = True, - auto_cleanup: bool = True, - background: Optional[bool] = None, -) -> Optional[str]: - """保存调试图像到存档目录 - - 参数: - image: PIL Image 对象 - operation_type: 操作类型("pixel_detect", "ocr", "template_match", "cut_pic") - picname: 图片名称(可选) - step: 步骤描述(可选,如 "before_detect", "detected") - coords: 坐标信息 (x1, y1, x2, y2)(可选) - extra_info: 额外信息字典(可选) - session_id: 会话ID(可选,默认使用当前日期,保留用于未来扩展) - annotate: 是否在图像上添加标注信息(默认True) - auto_cleanup: 是否自动清理旧目录(默认True) - - 返回: - 保存的文件路径,失败返回None - """ - try: - # 从配置读取是否启用调试图像保存;默认关闭 - try: - import json - - enabled = False - config_path = path_config.get_config_path() - if os.path.exists(config_path): - with open(config_path, "r", encoding="utf-8") as f: - config = json.load(f) - dbg_cfg = config.get("debug_captures") - if isinstance(dbg_cfg, dict): - enabled = bool(dbg_cfg.get("enabled", False)) - if not enabled: - return None - except Exception: - # 配置读取异常时,为安全起见直接跳过保存调试图像 - return None - - # 自动清理旧目录(仅在每天第一次保存时执行) - if auto_cleanup: - try: - # 检查今天是否已经清理过(使用简单的标记文件) - debug_base_dir = get_debug_captures_base_dir() - cleanup_marker = os.path.join(debug_base_dir, ".cleanup_marker") - from datetime import datetime - - today_str = datetime.now().strftime("%Y-%m-%d") - - # 读取标记文件,检查今天是否已清理 - need_cleanup = True - if os.path.exists(cleanup_marker): - try: - with open(cleanup_marker, "r", encoding="utf-8") as f: - last_cleanup_date = f.read().strip() - if last_cleanup_date == today_str: - need_cleanup = False - except Exception: - pass - - if need_cleanup: - # 从配置读取保留天数、最大文件数和自动清理设置 - keep_days = 7 # 默认7天 - max_files = 2000 # 默认2000个文件 - cleanup_enabled = True - try: - import json - - config_path = path_config.get_config_path() - if os.path.exists(config_path): - with open(config_path, "r", encoding="utf-8") as f: - config = json.load(f) - if "debug_captures" in config and isinstance( - config["debug_captures"], dict - ): - cleanup_enabled = config["debug_captures"].get( - "auto_cleanup", True - ) - keep_days = int( - config["debug_captures"].get("keep_days", 7) - ) - max_files = int( - config["debug_captures"].get("max_files", 2000) - ) - except Exception: - pass - - # 如果启用自动清理,执行清理 - if cleanup_enabled: - cleanup_debug_captures(keep_days=keep_days, max_files=max_files) - - # 更新标记文件(仅在执行清理后更新) - try: - with open(cleanup_marker, "w", encoding="utf-8") as f: - f.write(today_str) - except Exception: - pass - else: - # 即使今天已经清理过,也要检查文件数量是否超过限制 - # 如果超过,立即清理(不更新标记文件,避免频繁清理) - try: - import json - - config_path = path_config.get_config_path() - max_files = 2000 - if os.path.exists(config_path): - with open(config_path, "r", encoding="utf-8") as f: - config = json.load(f) - if "debug_captures" in config and isinstance( - config["debug_captures"], dict - ): - max_files = int( - config["debug_captures"].get("max_files", 2000) - ) - - # 检查当前文件数量 - current_count = count_debug_captures_files() - if current_count > max_files: - # 文件数量超过限制,立即清理 - try: - _mgr_log( - f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理" - ) - except Exception: - pass - cleanup_debug_captures( - keep_days=999, max_files=max_files - ) # keep_days设为999表示只按文件数量清理 - except Exception: - pass - except Exception: - # 清理失败不影响保存操作 - pass - - ensure_debug_captures_dir() - debug_dir = get_debug_captures_dir() - - # 生成文件名 - from datetime import datetime - - timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") - - parts = [] - if operation_type: - # 转换为中文 - operation_type_cn = _OPERATION_TYPE_CN.get(operation_type, operation_type) - parts.append(_sanitize_filename_part(operation_type_cn)) - if picname: - # 转换为中文 - picname_cn = _PICNAME_CN.get(picname, picname) - parts.append(_sanitize_filename_part(picname_cn)) - if step: - # 转换为中文 - step_cn = _STEP_CN.get(step, step) - parts.append(_sanitize_filename_part(step_cn)) - if coords: - parts.append(f"({coords[0]},{coords[1]})-({coords[2]},{coords[3]})") - if extra_info: - for key, value in extra_info.items(): - # 将键名转换为中文 - key_cn = _EXTRA_INFO_KEY_CN.get(key, key) - # 清理键名和值 - clean_key = _sanitize_filename_part(str(key_cn)) - # 处理值的转换(布尔值转为中文) - if isinstance(value, bool): - clean_value = "是" if value else "否" - else: - clean_value = _sanitize_filename_part(str(value)) - # 限制值的长度,避免文件名过长 - # 对于 text_preview 等长文本,限制更短(20字符) - if key == "text_preview" or key == "content": - if len(clean_value) > 20: - clean_value = clean_value[:20] - else: - if len(clean_value) > 30: - clean_value = clean_value[:30] - parts.append(f"{clean_key}_{clean_value}") - - filename_parts = [timestamp] + parts - filename = "_".join(str(p) for p in filename_parts if p) + ".png" - - # Windows文件名长度限制(260字符),自动截断 - # 考虑完整路径长度,文件名部分限制更严格 - max_len = 180 # 留更多余量,考虑目录路径长度 - if len(filename) > max_len: - # 保留时间戳和关键信息,截断其他部分 - # 优先保留:时间戳、操作类型、图片名、步骤 - base_parts = [timestamp] - if operation_type: - # 转换为中文 - operation_type_cn = _OPERATION_TYPE_CN.get( - operation_type, operation_type - ) - base_parts.append(_sanitize_filename_part(operation_type_cn)) - if picname: - # 转换为中文 - picname_cn = _PICNAME_CN.get(picname, picname) - base_parts.append(_sanitize_filename_part(picname_cn)) - if step: - # 转换为中文 - step_cn = _STEP_CN.get(step, step) - base_parts.append(_sanitize_filename_part(step_cn)) - - base = "_".join(base_parts) - - # 如果还有空间,添加最重要的额外信息(排除长文本) - remaining = max_len - len(base) - 10 # 留10字符余量 - if remaining > 20 and extra_info: - important_keys = ["mode", "size", "used_img2", "avg_confidence"] - for key in important_keys: - if key in extra_info and remaining > 0: - # 将键名转换为中文 - key_cn = _EXTRA_INFO_KEY_CN.get(key, key) - clean_key = _sanitize_filename_part(str(key_cn)) - # 处理值的转换(布尔值转为中文) - value = extra_info[key] - if isinstance(value, bool): - clean_value = "是" if value else "否" - else: - clean_value = _sanitize_filename_part(str(value)) - if len(clean_value) > 15: - clean_value = clean_value[:15] - part = f"{clean_key}_{clean_value}" - if len(part) <= remaining: - base += f"_{part}" - remaining -= len(part) + 1 - - filename = base[:max_len] + ".png" - - file_path = os.path.join(debug_dir, filename) - - # 在保存文件前,再次确保目录存在(防止并发访问或权限问题导致目录不存在) - try: - ensure_debug_captures_dir() - except Exception: - pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理 - - # 根据配置决定是否后台保存(优先使用函数参数,参数为 None 时读取 config) - if background is None: - try: - import json - - config_path = path_config.get_config_path() - if os.path.exists(config_path): - with open(config_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 {} - ) - background = bool(dbg_cfg.get("async_save", True)) - else: - background = True - except Exception: - background = True - - # 保存图像的辅助函数,带重试机制 - 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: - _mgr_log( - f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}" - ) - except Exception: - pass - else: - # 最后一次尝试失败,抛出异常 - raise - except PermissionError as e: - # 权限错误,不重试 - try: - _mgr_log(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}") - except Exception: - pass - raise - except OSError as e: - # 系统级错误(磁盘空间不足等),不重试 - try: - _mgr_log(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}") - except Exception: - pass - raise - except Exception as e: - # 其他异常直接抛出 - last_error = e - raise - # 所有重试都失败 - if last_error: - raise last_error - return False - - # 如果选择后台保存,入队并返回 None(不阻塞主线程) - if background: - try: - # 如果在高频路径中要求跳过调试保存(通过环境变量控制),则直接跳过以免阻塞或占用IO - if _SKIP_DEBUG_SAVE_IN_HOTLOOPS and operation_type in ( - "pixel_detect", - "cut_pic", - "pixel", - ): - try: - logging.debug( - "[截图管理] 跳过热路径调试保存: %s %s", - operation_type, - picname, - ) - except Exception: - pass - return None - _ensure_debug_save_worker_started() - # 放入队列(复制 image 避免被外部修改) - try: - img_copy = image.copy() - except Exception: - img_copy = image - t0 = time.time() - _debug_save_queue.put( - ( - img_copy, - file_path, - annotate, - coords, - extra_info, - operation_type, - picname, - step, - ) - ) - dur_enqueue = (time.time() - t0) * 1000.0 - try: - logging.debug( - "[截图管理] 异步入队耗时(ms): %.1f op=%s pic=%s", - dur_enqueue, - operation_type, - picname, - ) - except Exception: - pass - return None - except Exception: - # 如果队列机制失败,回退到同步保存 - pass - - # 如果需要标注,在图像上添加信息 - 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) - - # 添加文本信息:统一使用底部半透明信息栏,风格与 OCR 调试图一致 - try: - info_lines = [] - # 基础信息行:图片名 / 步骤 - if picname: - info_lines.append(str(_PICNAME_CN.get(picname, picname))) - if step: - info_lines.append(str(_STEP_CN.get(step, step))) - - # 坐标与额外信息优先展示重要字段 - if coords: - info_lines.append( - f"coords: ({coords[0]},{coords[1]})-({coords[2]},{coords[3]})" - ) - - if extra_info: - # 组织额外信息为若干行,按重要字段顺序展示 - important_keys = [ - "result", - "detected_x", - "detected_x_scaled", - "match_score", - "mode", - "size", - "avg_confidence", - "text_preview", - ] - for key in important_keys: - if key in extra_info: - info_lines.append( - f"{_EXTRA_INFO_KEY_CN.get(key, key)}: {extra_info.get(key)}" - ) - # 将其余的键也加入(但限制长度) - for k, v in extra_info.items(): - if k in important_keys: - continue - # 限制文本长度,避免溢出 - s = str(v) - if len(s) > 30: - s = s[:30] + "..." - info_lines.append(f"{_EXTRA_INFO_KEY_CN.get(k, k)}: {s}") - - # 如果没有任何信息,则不绘制信息栏 - if info_lines: - # 准备RGBA图层以绘制半透明底栏 - if annotated_image.mode != "RGBA": - annotated_image = annotated_image.convert("RGBA") - overlay = Image.new("RGBA", annotated_image.size, (0, 0, 0, 0)) - odraw = ImageDraw.Draw(overlay) - - # 计算文字区域高度 - padding_v = 6 - padding_h = 8 - max_width = annotated_image.size[0] - padding_h * 2 - lines_to_draw = [] - - # Helper to measure text size in a Pillow-version-safe way. - def _measure_text(text: str): - try: - # Preferred: ImageDraw.textbbox -> returns (left, top, right, bottom) - if hasattr(odraw, "textbbox"): - l, t, r, b = odraw.textbbox((0, 0), text, font=font) - return (r - l, b - t) - # 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"): - 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 - return (len(text) * 7, 14) - - for line in info_lines: - # 简单换行:如果太长,切断 - w, h = _measure_text(line) - if w > max_width: - # 估算每行能容纳的字符数并切断 - approx_chars = max( - 10, int(len(line) * max_width / max(int(w), 1)) - ) - lines_to_draw.append(line[:approx_chars] + "...") - else: - lines_to_draw.append(line) - - # Compute line height using safe measurement - try: - line_height = _measure_text("Ay")[1] - except Exception: - line_height = 14 - bar_height = padding_v * 2 + line_height * len(lines_to_draw) - img_w, img_h = annotated_image.size - bar_y1 = img_h - bar_height - bar_y2 = img_h - - # 绘制半透明白色底栏 - odraw.rectangle( - (0, bar_y1, img_w, bar_y2), fill=(255, 255, 255, 200) - ) - - # 绘制文字(黑色) - text_x = padding_h - text_y = bar_y1 + padding_v - for line in lines_to_draw: - try: - odraw.text( - (text_x, text_y), - line, - fill=(10, 10, 10, 255), - font=font, - ) - except Exception: - try: - odraw.text( - (text_x, text_y), line, fill=(10, 10, 10, 255) - ) - except Exception: - pass - text_y += line_height - - # 如果 extra_info 中包含匹配坐标(match_coords)或检测像素坐标(detected_x_scaled),绘制点/框以便快速定位 - try: - if extra_info: - # 模板匹配提供 match_coords 字段(tuple) - 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, - ) - # 像素检测提供 detected_x_scaled:图像坐标系中的x(单点),并依赖 coords 提供 y 区域 - elif "detected_x_scaled" in extra_info and coords: - try: - dx = int(extra_info["detected_x_scaled"]) - cy = (coords[1] + coords[3]) // 2 - r = max( - 4, int(min(annotated_image.size) * 0.01) - ) - odraw.ellipse( - [dx - r, cy - r, dx + r, cy + r], - fill=(0, 128, 255, 220), - outline=(0, 64, 192, 220), - ) - except Exception: - pass - except Exception: - pass - - # 合并 overlay 到原图并保存 - try: - annotated_image = Image.alpha_composite( - annotated_image, overlay - ) - # 转回 RGB 保存为PNG,以减少兼容问题 - annotated_image = annotated_image.convert("RGB") - except Exception: - pass - except Exception: - # 标注失败,回退到原有行为(什么也不画) - pass - - save_image_with_retry(annotated_image, file_path) - except (PermissionError, OSError) as e: - # 权限或系统错误,尝试保存原图 - try: - try: - _mgr_log(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}") - except Exception: - pass - save_image_with_retry(image, file_path) - except Exception: - # 如果保存原图也失败,抛出异常让外层处理 - raise - except Exception as e: - # 其他标注错误,尝试保存原图 - try: - try: - _mgr_log(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: - _mgr_log(f"[截图管理] 保存调试图像失败(文件/目录不存在): {e}") - except Exception: - pass - return None - except PermissionError as e: - # 权限错误 - try: - _mgr_log(f"[截图管理] 保存调试图像失败(权限错误): {e}") - except Exception: - pass - return None - except OSError as e: - # 系统级错误(磁盘空间不足、路径过长等) - try: - _mgr_log(f"[截图管理] 保存调试图像失败(系统错误): {e}") - except Exception: - pass - return None - except Exception as e: - # 其他未知错误 - try: - error_type = type(e).__name__ - _mgr_log(f"[截图管理] 保存调试图像失败({error_type}): {e}") - except Exception: - pass - return None - - # 结束 save_debug_image 的主逻辑,返回 None 表示保存失败 - return None +__all__ = [ + "_LOGGER", + "_mgr_log", + "_sanitize_filename_part", + "_SKIP_DEBUG_SAVE_IN_HOTLOOPS", + "_async_save_counters_lock", + "_debug_save_queue", + "_debug_save_shutdown_event", + "_debug_save_worker_lock", + "_debug_save_loop", + "_ensure_debug_save_worker_started", + "shutdown_debug_save_worker", + "get_async_save_counters", + "reset_async_save_counters", + "get_ocr_dir", + "get_category_for_picname", + "get_latest_attempt_path", + "get_last_success_path", + "ensure_ocr_dir", + "get_debug_captures_dir", + "ensure_debug_captures_dir", + "get_debug_captures_base_dir", + "cleanup_ocr_dir", + "save_latest_attempt", + "save_last_success", + "save_attempt_from_file", + "save_success_from_file", + "count_debug_captures_files", + "cleanup_debug_captures", + "init_debug_captures_cleanup", + "save_debug_image", +] diff --git a/douyin/handlers/screenshot_manager/__init__.py b/douyin/handlers/screenshot_manager/__init__.py new file mode 100644 index 0000000..4b60d2d --- /dev/null +++ b/douyin/handlers/screenshot_manager/__init__.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +"""screenshot_manager - 截图管理子包(双截图记录 + 异步调试保存)。 + +原 douyin/handlers/douyin_screenshot_manager.py 拆成 6 个子模块: + +- _common 共享 logger / 全局状态 / 异步计数器 +- paths OCR 目录、调试存档目录、各类路径计算 +- save_files save_latest_attempt / save_last_success / save_*_from_file / cleanup_ocr_dir +- async_save _debug_save_loop + 工作线程启停 +- cleanup debug_captures 目录的清理与轮转 +- save_image save_debug_image 主入口 + +外部 import 路径不变:from douyin.handlers.douyin_screenshot_manager import save_debug_image +仍能工作(原文件改为 re-export shell)。 +""" + +from ._common import ( + _LOGGER, + _mgr_log, + _debug_save_queue, + _debug_save_worker_lock, + _debug_save_shutdown_event, + _async_save_counters_lock, + _SKIP_DEBUG_SAVE_IN_HOTLOOPS, + get_async_save_counters, + reset_async_save_counters, +) +from .paths import ( + get_ocr_dir, + get_category_for_picname, + get_latest_attempt_path, + get_last_success_path, + ensure_ocr_dir, + get_debug_captures_dir, + ensure_debug_captures_dir, + get_debug_captures_base_dir, +) +from .save_files import ( + cleanup_ocr_dir, + save_latest_attempt, + save_last_success, + save_attempt_from_file, + save_success_from_file, +) +from .async_save import ( + _debug_save_loop, + _ensure_debug_save_worker_started, + shutdown_debug_save_worker, +) +from .cleanup import ( + count_debug_captures_files, + cleanup_debug_captures, + init_debug_captures_cleanup, +) +from .save_image import ( + _sanitize_filename_part, + save_debug_image, +) + +__all__ = [ + "_LOGGER", + "_mgr_log", + "get_async_save_counters", + "reset_async_save_counters", + "get_ocr_dir", + "get_category_for_picname", + "get_latest_attempt_path", + "get_last_success_path", + "ensure_ocr_dir", + "get_debug_captures_dir", + "ensure_debug_captures_dir", + "get_debug_captures_base_dir", + "cleanup_ocr_dir", + "save_latest_attempt", + "save_last_success", + "save_attempt_from_file", + "save_success_from_file", + "shutdown_debug_save_worker", + "count_debug_captures_files", + "cleanup_debug_captures", + "init_debug_captures_cleanup", + "save_debug_image", +] diff --git a/douyin/handlers/screenshot_manager/_common.py b/douyin/handlers/screenshot_manager/_common.py new file mode 100644 index 0000000..a840b04 --- /dev/null +++ b/douyin/handlers/screenshot_manager/_common.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +"""screenshot_manager._common - 共享 logger + 全局状态 + 异步保存计数器。 + +被本子包的 async_save / save_files / cleanup / save_image 共享: +- _LOGGER / _mgr_log:统一日志出口 +- _debug_save_queue / _debug_save_worker_started / _debug_save_worker_lock + / _debug_save_shutdown_event:异步保存的工作线程状态 +- _async_save_*_count / _async_save_counters_lock:异步计数器 +- _SKIP_DEBUG_SAVE_IN_HOTLOOPS:高频路径跳过开关 +""" + +import os +import threading +from queue import Queue +from typing import Optional, Tuple + +import logging as _logging +from PIL import Image + +# 模块级 logger:原代码用 print 输出截图管理 / 调试图像清理日志,统一走 logging。 +# 保留消息中已有的 "[截图管理]"/"[调试图像清理]" 前缀,避免改变历史搜索习惯。 +_LOGGER = _logging.getLogger("douyin.handlers.douyin_screenshot_manager") + + +def _mgr_log(msg: str, level: str = "INFO") -> None: + """统一截图管理日志出口;失败兜底 stdout。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + print(str(msg)) + except Exception: + pass + + +# 背景保存队列与工作线程(用于异步保存调试图像,避免阻塞主流程) +_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 +_debug_save_worker_lock = threading.Lock() # 保护 worker 启动的双检查锁 +_debug_save_shutdown_event = threading.Event() # 用于优雅关闭 + +# 异步保存计数(用于 GUI 显示) +_async_save_success_count = 0 +_async_save_failure_count = 0 +_async_save_counters_lock = threading.Lock() + +# 环境开关:在高频路径中跳过调试图像保存以提升性能(默认启用跳过) +_SKIP_DEBUG_SAVE_IN_HOTLOOPS = bool( + os.environ.get("SKIP_DEBUG_SAVE_IN_HOTLOOPS", "1") == "1" +) + + +def get_async_save_counters() -> tuple[int, int]: + """返回 (success_count, failure_count)""" + try: + with _async_save_counters_lock: + return int(_async_save_success_count), int(_async_save_failure_count) + except Exception: + return 0, 0 + + +def reset_async_save_counters() -> None: + """重置计数器(GUI 可调用)""" + try: + with _async_save_counters_lock: + global _async_save_success_count, _async_save_failure_count + _async_save_success_count = 0 + _async_save_failure_count = 0 + except Exception: + pass diff --git a/douyin/handlers/screenshot_manager/async_save.py b/douyin/handlers/screenshot_manager/async_save.py new file mode 100644 index 0000000..05ce57d --- /dev/null +++ b/douyin/handlers/screenshot_manager/async_save.py @@ -0,0 +1,360 @@ +from __future__ import annotations + +"""screenshot_manager.async_save - 异步调试图像保存工作线程。 + +定义: +- _debug_save_loop:消费 _debug_save_queue 的后台线程入口 +- shutdown_debug_save_worker:优雅关闭(atexit 注册一次) +- _ensure_debug_save_worker_started:启动 worker(双检查锁) +""" + +import json +import os +import threading +import traceback +from datetime import datetime +from queue import Empty +from typing import Optional, Tuple + +import logging +from PIL import Image, ImageDraw, ImageFont + +from douyin.core import path_config + +from ._common import ( + _async_save_counters_lock, + _debug_save_queue, + _debug_save_shutdown_event, + _debug_save_worker_lock, + _LOGGER, + _mgr_log, +) +from . import _common as _state +from .paths import ensure_debug_captures_dir + + +def _debug_save_loop() -> None: + """后台线程循环,消费调试图像保存任务并执行同步保存。""" + while not _debug_save_shutdown_event.is_set(): + try: + task = _debug_save_queue.get(timeout=1.0) + if task is None: + _debug_save_queue.task_done() + break + ( + img, + file_path, + annotate, + coords, + extra_info, + operation_type, + picname, + step, + ) = task + # 在函数中修改全局计数器时需要声明 global,避免静态分析/运行时错误 + try: + # 执行同步保存(重复之前 save_debug_image 中的标注与保存逻辑) + 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: + pass + else: + raise + except PermissionError: + raise + except OSError: + raise + if last_error: + raise last_error + return False + + # 标注并保存 + if annotate and (coords or extra_info): + try: + from PIL import ImageDraw, ImageFont + + annotated_image = img.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: + rect_coords = ( + 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 + + try: + _save_image_with_retry(annotated_image, file_path) + # 计数并写入 actions.log + try: + with _async_save_counters_lock: + _state._async_save_success_count += 1 + except Exception: + pass + try: + import logging + + logging.getLogger("action_logger").info( + "[调试图像] 异步保存完成: %s", file_path + ) + 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) + try: + with _async_save_counters_lock: + _state._async_save_success_count += 1 + except Exception: + pass + try: + import logging + + logging.getLogger("action_logger").info( + "[调试图像] 异步保存完成: %s", file_path + ) + 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: + # 保存失败:写入异步错误日志、计数并写入 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: + _state._async_save_failure_count += 1 + except Exception: + pass + try: + import logging + + logging.getLogger("action_logger").info( + "[调试图像] 异步保存失败: %s", file_path + ) + except Exception: + pass + # 捕获标注过程中的任何异常,避免线程退出 + except Exception: + pass + # end if annotate block + else: + try: + _save_image_with_retry(img, file_path) + try: + with _async_save_counters_lock: + _state._async_save_success_count += 1 + except Exception: + pass + try: + import logging + + logging.getLogger("action_logger").info( + "[调试图像] 异步保存完成: %s", file_path + ) + 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: + # 保存失败:写入异步错误日志以便追踪,同时记录到 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: + _state._async_save_failure_count += 1 + except Exception: + pass + try: + import logging + + logging.getLogger("action_logger").info( + "[调试图像] 异步保存失败: %s", file_path + ) + except Exception: + pass + except Exception: + pass + finally: + _debug_save_queue.task_done() + except Empty: + continue + except Exception: + # 防止线程因异常退出 + try: + import time + + time.sleep(0.1) + except Exception: + pass + + + + +def shutdown_debug_save_worker(timeout: float = 5.0) -> None: + """优雅关闭调试保存工作线程""" + if not _state._debug_save_worker_started: + return + _debug_save_shutdown_event.set() + _debug_save_queue.put(None) # 毒丸信号 + try: + _debug_save_queue.join() + except Exception: + pass + _state._debug_save_worker_started = False + + +# 注册 atexit 清理函数 +import atexit +atexit.register(shutdown_debug_save_worker) + + + + +def _ensure_debug_save_worker_started() -> None: + if _state._debug_save_worker_started: + return + with _debug_save_worker_lock: + if _state._debug_save_worker_started: + return + t = threading.Thread(target=_debug_save_loop, name="debug-save-worker", daemon=True) + t.start() + _state._debug_save_worker_started = True + + +# 注册 atexit 清理函数(仅注册一次) +import atexit +atexit.register(shutdown_debug_save_worker) diff --git a/douyin/handlers/screenshot_manager/cleanup.py b/douyin/handlers/screenshot_manager/cleanup.py new file mode 100644 index 0000000..f517b6b --- /dev/null +++ b/douyin/handlers/screenshot_manager/cleanup.py @@ -0,0 +1,293 @@ +from __future__ import annotations + +"""screenshot_manager.cleanup - 调试图像存档目录的轮转 / 清理。""" + +import os +import shutil +import time +from datetime import datetime + +from douyin.core import path_config + +from ._common import _mgr_log +from .paths import get_debug_captures_base_dir + + +def count_debug_captures_files() -> int: + """统计所有调试图像文件的总数量 + + 返回: + 文件总数 + """ + try: + debug_base_dir = get_debug_captures_base_dir() + if not os.path.exists(debug_base_dir): + return 0 + + total_count = 0 + # 遍历所有日期目录 + for item in os.listdir(debug_base_dir): + # 跳过隐藏文件和标记文件 + if item.startswith("."): + continue + + item_path = os.path.join(debug_base_dir, item) + if not os.path.isdir(item_path): + continue + + # 统计该目录下的所有PNG文件 + try: + for _root, _dirs, files in os.walk(item_path): + for f in files: + if f.lower().endswith(".png"): + total_count += 1 + except Exception: + pass + + return total_count + except Exception: + return 0 + + + + +def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: + """清理旧的调试图像存档目录 + + 参数: + keep_days: 保留天数,默认7天,超过此天数的目录将被删除 + max_files: 最大文件数量,默认2000,超过此数量时删除最旧的目录 + + 返回: + 清理的目录数量 + """ + try: + debug_base_dir = get_debug_captures_base_dir() + if not os.path.exists(debug_base_dir): + return 0 + + from datetime import datetime, timedelta + + # 计算截止日期 + cutoff_date = datetime.now() - timedelta(days=keep_days) + + deleted_count = 0 + deleted_dirs = [] + total_size_freed = 0 + + # 收集所有日期目录及其信息 + dirs_info = [] + for item in os.listdir(debug_base_dir): + # 跳过隐藏文件和标记文件 + if item.startswith("."): + continue + + item_path = os.path.join(debug_base_dir, item) + if not os.path.isdir(item_path): + continue + + # 尝试解析目录名为日期(格式:YYYY-MM-DD) + try: + dir_date = datetime.strptime(item, "%Y-%m-%d") + + # 统计该目录下的文件数量和大小 + file_count = 0 + dir_size = 0 + try: + for root, _dirs, files in os.walk(item_path): + for f in files: + if f.lower().endswith(".png"): + file_count += 1 + file_path = os.path.join(root, f) + try: + dir_size += os.path.getsize(file_path) + except Exception: + pass + except Exception: + pass + + dirs_info.append( + { + "name": item, + "path": item_path, + "date": dir_date, + "file_count": file_count, + "size": dir_size, + } + ) + except ValueError: + # 如果目录名不是日期格式,跳过 + continue + + # 按日期排序(最旧的在前) + dirs_info.sort(key=lambda x: x["date"]) + + # 先按天数清理:删除超过保留天数的目录 + for dir_info in dirs_info[:]: + if dir_info["date"] < cutoff_date: + try: + shutil.rmtree(dir_info["path"]) + deleted_count += 1 + deleted_dirs.append(dir_info["name"]) + total_size_freed += dir_info["size"] + dirs_info.remove(dir_info) + except Exception as e: + try: + _mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") + except Exception: + pass + + # 再按文件数量清理:如果文件总数超过max_files,删除最旧的目录 + total_files = sum(d["file_count"] for d in dirs_info) + if total_files > max_files: + # 计算需要删除的文件数量 + need_delete_count = total_files - max_files + + # 从最旧的目录开始删除,直到文件数量降到max_files以下 + deleted_files_count = 0 + for dir_info in dirs_info[:]: + if deleted_files_count >= need_delete_count: + break + + try: + shutil.rmtree(dir_info["path"]) + deleted_count += 1 + deleted_dirs.append(dir_info["name"]) + total_size_freed += dir_info["size"] + deleted_files_count += dir_info["file_count"] + dirs_info.remove(dir_info) + except Exception as e: + try: + _mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") + except Exception: + pass + + if deleted_count > 0: + try: + size_mb = total_size_freed / (1024 * 1024) + reason_parts = [] + if total_files > max_files: + reason_parts.append(f"文件数量超过{max_files}") + if any( + d["date"] < cutoff_date + for d in dirs_info + if d not in [{"name": name} for name in deleted_dirs] + ): + reason_parts.append(f"超过{keep_days}天") + reason = ",".join(reason_parts) if reason_parts else "自动清理" + + _mgr_log( + f"[调试图像清理] 已删除 {deleted_count} 个调试图像目录: {', '.join(deleted_dirs)}" + ) + _mgr_log(f"[调试图像清理] 清理原因: {reason}") + if size_mb > 0.1: # 只显示大于0.1MB的清理 + _mgr_log(f"[调试图像清理] 释放空间: {size_mb:.2f} MB") + except Exception: + pass + + return deleted_count + except Exception as e: + # 清理失败不应影响程序运行 + try: + _mgr_log(f"[调试图像清理] 清理旧调试图像时出错: {e}") + except Exception: + pass + return 0 + + + + +def init_debug_captures_cleanup() -> None: + """初始化调试图像清理(在程序启动时调用) + + 从 config.json 读取配置并执行清理 + """ + try: + import json + + config_path = path_config.get_config_path() + if not os.path.exists(config_path): + return + + with open(config_path, "r", encoding="utf-8") as f: + config = json.load(f) + + # 检查是否启用自动清理 + auto_cleanup = True + keep_days = 7 + max_files = 2000 + + if "debug_captures" in config and isinstance(config["debug_captures"], dict): + auto_cleanup = config["debug_captures"].get("auto_cleanup", True) + keep_days = int(config["debug_captures"].get("keep_days", 7)) + max_files = int(config["debug_captures"].get("max_files", 2000)) + + if auto_cleanup: + cleanup_debug_captures(keep_days=keep_days, max_files=max_files) + except Exception: + # 初始化失败不影响程序运行 + pass + + +# 操作类型和步骤的中文映射 +_OPERATION_TYPE_CN = { + "cut_pic": "裁剪图片", + "ocr": "ocr", # 保持ocr不变 + "pixel_detect": "像素检测", + "template_match": "模板匹配", +} + +_STEP_CN = { + "before_ocr": "识别前", + "preprocessed": "预处理后", + "after_ocr": "识别后", + "before_detect": "检测前", + "detected": "检测成功", + "not_detected": "未检测到", + "matched": "匹配成功", + "failed": "匹配失败", +} + +# picname 的中文映射 +_PICNAME_CN = { + "live_room_title_mid": "直播间标题", # 现在只使用一个区域,简化为"直播间标题" + "live_room_title_large": "直播间标题_大", # 保留以兼容旧代码 + "live_room_title_small": "直播间标题_小", # 保留以兼容旧代码 + "live_room_title_mid_tmp": "直播间标题_临时", # 保留以兼容旧代码 + "live_room_title_large_tmp": "直播间标题_大_临时", # 保留以兼容旧代码 + "fudai_icon": "福袋图标", + "lucky_draw_result": "抽奖结果", + "attend_button": "参与按钮", + "live_room_icons": "直播间图标", + "fudai_content": "福袋内容", + "fudai_countdown": "福袋倒计时", + "fudai_value": "福袋价值", + "fudai_task_list": "福袋任务列表", + "fudai_coupon": "优惠券", + "shopping_redpacket": "购物红包", +} + +# extra_info 键名的中文映射 +_EXTRA_INFO_KEY_CN = { + "mode": "模式", + "size": "尺寸", + "used_img2": "使用图片2", + "avg_confidence": "平均置信度", + "min_confidence": "最小置信度", + "max_confidence": "最大置信度", + "confidence_items": "置信度项数", + "text_preview": "文本预览", + "text_len": "文本长度", + "source": "来源", + "has_full_screenshot": "有完整截图", + "has_coords": "有坐标", + "digits": "数字", + "type": "类型", + "region": "区域", + "y_offset": "Y偏移", + "region_size": "区域尺寸", + "content": "内容", + "threshold": "阈值", + "score": "分数", + "loc": "位置", +} diff --git a/douyin/handlers/screenshot_manager/paths.py b/douyin/handlers/screenshot_manager/paths.py new file mode 100644 index 0000000..9d9345d --- /dev/null +++ b/douyin/handlers/screenshot_manager/paths.py @@ -0,0 +1,205 @@ +from __future__ import annotations + +"""screenshot_manager.paths - 路径计算与目录确保。 + +包含:OCR 目录、调试存档目录、最新尝试 / 上次成功的路径, +以及按图片名称分类到子目录的辅助函数。 +""" + +import os +from datetime import datetime + +from douyin.core import path_config + + +def get_ocr_dir() -> str: + """获取OCR目录路径""" + return os.path.join(path_config.get_pic_dir(), "ocr") + + + + +def get_category_for_picname(picname: str) -> str: + """根据图片名称判断应该保存到哪个分类目录 + + 参数: + picname: 图片名称(不含扩展名) + + 返回: + 分类目录名称,如 "fudai", "live_room", "popups", "buttons", "stage_diag", "others" + """ + picname_lower = picname.lower() + + # 福袋相关 + if any(keyword in picname_lower for keyword in ["福袋", "fudai"]): + return "fudai" + + # 直播间相关 + if any( + keyword in picname_lower + for keyword in [ + "live_room", + "直播间", + "直播列表", + "直播广场", + "直播状态", + "直播验证", + ] + ): + return "live_room" + + # 弹窗相关 + if any( + keyword in picname_lower + for keyword in [ + "抽奖结果", + "无奖励", + "优惠券", + "购物红包", + "奖励通知", + "订单确认", + "lucky_draw", + "coupon", + "redpacket", + "reward", + "order", + ] + ): + return "popups" + + # 按钮相关 + if any( + keyword in picname_lower + for keyword in ["参与按钮", "粉丝团", "attend_button", "fans_club"] + ): + return "buttons" + + # 阶段诊断相关 + if any( + keyword in picname_lower + for keyword in [ + "推荐页", + "关注列表", + "直播列表标签", + "recommend", + "follow", + "live_list", + ] + ): + return "stage_diag" + + # 其他 + return "others" + + + + +def get_latest_attempt_path(operation_type: str = "general") -> str: + """获取实时操作截图路径 + + 参数: + operation_type: 操作类型,可选值: + - "pixel" 或 "pixel_detect": 像素检测 + - "ocr": OCR识别 + - "template" 或 "template_match": 模板匹配 + - 其他: 通用操作 + """ + # 规范化操作类型 + if operation_type.startswith("pixel"): + type_key = "pixel" + elif operation_type.startswith("ocr") or operation_type.startswith("cut_pic"): + type_key = "ocr" + elif operation_type.startswith("template"): + type_key = "template" + else: + type_key = "general" + + return os.path.join(get_ocr_dir(), f"latest_attempt_{type_key}.png") + + + + +def get_last_success_path(operation_type: str = "general") -> str: + """获取成功识别存档截图路径 + + 参数: + operation_type: 操作类型,可选值: + - "pixel" 或 "pixel_detect": 像素检测 + - "ocr": OCR识别 + - "template" 或 "template_match": 模板匹配 + - 其他: 通用操作 + """ + # 规范化操作类型 + if operation_type.startswith("pixel"): + type_key = "pixel" + elif operation_type.startswith("ocr") or operation_type.startswith("cut_pic"): + type_key = "ocr" + elif operation_type.startswith("template"): + type_key = "template" + else: + type_key = "general" + + return os.path.join(get_ocr_dir(), f"last_success_{type_key}.png") + + + + +def ensure_ocr_dir() -> None: + """确保OCR目录存在""" + ocr_dir = get_ocr_dir() + os.makedirs(ocr_dir, exist_ok=True) + + + + +def get_debug_captures_dir() -> str: + """获取调试图像存档目录路径""" + pic_dir = path_config.get_pic_dir() + debug_dir = os.path.join(pic_dir, "debug_captures") + # 按日期分类:YYYY-MM-DD + from datetime import datetime + + date_str = datetime.now().strftime("%Y-%m-%d") + return os.path.join(debug_dir, date_str) + + + + +def ensure_debug_captures_dir() -> None: + """确保调试图像存档目录存在""" + try: + debug_dir = get_debug_captures_dir() + # 确保父目录也存在 + parent_dir = os.path.dirname(debug_dir) + if parent_dir and not os.path.exists(parent_dir): + 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: + 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: + _mgr_log(f"[截图管理] 创建调试图像目录失败({error_type}): {e}") + except Exception: + pass + raise + + + + +def get_debug_captures_base_dir() -> str: + """获取调试图像存档根目录路径(不包含日期)""" + pic_dir = path_config.get_pic_dir() + return os.path.join(pic_dir, "debug_captures") diff --git a/douyin/handlers/screenshot_manager/save_files.py b/douyin/handlers/screenshot_manager/save_files.py new file mode 100644 index 0000000..a0c737d --- /dev/null +++ b/douyin/handlers/screenshot_manager/save_files.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +"""screenshot_manager.save_files - 双截图记录的保存接口。 + +实时操作截图(latest_attempt_.png)每次都覆盖; +成功识别存档截图(last_success_.png)仅在成功时保存。 +""" + +import os +from PIL import Image + +from ._common import _mgr_log +from .paths import ( + ensure_ocr_dir, + get_latest_attempt_path, + get_last_success_path, + get_ocr_dir, +) + + +def cleanup_ocr_dir( + keep_latest_attempt: bool = True, + keep_last_success: bool = True, + keep_success_files: bool = True, + max_files: int = 50, +) -> int: + """清理OCR目录中的旧文件 + + 参数: + keep_latest_attempt: 是否保留所有 latest_attempt_*.png 文件 + keep_last_success: 是否保留所有 last_success_*.png 文件 + keep_success_files: 是否保留所有 _success.png 文件 + max_files: 最多保留的文件数(不包括特殊文件) + + 返回: + 清理的文件数量 + """ + try: + ocr_dir = get_ocr_dir() + if not os.path.exists(ocr_dir): + return 0 + + files = [] + for f in os.listdir(ocr_dir): + file_path = os.path.join(ocr_dir, f) + if os.path.isfile(file_path) and f.lower().endswith(".png"): + # 检查是否为特殊文件 + is_special = False + if f.startswith("latest_attempt_") and keep_latest_attempt: + is_special = True + elif f.startswith("last_success_") and keep_last_success: + is_special = True + elif f.endswith("_success.png") and keep_success_files: + is_special = True + + if not is_special: + files.append((file_path, os.path.getmtime(file_path))) + + # 按修改时间排序,保留最新的 + files.sort(key=lambda x: x[1], reverse=True) + + # 删除超出限制的文件 + deleted_count = 0 + for file_path, _ in files[max_files:]: + try: + os.remove(file_path) + deleted_count += 1 + except Exception: + pass + + return deleted_count + except Exception: + return 0 + + + + +def save_latest_attempt(image: Image.Image, operation_type: str = "") -> bool: + """保存实时操作截图(覆盖保存) + + 参数: + image: PIL Image 对象 + operation_type: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic") + + 返回: + 是否保存成功 + """ + try: + ensure_ocr_dir() + path = get_latest_attempt_path(operation_type) + image.save(path, "PNG") + return True + except Exception as e: + try: + _mgr_log(f"[截图管理] 保存 latest_attempt_{operation_type}.png 失败: {e}") + except Exception: + pass + return False + + + + +def save_last_success(image: Image.Image, operation_type: str = "") -> bool: + """保存成功识别存档截图(不覆盖,仅成功时保存) + + 参数: + image: PIL Image 对象 + operation_type: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic") + + 返回: + 是否保存成功 + """ + try: + ensure_ocr_dir() + path = get_last_success_path(operation_type) + image.save(path, "PNG") + return True + except Exception as e: + try: + _mgr_log(f"[截图管理] 保存 last_success_{operation_type}.png 失败: {e}") + except Exception: + pass + return False + + + + +def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool: + """从文件保存实时操作截图 + + 参数: + source_path: 源图片文件路径 + operation_type: 操作类型 + + 返回: + 是否保存成功 + """ + try: + if not os.path.exists(source_path): + return False + image = Image.open(source_path) + return save_latest_attempt(image, operation_type) + except Exception as e: + try: + _mgr_log(f"[截图管理] 从文件保存 latest_attempt.png 失败: {e}") + except Exception: + pass + return False + + + + +def save_success_from_file(source_path: str, operation_type: str = "") -> bool: + """从文件保存成功识别存档截图 + + 参数: + source_path: 源图片文件路径 + operation_type: 操作类型 + + 返回: + 是否保存成功 + """ + try: + if not os.path.exists(source_path): + return False + image = Image.open(source_path) + return save_last_success(image, operation_type) + except Exception as e: + try: + _mgr_log(f"[截图管理] 从文件保存 last_success.png 失败: {e}") + except Exception: + pass + return False diff --git a/douyin/handlers/screenshot_manager/save_image.py b/douyin/handlers/screenshot_manager/save_image.py new file mode 100644 index 0000000..e585ff4 --- /dev/null +++ b/douyin/handlers/screenshot_manager/save_image.py @@ -0,0 +1,731 @@ +from __future__ import annotations + +"""screenshot_manager.save_image - save_debug_image 主入口。 + +包含 _sanitize_filename_part(文件名规范化)与 save_debug_image +(按 picname/operation_type/category 写入调试图像,支持异步队列)。 +""" + +import json +import os +import re +import threading +import time +import traceback +from datetime import datetime +from typing import Any, Optional, Tuple + +import logging +from PIL import Image, ImageDraw, ImageFont + +from douyin.core import path_config + +from ._common import ( + _async_save_counters_lock, + _debug_save_queue, + _LOGGER, + _mgr_log, + _SKIP_DEBUG_SAVE_IN_HOTLOOPS, +) +from . import _common as _state +from .paths import ( + ensure_debug_captures_dir, + get_category_for_picname, + get_debug_captures_dir, +) +from .async_save import _ensure_debug_save_worker_started + + +def _sanitize_filename_part(text: str) -> str: + """清理文件名部分,移除Windows不允许的字符 + + 参数: + text: 要清理的文本 + + 返回: + 清理后的文本 + """ + if not text: + return "" + + # Windows文件名不允许的字符: < > : " / \ | ? * + # 同时移除路径分隔符和空格(用下划线替换) + invalid_chars = '<>:"/\\|?*' + sanitized = str(text) + + # 如果是路径,只保留文件名部分 + if os.sep in sanitized or "/" in sanitized: + sanitized = os.path.basename(sanitized) + + # 移除所有无效字符 + for char in invalid_chars: + sanitized = sanitized.replace(char, "_") + + # 移除连续的下划线,替换为单个下划线 + while "__" in sanitized: + sanitized = sanitized.replace("__", "_") + + # 移除首尾的下划线和空格 + sanitized = sanitized.strip("_").strip() + + # 如果清理后为空,返回默认值 + if not sanitized: + sanitized = "unknown" + + return sanitized + + + + +def save_debug_image( # type: ignore + image: Image.Image, + operation_type: str = "", + picname: str = "", + step: str = "", + coords: Optional[Tuple[int, int, int, int]] = None, + extra_info: Optional[dict] = None, + session_id: Optional[str] = None, # noqa: ARG001 + annotate: bool = True, + auto_cleanup: bool = True, + background: Optional[bool] = None, +) -> Optional[str]: + """保存调试图像到存档目录 + + 参数: + image: PIL Image 对象 + operation_type: 操作类型("pixel_detect", "ocr", "template_match", "cut_pic") + picname: 图片名称(可选) + step: 步骤描述(可选,如 "before_detect", "detected") + coords: 坐标信息 (x1, y1, x2, y2)(可选) + extra_info: 额外信息字典(可选) + session_id: 会话ID(可选,默认使用当前日期,保留用于未来扩展) + annotate: 是否在图像上添加标注信息(默认True) + auto_cleanup: 是否自动清理旧目录(默认True) + + 返回: + 保存的文件路径,失败返回None + """ + try: + # 从配置读取是否启用调试图像保存;默认关闭 + try: + import json + + enabled = False + config_path = path_config.get_config_path() + if os.path.exists(config_path): + with open(config_path, "r", encoding="utf-8") as f: + config = json.load(f) + dbg_cfg = config.get("debug_captures") + if isinstance(dbg_cfg, dict): + enabled = bool(dbg_cfg.get("enabled", False)) + if not enabled: + return None + except Exception: + # 配置读取异常时,为安全起见直接跳过保存调试图像 + return None + + # 自动清理旧目录(仅在每天第一次保存时执行) + if auto_cleanup: + try: + # 检查今天是否已经清理过(使用简单的标记文件) + debug_base_dir = get_debug_captures_base_dir() + cleanup_marker = os.path.join(debug_base_dir, ".cleanup_marker") + from datetime import datetime + + today_str = datetime.now().strftime("%Y-%m-%d") + + # 读取标记文件,检查今天是否已清理 + need_cleanup = True + if os.path.exists(cleanup_marker): + try: + with open(cleanup_marker, "r", encoding="utf-8") as f: + last_cleanup_date = f.read().strip() + if last_cleanup_date == today_str: + need_cleanup = False + except Exception: + pass + + if need_cleanup: + # 从配置读取保留天数、最大文件数和自动清理设置 + keep_days = 7 # 默认7天 + max_files = 2000 # 默认2000个文件 + cleanup_enabled = True + try: + import json + + config_path = path_config.get_config_path() + if os.path.exists(config_path): + with open(config_path, "r", encoding="utf-8") as f: + config = json.load(f) + if "debug_captures" in config and isinstance( + config["debug_captures"], dict + ): + cleanup_enabled = config["debug_captures"].get( + "auto_cleanup", True + ) + keep_days = int( + config["debug_captures"].get("keep_days", 7) + ) + max_files = int( + config["debug_captures"].get("max_files", 2000) + ) + except Exception: + pass + + # 如果启用自动清理,执行清理 + if cleanup_enabled: + cleanup_debug_captures(keep_days=keep_days, max_files=max_files) + + # 更新标记文件(仅在执行清理后更新) + try: + with open(cleanup_marker, "w", encoding="utf-8") as f: + f.write(today_str) + except Exception: + pass + else: + # 即使今天已经清理过,也要检查文件数量是否超过限制 + # 如果超过,立即清理(不更新标记文件,避免频繁清理) + try: + import json + + config_path = path_config.get_config_path() + max_files = 2000 + if os.path.exists(config_path): + with open(config_path, "r", encoding="utf-8") as f: + config = json.load(f) + if "debug_captures" in config and isinstance( + config["debug_captures"], dict + ): + max_files = int( + config["debug_captures"].get("max_files", 2000) + ) + + # 检查当前文件数量 + current_count = count_debug_captures_files() + if current_count > max_files: + # 文件数量超过限制,立即清理 + try: + _mgr_log( + f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理" + ) + except Exception: + pass + cleanup_debug_captures( + keep_days=999, max_files=max_files + ) # keep_days设为999表示只按文件数量清理 + except Exception: + pass + except Exception: + # 清理失败不影响保存操作 + pass + + ensure_debug_captures_dir() + debug_dir = get_debug_captures_dir() + + # 生成文件名 + from datetime import datetime + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + + parts = [] + if operation_type: + # 转换为中文 + operation_type_cn = _OPERATION_TYPE_CN.get(operation_type, operation_type) + parts.append(_sanitize_filename_part(operation_type_cn)) + if picname: + # 转换为中文 + picname_cn = _PICNAME_CN.get(picname, picname) + parts.append(_sanitize_filename_part(picname_cn)) + if step: + # 转换为中文 + step_cn = _STEP_CN.get(step, step) + parts.append(_sanitize_filename_part(step_cn)) + if coords: + parts.append(f"({coords[0]},{coords[1]})-({coords[2]},{coords[3]})") + if extra_info: + for key, value in extra_info.items(): + # 将键名转换为中文 + key_cn = _EXTRA_INFO_KEY_CN.get(key, key) + # 清理键名和值 + clean_key = _sanitize_filename_part(str(key_cn)) + # 处理值的转换(布尔值转为中文) + if isinstance(value, bool): + clean_value = "是" if value else "否" + else: + clean_value = _sanitize_filename_part(str(value)) + # 限制值的长度,避免文件名过长 + # 对于 text_preview 等长文本,限制更短(20字符) + if key == "text_preview" or key == "content": + if len(clean_value) > 20: + clean_value = clean_value[:20] + else: + if len(clean_value) > 30: + clean_value = clean_value[:30] + parts.append(f"{clean_key}_{clean_value}") + + filename_parts = [timestamp] + parts + filename = "_".join(str(p) for p in filename_parts if p) + ".png" + + # Windows文件名长度限制(260字符),自动截断 + # 考虑完整路径长度,文件名部分限制更严格 + max_len = 180 # 留更多余量,考虑目录路径长度 + if len(filename) > max_len: + # 保留时间戳和关键信息,截断其他部分 + # 优先保留:时间戳、操作类型、图片名、步骤 + base_parts = [timestamp] + if operation_type: + # 转换为中文 + operation_type_cn = _OPERATION_TYPE_CN.get( + operation_type, operation_type + ) + base_parts.append(_sanitize_filename_part(operation_type_cn)) + if picname: + # 转换为中文 + picname_cn = _PICNAME_CN.get(picname, picname) + base_parts.append(_sanitize_filename_part(picname_cn)) + if step: + # 转换为中文 + step_cn = _STEP_CN.get(step, step) + base_parts.append(_sanitize_filename_part(step_cn)) + + base = "_".join(base_parts) + + # 如果还有空间,添加最重要的额外信息(排除长文本) + remaining = max_len - len(base) - 10 # 留10字符余量 + if remaining > 20 and extra_info: + important_keys = ["mode", "size", "used_img2", "avg_confidence"] + for key in important_keys: + if key in extra_info and remaining > 0: + # 将键名转换为中文 + key_cn = _EXTRA_INFO_KEY_CN.get(key, key) + clean_key = _sanitize_filename_part(str(key_cn)) + # 处理值的转换(布尔值转为中文) + value = extra_info[key] + if isinstance(value, bool): + clean_value = "是" if value else "否" + else: + clean_value = _sanitize_filename_part(str(value)) + if len(clean_value) > 15: + clean_value = clean_value[:15] + part = f"{clean_key}_{clean_value}" + if len(part) <= remaining: + base += f"_{part}" + remaining -= len(part) + 1 + + filename = base[:max_len] + ".png" + + file_path = os.path.join(debug_dir, filename) + + # 在保存文件前,再次确保目录存在(防止并发访问或权限问题导致目录不存在) + try: + ensure_debug_captures_dir() + except Exception: + pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理 + + # 根据配置决定是否后台保存(优先使用函数参数,参数为 None 时读取 config) + if background is None: + try: + import json + + config_path = path_config.get_config_path() + if os.path.exists(config_path): + with open(config_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 {} + ) + background = bool(dbg_cfg.get("async_save", True)) + else: + background = True + except Exception: + background = True + + # 保存图像的辅助函数,带重试机制 + 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: + _mgr_log( + f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}" + ) + except Exception: + pass + else: + # 最后一次尝试失败,抛出异常 + raise + except PermissionError as e: + # 权限错误,不重试 + try: + _mgr_log(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}") + except Exception: + pass + raise + except OSError as e: + # 系统级错误(磁盘空间不足等),不重试 + try: + _mgr_log(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}") + except Exception: + pass + raise + except Exception as e: + # 其他异常直接抛出 + last_error = e + raise + # 所有重试都失败 + if last_error: + raise last_error + return False + + # 如果选择后台保存,入队并返回 None(不阻塞主线程) + if background: + try: + # 如果在高频路径中要求跳过调试保存(通过环境变量控制),则直接跳过以免阻塞或占用IO + if _SKIP_DEBUG_SAVE_IN_HOTLOOPS and operation_type in ( + "pixel_detect", + "cut_pic", + "pixel", + ): + try: + logging.debug( + "[截图管理] 跳过热路径调试保存: %s %s", + operation_type, + picname, + ) + except Exception: + pass + return None + _ensure_debug_save_worker_started() + # 放入队列(复制 image 避免被外部修改) + try: + img_copy = image.copy() + except Exception: + img_copy = image + t0 = time.time() + _debug_save_queue.put( + ( + img_copy, + file_path, + annotate, + coords, + extra_info, + operation_type, + picname, + step, + ) + ) + dur_enqueue = (time.time() - t0) * 1000.0 + try: + logging.debug( + "[截图管理] 异步入队耗时(ms): %.1f op=%s pic=%s", + dur_enqueue, + operation_type, + picname, + ) + except Exception: + pass + return None + except Exception: + # 如果队列机制失败,回退到同步保存 + pass + + # 如果需要标注,在图像上添加信息 + 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) + + # 添加文本信息:统一使用底部半透明信息栏,风格与 OCR 调试图一致 + try: + info_lines = [] + # 基础信息行:图片名 / 步骤 + if picname: + info_lines.append(str(_PICNAME_CN.get(picname, picname))) + if step: + info_lines.append(str(_STEP_CN.get(step, step))) + + # 坐标与额外信息优先展示重要字段 + if coords: + info_lines.append( + f"coords: ({coords[0]},{coords[1]})-({coords[2]},{coords[3]})" + ) + + if extra_info: + # 组织额外信息为若干行,按重要字段顺序展示 + important_keys = [ + "result", + "detected_x", + "detected_x_scaled", + "match_score", + "mode", + "size", + "avg_confidence", + "text_preview", + ] + for key in important_keys: + if key in extra_info: + info_lines.append( + f"{_EXTRA_INFO_KEY_CN.get(key, key)}: {extra_info.get(key)}" + ) + # 将其余的键也加入(但限制长度) + for k, v in extra_info.items(): + if k in important_keys: + continue + # 限制文本长度,避免溢出 + s = str(v) + if len(s) > 30: + s = s[:30] + "..." + info_lines.append(f"{_EXTRA_INFO_KEY_CN.get(k, k)}: {s}") + + # 如果没有任何信息,则不绘制信息栏 + if info_lines: + # 准备RGBA图层以绘制半透明底栏 + if annotated_image.mode != "RGBA": + annotated_image = annotated_image.convert("RGBA") + overlay = Image.new("RGBA", annotated_image.size, (0, 0, 0, 0)) + odraw = ImageDraw.Draw(overlay) + + # 计算文字区域高度 + padding_v = 6 + padding_h = 8 + max_width = annotated_image.size[0] - padding_h * 2 + lines_to_draw = [] + + # Helper to measure text size in a Pillow-version-safe way. + def _measure_text(text: str): + try: + # Preferred: ImageDraw.textbbox -> returns (left, top, right, bottom) + if hasattr(odraw, "textbbox"): + l, t, r, b = odraw.textbbox((0, 0), text, font=font) + return (r - l, b - t) + # 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"): + 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 + return (len(text) * 7, 14) + + for line in info_lines: + # 简单换行:如果太长,切断 + w, h = _measure_text(line) + if w > max_width: + # 估算每行能容纳的字符数并切断 + approx_chars = max( + 10, int(len(line) * max_width / max(int(w), 1)) + ) + lines_to_draw.append(line[:approx_chars] + "...") + else: + lines_to_draw.append(line) + + # Compute line height using safe measurement + try: + line_height = _measure_text("Ay")[1] + except Exception: + line_height = 14 + bar_height = padding_v * 2 + line_height * len(lines_to_draw) + img_w, img_h = annotated_image.size + bar_y1 = img_h - bar_height + bar_y2 = img_h + + # 绘制半透明白色底栏 + odraw.rectangle( + (0, bar_y1, img_w, bar_y2), fill=(255, 255, 255, 200) + ) + + # 绘制文字(黑色) + text_x = padding_h + text_y = bar_y1 + padding_v + for line in lines_to_draw: + try: + odraw.text( + (text_x, text_y), + line, + fill=(10, 10, 10, 255), + font=font, + ) + except Exception: + try: + odraw.text( + (text_x, text_y), line, fill=(10, 10, 10, 255) + ) + except Exception: + pass + text_y += line_height + + # 如果 extra_info 中包含匹配坐标(match_coords)或检测像素坐标(detected_x_scaled),绘制点/框以便快速定位 + try: + if extra_info: + # 模板匹配提供 match_coords 字段(tuple) + 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, + ) + # 像素检测提供 detected_x_scaled:图像坐标系中的x(单点),并依赖 coords 提供 y 区域 + elif "detected_x_scaled" in extra_info and coords: + try: + dx = int(extra_info["detected_x_scaled"]) + cy = (coords[1] + coords[3]) // 2 + r = max( + 4, int(min(annotated_image.size) * 0.01) + ) + odraw.ellipse( + [dx - r, cy - r, dx + r, cy + r], + fill=(0, 128, 255, 220), + outline=(0, 64, 192, 220), + ) + except Exception: + pass + except Exception: + pass + + # 合并 overlay 到原图并保存 + try: + annotated_image = Image.alpha_composite( + annotated_image, overlay + ) + # 转回 RGB 保存为PNG,以减少兼容问题 + annotated_image = annotated_image.convert("RGB") + except Exception: + pass + except Exception: + # 标注失败,回退到原有行为(什么也不画) + pass + + save_image_with_retry(annotated_image, file_path) + except (PermissionError, OSError) as e: + # 权限或系统错误,尝试保存原图 + try: + try: + _mgr_log(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}") + except Exception: + pass + save_image_with_retry(image, file_path) + except Exception: + # 如果保存原图也失败,抛出异常让外层处理 + raise + except Exception as e: + # 其他标注错误,尝试保存原图 + try: + try: + _mgr_log(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: + _mgr_log(f"[截图管理] 保存调试图像失败(文件/目录不存在): {e}") + except Exception: + pass + return None + except PermissionError as e: + # 权限错误 + try: + _mgr_log(f"[截图管理] 保存调试图像失败(权限错误): {e}") + except Exception: + pass + return None + except OSError as e: + # 系统级错误(磁盘空间不足、路径过长等) + try: + _mgr_log(f"[截图管理] 保存调试图像失败(系统错误): {e}") + except Exception: + pass + return None + except Exception as e: + # 其他未知错误 + try: + error_type = type(e).__name__ + _mgr_log(f"[截图管理] 保存调试图像失败({error_type}): {e}") + except Exception: + pass + return None + + # 结束 save_debug_image 的主逻辑,返回 None 表示保存失败 + return None