精简像素调试图与日志

This commit is contained in:
Your Name committed 2026-06-03 02:11:45 +08:00
1 parent 168ab4e1f8
commit e51d37890a
11 files changed
+663 -297

No files matched your search

@@ -88,7 +88,7 @@ def _save_cut_debug_images(self: Any, cropped_img, pic, name: str, source_label:
)
if debug_path:
try:
logging.info("[调试图像] cut_pic保存: %s", debug_path)
logging.debug("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
@@ -274,7 +274,7 @@ def cut_pic(
)
if debug_path:
try:
logging.info("[调试图像] cut_pic保存: %s", debug_path)
logging.debug("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
@@ -267,7 +267,7 @@ def _save_debug_preprocessed(
)
if debug_path:
try:
logging.info("[调试图像] OCR预处理保存: %s", debug_path)
logging.debug("[调试图像] OCR预处理保存: %s", debug_path)
except Exception:
pass
except Exception:
@@ -345,7 +345,7 @@ def _save_debug_after_ocr(
# 记录 OCR 置信度到日志
if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0:
try:
logging.info(
logging.debug(
"[OCR置信度] %s: 平均=%.4f, 最小=%.4f, 最大=%.4f, 项目数=%d",
picname,
ocr_confidence_info.get("avg_confidence", 0.0),
@@ -357,7 +357,7 @@ def _save_debug_after_ocr(
pass
if debug_path:
try:
logging.info(
logging.debug(
"[调试图像] OCR结果保存: %s, 文本: %s",
debug_path,
ocr_result_preview,
+8
View File
@@ -228,6 +228,7 @@ def _check_detail_task_count_legacy_pixels(analyser: Any) -> int:
task_count=(
detected_task_count if detected_task_count is not None else 0
),
log_type="DEBUG",
)
except Exception:
pass
@@ -341,6 +342,12 @@ def _check_detail_task_count_v2_pixels(analyser: Any) -> int:
f"识别到福袋任务数量:{detected}个(v2像素高度)",
task_count=detected,
source="v2_pixels",
)
analyser._log_kv(
"检测",
"福袋任务数量v2像素高度详情",
task_count=detected,
source="v2_pixels",
reason=reason,
check_x=x,
task_text_y=y_task_text,
@@ -348,6 +355,7 @@ def _check_detail_task_count_v2_pixels(analyser: Any) -> int:
task_card_y=y_task_card,
task_card_pixel=task_card_pixel,
ui_mode=ui_mode,
log_type="DEBUG",
)
except Exception:
pass
+106 -100
View File
@@ -24,6 +24,7 @@ def detect_attend_button_red_area(
return_info: bool = False,
red_ratio_threshold: float | None = None,
analyser: Any = None,
save_debug: bool = True,
) -> bool | tuple[bool, dict]:
"""检测参与按钮:大片红色区域。
@@ -53,26 +54,27 @@ def detect_attend_button_red_area(
return False
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
logging.info("[调试图像] 参与按钮检测前保存: %s", debug_path)
except Exception: # type: ignore[general-exception]
pass
except Exception: # type: ignore[general-exception]
pass
logging.debug("[调试图像] 参与按钮检测前保存: %s", debug_path)
except Exception: # type: ignore[general-exception]
pass
except Exception: # type: ignore[general-exception]
pass
# 采样检测点:检测大片红色区域
red_count = 0
@@ -127,38 +129,39 @@ def detect_attend_button_red_area(
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
# 无论成功失败都保存debug截图
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 参与按钮检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
debug_path,
red_ratio,
threshold,
"success" if result else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
logging.debug(
"[调试图像] 参与按钮检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
debug_path,
red_ratio,
threshold,
"success" if result else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
return result
except Exception:
@@ -178,6 +181,7 @@ def detect_fansclub_join_red_area(
return_info: bool = False,
red_ratio_threshold: float | None = None,
analyser: Any = None,
save_debug: bool = True,
) -> bool | tuple[bool, dict]:
"""检测粉丝团加入:大片红色区域。
@@ -212,29 +216,30 @@ def detect_fansclub_join_red_area(
return False
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="fansclub_join",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="fansclub_join",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 粉丝团加入检测前保存: %s",
debug_path,
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
logging.debug(
"[调试图像] 粉丝团加入检测前保存: %s",
debug_path,
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
# 采样检测点:检测大片红色区域
red_count = 0
@@ -280,39 +285,40 @@ def detect_fansclub_join_red_area(
result = red_ratio >= threshold
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="fansclub_join",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="fansclub_join",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 粉丝团加入检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
debug_path,
red_ratio,
threshold,
"success" if result else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
logging.debug(
"[调试图像] 粉丝团加入检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
debug_path,
red_ratio,
threshold,
"success" if result else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
if return_info:
reason_value: Optional[str] = (
+78 -75
View File
@@ -296,6 +296,7 @@ def detect_lucky_draw_result_popup(
red_ratio_threshold: float = 0.8,
return_info: bool = False,
analyser: Any = None,
save_debug: bool = True,
) -> bool | tuple[bool, dict]:
"""检测抽奖结果弹窗:"我知道了"按钮区域,按 UI 版本检测对应按钮颜色。
@@ -334,41 +335,42 @@ def detect_lucky_draw_result_popup(
# 双截图记录:保存实时操作截图(像素检测区域)
detect_roi = None
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_latest_attempt(
detect_roi, operation_type="pixel_detect"
)
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_latest_attempt(
detect_roi, operation_type="pixel_detect"
)
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="lucky_draw_result",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"threshold": red_ratio_threshold,
"region_size": f"{x2-x1}x{y2-y1}",
"ui_version": profile.get("version"),
"pixel_style": pixel_style,
},
)
if debug_path:
try:
import logging
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="lucky_draw_result",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"threshold": red_ratio_threshold,
"region_size": f"{x2-x1}x{y2-y1}",
"ui_version": profile.get("version"),
"pixel_style": pixel_style,
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 像素检测前保存: %s, threshold=%s",
debug_path,
red_ratio_threshold,
)
except Exception: # type: ignore[general-exception]
pass
except Exception:
pass
logging.debug(
"[调试图像] 像素检测前保存: %s, threshold=%s",
debug_path,
red_ratio_threshold,
)
except Exception: # type: ignore[general-exception]
pass
except Exception:
pass
red_count = 0
white_count = 0
@@ -402,51 +404,52 @@ def detect_lucky_draw_result_popup(
result = red_ratio >= red_ratio_threshold
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
if result:
# 检测成功
if detect_roi is None:
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_last_success(
detect_roi, operation_type="pixel_detect"
)
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="lucky_draw_result",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"white_ratio": round(white_ratio, 4),
"red_count": red_count,
"white_count": white_count,
"total_samples": total_samples,
"threshold": red_ratio_threshold,
"result": "success" if result else "failed",
"ui_version": profile.get("version"),
"pixel_style": pixel_style,
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 抽奖结果检测保存: %s, red_ratio=%.4f, threshold=%s, score=%.4f",
debug_path,
red_ratio,
red_ratio_threshold,
red_ratio,
if result:
# 检测成功
if detect_roi is None:
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_last_success(
detect_roi, operation_type="pixel_detect"
)
except Exception: # type: ignore[general-exception]
pass
except Exception:
pass
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="lucky_draw_result",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"white_ratio": round(white_ratio, 4),
"red_count": red_count,
"white_count": white_count,
"total_samples": total_samples,
"threshold": red_ratio_threshold,
"result": "success" if result else "failed",
"ui_version": profile.get("version"),
"pixel_style": pixel_style,
},
)
if debug_path:
try:
import logging
logging.debug(
"[调试图像] 抽奖结果检测保存: %s, red_ratio=%.4f, threshold=%s, score=%.4f",
debug_path,
red_ratio,
red_ratio_threshold,
red_ratio,
)
except Exception: # type: ignore[general-exception]
pass
except Exception:
pass
# 如果请求详细信息,返回包含red_ratio的字典
if return_info:
+255 -66
View File
@@ -29,7 +29,193 @@ from .popups import (
)
def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
def _scale_box(
box: tuple[int, int, int, int],
width: int,
height: int,
) -> tuple[int, int, int, int]:
scale_x = width / 1080.0
scale_y = height / 2400.0
x1, y1, x2, y2 = box
sx1 = max(0, min(int(x1 * scale_x), width))
sy1 = max(0, min(int(y1 * scale_y), height))
sx2 = max(0, min(int(x2 * scale_x), width))
sy2 = max(0, min(int(y2 * scale_y), height))
return min(sx1, sx2), min(sy1, sy2), max(sx1, sx2), max(sy1, sy2)
def _live_room_icon_bbox(width: int, height: int) -> tuple[int, int, int, int]:
points = [
(1002, 172),
(999, 174),
(1011, 186),
(999, 199),
(1002, 202),
(1013, 190),
(1025, 201),
(1028, 198),
(1017, 187),
(1028, 174),
(1025, 172),
(1014, 184),
]
scale_x = width / 1080.0
scale_y = height / 2400.0
scaled = [(int(x * scale_x), int(y * scale_y)) for x, y in points]
xs = [p[0] for p in scaled]
ys = [p[1] for p in scaled]
return max(0, min(xs)), max(0, min(ys)), min(width, max(xs)), min(height, max(ys))
def _cleanup_pixel_stage_debug_images() -> None:
"""Keep the stage pixel diagnosis output to one overview image per latest run."""
try:
from douyin.handlers.screenshot_manager.paths import get_debug_captures_dir
debug_dir = get_debug_captures_dir()
if not os.path.isdir(debug_dir):
return
tokens = (
"_px_pxstage_",
"_px_lottery_",
"_px_attend_",
"_px_fansclub_",
"_px_liveicon_",
"_px_coupon_",
"_px_redpacket_",
"像素检测_抽奖结果",
"像素检测_参与按钮",
"像素检测_fansclub_join",
"像素检测_直播间图标",
"像素检测_阶段像素检测总览",
)
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 _save_pixel_stage_overview(
pic_rgb: Image.Image,
state: dict[str, bool],
details: dict[str, dict],
analyser: Any = None,
) -> None:
try:
from PIL import ImageDraw, ImageFont
from douyin.fudai.core.coords import (
get_fudai_detail_profile,
get_lottery_result_confirm_profile,
)
from douyin.handlers import douyin_screenshot_manager
from douyin.handlers.screenshot_manager.save_image_helpers import is_debug_captures_enabled
if not is_debug_captures_enabled():
return
width, height = pic_rgb.size
overview = pic_rgb.copy()
draw = ImageDraw.Draw(overview)
try:
font = ImageFont.truetype("arial.ttf", 24)
small_font = ImageFont.truetype("arial.ttf", 18)
except Exception:
font = ImageFont.load_default()
small_font = font
mode = getattr(analyser, "fudai_detail_ui_mode", "auto") if analyser is not None else "auto"
task_count = details.get("has_fudai_detail", {}).get("task_count")
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))),
}
def _color_for(key: str) -> tuple[int, int, int]:
info = details.get(key, {})
if info.get("method") == "disabled":
return (160, 160, 160)
return (0, 220, 80) if state.get(key) else (255, 70, 70)
for label, (key, base_box) in regions.items():
x1, y1, x2, y2 = _scale_box(base_box, width, height)
if x1 >= x2 or y1 >= y2:
continue
color = _color_for(key)
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)
panel_x, panel_y = 24, 28
lines = ["pixel stage overview"]
for key in (
"has_coupon_bg",
"has_redpacket_bg",
"has_lucky_draw_result",
"has_attend_button_red",
"has_fansclub_join_red",
"has_fudai_detail",
"has_live_room_pixel",
):
info = details.get(key, {})
status = "off" if info.get("method") == "disabled" else ("ok" if state.get(key) else "no")
score = info.get("confidence")
if score is None:
score = info.get("red_ratio")
if score is None:
score = info.get("white_ratio")
if score is None:
score = info.get("template_score")
score_text = "" if score is None else f" score={float(score):.3f}"
elapsed = info.get("elapsed_ms")
elapsed_text = "" if elapsed is None else f" {elapsed}ms"
lines.append(f"{key.replace('has_', '')}: {status}{score_text}{elapsed_text}")
panel_w = 620
panel_h = 36 + len(lines) * 28
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)
_cleanup_pixel_stage_debug_images()
ok_count = sum(1 for value in state.values() if value)
debug_path = douyin_screenshot_manager.save_debug_image(
overview,
operation_type="pixel_detect",
picname="pixel_stage",
step="overview",
extra_info={"ok": ok_count},
annotate=False,
background=False,
)
if debug_path:
try:
import logging
logging.debug("[调试图像] 像素阶段总览保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
def detect_live_room_icons_by_pixel(pic_rgb: Image.Image, save_debug: bool = True) -> tuple[bool, float]:
"""通过像素检测多边形区域内的白色像素,判断是否在直播间。
检测指定多边形区域内的白色像素比例,基于1080x2400分辨率:
@@ -124,42 +310,43 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
x1, y1, x2, y2 = 0, 0, 0, 0
# 保存调试图像(检测结果)
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="live_room_icons",
step="detected" if detected else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域边界框
extra_info={
"white_ratio": round(white_ratio, 4),
"white_count": white_count,
"total_pixels": total_pixels,
"confidence": round(confidence, 4),
"threshold": 0.8,
"result": "success" if detected else "failed",
"polygon_points": len(polygon_points),
},
)
if debug_path:
try:
import logging
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="live_room_icons",
step="detected" if detected else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域边界框
extra_info={
"white_ratio": round(white_ratio, 4),
"white_count": white_count,
"total_pixels": total_pixels,
"confidence": round(confidence, 4),
"threshold": 0.8,
"result": "success" if detected else "failed",
"polygon_points": len(polygon_points),
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, white_count=%d, total_pixels=%d, confidence=%.4f, result=%s",
debug_path,
white_ratio,
white_count,
total_pixels,
confidence,
"success" if detected else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
logging.debug(
"[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, white_count=%d, total_pixels=%d, confidence=%.4f, result=%s",
debug_path,
white_ratio,
white_count,
total_pixels,
confidence,
"success" if detected else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
return bool(detected), float(confidence)
except Exception as e: # type: ignore[general-exception]
@@ -337,7 +524,7 @@ def read_pixel_stage_state_from_screenshot(
def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]:
"""直播间图标像素检测包装函数,返回 (bool, dict) 格式"""
try:
detected, confidence = detect_live_room_icons_by_pixel(pic)
detected, confidence = detect_live_room_icons_by_pixel(pic, save_debug=False)
threshold = live_room_pixel_threshold or 0.8
is_detected = detected and confidence >= threshold
return is_detected, {
@@ -371,6 +558,7 @@ def read_pixel_stage_state_from_screenshot(
lucky_draw_red_ratio_threshold,
return_info=True,
analyser=analyser,
save_debug=False,
)
if _enabled("pixel_detect_attend_button_enabled", True):
detection_tasks["has_attend_button_red"] = lambda pic: detect_attend_button_red_area(
@@ -378,6 +566,7 @@ def read_pixel_stage_state_from_screenshot(
return_info=True,
red_ratio_threshold=attend_button_threshold,
analyser=analyser,
save_debug=False,
)
if _enabled("pixel_detect_fansclub_join_enabled", True):
detection_tasks["has_fansclub_join_red"] = lambda pic: detect_fansclub_join_red_area(
@@ -385,6 +574,7 @@ def read_pixel_stage_state_from_screenshot(
return_info=True,
red_ratio_threshold=fansclub_threshold,
analyser=analyser,
save_debug=False,
)
if _enabled("pixel_detect_fudai_detail_enabled", True):
detection_tasks["has_fudai_detail"] = lambda pic: detect_fudai_detail_page(
@@ -399,10 +589,9 @@ def read_pixel_stage_state_from_screenshot(
if _enabled("pixel_detect_live_room_enabled", True):
detection_tasks["has_live_room_pixel"] = _detect_live_room_pixel_wrapper
if return_details:
for key in state:
if key not in detection_tasks:
details[key] = {"detected": False, "method": "disabled", "reason": "switch_off"}
for key in state:
if key not in detection_tasks:
details[key] = {"detected": False, "method": "disabled", "reason": "switch_off"}
if not detection_tasks:
if return_details:
return state, details
@@ -431,38 +620,38 @@ def read_pixel_stage_state_from_screenshot(
# 检测函数返回 (bool, dict) 格式
is_detected, info = result
state[key] = bool(is_detected)
if return_details:
details[key] = {
"detected": bool(is_detected),
"method": info.get("method", "unknown"),
"template_score": info.get("template_score"),
"confidence": info.get(
"confidence"
), # 添加confidence支持(用于像素检测)
"task_count": info.get("task_count"), # 添加task_count支持
"red_ratio": info.get("red_ratio"), # 添加red_ratio支持
"effective_threshold": info.get("effective_threshold"),
"reason": info.get("reason"),
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
details[key] = {
"detected": bool(is_detected),
"method": info.get("method", "unknown"),
"template_score": info.get("template_score"),
"confidence": info.get(
"confidence"
), # 添加confidence支持(用于像素检测)
"task_count": info.get("task_count"), # 添加task_count支持
"red_ratio": info.get("red_ratio"), # 添加red_ratio支持
"white_ratio": info.get("white_ratio"),
"effective_threshold": info.get("effective_threshold"),
"reason": info.get("reason"),
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
else:
# 其他检测返回 bool(不应该发生,因为所有检测都支持return_info)
state[key] = bool(result)
if return_details:
details[key] = {
"detected": bool(result),
"method": "unknown",
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
details[key] = {
"detected": bool(result),
"method": "unknown",
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
except Exception as e: # type: ignore[general-exception]
# 如果某个检测失败,保持默认值 False
state[key] = False
if return_details:
details[key] = {
"detected": False,
"error": str(e),
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
details[key] = {
"detected": False,
"error": str(e),
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
_save_pixel_stage_overview(pic_rgb, state, details, analyser=analyser)
if return_details:
return state, details
@@ -125,14 +125,6 @@ def _debug_save_loop() -> None:
_state._async_save_success_count += 1
except Exception:
pass
try:
import logging
logging.getLogger("action_logger").info(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
pass
# 保存完成时的可选日志(原有逻辑)
try:
import json, logging
@@ -155,7 +147,7 @@ def _debug_save_loop() -> None:
dbg_cfg.get("log_on_complete", False)
)
if log_on_complete:
logging.info(
logging.debug(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
@@ -168,14 +160,6 @@ def _debug_save_loop() -> None:
_state._async_save_success_count += 1
except Exception:
pass
try:
import logging
logging.getLogger("action_logger").info(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
pass
try:
import json, logging
@@ -197,9 +181,9 @@ def _debug_save_loop() -> None:
dbg_cfg.get(
"log_on_complete", False
)
)
)
if log_on_complete:
logging.info(
logging.debug(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
@@ -247,14 +231,6 @@ def _debug_save_loop() -> None:
_state._async_save_success_count += 1
except Exception:
pass
try:
import logging
logging.getLogger("action_logger").info(
"[调试图像] 异步保存完成: %s", file_path
)
except Exception:
pass
try:
import json, logging
@@ -272,7 +248,7 @@ def _debug_save_loop() -> None:
dbg_cfg.get("log_on_complete", False)
)
if log_on_complete:
logging.info("[调试图像] 异步保存完成: %s", file_path)
logging.debug("[调试图像] 异步保存完成: %s", file_path)
except Exception:
pass
except Exception:
@@ -16,6 +16,7 @@ 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,
@@ -82,6 +83,8 @@ def save_debug_image( # type: ignore
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)
# 在保存文件前,再次确保目录存在(防止并发访问或权限问题导致目录不存在)
@@ -11,16 +11,84 @@ from PIL import Image, ImageDraw, ImageFont
from douyin.core import path_config
from .cleanup import (
_EXTRA_INFO_KEY_CN,
_OPERATION_TYPE_CN,
_PICNAME_CN,
_STEP_CN,
cleanup_debug_captures,
count_debug_captures_files,
)
from .paths import get_debug_captures_base_dir
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",
"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:
@@ -116,6 +184,27 @@ def maybe_auto_cleanup(auto_cleanup: bool, mgr_log) -> None:
pass
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":
return
try:
debug_dir = get_debug_captures_dir()
if not os.path.isdir(debug_dir):
return
tokens = ("_px_", "像素检测")
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,
@@ -126,47 +215,46 @@ def build_debug_filename(
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
parts = []
if operation_type:
parts.append(sanitize_filename_part(_OPERATION_TYPE_CN.get(operation_type, operation_type)))
parts.append(sanitize_filename_part(_SHORT_OPERATION_CODES.get(operation_type, operation_type)))
if picname:
parts.append(sanitize_filename_part(_PICNAME_CN.get(picname, picname)))
parts.append(sanitize_filename_part(_SHORT_PIC_CODES.get(picname, picname)))
if step:
parts.append(sanitize_filename_part(_STEP_CN.get(step, step)))
parts.append(sanitize_filename_part(_SHORT_STEP_CODES.get(step, step)))
if coords:
parts.append(f"({coords[0]},{coords[1]})-({coords[2]},{coords[3]})")
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 extra_info.items():
key_cn = _EXTRA_INFO_KEY_CN.get(key, key)
clean_key = sanitize_filename_part(str(key_cn))
clean_value = "是" if isinstance(value, bool) and value else ("否" if isinstance(value, bool) else sanitize_filename_part(str(value)))
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) > 20:
clean_value = clean_value[:20]
elif len(clean_value) > 30:
clean_value = clean_value[:30]
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 = 180
max_len = 120
if len(filename) <= max_len:
return filename
base_parts = [timestamp]
if operation_type:
base_parts.append(sanitize_filename_part(_OPERATION_TYPE_CN.get(operation_type, operation_type)))
base_parts.append(sanitize_filename_part(_SHORT_OPERATION_CODES.get(operation_type, operation_type)))
if picname:
base_parts.append(sanitize_filename_part(_PICNAME_CN.get(picname, picname)))
base_parts.append(sanitize_filename_part(_SHORT_PIC_CODES.get(picname, picname)))
if step:
base_parts.append(sanitize_filename_part(_STEP_CN.get(step, 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(_EXTRA_INFO_KEY_CN.get(key, key)))
clean_key = sanitize_filename_part(str(_SHORT_EXTRA_KEYS.get(key, key)))
value = extra_info[key]
clean_value = "是" if isinstance(value, bool) and value else ("否" if isinstance(value, bool) else sanitize_filename_part(str(value)))
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}"
+48
View File
@@ -158,6 +158,54 @@ class TestPixelStage:
assert hasattr(stage_mod, "detect_attend_button_red_area")
assert hasattr(stage_mod, "detect_fansclub_join_red_area")
def test_read_pixel_stage_saves_single_overview_debug_image(self, tmp_path, monkeypatch):
from douyin.detection.pixel.stage import read_pixel_stage_state_from_screenshot
img_path = tmp_path / "screen.png"
Image.new("RGB", (1080, 2400), (20, 20, 20)).save(img_path)
debug_dir = tmp_path / "debug"
debug_dir.mkdir()
(debug_dir / "20260603_像素检测_抽奖结果_检测前.png").write_bytes(b"old")
(debug_dir / "20260603_px_attend_pre.png").write_bytes(b"old")
calls = []
def fake_save_debug_image(image, **kwargs):
calls.append(kwargs)
return str(debug_dir / "20260603_px_pxstage_ov_ok_0.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,
)
read_pixel_stage_state_from_screenshot(
str(img_path),
return_details=True,
analyser=SimpleNamespace(
fudai_detail_ui_mode="v2_0",
pixel_detect_coupon_popup_enabled=False,
pixel_detect_shopping_redpacket_enabled=False,
pixel_detect_fudai_detail_enabled=False,
),
)
assert len(calls) == 1
assert calls[0]["operation_type"] == "pixel_detect"
assert calls[0]["picname"] == "pixel_stage"
assert calls[0]["step"] == "overview"
assert calls[0]["annotate"] is False
assert not (debug_dir / "20260603_像素检测_抽奖结果_检测前.png").exists()
assert not (debug_dir / "20260603_px_attend_pre.png").exists()
class TestPixelCommon:
"""pixel/_common 模块测试。"""
@@ -96,6 +96,51 @@ class TestSaveImageModule:
assert callable(save_debug_image)
def test_build_debug_filename_uses_short_english_codes(self):
from douyin.handlers.screenshot_manager.save_image_helpers import build_debug_filename
filename = build_debug_filename(
"pixel_detect",
"lucky_draw_result",
"before_detect",
(290, 1300, 790, 1415),
{
"threshold": 0.8,
"region_size": "500x115",
"ui_version": "v2_0",
"pixel_style": "white",
"text_preview": "我知道了",
},
)
assert filename.endswith(".png")
assert len(filename) <= 120
assert "_px_lottery_pre_" in filename
assert "像素检测" not in filename
assert "抽奖结果" not in filename
assert "检测前" not in filename
def test_cleanup_single_operation_debug_images_keeps_only_pixel_latest(self, tmp_path, monkeypatch):
from douyin.handlers.screenshot_manager.save_image_helpers import (
cleanup_single_operation_debug_images,
)
(tmp_path / "20260603_像素检测_福袋图标_检测成功.png").write_bytes(b"old")
(tmp_path / "20260603_px_pxstage_ov_ok_1.png").write_bytes(b"old")
ocr_file = tmp_path / "20260603_ocr_fdcontent_postocr.png"
ocr_file.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("pixel_detect")
assert not (tmp_path / "20260603_像素检测_福袋图标_检测成功.png").exists()
assert not (tmp_path / "20260603_px_pxstage_ov_ok_1.png").exists()
assert ocr_file.exists()
class TestScreenshotManagerSubmodules:
"""screenshot_manager 子模块存在性测试。"""