feat(reservation): Update reservation details and improve logging

- Updated reservation JSON data with new room titles, prize values, and timestamps.
- Enhanced logging in `douyin_fudai_core.py` to include OCR duration summaries for better analysis.
- Modified `SwipeHandler` to allow forced switching during seek processes to prevent deadlocks.
- Improved logging wrapper to handle field extraction and elapsed time calculations more robustly.
- Refactored log formatting functions for better readability and consistency.
- Added total timeout handling in `process_reservation_attend_window` to prevent blocking.
- Removed automatic backtracking in reservation verification to avoid infinite loops.
- Updated configuration management to include total timeout settings for reservations.
- Enhanced error handling and logging in `fudai_detail_reader.py` for validation failures.
This commit is contained in:
Your Name committed 2026-01-03 13:30:55 +08:00
1 parent 1223a1ea5a
commit 2fa2073f2e
11 files changed
+282 -784

No files matched your search

+20 -2
View File
@@ -568,6 +568,13 @@ class underlying_operations:
def _get_screenshot_direct(self, device_id, path="pic"):
"""直接截图(不使用服务模式)"""
overall_start = time_module.time()
# 初始化分阶段耗时占位,确保最终汇总时总有值
cleanup_dur = 0.0
adb_subprocess_dur = 0.0
validate_tmp_dur = 0.0
replace_dur = 0.0
mirror_dur = 0.0
validate_out_dur = 0.0
if path == "pic":
try:
@@ -765,8 +772,7 @@ class underlying_operations:
header = f.read(4)
if header == b"\x89PNG":
validate_out_dur = (
time_module.time()
- validate_out_start
time_module.time() - validate_out_start
) * 1000.0
if validate_out_dur > 50.0:
logging.info(
@@ -777,6 +783,18 @@ 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,
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,
+40 -350
View File
@@ -248,6 +248,7 @@ class fudai_analyse:
self._waiting_for_lottery_result: bool = False # 是否正在等待开奖结果
self._reservation_back_direct_attend: bool = False # 预约回退后直接参与标志
self._force_attend_after_reservation_back: bool = False # 强制参与标志
self._reservation_back_attempts: int = 0 # 直接参与尝试计数,防止无限重试
self._skip_stage_diagnosis_and_find_fudai: bool = False # 跳过阶段诊断标志
self._just_switched_room: bool = False # 是否刚刚切换了直播间
self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = (
@@ -1049,6 +1050,16 @@ class fudai_analyse:
def _write_state() -> None:
# 将预约队列写入状态文件,供外部查看(格式与 douyin_fudai_core.py 一致)
try:
# 节流:避免高频写盘(某些环境下会造成明显卡顿甚至看似卡死)
now_ts = time.time()
last_ts = float(
getattr(self, "_reservations_state_last_write_ts", 0.0)
or 0.0
)
if (now_ts - last_ts) < 1.0:
return
self._reservations_state_last_write_ts = now_ts
import json
os.makedirs(
@@ -1194,140 +1205,18 @@ class fudai_analyse:
try:
self._log_kv(
"预约",
"[预约] 队列满等待状态,已设置直接参与标志,立即执行参与(不再循环检查)",
"[预约] 队列满等待状态检测到直接参与标志:为避免卡死已禁用该分支,改走正常流程",
reservation_direct_attend=reservation_direct_attend,
)
except Exception:
pass
# 立即执行参与,不再循环检查预约回退
# 先进行阶段诊断,然后根据阶段执行参与
# 清理标志,避免每轮提前 return 导致卡在状态检查
try:
self.operation.get_screenshot(self.device_id)
self._reservation_back_direct_attend = False
self._force_attend_after_reservation_back = False
self._reservation_back_attempts = 0
except Exception:
pass
from douyin.stage import (
douyin_stage,
) # pylint: disable=redefined-outer-name
result = douyin_stage.diagnose_stage_from_current_screen(self)
if result is None:
stage, _ = (
"IN_LIVE_ROOM",
"阶段诊断返回 None,默认判定为在直播间",
)
else:
stage, _ = result
if stage == "FUDai_DETAIL":
# 在福袋详情页,直接参与
try:
self._log_kv(
"预约",
"[预约] 检测到福袋详情页,立即执行直接参与",
stage=stage,
)
except Exception:
pass
self._reservation_back_direct_attend = False # 清除标志
self._force_attend_after_reservation_back = (
True # 设置强制参与标志
)
self._handle_reservation_direct_attend()
elif stage == "IN_LIVE_ROOM":
# 在直播间,查找福袋并打开详情页
try:
self._log_kv(
"预约",
"[预约] 检测到直播间,查找福袋并打开详情页后执行直接参与",
stage=stage,
)
except Exception:
pass
# 查找福袋并打开详情页
from douyin.core import (
douyin_flow_control,
) # pylint: disable=redefined-outer-name
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
original_max_wait = getattr(
self, "fudai_icon_max_wait_seconds", None
)
try:
wait_seconds_for_find = float(
getattr(
self,
"switch_room_wait_after_stage_diag_seconds",
7.0,
)
or 7.0
)
self.fudai_icon_max_wait_seconds = wait_seconds_for_find
self._log_kv(
"预约",
"[预约] 开始查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds)",
room_pos=room_pos_ref[0],
max_wait_seconds=wait_seconds_for_find,
)
except Exception:
pass
found = douyin_flow_control.find_and_open_fudai_detail(
self, room_pos_ref
)
# 恢复原始配置
try:
if original_max_wait is not None:
self.fudai_icon_max_wait_seconds = original_max_wait
elif hasattr(self, "fudai_icon_max_wait_seconds"):
delattr(self, "fudai_icon_max_wait_seconds")
except Exception:
pass
if found:
# 成功打开详情页,直接参与
try:
self._log_kv(
"预约",
"[预约] 成功打开详情页,立即执行直接参与",
)
except Exception:
pass
self._reservation_back_direct_attend = False # 清除标志
self._force_attend_after_reservation_back = (
True # 设置强制参与标志
)
self._handle_reservation_direct_attend()
else:
# 查找福袋失败,保留标志,下一轮继续尝试
try:
self._reservation_back_direct_attend = (
True # 恢复标志
)
self._log_kv(
"预约",
"[预约] 预约回退后查找福袋失败,保留直接参与标志,下一轮继续尝试",
flag_restored=True,
)
except Exception:
pass
else:
# 其他阶段,保留标志,下一轮继续尝试
try:
self._reservation_back_direct_attend = True # 恢复标志
self._log_kv(
"预约",
"[预约] 检测到其他阶段,保留直接参与标志,下一轮继续尝试",
stage=stage,
flag_restored=True,
)
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(预约回退直接参与)",
elapsed_seconds=round(elapsed, 2),
)
return
# 检查是否所有预约已完成,需要重置到第一个直播间
if self.queue_full_waiting_at_earliest and not self.reservations:
@@ -1472,6 +1361,11 @@ class fudai_analyse:
# 已触发预约回退,设置标志:下一轮直接参与,跳过详情识别
try:
self._reservation_back_direct_attend = True
# reset attempts counter when first scheduling direct attend
try:
self._reservation_back_attempts = 0
except Exception:
pass
self._log_kv(
"预约",
"[预约] 预约回退成功,设置直接参与标志(跳过详情识别)",
@@ -1899,82 +1793,24 @@ class fudai_analyse:
except Exception:
pass
if reservation_direct_attend:
# 先检查预约是否过期
expired = False
try:
if self.reservations and len(self.reservations) > 0:
first_reservation = self.reservations[0]
future_ts = float(
first_reservation.get("future_ts", 0.0) or 0.0
)
if future_ts > 0:
now_ts = time.time()
poll_before = float(
getattr(
self, "high_value_fudai_poll_before_seconds", 10.0
)
or 10.0
)
expired_threshold = future_ts + max(0.0, poll_before)
if now_ts > expired_threshold:
expired = True
from datetime import datetime
future_str = (
datetime.fromtimestamp(future_ts).strftime(
"%Y-%m-%d %H:%M:%S"
)
if future_ts > 0
else "无效"
)
expired_seconds = int(now_ts - expired_threshold)
self._log_kv(
"预约",
"[预约] 预约回退后直接参与:福袋已过期,清除标志",
future_ts=int(future_ts),
future_str=future_str,
expired_seconds=expired_seconds,
)
# 清除相关标志
self._reservation_back_direct_attend = False
self._force_attend_after_reservation_back = False
self.queue_full_waiting_at_earliest = False
# 清理过期预约
from douyin.reservation import (
douyin_reservation_logic,
) # pylint: disable=redefined-outer-name
douyin_reservation_logic.cleanup_expired_reservations(
analyser=self,
reservations=self.reservations,
write_state_callback=lambda: None,
)
self._log_kv(
"预约",
"[预约] 检测到直接参与标志:为避免卡死已禁用该分支,改走正常详情流程",
)
except Exception:
pass
if not expired:
# 预约回退后直接参与:使用正常流程,但设置强制参与标志
try:
self._reservation_back_direct_attend = False # 清除标志
# 设置强制参与标志,让 basic_join_decision 跳过倒计时检查
self._force_attend_after_reservation_back = True
self._log_kv(
"预约",
"[预约] 预约回退后直接参与:使用正常流程,设置强制参与标志",
flag_cleared=True,
force_attend=True,
)
except Exception:
pass
# 使用正常流程处理
self._handle_reservation_direct_attend()
else:
# 已过期,执行正常流程
self._handle_in_fudai_detail()
try:
self._reservation_back_direct_attend = False
self._force_attend_after_reservation_back = False
self._reservation_back_attempts = 0
except Exception:
pass
self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(预约回退直接参与)",
"run_once_basic完成(处理福袋详情)",
elapsed_seconds=round(elapsed, 2),
)
else:
@@ -2009,165 +1845,19 @@ class fudai_analyse:
except Exception:
pass
if reservation_direct_attend:
# 先检查预约是否过期
expired = False
try:
if self.reservations and len(self.reservations) > 0:
first_reservation = self.reservations[0]
future_ts = float(
first_reservation.get("future_ts", 0.0) or 0.0
)
if future_ts > 0:
now_ts = time.time()
poll_before = float(
getattr(
self, "high_value_fudai_poll_before_seconds", 10.0
)
or 10.0
)
expired_threshold = future_ts + max(0.0, poll_before)
if now_ts > expired_threshold:
expired = True
from datetime import datetime
future_str = (
datetime.fromtimestamp(future_ts).strftime(
"%Y-%m-%d %H:%M:%S"
)
if future_ts > 0
else "无效"
)
expired_seconds = int(now_ts - expired_threshold)
self._log_kv(
"预约",
"[预约] 预约回退后直接参与:福袋已过期,清除标志",
future_ts=int(future_ts),
future_str=future_str,
expired_seconds=expired_seconds,
)
# 清除相关标志
self._reservation_back_direct_attend = False
self._force_attend_after_reservation_back = False
self.queue_full_waiting_at_earliest = False
# 清理过期预约
from douyin.reservation import (
douyin_reservation_logic,
) # pylint: disable=redefined-outer-name
douyin_reservation_logic.cleanup_expired_reservations(
analyser=self,
reservations=self.reservations,
write_state_callback=lambda: None,
)
except Exception:
pass
if not expired:
# 预约回退后直接参与:查找福袋并打开详情页,然后直接参与
try:
self._reservation_back_direct_attend = False # 清除标志
# 设置强制参与标志,让 basic_join_decision 跳过倒计时检查
self._force_attend_after_reservation_back = True
self._log_kv(
"预约",
"[预约] 预约回退后直接参与:查找福袋并打开详情页,设置强制参与标志",
flag_cleared=True,
force_attend=True,
stage=stage,
)
except Exception:
pass
# 回退后等待页面加载和查找福袋都使用 switch_room_wait_after_stage_diag_seconds 参数
try:
wait_seconds = float(
getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0)
or 7.0
)
self._log_kv(
"预约",
"[预约] 预约回退后等待页面加载(使用 switch_room_wait_after_stage_diag_seconds)",
wait_seconds=wait_seconds,
)
self.operation.delay(wait_seconds)
except Exception:
try:
time.sleep(7.0)
except Exception:
pass
# 查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds 作为最大等待时间)
from douyin.core import (
douyin_flow_control,
) # pylint: disable=redefined-outer-name
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
# 临时设置 fudai_icon_max_wait_seconds 为 switch_room_wait_after_stage_diag_seconds
original_max_wait = None
try:
original_max_wait = getattr(
self, "fudai_icon_max_wait_seconds", None
)
wait_seconds_for_find = float(
getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0)
or 7.0
)
self.fudai_icon_max_wait_seconds = wait_seconds_for_find
self._log_kv(
"预约",
"[预约] 开始查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds)",
room_pos=room_pos_ref[0],
max_wait_seconds=wait_seconds_for_find,
)
except Exception:
pass
found = douyin_flow_control.find_and_open_fudai_detail(
self, room_pos_ref
)
# 恢复原始配置
try:
if original_max_wait is not None:
self.fudai_icon_max_wait_seconds = original_max_wait
elif hasattr(self, "fudai_icon_max_wait_seconds"):
delattr(self, "fudai_icon_max_wait_seconds")
except Exception:
pass
try:
self._log_kv(
"预约",
"[预约] 查找福袋结果",
found=found,
room_pos=room_pos_ref[0],
"[预约] 检测到直接参与标志:为避免卡死已禁用该分支,改走正常直播间流程",
)
except Exception:
pass
if found:
# 成功打开详情页,直接参与
try:
self._log_kv(
"预约",
"[预约] 成功打开详情页,开始直接参与",
)
except Exception:
pass
self._handle_reservation_direct_attend()
else:
# 查找福袋失败,保留标志,下一轮继续尝试
try:
self._reservation_back_direct_attend = True # 恢复标志
self._log_kv(
"预约",
"[预约] 预约回退后查找福袋失败,保留直接参与标志,下一轮继续尝试",
flag_restored=True,
)
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(预约回退直接参与)",
elapsed_seconds=round(elapsed, 2),
)
return
try:
self._reservation_back_direct_attend = False
self._force_attend_after_reservation_back = False
self._reservation_back_attempts = 0
except Exception:
pass
# 在直播间:如果刚刚切换了直播间,等待福袋加载
just_switched = getattr(self, "_just_switched_room", False)
+34 -20
View File
@@ -1,35 +1,49 @@
{
"updated_ts": 1767415357.50075,
"updated_ts": 1767418177.7360778,
"reason": "record_reservation",
"room_pos": 1,
"current_room_title": "扬叔来了",
"current_room_title_raw": "扬叔来了",
"room_pos": 5,
"current_room_title": "希娜周",
"current_room_title_raw": "希娜周",
"reservations": [
{
"prize_value_yuan": 5999.0,
"prize_value_yuan": 899.0,
"content": "",
"future_ts": 1767415961.174306,
"future_str": "2026-01-03 12:52:41",
"pos_seen": 0,
"room_title": "一枝梅3号",
"room_title_raw": "一枝梅3号",
"created_ts": 1767415328.6684387,
"future_ts": 1767418453.861887,
"future_str": "2026-01-03 13:34:13",
"pos_seen": 2,
"room_title": "作业帮数",
"room_title_raw": "作业帮数",
"created_ts": 1767418099.2724433,
"task_count": 2,
"time_text": "10:38",
"time_text": "06:00",
"participants": 0,
"copies": 0
},
{
"prize_value_yuan": 3399.0,
"prize_value_yuan": 2999.0,
"content": "",
"future_ts": 1767416222.371734,
"future_str": "2026-01-03 12:57:02",
"pos_seen": 1,
"room_title": "扬叔来了",
"room_title_raw": "扬叔来了",
"created_ts": 1767415357.4982371,
"future_ts": 1767418858.452201,
"future_str": "2026-01-03 13:40:58",
"pos_seen": 3,
"room_title": "壬lSsheila",
"room_title_raw": "壬lSsheila",
"created_ts": 1767418126.485631,
"task_count": 2,
"time_text": "14:30",
"time_text": "12:17",
"participants": 0,
"copies": 0
},
{
"prize_value_yuan": 599.0,
"content": "",
"future_ts": 1767418893.057496,
"future_str": "2026-01-03 13:41:33",
"pos_seen": 5,
"room_title": "希娜周",
"room_title_raw": "希娜周",
"created_ts": 1767418177.7300756,
"task_count": 2,
"time_text": "12:00",
"participants": 0,
"copies": 0
}
+14
View File
@@ -1075,6 +1075,20 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
except Exception:
pass
# 输出一行紧凑的并行 OCR 汇总,便于日志聚合分析
try:
total_ocr_ms = round((time.time() - ocr_start_time) * 1000, 1)
durations_str = ",".join(f"{k}={v}" for k, v in durations.items())
import logging
logging.info(
"[OCR汇总] total_ms=%.1f %s",
total_ocr_ms,
durations_str,
)
except Exception:
pass
# 轻重分流:轻量OCR跑完后,仅在缺字段或强制时补充重OCR
try:
heavy_fields = _should_use_heavy(
+10 -1
View File
@@ -34,12 +34,21 @@ class SwipeHandler:
analyser: 分析器对象
"""
# 检查是否在预约锁定期内
# 但如果当前处于“预约回退/定位直播间”的 seek 过程,则允许强制切换,
# 否则会出现:回退逻辑需要上滑前进,但被锁定期拦截,导致流程看似卡死。
try:
try:
in_seek = bool(
getattr(analyser, "_skip_record_title_during_seek", False)
)
except Exception:
in_seek = False
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:
if (not in_seek) and focus_until > 0 and now_ts < focus_until:
# 在锁定期内,不允许上划离开预约直播间
remain_seconds = int(focus_until - now_ts)
try:
+11 -4
View File
@@ -376,7 +376,7 @@ class LoggingWrapper:
for k, v in fields.items():
kk = str(k)
if kk.startswith("字段_"):
kk = kk[len("字段_"):]
kk = kk[len("字段_") :]
fields_clean[kk] = v
# 提取耗时(从字段中查找,优先使用毫秒字段)
@@ -388,7 +388,9 @@ class LoggingWrapper:
elapsed_seconds = float(fields_clean.get("total_ms", 0)) / 1000.0
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
elif "total_elapsed_ms" in fields_clean:
elapsed_seconds = float(fields_clean.get("total_elapsed_ms", 0)) / 1000.0
elapsed_seconds = (
float(fields_clean.get("total_elapsed_ms", 0)) / 1000.0
)
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
elif "总耗时毫秒" in fields_clean:
elapsed_seconds = float(fields_clean.get("总耗时毫秒", 0)) / 1000.0
@@ -408,7 +410,10 @@ class LoggingWrapper:
score_str = f"分数:{score_val:.3f}"
except (ValueError, TypeError):
pass
elif "max_val" in fields_clean and fields_clean.get("max_val") is not None:
elif (
"max_val" in fields_clean
and fields_clean.get("max_val") is not None
):
try:
score_val = float(fields_clean.get("max_val", 0))
score_str = f"分数:{score_val:.3f}"
@@ -590,7 +595,9 @@ class LoggingWrapper:
original_levels = {}
for handler in console_handlers:
try:
original_levels[id(handler)] = getattr(handler, "level", logging.NOTSET)
original_levels[id(handler)] = getattr(
handler, "level", logging.NOTSET
)
handler.setLevel(logging.CRITICAL + 1) # 临时禁用
except Exception:
# 如果无法修改某个 handler,跳过但继续记录
+27 -13
View File
@@ -1,11 +1,15 @@
"""日志格式化与美化模块
纯函数化输出格式,便于在不同日志组件之间复用。
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
def format_debug_log(message: str, level: str = "DEBUG", tag: Optional[str] = None, **fields: Any) -> str:
def format_debug_log(
message: str, level: str = "DEBUG", tag: Optional[str] = None, **fields: Any
) -> str:
parts = []
if tag:
parts.append(f"[{tag}]")
@@ -16,6 +20,7 @@ def format_debug_log(message: str, level: str = "DEBUG", tag: Optional[str] = No
parts.append(kv)
return " ".join(parts)
def format_action_log(action: str, details: Optional[str] = None, **fields: Any) -> str:
"""
生成简洁的人类可读行为日志(优先中文),同时保留字段键值以便机器解析。
@@ -115,7 +120,9 @@ def format_action_log(action: str, details: Optional[str] = None, **fields: Any)
return f"[ACTION] {human_msg}"
def format_error_log(message: str, level: str = "ERROR", tag: Optional[str] = None, **fields: Any) -> str:
def format_error_log(
message: str, level: str = "ERROR", tag: Optional[str] = None, **fields: Any
) -> str:
"""格式化错误日志"""
parts = []
if tag:
@@ -127,31 +134,38 @@ def format_error_log(message: str, level: str = "ERROR", tag: Optional[str] = No
parts.append(kv)
return " ".join(parts)
def format_call_stack(stack: Optional[List[str]] = None) -> str:
if not stack:
return ""
return "\n".join(stack)
def format_parameters(params: Dict[str, Any]) -> str:
if not params:
return ""
return " ".join(f"{k}={v}" for k, v in params.items())
def format_variables(vars: Dict[str, Any]) -> str:
if not vars:
return ""
return " ".join(f"{k}={v}" for k, v in vars.items())
def format_exception(exc: BaseException) -> str:
import traceback
return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
def add_separators(text: str, label: Optional[str] = None) -> str:
if not label:
label = ""
sep = "=" * 80
return f"{sep}\n {label} \n{sep}\n{text}\n{sep}"
def add_colors(text: str, color: str = "green") -> str:
# 简易颜色支持,只有在控制台启用时有效
colors = {
@@ -230,15 +244,15 @@ def colorize_log_line(line: str) -> str:
__all__ = [
"format_debug_log",
"format_action_log",
"format_error_log",
"format_call_stack",
"format_parameters",
"format_variables",
"format_exception",
"add_separators",
"add_colors",
"beautify_log_output",
"colorize_log_line",
"format_debug_log",
"format_action_log",
"format_error_log",
"format_call_stack",
"format_parameters",
"format_variables",
"format_exception",
"add_separators",
"add_colors",
"beautify_log_output",
"colorize_log_line",
]
+80 -148
View File
@@ -917,6 +917,14 @@ def process_reservation_attend_window(
"""
start_time = time.time()
# 总超时兜底:避免预约分支在某些机型/状态下长时间阻塞导致主循环“看似卡死”。
try:
total_timeout_s = float(
getattr(analyser, "reservation_back_total_timeout_seconds", 20.0) or 20.0
)
except Exception:
total_timeout_s = 20.0
# 添加函数入口日志
try:
analyser._log_kv(
@@ -962,7 +970,76 @@ def process_reservation_attend_window(
)
# 按统一规则排序(防止外部遗漏 sort)
sort_reservations_callback()
# 这里不依赖外部 sort_reservations_callback:避免回调内部潜在阻塞/死锁导致主流程卡死。
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:开始队列排序",
reservations_count=len(reservations) if reservations else 0,
)
except Exception:
pass
# 超时检查
try:
if (time.time() - start_time) > total_timeout_s:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:超时退出(排序前)",
total_timeout_seconds=round(total_timeout_s, 3),
)
except Exception:
pass
return False
except Exception:
pass
try:
_sort_reservations_inplace(reservations)
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(reservations=reservations),
level="WARNING",
stage="队列排序",
)
else:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:队列排序异常(忽略)",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:队列排序完成",
earliest_future_ts=int(float((reservations[0].get("future_ts") or 0.0)))
if reservations
else 0,
)
except Exception:
pass
# 超时检查
try:
if (time.time() - start_time) > total_timeout_s:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:超时退出(排序后)",
total_timeout_seconds=round(total_timeout_s, 3),
)
except Exception:
pass
return False
except Exception:
pass
# 取队头(最早需要处理的一条)
target = reservations[0]
@@ -1512,7 +1589,7 @@ def process_reservation_attend_window(
except Exception:
pass
from douyin.reservation import douyin_reservation_verify
import douyin.reservation.douyin_reservation_verify as douyin_reservation_verify
verify_ok, verify_detail = (
douyin_reservation_verify.validate_back_to_reservation(
@@ -1556,7 +1633,7 @@ def process_reservation_attend_window(
try:
analyser._log_kv(
"预约",
"[预约] 回退校验失败:回退操作成功但校验未通过,尝试根据映射表自动回退到正确位置",
"[预约] 回退校验失败:回退操作成功但校验未通过(不再自动回退重试,避免循环卡死)",
target_pos=int(target.get("pos_seen", 0)),
target_room_title=(
target_room_title[:50]
@@ -1566,151 +1643,6 @@ def process_reservation_attend_window(
)
except Exception:
pass
# 校验失败,尝试根据映射表查找正确位置并自动回退
try:
if hasattr(analyser, "_find_room_pos_by_title"):
correct_pos = analyser._find_room_pos_by_title(
target_room_title, target_room_title_raw
)
if correct_pos is not None and correct_pos != int(
target.get("pos_seen", 0)
):
try:
analyser._log_kv(
"预约",
"[预约] 根据映射表找到正确位置,自动回退",
original_target_pos=int(
target.get("pos_seen", 0)
),
correct_pos=correct_pos,
target_room_title=(
target_room_title[:50]
if target_room_title
else ""
),
)
except Exception:
pass
# 更新目标位置并重新回退
target["pos_seen"] = correct_pos
try:
retry_ok = bool(
seek_reservation_room_callback(target)
)
if retry_ok:
# 重新进行校验
try:
verify_ok_retry, verify_detail_retry = (
douyin_reservation_verify.validate_back_to_reservation(
analyser=analyser,
item=target,
quick=False,
max_checks=3,
)
)
if verify_ok_retry:
try:
analyser._log_kv(
"预约",
"[预约] 根据映射表自动回退后校验通过",
correct_pos=correct_pos,
target_room_title=(
target_room_title[:50]
if target_room_title
else ""
),
)
except Exception:
pass
verify_ok = True
verify_detail = verify_detail_retry
ok = True
else:
try:
analyser._log_kv(
"预约",
"[预约] 根据映射表自动回退后校验仍失败",
correct_pos=correct_pos,
target_room_title=(
target_room_title[:50]
if target_room_title
else ""
),
)
except Exception:
pass
ok = False
except Exception as e:
try:
analyser._log_kv(
"预约",
"[预约] 根据映射表自动回退后重新校验时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
ok = False
else:
try:
analyser._log_kv(
"预约",
"[预约] 根据映射表自动回退操作失败",
correct_pos=correct_pos,
)
except Exception:
pass
ok = False
except Exception as e:
try:
analyser._log_kv(
"预约",
"[预约] 根据映射表自动回退时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
ok = False
elif correct_pos is None:
try:
analyser._log_kv(
"预约",
"[预约] 映射表中未找到目标直播间,无法自动回退",
target_room_title=(
target_room_title[:50]
if target_room_title
else ""
),
)
except Exception:
pass
ok = False
else:
try:
analyser._log_kv(
"预约",
"[预约] 映射表中的位置与目标位置相同,但校验仍失败",
target_pos=int(target.get("pos_seen", 0)),
)
except Exception:
pass
ok = False
else:
ok = False
except Exception as e:
try:
analyser._log_kv(
"预约",
"[预约] 根据映射表自动回退时发生异常",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
ok = False
else:
try:
analyser._log_kv(
+34 -244
View File
@@ -208,7 +208,8 @@ def validate_back_to_reservation(
) -> Tuple[bool, Optional[Tuple]]:
"""回退后校验:只校验直播间标题,不校验福袋。
如果直播间标题不符合,则根据映射表找到正确位置并回退。
注意:此函数仅做“校验”,不在内部执行任何回退/滑动等导航动作,
以避免在复杂 UI 状态下产生循环/卡死。回退动作由调用方统一控制。
参数:
analyser: 分析器对象
@@ -372,16 +373,20 @@ def validate_back_to_reservation(
current_title, current_title_raw = (
douyin_fudai_detail.read_live_room_title_core(analyser, y_pianyi_val)
)
try:
# 计算预期标题与当前标题的相似度
ratio = 0.0
if current_title and expected_title:
# 计算预期标题与当前标题的相似度
ratio = 0.0
if current_title and expected_title:
try:
import difflib as _difflib
ratio = _difflib.SequenceMatcher(
None, expected_title, current_title
).ratio()
except Exception:
ratio = 0.0
try:
analyser._log_kv(
"预约",
"回退校验:直播间名对比",
@@ -395,255 +400,40 @@ def validate_back_to_reservation(
except Exception:
pass
# 强不匹配:根据映射表找到正确位置并回退
if (
current_title
and (expected_title not in current_title)
and (current_title not in expected_title)
and ratio < 0.45
):
try:
analyser._log_kv(
"预约",
"回退校验:直播间标题不匹配,尝试根据映射表找到正确位置",
expected_title=(
expected_title[:50] if expected_title else ""
),
current_title=current_title[:50] if current_title else "",
ratio=round(ratio, 3),
)
except Exception:
pass
# 根据映射表找到正确位置
try:
if hasattr(analyser, "_find_room_pos_by_title"):
correct_pos = analyser._find_room_pos_by_title(
expected_title, expected_title_raw
)
if correct_pos is not None:
try:
analyser._log_kv(
"预约",
"回退校验:在映射表中找到正确位置,准备回退",
correct_pos=correct_pos,
current_pos=int(
getattr(analyser, "room_pos", 0) or 0
),
expected_title=(
expected_title[:50]
if expected_title
else ""
),
)
except Exception:
pass
# 回退到正确位置
try:
# 更新 item 中的 pos_seen
item["pos_seen"] = correct_pos
# 调用回退函数
if hasattr(analyser, "_seek_reservation_room"):
seek_ok = analyser._seek_reservation_room(item)
if seek_ok:
# 重新读取标题验证
try:
y_pianyi_val = int(
getattr(analyser, "y_pianyi", 0)
or 0
)
new_title, _new_title_raw = (
douyin_fudai_detail.read_live_room_title_core(
analyser, y_pianyi_val
)
)
if new_title:
new_ratio = 0.0
try:
new_ratio = float(
difflib.SequenceMatcher(
None,
expected_title,
new_title,
).ratio()
)
except Exception:
pass
if (
(expected_title in new_title)
or (new_title in expected_title)
or new_ratio >= 0.45
):
try:
analyser._log_kv(
"预约",
"回退校验:根据映射表回退后,标题匹配成功",
expected_title=(
expected_title[:50]
if expected_title
else ""
),
new_title=(
new_title[:50]
if new_title
else ""
),
new_ratio=round(
new_ratio, 3
),
)
except Exception:
pass
return True, None
else:
try:
analyser._log_kv(
"预约",
"回退校验:根据映射表回退后,标题仍不匹配",
expected_title=(
expected_title[:50]
if expected_title
else ""
),
new_title=(
new_title[:50]
if new_title
else ""
),
new_ratio=round(
new_ratio, 3
),
)
except Exception:
pass
return False, None
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(
item=item,
expected_title=(
expected_title[:50]
if expected_title
else ""
),
),
level="WARNING",
stage="根据映射表回退后重新读取标题",
)
else:
try:
analyser._log_kv(
"预约",
"回退校验:根据映射表回退后,重新读取标题失败",
error=str(e),
)
except Exception:
pass
return False, None
else:
try:
analyser._log_kv(
"预约",
"回退校验:根据映射表回退失败",
)
except Exception:
pass
return False, None
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(
item=item,
expected_title=(
expected_title[:50]
if expected_title
else ""
),
),
level="WARNING",
stage="根据映射表回退",
)
else:
try:
analyser._log_kv(
"预约",
"回退校验:根据映射表回退时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
return False, None
else:
try:
analyser._log_kv(
"预约",
"回退校验:映射表中未找到匹配的标题",
expected_title=(
expected_title[:50]
if expected_title
else ""
),
)
except Exception:
pass
return False, None
else:
try:
analyser._log_kv(
"预约",
"回退校验:analyser 没有 _find_room_pos_by_title 方法",
)
except Exception:
pass
return False, None
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(
item=item,
expected_title=(
expected_title[:50] if expected_title else ""
),
),
level="WARNING",
stage="根据映射表查找位置",
)
else:
try:
analyser._log_kv(
"预约",
"回退校验:根据映射表查找位置时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
return False, None
# 强不匹配:仅返回失败(不做任何回退动作)
if (
current_title
and (expected_title not in current_title)
and (current_title not in expected_title)
and ratio < 0.45
):
try:
analyser._log_kv(
"预约",
"回退校验:直播间标题不匹配(不在校验内自动回退)",
expected_title=(expected_title[:50] if expected_title else ""),
current_title=current_title[:50] if current_title else "",
ratio=round(ratio, 3),
)
except Exception:
pass
return False, None
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(
item=item,
),
format_reservation_context(item=item),
level="WARNING",
stage="读取直播间标题(外层)",
stage="读取直播间标题",
)
else:
try:
analyser._log_kv(
"预约", "回退校验:读取直播间标题失败", error=str(e)
"预约",
"回退校验:读取直播间标题失败",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
+5
View File
@@ -200,6 +200,11 @@ class ConfigManager:
config["reservation_back_swipe_delay"] or 0.6
)
if "reservation_back_total_timeout_seconds" in config:
analyser.reservation_back_total_timeout_seconds = float(
config["reservation_back_total_timeout_seconds"] or 20.0
)
if "reservation_preempt_min_value_yuan" in config:
analyser.reservation_preempt_min_value_yuan = float(
config["reservation_preempt_min_value_yuan"] or 0.0
+7 -2
View File
@@ -1061,6 +1061,13 @@ def read_fudai_detail_with_retries(
if last_status == "ok":
is_valid, reason = validate_fudai_detail(last_tuple, analyser)
if not is_valid:
# 先标记状态,避免日志异常导致未标记
try:
analyser._last_fudai_detail_status = "validation_failed" # type: ignore[attr-defined]
except Exception:
pass
# 同步本地状态用于后续日志输出
last_status = "validation_failed"
try:
analyser._log_kv(
"福袋详情",
@@ -1072,8 +1079,6 @@ def read_fudai_detail_with_retries(
copies=copies,
time_text=time_text[:30] if time_text else "",
)
# 标记为识别错误
analyser._last_fudai_detail_status = "validation_failed" # type: ignore[attr-defined]
except Exception:
pass