Refactor code structure for improved readability and maintainability

This commit is contained in:
Your Name committed 2026-01-11 23:31:38 +08:00
1 parent 7e5d88d3f1
commit 54f3b35a26
14 files changed
+2054 -562

No files matched your search

+69 -22
View File
@@ -551,6 +551,7 @@ class underlying_operations:
pass
except Exception:
pass
service_success = False
# 如果启用服务模式,使用后台截图服务;若服务不可用或返回 False,则回退到直接截图
if use_service:
try:
@@ -574,8 +575,7 @@ class underlying_operations:
)
try:
service_result = service.get_screenshot(device_id, force=False)
if service_result:
if service.get_screenshot(device_id, force=False):
dur = (time_module.time() - start_ts) * 1000.0
logging.info(
"[截图] 使用后台服务耗时(ms)=%.1f device=%s", dur, device_id
@@ -612,7 +612,7 @@ class underlying_operations:
except Exception:
pass
# do not return here; let final return at function end
result = True
service_success = True
else:
timetag = datetime.now().strftime("%H:%M:%S")
logging.info(
@@ -627,8 +627,7 @@ class underlying_operations:
timetag,
e,
)
# ensure result exists
result = False
service_success = False
except ImportError as e:
timetag = datetime.now().strftime("%H:%M:%S")
logging.warning(
@@ -636,19 +635,18 @@ class underlying_operations:
timetag,
e,
)
result = False
service_success = False
except Exception as e:
timetag = datetime.now().strftime("%H:%M:%S")
logging.warning(
"[%s] [截图操作] 服务模式不可用,回退到直接截图: %s", timetag, e
)
result = False
service_success = False
# 原有的直接截图逻辑(保持向后兼容),测量其耗时
try:
# If result already set by service branch, skip direct call
if "result" in locals() and locals()["result"] is True:
# already successful via service
if service_success:
final_result = True
else:
final_result = self._get_screenshot_direct(device_id, path)
@@ -798,6 +796,12 @@ class underlying_operations:
# 优先走 exec-out:只需 1 次 adb 调用;不在手机端落盘,减少 I/O 与卡顿
# 为避免被并发读取到"半写入文件",写入 tmp 后再原子替换。
execout_timeout_sec = float(os.environ.get("ADB_EXECOUT_TIMEOUT_SEC", "10"))
execout_warn_after_sec = float(os.environ.get("ADB_EXECOUT_WARN_AFTER_SEC", "3"))
execout_heartbeat_interval_sec = float(
os.environ.get("ADB_EXECOUT_HEARTBEAT_INTERVAL_SEC", "5")
)
execout_heartbeat_max = int(os.environ.get("ADB_EXECOUT_HEARTBEAT_MAX", "3"))
for attempt in range(2):
try:
cleanup_start = time_module.time()
@@ -821,24 +825,58 @@ class underlying_operations:
bufsize=0, # 无缓冲,立即传输
)
# 使用更大的缓冲区(256KB)提高写入效率
if process.stdout is None:
raise RuntimeError("ADB process stdout is None")
with open(tmp_file, "wb", buffering=262144) as f:
while True:
chunk = process.stdout.read(262144) # 256KB chunks
if not chunk:
break
f.write(chunk)
# 注意:Windows 上 stdout.read() 可能永久阻塞(adb 卡住时不会退出),导致 wait(timeout=...) 永远到不了。
# 这里用 communicate(timeout=...) 保证超时可触发,从而进入重试/回退方案。
done_event = None
watchdog_thread = None
try:
import threading
# 等待进程完成
return_code = process.wait(timeout=10)
if return_code != 0:
done_event = threading.Event()
def _watchdog() -> None:
try:
if execout_warn_after_sec > 0:
if done_event.wait(timeout=execout_warn_after_sec):
return
start_wait = time_module.time()
for i in range(max(0, execout_heartbeat_max)):
if done_event.is_set():
return
waited = (time_module.time() - start_wait) * 1000.0
logging.warning(
"[截图] exec-out 仍在进行中:已等待(ms)=%.0f device=%s attempt=%s",
waited,
device_id,
attempt + 1,
)
if done_event.wait(
timeout=max(0.5, execout_heartbeat_interval_sec)
):
return
except Exception:
return
watchdog_thread = threading.Thread(
target=_watchdog, name="adb-execout-watchdog", daemon=True
)
watchdog_thread.start()
except Exception:
done_event = None
stdout_data, _ = process.communicate(timeout=execout_timeout_sec)
if done_event is not None:
done_event.set()
if process.returncode != 0:
raise subprocess.CalledProcessError(
return_code,
process.returncode,
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
)
with open(tmp_file, "wb", buffering=262144) as f:
f.write(stdout_data)
adb_subprocess_dur = (time_module.time() - adb_start) * 1000.0
# 合并ADB subprocess耗时到最终汇总日志中,不单独输出
@@ -847,6 +885,15 @@ class underlying_operations:
# 这样可以减少 10-50ms 的等待时间
except subprocess.TimeoutExpired:
process.kill()
try:
process.communicate(timeout=1)
except Exception:
pass
try:
if done_event is not None:
done_event.set()
except Exception:
pass
raise
validate_tmp_start = time_module.time()
+2 -2
View File
@@ -31,8 +31,8 @@
"fudai_icon_max_wait_seconds": 5.0,
"fudai_icon_retry_delay_seconds": 0.1,
"fudai_exit_after_misses": 10,
"enable_back_on_misses": false,
"fudai_click_wait_seconds": 1.6,
"enable_back_on_misses": true,
"fudai_click_wait_seconds": 1.2,
"fudai_detail_initial_wait_seconds": 0.8,
"fudai_detail_verified_wait_seconds": 0.2,
"fudai_detail_retry_delay_seconds": 0.5,
+9 -4
View File
@@ -319,6 +319,7 @@ class fudai_analyse:
None # 上次读取的福袋详情
)
self._current_fudai_future_ts: float = 0.0 # 当前福袋的开奖时间戳
self._current_fudai_content: str = "" # 当前福袋的内容标识
self._fudai_detail_first_read: bool = False # 是否第一次读取福袋详情
self._fudai_detail_consecutive_failures: int = 0 # 连续失败次数
self._detail_closed_by_attend: bool = False # 详情页是否由参与操作关闭
@@ -2599,8 +2600,9 @@ class fudai_analyse:
# 重新读取后,更新保存的详情数据
if detail and isinstance(detail, tuple) and len(detail) >= 6:
self._last_fudai_detail_tuple = detail
# 设置当前福袋的 content
self._current_fudai_content = detail[0] if len(detail) > 0 else ""
# 设置当前福袋的 content(使用 cast 帮助静态分析)
detail_t: Tuple[Any, ...] = tuple(detail)
self._current_fudai_content = detail_t[0] if len(detail_t) > 0 else ""
else:
# 使用第一次保存的详情数据,设置当前福袋的倒计时信息
try:
@@ -2611,8 +2613,10 @@ class fudai_analyse:
and isinstance(detail, tuple)
and len(detail) >= 6
):
# 使用 cast 明确 detail 的类型,避免静态分析报 unsubscriptable
detail_t: Tuple[Any, ...] = tuple(detail)
# detail 已校验为 tuple 且长度足够,可直接索引读取倒计时信息
countdown_tuple = detail[5] # type: ignore[index]
countdown_tuple = detail_t[5]
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
@@ -2622,7 +2626,7 @@ class fudai_analyse:
# 设置当前福袋的 future_ts 和 content,供 attend_choujiang 使用
self._current_fudai_future_ts = future_ts
self._current_fudai_content = (
detail[0] if len(detail) > 0 else ""
detail_t[0] if len(detail_t) > 0 else ""
)
self._log_kv(
"参与",
@@ -2835,6 +2839,7 @@ class fudai_analyse:
else None
),
join_ahead_threshold=join_ahead_seconds,
level="DEBUG",
)
except Exception:
pass
+1 -1
View File
@@ -251,7 +251,7 @@ def detect_redpacket_popup_background(
red_ratio = red_pixels / total_pixels if total_pixels > 0 else 0
# 阈值:至少15%的像素满足红色特征
result = red_ratio > 0.15
result = bool(red_ratio > 0.15)
if return_info:
reason_value: Optional[str] = (
+47 -4
View File
@@ -77,7 +77,24 @@ def attend_choujiang(analyser) -> bool:
analyser.operation.analyse_pic_word(use_name, 1) or ""
)
analyser._log_kv("参与", "识别参与按钮", text=attend_button_text)
if (
if attend_button_text and "不满足参与条件" in attend_button_text:
analyser.last_attend_fail_reason = "condition_not_met"
analyser._log_kv("参与", "不满足参与条件,直接放弃", result="不满足条件")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="condition_not_met",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif (
attend_button_text and "参与成功" in attend_button_text
): # 如果识别到已经参与抽奖
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
@@ -190,13 +207,17 @@ def attend_choujiang(analyser) -> bool:
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return True
elif attend_button_text and (
("活动已结束" in attend_button_text) or ("活动己结束" in attend_button_text)
("活动已结束" in attend_button_text) or
("活动己结束" in attend_button_text) or
("福袋超时" in attend_button_text) or
("活动超时" in attend_button_text) or
("已超时" in attend_button_text)
):
# 活动结束:按一次返回键退出详情
# 活动结束/福袋超时:按一次返回键退出详情
analyser.last_attend_fail_reason = "activity_ended"
try:
analyser._log_kv(
"参与", "活动已结束:按返回键退出详情", result="activity_ended"
"参与", "活动已结束/福袋超时:按返回键退出详情", result="activity_ended"
)
except Exception:
pass
@@ -257,6 +278,17 @@ def attend_choujiang(analyser) -> bool:
return False
elif attend_button_text and "时长不足" in attend_button_text:
analyser._log_kv("参与", "无法参与(看播时长不足)", result="时长不足")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="watch_duration_insufficient",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
@@ -1506,4 +1538,15 @@ def attend_choujiang(analyser) -> bool:
last_text=attend_button_text or "", # type: ignore[possibly-unbound]
result="参与失败",
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="button_not_recognized",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
return False
+1
View File
@@ -935,6 +935,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
int(remain_seconds) if remain_seconds is not None else None
),
join_ahead_threshold=join_ahead_seconds,
level="DEBUG",
)
except Exception:
pass
+297 -248
View File
@@ -90,10 +90,10 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
# 轻重分流模式:auto(缺失字段才跑重)、light(只跑轻)、heavy(轻后必跑重)
try:
ocr_mode = str(
getattr(analyser, "fudai_detail_ocr_mode", "auto") or "auto"
).lower()
getattr(analyser, "fudai_detail_ocr_mode", "light") or "light"
).lower() # 优化:默认使用light模式,提升性能
except Exception:
ocr_mode = "auto"
ocr_mode = "light"
force_light = ocr_mode == "light"
force_heavy = ocr_mode == "heavy"
@@ -5398,284 +5398,333 @@ def basic_join_decision(
# 记录预约,并检查队列是否已满
queue_full_flag = [False]
def _add_reservation_with_flag(q, item):
queue_full_flag[0] = douyin_reservation_logic.add_reservation_core_logic( # type: ignore[attr-defined]
q,
item,
max_reservations=int(
getattr(
analyser, "high_value_fudai_max_reservations", 3
)
or 3
),
analyser=analyser,
write_state_callback=_write_reservation_state,
)
# 获取任务数量和其他详情信息(从阶段检测结果获取)
task_count = 2 # 默认2个任务
time_text = ""
participants = 0
copies = 0
# 检查预约队列中是否已经存在相同的福袋(避免重复记录)
already_reserved = False
try:
# 从 detail tuple 中获取信息
if isinstance(detail, tuple) and len(detail) >= 6:
time_text = str(detail[1] or "")
participants = int(detail[2] or 0)
copies = int(detail[3] or 0)
if reservations:
for r in reservations:
r_ft = float(r.get("future_ts") or 0.0)
r_content = str(r.get("content") or "")
r_room_title = str(r.get("room_title") or "")
# 检查是否是同一个福袋:开奖时间相同且内容相同
if abs(r_ft - future_ts) < 5.0 and r_content == content:
already_reserved = True
try:
analyser._log_kv(
"预约",
"basic_join_decision:福袋已在预约队列中,跳过重复记录",
future_ts=int(future_ts),
content=content[:50] if content else "",
existing_future_ts=int(r_ft),
existing_content=r_content[:50] if r_content else "",
)
except Exception:
pass
break
except Exception as e:
try:
analyser._log_kv(
"预约",
"basic_join_decision:检查重复预约时出错,继续记录",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
# 从阶段检测结果获取任务数量
task_count_from_stage = getattr(
analyser, "_fudai_detail_task_count_from_stage", None
)
if task_count_from_stage is not None:
task_count = int(task_count_from_stage or 2)
# 清除标志,避免影响后续调用
analyser._fudai_detail_task_count_from_stage = None
else:
# 如果阶段检测未保存任务数量,尝试通过阶段检测获取
try:
from douyin.stage import douyin_stage
# 如果已经预约过,跳过记录
if already_reserved:
try:
analyser._log_kv(
"预约",
"basic_join_decision:跳过重复预约记录",
value_yuan=prize_value_yuan,
future_ts=int(future_ts),
room_pos=room_pos,
)
except Exception:
pass
else:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
result = (
douyin_stage.diagnose_stage_from_current_screen(
analyser
def _add_reservation_with_flag(q, item):
queue_full_flag[0] = douyin_reservation_logic.add_reservation_core_logic( # type: ignore[attr-defined]
q,
item,
max_reservations=int(
getattr(
analyser, "high_value_fudai_max_reservations", 3
)
)
if result:
stage, _ = result
if stage == "FUDai_DETAIL":
# 尝试通过像素检测获取任务数量
try:
from douyin.detection import douyin_pixel
or 3
),
analyser=analyser,
write_state_callback=_write_reservation_state,
)
pic_path = os.path.join(
os.path.dirname(__file__),
"pic",
"screenshot.png",
)
if os.path.exists(pic_path):
pic = Image.open(pic_path)
pic_rgb = pic.convert("RGB")
rx = int(
getattr(
analyser,
"resolution_ratio_x",
1080,
)
or 1080
# 获取任务数量和其他详情信息(从阶段检测结果获取)
task_count = 2 # 默认2个任务
time_text = ""
participants = 0
copies = 0
try:
# 从 detail tuple 中获取信息
if isinstance(detail, tuple) and len(detail) >= 6:
time_text = str(detail[1] or "")
participants = int(detail[2] or 0)
copies = int(detail[3] or 0)
# 从阶段检测结果获取任务数量
task_count_from_stage = getattr(
analyser, "_fudai_detail_task_count_from_stage", None
)
if task_count_from_stage is not None:
task_count = int(task_count_from_stage or 2)
# 清除标志,避免影响后续调用
analyser._fudai_detail_task_count_from_stage = None
else:
# 如果阶段检测未保存任务数量,尝试通过阶段检测获取
try:
from douyin.stage import douyin_stage
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
result = (
douyin_stage.diagnose_stage_from_current_screen(
analyser
)
)
if result:
stage, _ = result
if stage == "FUDai_DETAIL":
# 尝试通过像素检测获取任务数量
try:
from douyin.detection import douyin_pixel
pic_path = os.path.join(
os.path.dirname(__file__),
"pic",
"screenshot.png",
)
ry = int(
getattr(
analyser,
"resolution_ratio_y",
2400,
)
or 2400
)
y_pianyi = int(
getattr(analyser, "y_pianyi", 0)
or 0
)
result = douyin_pixel.detect_fudai_detail_page(
pic_rgb,
rx,
ry,
y_pianyi,
float(
if os.path.exists(pic_path):
pic = Image.open(pic_path)
pic_rgb = pic.convert("RGB")
rx = int(
getattr(
analyser,
"fudai_detail_template_threshold",
0.7,
"resolution_ratio_x",
1080,
)
or 0.7
),
return_info=True,
analyser=analyser,
)
if isinstance(result, tuple):
_, detect_info = result
detected_task_count = (
detect_info.get("task_count", 0)
or 1080
)
if detected_task_count in (1, 2, 3):
task_count = detected_task_count
except Exception:
pass
except Exception:
pass
ry = int(
getattr(
analyser,
"resolution_ratio_y",
2400,
)
or 2400
)
y_pianyi = int(
getattr(analyser, "y_pianyi", 0)
or 0
)
result = douyin_pixel.detect_fudai_detail_page(
pic_rgb,
rx,
ry,
y_pianyi,
float(
getattr(
analyser,
"fudai_detail_template_threshold",
0.7,
)
or 0.7
),
return_info=True,
analyser=analyser,
)
if isinstance(result, tuple):
_, detect_info = result
detected_task_count = (
detect_info.get("task_count", 0)
)
if detected_task_count in (1, 2, 3):
task_count = detected_task_count
except Exception:
pass
except Exception:
pass
# 限制任务数量在合理范围内
if task_count not in (1, 2, 3):
# 限制任务数量在合理范围内
if task_count not in (1, 2, 3):
task_count = 2
except Exception:
task_count = 2
except Exception:
task_count = 2
douyin_reservation_logic.record_high_value_reservation( # type: ignore[attr-defined]
analyser=analyser,
fudai_content_text=content,
prize_value_yuan=prize_value_yuan,
lastsecond=0,
future_timestamp=future_ts,
x=0,
needswitch=True,
wait_minutes=0,
post_switch_delay_s=0.0,
room_pos=room_pos,
reservations=reservations,
reservation_focus_until_ts_ref=[
float(
getattr(analyser, "reservation_focus_until_ts", 0.0)
or 0.0
)
],
close_detail_callback=lambda: None,
swipe_up_switch_callback=lambda: None,
swipe_down_back_callback=lambda: None,
add_reservation_callback=_add_reservation_with_flag,
sort_reservations_callback=lambda: (
douyin_reservation_logic._sort_reservations_inplace( # type: ignore[attr-defined]
reservations if reservations is not None else [] # type: ignore[arg-type]
)
),
write_state_callback=_write_reservation_state,
room_title=room_title,
room_title_raw=room_title_raw,
task_count=task_count,
time_text=time_text,
participants=participants,
copies=copies,
)
# 如果队列已满,设置标志以便主循环处理
if queue_full_flag[0]:
try:
analyser.queue_full_waiting_at_earliest = (
False # 重置标志,让主循环处理
)
except Exception:
pass
try:
analyser._log_kv(
"预约",
"basic_join_decision:命中高价值阈值,已记录为预约,不立即参与",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
future_ts=int(future_ts),
douyin_reservation_logic.record_high_value_reservation( # type: ignore[attr-defined]
analyser=analyser,
fudai_content_text=content,
prize_value_yuan=prize_value_yuan,
lastsecond=0,
future_timestamp=future_ts,
x=0,
needswitch=True,
wait_minutes=0,
post_switch_delay_s=0.0,
room_pos=room_pos,
queue_len=len(reservations),
reservations=reservations,
reservation_focus_until_ts_ref=[
float(
getattr(analyser, "reservation_focus_until_ts", 0.0)
or 0.0
)
],
close_detail_callback=lambda: None,
swipe_up_switch_callback=lambda: None,
swipe_down_back_callback=lambda: None,
add_reservation_callback=_add_reservation_with_flag,
sort_reservations_callback=lambda: (
douyin_reservation_logic._sort_reservations_inplace( # type: ignore[attr-defined]
reservations if reservations is not None else [] # type: ignore[arg-type]
)
),
write_state_callback=_write_reservation_state,
room_title=room_title,
room_title_raw=room_title_raw,
task_count=task_count,
time_text=time_text,
participants=participants,
copies=copies,
)
except Exception:
pass
# 关闭当前详情,避免长时间停留
try:
analyser.click(500, 470)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser._log_kv(
"参与",
"basic_join_decision:已关闭详情",
action="close_detail",
)
except Exception:
pass
# 记录预约后,切换直播间继续找别的福袋
# 注意:如果已经在锁定期内(已回退到预约直播间),不应该切换直播间
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
# 检查是否在锁定期内
in_lock_period = False
try:
focus_until = float(
getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0
)
now_ts = time.time()
if focus_until > 0 and now_ts < focus_until:
in_lock_period = True
# 如果队列已满,设置标志以便主循环处理
if queue_full_flag[0]:
try:
analyser._log_kv(
"预约",
"[预约] 记录预约后:在锁定期内,不切换直播间",
focus_until=int(focus_until),
remain_seconds=int(focus_until - now_ts),
analyser.queue_full_waiting_at_earliest = (
False # 重置标志,让主循环处理
)
except Exception:
pass
except Exception:
pass
if needswitch and not in_lock_period:
try:
analyser._log_kv(
"参与",
"basic_join_decision:记录预约后切换直播间",
reason="high_value_reservation",
"预约",
"basic_join_decision:命中高价值阈值,已记录为预约,不立即参与",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
future_ts=int(future_ts),
room_pos=room_pos,
queue_len=len(reservations),
)
except Exception:
pass
# 关闭当前详情,避免长时间停留
try:
# 优先使用封装好的上滑切房方法
if hasattr(analyser, "swipe_up_to_next_live"):
analyser.swipe_up_to_next_live()
else:
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
analyser.click(500, 470)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser._log_kv(
"参与",
"basic_join_decision:已关闭详情",
action="close_detail",
)
except Exception:
pass
# 记录预约后,切换直播间继续找别的福袋
# 注意:如果已经在锁定期内(已回退到预约直播间),不应该切换直播间
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
# 检查是否在锁定期内
in_lock_period = False
try:
focus_until = float(
getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0
)
now_ts = time.time()
if focus_until > 0 and now_ts < focus_until:
in_lock_period = True
try:
rx = int(
getattr(analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400)
or 2400
analyser._log_kv(
"预约",
"[预约] 记录预约后:在锁定期内,不切换直播间",
focus_until=int(focus_until),
remain_seconds=int(focus_until - now_ts),
)
except Exception:
rx, ry = 1080, 2400
start_x = 540 * rx // 1080
start_y = 1700 * ry // 2400
end_x = 540 * rx // 1080
end_y = 700 * ry // 2400
analyser.operation.swipe(
analyser.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
except Exception:
# 切房失败不影响主流程,直接返回
pass
elif in_lock_period:
# 在锁定期内,不切换直播间,但记录日志说明原因
try:
analyser._log_kv(
"参与",
"basic_join_decision:记录预约后不切换直播间(锁定期内)",
reason="lock_period_active",
)
pass
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(记录预约)",
elapsed_seconds=round(elapsed, 2),
)
return True
if needswitch and not in_lock_period:
try:
analyser._log_kv(
"参与",
"basic_join_decision:记录预约后切换直播间",
reason="high_value_reservation",
)
except Exception:
pass
try:
# 优先使用封装好的上滑切房方法
if hasattr(analyser, "swipe_up_to_next_live"):
analyser.swipe_up_to_next_live()
else:
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
try:
rx = int(
getattr(analyser, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(analyser, "resolution_ratio_y", 2400)
or 2400
)
except Exception:
rx, ry = 1080, 2400
start_x = 540 * rx // 1080
start_y = 1700 * ry // 2400
end_x = 540 * rx // 1080
end_y = 700 * ry // 2400
analyser.operation.swipe(
analyser.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
except Exception:
# 切房失败不影响主流程,直接返回
pass
elif in_lock_period:
# 在锁定期内,不切换直播间,但记录日志说明原因
try:
analyser._log_kv(
"参与",
"basic_join_decision:记录预约后不切换直播间(锁定期内)",
reason="lock_period_active",
)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(记录预约)",
elapsed_seconds=round(elapsed, 2),
)
return True
except Exception:
# 若预约逻辑异常,退化为直接参与抽奖
try:
+83 -11
View File
@@ -535,9 +535,9 @@ def configure_logging(
compress_logs: Optional[bool] = None, # 是否压缩旧日志
max_total_size_gb: float = 10.0, # 最大总日志大小(GB)
compress_after_days: int = 7, # 几天后压缩
enable_monitor: bool = True, # 是否启用日志监控
monitor_warning_mb: float = 500.0, # 监控警告大小(MB)
monitor_critical_mb: float = 2000.0, # 监控严重大小(MB)
enable_monitor: Optional[bool] = None, # 是否启用日志监控(仅启动阶段检查;运行时监控需显式开启)
monitor_warning_mb: Optional[float] = None, # 监控警告大小(MB)
monitor_critical_mb: Optional[float] = None, # 监控严重大小(MB)
) -> None:
"""配置日志系统
@@ -553,7 +553,7 @@ def configure_logging(
compress_logs: 是否压缩旧日志,默认True
max_total_size_gb: 最大总日志大小(GB),超过后删除最旧文件,默认10GB
compress_after_days: 几天后压缩日志,默认7天
enable_monitor: 是否启用日志轮转监控,默认True
enable_monitor: 是否启用日志监控(默认从 config.json 读取;仅影响启动阶段检查)
monitor_warning_mb: 监控警告大小阈值(MB),默认500MB
monitor_critical_mb: 监控严重大小阈值(MB),默认2000MB
"""
@@ -598,6 +598,20 @@ def configure_logging(
if compress_after_days == 7: # 如果是默认值,从配置读取
compress_after_days = log_config.get("compress_after_days", 7)
# 读取 monitor 配置
if enable_monitor is None:
enable_monitor = bool(log_config.get("enable_monitor", False))
if monitor_warning_mb is None:
try:
monitor_warning_mb = float(log_config.get("monitor_warning_mb", 500.0))
except Exception:
monitor_warning_mb = 500.0
if monitor_critical_mb is None:
try:
monitor_critical_mb = float(log_config.get("monitor_critical_mb", 2000.0))
except Exception:
monitor_critical_mb = 2000.0
# 读取 rotation 配置(优先级高于函数默认参数)
rotation_cfg = (
log_config.get("rotation", {})
@@ -626,11 +640,26 @@ def configure_logging(
if compress_logs is None:
compress_logs = True
if enable_monitor is None:
enable_monitor = False
if monitor_warning_mb is None:
monitor_warning_mb = 500.0
if monitor_critical_mb is None:
monitor_critical_mb = 2000.0
# rotation 默认值(当读取 config 出错时)
rotation_when = None
rotation_interval = 1
rotation_enabled = False
# 规范化 monitor 默认值
if enable_monitor is None:
enable_monitor = False
if monitor_warning_mb is None:
monitor_warning_mb = 500.0
if monitor_critical_mb is None:
monitor_critical_mb = 2000.0
# 规范化日志级别
if log_level is None:
log_level = "INFO"
@@ -751,18 +780,44 @@ def configure_logging(
except Exception:
pass
# 启动日志监控器
if enable_monitor:
# 注意:按用户反馈,默认不在运行过程中做日志目录体积检查。
# 仅当显式开启运行时监控时才启动后台线程(避免主流程中途 I/O 干扰与刷屏)。
runtime_monitor_enabled = False
try:
runtime_monitor_enabled = bool(
(log_config.get("enable_runtime_monitor", False) if isinstance(log_config, dict) else False)
)
except Exception:
runtime_monitor_enabled = False
# 环境变量可强制开启(便于临时诊断)
if os.environ.get("ENABLE_RUNTIME_LOG_MONITOR") == "1":
runtime_monitor_enabled = True
if runtime_monitor_enabled:
try:
monitor_check_interval = 300
try:
if isinstance(log_config, dict):
monitor_check_interval = int(
log_config.get("monitor_check_interval", 300)
)
except Exception:
monitor_check_interval = 300
start_log_monitor(
logs_dir=log_dir or path_config.get_logs_dir(),
base_name=os.path.basename(base_filename_base),
warning_size_mb=monitor_warning_mb,
critical_size_mb=monitor_critical_mb,
warning_size_mb=float(monitor_warning_mb),
critical_size_mb=float(monitor_critical_mb),
check_interval=monitor_check_interval,
enable_runtime_cleanup=bool(
(log_config.get("enable_runtime_cleanup", False) if isinstance(log_config, dict) else False)
),
)
except Exception as e:
try:
print(f"[日志配置] 启动监控器失败: {e}")
print(f"[日志配置] 启动运行时监控器失败: {e}")
except Exception:
pass
else:
@@ -1085,6 +1140,11 @@ class LogRotationMonitor:
# 是否允许在运行过程中触发自动清理(默认不允许)
self.enable_runtime_cleanup = bool(enable_runtime_cleanup)
# 告警输出限流:避免在运行时开启监控时刷屏
self._last_warning_print_ts = 0.0
self._last_critical_print_ts = 0.0
self._min_alert_print_interval_sec = 3600.0
def start(self) -> None:
"""启动监控器"""
if self._running:
@@ -1130,7 +1190,13 @@ class LogRotationMonitor:
if self.alert_callback:
self.alert_callback("CRITICAL", message)
else:
print(f"[日志监控] CRITICAL: {message}")
now_ts = time.time()
if (
now_ts - self._last_critical_print_ts
>= self._min_alert_print_interval_sec
):
print(f"[日志监控] CRITICAL: {message}")
self._last_critical_print_ts = now_ts
elif total_size_mb >= self.warning_size_mb:
message = (
@@ -1139,7 +1205,13 @@ class LogRotationMonitor:
if self.alert_callback:
self.alert_callback("WARNING", message)
else:
print(f"[日志监控] WARNING: {message}")
now_ts = time.time()
if (
now_ts - self._last_warning_print_ts
>= self._min_alert_print_interval_sec
):
print(f"[日志监控] WARNING: {message}")
self._last_warning_print_ts = now_ts
# 运行时不再自动触发清理,清理仅在启动阶段执行以避免中途 I/O 干扰
# 检查轮转频率
current_time = datetime.now()
+6 -2
View File
@@ -26,7 +26,7 @@ def format_action_log(action: str, details: Optional[str] = None, **fields: Any)
生成简洁的人类可读行为日志(优先中文),同时保留字段键值以便机器解析。
输出示例:
- 上滑切换直播间 耗时=2.10s
- 上滑切换直播间 耗时=2100.00ms
- 点击参与 福袋ID=123 value=200.0 slow=1
保留原始 key=value 形式以便下游解析器仍可使用。
"""
@@ -65,7 +65,11 @@ def format_action_log(action: str, details: Optional[str] = None, **fields: Any)
elapsed = None
if elapsed is not None:
kv_parts.append(f"耗时={round(elapsed,2)}s")
try:
elapsed_ms = float(elapsed) * 1000.0
kv_parts.append(f"耗时={elapsed_ms:.2f}ms")
except Exception:
kv_parts.append(f"耗时={elapsed}")
# 专门处理以 `_ms` 命名的耗时字段,使用友好中文标签并统一以 ms 单位显示
ms_kv_parts: list[str] = []
+13 -2
View File
@@ -3,7 +3,10 @@ from __future__ import annotations
import os
import random
import time
import cv2
from typing import Any
import cv2 as _cv2
cv2: Any = _cv2
# pylint: disable=E1101
import numpy as np
@@ -293,7 +296,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
if now - last_desktop_check_ts >= check_interval:
last_desktop_check_ts = now
try:
# TODO: 实现桌面检测和恢复功能
# 桌面检测与恢复逻辑待实现(保留占位)
# if yanghao_check_and_recover_from_desktop(analyser):
# print("[养号] 检测到在桌面,已尝试恢复")
# analyser.operation.delay(1)
@@ -507,3 +510,11 @@ def yanghao_wait(analyser, total_seconds: int) -> None:
# 执行推荐页养号流程
yanghao_recommend_flow(analyser, total_seconds)
def yanghao_get_recommend_seconds(analyser) -> int:
"""返回推荐页养号的默认时长(兼容接口)。"""
try:
return int(getattr(analyser, "yanghao_recommend_duration_seconds", 60) or 60)
except Exception:
return 60
+4 -4
View File
@@ -72,11 +72,11 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa:
analyser, "stage_diag_max_time", 10.0
) # 最大诊断时间(可配置,默认10秒)
max_step_time = getattr(
analyser, "stage_diag_max_step_time", 2.0
) # 每个步骤最大耗时(可配置,默认2秒)
analyser, "stage_diag_max_step_time", 1.5
) # 每个步骤最大耗时(优化:从2.0秒降低到1.5秒)
enable_ocr_mode1 = bool(
getattr(analyser, "enable_ocr_mode1", False)
) # OCR模式1开关(二值化)
getattr(analyser, "enable_ocr_mode1", True)
) # OCR模式1开关(二值化)- 优化:默认启用以提升性能
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
+16 -86
View File
@@ -219,7 +219,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
screenshot_end = time.time()
wait_file_ms = round((screenshot_end - wait_start) * 1000, 1)
_log_perf("after_screenshot")
_log_perf("after_screenshot") # 移除:避免过多性能日志
except Exception:
screenshot_end = time.time() if screenshot_start is not None else None
@@ -243,7 +243,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
pic.load()
pic_rgb = pic.convert("RGB")
image_load_ms = round((time.time() - _img0) * 1000, 1)
_log_perf("after_image_load")
_log_perf("after_image_load") # 移除:避免过多性能日志
except Exception:
pass
@@ -304,7 +304,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
analyser, renwu=task_count
)
ocr_end = time.time()
_log_perf("after_get_fudai_contain")
_log_perf("after_get_fudai_contain") # 移除:避免过多性能日志
except Exception as e: # pyright: ignore[reportTooBroadExceptionType]
# 出现异常时,记录详细错误和 traceback 并返回占位结果,便于排查
try:
@@ -413,7 +413,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
countdown_start = float(countdown_start)
countdown_end = float(future_ts)
countdown_parse_ms = round((time.time() - _cd0) * 1000, 1)
_log_perf("after_countdown_parse")
# _log_perf("after_countdown_parse") # 移除:避免过多性能日志
except Exception:
pass
@@ -474,70 +474,6 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析
level="DEBUG",
)
analyser._log_kv(
"福袋详情",
f"read_fudai_detail_once 完整识别结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
status="ok",
room_title=room_title,
room_title_raw=room_title_raw,
task_count=task_count,
content=content_full,
content_length=len(content_full),
time_text=time_text or "",
participants=int(participants or 0),
copies=int(copies or 0),
prize_value_yuan=float(prize_value_yuan or 0.0),
countdown_start=countdown_start,
countdown_start_str=countdown_start_str,
countdown_end=countdown_end,
countdown_end_str=countdown_end_str,
remain_seconds=remain_seconds,
elapsed_seconds=round(time.time() - start_time, 2),
level="DEBUG",
)
# 输出到行为日志(使用更详细的格式)
content_preview = (content or "")[:60] if content else "未识别到"
analyser._log_kv(
"行为",
f"识别福袋详情完成:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
action="识别福袋详情",
result="成功",
detail={
"直播间": room_title if room_title else room_title_raw,
"直播间原始": room_title_raw,
"任务数量": task_count,
"福袋内容": content or "",
"倒计时文本": time_text or "",
"参与人数": int(participants or 0),
"福袋份数": int(copies or 0),
"奖品价值": float(prize_value_yuan or 0.0),
"倒计时开始时间": (
countdown_start_str if countdown_start_str else f"{countdown_start}"
),
"倒计时结束时间": (
countdown_end_str if countdown_end_str else f"{countdown_end}"
),
"剩余秒数": remain_seconds,
},
level="DEBUG",
)
# 输出简化的运行日志(兼容原有格式)
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 结果",
status="ok",
content=detail_tuple[0],
time_text=detail_tuple[1],
participants=detail_tuple[2],
copies=detail_tuple[3],
prize_value_yuan=detail_tuple[4],
countdown_start=countdown_start,
countdown_end=countdown_end,
task_count=task_count,
level="DEBUG",
)
except Exception as e:
# 如果详细日志输出失败,至少输出基本信息
try:
@@ -587,7 +523,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
copies=int(copies or 0),
task_count=task_count,
)
_log_perf("success")
_log_perf("success") # 只在最终成功时输出性能日志
return "ok", detail_tuple, extra
@@ -633,12 +569,12 @@ def read_fudai_detail_with_retries(
except Exception:
pass
else:
# 未验证情况,使用配置项,默认0.8秒(比之前的1.2秒更快)
# 未验证情况,使用配置项,默认0.5秒(优化:从0.8秒降低到0.5秒)
initial_wait = float(
getattr(analyser, "fudai_detail_initial_wait_seconds", 0.8) or 0.8
getattr(analyser, "fudai_detail_initial_wait_seconds", 0.5) or 0.5
)
if initial_wait < 0.5:
initial_wait = 0.5 # 最小0.5秒
if initial_wait < 0.3:
initial_wait = 0.3 # 最小0.3秒
try:
analyser.operation.delay(initial_wait)
except Exception:
@@ -651,16 +587,16 @@ def read_fudai_detail_with_retries(
max_attempts = 2
if max_attempts < 1:
max_attempts = 1
# 使用配置项,默认0.5秒(比之前的0.8秒更快)
retry_delay = 0.5
# 使用配置项,默认0.3秒(优化:从0.5秒降低到0.3秒)
retry_delay = 0.3
try:
retry_delay = float(
getattr(analyser, "fudai_detail_retry_delay_seconds", 0.5) or 0.5
getattr(analyser, "fudai_detail_retry_delay_seconds", 0.3) or 0.3
)
except Exception:
retry_delay = 0.5
if retry_delay < 0.3:
retry_delay = 0.3 # 最小0.3秒
retry_delay = 0.3
if retry_delay < 0.2:
retry_delay = 0.2 # 最小0.2秒
last_tuple: Optional[Tuple] = None
last_status: str = "error"
@@ -986,13 +922,7 @@ def read_fudai_detail_with_retries(
# 运行日志:完整的福袋详情
content_preview = (content or "")[:60] if content else "未识别到"
content_full = content or ""
# 添加明确的"福袋内容:"格式输出,确保GUI能正确解析(即使内容为空也输出)
if last_status == "ok":
analyser._log_kv(
"福袋",
f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析
level="INFO",
)
# 移除重复的福袋内容输出,避免与read_fudai_detail_once重复
analyser._log_kv(
"福袋详情",
f"read_fudai_detail_with_retries 最终结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
+2 -2
View File
@@ -3749,12 +3749,12 @@ def main():
lines.append(f"福袋识别次数: {fudai_seen_unique}")
lines.append(f"打开详情: {fudai_open_detail_unique}")
if fudai_seen > 0:
if fudai_seen_unique > 0:
open_rate = (fudai_open_detail_unique / fudai_seen_unique) * 100
lines.append(f" 打开成功率: {open_rate:.1f}%")
lines.append(f"点击参与: {fudai_click_attend_unique}")
if fudai_open_detail > 0:
if fudai_open_detail_unique > 0:
click_rate = (
fudai_click_attend_unique / fudai_open_detail_unique
) * 100
+1504 -174
View File
File diff suppressed because it is too large. Load diff