Files
douyi_guaji_main/douyin/handlers/screenshot_manager/save_image.py
T

216 lines
7.5 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 os
import time
from typing import Optional, Tuple
import logging
from PIL import Image
from .save_image_helpers import (
annotate_debug_image,
build_debug_filename,
cleanup_single_operation_debug_images,
is_debug_captures_enabled,
maybe_auto_cleanup,
resolve_background_flag,
save_image_with_retry,
sanitize_filename_part as _sanitize_filename_part_impl,
)
from ._common import (
_debug_save_queue,
_mgr_log,
_SKIP_DEBUG_SAVE_IN_HOTLOOPS,
)
from .cleanup import _EXTRA_INFO_KEY_CN, _OPERATION_TYPE_CN, _PICNAME_CN, _STEP_CN
from .paths import (
ensure_debug_captures_dir,
get_debug_captures_dir,
)
from .async_save import _ensure_debug_save_worker_started
def _sanitize_filename_part(text: str) -> str:
return _sanitize_filename_part_impl(text)
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,
force: bool = False,
) -> 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:
if not force and not is_debug_captures_enabled():
return None
maybe_auto_cleanup(auto_cleanup, _mgr_log)
ensure_debug_captures_dir()
debug_dir = get_debug_captures_dir()
filename = build_debug_filename(operation_type, picname, step, coords, extra_info)
cleanup_single_operation_debug_images(operation_type)
file_path = os.path.join(debug_dir, filename)
# 在保存文件前,再次确保目录存在(防止并发访问或权限问题导致目录不存在)
try:
ensure_debug_captures_dir()
except Exception:
pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理
background = resolve_background_flag(background)
# 如果选择后台保存,入队并返回 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:
annotated_image = annotate_debug_image(
image=image,
picname=picname,
step=step,
coords=coords,
extra_info=extra_info,
)
save_image_with_retry(annotated_image, file_path, ensure_debug_captures_dir)
except (PermissionError, OSError) as e:
# 权限或系统错误,尝试保存原图
try:
try:
_mgr_log(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}")
except Exception:
pass
save_image_with_retry(image, file_path, ensure_debug_captures_dir)
except Exception:
# 如果保存原图也失败,抛出异常让外层处理
raise
except Exception as e:
# 其他标注错误,尝试保存原图
try:
try:
_mgr_log(f"[截图管理] 图像标注失败,尝试保存原图: {e}")
except Exception:
pass
save_image_with_retry(image, file_path, ensure_debug_captures_dir)
except Exception:
# 如果保存原图也失败,抛出异常让外层处理
raise
else:
save_image_with_retry(image, file_path, ensure_debug_captures_dir)
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