refactor(stage): 拆出 douyin_stage 日志格式化辅助(1385→1284,-101 行)

diagnose_stage_from_current_screen 中并行检测后的详细日志记录块(108 行)
是纯日志格式化逻辑,依赖 pixel_state / pixel_details,不修改业务状态。
拆到 douyin_stage_helpers:
- _format_detail_log_fields:单 detail 字典 → 日志字段映射
- log_pixel_detection_details:遍历 pixel_details 写日志(含 has_fudai_detail
  的 task_count 矛盾告警)
- summarize_pixel_state:pixel_state 摘要写一行日志

新增 12 个单元测试覆盖纯函数行为,1038 → 1050 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-22 02:04:10 +08:00
1 parent 20e48d6a51
commit 189d24255d
3 files changed
+256 -107

No files matched your search

+6 -107
View File
@@ -14,6 +14,10 @@ from douyin.fudai.core.coords import (
STAGE_RED_PACKET_OCR,
COUPON_PARTICIPATE_BUTTON_ALT,
)
from douyin.stage.douyin_stage_helpers import (
log_pixel_detection_details,
summarize_pixel_state,
)
# 模块级 logger:原代码用 print 输出阶段诊断起始信息,统一走 logging。
_LOGGER = logging.getLogger("douyin.stage.douyin_stage")
@@ -208,114 +212,9 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
)
# 记录每个检测步骤的详细信息
for key, detail in pixel_details.items():
step_name_map = {
"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": "直播间图标(像素检测-多边形区域白色像素)",
}
step_name = step_name_map.get(key, key)
detected = detail.get("detected", False)
method = detail.get("method", "unknown")
log_pixel_detection_details(pixel_details, analyser, _log)
log_fields = {
"步骤": step_name,
"检测结果": "命中" if detected else "未命中",
"检测方法": method,
}
# 添加耗时信息
if "elapsed_ms" in detail:
log_fields["耗时(ms)"] = detail["elapsed_ms"]
# 添加分数信息
if "template_score" in detail and detail["template_score"] is not None:
log_fields["分数"] = round(detail["template_score"], 4)
log_fields["模板匹配分数"] = round(detail["template_score"], 4)
# 对于像素检测,添加置信度信息
if "confidence" in detail and detail["confidence"] is not None:
if "分数" not in log_fields:
log_fields["分数"] = round(detail["confidence"], 4)
log_fields["置信度"] = round(detail["confidence"], 4)
# 如果是三部分识别,显示平均分和区域结果
if "avg_score" in detail and detail["avg_score"] is not None:
log_fields["平均分"] = round(detail["avg_score"], 4)
if "detected_parts" in detail and detail["detected_parts"]:
log_fields["匹配部分"] = ",".join(detail["detected_parts"])
if "best_region" in detail and detail["best_region"]:
log_fields["最佳区域"] = detail["best_region"]
if "region_results" in detail and detail["region_results"]:
region_scores = detail["region_results"]
if isinstance(region_scores, dict):
log_fields["区域分数"] = (
f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}"
)
# 对于像素检测,red_ratio也作为分数显示
if "red_ratio" in detail and detail["red_ratio"] is not None:
log_fields["红色比例"] = round(detail["red_ratio"], 4)
# 如果还没有分数,将red_ratio作为分数显示
if "分数" not in log_fields:
log_fields["分数"] = round(detail["red_ratio"], 4)
# 显示阈值(无论是否为None都显示,方便调试)
if "effective_threshold" in detail:
threshold_val = detail["effective_threshold"]
if threshold_val is not None:
log_fields["阈值"] = round(threshold_val, 4)
else:
log_fields["阈值"] = "未设置"
# 对于福袋详情页,额外显示配置的阈值(用于调试)
if key == "has_fudai_detail":
# 显示任务数量信息(无论是否为None都显示,便于调试)
if "task_count" in detail:
task_count_val = detail["task_count"]
log_fields["任务数量"] = task_count_val
# 如果任务数量存在但检测结果为False,记录警告
if (
task_count_val is not None
and task_count_val > 0
and not detected
):
try:
_log( # type: ignore[misc]
"警告:检测到任务数量但 has_fudai_detail 为 False",
任务数量=task_count_val,
detected=detected,
)
except Exception:
pass
else:
log_fields["任务数量"] = "未获取"
try:
configured_threshold = float(
getattr(analyser, "fudai_detail_template_threshold", None)
or getattr(analyser, "fudai_template_match_threshold", 0.7)
or 0.7
)
log_fields["配置阈值"] = round(configured_threshold, 4)
except Exception:
pass
if "reason" in detail:
log_fields["原因"] = detail["reason"]
if "error" in detail:
log_fields["错误"] = detail["error"]
_log(f"并行检测-{step_name}", **log_fields)
_log(
"像素状态(并行检测完成)",
耗时毫秒=pixel_detection_elapsed,
直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)),
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
福袋详情页=bool(pixel_state.get("has_fudai_detail", False)),
)
summarize_pixel_state(pixel_state, pixel_detection_elapsed, _log)
except Exception as e:
import traceback
+145
View File
@@ -0,0 +1,145 @@
"""douyin_stage.py 内部用到的辅助函数。
把 diagnose_stage_from_current_screen 中纯日志格式化、纯映射查询的子块抽出来:
- log_pixel_detection_details:把 pixel_details 里每个 key 的检测详情格式化并写入日志
- summarize_pixel_state:把 pixel_state 摘要写入日志(一次调用替代 9 行字段构造)
"""
from __future__ import annotations
from typing import Any, Callable, Dict
_STEP_NAME_MAP: Dict[str, str] = {
"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": "直播间图标(像素检测-多边形区域白色像素)",
}
def _format_detail_log_fields(key: str, detail: Dict[str, Any], analyser: Any) -> Dict[str, Any]:
"""把单个 detail 字典格式化成日志字段。"""
step_name = _STEP_NAME_MAP.get(key, key)
detected = detail.get("detected", False)
method = detail.get("method", "unknown")
log_fields: Dict[str, Any] = {
"步骤": step_name,
"检测结果": "命中" if detected else "未命中",
"检测方法": method,
}
if "elapsed_ms" in detail:
log_fields["耗时(ms)"] = detail["elapsed_ms"]
if "template_score" in detail and detail["template_score"] is not None:
log_fields["分数"] = round(detail["template_score"], 4)
log_fields["模板匹配分数"] = round(detail["template_score"], 4)
if "confidence" in detail and detail["confidence"] is not None:
if "分数" not in log_fields:
log_fields["分数"] = round(detail["confidence"], 4)
log_fields["置信度"] = round(detail["confidence"], 4)
if "avg_score" in detail and detail["avg_score"] is not None:
log_fields["平均分"] = round(detail["avg_score"], 4)
if "detected_parts" in detail and detail["detected_parts"]:
log_fields["匹配部分"] = ",".join(detail["detected_parts"])
if "best_region" in detail and detail["best_region"]:
log_fields["最佳区域"] = detail["best_region"]
if "region_results" in detail and detail["region_results"]:
region_scores = detail["region_results"]
if isinstance(region_scores, dict):
log_fields["区域分数"] = (
f"上:{region_scores.get('上部分', 0):.3f} 中:{region_scores.get('中部分', 0):.3f} 下:{region_scores.get('下部分', 0):.3f}"
)
if "red_ratio" in detail and detail["red_ratio"] is not None:
log_fields["红色比例"] = round(detail["red_ratio"], 4)
if "分数" not in log_fields:
log_fields["分数"] = round(detail["red_ratio"], 4)
if "effective_threshold" in detail:
threshold_val = detail["effective_threshold"]
if threshold_val is not None:
log_fields["阈值"] = round(threshold_val, 4)
else:
log_fields["阈值"] = "未设置"
if key == "has_fudai_detail":
if "task_count" in detail:
log_fields["任务数量"] = detail["task_count"]
else:
log_fields["任务数量"] = "未获取"
try:
configured_threshold = float(
getattr(analyser, "fudai_detail_template_threshold", None)
or getattr(analyser, "fudai_template_match_threshold", 0.7)
or 0.7
)
log_fields["配置阈值"] = round(configured_threshold, 4)
except Exception:
pass
if "reason" in detail:
log_fields["原因"] = detail["reason"]
if "error" in detail:
log_fields["错误"] = detail["error"]
return log_fields
def log_pixel_detection_details(
pixel_details: Dict[str, Dict[str, Any]],
analyser: Any,
log_callback: Callable[..., None],
) -> None:
"""记录并行像素检测每个步骤的详细日志。"""
for key, detail in (pixel_details or {}).items():
log_fields = _format_detail_log_fields(key, detail, analyser)
# has_fudai_detail 单独保留任务数量与 detected 矛盾的告警分支
if key == "has_fudai_detail":
task_count_val = detail.get("task_count")
detected = detail.get("detected", False)
if (
task_count_val is not None
and task_count_val > 0
and not detected
):
try:
log_callback(
"警告:检测到任务数量但 has_fudai_detail 为 False",
任务数量=task_count_val,
detected=detected,
)
except Exception:
pass
step_name = _STEP_NAME_MAP.get(key, key)
try:
log_callback(f"并行检测-{step_name}", **log_fields)
except Exception:
pass
def summarize_pixel_state(
pixel_state: Dict[str, Any],
pixel_detection_elapsed_ms: float,
log_callback: Callable[..., None],
) -> None:
"""把 pixel_state 摘要写到日志,方便排查命中/未命中分布。"""
try:
log_callback(
"像素状态(并行检测完成)",
耗时毫秒=pixel_detection_elapsed_ms,
直播间图标像素检测=bool(pixel_state.get("has_live_room_pixel", False)),
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
福袋详情页=bool(pixel_state.get("has_fudai_detail", False)),
)
except Exception:
pass
+105
View File
@@ -0,0 +1,105 @@
"""单元测试:douyin/stage/douyin_stage_helpers.py
只测纯日志格式化函数 _format_detail_log_fields 的输入→输出映射。
更上层的 log_pixel_detection_details / summarize_pixel_state 用 callback
桩做行为验证。
"""
from __future__ import annotations
from unittest.mock import MagicMock
from douyin.stage import douyin_stage_helpers as h
def test_format_basic_detail():
detail = {"detected": True, "method": "pixel"}
fields = h._format_detail_log_fields("has_coupon_bg", detail, MagicMock())
assert fields["步骤"] == "优惠券背景"
assert fields["检测结果"] == "命中"
assert fields["检测方法"] == "pixel"
def test_format_unknown_key_falls_back_to_key():
detail = {"detected": False, "method": "x"}
fields = h._format_detail_log_fields("unknown_key", detail, MagicMock())
assert fields["步骤"] == "unknown_key"
assert fields["检测结果"] == "未命中"
def test_format_with_template_score():
detail = {"detected": True, "method": "tpl", "template_score": 0.876543}
fields = h._format_detail_log_fields("has_lucky_draw_result", detail, MagicMock())
assert fields["分数"] == 0.8765
assert fields["模板匹配分数"] == 0.8765
def test_format_with_confidence_only():
detail = {"detected": True, "method": "px", "confidence": 0.5}
fields = h._format_detail_log_fields("has_live_room_pixel", detail, MagicMock())
assert fields["置信度"] == 0.5
assert fields["分数"] == 0.5
def test_format_threshold_none_shows_text():
detail = {"detected": False, "method": "x", "effective_threshold": None}
fields = h._format_detail_log_fields("has_redpacket_bg", detail, MagicMock())
assert fields["阈值"] == "未设置"
def test_format_fudai_detail_with_task_count():
analyser = MagicMock()
analyser.fudai_detail_template_threshold = 0.6
analyser.fudai_template_match_threshold = 0.7
detail = {"detected": True, "method": "tpl", "task_count": 3}
fields = h._format_detail_log_fields("has_fudai_detail", detail, analyser)
assert fields["任务数量"] == 3
assert fields["配置阈值"] == 0.6
def test_format_fudai_detail_missing_task_count():
detail = {"detected": False, "method": "tpl"}
fields = h._format_detail_log_fields("has_fudai_detail", detail, MagicMock())
assert fields["任务数量"] == "未获取"
def test_log_pixel_detection_details_iterates_all_keys():
log = MagicMock()
pixel_details = {
"has_coupon_bg": {"detected": True, "method": "px"},
"has_redpacket_bg": {"detected": False, "method": "px"},
}
h.log_pixel_detection_details(pixel_details, MagicMock(), log)
assert log.call_count == 2 # 一个 key 一次
def test_log_pixel_detection_details_warns_on_task_count_mismatch():
"""has_fudai_detail 检测为 False 但 task_count > 0 时应额外告警"""
log = MagicMock()
pixel_details = {
"has_fudai_detail": {"detected": False, "method": "tpl", "task_count": 5},
}
h.log_pixel_detection_details(pixel_details, MagicMock(), log)
# 一次告警 + 一次普通日志 = 2 次
assert log.call_count == 2
def test_log_pixel_detection_details_handles_empty():
log = MagicMock()
h.log_pixel_detection_details({}, MagicMock(), log)
assert log.call_count == 0
def test_summarize_pixel_state_writes_one_log_line():
log = MagicMock()
h.summarize_pixel_state({"has_live_room_pixel": True}, 12.3, log)
assert log.call_count == 1
args, kwargs = log.call_args
assert args[0] == "像素状态(并行检测完成)"
assert kwargs["直播间图标像素检测"] is True
def test_summarize_pixel_state_swallows_exceptions():
"""log_callback 抛错也不应传播"""
bad_log = MagicMock(side_effect=RuntimeError("boom"))
h.summarize_pixel_state({}, 0.0, bad_log)