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) image.load() # Force load to catch truncated files early 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) image.load() # Force load to catch truncated files early return save_last_success(image, operation_type) except Exception as e: try: print(f"[截图管理] 从文件保存 last_success.png 失败: {e}") except Exception: pass return False