from __future__ import annotations """ 截图管理模块:双截图记录机制 ============================ 功能: 1. 实时操作截图(latest_attempt.png):每次识别操作都覆盖保存 2. 成功识别存档截图(last_success.png):仅在成功时保存,不会被覆盖 3. OCR文件夹清理:自动清理旧的OCR图片 """ import os import shutil import time from typing import Optional, Tuple from PIL import Image 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 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: print(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: print(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: print(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: print(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): os.makedirs(parent_dir, exist_ok=True) os.makedirs(debug_dir, exist_ok=True) except Exception as e: # 如果目录创建失败,记录错误但不抛出异常(让调用方处理) try: print(f"[截图管理] 创建调试图像目录失败: {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: print(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: print(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 "自动清理" print( f"[调试图像清理] 已删除 {deleted_count} 个调试图像目录: {', '.join(deleted_dirs)}" ) print(f"[调试图像清理] 清理原因: {reason}") if size_mb > 0.1: # 只显示大于0.1MB的清理 print(f"[调试图像清理] 释放空间: {size_mb:.2f} MB") except Exception: pass return deleted_count except Exception as e: # 清理失败不应影响程序运行 try: print(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 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( 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, annotate: bool = True, auto_cleanup: bool = True, ) -> 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: print(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: parts.append(_sanitize_filename_part(operation_type)) if picname: parts.append(_sanitize_filename_part(picname)) if step: parts.append(_sanitize_filename_part(step)) if coords: parts.append(f"({coords[0]},{coords[1]})-({coords[2]},{coords[3]})") if extra_info: for key, value in extra_info.items(): # 清理键名和值 clean_key = _sanitize_filename_part(str(key)) 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: base_parts.append(_sanitize_filename_part(operation_type)) if picname: base_parts.append(_sanitize_filename_part(picname)) if step: base_parts.append(_sanitize_filename_part(step)) 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: clean_key = _sanitize_filename_part(str(key)) clean_value = _sanitize_filename_part(str(extra_info[key])) 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 # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理 # 保存图像的辅助函数,带重试机制 def save_image_with_retry(img_to_save: Image.Image, path: str, max_retries: int = 2) -> bool: """保存图像,如果目录不存在则创建后重试""" for attempt in range(max_retries): try: img_to_save.save(path, "PNG") return True except FileNotFoundError: # 目录不存在,尝试创建后重试 if attempt < max_retries - 1: try: ensure_debug_captures_dir() except Exception: pass else: # 最后一次尝试失败,抛出异常 raise except Exception: # 其他异常直接抛出 raise 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 Exception: # 如果标注失败,直接保存原图 try: save_image_with_retry(image, file_path) except Exception: # 如果保存原图也失败,抛出异常让外层处理 raise else: save_image_with_retry(image, file_path) return file_path except Exception as e: try: print(f"[截图管理] 保存调试图像失败: {e}") except Exception: pass return None