Files
douyin_guaji-main/douyin/reservation/douyin_reservation_handler_pkg/find_room.py
T
CodexandClaude Opus 4.7 85bd488f66 拆分 douyin_reservation_handler (1314 → 6 个子模块 + 29 行 shim)
把 douyin/reservation/douyin_reservation_handler.py 按职责拆成
douyin/reservation/douyin_reservation_handler_pkg/ 子包:

- find_room (169)       find_room_pos_by_title 按标题查找直播间位置
- record_title (333)    record_room_title_and_pos 记录直播间标题与位置
- seek_room (319)       seek_reservation_room 回退到目标预约直播间
- direct_attend (441)   handle_reservation_direct_attend 预约直接参与
- dump_state (180)      _dump_room_pos_map_to_state 序列化映射到 state 文件
- handler (43)          ReservationHandler 类(薄壳,每个 staticmethod 1 行 forwarding)

策略亮点:原 ReservationHandler 4 个方法都是 @staticmethod 且第一个参数为
analyser,搬出来成 module-level 函数后,类方法变成 1 行 forwarding。
公共 API 100% 保留:ReservationHandler.method(analyser, ...) 完全不需要改。

外部 import 路径不变:
``from douyin.reservation.douyin_reservation_handler import ReservationHandler``
仍可用(原文件改成 29 行 re-export shim)。
- ReservationHandler 5 处外部引用
- find_room_pos_by_title 2 处外部引用
- handle_reservation_direct_attend / _dump_room_pos_map_to_state 各 1 处
全部不需修改。

回归:
- 7 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- ReservationHandler.find_room_pos_by_title / module-level 函数 / 顶层
  _dump_room_pos_map_to_state 都能正常调用

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 18:21:40 +08:00

170 lines
5.8 KiB
Python

"""douyin_reservation_handler_pkg.find_room - 按直播间标题查找位置。
find_room_pos_by_title:在 analyser._room_pos_to_title_map 中按规范化标题
查找对应位置(用于回退时识别目标直播间)。
"""
from __future__ import annotations
import csv
import difflib
import json
import os
import time
from typing import Any, Dict, Optional
from douyin.core import path_config
from douyin.fudai import douyin_fudai_detail
from douyin.handlers import douyin_swipe_handler
from douyin.reservation import douyin_reservation_logic
# 错误处理工具占位(与原文件保持兼容降级)
try:
from douyin.reservation.core.reservation_error_utils import (
log_reservation_error,
format_reservation_context,
)
_RESERVATION_ERROR_UTILS_AVAILABLE = True
except ImportError:
def log_reservation_error(*args, **kwargs):
return None
def format_reservation_context(*args, **kwargs):
return {}
_RESERVATION_ERROR_UTILS_AVAILABLE = False
def find_room_pos_by_title(
analyser: Any, target_title: str, target_title_raw: str = ""
) -> Optional[int]:
"""根据直播间标题在运行时映射表中查找对应的位置。
参数:
analyser: 分析器对象
target_title: 目标标题
target_title_raw: 目标原始标题
返回:
如果找到匹配的位置,返回位置值;否则返回 None
"""
try:
if not target_title and not target_title_raw:
return None
room_pos_map = getattr(analyser, "_room_pos_to_title_map", {})
if not room_pos_map:
return None
# 规范化目标标题
try:
from douyin.other import douyin_high_value_room
if hasattr(douyin_high_value_room, "_normalize_room_title"):
target_norm = douyin_high_value_room._normalize_room_title( # type: ignore[attr-defined]
target_title
)
else:
target_norm = target_title.strip()
except Exception:
target_norm = target_title.strip()
# 遍历映射表查找匹配的标题
best_match_pos: Optional[int] = None
best_match_score = 0.0
for pos, room_info in room_pos_map.items():
if isinstance(room_info, dict):
recorded_title = room_info.get("title", "")
recorded_title_raw = room_info.get("title_raw", "")
else:
# 兼容旧格式
recorded_title, recorded_title_raw = room_info
if not recorded_title and not recorded_title_raw:
continue
# 规范化记录的标题
try:
from douyin.other import douyin_high_value_room
if hasattr(douyin_high_value_room, "_normalize_room_title"):
recorded_norm = douyin_high_value_room._normalize_room_title( # type: ignore[attr-defined]
recorded_title
)
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:
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:
room_info = room_pos_map[best_match_pos]
if isinstance(room_info, dict):
recorded_title = room_info.get("title", "")
else:
recorded_title = room_info[0] if room_info else ""
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] _find_room_pos_by_title:在映射表中找到匹配位置",
log_type="OP",
target_title=target_title[:50] if target_title else "",
found_pos=best_match_pos,
match_score=round(best_match_score, 3),
recorded_title=recorded_title[:50] if recorded_title else "",
)
except Exception:
pass
return best_match_pos
return None
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(
target_title=target_title[:50] if target_title else "",
target_title_raw=(
target_title_raw[:50] if target_title_raw else ""
),
),
level="WARNING",
stage="根据标题查找位置",
)
else:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] _find_room_pos_by_title:查找时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
return None