修复福袋详情OCR v2与调试日志

This commit is contained in:
Your Name committed 2026-06-03 01:22:13 +08:00
1 parent 2c6f024a24
commit 1d37d57c90
119 files changed
+5582 -767

No files matched your search

+199
View File
@@ -7,6 +7,7 @@ import subprocess
import sys
import threading
import time
import atexit
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Optional
@@ -85,6 +86,7 @@ class ProcRunner:
self._last_log_ts: Optional[float] = None
self._exit_code: Optional[int] = None
self._pid: Optional[int] = None
self._owned_run_cli_pids: set[int] = set()
# 运行统计(基于 stdout 日志解析)
self._counters: dict[str, int] = {}
@@ -207,6 +209,139 @@ class ProcRunner:
with self._lock:
return self._proc is not None and self._proc.poll() is None
def _list_project_run_cli_processes(self) -> list[tuple[int, str]]:
"""列出当前仓库下运行的 run_cli.py 进程(含 pid 与命令行)。"""
entries: list[tuple[int, str]] = []
root_norm = str(path_config.PROJECT_ROOT).replace("/", "\\").lower()
try:
if os.name == "nt":
ps_cmd = (
"Get-CimInstance Win32_Process "
"| Where-Object { $_.Name -eq 'python.exe' -and $_.CommandLine -like '*run_cli.py*' } "
"| Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"
)
proc = subprocess.run(
["powershell", "-NoProfile", "-Command", ps_cmd],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=6,
check=False,
)
raw = (proc.stdout or "").strip()
if not raw:
return entries
try:
data = json.loads(raw)
except Exception:
data = None
if isinstance(data, dict):
data = [data]
if isinstance(data, list):
for item in data:
try:
pid = int(item.get("ProcessId") or 0)
cmdline = str(item.get("CommandLine") or "")
except Exception:
continue
if pid <= 0 or not cmdline:
continue
if root_norm in cmdline.replace("/", "\\").lower():
entries.append((pid, cmdline))
else:
proc = subprocess.run(
["ps", "-eo", "pid=,args="],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=4,
check=False,
)
for line in (proc.stdout or "").splitlines():
s = str(line or "").strip()
if not s:
continue
parts = s.split(None, 1)
if len(parts) < 2:
continue
try:
pid = int(parts[0])
except Exception:
continue
cmdline = parts[1]
low = cmdline.lower()
if "run_cli.py" in low and root_norm in cmdline.replace("/", "\\").lower():
entries.append((pid, cmdline))
except Exception:
return []
return entries
def _cleanup_orphan_run_cli_processes(self, device_id: str = "") -> int:
"""清理当前仓库遗留的 run_cli.py 进程,避免同机并发导致重复动作。"""
try:
with self._lock:
tracked_pid = int(self._pid or 0)
owned_pids = {int(x) for x in (self._owned_run_cli_pids or set())}
except Exception:
tracked_pid = 0
owned_pids = set()
current_pid = int(os.getpid() or 0)
device_tag = str(device_id or "").strip()
if not device_tag:
return 0
killed = 0
for pid, cmdline in self._list_project_run_cli_processes():
if pid <= 0:
continue
if pid in (tracked_pid, current_pid):
continue
if pid not in owned_pids:
continue
if device_tag:
dev1 = f"--device-id {device_tag}"
dev2 = f'--device-id "{device_tag}"'
if dev1 not in cmdline and dev2 not in cmdline:
continue
try:
self._append_log(f"[启动清理] 发现遗留 run_cli 进程 pid={pid},准备终止")
except Exception:
pass
try:
if os.name == "nt":
subprocess.run(
["taskkill", "/PID", str(pid), "/T", "/F"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=8,
check=False,
)
else:
subprocess.run(
["kill", "-9", str(pid)],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=5,
check=False,
)
killed += 1
try:
self._append_log(f"[启动清理] 已终止遗留 run_cli 进程 pid={pid}")
except Exception:
pass
except Exception as e:
try:
self._append_log(f"[启动清理] 终止遗留 run_cli 进程失败 pid={pid} error={e}")
except Exception:
pass
return killed
def get_reservations(self) -> dict:
return _proc_ops.get_reservations(self)
@@ -238,7 +373,15 @@ class ProcRunner:
with self._lock:
self._proc = None
self._pid = None
if pid:
self._owned_run_cli_pids.discard(int(pid))
self._exit_code = self._exit_code if self._exit_code is not None else -9
try:
extra_killed = self._cleanup_orphan_run_cli_processes("")
if extra_killed > 0:
self._append_log(f"[停止] 额外清理遗留 run_cli 进程 {extra_killed} 个")
except Exception:
pass
self._append_log("[停止] 强制停止完成")
def stop(self) -> None:
@@ -260,6 +403,8 @@ class ProcRunner:
try:
self._proc = None
self._pid = None
if getattr(p, "pid", None):
self._owned_run_cli_pids.discard(int(p.pid))
except Exception:
pass
self._append_log("[网页] 停止:已尝试终止并清理进程引用")
@@ -328,6 +473,14 @@ class ProcRunner:
device_id = str(_pick("device_id", "") or "").strip()
adb = find_adb_executable()
device_id = resolve_adb_device(adb, device_id)
try:
cleaned = self._cleanup_orphan_run_cli_processes(device_id)
if cleaned > 0:
self._append_log(
f"[启动清理] 已清理同设备遗留 run_cli 进程 {cleaned} 个,避免重复切房"
)
except Exception:
pass
y_pianyi = int(_pick("y_pianyi", 0) or 0)
needswitch = bool(_pick("needswitch", False))
reset_after_swipes_enabled = bool(_pick("reset_after_swipes_enabled", False))
@@ -513,7 +666,36 @@ class ProcRunner:
except Exception:
pass
reenter_mode = str(
_pick("reenter_live_entry_mode", "follow_list") or "follow_list"
).strip().lower()
reenter_mode_source = "default"
try:
if (
isinstance(params, dict)
and params.get("reenter_live_entry_mode") is not None
):
reenter_mode_source = "params"
elif isinstance(cfg, dict) and cfg.get("reenter_live_entry_mode") is not None:
reenter_mode_source = "config"
except Exception:
reenter_mode_source = "default"
if reenter_mode in ("follow_list", "screen_center"):
cmd += ["--reenter-live-entry-mode", reenter_mode]
self._start_process(cmd)
try:
# 放在 _start_process 之后,避免被启动时日志清空逻辑抹掉
self._append_log(
"[WEB_DEBUG] 启动参数解析:reenter_live_entry_mode="
f"{reenter_mode} source={reenter_mode_source}"
)
self._append_log(
"[WEB_DEBUG] 启动命令检查:cmd_has_reenter_flag="
f"{'--reenter-live-entry-mode' in cmd}"
)
except Exception:
pass
def _start_process(self, cmd: list[str]) -> None:
# 每次启动前刷新一次日志设置
@@ -551,6 +733,7 @@ class ProcRunner:
with self._lock:
self._proc = p
self._pid = p.pid
self._owned_run_cli_pids.add(int(p.pid))
self._start_ts = time.time()
self._exit_code = None
self._last_log_ts = time.time()
@@ -618,11 +801,18 @@ class ProcRunner:
self._append_log(f"[网页] 进程退出:退出码={rc}")
with self._lock:
self._exit_code = rc
try:
self._proc = None
self._pid = None
self._owned_run_cli_pids.discard(int(p.pid))
except Exception:
pass
threading.Thread(target=_reader, daemon=True).start()
RUNNER = ProcRunner()
atexit.register(lambda: RUNNER.force_stop())
class Handler(BaseHTTPRequestHandler):
@@ -668,6 +858,15 @@ def main() -> int:
httpd.serve_forever()
except KeyboardInterrupt:
print("[WEBGUI] 收到中断,退出")
try:
RUNNER.force_stop()
except Exception:
pass
finally:
try:
httpd.server_close()
except Exception:
pass
return 0