修正调试图标注对齐

This commit is contained in:
Your Name committed 2026-06-03 10:47:39 +08:00
1 parent 24b58a8c6d
commit 42aa0f214d
6 files changed
+187 -218

No files matched your search

+23 -13
View File
@@ -134,14 +134,22 @@ def _save_pixel_stage_overview(
detail_profile = get_fudai_detail_profile(mode, task_count=task_count)
lottery_profile = get_lottery_result_confirm_profile(mode)
regions = {
"coupon": ("has_coupon_bg", (9, 1173, 1079, 2255)),
"redpacket": ("has_redpacket_bg", (200, 300, 880, 1400)),
"lottery": ("has_lucky_draw_result", tuple(lottery_profile.get("pixel") or (181, 1261, 890, 1389))),
"attend": ("has_attend_button_red", (200, 2000, 880, 2120)),
"fansclub": ("has_fansclub_join_red", (200, 1940, 880, 2140)),
"detail": ("has_fudai_detail", tuple(detail_profile.get("task_count") or (860, 1770, 1035, 1875))),
}
regions: dict[str, tuple[str, tuple[int, int, int, int]]] = {}
if state.get("has_fudai_detail"):
regions["detail_body"] = ("has_fudai_detail", (0, 1160, 1080, 2250))
if task_count not in (None, 0):
regions["task_count"] = ("has_fudai_detail", tuple(detail_profile.get("task_count") or (860, 1770, 1035, 1875)))
else:
if state.get("has_coupon_bg"):
regions["coupon"] = ("has_coupon_bg", (9, 1173, 1079, 2255))
if state.get("has_redpacket_bg"):
regions["redpacket"] = ("has_redpacket_bg", (200, 300, 880, 1400))
if state.get("has_lucky_draw_result"):
regions["lottery"] = ("has_lucky_draw_result", tuple(lottery_profile.get("pixel") or (181, 1261, 890, 1389)))
if state.get("has_attend_button_red"):
regions["attend"] = ("has_attend_button_red", (200, 2000, 880, 2120))
if state.get("has_fansclub_join_red"):
regions["fansclub"] = ("has_fansclub_join_red", (200, 1940, 880, 2140))
def _color_for(key: str) -> tuple[int, int, int]:
info = details.get(key, {})
@@ -157,12 +165,13 @@ def _save_pixel_stage_overview(
draw.rectangle((x1, y1, x2, y2), outline=color, width=4)
draw.text((x1 + 6, max(0, y1 - 26)), label, fill=color, font=small_font)
x1, y1, x2, y2 = _live_room_icon_bbox(width, height)
color = _color_for("has_live_room_pixel")
draw.rectangle((x1, y1, x2, y2), outline=color, width=4)
draw.text((max(0, x1 - 120), max(0, y1 - 26)), "liveicon", fill=color, font=small_font)
if state.get("has_live_room_pixel"):
x1, y1, x2, y2 = _live_room_icon_bbox(width, height)
color = _color_for("has_live_room_pixel")
draw.rectangle((x1, y1, x2, y2), outline=color, width=4)
draw.text((max(0, x1 - 120), max(0, y1 - 26)), "liveicon", fill=color, font=small_font)
panel_x, panel_y = 24, 28
panel_x = 24
lines = ["pixel stage overview"]
for key in (
"has_coupon_bg",
@@ -189,6 +198,7 @@ def _save_pixel_stage_overview(
panel_w = 620
panel_h = 36 + len(lines) * 28
panel_y = max(24, height - panel_h - 92)
draw.rectangle((panel_x - 10, panel_y - 10, panel_x + panel_w, panel_y + panel_h), fill=(0, 0, 0))
for idx, line in enumerate(lines):
draw.text((panel_x, panel_y + idx * 28), line, fill=(255, 255, 255), font=font if idx == 0 else small_font)
+3 -2
View File
@@ -478,9 +478,10 @@ def save_fudai_detail_debug_overview(
]
pad = 12
legend_h = 34 * len(legend_lines) + pad * 2
draw.rectangle((18, 90, min(width - 18, 1040), 90 + legend_h), fill=(0, 0, 0))
legend_y = max(0, height - legend_h - 78)
draw.rectangle((18, legend_y, min(width - 18, 1040), legend_y + legend_h), fill=(0, 0, 0))
for idx, line in enumerate(legend_lines):
draw.text((30, 102 + idx * 34), line, fill=(255, 255, 255), font=small_font)
draw.text((30, legend_y + 12 + idx * 34), line, fill=(255, 255, 255), font=small_font)
for idx, region in enumerate(region_list):
coords = tuple(region.get("coords") or ())
+66 -201
View File
@@ -17,7 +17,7 @@ from queue import Empty
from typing import Optional, Tuple
import logging
from PIL import Image, ImageDraw, ImageFont
from PIL import Image
from douyin.core import path_config
@@ -29,6 +29,57 @@ from ._common import (
)
from . import _common as _state
from .paths import ensure_debug_captures_dir
from .save_image_helpers import annotate_debug_image
def _debug_log_on_complete(file_path: str) -> None:
try:
cfg_path = path_config.get_config_path()
log_on_complete = False
if os.path.exists(cfg_path):
with open(cfg_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 {}
)
log_on_complete = bool(dbg_cfg.get("log_on_complete", False))
if log_on_complete:
logging.debug("[调试图像] 异步保存完成: %s", file_path)
except Exception:
pass
def _record_async_success(file_path: str) -> None:
try:
with _async_save_counters_lock:
_state._async_save_success_count += 1
except Exception:
pass
_debug_log_on_complete(file_path)
def _record_async_failure(file_path: str) -> None:
try:
logs_dir = path_config.get_logs_dir()
os.makedirs(logs_dir, exist_ok=True)
err_path = os.path.join(logs_dir, "async_debug_save_errors.log")
with open(err_path, "a", encoding="utf-8") as ef:
ef.write(f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n")
ef.write(traceback.format_exc())
ef.write("\n\n")
except Exception:
pass
try:
with _async_save_counters_lock:
_state._async_save_failure_count += 1
except Exception:
pass
try:
logging.getLogger("action_logger").info("[调试图像] 异步保存失败: %s", file_path)
except Exception:
pass
def _debug_save_loop() -> None:
@@ -77,209 +128,23 @@ def _debug_save_loop() -> None:
raise last_error
return False
# 标注并保存
if annotate and (coords or extra_info):
try:
from PIL import ImageDraw, ImageFont
annotated_image = img.copy()
draw = ImageDraw.Draw(annotated_image)
try:
img_to_save = img
if annotate and (coords or extra_info):
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:
rect_coords = (
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
try:
_save_image_with_retry(annotated_image, file_path)
# 计数并写入 actions.log
try:
with _async_save_counters_lock:
_state._async_save_success_count += 1
except Exception:
pass
# 保存完成时的可选日志(原有逻辑)
try:
import json, logging
cfg_path = path_config.get_config_path()
log_on_complete = False
if os.path.exists(cfg_path):
with open(
cfg_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 {}
)
log_on_complete = bool(
dbg_cfg.get("log_on_complete", False)
)
if log_on_complete:
logging.debug(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
pass
except Exception:
try:
_save_image_with_retry(img, file_path)
try:
with _async_save_counters_lock:
_state._async_save_success_count += 1
except Exception:
pass
try:
import json, logging
cfg_path = path_config.get_config_path()
log_on_complete = False
if os.path.exists(cfg_path):
with open(
cfg_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 {}
)
log_on_complete = bool(
dbg_cfg.get(
"log_on_complete", False
)
)
if log_on_complete:
logging.debug(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
pass
except Exception:
# 保存失败:写入异步错误日志、计数并写入 actions.log
try:
logs_dir = path_config.get_logs_dir()
os.makedirs(logs_dir, exist_ok=True)
err_path = os.path.join(
logs_dir, "async_debug_save_errors.log"
)
with open(
err_path, "a", encoding="utf-8"
) as ef:
ef.write(
f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n"
)
ef.write(traceback.format_exc())
ef.write("\n\n")
except Exception:
pass
try:
with _async_save_counters_lock:
_state._async_save_failure_count += 1
except Exception:
pass
try:
import logging
logging.getLogger("action_logger").info(
"[调试图像] 异步保存失败: %s", file_path
)
except Exception:
pass
# 捕获标注过程中的任何异常,避免线程退出
except Exception:
pass
# end if annotate block
else:
try:
_save_image_with_retry(img, file_path)
try:
with _async_save_counters_lock:
_state._async_save_success_count += 1
except Exception:
pass
try:
import json, logging
cfg_path = path_config.get_config_path()
log_on_complete = False
if os.path.exists(cfg_path):
with open(cfg_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 {}
)
log_on_complete = bool(
dbg_cfg.get("log_on_complete", False)
)
if log_on_complete:
logging.debug("[调试图像] 异步保存完成: %s", file_path)
except Exception:
pass
except Exception:
# 保存失败:写入异步错误日志以便追踪,同时记录到 actions.log
try:
logs_dir = path_config.get_logs_dir()
os.makedirs(logs_dir, exist_ok=True)
err_path = os.path.join(
logs_dir, "async_debug_save_errors.log"
)
with open(err_path, "a", encoding="utf-8") as ef:
ef.write(
f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n"
)
ef.write(traceback.format_exc())
ef.write("\n\n")
except Exception:
pass
try:
with _async_save_counters_lock:
_state._async_save_failure_count += 1
except Exception:
pass
try:
import logging
logging.getLogger("action_logger").info(
"[调试图像] 异步保存失败: %s", file_path
img_to_save = annotate_debug_image(
image=img,
picname=picname,
step=step,
coords=coords,
extra_info=extra_info,
)
except Exception:
pass
img_to_save = img
_save_image_with_retry(img_to_save, file_path)
_record_async_success(file_path)
except Exception:
_record_async_failure(file_path)
except Exception:
pass
finally:
@@ -21,6 +21,7 @@ _SHORT_OPERATION_CODES = {
"cut_pic": "cut",
"ocr": "ocr",
"pixel_detect": "px",
"detection": "det",
"template_match": "tpl",
}
@@ -186,13 +187,13 @@ def maybe_auto_cleanup(auto_cleanup: bool, mgr_log) -> None:
def cleanup_single_operation_debug_images(operation_type: str) -> None:
"""Apply per-operation latest-only policies before saving a new debug image."""
if operation_type != "pixel_detect":
if operation_type not in {"pixel_detect", "detection"}:
return
try:
debug_dir = get_debug_captures_dir()
if not os.path.isdir(debug_dir):
return
tokens = ("_px_", "像素检测")
tokens = ("_px_", "像素检测") if operation_type == "pixel_detect" else ("_det_", "检测_福袋图标", "detection_福袋图标")
for name in os.listdir(debug_dir):
if not name.lower().endswith(".png"):
continue
+59
View File
@@ -169,9 +169,11 @@ class TestPixelStage:
(debug_dir / "20260603_px_attend_pre.png").write_bytes(b"old")
calls = []
saved_images = []
def fake_save_debug_image(image, **kwargs):
calls.append(kwargs)
saved_images.append(image.copy())
return str(debug_dir / "20260603_px_pxstage_ov_ok_0.png")
monkeypatch.setattr(
@@ -203,9 +205,66 @@ class TestPixelStage:
assert calls[0]["picname"] == "pixel_stage"
assert calls[0]["step"] == "overview"
assert calls[0]["annotate"] is False
assert saved_images
assert not (debug_dir / "20260603_像素检测_抽奖结果_检测前.png").exists()
assert not (debug_dir / "20260603_px_attend_pre.png").exists()
def test_pixel_stage_overview_does_not_draw_failed_candidate_boxes(self, tmp_path, monkeypatch):
from douyin.detection.pixel.stage import _save_pixel_stage_overview
debug_dir = tmp_path / "debug"
debug_dir.mkdir()
saved_images = []
def fake_save_debug_image(image, **kwargs):
saved_images.append(image.copy())
return str(debug_dir / "20260603_px_pxstage_ov_ok_1.png")
monkeypatch.setattr(
"douyin.handlers.screenshot_manager.save_image_helpers.is_debug_captures_enabled",
lambda: True,
)
monkeypatch.setattr(
"douyin.handlers.screenshot_manager.paths.get_debug_captures_dir",
lambda: str(debug_dir),
)
monkeypatch.setattr(
"douyin.handlers.douyin_screenshot_manager.save_debug_image",
fake_save_debug_image,
)
image = Image.new("RGB", (1080, 2400), (20, 20, 20))
_save_pixel_stage_overview(
image,
{
"has_coupon_bg": False,
"has_redpacket_bg": False,
"has_lucky_draw_result": False,
"has_attend_button_red": False,
"has_fansclub_join_red": False,
"has_fudai_detail": False,
"has_live_room_pixel": True,
},
{
"has_coupon_bg": {"method": "template_match", "template_score": 0.1},
"has_redpacket_bg": {"method": "disabled"},
"has_lucky_draw_result": {"method": "pixel_detect", "red_ratio": 0.0},
"has_attend_button_red": {"method": "pixel_detect", "red_ratio": 0.0},
"has_fansclub_join_red": {"method": "pixel_detect", "red_ratio": 0.0},
"has_fudai_detail": {"method": "task_count", "task_count": 0},
"has_live_room_pixel": {"method": "pixel_detection", "confidence": 0.95},
},
analyser=SimpleNamespace(fudai_detail_ui_mode="v2_0"),
)
assert saved_images
overview = saved_images[0]
# Old failed candidate boxes used to draw red outlines here.
assert overview.getpixel((10, 1173)) != (255, 70, 70)
assert overview.getpixel((250, 1261)) != (255, 70, 70)
# Successful live-room icon detection is still annotated.
assert overview.getpixel((1002, 172)) == (0, 220, 80)
class TestPixelCommon:
"""pixel/_common 模块测试。"""
@@ -141,6 +141,39 @@ class TestSaveImageModule:
assert not (tmp_path / "20260603_px_pxstage_ov_ok_1.png").exists()
assert ocr_file.exists()
def test_detection_debug_filename_uses_short_code(self):
from douyin.handlers.screenshot_manager.save_image_helpers import build_debug_filename
filename = build_debug_filename(
"detection",
"fudai_icon",
"detected",
(41, 348, 561, 540),
{"result": "success", "detected_x": 209},
)
assert "_det_fdicon_ok_" in filename
assert "福袋" not in filename
def test_cleanup_single_operation_debug_images_cleans_detection_only(self, tmp_path, monkeypatch):
from douyin.handlers.screenshot_manager.save_image_helpers import (
cleanup_single_operation_debug_images,
)
old_det = tmp_path / "20260603_detection_福袋图标_检测成功.png"
old_det.write_bytes(b"old")
old_px = tmp_path / "20260603_px_pxstage_ov_ok_1.png"
old_px.write_bytes(b"keep")
monkeypatch.setattr(
"douyin.handlers.screenshot_manager.save_image_helpers.get_debug_captures_dir",
lambda: str(tmp_path),
)
cleanup_single_operation_debug_images("detection")
assert not old_det.exists()
assert old_px.exists()
class TestScreenshotManagerSubmodules:
"""screenshot_manager 子模块存在性测试。"""