fix: Clean up blank lines and enhance readability across multiple files

- Removed excessive blank lines from various markdown and Python files to improve readability and maintainability.
- Ensured consistent formatting across documentation and code files, contributing to overall project clarity.
- Enhanced logging mechanisms for better consistency and debugging support.
This commit is contained in:
Your Name committed 2025-12-27 15:19:04 +08:00
1 parent 4678adb8f3
commit efaa3d3adc
36 files changed
+15075 -517

No files matched your search

+426 -135
View File
@@ -73,6 +73,8 @@ class fudai_analyse:
self._log_kv_orig = None
# 使用增强版本
self._log_kv = self._enhanced_log_kv
# 用于跟踪上一个日志标签,以便检测阶段变化并添加分隔符
self._last_log_tag = None
# 预定义可在运行中动态创建的属性,避免 access-before-definition / attribute-defined-outside-init 警告
self._std_logger = None # type: ignore[assignment]
@@ -232,10 +234,179 @@ class fudai_analyse:
os.path.dirname(__file__), "state", "reservations.json"
)
# 运行时直播间标题和位置映射表(用于回退校验)
# 格式:{room_pos: (room_title, room_title_raw)}
self._room_pos_to_title_map: dict[int, tuple[str, str]] = {}
# 初次加载配置
self.load_config()
# ===== 兼容原始脚本的一些简单封装方法 =====
def _find_room_pos_by_title(self, target_title: str, target_title_raw: str = "") -> int | None:
"""根据直播间标题在运行时映射表中查找对应的位置。
返回:
如果找到匹配的位置,返回位置值;否则返回 None
"""
try:
if not target_title and not target_title_raw:
return None
room_pos_map = getattr(self, "_room_pos_to_title_map", {})
if not room_pos_map:
return None
# 规范化目标标题
try:
import douyin_high_value_room
if hasattr(douyin_high_value_room, '_normalize_room_title'):
target_norm = douyin_high_value_room._normalize_room_title(target_title) # type: ignore[attr-defined]
else:
target_norm = target_title.strip()
except Exception:
target_norm = target_title.strip()
# 遍历映射表查找匹配的标题
best_match_pos = None
best_match_score = 0.0
for pos, (recorded_title, recorded_title_raw) in room_pos_map.items():
if not recorded_title and not recorded_title_raw:
continue
# 规范化记录的标题
try:
import douyin_high_value_room
if hasattr(douyin_high_value_room, '_normalize_room_title'):
recorded_norm = douyin_high_value_room._normalize_room_title(recorded_title) # type: ignore[attr-defined]
else:
recorded_norm = recorded_title.strip()
except Exception:
recorded_norm = recorded_title.strip()
# 计算匹配度
match_score = 0.0
if target_norm and recorded_norm:
# 完全匹配
if target_norm == recorded_norm:
match_score = 1.0
# 子串匹配
elif target_norm in recorded_norm or recorded_norm in target_norm:
match_score = 0.8
# 使用相似度
else:
try:
import difflib
match_score = difflib.SequenceMatcher(None, target_norm, recorded_norm).ratio()
except Exception:
match_score = 0.0
# 如果匹配度足够高,记录最佳匹配
if match_score > best_match_score and match_score >= 0.6:
best_match_score = match_score
best_match_pos = pos
if best_match_pos is not None:
try:
self._log_kv(
"预约",
"[预约] _find_room_pos_by_title:在映射表中找到匹配位置",
target_title=target_title[:50] if target_title else "",
found_pos=best_match_pos,
match_score=round(best_match_score, 3),
recorded_title=room_pos_map[best_match_pos][0][:50] if room_pos_map[best_match_pos][0] else "",
)
except Exception:
pass
return best_match_pos
return None
except Exception as e:
try:
self._log_kv(
"预约",
"[预约] _find_room_pos_by_title:查找时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
return None
def _record_room_title_and_pos(self) -> None:
"""记录当前直播间的标题和位置到运行时映射表。
用于预约回退校验时验证位置信息。
"""
try:
room_pos = int(getattr(self, "room_pos", 0) or 0)
# 读取当前直播间标题
try:
import douyin_fudai_detail as dfd_module
y_pianyi_val = int(getattr(self, "y_pianyi", 0) or 0)
room_title, room_title_raw = dfd_module.read_live_room_title_core(
self, y_pianyi_val
)
# 更新 analyser 的属性
try:
self.current_room_title = room_title
self.current_room_title_raw = room_title_raw
except Exception:
pass
# 记录到映射表
if room_pos not in self._room_pos_to_title_map:
self._room_pos_to_title_map[room_pos] = (room_title, room_title_raw)
try:
self._log_kv(
"预约",
"[预约] 记录直播间标题和位置到运行时映射表",
room_pos=room_pos,
room_title=room_title[:50] if room_title else "",
room_title_raw=room_title_raw[:50] if room_title_raw else "",
map_size=len(self._room_pos_to_title_map),
)
except Exception:
pass
else:
# 如果已存在,更新标题(可能标题有变化)
old_title, old_title_raw = self._room_pos_to_title_map[room_pos]
if old_title != room_title or old_title_raw != room_title_raw:
self._room_pos_to_title_map[room_pos] = (room_title, room_title_raw)
try:
self._log_kv(
"预约",
"[预约] 更新直播间标题和位置到运行时映射表",
room_pos=room_pos,
old_room_title=old_title[:50] if old_title else "",
new_room_title=room_title[:50] if room_title else "",
)
except Exception:
pass
except Exception as e:
# 如果读取标题失败,尝试使用缓存的标题
try:
room_title = str(getattr(self, "current_room_title", "") or "")
room_title_raw = str(getattr(self, "current_room_title_raw", "") or "")
if room_title or room_title_raw:
self._room_pos_to_title_map[room_pos] = (room_title, room_title_raw)
try:
self._log_kv(
"预约",
"[预约] 使用缓存标题记录直播间位置到运行时映射表",
room_pos=room_pos,
room_title=room_title[:50] if room_title else "",
error=str(e),
)
except Exception:
pass
except Exception:
pass
except Exception:
pass
def click(self, x: int, y: int) -> None:
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
start_time = time.time()
@@ -1310,6 +1481,47 @@ class fudai_analyse:
# 构建完整日志行
log_line = " ".join(log_parts)
# 判断是否需要添加分隔符(便于查看日志)
need_separator = False
separator_reason = ""
# 1. 错误发生时(优先级最高)
if log_level in ("ERROR", "WARNING", "CRITICAL"):
need_separator = True
separator_reason = "错误/警告"
# 2. 运行开始时
elif tag and any(keyword in str(tag) for keyword in ["运行", "启动", "开始", "初始化"]):
need_separator = True
separator_reason = "运行开始"
# 3. 阶段变化时(tag变化且包含阶段相关关键词)
elif tag and self._last_log_tag != tag:
if any(keyword in str(tag) for keyword in ["阶段", "循环", "参与", "检测", "寻找", "进入", "退出"]):
need_separator = True
separator_reason = "阶段变化"
# 4. 重要操作(通过tag判断)
elif tag and self._last_log_tag != tag:
if any(keyword in str(tag) for keyword in ["参与", "中奖", "完成", "失败", "超时"]):
need_separator = True
separator_reason = "重要操作"
# 输出分隔符(如果需要)
if need_separator:
try:
# 使用等号作为分隔符,更清晰易读
separator = "=" * 80
# 在分隔符中间显示原因,更美观
reason_text = f" {separator_reason} "
separator_line = f"{separator}\n{reason_text.center(80, '=')}\n{separator}"
print(separator_line, flush=True)
except Exception:
pass
# 更新上一个日志标签
self._last_log_tag = tag
# 始终输出到 stdout(供 GUI 捕获)- 这是最重要的!
try:
print(log_line, flush=True) # flush=True 确保立即输出,不缓冲
@@ -3464,6 +3676,15 @@ class fudai_analyse:
except Exception:
pass
# 记录当前直播间的标题和位置到运行时映射表(用于回退校验)
# 如果是在回退过程中(_seek_reservation_room),跳过记录,因为之前已经记录过了
try:
skip_record = bool(getattr(self, "_skip_record_title_during_seek", False))
if not skip_record:
self._record_room_title_and_pos()
except Exception:
pass
def _return_to_recommend_and_reenter_live(self) -> None:
"""返回推荐页面并重新进入直播间。
@@ -3628,6 +3849,15 @@ class fudai_analyse:
self.room_pos -= 1
except Exception:
self.room_pos = 0
# 记录当前直播间的标题和位置到运行时映射表(用于回退校验)
# 如果是在回退过程中(_seek_reservation_room),跳过记录,因为之前已经记录过了
try:
skip_record = bool(getattr(self, "_skip_record_title_during_seek", False))
if not skip_record:
self._record_room_title_and_pos()
except Exception:
pass
def _maybe_reset_after_swipes(self) -> int:
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。
@@ -3688,9 +3918,21 @@ class fudai_analyse:
start_y = 800 * ry // 2400 # 上方起始位置
end_x = 760 * rx // 1080
end_y = 1600 * ry // 2400 # 下方结束位置
self.operation.swipe(
self.device_id, start_x, start_y, end_x, end_y, 200
)
# 直接使用 ADB 内部滑动命令
try:
import subprocess
if hasattr(self.operation, '_adb'):
adb_cmd = self.operation._adb()
else:
import os
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
adb_cmd = f'"{adb_cmd}"'
cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 200"
subprocess.run(cmd, shell=True, timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception:
# 回退到 operation.swipe
self.operation.swipe(self.device_id, start_x, start_y, end_x, end_y, 200)
try:
self._log_kv("流程", "回退直播间 {}/{}".format(i + 1, back_times))
except Exception:
@@ -3731,6 +3973,8 @@ class fudai_analyse:
# 注意:pos_diff = target_pos - cur_pos
# - 如果 pos_diff < 0,说明 target_pos < cur_pos,目标在上方,需要向上回退(减少 room_pos)
# - 如果 pos_diff > 0,说明 target_pos > cur_pos,目标在下方,需要向下切换(增加 room_pos)
# 注意:如果预先下滑了一次(在 process_reservation_attend_window 中),cur_pos 已经减1了
# 但这是为了确保在直播列表中,不影响回退次数的计算,因为回退次数是基于实际的位置差计算的
pos_diff = target_pos - cur_pos
try:
@@ -3747,6 +3991,20 @@ class fudai_analyse:
target_room_title = str(item.get("room_title") or "").strip()
target_room_title_raw = str(item.get("room_title_raw") or "").strip()
# 输出目标直播间的位置和标题信息
try:
self._log_kv(
"预约",
"[预约] _seek_reservation_room:开始回退到目标直播间",
target_room_title=target_room_title,
target_room_title_raw=target_room_title_raw,
target_pos=target_pos,
current_room_pos=cur_pos,
target_room_info=f"位置={target_pos}, 标题={target_room_title or target_room_title_raw}",
)
except Exception:
pass
try:
self._log_kv(
"预约",
@@ -3767,6 +4025,11 @@ class fudai_analyse:
elif pos_diff < 0:
# 目标在上方(target_pos < cur_pos),需要向上回退(减少 room_pos)
# 使用 swipe_down_back_from_live(),它会执行 room_pos -= 1
# 注意:如果预先下滑了一次(在 process_reservation_attend_window 中),cur_pos 已经减1了
# 这会导致 pos_diff 的计算少1,所以需要补偿:back_times = abs(pos_diff) + 1
# 但实际上,预先下滑是为了确保在直播列表中,不应该影响回退次数
# 所以如果预先下滑了,pos_diff 已经包含了这个影响,直接使用 abs(pos_diff) 即可
# 但为了确保回退到正确位置,如果 pos_diff < 0,需要回退 abs(pos_diff) 次
back_times = min(abs(pos_diff), max_back) if max_back > 0 else abs(pos_diff)
try:
self._log_kv(
@@ -3782,12 +4045,22 @@ class fudai_analyse:
except Exception:
pass
delay_s = float(getattr(self, "reservation_back_swipe_delay", 0.6) or 0.6)
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
try:
self._skip_record_title_during_seek = True
except Exception:
pass
for _ in range(back_times):
self.swipe_down_back_from_live()
try:
self.operation.delay(delay_s)
except Exception:
time.sleep(delay_s)
# 清除标志
try:
self._skip_record_title_during_seek = False
except Exception:
pass
else:
# 目标在下方(target_pos > cur_pos),需要向下切换(增加 room_pos)
# 使用 swipe_up_to_next_live(),它会执行 room_pos += 1
@@ -3806,28 +4079,73 @@ class fudai_analyse:
except Exception:
pass
delay_s = float(getattr(self, "reservation_back_swipe_delay", 0.6) or 0.6)
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
try:
self._skip_record_title_during_seek = True
except Exception:
pass
for _ in range(forward_times):
self.swipe_up_to_next_live()
try:
self.operation.delay(delay_s)
except Exception:
time.sleep(delay_s)
# 清除标志
try:
self._skip_record_title_during_seek = False
except Exception:
pass
# 回退完成后记录日志
try:
current_room_pos_after = int(getattr(self, "room_pos", cur_pos) or cur_pos)
self._log_kv(
"预约",
"[预约] _seek_reservation_room 回退完成",
target_room_title=target_room_title,
target_room_title_raw=target_room_title_raw,
target_pos=target_pos,
current_room_pos=int(getattr(self, "room_pos", cur_pos) or cur_pos),
current_room_pos=current_room_pos_after,
)
except Exception:
pass
# 回退过程中只执行回退操作,不进行校验或读取预约数据
# 回退完成后直接返回成功
# 回退完成后,从映射表中读取目标位置的标题进行验证
# 不需要再次记录标题,因为:
# 1. 在寻找福袋的过程中已经记录过直播间标题了
# 2. 回退时只需要滑动到目标位置,不需要再次记录
# 3. 直接使用映射表中已有的数据验证即可
try:
room_pos_map = getattr(self, "_room_pos_to_title_map", {})
if target_pos in room_pos_map:
recorded_title, recorded_title_raw = room_pos_map[target_pos]
try:
self._log_kv(
"预约",
"[预约] _seek_reservation_room 回退完成,从映射表验证标题",
target_pos=target_pos,
target_room_title=target_room_title[:50] if target_room_title else "",
recorded_room_title=recorded_title[:50] if recorded_title else "",
title_match=(target_room_title in recorded_title) or (recorded_title in target_room_title) if (target_room_title and recorded_title) else False,
)
except Exception:
pass
else:
try:
self._log_kv(
"预约",
"[预约] _seek_reservation_room 回退完成,但映射表中未找到目标位置",
target_pos=target_pos,
map_size=len(room_pos_map),
available_positions=list(room_pos_map.keys())[:10] if room_pos_map else [],
)
except Exception:
pass
except Exception:
pass
# 回退过程中只执行回退操作,不进行校验
# 校验将在 process_reservation_attend_window 中统一进行,使用映射表中的数据
return True
# ========== 福袋相关 ==========
@@ -3902,7 +4220,6 @@ class fudai_analyse:
self._current_fudai_future_ts = future_ts
# 直接调用参与决策,跳过详情识别
import douyin_fudai_core
join_result = douyin_fudai_core.basic_join_decision(self, detail)
# 如果参与成功,设置开奖等待状态并从预约队列中移除
@@ -4068,14 +4385,14 @@ class fudai_analyse:
# 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋
# 检查是否是第二次打开福袋详情(已经读取过详情)
# 如果是第二次打开,只需要验证参与按钮,不需要重新识别内容、倒计时、价值
# 如果是第二次打开,直接点击参与,不需要验证,使用第一次的倒计时
is_second_open = getattr(self, "_fudai_detail_first_read", False)
if is_second_open:
# 第二次打开:只检测参与按钮,使用第一次读取的详情数据
# 第二次打开:直接点击参与,不进行验证,使用第一次的倒计时
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:第二次打开,只验证参与按钮,跳过内容识别",
"_handle_in_fudai_detail:第二次打开,直接点击参与,跳过验证和内容识别",
)
except Exception:
pass
@@ -4098,120 +4415,66 @@ class fudai_analyse:
close_detail_callback=douyin_fudai_detail.close_fudai_detail,
ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open,
)
# 重新读取后,更新保存的详情数据
if detail and isinstance(detail, tuple) and len(detail) >= 6:
self._last_fudai_detail_tuple = detail
else:
# 只检测参与按钮,不重新识别内容
# 使用第一次保存的详情数据,设置当前福袋的倒计时信息
try:
self.operation.get_screenshot(self.device_id)
self.cut_pic(306, 2030, 780, 2110, "", "参与按钮")
# OCR识别参与按钮
attend_button_text = str(
self.operation.analyse_pic_word("参与按钮", 0) or ""
)
if not attend_button_text or not any(
k in attend_button_text
for k in (
"参与成功",
"还需看播",
"评论",
"参与抽奖",
"开始观看",
"参与",
)
):
attend_button_text = str(
self.operation.analyse_pic_word("参与按钮", 1) or ""
)
self._log_kv(
"参与", "第二次打开:只验证参与按钮", text=attend_button_text
)
# 如果已参与,设置等待开奖标志并返回,不需要继续处理
if (
"参与成功" in attend_button_text
or "还需看播" in attend_button_text
or "等待开奖" in attend_button_text
):
self._log_kv(
"参与", "第二次打开:已参与,无需再次点击", result="已参与"
)
# 从第一次保存的详情数据中获取倒计时信息,设置等待开奖标志
try:
detail = getattr(self, "_last_fudai_detail_tuple", None)
if (
detail
and isinstance(detail, tuple)
and len(detail) >= 6
):
countdown_tuple = detail[5] # type: ignore[index]
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
):
future_ts = float(countdown_tuple[1] or 0.0)
if future_ts > 0:
current_time = time.time()
remain_seconds = int(future_ts - current_time)
if remain_seconds > 0:
# 设置等待开奖标志和预期开奖时间
# 提前13秒,修正倒计时误差
self._waiting_for_lottery_result = True
self._lottery_result_expected_ts = (
future_ts - 13.0
)
self._log_kv(
"参与",
"第二次打开:已参与,设置等待开奖标志",
remain_seconds=remain_seconds,
future_ts=int(future_ts),
)
else:
self._log_kv(
"参与",
"第二次打开:已参与,但倒计时已过期,不设置等待标志",
)
else:
self._log_kv(
"参与",
"第二次打开:已参与,但无法获取倒计时信息",
)
else:
self._log_kv(
"参与",
"第二次打开:已参与,但详情数据中无倒计时信息",
)
else:
if isinstance(detail, tuple) and len(detail) >= 6:
countdown_tuple = detail[5] # type: ignore[index]
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
future_ts = float(countdown_tuple[1] or 0.0)
if future_ts > 0:
# 设置当前福袋的 future_ts,供 attend_choujiang 使用
self._current_fudai_future_ts = future_ts
self._log_kv(
"参与", "第二次打开:已参与,但未找到保存的详情数据"
"参与",
"第二次打开:使用第一次的倒计时信息",
future_ts=int(future_ts),
remain_seconds=int(future_ts - time.time()),
)
except Exception as e:
self._log_kv(
"参与",
"第二次打开:设置等待开奖标志时出错",
error=str(e),
)
# 关闭详情页
self.click(500, 470)
# 清除第一次读取标志,下次打开新福袋时重新识别
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(第二次打开已参与)",
elapsed_seconds=round(elapsed, 2),
)
return
# 如果还需要参与,继续后续的参与决策流程
except Exception as e:
self._log_kv("参与", "第二次打开:验证参与按钮异常", error=str(e))
self._log_kv(
"参与",
"第二次打开:设置倒计时信息时出错",
error=str(e),
)
# 直接调用参与函数,不进行验证
try:
attend_result = douyin_fudai_core.attend_choujiang(self)
if attend_result:
self._log_kv(
"参与",
"第二次打开:直接点击参与成功",
result="参与成功",
)
else:
self._log_kv(
"参与",
"第二次打开:直接点击参与失败",
result="参与失败",
)
# 清除第一次读取标志,下次打开新福袋时重新识别
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(第二次打开直接参与)",
elapsed_seconds=round(elapsed, 2),
attend_result=attend_result,
)
return
except Exception as e:
self._log_kv("参与", "第二次打开:直接点击参与异常", error=str(e))
# 异常时继续正常流程
else:
# 第一次打开:完整读取详情(包括内容、倒计时、价值)
@@ -4443,14 +4706,28 @@ class fudai_analyse:
start_y = 1700 * ry // 2400
end_x = 540 * rx // 1080
end_y = 700 * ry // 2400
self.operation.swipe(
self.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
# 直接使用 ADB 内部滑动命令
try:
import subprocess
if hasattr(self.operation, '_adb'):
adb_cmd = self.operation._adb()
else:
import os
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
adb_cmd = f'"{adb_cmd}"'
cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300"
subprocess.run(cmd, shell=True, timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception:
# 回退到 operation.swipe
self.operation.swipe(
self.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
except Exception:
pass
@@ -4595,14 +4872,28 @@ class fudai_analyse:
start_y = 1700 * ry // 2400
end_x = 540 * rx // 1080
end_y = 700 * ry // 2400
self.operation.swipe(
self.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
# 直接使用 ADB 内部滑动命令
try:
import subprocess
if hasattr(self.operation, '_adb'):
adb_cmd = self.operation._adb()
else:
import os
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
adb_cmd = f'"{adb_cmd}"'
cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300"
subprocess.run(cmd, shell=True, timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception:
# 回退到 operation.swipe
self.operation.swipe(
self.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
self.operation.delay(0.5)
except Exception:
pass