Files
douyin_guaji-main/douyin_reservation_verify.py
T
Your Name efaa3d3adc 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.
2025-12-27 15:19:04 +08:00

461 lines
21 KiB
Python

from __future__ import annotations
"""
预约回退校验模块
================
提供回退到预约直播间后的详细校验功能:
- 直播间名称匹配
- 福袋详情匹配(内容、价值、开奖时间)
- 任务类型检查(排除"观看XX分钟"类任务)
"""
from typing import Any, Dict, Tuple, Optional
import re
import difflib
import time
import douyin_fudai_detail
def _compact_text(text: str) -> str:
"""压缩文本:去除空格,用于比较。"""
try:
return re.sub(r"\s+", "", str(text or "")).strip()
except Exception:
return ""
def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, Dict[str, Any]]:
"""校验回退后的福袋详情是否匹配预约。返回 (ok, reason, debug_dict)
参数:
item: 预约项字典
detail: 福袋详情 tuple (content, time_text, participants, copies, prize_value_yuan, countdown_tuple)
返回:
(is_match, reason, debug_dict)
"""
try:
expected_value = float(item.get("prize_value_yuan") or 0.0)
except Exception:
expected_value = 0.0
try:
expected_future = float(item.get("future_ts") or 0.0)
except Exception:
expected_future = 0.0
expected_content = _compact_text(item.get("content") or "")
if not isinstance(detail, tuple) or len(detail) < 6:
return False, "detail_invalid", {
"expected_future": expected_future,
"expected_value": expected_value,
"expected_content": expected_content,
}
fc, tt, participants, copies, pv, cd = detail[:6]
actual_content = _compact_text(fc or "")
try:
actual_value = float(pv or 0.0)
except Exception:
actual_value = 0.0
try:
actual_future = float(cd[1] if (isinstance(cd, (tuple, list)) and len(cd) >= 2) else 0.0)
except Exception:
actual_future = 0.0
# 检查是否为"观看XX分钟"类任务:若是,则视为任务型福袋,回退校验应判为不匹配(跳过预约)
try:
fc_full = str(fc or "")
chinese_num_chars = "零一二三四五六七八九十百千两"
patt = rf"(?:观看|看)(?:直播)?\s*(?:\d+|[{chinese_num_chars}]+)\s*分钟"
if re.search(patt, fc_full):
return False, "watch_task_detected", {
"expected_future": expected_future,
"actual_future": actual_future,
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
except Exception:
pass
# future 必须可验证(否则无法确认回退成功)
if not (expected_future > 0 and actual_future > 0):
return False, "future_missing", {
"expected_future": expected_future,
"actual_future": actual_future,
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
future_diff = abs(expected_future - actual_future)
# value/content 二选一命中即可(OCR 有误差,且部分福袋可能不展示价值)
value_ok = False
if expected_value > 0 and actual_value > 0:
tol = max(50.0, expected_value * 0.25)
value_ok = abs(expected_value - actual_value) <= tol
content_ok = False
if expected_content and actual_content:
content_ok = (expected_content in actual_content) or (actual_content in expected_content)
if not (value_ok or content_ok):
return False, "content_or_value_mismatch", {
"expected_future": expected_future,
"actual_future": actual_future,
"future_diff_s": int(future_diff),
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
# 优先用 future 精确匹配;但在"内容+价值都一致"时,允许一定范围的 future 偏差,避免 OCR 倒计时误读导致误判。
# 说明:正常情况下 future_diff 应该很小;若 future_diff 过大仍会判不匹配。
if future_diff > 180:
if value_ok and content_ok and future_diff <= 1200:
return True, "future_mismatch_relaxed", {
"expected_future": expected_future,
"actual_future": actual_future,
"future_diff_s": int(future_diff),
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
return False, "future_mismatch", {
"expected_future": expected_future,
"actual_future": actual_future,
"future_diff_s": int(future_diff),
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
return True, "ok", {
"expected_future": expected_future,
"actual_future": actual_future,
"future_diff_s": int(future_diff),
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
def validate_back_to_reservation(
analyser: Any,
item: Dict[str, Any],
quick: bool = False,
max_checks: int = 3,
) -> Tuple[bool, Optional[Tuple]]:
"""回退后校验:只校验直播间标题,不校验福袋。
如果直播间标题不符合,则根据映射表找到正确位置并回退。
参数:
analyser: 分析器对象
item: 预约项字典
quick: 是否快速模式(减少检查次数)
max_checks: 最大检查次数(未使用,保留兼容性)
返回:
(is_valid, None) - 如果校验通过返回 True,否则返回 False
"""
try:
analyser._log_kv(
"预约",
"[预约] validate_back_to_reservation:函数入口",
target_pos=int(item.get("pos_seen", 0)),
target_room_title=str(item.get("room_title", ""))[:50],
quick=quick,
max_checks=max_checks,
level="DEBUG",
)
except Exception:
pass
# 若开关关闭,则跳过复杂校验,直接认为回退成功以加速流程
try:
verify_enabled = bool(getattr(analyser, "reservation_back_verify_enabled", True))
if not verify_enabled:
try:
analyser._log_kv("预约", "回退校验已被禁用:跳过校验", level="DEBUG")
except Exception:
pass
return True, None
except Exception:
pass
# 先用"直播间名"做一次快速判断:不匹配则大概率回错房间,优先驱动微调继续找
try:
# 使用 douyin_high_value_room 中的规范化函数
import douyin_high_value_room
if hasattr(douyin_high_value_room, '_normalize_room_title'):
expected_title = douyin_high_value_room._normalize_room_title(item.get("room_title") or "") # type: ignore[attr-defined]
else:
expected_title = str(item.get("room_title") or "").strip()
except Exception:
try:
expected_title_raw_text = str(item.get("room_title") or "")
# 简单的规范化:去除空格和特殊字符
expected_title = re.sub(r"\s+", "", expected_title_raw_text).strip()
# 去掉常见无关词
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"):
expected_title = expected_title.replace(w, "")
expected_title = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", expected_title)
except Exception:
expected_title = str(item.get("room_title") or "").strip()
expected_title_raw = str(item.get("room_title_raw") or "").strip()
# 使用运行时映射表验证位置信息
target_pos_seen = int(item.get("pos_seen") or 0)
try:
room_pos_map = getattr(analyser, "_room_pos_to_title_map", {})
if target_pos_seen in room_pos_map:
recorded_title, recorded_title_raw = room_pos_map[target_pos_seen]
try:
analyser._log_kv(
"预约",
"回退校验:运行时映射表验证位置信息",
target_pos=target_pos_seen,
expected_room_title=expected_title[:50] if expected_title else "",
recorded_room_title=recorded_title[:50] if recorded_title else "",
expected_room_title_raw=expected_title_raw[:50] if expected_title_raw else "",
recorded_room_title_raw=recorded_title_raw[:50] if recorded_title_raw else "",
)
except Exception:
pass
# 如果映射表中的标题与预期标题匹配,增强验证信心
if expected_title and recorded_title:
try:
import douyin_high_value_room
if hasattr(douyin_high_value_room, '_normalize_room_title'):
expected_norm = douyin_high_value_room._normalize_room_title(expected_title) # type: ignore[attr-defined]
recorded_norm = douyin_high_value_room._normalize_room_title(recorded_title) # type: ignore[attr-defined]
if expected_norm == recorded_norm or expected_norm in recorded_norm or recorded_norm in expected_norm:
try:
analyser._log_kv(
"预约",
"回退校验:运行时映射表验证通过,位置和标题匹配",
target_pos=target_pos_seen,
)
except Exception:
pass
except Exception:
pass
else:
try:
analyser._log_kv(
"预约",
"回退校验:运行时映射表中未找到目标位置",
target_pos=target_pos_seen,
map_size=len(room_pos_map),
available_positions=list(room_pos_map.keys())[:10] if room_pos_map else [],
)
except Exception:
pass
except Exception as e:
try:
analyser._log_kv(
"预约",
"回退校验:运行时映射表验证时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
if expected_title:
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
current_title, current_title_raw = douyin_fudai_detail.read_live_room_title_core(
analyser, y_pianyi_val
)
# 更新 analyser 的属性
try:
analyser.current_room_title = current_title
analyser.current_room_title_raw = current_title_raw
except Exception:
pass
if current_title:
ratio = 0.0
try:
ratio = float(difflib.SequenceMatcher(None, expected_title, current_title).ratio())
except Exception:
ratio = 0.0
try:
analyser._log_kv(
"预约",
"回退校验:直播间名对比",
room_title_expected=expected_title,
room_title_current=current_title,
room_title_raw_expected=expected_title_raw,
room_title_raw_current=current_title_raw,
room_title_ratio=round(ratio, 3),
)
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:
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:
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:
try:
analyser._log_kv(
"预约",
"回退校验:根据映射表查找位置时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
return False, None
except Exception as e:
try:
analyser._log_kv("预约", "回退校验:读取直播间标题失败", error=str(e))
except Exception:
pass
# 如果标题匹配或没有标题,校验通过
try:
analyser._log_kv(
"预约",
"回退校验通过:直播间标题匹配",
target_room_title=str(item.get("room_title") or "").strip()[:50],
)
except Exception:
pass
return True, None