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

501 lines
17 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
"""save_image 的辅助函数:清理策略、文件名构造、后台保存开关。"""
import json
import os
from datetime import datetime
from typing import Optional, Tuple
from PIL import Image, ImageDraw, ImageFont
from douyin.core import path_config
from .cleanup import (
cleanup_debug_captures,
count_debug_captures_files,
_EXTRA_INFO_KEY_CN,
_PICNAME_CN,
_STEP_CN,
)
from .paths import get_debug_captures_base_dir, get_debug_captures_dir
from ._common import _mgr_log
_SHORT_OPERATION_CODES = {
"cut_pic": "cut",
"ocr": "ocr",
"pixel_detect": "px",
"detection": "det",
"template_match": "tpl",
}
_SHORT_STEP_CODES = {
"before_ocr": "preocr",
"preprocessed": "prep",
"after_ocr": "postocr",
"before_detect": "pre",
"detected": "ok",
"not_detected": "no",
"matched": "match",
"failed": "fail",
"overview": "ov",
}
_SHORT_PIC_CODES = {
"live_room_title_mid": "livetitle",
"live_room_title_large": "livetitle_lg",
"live_room_title_small": "livetitle_sm",
"live_room_title_mid_tmp": "livetitle_tmp",
"live_room_title_large_tmp": "livetitle_lg_tmp",
"fudai_icon": "fdicon",
"lucky_draw_result": "lottery",
"attend_button": "attend",
"fansclub_join": "fansclub",
"live_room_icons": "liveicon",
"pixel_stage": "pxstage",
"fudai_content": "fdcontent",
"fudai_countdown": "fdcountdown",
"fudai_value": "fdvalue",
"fudai_task_list": "fdtask",
"fudai_coupon": "coupon",
"shopping_redpacket": "redpacket",
"fudai_detail_overview": "fddetail",
}
_SHORT_EXTRA_KEYS = {
"avg_confidence": "avg",
"confidence": "conf",
"confidence_items": "items",
"content": "txt",
"digits": "digits",
"effective_threshold": "thr",
"has_coords": "coords",
"has_full_screenshot": "full",
"max_confidence": "max",
"min_confidence": "min",
"mode": "mode",
"ok": "ok",
"pixel_style": "style",
"red_ratio": "rr",
"region": "reg",
"region_name": "reg",
"region_size": "size",
"result": "res",
"score": "score",
"size": "size",
"source": "src",
"task_count_source": "tcsrc",
"text_len": "len",
"text_preview": "txt",
"threshold": "thr",
"ui_version": "ui",
"used_img2": "img2",
"white_ratio": "wr",
"y_offset": "dy",
}
def is_debug_captures_enabled() -> bool:
try:
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))
return enabled
except Exception:
return False
def sanitize_filename_part(text: str) -> str:
if not text:
return ""
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()
return sanitized or "unknown"
def maybe_auto_cleanup(auto_cleanup: bool, mgr_log) -> None:
if not auto_cleanup:
return
try:
debug_base_dir = get_debug_captures_base_dir()
cleanup_marker = os.path.join(debug_base_dir, ".cleanup_marker")
over_limit_marker = os.path.join(debug_base_dir, ".over_limit_marker")
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:
if f.read().strip() == today_str:
need_cleanup = False
except Exception:
pass
if need_cleanup:
keep_days = 7
max_files = 2000
cleanup_enabled = True
try:
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 = config.get("debug_captures")
if isinstance(dbg, dict):
cleanup_enabled = dbg.get("auto_cleanup", True)
keep_days = int(dbg.get("keep_days", 7))
max_files = int(dbg.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
return
try:
if os.path.exists(over_limit_marker):
try:
with open(over_limit_marker, "r", encoding="utf-8") as f:
if f.read().strip() == today_str:
return
except Exception:
pass
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)
dbg = config.get("debug_captures")
if isinstance(dbg, dict):
max_files = int(dbg.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
deleted = cleanup_debug_captures(keep_days=999, max_files=max_files)
if deleted == 0:
try:
mgr_log("[调试图像清理] 当前仅保留当天测试证据,本日跳过后续超限扫描")
except Exception:
pass
try:
with open(over_limit_marker, "w", encoding="utf-8") as f:
f.write(today_str)
except Exception:
pass
except Exception:
pass
except Exception:
pass
def cleanup_single_operation_debug_images(operation_type: str) -> None:
"""Apply per-operation cleanup policies before saving a new debug image."""
if operation_type != "detection":
return
try:
debug_dir = get_debug_captures_dir()
if not os.path.isdir(debug_dir):
return
tokens = ("_det_", "检测_福袋图标", "detection_福袋图标")
for name in os.listdir(debug_dir):
if not name.lower().endswith(".png"):
continue
if any(token in name for token in tokens):
try:
os.remove(os.path.join(debug_dir, name))
except Exception:
pass
except Exception:
pass
def build_debug_filename(
operation_type: str,
picname: str,
step: str,
coords: Optional[Tuple[int, int, int, int]],
extra_info: Optional[dict],
) -> str:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
parts = []
if operation_type:
parts.append(sanitize_filename_part(_SHORT_OPERATION_CODES.get(operation_type, operation_type)))
if picname:
parts.append(sanitize_filename_part(_SHORT_PIC_CODES.get(picname, picname)))
if step:
parts.append(sanitize_filename_part(_SHORT_STEP_CODES.get(step, step)))
if coords:
parts.append(f"x{coords[0]}y{coords[1]}w{max(0, coords[2]-coords[0])}h{max(0, coords[3]-coords[1])}")
if extra_info:
for key, value in list(extra_info.items())[:6]:
clean_key = sanitize_filename_part(str(_SHORT_EXTRA_KEYS.get(key, key)))
clean_value = "true" if isinstance(value, bool) and value else ("false" if isinstance(value, bool) else sanitize_filename_part(str(value)))
if key in ("text_preview", "content"):
if len(clean_value) > 12:
clean_value = clean_value[:12]
elif len(clean_value) > 16:
clean_value = clean_value[:16]
parts.append(f"{clean_key}_{clean_value}")
filename_parts = [timestamp] + parts
filename = "_".join(str(p) for p in filename_parts if p) + ".png"
max_len = 120
if len(filename) <= max_len:
return filename
base_parts = [timestamp]
if operation_type:
base_parts.append(sanitize_filename_part(_SHORT_OPERATION_CODES.get(operation_type, operation_type)))
if picname:
base_parts.append(sanitize_filename_part(_SHORT_PIC_CODES.get(picname, picname)))
if step:
base_parts.append(sanitize_filename_part(_SHORT_STEP_CODES.get(step, step)))
base = "_".join(base_parts)
remaining = max_len - len(base) - 10
if remaining > 20 and extra_info:
for key in ["mode", "size", "used_img2", "avg_confidence"]:
if key in extra_info and remaining > 0:
clean_key = sanitize_filename_part(str(_SHORT_EXTRA_KEYS.get(key, key)))
value = extra_info[key]
clean_value = "true" if isinstance(value, bool) and value else ("false" if isinstance(value, bool) else 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
return base[:max_len] + ".png"
def resolve_background_flag(background: Optional[bool]) -> bool:
if background is not None:
return bool(background)
try:
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 {}
return bool(dbg_cfg.get("async_save", True))
except Exception:
pass
return True
def save_image_with_retry(
img_to_save: Image.Image, path: str, ensure_debug_captures_dir, 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
def annotate_debug_image(
image: Image.Image,
picname: str,
step: str,
coords: Optional[Tuple[int, int, int, int]],
extra_info: Optional[dict],
) -> Image.Image:
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:
draw.rectangle((float(x1), float(y1), float(x2), float(y2)), outline="red", width=2)
def _draw_green_arrow(draw_ctx, target_x: int, target_y: int) -> None:
try:
img_w, img_h = annotated_image.size
tx = max(0, min(int(target_x), img_w - 1))
ty = max(0, min(int(target_y), img_h - 1))
start_x = max(10, tx - 120)
start_y = max(10, ty - 80)
draw_ctx.line((start_x, start_y, tx, ty), fill=(0, 220, 80, 255), width=5)
head = 16
draw_ctx.line((tx, ty, tx - head, ty - 4), fill=(0, 220, 80, 255), width=5)
draw_ctx.line((tx, ty, tx - 4, ty - head), fill=(0, 220, 80, 255), width=5)
except Exception:
pass
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 not info_lines:
return annotated_image
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)
def _measure_text(text: str):
try:
if hasattr(odraw, "textbbox"):
l, t, r, b = odraw.textbbox((0, 0), text, font=font)
return (r - l, b - t)
if font is not None and hasattr(font, "getbbox"):
l, t, r, b = font.getbbox(text)
return (r - l, b - t)
if font is not None:
mask = font.getmask(text)
return (mask.size[0], mask.size[1])
if hasattr(odraw, "textsize"):
return odraw.textsize(text, font=font) if font is not None else odraw.textsize(text)
except Exception:
pass
return (len(text) * 7, 14)
padding_v = 6
padding_h = 8
max_width = annotated_image.size[0] - padding_h * 2
lines_to_draw = []
for line in info_lines:
w, _ = _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)
line_height = _measure_text("Ay")[1]
bar_height = padding_v * 2 + line_height * len(lines_to_draw)
img_w, img_h = annotated_image.size
bar_y1 = img_h - bar_height
odraw.rectangle((0, bar_y1, img_w, img_h), 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
try:
if extra_info:
is_fudai_icon_success = (
picname == "fudai_icon"
and step == "detected"
and "detected_x_scaled" in extra_info
and coords
)
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"]
odraw.rectangle((mx1, my1, mx2, my2), outline=(255, 0, 0, 200), width=2)
elif "detected_x_scaled" in extra_info and coords and not is_fudai_icon_success:
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))
if is_fudai_icon_success:
_draw_green_arrow(odraw, int(extra_info["detected_x_scaled"]), (coords[1] + coords[3]) // 2)
except Exception:
pass
try:
out = Image.alpha_composite(annotated_image, overlay)
return out.convert("RGB")
except Exception:
return image.copy()