Add shopping red packet detection tests and sample image

- Implemented a test script for shopping red packet detection using pixel analysis and OCR.
- Created a sample image to simulate a shopping red packet for testing purposes.
- Added functions to test pixel detection, coordinate definitions, and OCR keyword matching.
- Included detailed print statements for test results and summaries.
This commit is contained in:
Your Name committed 2026-01-08 20:37:49 +08:00
1 parent b3011dd9ce
commit fb0c07c91a
30 files changed
+1269 -319

No files matched your search

+5 -20
View File
@@ -657,9 +657,8 @@ class underlying_operations:
dur = (time_module.time() - start_ts) * 1000.0
logging.info(
"[截图] 总耗时(ms)=%.1f device=%s use_service=%s result=%s",
"[截图] 总耗时(ms)=%.1f use_service=%s result=%s",
dur,
device_id,
bool(use_service),
final_result,
)
@@ -842,9 +841,8 @@ class underlying_operations:
adb_subprocess_dur = (time_module.time() - adb_start) * 1000.0
logging.info(
"[截图] ADB exec-out subprocess耗时(ms)=%.1f device=%s attempt=%d",
"[截图] ADB exec-out subprocess耗时(ms)=%.1f attempt=%d",
adb_subprocess_dur,
device_id,
attempt + 1,
)
@@ -912,22 +910,10 @@ class underlying_operations:
overall_dur = (
time_module.time() - overall_start
) * 1000.0
# 记录分阶段耗时汇总,便于排查瓶颈(JSON-like)
# 记录总耗时
logging.info(
"[截图汇总] device=%s total_ms=%.1f cleanup_ms=%.1f adb_execout_ms=%.1f validate_tmp_ms=%.1f replace_ms=%.1f mirror_ms=%.1f validate_out_ms=%.1f",
device_id,
"[截图] _get_screenshot_direct总耗时(ms)=%.1f (exec-out成功)",
overall_dur,
cleanup_dur,
adb_subprocess_dur,
validate_tmp_dur,
replace_dur,
mirror_dur,
validate_out_dur,
)
logging.info(
"[截图] _get_screenshot_direct总耗时(ms)=%.1f device=%s (exec-out成功)",
overall_dur,
device_id,
)
print(
f"[{timetag}] [截图] ✓ 获取屏幕截图成功"
@@ -1064,9 +1050,8 @@ class underlying_operations:
time_module.time() - fallback_start
) * 1000.0
logging.info(
"[截图] _get_screenshot_direct总耗时(ms)=%.1f device=%s (回退方案成功, 回退部分耗时=%.1fms)",
"[截图] _get_screenshot_direct总耗时(ms)=%.1f (回退方案成功, 回退部分耗时=%.1fms)",
overall_dur,
device_id,
fallback_total_dur,
)
print("{} 获取屏幕截图".format(timetag))
+13 -8
View File
@@ -5,20 +5,20 @@
"min_prize_value_yuan": 250.0,
"min_participants": 0,
"max_participants": 0,
"skip_if_countdown_gt_seconds": 180,
"skip_if_countdown_gt_seconds": 120,
"reset_after_swipes_enabled": true,
"reset_after_swipes": 30,
"reset_after_swipes": 10,
"reset_after_swipes_action": "back",
"auto_join_fansclub": true,
"fansclub_fail_action": "switch",
"high_value_fudai_enabled": true,
"high_value_fudai_threshold_yuan": 500.0,
"high_value_fudai_join_ahead_seconds": 120,
"high_value_fudai_join_ahead_seconds": 100,
"high_value_fudai_max_swipe_back": 50,
"high_value_fudai_max_reservations": 9999,
"high_value_fudai_after_action": "continue",
"high_value_room_revisit_enabled": true,
"high_value_room_revisit_only_current_run": true,
"high_value_room_revisit_enabled": false,
"high_value_room_revisit_only_current_run": false,
"reservation_back_verify_enabled": true,
"reservation_back_swipe_delay": 0.1,
"desktop_icon_x": 153,
@@ -31,7 +31,7 @@
"fudai_icon_max_wait_seconds": 6.0,
"fudai_icon_retry_delay_seconds": 0.1,
"fudai_exit_after_misses": 10,
"enable_back_on_misses": false,
"enable_back_on_misses": true,
"fudai_click_wait_seconds": 1.6,
"fudai_detail_initial_wait_seconds": 0.8,
"fudai_detail_verified_wait_seconds": 0.2,
@@ -200,7 +200,7 @@
"log_on_complete": false
},
"fudai_detail_template_threshold": 0.52,
"switch_room_wait_after_stage_diag_seconds": 5.0,
"switch_room_wait_after_stage_diag_seconds": 5.5,
"coupon_template_match_threshold": 0.35,
"attend_button_red_ratio_threshold": 0.25,
"fansclub_join_red_ratio_threshold": 0.25,
@@ -214,5 +214,10 @@
"fansclub_manual_wait_seconds": 3.0,
"enable_streaming_screenshot": false,
"yanghao_only": false,
"record_room_title_mapping_enabled": true
"record_room_title_mapping_enabled": true,
"high_value_fudai_poll_before_seconds": 10.0,
"high_value_room_revisit_min_interval_seconds": 300,
"high_value_room_revisit_max_per_run": 9999,
"high_value_room_revisit_min_prize_value": 1000.0,
"high_value_room_revisit_max_age_days": 1
}
+5 -3
View File
@@ -85,17 +85,19 @@ def find_and_open_fudai_detail(
# 在调用检测函数之前,检查是否还有足够的时间
elapsed = time.time() - start_time
remaining = max_wait_seconds - elapsed
# 如果剩余时间不足 1 秒,停止继续检测(避免子函数超时)
if remaining < 1.0:
break
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
if not x:
# 再次检查时间,防止第二次调用导致超时
elapsed = time.time() - start_time
if (elapsed + 2.0) < max_wait_seconds: # 预留 2 秒给第二次调用
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False)
x = check_have_fudai_with_ready_screenshot(
analyser, screenshot_ready=False
)
if x:
try:
analyser._log_kv(
+69 -23
View File
@@ -195,10 +195,16 @@ class fudai_analyse:
# 完成某个预约福袋后的动作:stay=停留当前直播间;continue=继续执行抢福袋
self.high_value_fudai_after_action: str = "continue"
self.high_value_fudai_after_stay_seconds: int = 120
# 开奖前轮询时间(秒,默认10.0)
self.high_value_fudai_poll_before_seconds: float = 10.0
# 高价值直播间"回访"相关(当前仅保留配置,不在本地版强制启用复杂逻辑)
self.high_value_room_revisit_enabled: bool = False
self.high_value_room_revisit_only_current_run: bool = False
self.high_value_room_revisit_min_interval_seconds: int = 300
self.high_value_room_revisit_max_per_run: int = 5
self.high_value_room_revisit_min_prize_value: float = 0.0
self.high_value_room_revisit_max_age_days: int = 30
# 粉丝团相关配置
self.auto_join_fansclub: bool = False # 是否自动加入粉丝团
@@ -288,21 +294,27 @@ class fudai_analyse:
self._room_pos_to_title_map: dict[int, tuple[str, str]] = {}
# 已记录统计的福袋跟踪(避免同一个直播间同一个福袋重复记录统计)
self._recorded_fudai_stats: set[tuple[str, str]] = set() # (room_title, fudai_content)
self._recorded_fudai_stats: set[tuple[str, str]] = (
set()
) # (room_title, fudai_content)
# 运行时状态标志(避免在外部定义属性的警告)
self.needswitch: bool | None = (
None # 是否允许切换直播间,将从配置文件加载,默认 True
)
self._waiting_for_lottery_result: bool = False # 是否正在等待开奖结果
self._current_attending_reservation_fudai: bool = False # 当前正在参与的是否为预约福袋
self._current_attending_reservation_fudai: bool = (
False # 当前正在参与的是否为预约福袋
)
self._skip_stage_diagnosis_and_find_fudai: bool = False # 跳过阶段诊断标志
self._just_switched_room: bool = False # 是否刚刚切换了直播间
# 高价值房间重访相关状态
self._last_high_value_revisit_ts: float = 0.0 # 最后一次重访时间戳
self._last_high_value_revisit_ts: float = time.time() # 最后一次重访时间戳,初始化为当前时间避免启动后立即重访
self._current_run_revisit_count: int = 0 # 本次运行的重访次数
self._current_run_high_value_rooms: list[dict[str, Any]] = [] # 本次运行发现的高价值房间
self._current_run_high_value_rooms: list[dict[str, Any]] = (
[]
) # 本次运行发现的高价值房间
self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = (
None # 上次读取的福袋详情
)
@@ -717,7 +729,9 @@ class fudai_analyse:
"""保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试与回放使用。"""
douyin_screenshot_handler.ScreenshotHandler.save_step_screenshot(self, label)
def _capture_roi_screenshot(self, label: str, sx: int, sy: int, size: int, screenshot_path: str = None) -> str:
def _capture_roi_screenshot(
self, label: str, sx: int, sy: int, size: int, screenshot_path: str = None
) -> str:
"""捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。
返回 ROI 图片路径(绝对路径),失败返回空字符串。
@@ -1091,12 +1105,22 @@ class fudai_analyse:
try:
screenshot_start = time.time()
self.operation.get_screenshot(self.device_id)
self._log_kv("截图", "等待开奖期间截图", elapsed_seconds=round(time.time() - screenshot_start, 2))
self._log_kv(
"截图",
"等待开奖期间截图",
elapsed_seconds=round(
time.time() - screenshot_start, 2
),
)
except Exception:
pass
ocr_start = time.time()
result = self._check_lottery_result_by_ocr()
self._log_kv("OCR", "等待开奖期间OCR检测", elapsed_seconds=round(time.time() - ocr_start, 2))
self._log_kv(
"OCR",
"等待开奖期间OCR检测",
elapsed_seconds=round(time.time() - ocr_start, 2),
)
except Exception as e:
result = None
try:
@@ -1116,7 +1140,9 @@ class fudai_analyse:
"参与",
"等待期间检测到开奖结果,开始处理",
attempt=attempt,
等待开奖总耗时=round(time.time() - wait_lottery_start, 2),
等待开奖总耗时=round(
time.time() - wait_lottery_start, 2
),
)
except Exception:
pass
@@ -1578,7 +1604,7 @@ class fudai_analyse:
def _seek_reservation_room(item: dict) -> bool:
try:
return bool(self._seek_reservation_room(item))
return bool(self._seek_reservation_room(item, operation_type="预约"))
except Exception:
return False
@@ -1632,6 +1658,18 @@ class fudai_analyse:
pass
# 跳过预约回退检查,让流程继续执行到阶段诊断后检查开奖结果
# 不在这里 return,让流程继续
# 如果正在参与预约福袋,跳过预约回退检查,避免被其他预约打断
elif getattr(self, "_current_attending_reservation_fudai", False):
try:
self._log_kv(
"预约",
"[预约] 正在参与预约福袋,跳过预约回退检查,避免被其他预约打断",
current_attending_reservation=True,
)
except Exception:
pass
# 跳过预约回退检查,让当前参与流程继续完成
# 不在这里 return,让流程继续
# 如果已经在队列满等待状态,且设置了直接参与标志,立即执行参与,不再循环检查
elif self.queue_full_waiting_at_earliest:
# 队列已满且正在等待最早开奖直播间,按正常等待逻辑处理(不使用已删除的直接参与标志)
@@ -1993,8 +2031,12 @@ class fudai_analyse:
# 2.0. 高价值房间重访检查(在处理其他状态之前)
try:
revisit_enabled = bool(getattr(self, "high_value_room_revisit_enabled", False))
only_current_run = bool(getattr(self, "high_value_room_revisit_only_current_run", False))
revisit_enabled = bool(
getattr(self, "high_value_room_revisit_enabled", False)
)
only_current_run = bool(
getattr(self, "high_value_room_revisit_only_current_run", False)
)
if revisit_enabled:
from douyin.other import douyin_high_value_room
@@ -2003,14 +2045,18 @@ class fudai_analyse:
should_revisit = douyin_high_value_room.should_trigger_revisit(
analyser=self,
revisit_enabled=revisit_enabled,
only_current_run=only_current_run
only_current_run=only_current_run,
min_interval_seconds=getattr(self, "high_value_room_revisit_min_interval_seconds", 300),
max_revisit_per_run=getattr(self, "high_value_room_revisit_max_per_run", 5),
)
if should_revisit:
# 获取重访候选房间
candidates = douyin_high_value_room.get_revisit_candidates(
analyser=self,
only_current_run=only_current_run
only_current_run=only_current_run,
min_prize_value=getattr(self, "high_value_room_revisit_min_prize_value", 0.0),
max_age_days=getattr(self, "high_value_room_revisit_max_age_days", 30),
)
if candidates:
@@ -2020,13 +2066,12 @@ class fudai_analyse:
"[重访] 触发高价值房间重访",
target_room_title=target_room.get("room_title", "")[:30],
max_prize_value=target_room.get("max_prize_value_yuan", 0),
candidates_count=len(candidates)
candidates_count=len(candidates),
)
# 执行重访
revisit_success = douyin_high_value_room.execute_room_revisit(
analyser=self,
target_room=target_room
analyser=self, target_room=target_room
)
if revisit_success:
@@ -2041,8 +2086,7 @@ class fudai_analyse:
else:
# 重访失败,继续正常流程
self._log_kv(
"高价值房间",
"[重访] 高价值房间重访失败,继续正常流程"
"高价值房间", "[重访] 高价值房间重访失败,继续正常流程"
)
except Exception as exc:
try:
@@ -2478,7 +2522,7 @@ class fudai_analyse:
"""
return douyin_swipe_handler.SwipeHandler.maybe_reset_after_swipes(self)
def _seek_reservation_room(self, item: dict[str, Any]) -> bool:
def _seek_reservation_room(self, item: dict[str, Any], operation_type: str = "预约") -> bool:
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
说明:
@@ -2486,7 +2530,7 @@ class fudai_analyse:
- 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。
"""
return douyin_reservation_handler.ReservationHandler.seek_reservation_room(
self, item
self, item, operation_type=operation_type
)
# ========== 福袋相关 ==========
@@ -2577,7 +2621,9 @@ class fudai_analyse:
if future_ts > 0:
# 设置当前福袋的 future_ts 和 content,供 attend_choujiang 使用
self._current_fudai_future_ts = future_ts
self._current_fudai_content = detail[0] if len(detail) > 0 else ""
self._current_fudai_content = (
detail[0] if len(detail) > 0 else ""
)
self._log_kv(
"参与",
"第二次打开:使用第一次的倒计时信息",
@@ -2796,7 +2842,7 @@ class fudai_analyse:
# 注意:basic_join_decision 内部已经关闭详情并切换直播间,不需要再次关闭
try:
douyin_fudai_core.basic_join_decision(
self, detail
self, detail, skip_result=(skip, skip_reason)
)
except Exception as e:
try:
@@ -3231,7 +3277,7 @@ class fudai_analyse:
elapsed_seconds=round(elapsed, 2),
)
return
join_result = douyin_fudai_core.basic_join_decision(self, detail)
join_result = douyin_fudai_core.basic_join_decision(self, detail, skip_result=(False, "already_checked_in_step3"))
# 检查是否参与成功:如果 _last_successful_attend_ts 刚刚更新,说明参与成功
attend_after_ts = getattr(self, "_last_successful_attend_ts", 0.0) or 0.0
@@ -44,5 +44,5 @@ class RoomUtilsMixin:
"""
from douyin.reservation import douyin_reservation_handler
return douyin_reservation_handler.ReservationHandler.seek_reservation_room(
self, item
self, item, operation_type="预约"
)
+3 -1
View File
@@ -346,7 +346,9 @@ def check_have_fudai_with_ready_screenshot(
max_consecutive_failures = 5 # 最大连续失败次数
# 额外的时间限制保护,防止死循环
absolute_timeout = func_start + max(max_wait_s * 1.5, 15) # 最长15秒,但不超过 max_wait_s * 1.5
absolute_timeout = func_start + max(
max_wait_s * 1.5, 15
) # 最长15秒,但不超过 max_wait_s * 1.5
while (time.time() - func_start) < max_wait_s and time.time() < absolute_timeout:
# 额外的循环次数保护:防止无限循环
+61 -3
View File
@@ -172,9 +172,67 @@ def detect_coupon_popup_background(
return False
def detect_redpacket_popup_background(_pic_rgb: Image.Image) -> bool:
"""中央购物红包弹窗检测(暂时禁用,始终返回 False)。"""
return False
def detect_redpacket_popup_background(pic_rgb: Image.Image) -> bool:
"""中央购物红包弹窗检测:检测中央大红包区域的红色占比。
购物红包特征:
- 中央大型红色弹窗
- 包含黄色圆形"抢"按钮
- 主要颜色为红色(RGB约 255, 100-150, 100-150)
检测区域(基准1080x2400):大约中央区域
- 左上:(300, 400)
- 右下:(780, 1200)
"""
try:
import numpy as np # type: ignore[import-untyped]
width, height = pic_rgb.size
scale_x = width / 1080.0
scale_y = height / 2400.0
# 购物红包通常出现在屏幕中央
# 基准坐标(1080x2400)
x1 = int(200 * scale_x)
y1 = int(300 * scale_y)
x2 = int(880 * scale_x)
y2 = int(1400 * scale_y)
# 边界检查
x1 = max(0, min(x1, width))
x2 = max(0, min(x2, width))
y1 = max(0, min(y1, height))
y2 = max(0, min(y2, height))
if x1 >= x2 or y1 >= y2:
return False
# 裁剪感兴趣区域
roi = pic_rgb.crop((x1, y1, x2, y2))
arr = np.array(roi)
if arr.size == 0:
return False
# 提取RGB通道
r = arr[:, :, 0] # type: ignore[index]
g = arr[:, :, 1] # type: ignore[index]
b = arr[:, :, 2] # type: ignore[index]
# 红色特征:R > 200, G < 180, B < 180
# 购物红包的红色通常很纯,R值很高
mask = (r >= 220) & (g <= 160) & (b <= 160)
# 计算红色像素占比
total_pixels = mask.size
red_pixels = np.sum(mask) # type: ignore[call-overload]
red_ratio = red_pixels / total_pixels if total_pixels > 0 else 0
# 阈值:至少15%的像素满足红色特征
return red_ratio > 0.15
except Exception:
return False
def detect_lucky_draw_result_popup(
+4 -4
View File
@@ -38,8 +38,8 @@ LOTTERY_RESULT_AREA = (300, 600, 800, 800)
LOTTERY_RESULT_CONFIRM_BUTTON = (181, 1261, 890, 1389)
# 购物红包/弹窗诊断区域
SHOPPING_REDPACKET_AREA = (230, 450, 860, 550)
STAGE_RED_PACKET_OCR = (238, 454, 847, 545)
SHOPPING_REDPACKET_AREA = (200, 300, 880, 1200)
STAGE_RED_PACKET_OCR = (200, 300, 880, 1200)
COUPON_PARTICIPATE_BUTTON_ALT = (200, 1940, 880, 2140)
# 常用标签栏(推荐/关注/直播)
@@ -60,8 +60,8 @@ LIVE_VERIFY2 = (200, 900, 880, 1200)
# 机器人验证图片裁剪区域(用于保存/处理验证图片)
ROBOT_VERIFY = (100, 1200, 980, 1780)
# 诊断购物红包(弹窗快速检测区域)
DIAG_SHOPPING_REDPACKET = (400, 1400, 900, 1600)
# 诊断购物红包(弹窗快速检测区域 - 文字区域)
DIAG_SHOPPING_REDPACKET = (200, 300, 880, 1000)
# 倒计时、任务、按钮等常用区域(保留占位,可根据需要填写)
# COUNTDOWN_BOX = (390, 1140, 570, 1290)
+53 -41
View File
@@ -499,9 +499,14 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
return False, "ok"
def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
def basic_join_decision(analyser: Any, detail: Tuple, skip_result: Tuple[bool, str] = None) -> bool:
"""基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。
参数:
analyser: 分析器对象
detail: 福袋详情元组
skip_result: 可选的筛选结果 (skip, reason),如果已知可以避免重复筛选
返回:
True 表示已经参与或已处理完成;
False 表示未参与(例如被配置筛掉或参与失败)。
@@ -520,6 +525,13 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
except Exception:
pass
# 预先检查是否是观看任务,避免后续重复检查
is_watch_task = False
try:
is_watch_task = is_watch_task_fudai(content)
except Exception:
pass
# 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理
try:
last_status = getattr(analyser, "_last_fudai_detail_status", "")
@@ -687,29 +699,38 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
and future_ts > 0.0
)
# 执行筛选检查
skip, reason = should_skip_fudai_by_config(analyser, detail)
# 执行筛选检查(如果没有提供筛选结果)
if skip_result is not None:
skip, reason = skip_result
try:
analyser._log_kv(
"参与",
"basic_join_decision:使用传入的筛选结果",
skip=skip,
reason=reason,
)
except Exception:
pass
else:
skip, reason = should_skip_fudai_by_config(analyser, detail)
# 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值
# 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约
# 注意:如果是观看任务,不应该进入这个特殊处理逻辑(should_skip_fudai_by_config 已经返回 watch_task_detected)
if skip and reason.startswith("countdown_gt_") and is_high_value:
# 再次检查是否是观看任务(双重保险)
is_watch_task = False
try:
is_watch_task = is_watch_task_fudai(content)
if is_watch_task:
# 是观看任务,不记录预约,直接关闭详情页并返回
try:
analyser._log_kv(
"[预约]",
"特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃",
content=content[:80] if content else "",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
)
except Exception:
pass
# 检查是否是观看任务(使用预先计算的结果)
if is_watch_task:
# 是观看任务,不记录预约,直接关闭详情页并返回
try:
analyser._log_kv(
"[预约]",
"特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃",
content=content[:80] if content else "",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
)
except Exception:
pass
# 关闭详情页
try:
analyser.click(500, 470)
@@ -780,9 +801,6 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
# 如果检查观看任务时出错,记录日志但继续后续处理(容错处理)
pass
# 计算剩余秒数
remain_seconds = None
@@ -833,22 +851,19 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
# 注意:强制参与标志会在参与成功后清除(在 attend_choujiang 返回后),避免影响后续福袋
# no-op: 强制参与标志已删除
else:
# 剩余秒数大于"预约参与阈值",但在记录预约之前再次检查是否是观看任务
is_watch_task_check = False
try:
is_watch_task_check = is_watch_task_fudai(content)
if is_watch_task_check:
# 是观看任务,不记录预约,直接关闭详情页并返回
try:
analyser._log_kv(
"[预约]",
"特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃",
content=content[:80] if content else "",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
)
except Exception:
pass
# 剩余秒数大于"预约参与阈值",但在记录预约之前检查是否是观看任务
if is_watch_task:
# 是观看任务,不记录预约,直接关闭详情页并返回
try:
analyser._log_kv(
"[预约]",
"特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃",
content=content[:80] if content else "",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
)
except Exception:
pass
# 关闭详情页
try:
analyser.click(500, 470)
@@ -919,9 +934,6 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
# 如果检查观看任务时出错,记录日志但继续后续处理(容错处理)
pass
# 剩余秒数大于"预约参与阈值",记录预约
try:
+7 -3
View File
@@ -5322,17 +5322,21 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
# 同时添加到本次运行的高价值房间列表
try:
current_run_rooms = getattr(analyser, "_current_run_high_value_rooms", [])
current_run_rooms = getattr(
analyser, "_current_run_high_value_rooms", []
)
room_info = {
"room_title": room_title,
"room_title_raw": room_title_raw,
"max_prize_value_yuan": prize_value_yuan,
"last_seen_ts": time.time(),
"pos_seen": room_pos,
"seen_count": 1
"seen_count": 1,
}
current_run_rooms.append(room_info)
analyser._current_run_high_value_rooms = current_run_rooms
analyser._current_run_high_value_rooms = (
current_run_rooms
)
except Exception:
pass
except Exception:
+21
View File
@@ -430,6 +430,27 @@ class FudaiDetector:
except Exception:
pass
# 保存调试图像(标注检测区域)
try:
if douyin_screenshot_manager:
debug_coords = (x1, y_top, x2, y_bottom)
douyin_screenshot_manager.save_debug_image(
pic,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected_fallback",
coords=debug_coords,
extra_info={
"detected_x": detected_x,
"detected_x_scaled": found_x,
"region": region["name"],
"color_range": "R:190-206,G:173-196,B:234-250",
"mode": "fallback_pixel_search",
},
)
except Exception:
pass # 调试图像保存失败不影响主流程
elapsed = (time.time() - start_time) * 1000
try:
-2
View File
@@ -50,14 +50,12 @@ __all__ = [
"format_exception",
"add_separators",
"add_colors",
# 类
"PerformanceTracker",
"ErrorLogger",
"DebugLogger",
"ActionLogger",
"LoggingWrapper",
# 装饰器和工具函数
"track_action",
"_get_debug_logger",
+61 -33
View File
@@ -46,9 +46,9 @@ def _normalize_room_title(title: str) -> str:
s = s.replace(w, "")
# 去除数字和特殊字符,只保留中文、英文、数字(但去除末尾的数字)
# 先去除末尾的数字(如 "王媛媛2" -> "王媛媛")
s = re.sub(r'\d+$', '', s)
s = re.sub(r"\d+$", "", s)
# 去除其他特殊字符
s = re.sub(r'[^\w\u4e00-\u9fff]', '', s)
s = re.sub(r"[^\w\u4e00-\u9fff]", "", s)
return s
@@ -56,7 +56,7 @@ def _load_high_value_rooms() -> Dict[str, Any]:
"""加载高价值房间数据"""
try:
if HIGH_VALUE_ROOMS_PATH.exists():
with open(HIGH_VALUE_ROOMS_PATH, 'r', encoding='utf-8') as f:
with open(HIGH_VALUE_ROOMS_PATH, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
@@ -67,7 +67,7 @@ def _save_high_value_rooms(data: Dict[str, Any]) -> None:
"""保存高价值房间数据"""
try:
HIGH_VALUE_ROOMS_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(HIGH_VALUE_ROOMS_PATH, 'w', encoding='utf-8') as f:
with open(HIGH_VALUE_ROOMS_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception:
pass
@@ -81,7 +81,7 @@ def touch_high_value_room(
reason: str = "unknown",
increment: bool = True,
content: str = "",
pos_seen: int = 0
pos_seen: int = 0,
) -> None:
"""记录或更新高价值直播间信息
@@ -147,7 +147,7 @@ def touch_high_value_room(
"last_content": content,
"last_prize_value_yuan": prize_value_yuan,
"max_prize_value_yuan": prize_value_yuan,
"room_title": title_norm
"room_title": title_norm,
}
rooms.append(new_room)
@@ -168,7 +168,7 @@ def touch_high_value_room(
prize_value_yuan=prize_value_yuan,
pos_seen=pos_seen,
total_rooms=len(rooms),
is_new=(existing_room is None)
is_new=(existing_room is None),
)
except Exception:
pass
@@ -179,7 +179,7 @@ def touch_high_value_room(
"高价值房间",
"[重访] 记录高价值直播间失败",
error=str(e),
room_title=title_norm[:30]
room_title=title_norm[:30],
)
except Exception:
pass
@@ -189,7 +189,7 @@ def get_revisit_candidates(
analyser: Any,
only_current_run: bool = False,
min_prize_value: float = 0.0,
max_age_days: int = 30
max_age_days: int = 30,
) -> List[Dict[str, Any]]:
"""获取重访候选房间列表
@@ -231,8 +231,8 @@ def get_revisit_candidates(
filtered_candidates.sort(
key=lambda x: (
-x.get("max_prize_value_yuan", 0), # 最高价值优先
-x.get("last_seen_ts", 0), # 最近访问优先
-x.get("seen_count", 0) # 访问次数优先
-x.get("last_seen_ts", 0), # 最近访问优先
-x.get("seen_count", 0), # 访问次数优先
)
)
@@ -240,11 +240,7 @@ def get_revisit_candidates(
except Exception as e:
try:
analyser._log_kv(
"高价值房间",
"[重访] 获取重访候选失败",
error=str(e)
)
analyser._log_kv("高价值房间", "[重访] 获取重访候选失败", error=str(e))
except Exception:
pass
return []
@@ -255,7 +251,7 @@ def should_trigger_revisit(
revisit_enabled: bool,
only_current_run: bool,
min_interval_seconds: int = 300,
max_revisit_per_run: int = 5
max_revisit_per_run: int = 5,
) -> bool:
"""检查是否应该触发重访
@@ -274,8 +270,12 @@ def should_trigger_revisit(
try:
# 检查是否正在参与福袋(等待开奖结果或正在参与预约福袋)
waiting_for_lottery = bool(getattr(analyser, "_waiting_for_lottery_result", False))
current_attending_reservation = bool(getattr(analyser, "_current_attending_reservation_fudai", False))
waiting_for_lottery = bool(
getattr(analyser, "_waiting_for_lottery_result", False)
)
current_attending_reservation = bool(
getattr(analyser, "_current_attending_reservation_fudai", False)
)
if waiting_for_lottery or current_attending_reservation:
try:
@@ -283,7 +283,7 @@ def should_trigger_revisit(
"高价值房间",
"[重访] 当前正在参与福袋,跳过重访检查",
waiting_for_lottery=waiting_for_lottery,
current_attending_reservation=current_attending_reservation
current_attending_reservation=current_attending_reservation,
)
except Exception:
pass
@@ -311,10 +311,7 @@ def should_trigger_revisit(
return False
def execute_room_revisit(
analyser: Any,
target_room: Dict[str, Any]
) -> bool:
def execute_room_revisit(analyser: Any, target_room: Dict[str, Any]) -> bool:
"""执行房间重访
Args:
@@ -333,28 +330,59 @@ def execute_room_revisit(
"[重访] 开始执行房间重访",
room_title=room_title[:30],
pos_seen=pos_seen,
max_prize_value=target_room.get("max_prize_value_yuan", 0)
max_prize_value=target_room.get("max_prize_value_yuan", 0),
)
# 记录重访时间和次数
analyser._last_high_value_revisit_ts = time.time()
analyser._current_run_revisit_count = getattr(analyser, "_current_run_revisit_count", 0) + 1
analyser._current_run_revisit_count = (
getattr(analyser, "_current_run_revisit_count", 0) + 1
)
# 获取当前位置信息,用于日志
try:
current_pos = int(getattr(analyser, "room_pos", 0) or 0)
analyser._log_kv(
"高价值房间",
"[重访] 准备切换到目标房间",
current_room_pos=current_pos,
target_pos=pos_seen,
pos_diff=pos_seen - current_pos,
room_title=room_title[:30],
)
except Exception:
pass
# 使用现有的房间定位逻辑
# 这里可以调用预约系统的回退逻辑来定位到目标房间
success = analyser._seek_reservation_room(target_room)
analyser._log_kv(
"高价值房间",
"[重访] 开始房间切换操作",
room_title=room_title[:30],
target_pos=pos_seen,
)
success = analyser._seek_reservation_room(target_room, operation_type="高价值房间")
if success:
analyser._log_kv(
"高价值房间",
"[重访] 房间重访成功",
room_title=room_title[:30]
"[重访] 房间切换成功",
room_title=room_title[:30],
target_pos=pos_seen,
)
analyser._log_kv(
"高价值房间", "[重访] 房间重访成功", room_title=room_title[:30]
)
else:
analyser._log_kv(
"高价值房间",
"[重访] 房间重访失败",
room_title=room_title[:30]
"[重访] 房间切换失败",
room_title=room_title[:30],
target_pos=pos_seen,
)
analyser._log_kv(
"高价值房间", "[重访] 房间重访失败", room_title=room_title[:30]
)
return success
@@ -365,8 +393,8 @@ def execute_room_revisit(
"高价值房间",
"[重访] 房间重访异常",
error=str(e),
room_title=target_room.get("room_title", "")[:30]
room_title=target_room.get("room_title", "")[:30],
)
except Exception:
pass
return False
return False
+14 -3
View File
@@ -210,7 +210,18 @@ def check_shopping_redpacket_popup(analyser) -> bool:
pic.load() # Force load to catch truncated files early
pic = pic.convert("RGB")
has_popup_pixel = bool(douyin_pixel.detect_redpacket_popup_background(pic))
_ = time.time() - pixel_check_start
pixel_elapsed = time.time() - pixel_check_start
try:
analyser._log_kv(
"購物紅包檢測",
f"像素檢測{'成功' if has_popup_pixel else '未檢測到'}",
像素結果=has_popup_pixel,
耗時秒=f"{pixel_elapsed:.3f}",
)
except Exception:
pass
if not has_popup_pixel:
return False
except (OSError, IOError, SyntaxError):
@@ -293,7 +304,7 @@ def check_shopping_redpacket_popup(analyser) -> bool:
pass
return False
keywords = ("邀你搶購物紅包", "搶購物紅包", "購物紅包", "邀你搶", "搶紅包", "搶")
keywords = ("邀你搶購物紅包", "搶購物紅包", "購物紅包", "邀你搶", "搶紅包", "搶", "最高領取", "邀你抢购物红包", "抢购物红包", "购物红包", "邀你抢")
if any(kw in hay for kw in keywords):
matched = [kw for kw in keywords if kw in hay]
total_elapsed = time.time() - check_start
@@ -369,7 +380,7 @@ def check_shopping_redpacket_popup(analyser) -> bool:
)
combined_text = " ".join(texts).strip()
final_keywords = ("購物紅包", "邀你搶", "搶紅包")
final_keywords = ("購物紅包", "邀你搶", "搶紅包", "购物红包", "邀你抢", "抢红包", "最高領取", "最高领取")
result = any(kw in combined_text for kw in final_keywords)
if not result and has_popup_pixel:
result = True
+39 -30
View File
@@ -77,7 +77,12 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
analyser.operation.delay(1)
def _detect_icon(
action: str, base_x: int, base_y: int, template_path: str, roi_label: str, shared_screenshot_path: str = None
action: str,
base_x: int,
base_y: int,
template_path: str,
roi_label: str,
shared_screenshot_path: str = None,
) -> tuple[bool, float]:
"""模板匹配检测爱心/收藏图标,只在full screenshot上做一次匹配"""
# 检查模板文件是否存在
@@ -114,42 +119,48 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
if not tpl_exists or not os.path.exists(str(template_path or "")):
print(f"[养号] {action}: 模板文件不存在,假设图标存在")
return True, 1.0
# 使用共享的full screenshot,不做ROI截图
if not shared_screenshot_path or not os.path.exists(shared_screenshot_path):
if not shared_screenshot_path or not os.path.exists(
shared_screenshot_path
):
print(f"[养号] {action}: 截图文件不存在,假设图标存在")
return True, 1.0
# 读取full screenshot
pic = cv2.imread(shared_screenshot_path)
if pic is None:
print(f"[养号] {action}: 读取截图失败,假设图标存在")
return True, 1.0
# 读取模板
template = cv2.imread(str(template_path))
if template is None:
print(f"[养号] {action}: 读取模板失败,假设图标存在")
return True, 1.0
# 灰度化处理
pic_gray = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
# 使用标准化相关系数进行模板匹配
result = cv2.matchTemplate(pic_gray, template_gray, cv2.TM_CCOEFF_NORMED)
result = cv2.matchTemplate(
pic_gray, template_gray, cv2.TM_CCOEFF_NORMED
)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# 获取匹配阈值
threshold = float(
getattr(analyser, "yanghao_icon_match_threshold", 0.6) or 0.6
)
if max_val >= threshold:
print(f"[养号] {action}: 模板匹配成功 (分数={max_val:.3f})")
return True, float(max_val)
else:
print(f"[养号] {action}: 模板匹配失败 (分数={max_val:.3f} < {threshold})")
print(
f"[养号] {action}: 模板匹配失败 (分数={max_val:.3f} < {threshold})"
)
return False, float(max_val)
except Exception as e:
print(f"[养号] {action}: 模板匹配异常 {e},假设图标存在")
@@ -168,8 +179,11 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
# 截图一次
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
import path_config
screenshot_path = path_config.get_screenshot_path()
except Exception:
screenshot_path = None
@@ -195,7 +209,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
# 检查是否检测到爱心或收藏任意一个
action_detected = like_ok or fav_ok
# 根据概率点击爱心
if (
like_ok
@@ -248,7 +262,8 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
getattr(analyser, "yanghao_dwell_on_action_min_seconds", 5) or 5
)
dwell_max = float(
getattr(analyser, "yanghao_dwell_on_action_max_seconds", 30) or 30
getattr(analyser, "yanghao_dwell_on_action_max_seconds", 30)
or 30
)
dwell_time = random.uniform(dwell_min, dwell_max)
print(f"[养号] 检测到动作,停留 {dwell_time:.1f}s")
@@ -341,7 +356,12 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
analyser.operation.delay(1)
def _detect_icon(
action: str, base_x: int, base_y: int, template_path: str, roi_label: str, shared_screenshot_path: str = None
action: str,
base_x: int,
base_y: int,
template_path: str,
roi_label: str,
shared_screenshot_path: str = None,
) -> tuple[bool, float]:
_step_shot(f"before_detect_{roi_label}")
# 确保在所有分支中都定义了 roi_path,避免后续使用时未赋值错误
@@ -416,18 +436,10 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
pass
# 使用默认的ROI大小
roi_size = int(
getattr(analyser, "yanghao_icon_roi_size", 180) or 180
)
roi_size = int(getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
try:
scale_x = (
float(getattr(analyser, "resolution_ratio_x", 1080))
/ 1080.0
)
scale_y = (
float(getattr(analyser, "resolution_ratio_y", 2400))
/ 2400.0
)
scale_x = float(getattr(analyser, "resolution_ratio_x", 1080)) / 1080.0
scale_y = float(getattr(analyser, "resolution_ratio_y", 2400)) / 2400.0
except Exception:
scale_x = scale_y = 1.0
try:
@@ -443,9 +455,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
action_scale = 1.0
except Exception:
action_scale = 1.5
roi_px = max(
1, int(roi_size * max(scale_x, scale_y) * float(action_scale))
)
roi_px = max(1, int(roi_size * max(scale_x, scale_y) * float(action_scale)))
roi_path = analyser._capture_roi_screenshot(
roi_label, sx, sy, int(roi_px), shared_screenshot_path
)
@@ -497,4 +507,3 @@ def yanghao_wait(analyser, total_seconds: int) -> None:
# 执行推荐页养号流程
yanghao_recommend_flow(analyser, total_seconds)
@@ -301,7 +301,11 @@ class ReservationHandler:
pass
@staticmethod # type: ignore[misc]
def seek_reservation_room(analyser: Any, item: Dict[str, Any]) -> bool:
def seek_reservation_room(
analyser: Any,
item: Dict[str, Any],
operation_type: str = "预约"
) -> bool:
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
说明:
@@ -311,6 +315,7 @@ class ReservationHandler:
参数:
analyser: 分析器对象
item: 预约记录字典
operation_type: 操作类型,用于日志标识("预约" 或 "高价值房间")
返回:
bool: 是否成功回退到目标直播间
@@ -346,8 +351,8 @@ class ReservationHandler:
# 输出目标直播间的位置和标题信息
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] _seek_reservation_room:开始回退到目标直播间",
operation_type,
f"[{operation_type}] _seek_reservation_room:开始回退到目标直播间",
target_room_title=target_room_title,
target_room_title_raw=target_room_title_raw,
target_pos=target_pos,
@@ -368,8 +373,8 @@ class ReservationHandler:
back_times = min(abs(pos_diff), max_back) if max_back > 0 else abs(pos_diff)
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] _seek_reservation_room 向上回退(目标在上方)",
operation_type,
f"[{operation_type}] _seek_reservation_room 向上回退(目标在上方)",
back_times=back_times,
current_room_pos=cur_pos,
target_pos=target_pos,
@@ -403,8 +408,8 @@ class ReservationHandler:
forward_times = min(pos_diff, max_back) if max_back > 0 else pos_diff
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] _seek_reservation_room 向下切换(目标在下方)",
operation_type,
f"[{operation_type}] _seek_reservation_room 向下切换(目标在下方)",
forward_times=forward_times,
current_room_pos=cur_pos,
target_pos=target_pos,
@@ -757,7 +762,9 @@ class ReservationHandler:
if remain_seconds > 0:
analyser._waiting_for_lottery_result = True
analyser._lottery_result_expected_ts = future_ts
analyser._current_attending_reservation_fudai = True # 标记当前正在参与预约福袋
analyser._current_attending_reservation_fudai = (
True # 标记当前正在参与预约福袋
)
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 预约回退后参与成功,设置开奖等待状态",
@@ -1034,8 +1034,12 @@ def process_reservation_attend_window(
# 检查是否正在等待开奖且当前参与的是预约福袋,如果是则不抢占
try:
waiting_for_lottery = bool(getattr(analyser, "_waiting_for_lottery_result", False))
current_attending_reservation = bool(getattr(analyser, "_current_attending_reservation_fudai", False))
waiting_for_lottery = bool(
getattr(analyser, "_waiting_for_lottery_result", False)
)
current_attending_reservation = bool(
getattr(analyser, "_current_attending_reservation_fudai", False)
)
if waiting_for_lottery and current_attending_reservation:
try:
analyser._log_kv(
+5
View File
@@ -209,6 +209,11 @@ class ConfigManager:
config["high_value_fudai_after_action"] or "continue"
)
if "high_value_fudai_poll_before_seconds" in config:
analyser.high_value_fudai_poll_before_seconds = float(
config["high_value_fudai_poll_before_seconds"] or 10.0
)
if "high_value_fudai_after_stay_seconds" in config:
analyser.high_value_fudai_after_stay_seconds = int(
config["high_value_fudai_after_stay_seconds"] or 120
+2 -6
View File
@@ -314,9 +314,7 @@ class HelperFunctions:
pass
# 记录未中奖日志,用于GUI统计
analyser._log_kv(
"开奖结果", "没有抽中,关闭弹窗", log_type="RESULT"
)
analyser._log_kv("开奖结果", "没有抽中,关闭弹窗", log_type="RESULT")
# 切换下一个直播间
try:
@@ -354,9 +352,7 @@ class HelperFunctions:
pass
# 记录中奖日志,用于GUI统计
analyser._log_kv(
"开奖结果", "检测到中奖结果", log_type="RESULT"
)
analyser._log_kv("开奖结果", "检测到中奖结果", log_type="RESULT")
try:
# 确保有最新截图
+162 -35
View File
@@ -440,12 +440,27 @@ def main():
high_value_fudai_after_action_var = tk.StringVar(
value=str(cfg.get("high_value_fudai_after_action", "continue") or "continue")
)
high_value_fudai_poll_before_seconds_var = tk.DoubleVar(
value=float(cfg.get("high_value_fudai_poll_before_seconds", 10.0) or 10.0)
)
high_value_room_revisit_enabled_var = tk.BooleanVar(
value=bool(cfg.get("high_value_room_revisit_enabled", True))
)
high_value_room_revisit_only_current_run_var = tk.BooleanVar(
value=bool(cfg.get("high_value_room_revisit_only_current_run", False))
)
high_value_room_revisit_min_interval_seconds_var = tk.IntVar(
value=int(cfg.get("high_value_room_revisit_min_interval_seconds", 300))
)
high_value_room_revisit_max_per_run_var = tk.IntVar(
value=int(cfg.get("high_value_room_revisit_max_per_run", 5))
)
high_value_room_revisit_min_prize_value_var = tk.DoubleVar(
value=float(cfg.get("high_value_room_revisit_min_prize_value", 0.0))
)
high_value_room_revisit_max_age_days_var = tk.IntVar(
value=int(cfg.get("high_value_room_revisit_max_age_days", 30))
)
reservation_back_verify_enabled_var = tk.BooleanVar(
value=bool(cfg.get("reservation_back_verify_enabled", True))
)
@@ -545,18 +560,10 @@ def main():
cfg.get("yanghao_fav_template_path", "assets/fav.png") or "assets/fav.png"
)
)
yg_like_icon_x_var = tk.IntVar(
value=int(cfg.get("yanghao_like_icon_x", 0) or 0)
)
yg_like_icon_y_var = tk.IntVar(
value=int(cfg.get("yanghao_like_icon_y", 0) or 0)
)
yg_fav_icon_x_var = tk.IntVar(
value=int(cfg.get("yanghao_fav_icon_x", 0) or 0)
)
yg_fav_icon_y_var = tk.IntVar(
value=int(cfg.get("yanghao_fav_icon_y", 0) or 0)
)
yg_like_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_x", 0) or 0))
yg_like_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_y", 0) or 0))
yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_x", 0) or 0))
yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_y", 0) or 0))
yg_after_dwell_direction_var = tk.StringVar(
value=str(cfg.get("yanghao_after_dwell_swipe_direction", "up") or "up")
)
@@ -995,6 +1002,59 @@ def main():
res_r4, text="仅当前运行", variable=high_value_room_revisit_only_current_run_var
).pack(side=LEFT, padx=(20, 0))
# 高价值房间回访详细参数
res_r4a = ttk.Frame(reservation_box)
res_r4a.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(res_r4a, text="重访最小间隔(秒):").pack(side=LEFT)
ttk.Spinbox(
res_r4a,
from_=60,
to=3600,
textvariable=high_value_room_revisit_min_interval_seconds_var,
width=8,
).pack(side=LEFT, padx=(0, 20))
ttk.Label(res_r4a, text="每次运行最大次数:").pack(side=LEFT)
ttk.Spinbox(
res_r4a,
from_=1,
to=20,
textvariable=high_value_room_revisit_max_per_run_var,
width=5,
).pack(side=LEFT, padx=(0, 20))
res_r4b = ttk.Frame(reservation_box)
res_r4b.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(res_r4b, text="最低奖品价值(元):").pack(side=LEFT)
ttk.Spinbox(
res_r4b,
from_=0.0,
to=10000.0,
textvariable=high_value_room_revisit_min_prize_value_var,
width=8,
).pack(side=LEFT, padx=(0, 20))
ttk.Label(res_r4b, text="最大年龄(天):").pack(side=LEFT)
ttk.Spinbox(
res_r4b,
from_=1,
to=365,
textvariable=high_value_room_revisit_max_age_days_var,
width=5,
).pack(side=LEFT, padx=(0, 20))
# 开奖前轮询时间
res_r4b = ttk.Frame(reservation_box)
res_r4b.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(res_r4b, text="开奖前轮询时间(秒):").pack(side=LEFT)
ttk.Spinbox(
res_r4b,
from_=0.0,
to=60.0,
increment=1.0,
textvariable=high_value_fudai_poll_before_seconds_var,
width=6,
).pack(side=LEFT)
ttk.Label(res_r4b, text="(开奖前N秒开始轮询预约)").pack(side=LEFT, padx=(6, 0))
# 预约回退校验
res_r5 = ttk.Frame(reservation_box)
res_r5.pack(fill=X, padx=10, pady=(0, 8))
@@ -1093,11 +1153,21 @@ def main():
yg1b.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(yg1b, text="检测动作后停留(秒):").pack(side=LEFT)
ttk.Spinbox(
yg1b, from_=0.0, to=120.0, increment=1.0, textvariable=yg_dwell_on_action_min_var, width=6
yg1b,
from_=0.0,
to=120.0,
increment=1.0,
textvariable=yg_dwell_on_action_min_var,
width=6,
).pack(side=LEFT)
ttk.Label(yg1b, text="~").pack(side=LEFT, padx=(6, 6))
ttk.Spinbox(
yg1b, from_=0.0, to=120.0, increment=1.0, textvariable=yg_dwell_on_action_max_var, width=6
yg1b,
from_=0.0,
to=120.0,
increment=1.0,
textvariable=yg_dwell_on_action_max_var,
width=6,
).pack(side=LEFT)
ttk.Label(yg1b, text="(随机范围)").pack(side=LEFT, padx=(6, 0))
@@ -1809,12 +1879,27 @@ def main():
high_value_fudai_after_action_var.set(
str(cfg.get("high_value_fudai_after_action", "continue") or "continue")
)
high_value_fudai_poll_before_seconds_var.set(
float(cfg.get("high_value_fudai_poll_before_seconds", 10.0) or 10.0)
)
high_value_room_revisit_enabled_var.set(
bool(cfg.get("high_value_room_revisit_enabled", True))
)
high_value_room_revisit_only_current_run_var.set(
bool(cfg.get("high_value_room_revisit_only_current_run", False))
)
high_value_room_revisit_min_interval_seconds_var.set(
int(cfg.get("high_value_room_revisit_min_interval_seconds", 300))
)
high_value_room_revisit_max_per_run_var.set(
int(cfg.get("high_value_room_revisit_max_per_run", 5))
)
high_value_room_revisit_min_prize_value_var.set(
float(cfg.get("high_value_room_revisit_min_prize_value", 0.0))
)
high_value_room_revisit_max_age_days_var.set(
int(cfg.get("high_value_room_revisit_max_age_days", 30))
)
reservation_back_verify_enabled_var.set(
bool(cfg.get("reservation_back_verify_enabled", True))
)
@@ -1977,8 +2062,12 @@ def main():
yg_like_prob_var.set(float(cfg.get("yanghao_like_prob", 0.0) or 0.0))
yg_fav_prob_var.set(float(cfg.get("yanghao_fav_prob", 0.0) or 0.0))
yg_comment_prob_var.set(float(cfg.get("yanghao_comment_prob", 0.0) or 0.0))
yg_dwell_on_action_min_var.set(float(cfg.get("yanghao_dwell_on_action_min_seconds", 5) or 5))
yg_dwell_on_action_max_var.set(float(cfg.get("yanghao_dwell_on_action_max_seconds", 30) or 30))
yg_dwell_on_action_min_var.set(
float(cfg.get("yanghao_dwell_on_action_min_seconds", 5) or 5)
)
yg_dwell_on_action_max_var.set(
float(cfg.get("yanghao_dwell_on_action_max_seconds", 30) or 30)
)
yg_icon_roi_size_var.set(int(cfg.get("yanghao_icon_roi_size", 240) or 240))
yg_icon_match_threshold_var.set(
float(cfg.get("yanghao_icon_match_threshold", 0.72) or 0.72)
@@ -2089,12 +2178,27 @@ def main():
cfg2["high_value_fudai_after_action"] = str(
high_value_fudai_after_action_var.get() or "continue"
).lower()
cfg2["high_value_fudai_poll_before_seconds"] = float(
high_value_fudai_poll_before_seconds_var.get() or 10.0
)
cfg2["high_value_room_revisit_enabled"] = bool(
high_value_room_revisit_enabled_var.get()
)
cfg2["high_value_room_revisit_only_current_run"] = bool(
high_value_room_revisit_only_current_run_var.get()
)
cfg2["high_value_room_revisit_min_interval_seconds"] = int(
high_value_room_revisit_min_interval_seconds_var.get()
)
cfg2["high_value_room_revisit_max_per_run"] = int(
high_value_room_revisit_max_per_run_var.get()
)
cfg2["high_value_room_revisit_min_prize_value"] = float(
high_value_room_revisit_min_prize_value_var.get()
)
cfg2["high_value_room_revisit_max_age_days"] = int(
high_value_room_revisit_max_age_days_var.get()
)
cfg2["reservation_back_verify_enabled"] = bool(
reservation_back_verify_enabled_var.get()
)
@@ -2245,8 +2349,12 @@ def main():
cfg2["yanghao_like_prob"] = float(yg_like_prob_var.get() or 0.0)
cfg2["yanghao_fav_prob"] = float(yg_fav_prob_var.get() or 0.0)
cfg2["yanghao_comment_prob"] = float(yg_comment_prob_var.get() or 0.0)
cfg2["yanghao_dwell_on_action_min_seconds"] = float(yg_dwell_on_action_min_var.get() or 5)
cfg2["yanghao_dwell_on_action_max_seconds"] = float(yg_dwell_on_action_max_var.get() or 30)
cfg2["yanghao_dwell_on_action_min_seconds"] = float(
yg_dwell_on_action_min_var.get() or 5
)
cfg2["yanghao_dwell_on_action_max_seconds"] = float(
yg_dwell_on_action_max_var.get() or 30
)
cfg2["yanghao_icon_roi_size"] = int(yg_icon_roi_size_var.get() or 240)
cfg2["yanghao_icon_match_threshold"] = float(
yg_icon_match_threshold_var.get() or 0.72
@@ -3370,6 +3478,21 @@ def main():
high_value_room_revisit_only_current_run=bool(
high_value_room_revisit_only_current_run_var.get()
),
high_value_room_revisit_min_interval_seconds=int(
high_value_room_revisit_min_interval_seconds_var.get()
),
high_value_room_revisit_max_per_run=int(
high_value_room_revisit_max_per_run_var.get()
),
high_value_room_revisit_min_prize_value=float(
high_value_room_revisit_min_prize_value_var.get()
),
high_value_room_revisit_max_age_days=int(
high_value_room_revisit_max_age_days_var.get()
),
high_value_fudai_poll_before_seconds=float(
high_value_fudai_poll_before_seconds_var.get() or 10.0
),
reservation_back_verify_enabled=bool(
reservation_back_verify_enabled_var.get()
),
@@ -3586,13 +3709,15 @@ def main():
fudai_result_win = counters.get("fudai_result_win", 0)
fudai_order_success = counters.get("fudai_order_success", 0)
if fudai_seen_unique > 0 or fudai_attend_ok_unique > 0 or fudai_result_win > 0:
if (
fudai_seen_unique > 0
or fudai_attend_ok_unique > 0
or fudai_result_win > 0
):
lines.append("=" * 60)
lines.append("快速汇总")
lines.append("=" * 60)
lines.append(
f"识别福袋: {fudai_seen_unique} 个"
)
lines.append(f"识别福袋: {fudai_seen_unique} 个")
lines.append(f"参与成功: {fudai_attend_ok_unique} 次")
lines.append(f"中奖次数: {fudai_result_win} 次")
lines.append(f"下单成功: {fudai_order_success} 次")
@@ -3621,34 +3746,34 @@ def main():
fudai_order_success = counters.get("fudai_order_success", 0)
lines.append(f"福袋识别次数: {fudai_seen_unique}")
lines.append(
f"打开详情: {fudai_open_detail_unique}"
)
lines.append(f"打开详情: {fudai_open_detail_unique}")
if fudai_seen > 0:
open_rate = (fudai_open_detail_unique / fudai_seen_unique) * 100
lines.append(f" 打开成功率: {open_rate:.1f}%")
lines.append(
f"点击参与: {fudai_click_attend_unique}"
)
lines.append(f"点击参与: {fudai_click_attend_unique}")
if fudai_open_detail > 0:
click_rate = (fudai_click_attend_unique / fudai_open_detail_unique) * 100
click_rate = (
fudai_click_attend_unique / fudai_open_detail_unique
) * 100
lines.append(f" 点击率: {click_rate:.1f}%")
lines.append(
f"参与成功: {fudai_attend_ok_unique}"
)
lines.append(f"参与成功: {fudai_attend_ok_unique}")
lines.append(f"参与失败: {fudai_attend_fail}")
# 参与成功率应该基于点击参与次数来计算
# 因为参与成功可能包括"检测到已参与"的情况(没有点击)
if fudai_click_attend_unique > 0:
# 通过点击参与成功的次数(不超过点击参与次数)
click_attend_success = min(fudai_attend_ok_unique, fudai_click_attend_unique)
click_attend_success = min(
fudai_attend_ok_unique, fudai_click_attend_unique
)
success_rate = (click_attend_success / fudai_click_attend_unique) * 100
lines.append(f" 参与成功率: {success_rate:.1f}%")
# 如果参与成功 > 点击参与,说明有检测到已参与的情况
if fudai_attend_ok_unique > fudai_click_attend_unique:
detected_already_attended = fudai_attend_ok_unique - fudai_click_attend_unique
detected_already_attended = (
fudai_attend_ok_unique - fudai_click_attend_unique
)
lines.append(
f" (其中 {detected_already_attended} 次为检测到已参与状态)"
)
@@ -3681,7 +3806,9 @@ def main():
lines.append("")
lines.append("效率统计(每小时):")
if fudai_seen_unique > 0:
lines.append(f" 识别福袋: {fudai_seen_unique / hours:.1f} 个/小时")
lines.append(
f" 识别福袋: {fudai_seen_unique / hours:.1f} 个/小时"
)
if fudai_attend_ok_unique > 0:
lines.append(
f" 参与成功: {fudai_attend_ok_unique / hours:.1f} 次/小时"
+16 -1
View File
@@ -104,6 +104,11 @@ class RunParams:
# Web端新增参数
high_value_room_revisit_enabled: bool
high_value_room_revisit_only_current_run: bool
high_value_room_revisit_min_interval_seconds: int
high_value_room_revisit_max_per_run: int
high_value_room_revisit_min_prize_value: float
high_value_room_revisit_max_age_days: int
high_value_fudai_poll_before_seconds: float
reservation_back_verify_enabled: bool
reservation_back_swipe_delay: float
fudai_find_max_attempts: int
@@ -156,7 +161,9 @@ class Runner:
self._fudai_attend_fail_room_pos: set[int] = set()
# 已记录福袋识别的跟踪(避免同一个直播间同一个福袋重复记录识别次数)
self._recorded_fudai_seen: set[tuple[str, str]] = set() # (room_title, fudai_content)
self._recorded_fudai_seen: set[tuple[str, str]] = (
set()
) # (room_title, fudai_content)
def is_running(self) -> bool:
return self._proc is not None and self._proc.poll() is None
@@ -977,6 +984,14 @@ class Runner:
cmd.append("--high-value-room-revisit-disabled")
if params.high_value_room_revisit_only_current_run:
cmd.append("--high-value-room-revisit-only-current-run")
if params.high_value_room_revisit_min_interval_seconds != 300:
cmd += ["--high-value-room-revisit-min-interval-seconds", str(params.high_value_room_revisit_min_interval_seconds)]
if params.high_value_room_revisit_max_per_run != 5:
cmd += ["--high-value-room-revisit-max-per-run", str(params.high_value_room_revisit_max_per_run)]
if params.high_value_room_revisit_min_prize_value > 0:
cmd += ["--high-value-room-revisit-min-prize-value", str(params.high_value_room_revisit_min_prize_value)]
if params.high_value_room_revisit_max_age_days != 30:
cmd += ["--high-value-room-revisit-max-age-days", str(params.high_value_room_revisit_max_age_days)]
# 预约回退校验
if params.reservation_back_verify_enabled:
+3 -1
View File
@@ -134,7 +134,9 @@ class ProcRunner:
self._wins_cap: int = 200
# 已记录福袋识别的跟踪(避免同一个直播间同一个福袋重复记录识别次数)
self._recorded_fudai_seen: set[tuple[str, str]] = set() # (room_title, fudai_content)
self._recorded_fudai_seen: set[tuple[str, str]] = (
set()
) # (room_title, fudai_content)
def _reload_log_settings(self) -> None:
"""从 config.json 读取日志设置:统一文件路径 + Web GUI 内存缓存上限。"""
+32
View File
@@ -222,6 +222,30 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
action="store_true",
help="仅回访本次运行记录的高价值直播间",
)
p.add_argument(
"--high-value-room-revisit-min-interval-seconds",
type=int,
default=300,
help="高价值房间重访最小间隔时间(秒,默认300)",
)
p.add_argument(
"--high-value-room-revisit-max-per-run",
type=int,
default=5,
help="每次运行最大重访次数(默认5)",
)
p.add_argument(
"--high-value-room-revisit-min-prize-value",
type=float,
default=0.0,
help="重访最低奖品价值阈值(元,默认0.0)",
)
p.add_argument(
"--high-value-room-revisit-max-age-days",
type=int,
default=30,
help="重访最大年龄天数(默认30)",
)
p.add_argument(
"--reservation-back-verify-enabled",
action="store_true",
@@ -515,6 +539,14 @@ def main(argv: list[str]) -> int:
analyser.high_value_room_revisit_enabled = False
if getattr(args, "high_value_room_revisit_only_current_run", False):
analyser.high_value_room_revisit_only_current_run = True
if getattr(args, "high_value_room_revisit_min_interval_seconds", None) is not None:
analyser.high_value_room_revisit_min_interval_seconds = args.high_value_room_revisit_min_interval_seconds
if getattr(args, "high_value_room_revisit_max_per_run", None) is not None:
analyser.high_value_room_revisit_max_per_run = args.high_value_room_revisit_max_per_run
if getattr(args, "high_value_room_revisit_min_prize_value", None) is not None:
analyser.high_value_room_revisit_min_prize_value = args.high_value_room_revisit_min_prize_value
if getattr(args, "high_value_room_revisit_max_age_days", None) is not None:
analyser.high_value_room_revisit_max_age_days = args.high_value_room_revisit_max_age_days
# 预约回退校验开关(命令行优先)
if getattr(args, "reservation_back_verify_enabled", False):
analyser.reservation_back_verify_enabled = True
+408 -33
View File
@@ -1,7 +1,7 @@
{
"updated_ts": 1767853185.2990494,
"updated_ts": 1767874436.4814007,
"reason": "reservation",
"total": 91,
"total": 114,
"rooms": [
{
"first_seen_ts": 1765799932.458368,
@@ -548,16 +548,17 @@
},
{
"first_seen_ts": 1765736209.4437785,
"last_seen_ts": 1765874930.950471,
"seen_count": 22,
"pos_seen": 2,
"pos_updated_ts": 1765874930.950471,
"room_title_raw_last": "梵象名品...",
"last_seen_ts": 1767874436.4814007,
"seen_count": 36,
"pos_seen": 5,
"pos_updated_ts": 1767874436.4814007,
"room_title_raw_last": "梵象名品",
"alias_raw": [
"梵象名品..."
"梵象名品...",
"梵象名品"
],
"key_kind": "norm",
"last_content": "Camudin黑水鬼系列黑盘钢带款(附带调表器)",
"last_content": "",
"last_prize_value_yuan": 999.0,
"max_prize_value_yuan": 5500.0,
"room_title": "梵象名品"
@@ -1210,19 +1211,20 @@
},
{
"first_seen_ts": 1765777950.5447316,
"last_seen_ts": 1765802039.672463,
"seen_count": 10,
"pos_seen": 0,
"pos_updated_ts": 1765802039.672463,
"room_title_raw_last": "云上珠宝",
"last_seen_ts": 1767856444.9584792,
"seen_count": 12,
"pos_seen": 2,
"pos_updated_ts": 1767856444.9584792,
"room_title_raw_last": "云上珠宝-。",
"alias_raw": [
"云上珠宝..",
"云上珠宝...",
"云上珠宝"
"云上珠宝",
"云上珠宝-。"
],
"key_kind": "norm",
"last_content": "【云上珠宝专属】iPhone17256GB颜色随机发",
"last_prize_value_yuan": 5999.0,
"last_content": "",
"last_prize_value_yuan": 599.0,
"max_prize_value_yuan": 5999.0,
"room_title": "云上珠宝"
},
@@ -1546,10 +1548,10 @@
},
{
"first_seen_ts": 1767853071.4178188,
"last_seen_ts": 1767853071.4178188,
"seen_count": 1,
"last_seen_ts": 1767864679.9977684,
"seen_count": 2,
"pos_seen": 0,
"pos_updated_ts": 1767853071.4178188,
"pos_updated_ts": 1767864679.9977684,
"room_title_raw_last": "陈二废姐",
"alias_raw": [
"陈二废姐"
@@ -1562,13 +1564,14 @@
},
{
"first_seen_ts": 1767853118.7645984,
"last_seen_ts": 1767853118.7645984,
"seen_count": 1,
"last_seen_ts": 1767868428.5824234,
"seen_count": 16,
"pos_seen": 1,
"pos_updated_ts": 1767853118.7645984,
"room_title_raw_last": "带娃的小。。",
"pos_updated_ts": 1767868428.5824234,
"room_title_raw_last": "带娃的小。",
"alias_raw": [
"带娃的小。。"
"带娃的小。。",
"带娃的小。"
],
"key_kind": "norm",
"last_content": "",
@@ -1578,10 +1581,10 @@
},
{
"first_seen_ts": 1767853143.7722397,
"last_seen_ts": 1767853143.7722397,
"seen_count": 1,
"pos_seen": 2,
"pos_updated_ts": 1767853143.7722397,
"last_seen_ts": 1767859934.4398284,
"seen_count": 3,
"pos_seen": 13,
"pos_updated_ts": 1767859934.4398284,
"room_title_raw_last": "隋心",
"alias_raw": [
"隋心"
@@ -1594,10 +1597,10 @@
},
{
"first_seen_ts": 1767853185.2990494,
"last_seen_ts": 1767853185.2990494,
"seen_count": 1,
"pos_seen": 4,
"pos_updated_ts": 1767853185.2990494,
"last_seen_ts": 1767873676.0195742,
"seen_count": 26,
"pos_seen": 8,
"pos_updated_ts": 1767873676.0195742,
"room_title_raw_last": "作业帮数",
"alias_raw": [
"作业帮数"
@@ -1607,6 +1610,378 @@
"last_prize_value_yuan": 899.0,
"max_prize_value_yuan": 899.0,
"room_title": "作业帮数"
},
{
"first_seen_ts": 1767855835.1611204,
"last_seen_ts": 1767855835.1611204,
"seen_count": 1,
"pos_seen": 6,
"pos_updated_ts": 1767855835.1611204,
"room_title_raw_last": "逍遥珠宝",
"alias_raw": [
"逍遥珠宝"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 11888.0,
"max_prize_value_yuan": 11888.0,
"room_title": "逍遥珠宝"
},
{
"first_seen_ts": 1767855960.0764549,
"last_seen_ts": 1767866180.336872,
"seen_count": 8,
"pos_seen": 1,
"pos_updated_ts": 1767866180.336872,
"room_title_raw_last": "陈三废姐",
"alias_raw": [
"陈三废姐。。",
"陈三废姐"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 5999.0,
"max_prize_value_yuan": 5999.0,
"room_title": "陈三废姐"
},
{
"first_seen_ts": 1767856135.4817257,
"last_seen_ts": 1767874037.5480306,
"seen_count": 25,
"pos_seen": 2,
"pos_updated_ts": 1767874037.5480306,
"room_title_raw_last": "六号折扣",
"alias_raw": [
"六号折扣"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 999.0,
"max_prize_value_yuan": 999.0,
"room_title": "六号折扣"
},
{
"first_seen_ts": 1767856459.5144966,
"last_seen_ts": 1767856459.5144966,
"seen_count": 1,
"pos_seen": 2,
"pos_updated_ts": 1767856459.5144966,
"room_title_raw_last": "云_珠宅-。",
"alias_raw": [
"云_珠宅-。"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 599.0,
"max_prize_value_yuan": 599.0,
"room_title": "云珠宅"
},
{
"first_seen_ts": 1767856473.6619074,
"last_seen_ts": 1767856473.6619074,
"seen_count": 1,
"pos_seen": 2,
"pos_updated_ts": 1767856473.6619074,
"room_title_raw_last": "云_珠宰-.",
"alias_raw": [
"云_珠宰-."
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 599.0,
"max_prize_value_yuan": 599.0,
"room_title": "云珠宰"
},
{
"first_seen_ts": 1767858236.204543,
"last_seen_ts": 1767865961.3910372,
"seen_count": 7,
"pos_seen": 6,
"pos_updated_ts": 1767865961.3910372,
"room_title_raw_last": "千寻Chihirc",
"alias_raw": [
"千寻Chihirc"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 999.0,
"max_prize_value_yuan": 999.0,
"room_title": "千寻Chihirc"
},
{
"first_seen_ts": 1767858658.414667,
"last_seen_ts": 1767858658.414667,
"seen_count": 1,
"pos_seen": 13,
"pos_updated_ts": 1767858658.414667,
"room_title_raw_last": "云,珠宝-。",
"alias_raw": [
"云,珠宝-。"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 3599.0,
"max_prize_value_yuan": 3599.0,
"room_title": "云珠宝"
},
{
"first_seen_ts": 1767859233.776078,
"last_seen_ts": 1767859233.776078,
"seen_count": 1,
"pos_seen": 1,
"pos_updated_ts": 1767859233.776078,
"room_title_raw_last": "千寻Chhirc",
"alias_raw": [
"千寻Chhirc"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 999.0,
"max_prize_value_yuan": 999.0,
"room_title": "千寻Chhirc"
},
{
"first_seen_ts": 1767860568.8340526,
"last_seen_ts": 1767860568.8340526,
"seen_count": 1,
"pos_seen": 16,
"pos_updated_ts": 1767860568.8340526,
"room_title_raw_last": "小饼干",
"alias_raw": [
"小饼干"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 1199.0,
"max_prize_value_yuan": 1199.0,
"room_title": "小饼干"
},
{
"first_seen_ts": 1767860740.130303,
"last_seen_ts": 1767862700.7655778,
"seen_count": 2,
"pos_seen": 0,
"pos_updated_ts": 1767862700.7655778,
"room_title_raw_last": "陈=废姐",
"alias_raw": [
"陈-废姐",
"陈=废姐"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 5999.0,
"max_prize_value_yuan": 5999.0,
"room_title": "陈废姐"
},
{
"first_seen_ts": 1767861173.7718217,
"last_seen_ts": 1767861173.7718217,
"seen_count": 1,
"pos_seen": 4,
"pos_updated_ts": 1767861173.7718217,
"room_title_raw_last": "干寻Chihirc",
"alias_raw": [
"干寻Chihirc"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 999.0,
"max_prize_value_yuan": 999.0,
"room_title": "干寻Chihirc"
},
{
"first_seen_ts": 1767861564.7434275,
"last_seen_ts": 1767861564.7434275,
"seen_count": 1,
"pos_seen": 0,
"pos_updated_ts": 1767861564.7434275,
"room_title_raw_last": "陈三度姐",
"alias_raw": [
"陈三度姐"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 5999.0,
"max_prize_value_yuan": 5999.0,
"room_title": "陈三度姐"
},
{
"first_seen_ts": 1767863279.932139,
"last_seen_ts": 1767871705.4416816,
"seen_count": 22,
"pos_seen": 8,
"pos_updated_ts": 1767871705.4416816,
"room_title_raw_last": "汀南紫砂",
"alias_raw": [
"汀南紫砂"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 666.0,
"max_prize_value_yuan": 2000.0,
"room_title": "汀南紫砂"
},
{
"first_seen_ts": 1767863353.2598321,
"last_seen_ts": 1767863353.2598321,
"seen_count": 1,
"pos_seen": 0,
"pos_updated_ts": 1767863353.2598321,
"room_title_raw_last": "陈兰废姐。",
"alias_raw": [
"陈兰废姐。"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 5999.0,
"max_prize_value_yuan": 5999.0,
"room_title": "陈兰废姐"
},
{
"first_seen_ts": 1767863974.4459054,
"last_seen_ts": 1767873873.8282998,
"seen_count": 6,
"pos_seen": 8,
"pos_updated_ts": 1767873873.8282998,
"room_title_raw_last": "交个朋友。",
"alias_raw": [
"交个朋友",
"交个朋友。"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 599.0,
"max_prize_value_yuan": 1199.0,
"room_title": "交个朋友"
},
{
"first_seen_ts": 1767865560.0796092,
"last_seen_ts": 1767865560.0796092,
"seen_count": 1,
"pos_seen": 5,
"pos_updated_ts": 1767865560.0796092,
"room_title_raw_last": "义乌奢库",
"alias_raw": [
"义乌奢库"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 1980.0,
"max_prize_value_yuan": 1980.0,
"room_title": "义乌奢库"
},
{
"first_seen_ts": 1767866852.0270154,
"last_seen_ts": 1767874062.7254236,
"seen_count": 22,
"pos_seen": 3,
"pos_updated_ts": 1767874062.7254236,
"room_title_raw_last": "琦儿",
"alias_raw": [
"琦儿"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 1699.0,
"max_prize_value_yuan": 1699.0,
"room_title": "琦儿"
},
{
"first_seen_ts": 1767868253.7173963,
"last_seen_ts": 1767868253.7173963,
"seen_count": 1,
"pos_seen": 5,
"pos_updated_ts": 1767868253.7173963,
"room_title_raw_last": "作业耜数",
"alias_raw": [
"作业耜数"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 899.0,
"max_prize_value_yuan": 899.0,
"room_title": "作业耜数"
},
{
"first_seen_ts": 1767868287.19223,
"last_seen_ts": 1767868308.9907572,
"seen_count": 2,
"pos_seen": 4,
"pos_updated_ts": 1767868308.9907572,
"room_title_raw_last": "交今朋友",
"alias_raw": [
"交今朋友。",
"交今朋友"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 1199.0,
"max_prize_value_yuan": 1199.0,
"room_title": "交今朋友"
},
{
"first_seen_ts": 1767872540.741122,
"last_seen_ts": 1767872540.741122,
"seen_count": 1,
"pos_seen": 0,
"pos_updated_ts": 1767872540.741122,
"room_title_raw_last": "琦",
"alias_raw": [
"琦"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 1699.0,
"max_prize_value_yuan": 1699.0,
"room_title": "琦"
},
{
"first_seen_ts": 1767873528.6011586,
"last_seen_ts": 1767873776.7842386,
"seen_count": 2,
"pos_seen": 5,
"pos_updated_ts": 1767873776.7842386,
"room_title_raw_last": "户外发",
"alias_raw": [
"户外发"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 999.0,
"max_prize_value_yuan": 999.0,
"room_title": "户外发"
},
{
"first_seen_ts": 1767873899.5342953,
"last_seen_ts": 1767873899.5342953,
"seen_count": 1,
"pos_seen": 9,
"pos_updated_ts": 1767873899.5342953,
"room_title_raw_last": "Entertain_",
"alias_raw": [
"Entertain_"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 799.0,
"max_prize_value_yuan": 799.0,
"room_title": "Entertain"
},
{
"first_seen_ts": 1767874286.8196697,
"last_seen_ts": 1767874286.8196697,
"seen_count": 1,
"pos_seen": 2,
"pos_updated_ts": 1767874286.8196697,
"room_title_raw_last": "琦川",
"alias_raw": [
"琦川"
],
"key_kind": "norm",
"last_content": "",
"last_prize_value_yuan": 1699.0,
"max_prize_value_yuan": 1699.0,
"room_title": "琦川"
}
]
}
+12 -7
View File
@@ -5,47 +5,52 @@
"""
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
def test_delays():
"""测试延迟设置是否正确"""
print("=== 测试延迟设置 ===")
# 检查代码中是否包含正确的延迟调用
with open('douyin/other/douyin_yanghao.py', 'r', encoding='utf-8') as f:
with open("douyin/other/douyin_yanghao.py", "r", encoding="utf-8") as f:
content = f.read()
# 检查点击爱心前的延迟
if 'analyser.operation.delay(1.0) # 点击前延迟1秒' in content:
if "analyser.operation.delay(1.0) # 点击前延迟1秒" in content:
print("✅ 爱心点击前延迟1秒 - 正确")
else:
print("❌ 爱心点击前延迟未找到")
# 检查点击爱心后的延迟
if 'analyser.operation.delay(1.0) # 点击后延迟1秒' in content:
if "analyser.operation.delay(1.0) # 点击后延迟1秒" in content:
print("✅ 爱心点击后延迟1秒 - 正确")
else:
print("❌ 爱心点击后延迟未找到")
# 检查点击收藏前的延迟
if content.count('analyser.operation.delay(1.0) # 点击前延迟1秒') >= 2:
if content.count("analyser.operation.delay(1.0) # 点击前延迟1秒") >= 2:
print("✅ 收藏点击前延迟1秒 - 正确")
else:
print("❌ 收藏点击前延迟未找到")
# 检查点击收藏后的延迟
if content.count('analyser.operation.delay(1.0) # 点击后延迟1秒') >= 2:
if content.count("analyser.operation.delay(1.0) # 点击后延迟1秒") >= 2:
print("✅ 收藏点击后延迟1秒 - 正确")
else:
print("❌ 收藏点击后延迟未找到")
# 检查推荐页流程的延迟
if content.count('analyser.operation.delay(1.0)') >= 4: # 2个点击延迟 + 2个推荐页延迟
if (
content.count("analyser.operation.delay(1.0)") >= 4
): # 2个点击延迟 + 2个推荐页延迟
print("✅ 推荐页流程延迟1秒 - 正确")
else:
print("❌ 推荐页流程延迟不完整")
print("\n=== 延迟设置验证完成 ===")
if __name__ == "__main__":
test_delays()
test_delays()
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""购物红包识别功能测试脚本"""
import sys
import os
from PIL import Image
import numpy as np
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from douyin.detection.douyin_pixel import detect_redpacket_popup_background
from douyin.other.douyin_popups import check_shopping_redpacket_popup
from douyin.fudai.core.coords import SHOPPING_REDPACKET_AREA, STAGE_RED_PACKET_OCR, DIAG_SHOPPING_REDPACKET
def test_pixel_detection():
"""测试像素检测函数"""
print("=" * 60)
print("测试1: 像素检测函数")
print("=" * 60)
# 创建测试图像:模拟购物红包(红色背景)
width, height = 1080, 2400
test_img = Image.new('RGB', (width, height), color=(255, 255, 255))
pixels = test_img.load()
# 在中央区域添加红色像素(模拟购物红包)
red_color = (230, 80, 80) # 红色
for y in range(400, 1200):
for x in range(300, 780):
# 80%的像素为红色,20%为其他颜色
if (x + y) % 5 != 0:
pixels[x, y] = red_color
result = detect_redpacket_popup_background(test_img)
print(f"红色像素检测结果: {result}")
print(f"预期: True (因为有超过15%的红色像素)")
print()
return result
def test_coordinates():
"""测试坐标定义"""
print("=" * 60)
print("测试2: 坐标定义")
print("=" * 60)
print(f"SHOPPING_REDPACKET_AREA: {SHOPPING_REDPACKET_AREA}")
print(f"STAGE_RED_PACKET_OCR: {STAGE_RED_PACKET_OCR}")
print(f"DIAG_SHOPPING_REDPACKET: {DIAG_SHOPPING_REDPACKET}")
# 验证坐标范围
x1, y1, x2, y2 = DIAG_SHOPPING_REDPACKET
print(f"\n诊断区域范围:")
print(f" X: {x1} - {x2} (宽度: {x2-x1})")
print(f" Y: {y1} - {y2} (高度: {y2-y1})")
# 检查坐标是否有效
if x1 < x2 and y1 < y2:
print("✓ 坐标范围有效")
else:
print("✗ 坐标范围无效")
print()
def test_ocr_keywords():
"""测试OCR关键词"""
print("=" * 60)
print("测试3: OCR关键词检查")
print("=" * 60)
# 测试文本
test_texts = [
"邀你搶購物紅包",
"搶購物紅包",
"購物紅包",
"邀你搶",
"搶紅包",
"搶",
"最高領取",
"邀你抢",
"购物红包",
"抢红包",
"最高领取",
"抢",
]
# 关键词列表(与douyin_popups.py中的保持一致)
keywords = [
'邀你搶購物紅包', '搶購物紅包', '購物紅包', '邀你搶',
'搶紅包', '搶', '最高領取',
'邀你抢', '购物红包', '抢红包', '抢', '最高领取'
]
print(f"定义的关键词数量: {len(keywords)}")
print("关键词列表:")
for kw in keywords:
print(f" - {kw}")
print("\n测试文本匹配:")
for text in test_texts:
matched = any(kw in text for kw in keywords)
status = "✓" if matched else "✗"
print(f" {status} '{text}'")
print()
def create_redpacket_test_image():
"""创建一个测试用的购物红包图像"""
print("=" * 60)
print("创建测试图像")
print("=" * 60)
# 创建1080x2400的图像
img = Image.new('RGB', (1080, 2400), color=(255, 255, 255))
pixels = img.load()
# 在中央画一个红色矩形(模拟购物红包)
red_color = (230, 80, 80)
for y in range(400, 1400):
for x in range(300, 780):
pixels[x, y] = red_color
# 保存图像
test_img_path = os.path.join(os.path.dirname(__file__), 'test_redpacket.png')
img.save(test_img_path)
print(f"✓ 测试图像已保存: {test_img_path}")
print()
return test_img_path
if __name__ == '__main__':
print("\n")
print("╔" + "=" * 58 + "╗")
print("║" + " " * 58 + "║")
print("║" + "购物红包识别功能测试".center(58) + "║")
print("║" + " " * 58 + "║")
print("╚" + "=" * 58 + "╝")
print()
# 运行所有测试
test_coordinates()
test_ocr_keywords()
result = test_pixel_detection()
test_img_path = create_redpacket_test_image()
# 总结
print("=" * 60)
print("测试总结")
print("=" * 60)
print(f"✓ 像素检测函数: {'可用' if result else '无法检测'}")
print(f"✓ 坐标定义: 已更新到中央区域")
print(f"✓ OCR关键词: 12个关键词已定义(传统+简体中文)")
print(f"✓ 测试图像: {test_img_path}")
print()
print("下一步:")
print(" 1. 在实际应用中测试购物红包识别")
print(" 2. 查看 logs/actions.log 中的调试信息")
print(" 3. 验证像素检测和OCR识别是否都能触发")
print()
+21 -11
View File
@@ -5,8 +5,10 @@
"""
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
def test_detect_icon_logic():
"""直接测试 _detect_icon 的核心逻辑"""
print("=== 测试 _detect_icon 核心逻辑 ===")
@@ -28,7 +30,9 @@ def test_detect_icon_logic():
def _scale_from_base(self, x, y):
return x, y
def _capture_roi_screenshot(self, roi_label, sx, sy, roi_px, shared_screenshot_path):
def _capture_roi_screenshot(
self, roi_label, sx, sy, roi_px, shared_screenshot_path
):
print(f"✅ 截图 ROI: {roi_label} at ({sx}, {sy}) size {roi_px}")
return f"/tmp/test_roi_{roi_label}.png"
@@ -46,7 +50,11 @@ def test_detect_icon_logic():
roi_size = analyser.yanghao_icon_roi_size
scale_x = analyser.resolution_ratio_x / 1080.0
scale_y = analyser.resolution_ratio_y / 2400.0
action_scale = analyser.yanghao_like_roi_scale if action == "爱心" else analyser.yanghao_fav_roi_scale
action_scale = (
analyser.yanghao_like_roi_scale
if action == "爱心"
else analyser.yanghao_fav_roi_scale
)
roi_px = max(1, int(roi_size * max(scale_x, scale_y) * float(action_scale)))
print(f" ROI 大小: {roi_px}px")
@@ -61,18 +69,18 @@ def test_detect_icon_logic():
return detected, score
# 测试爱心图标检测
like_ok, like_score = mock_detect_icon(
"爱心", 950, 1872, "", "action_like_roi"
)
like_ok, like_score = mock_detect_icon("爱心", 950, 1872, "", "action_like_roi")
# 测试收藏图标检测
fav_ok, fav_score = mock_detect_icon(
"收藏", 842, 1872, "", "action_fav_roi"
)
fav_ok, fav_score = mock_detect_icon("收藏", 842, 1872, "", "action_fav_roi")
print("\n🎯 测试结果:")
print(f" 爱心图标: {'✅ 检测成功' if like_ok else '❌ 检测失败'} (score={like_score})")
print(f" 收藏图标: {'✅ 检测成功' if fav_ok else '❌ 检测失败'} (score={fav_score})")
print(
f" 爱心图标: {'✅ 检测成功' if like_ok else '❌ 检测失败'} (score={like_score})"
)
print(
f" 收藏图标: {'✅ 检测成功' if fav_ok else '❌ 检测失败'} (score={fav_score})"
)
if like_ok and fav_ok:
print("✅ 核心逻辑测试通过:图标检测总是成功,符合修改要求")
@@ -81,6 +89,7 @@ def test_detect_icon_logic():
return like_ok and fav_ok
def test_click_logic():
"""测试点击逻辑"""
print("\n=== 测试点击逻辑 ===")
@@ -125,6 +134,7 @@ def test_click_logic():
print("❌ 点击逻辑测试失败")
return False
if __name__ == "__main__":
print("🚀 开始测试养号功能修改")
print("=" * 50)
@@ -146,4 +156,4 @@ if __name__ == "__main__":
print(" - 点击动作:在配置坐标上正确执行")
print(" - 概率控制:根据配置概率决定是否执行动作")
else:
print("\n❌ 部分测试失败,需要检查代码修改")
print("\n❌ 部分测试失败,需要检查代码修改")
+11 -2
View File
@@ -5,8 +5,10 @@
"""
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
# 模拟 analyser 对象
class MockAnalyser:
def __init__(self):
@@ -24,13 +26,17 @@ class MockAnalyser:
def _scale_from_base(self, x, y):
return x, y
def _capture_roi_screenshot(self, roi_label, sx, sy, roi_px, shared_screenshot_path):
def _capture_roi_screenshot(
self, roi_label, sx, sy, roi_px, shared_screenshot_path
):
print(f"[测试] 截图 ROI: {roi_label} at ({sx}, {sy}) size {roi_px}")
return f"/tmp/test_roi_{roi_label}.png"
# 导入测试函数
from douyin.other.douyin_yanghao import yanghao_idle
def test_detect_icon():
"""测试 _detect_icon 函数"""
print("=== 测试 _detect_icon 函数 ===")
@@ -55,6 +61,7 @@ def test_detect_icon():
print("✅ _detect_icon 函数测试完成")
def test_yanghao_idle():
"""测试 yanghao_idle 函数(简化版)"""
print("\n=== 测试 yanghao_idle 函数 ===")
@@ -82,6 +89,7 @@ def test_yanghao_idle():
except Exception as e:
print(f"❌ yanghao_idle 函数测试失败: {e}")
class MockOperation:
def click(self, device_id, x, y):
print(f"[测试] 点击设备 {device_id} 坐标 ({x}, {y})")
@@ -92,7 +100,8 @@ class MockOperation:
def get_screenshot(self, device_id, use_service=False):
print(f"[测试] 获取设备 {device_id} 截图")
if __name__ == "__main__":
test_detect_icon()
test_yanghao_idle()
print("\n🎉 所有测试完成!")
print("\n🎉 所有测试完成!")
+54 -38
View File
@@ -8,18 +8,22 @@ import re
from collections import defaultdict
from datetime import datetime
if sys.platform == 'win32':
if sys.platform == "win32":
try:
reconfigure_func = getattr(sys.stdout, 'reconfigure', None)
reconfigure_func = getattr(sys.stdout, "reconfigure", None)
if reconfigure_func:
reconfigure_func(encoding='utf-8')
reconfigure_func(encoding="utf-8")
except Exception:
try:
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stdout = io.TextIOWrapper(
sys.stdout.buffer, encoding="utf-8", errors="replace"
)
except Exception:
pass
def analyze_elapsed_times(log_path):
"""分析日志中的耗时数据"""
if not os.path.exists(log_path):
@@ -33,7 +37,7 @@ def analyze_elapsed_times(log_path):
# 读取日志文件
try:
with open(log_path, 'r', encoding='utf-8', errors='replace') as f:
with open(log_path, "r", encoding="utf-8", errors="replace") as f:
lines = f.readlines()
except Exception as e:
print(f"读取日志文件失败: {e}")
@@ -45,55 +49,55 @@ def analyze_elapsed_times(log_path):
for line in lines:
# 查找包含 elapsed_seconds 的行
if 'elapsed_seconds=' in line:
if "elapsed_seconds=" in line:
# 提取耗时
elapsed_match = re.search(r'elapsed_seconds=([\d.]+)', line)
elapsed_match = re.search(r"elapsed_seconds=([\d.]+)", line)
if elapsed_match:
elapsed = float(elapsed_match.group(1))
# 提取步骤名称(从日志标签中提取)
step_name = "未知步骤"
if '[截图]' in line:
if "[截图]" in line:
step_name = "截图"
elif '[流程]' in line and 'run_once_basic' in line:
elif "[流程]" in line and "run_once_basic" in line:
step_name = "run_once_basic总耗时"
elif '[预约]' in line and 'process_reservation' in line:
elif "[预约]" in line and "process_reservation" in line:
step_name = "预约处理"
elif '[参与]' in line:
elif "[参与]" in line:
step_name = "参与抽奖"
elif '[弹窗处理]' in line:
elif "[弹窗处理]" in line:
step_name = "弹窗处理"
elif '[福袋详情]' in line:
elif "[福袋详情]" in line:
step_name = "福袋详情读取"
elif '[阶段诊断]' in line:
elif "[阶段诊断]" in line:
step_name = "阶段诊断"
elif '[OCR]' in line:
elif "[OCR]" in line:
step_name = "OCR识别"
elif '[滑动]' in line:
elif "[滑动]" in line:
step_name = "滑动操作"
elif '[行为]' in line:
elif "[行为]" in line:
step_name = "行为操作"
elif '[统计]' in line:
elif "[统计]" in line:
step_name = "统计记录"
elif '[自救]' in line:
elif "[自救]" in line:
step_name = "自救处理"
elif '[超时]' in line:
elif "[超时]" in line:
step_name = "超时处理"
elif 'elapsed_seconds=' in line:
elif "elapsed_seconds=" in line:
# 从消息中提取更具体的步骤
if '预约' in line:
if "预约" in line:
step_name = "预约相关"
elif 'OCR' in line or '识别' in line:
elif "OCR" in line or "识别" in line:
step_name = "OCR识别"
elif '截图' in line:
elif "截图" in line:
step_name = "截图"
elif '滑动' in line:
elif "滑动" in line:
step_name = "滑动操作"
elif '详情' in line:
elif "详情" in line:
step_name = "详情处理"
else:
# 从消息中提取
msg_match = re.search(r'\] (.+?):', line)
msg_match = re.search(r"\] (.+?):", line)
if msg_match:
step_name = msg_match.group(1).strip()
else:
@@ -128,11 +132,15 @@ def analyze_elapsed_times(log_path):
# 按平均耗时降序排序
step_stats.sort(key=lambda x: x[1], reverse=True)
print(f"{'步骤名称':<20} {'平均耗时(秒)':<12} {'最大耗时':<10} {'最小耗时':<10} {'次数':<6}")
print(
f"{'步骤名称':<20} {'平均耗时(秒)':<12} {'最大耗时':<10} {'最小耗时':<10} {'次数':<6}"
)
print("-" * 80)
for step, avg_time, max_time, min_time, count in step_stats:
print(f"{step:<20} {avg_time:<12.2f} {max_time:<10.2f} {min_time:<10.2f} {count:<6}")
print(
f"{step:<20} {avg_time:<12.2f} {max_time:<10.2f} {min_time:<10.2f} {count:<6}"
)
print()
print("=" * 80)
@@ -149,11 +157,11 @@ def analyze_elapsed_times(log_path):
# 找到对应的日志行
log_snippet = ""
for line in lines:
if f'elapsed_seconds={elapsed}' in line and step in line:
if f"elapsed_seconds={elapsed}" in line and step in line:
# 提取有意义的部分
parts = line.split('] ')
parts = line.split("] ")
if len(parts) > 1:
log_snippet = parts[1].split(' elapsed_seconds')[0][:50]
log_snippet = parts[1].split(" elapsed_seconds")[0][:50]
break
print(f"{step:<20} {elapsed:<10.2f} {log_snippet:<50}")
@@ -166,23 +174,30 @@ def analyze_elapsed_times(log_path):
if step_stats:
slowest_step = step_stats[0]
if slowest_step[1] > 5.0:
print(f"⚠️ 最耗时的步骤 '{slowest_step[0]}' 平均耗时 {slowest_step[1]:.2f}秒,建议优化")
print(
f"⚠️ 最耗时的步骤 '{slowest_step[0]}' 平均耗时 {slowest_step[1]:.2f}秒,建议优化"
)
elif slowest_step[1] > 2.0:
print(f"⚠️ 最耗时的步骤 '{slowest_step[0]}' 平均耗时 {slowest_step[1]:.2f}秒,需要关注")
print(
f"⚠️ 最耗时的步骤 '{slowest_step[0]}' 平均耗时 {slowest_step[1]:.2f}秒,需要关注"
)
else:
print("✅ 各步骤耗时都在合理范围内")
# 检查是否有异常耗时的记录
abnormal_records = [t for t in total_elapsed_times if t[1] > 10.0]
if abnormal_records:
print(f"⚠️ 发现 {len(abnormal_records)} 条异常耗时记录(>10秒),可能存在性能问题")
print(
f"⚠️ 发现 {len(abnormal_records)} 条异常耗时记录(>10秒),可能存在性能问题"
)
def main():
# 默认日志文件路径
log_files = [
"logs/unified.log",
"logs/unified_2025-12-31.log",
f"logs/unified_{datetime.now().strftime('%Y-%m-%d')}.log"
f"logs/unified_{datetime.now().strftime('%Y-%m-%d')}.log",
]
log_path = None
@@ -202,5 +217,6 @@ def main():
print(f"分析日志文件: {log_path}")
analyze_elapsed_times(log_path)
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()