Files
douyi_guaji_main/douyin/handlers/screenshot_manager/save_image.py
T
CodexandClaude Opus 4.7 bf7f30996e 拆分 douyin_screenshot_manager (1705 → 6 个子模块 + 79 行 shim)
把巨型文件 douyin/handlers/douyin_screenshot_manager.py 按职责拆成
douyin/handlers/screenshot_manager/ 子包:

- _common (79)     共享 logger / 全局状态 / 异步计数器
- paths (205)      OCR 目录、调试存档目录、各类路径
- save_files (173) save_latest_attempt / save_last_success / save_*_from_file / cleanup_ocr_dir
- async_save (360) _debug_save_loop + 工作线程启停(global 状态走 _common._state.X)
- cleanup (293)    debug_captures 目录清理与轮转
- save_image (731) save_debug_image 主入口(最大头)

原文件改为 79 行 re-export shim,30 个公共符号全部保留。
外部 29 处 save_debug_image / 6 处 save_latest_attempt / 等
import 路径不变,零调用方修改。

回归:
- 子包 7 文件 + shim compileall 通过
- pytest 353 passed / 1 skipped(与拆分前完全一致)
- 旧 import 路径与新子包路径返回同一函数对象
- AST 验证 30 个期望符号全部正确暴露

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 16:25:59 +08:00

732 lines
31 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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