refactor(stage): 抽 diagnose_stage_from_current_screen 步骤0"并行像素检测+详情日志"块到独立模块

将 204 行的"并行像素检测 + 详情日志记录"块抽到 douyin_stage_step0.py:run_parallel_pixel_detection。
逻辑:
- 调用 _read_pixel_stage_state 并行采集所有像素特征
- 检查直播间图标像素(白色比例 >= 阈值则判定在直播间)
- 兜底:检测到抽奖结果弹窗也视为在直播间
- 记录每个检测项的详细信息(耗时、分数、阈值、任务数量等)
- 写整体并行检测完成日志

返回 (pixel_state, pixel_details, in_live_room, live_room_score, detection_method) 五元组。

douyin_stage.py: 462 → 273 行 (-189)
新增 douyin_stage_step0.py: 231 行

douyin_stage.py 跌破 300 行(1385 → 273,本会话累计削减 1112 行 = -80%)

验证:
- pytest 1013 passed
- compile OK

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 14:01:28 +08:00
1 parent 1801e50a4c
commit 2594788a8c
2 files changed
+243 -201

No files matched your search

+12 -201
View File
@@ -128,209 +128,20 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
if pixel_threshold > 1.0:
pixel_threshold = 1.0
# ========== 第一步:基于同一张截图并行采集所有像素特征(包括直播间图标检测)==========
# 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行
# 包括:直播间图标像素检测(多边形区域白色像素检测)以及其他所有阶段检测
pixel_state = {}
pixel_details = {}
pixel_detection_start = time.time()
try:
result = analyser._read_pixel_stage_state(return_details=True)
if isinstance(result, tuple):
pixel_state, pixel_details = result
else:
pixel_state = result
pixel_details = {}
# 步骤0第一步:并行像素检测 + 详情日志记录
from douyin.stage.douyin_stage_step0 import run_parallel_pixel_detection
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
# 从并行检测结果中获取直播间图标检测结果
# 只使用像素检测(多边形区域白色像素检测),白色比例 >= 阈值则判定为在直播间
live_room_pixel_detected = bool(pixel_state.get("has_live_room_pixel", False))
# 获取检测分数(白色像素比例)
pixel_confidence = 0.0
if "has_live_room_pixel" in pixel_details:
pixel_confidence = float(
pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0
)
# 如果像素检测通过(白色比例 >= 阈值),判定为在直播间
if live_room_pixel_detected:
in_live_room = True
detection_method = "像素检测(多边形区域白色像素)"
live_room_score = pixel_confidence # 白色像素比例即为置信度
_log(
"步骤0[检测直播间]-命中(像素检测,多边形区域白色像素)",
白色像素比例=round(pixel_confidence, 3),
阈值=pixel_threshold,
)
else:
# 像素检测未通过(直播间图标未命中)
in_live_room = False
detection_method = "像素检测未命中"
_log(
"步骤0[检测直播间]-像素检测未命中",
白色像素比例=round(pixel_confidence, 3),
阈值=pixel_threshold,
)
# 简单策略:若检测到抽奖结果弹窗,也可视为在直播间(减少漏报)
try:
if pixel_state.get("has_lucky_draw_result", False):
# 如果并行检测里抽奖弹窗命中,则视为在直播间
in_live_room = True
detection_method = "抽奖结果弹窗(像素检测)"
# 尽量使用该项的置信度作为分数(回退为0.0)
try:
live_room_score = float(
pixel_details.get("has_lucky_draw_result", {}).get(
"confidence", 0.0
)
or 0.0
)
except Exception:
live_room_score = 0.0
_log(
"步骤0[检测直播间]-命中(抽奖结果弹窗作为证据)",
抽奖弹窗置信度=round(live_room_score, 4),
)
except Exception:
# 此处为容错:若 pixel_state/pixel_details 格式异常,继续保持未命中
pass
if in_live_room:
total_elapsed = (time.time() - step_start) * 1000
_log(
"步骤0[检测直播间]-最终结果:在直播间",
检测方法=detection_method,
分数=live_room_score,
总耗时毫秒=total_elapsed,
)
# 记录每个检测步骤的详细信息
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_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)),
pixel_state, pixel_details, in_live_room, live_room_score, detection_method = (
run_parallel_pixel_detection(
analyser,
in_live_room,
live_room_score,
detection_method,
pixel_threshold,
step_start,
_log,
)
except Exception as e:
import traceback
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
_log(
"并行检测异常",
耗时毫秒=pixel_detection_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
pixel_state = {}
pixel_details = {}
# 步骤0结束计时
step0_elapsed = (time.time() - step_start) * 1000
)
_log("步骤0[并行检测]-完成", 总耗时毫秒=step0_elapsed)
# ========== 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)==========
+231
View File
@@ -0,0 +1,231 @@
"""阶段诊断辅助:步骤 0 第一步(并行像素检测 + 详情日志记录)
从 douyin/stage/douyin_stage.py:diagnose_stage_from_current_screen 中提取。
基于一张截图并行采集所有像素特征(直播间图标、福袋详情页、抽奖结果、
优惠券背景等),然后逐项记录详情日志。
"""
from __future__ import annotations
import time
from typing import Tuple
def run_parallel_pixel_detection(
analyser,
in_live_room: bool,
live_room_score: float,
detection_method: str,
pixel_threshold: float,
step_start: float,
log_fn,
) -> Tuple[dict, dict, bool, float, str]:
"""步骤 0 第一步:并行像素检测 + 详情日志记录。
返回 (pixel_state, pixel_details, in_live_room, live_room_score, detection_method) 五元组。
"""
# ========== 第一步:基于同一张截图并行采集所有像素特征(包括直播间图标检测)==========
# 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行
# 包括:直播间图标像素检测(多边形区域白色像素检测)以及其他所有阶段检测
pixel_state = {}
pixel_details = {}
pixel_detection_start = time.time()
try:
result = analyser._read_pixel_stage_state(return_details=True)
if isinstance(result, tuple):
pixel_state, pixel_details = result
else:
pixel_state = result
pixel_details = {}
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
# 从并行检测结果中获取直播间图标检测结果
# 只使用像素检测(多边形区域白色像素检测),白色比例 >= 阈值则判定为在直播间
live_room_pixel_detected = bool(pixel_state.get("has_live_room_pixel", False))
# 获取检测分数(白色像素比例)
pixel_confidence = 0.0
if "has_live_room_pixel" in pixel_details:
pixel_confidence = float(
pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0
)
# 如果像素检测通过(白色比例 >= 阈值),判定为在直播间
if live_room_pixel_detected:
in_live_room = True
detection_method = "像素检测(多边形区域白色像素)"
live_room_score = pixel_confidence # 白色像素比例即为置信度
log_fn(
"步骤0[检测直播间]-命中(像素检测,多边形区域白色像素)",
白色像素比例=round(pixel_confidence, 3),
阈值=pixel_threshold,
)
else:
# 像素检测未通过(直播间图标未命中)
in_live_room = False
detection_method = "像素检测未命中"
log_fn(
"步骤0[检测直播间]-像素检测未命中",
白色像素比例=round(pixel_confidence, 3),
阈值=pixel_threshold,
)
# 简单策略:若检测到抽奖结果弹窗,也可视为在直播间(减少漏报)
try:
if pixel_state.get("has_lucky_draw_result", False):
# 如果并行检测里抽奖弹窗命中,则视为在直播间
in_live_room = True
detection_method = "抽奖结果弹窗(像素检测)"
# 尽量使用该项的置信度作为分数(回退为0.0)
try:
live_room_score = float(
pixel_details.get("has_lucky_draw_result", {}).get(
"confidence", 0.0
)
or 0.0
)
except Exception:
live_room_score = 0.0
log_fn(
"步骤0[检测直播间]-命中(抽奖结果弹窗作为证据)",
抽奖弹窗置信度=round(live_room_score, 4),
)
except Exception:
# 此处为容错:若 pixel_state/pixel_details 格式异常,继续保持未命中
pass
if in_live_room:
total_elapsed = (time.time() - step_start) * 1000
log_fn(
"步骤0[检测直播间]-最终结果:在直播间",
检测方法=detection_method,
分数=live_room_score,
总耗时毫秒=total_elapsed,
)
# 记录每个检测步骤的详细信息
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_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_fn( # 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_fn(f"并行检测-{step_name}", **log_fields)
log_fn(
"像素状态(并行检测完成)",
耗时毫秒=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)),
)
except Exception as e:
import traceback
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
log_fn(
"并行检测异常",
耗时毫秒=pixel_detection_elapsed,
异常类型=type(e).__name__,
异常信息=str(e),
)
pixel_state = {}
pixel_details = {}
# 步骤0结束计时
step0_elapsed = (time.time() - step_start) * 1000
log_fn("步骤0[并行检测]-完成", 总耗时毫秒=step0_elapsed)
return pixel_state, pixel_details, in_live_room, live_room_score, detection_method