From 2899c932c47b37ee2871113f0471f49bf3b0eda8 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 22 May 2026 13:40:48 +0800 Subject: [PATCH] =?UTF-8?q?refactor(fudai):=20=E6=8A=BD=20=5F=5Finit=5F=5F?= =?UTF-8?q?=20=E4=B8=AD"=E6=97=A5=E5=BF=97=E7=B3=BB=E7=BB=9F=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E5=8C=96=20+=20=E6=98=A0=E5=B0=84=E8=A1=A8=E6=B8=85?= =?UTF-8?q?=E7=90=86=20+=20=E8=BF=90=E8=A1=8C=E6=97=B6=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E6=A0=87=E5=BF=97"=E5=9D=97=E5=88=B0=20fudai=5Finit=5Fdefaults?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将 __init__ 中 3 个独立的初始化块抽到 helper: - init_logging_system:MDC trace_id + _std_logger 配置(约 28 行) - cleanup_old_room_pos_map_files:删除 JSON/CSV/MD 旧导出(约 18 行) - init_runtime_state_flags:运行时状态标志初始化(约 28 行) douyin_fudai.py: 870 → 809 行 (-61) fudai_init_defaults.py: 132 → 210 行 douyin_fudai.py 跌破 850 行(4121 → 809,本会话累计削减 3312 行 = -80%) 验证: - pytest 1013 passed - compile OK Co-Authored-By: Claude Opus 4.7 (1M context) --- douyin/core/douyin_fudai.py | 81 +++---------------- .../core/fudai_modules/fudai_init_defaults.py | 78 ++++++++++++++++++ 2 files changed, 88 insertions(+), 71 deletions(-) diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index a96f533..c7bee0b 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -87,35 +87,14 @@ class fudai_analyse: # 预定义可在运行中动态创建的属性,避免 access-before-definition / attribute-defined-outside-init 警告 self._std_logger = None # type: ignore[assignment] - # 初始化统一日志系统和traceId - # 确保日志系统已配置(在实例化之前) - try: - from douyin.logging import douyin_logging + # 初始化统一日志系统和 traceId + from douyin.core.fudai_modules.fudai_init_defaults import ( + cleanup_old_room_pos_map_files, + init_logging_system, + init_runtime_state_flags, + ) - # 检查 _logging_configured 标志是否存在 - if not getattr(douyin_logging, "_logging_configured", False): - douyin_logging.configure_logging() - except Exception as e: - logging.warning("日志系统初始化失败: %s", e) - - try: - from douyin.logging.unified_logger import MDC, get_unified_logger - - # 为当前实例设置traceId - MDC.set_trace_id(f"run_{self._run_id}") - self._std_logger = get_unified_logger("douyin.fudai") - except ImportError: - # 如果unified_logger不可用,使用标准logging - self._std_logger = logging.getLogger("douyin.fudai") - # 确保根 logger 有 handlers - root_logger = logging.getLogger() - if not root_logger.handlers: - try: - from douyin.logging import douyin_logging - - douyin_logging.configure_logging() - except Exception: - pass + init_logging_system(self) self._forced_reservation_detail = None self._forced_reservation_fudai_x = None @@ -169,21 +148,8 @@ class fudai_analyse: # 运行时直播间标题和位置映射表(用于回退校验) # 格式:{room_pos: {"title": str, "title_raw": str, "has_fudai": bool, "fudai_content": str, "fudai_detail": Any}} self._room_pos_to_title_map: dict[int, dict[str, Any]] = {} - # 每次重新运行时丢弃磁盘上旧的映射表,确保只记录本次运行的结果。 - # 同时尝试删除旧的导出文件(JSON/CSV/MD),以避免 GUI 在未写入新数据前显示过期内容。 - try: - state_dir = os.path.dirname(self._reservations_state_path) - state_path = os.path.join(state_dir, "room_pos_map.json") - csv_path = os.path.join(state_dir, "room_pos_map.csv") - md_path = os.path.join(state_dir, "room_pos_map.md") - for p in (state_path, csv_path, md_path): - try: - if os.path.exists(p): - os.remove(p) - except Exception: - pass - except Exception: - pass + # 每次重新运行时丢弃磁盘上旧的映射表导出文件 + cleanup_old_room_pos_map_files(self) # 已记录统计的福袋跟踪(避免同一个直播间同一个福袋重复记录统计) self._recorded_fudai_stats: set[tuple[str, str]] = ( @@ -191,34 +157,7 @@ class fudai_analyse: ) # (room_title, fudai_content) # 运行时状态标志(避免在外部定义属性的警告) - self.needswitch: bool | None = ( - None # 是否允许切换直播间,将从配置文件加载,默认 True - ) - self._waiting_for_lottery_result: bool = False # 是否正在等待开奖结果 - self._current_attending_reservation_fudai: bool = ( - False # 当前正在参与的是否为预约福袋 - ) - self._skip_stage_diagnosis_and_find_fudai: bool = False # 跳过阶段诊断标志 - self._just_switched_room: bool = False # 是否刚刚切换了直播间 - - # 高价值房间重访相关状态 - self._last_high_value_revisit_ts: float = ( - time.time() - ) # 最后一次重访时间戳,初始化为当前时间避免启动后立即重访 - self._current_run_revisit_count: int = 0 # 本次运行的重访次数 - self._current_run_high_value_rooms: list[dict[str, Any]] = ( - [] - ) # 本次运行发现的高价值房间 - self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = ( - 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 # 详情页是否由参与操作关闭 - self._lottery_result_expected_ts: float = 0.0 # 开奖结果预期时间戳 - self._lottery_wait_start_ts: float = 0.0 # 开始等待开奖的时间戳 + init_runtime_state_flags(self) # 初次加载配置 self.load_config() diff --git a/douyin/core/fudai_modules/fudai_init_defaults.py b/douyin/core/fudai_modules/fudai_init_defaults.py index e2902b4..3d1c774 100644 --- a/douyin/core/fudai_modules/fudai_init_defaults.py +++ b/douyin/core/fudai_modules/fudai_init_defaults.py @@ -7,6 +7,84 @@ from __future__ import annotations +def init_logging_system(self) -> None: + """初始化统一日志系统 + traceId(MDC)。 + + 设置 self._std_logger 和 trace_id(基于 _run_id)。 + """ + import logging + + try: + from douyin.logging import douyin_logging + + if not getattr(douyin_logging, "_logging_configured", False): + douyin_logging.configure_logging() + except Exception as e: + logging.warning("日志系统初始化失败: %s", e) + + try: + from douyin.logging.unified_logger import MDC, get_unified_logger + + MDC.set_trace_id(f"run_{self._run_id}") + self._std_logger = get_unified_logger("douyin.fudai") + except ImportError: + self._std_logger = logging.getLogger("douyin.fudai") + root_logger = logging.getLogger() + if not root_logger.handlers: + try: + from douyin.logging import douyin_logging + + douyin_logging.configure_logging() + except Exception: + pass + + +def cleanup_old_room_pos_map_files(self) -> None: + """每次重新运行时丢弃磁盘上旧的映射表导出文件(JSON/CSV/MD)。""" + import os + + try: + state_dir = os.path.dirname(self._reservations_state_path) + state_path = os.path.join(state_dir, "room_pos_map.json") + csv_path = os.path.join(state_dir, "room_pos_map.csv") + md_path = os.path.join(state_dir, "room_pos_map.md") + for p in (state_path, csv_path, md_path): + try: + if os.path.exists(p): + os.remove(p) + except Exception: + pass + except Exception: + pass + + +def init_runtime_state_flags(self) -> None: + """初始化运行时状态标志(避免在外部定义属性的警告)。 + + 包括等待开奖、预约参与、跳过阶段、刚切换、高价值重访、福袋详情等状态字段。 + """ + import time + from typing import Any, Optional, Tuple + + self.needswitch: bool | None = None + self._waiting_for_lottery_result: bool = False + self._current_attending_reservation_fudai: bool = False + self._skip_stage_diagnosis_and_find_fudai: bool = False + self._just_switched_room: bool = False + + self._last_high_value_revisit_ts: float = time.time() + self._current_run_revisit_count: int = 0 + self._current_run_high_value_rooms: list[dict[str, Any]] = [] + self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = 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 + self._lottery_result_expected_ts: float = 0.0 + self._lottery_wait_start_ts: float = 0.0 + + def init_default_config(self) -> None: """初始化所有配置字段的默认值。