From d100ac0a660ac361415ad7d3e16bfca00e321483 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 3 Jan 2026 19:18:57 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E6=A0=BC=E5=BC=8F=EF=BC=8C=E8=B0=83=E6=95=B4=E5=A4=9A?= =?UTF-8?q?=E4=B8=AA=E6=96=87=E4=BB=B6=E4=B8=AD=E7=9A=84=E6=8D=A2=E8=A1=8C?= =?UTF-8?q?=E5=92=8C=E7=BC=A9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- douyin/core/douyin_fudai.py | 14 ++---- douyin/fudai/core/fudai_filter.py | 2 + douyin/stage/douyin_stage.py | 6 ++- douyin/utils/param_usage_tracer.py | 19 ++++++-- douyin/utils/param_usage_tracker.py | 11 +++-- gui/gui_app.py | 5 +- scripts/inspect_lines.py | 11 +++-- tools/generate_param_locations.py | 46 +++++++++++++++---- tools/param_usage_tool.py | 5 +- tools/simulate_reservation_preempted_flow.py | 8 ++-- ...late_reservation_preempted_flow_dynamic.py | 4 +- 11 files changed, 91 insertions(+), 40 deletions(-) diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 19113ae..8e10693 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -675,13 +675,10 @@ class fudai_analyse: 0, future_ts - current_ts + 6.0 ) # 加上6秒延迟,修正倒计时误差 - # 这里的 `future_ts` 存储的是预期的“开奖时间偏移值”(在其他模块被设置为 - # countdown_end - 13),为了以实际的倒计时结束为基准开始检测,需要把 - # 检测窗口向后平移 13 秒,使 `check_start_ts` 对应真实的开奖时间。 - # 开奖后 0 秒开始检测(可视作真实开奖时间的 +0s 缓冲) - check_start_ts = future_ts + 13.0 - # 超时时间:真实开奖后 10 秒仍未识别到结果则放弃(真实开奖时间 +10s) - timeout_ts = future_ts + 23.0 + # 开奖时间 + 1秒缓冲后开始检测开奖结果(提前4秒:从+5秒改为+1秒) + check_start_ts = future_ts + 1.0 + # 超时时间:如果超过开奖时间10秒还没检测到结果,清除等待标志(福袋开奖后10秒会自动关闭) + timeout_ts = future_ts + 10.0 if current_ts >= timeout_ts: # 超过超时时间,清除等待标志,避免卡死 @@ -696,8 +693,7 @@ class fudai_analyse: elif current_ts >= check_start_ts: # 已到检测窗口:在这里改为最多连续检测 10 秒(截图+OCR), # 直到识别到结果或超时。保持原有 timeout_ts 上限( future_ts+10 )。 - # 这里计算已过真实开奖时间的秒数:current - (future_ts + 13) - passed_seconds = int(current_ts - (future_ts + 13.0)) + passed_seconds = int(current_ts - future_ts) self._log_kv( "参与", f"等待开奖结果中,进入连续检测窗口(最多10s),已过开奖时间{passed_seconds}秒", diff --git a/douyin/fudai/core/fudai_filter.py b/douyin/fudai/core/fudai_filter.py index a9d8748..3a2c52c 100644 --- a/douyin/fudai/core/fudai_filter.py +++ b/douyin/fudai/core/fudai_filter.py @@ -621,6 +621,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: pass # 这里需要导入 attend_choujiang 函数 from .fudai_attend import attend_choujiang + result = attend_choujiang(analyser) elapsed = time.time() - start_time analyser._log_kv( @@ -996,6 +997,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: except Exception: pass from .fudai_attend import attend_choujiang + result = attend_choujiang(analyser) elapsed = time.time() - start_time analyser._log_kv( diff --git a/douyin/stage/douyin_stage.py b/douyin/stage/douyin_stage.py index c5d222a..2d0eb81 100644 --- a/douyin/stage/douyin_stage.py +++ b/douyin/stage/douyin_stage.py @@ -606,7 +606,11 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: else: _log("步骤1:像素检测到弹窗但未识别出按钮,继续后续检测") except Exception as e: - _log("步骤1[检测抽奖结果弹窗]-简化OCR异常", 异常类型=type(e).__name__, 异常信息=str(e)) + _log( + "步骤1[检测抽奖结果弹窗]-简化OCR异常", + 异常类型=type(e).__name__, + 异常信息=str(e), + ) # 优先级1.5:购物红包弹窗检测(保持现有检测方式) if pixel_state.get("has_redpacket_bg", False): diff --git a/douyin/utils/param_usage_tracer.py b/douyin/utils/param_usage_tracer.py index 3c8b03d..cd38f0b 100644 --- a/douyin/utils/param_usage_tracer.py +++ b/douyin/utils/param_usage_tracer.py @@ -4,6 +4,7 @@ 该跟踪器使用 `sys.settrace` 捕获函数调用事件,仅记录位于项目根目录下的文件中的函数调用,避免跟踪第三方库。 记录格式与 `param_usage_tracker` 兼容,写入 `state/param_usage.json`(逐行 JSON)。 """ + from __future__ import annotations import os @@ -16,8 +17,12 @@ from typing import Any, Dict try: from path_config import get_project_root except Exception: + def get_project_root() -> str: - return os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) + return os.path.abspath( + os.path.join(os.path.dirname(__file__), os.pardir, os.pardir) + ) + try: # reuse internal writer for consistent format @@ -68,9 +73,13 @@ def _tracefunc(frame, event, arg): if n in arginfo.locals: params[n] = _safe_short_repr(arginfo.locals.get(n)) if arginfo.varargs and arginfo.varargs in arginfo.locals: - params["*" + arginfo.varargs] = _safe_short_repr(arginfo.locals.get(arginfo.varargs)) + params["*" + arginfo.varargs] = _safe_short_repr( + arginfo.locals.get(arginfo.varargs) + ) if arginfo.keywords and arginfo.keywords in arginfo.locals: - params["**" + arginfo.keywords] = _safe_short_repr(arginfo.locals.get(arginfo.keywords)) + params["**" + arginfo.keywords] = _safe_short_repr( + arginfo.locals.get(arginfo.keywords) + ) except Exception: params = {"_args": ""} @@ -80,7 +89,9 @@ def _tracefunc(frame, event, arg): "func_name": func_name, "def_file": filename, "def_line": getattr(code, "co_firstlineno", None), - "call_file": frame.f_back.f_code.co_filename if frame.f_back is not None else None, + "call_file": ( + frame.f_back.f_code.co_filename if frame.f_back is not None else None + ), "call_line": frame.f_back.f_lineno if frame.f_back is not None else None, "params": params, } diff --git a/douyin/utils/param_usage_tracker.py b/douyin/utils/param_usage_tracker.py index 34ffbbf..4026fdd 100644 --- a/douyin/utils/param_usage_tracker.py +++ b/douyin/utils/param_usage_tracker.py @@ -6,6 +6,7 @@ 日志以逐行 JSON(NDJSON)格式追加到 `state/param_usage.json`,方便并发写入与后续分析。 """ + from __future__ import annotations import inspect @@ -20,7 +21,9 @@ try: except Exception: # 兜底:如果无法导入 path_config,则使用 workspace 相对的 state 目录 def get_state_dir() -> str: - return os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir, "state") + return os.path.join( + os.path.dirname(os.path.abspath(__file__)), os.pardir, os.pardir, "state" + ) def ensure_dir(path: str) -> None: dir_path = os.path.dirname(path) if os.path.isfile(path) else path @@ -111,8 +114,10 @@ def track_call(include_args: bool = True) -> Callable[[Callable], Callable]: "ts": _now_ts(), "type": "call", "func_name": getattr(func, "__name__", str(func)), - "def_file": getattr(func, "__code__", None) and func.__code__.co_filename, - "def_line": getattr(func, "__code__", None) and func.__code__.co_firstlineno, + "def_file": getattr(func, "__code__", None) + and func.__code__.co_filename, + "def_line": getattr(func, "__code__", None) + and func.__code__.co_firstlineno, "call_file": call_site.get("file"), "call_line": call_site.get("lineno"), "call_func": call_site.get("function"), diff --git a/gui/gui_app.py b/gui/gui_app.py index ff17540..b0d831f 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -2055,6 +2055,7 @@ def main(): def screenshot_thread(): try: from Underlying_Operations import underlying_operations + # 使用模块级别导入的 Image 与 os,避免重复导入导致 Pylance 警告 # 使用 root.after 在主线程中更新日志 @@ -3802,7 +3803,9 @@ def main(): # 格式化显示 lines.append( - "┌─ 预约 #" + str(idx) + " ─────────────────────────────────────────────" + "┌─ 预约 #" + + str(idx) + + " ─────────────────────────────────────────────" ) lines.append(f"│ 状态:{status_icon} {remain_str}") lines.append("│") diff --git a/scripts/inspect_lines.py b/scripts/inspect_lines.py index 98ba953..2201a30 100644 --- a/scripts/inspect_lines.py +++ b/scripts/inspect_lines.py @@ -1,12 +1,13 @@ import sys + path = sys.argv[1] start = int(sys.argv[2]) end = int(sys.argv[3]) -with open(path, 'r', encoding='utf-8') as f: +with open(path, "r", encoding="utf-8") as f: lines = f.readlines() -for i in range(start, end+1): - idx = i-1 +for i in range(start, end + 1): + idx = i - 1 if 0 <= idx < len(lines): - line = lines[idx].rstrip('\n') + line = lines[idx].rstrip("\n") print(f"{i:4}: {line}") - print(' repr:', repr(lines[idx])) + print(" repr:", repr(lines[idx])) diff --git a/tools/generate_param_locations.py b/tools/generate_param_locations.py index b26762c..957d72b 100644 --- a/tools/generate_param_locations.py +++ b/tools/generate_param_locations.py @@ -9,6 +9,7 @@ 用法: python tools/generate_param_locations.py """ + from __future__ import annotations import ast @@ -22,7 +23,12 @@ OUT_PATH = os.path.join(ROOT, "state", "param_locations.json") def scan_py_file(path: str) -> Dict[str, List[Dict[str, Any]]]: - res = {"functions": [], "argparse": [], "track_param_calls": [], "track_call_calls": []} + res = { + "functions": [], + "argparse": [], + "track_param_calls": [], + "track_call_calls": [], + } try: with open(path, "r", encoding="utf-8", errors="ignore") as f: src = f.read() @@ -35,13 +41,19 @@ def scan_py_file(path: str) -> Dict[str, List[Dict[str, Any]]]: # fallback to regex scanning for i, line in enumerate(src.splitlines(), 1): if "track_param(" in line: - res["track_param_calls"].append({"file": path, "line": i, "text": line.strip()}) + res["track_param_calls"].append( + {"file": path, "line": i, "text": line.strip()} + ) if "track_call(" in line or "@track_call" in line: - res["track_call_calls"].append({"file": path, "line": i, "text": line.strip()}) + res["track_call_calls"].append( + {"file": path, "line": i, "text": line.strip()} + ) if "add_argument(" in line: # try extract string args for m in re.finditer(r"([\'\"]--?[\w-]+[\'\"])", line): - res["argparse"].append({"file": path, "line": i, "arg": m.group(1).strip("'\"")}) + res["argparse"].append( + {"file": path, "line": i, "arg": m.group(1).strip("'\"")} + ) return res for node in ast.walk(tree): @@ -54,7 +66,9 @@ def scan_py_file(path: str) -> Dict[str, List[Dict[str, Any]]]: params.append("*" + node.args.vararg.arg) if node.args.kwarg: params.append("**" + node.args.kwarg.arg) - res["functions"].append({"file": path, "line": node.lineno, "name": node.name, "params": params}) + res["functions"].append( + {"file": path, "line": node.lineno, "name": node.name, "params": params} + ) if isinstance(node, ast.Call): # add_argument @@ -69,7 +83,9 @@ def scan_py_file(path: str) -> Dict[str, List[Dict[str, Any]]]: # extract string literals from args for arg in node.args: if isinstance(arg, ast.Constant) and isinstance(arg.value, str): - res["argparse"].append({"file": path, "line": node.lineno, "arg": arg.value}) + res["argparse"].append( + {"file": path, "line": node.lineno, "arg": arg.value} + ) # track_param calls if (isinstance(func, ast.Name) and func.id == "track_param") or ( isinstance(func, ast.Attribute) and func.attr == "track_param" @@ -79,7 +95,9 @@ def scan_py_file(path: str) -> Dict[str, List[Dict[str, Any]]]: a0 = node.args[0] if isinstance(a0, ast.Constant) and isinstance(a0.value, str): first = a0.value - res["track_param_calls"].append({"file": path, "line": node.lineno, "param_name": first}) + res["track_param_calls"].append( + {"file": path, "line": node.lineno, "param_name": first} + ) if (isinstance(func, ast.Name) and func.id == "track_call") or ( isinstance(func, ast.Attribute) and func.attr == "track_call" ): @@ -91,7 +109,12 @@ def scan_py_file(path: str) -> Dict[str, List[Dict[str, Any]]]: def main() -> int: - out: Dict[str, List[Any]] = {"functions": [], "argparse": [], "track_param_calls": [], "track_call_calls": []} + out: Dict[str, List[Any]] = { + "functions": [], + "argparse": [], + "track_param_calls": [], + "track_call_calls": [], + } for dirpath, dirs, files in os.walk(ROOT): # skip virtual envs and git if ".venv" in dirpath or ".git" in dirpath: @@ -106,7 +129,12 @@ def main() -> int: os.makedirs(os.path.dirname(OUT_PATH), exist_ok=True) with open(OUT_PATH, "w", encoding="utf-8") as f: - json.dump({"generated_at": __import__("time").time(), "report": out}, f, ensure_ascii=False, indent=2) + json.dump( + {"generated_at": __import__("time").time(), "report": out}, + f, + ensure_ascii=False, + indent=2, + ) print("written:", OUT_PATH) return 0 diff --git a/tools/param_usage_tool.py b/tools/param_usage_tool.py index 237b132..6ccc399 100644 --- a/tools/param_usage_tool.py +++ b/tools/param_usage_tool.py @@ -5,6 +5,7 @@ python tools/param_usage_tool.py scan --pattern track_param python tools/param_usage_tool.py tail """ + from __future__ import annotations import argparse @@ -71,7 +72,9 @@ def cmd_show(args: argparse.Namespace) -> int: top = sorted(by_param.items(), key=lambda kv: -len(kv[1]))[: args.top] for name, lst in top: first = lst[0] - print(f"{name}: count={len(lst)} first_at={first.get('caller_file')}:{first.get('caller_line')}") + print( + f"{name}: count={len(lst)} first_at={first.get('caller_file')}:{first.get('caller_line')}" + ) return 0 diff --git a/tools/simulate_reservation_preempted_flow.py b/tools/simulate_reservation_preempted_flow.py index 7c4cd62..265fda6 100644 --- a/tools/simulate_reservation_preempted_flow.py +++ b/tools/simulate_reservation_preempted_flow.py @@ -49,7 +49,9 @@ def _node_contains_return(node: ast.AST) -> bool: # 不进入嵌套函数 return - def visit_AsyncFunctionDef(self, _n: ast.AsyncFunctionDef) -> None: # noqa: N802 + def visit_AsyncFunctionDef( + self, _n: ast.AsyncFunctionDef + ) -> None: # noqa: N802 return def visit_Lambda(self, _n: ast.Lambda) -> None: # noqa: N802 @@ -137,9 +139,7 @@ def _check() -> tuple[bool, int]: lineno = getattr(enclosing_if, "lineno", -1) raise _FoundBlock(has_return=has_return, lineno=lineno) - raise RuntimeError( - f"未找到目标分支:{TARGET_LOG_SNIPPET}(文件:{TARGET_FILE})" - ) + raise RuntimeError(f"未找到目标分支:{TARGET_LOG_SNIPPET}(文件:{TARGET_FILE})") def main() -> None: diff --git a/tools/simulate_reservation_preempted_flow_dynamic.py b/tools/simulate_reservation_preempted_flow_dynamic.py index fddfc46..df7b94f 100644 --- a/tools/simulate_reservation_preempted_flow_dynamic.py +++ b/tools/simulate_reservation_preempted_flow_dynamic.py @@ -115,9 +115,7 @@ def main() -> None: try: analyser.run_once_basic() except _ReachedScreenshot: - print( - "PASS: preempted=True did not early-return; reached screenshot stage" - ) + print("PASS: preempted=True did not early-return; reached screenshot stage") return print(