fix: Adjust configuration settings and improve error handling

- Updated `config.json` to modify `yanghao_recommend_interval_seconds` for better timing control.
- Refactored logging in `douyin_detection.py` to enhance readability and error handling.
- Improved pixel loading and error management in image processing functions across multiple modules.
- Enhanced GUI elements in `gui_app.py` to support new configuration options and improve user experience.
This commit is contained in:
Your Name committed 2025-12-21 21:55:30 +08:00
1 parent 47e6b016c5
commit 2cd81c05a3
35 files changed
+12043 -1711

No files matched your search

+181 -73
View File
@@ -15,14 +15,14 @@ CONFIG_PATH = os.path.join(BASE_DIR, "config.json")
WEBUI_DIR = os.path.join(BASE_DIR, "webui")
# ANSI转义序列清理正则表达式
_ANSI_ESCAPE_RE = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
_ANSI_ESCAPE_RE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
def strip_ansi_escape_codes(text: str) -> str:
"""移除字符串中的ANSI转义序列(颜色代码等)。"""
if not isinstance(text, str):
return str(text)
return _ANSI_ESCAPE_RE.sub('', text)
return _ANSI_ESCAPE_RE.sub("", text)
def find_adb_executable() -> str:
@@ -35,7 +35,9 @@ def find_adb_executable() -> str:
candidates.append(os.path.join(localapp, "platform-tools", "adb.exe"))
userprofile = os.environ.get("USERPROFILE") or ""
if userprofile:
candidates.append(os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe"))
candidates.append(
os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe")
)
for p in candidates:
if os.path.exists(p):
return p
@@ -46,7 +48,13 @@ def list_adb_devices(adb_exe: str) -> list[str]:
try:
if not adb_exe:
return []
proc = subprocess.run([adb_exe, "devices", "-l"], capture_output=True, text=True, encoding="utf-8", errors="replace")
proc = subprocess.run(
[adb_exe, "devices", "-l"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
except FileNotFoundError:
return []
text = (proc.stdout or "") + "\n" + (proc.stderr or "")
@@ -72,7 +80,9 @@ class ProcRunner:
self._proc: subprocess.Popen | None = None
self._lock = threading.Lock()
self._log: list[str] = []
self._log_capacity: int = 10000 # 0=不限制(可能占用大量内存),增加到10000避免日志被过早截断
self._log_capacity: int = (
10000 # 0=不限制(可能占用大量内存),增加到10000避免日志被过早截断
)
self._log_file_enabled: bool = True
self._log_file_path: str = os.path.join(BASE_DIR, "logs", "unified.log")
self._start_ts: float | None = None
@@ -132,18 +142,20 @@ class ProcRunner:
pass
try:
# 使用 utf-8-sig:文件首次创建时会写入 BOM,避免 Windows PowerShell 误按 ANSI 读取导致中文乱码
with open(self._log_file_path, "a", encoding="utf-8-sig", errors="replace") as f:
with open(
self._log_file_path, "a", encoding="utf-8-sig", errors="replace"
) as f:
f.write(line + "\n")
f.flush() # 确保立即写入磁盘,避免缓冲区延迟导致日志丢失
except PermissionError as e:
# 权限错误,只输出一次警告避免刷屏
if not hasattr(self, '_log_permission_warned'):
if not hasattr(self, "_log_permission_warned"):
print(f"[WEB_GUI] 警告:日志文件写入权限错误: {self._log_file_path}")
print(f"[WEB_GUI] 错误详情: {e}")
self._log_permission_warned = True
except Exception as e:
# 其他文件写失败不应影响主流程,但记录第一次错误以便调试
if not hasattr(self, '_log_write_error_warned'):
if not hasattr(self, "_log_write_error_warned"):
print(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}")
print(f"[WEB_GUI] 错误详情: {e}")
self._log_write_error_warned = True
@@ -159,7 +171,7 @@ class ProcRunner:
}
self._events.append(ev)
if len(self._events) > self._events_cap:
self._events = self._events[-self._events_cap:]
self._events = self._events[-self._events_cap :]
def _record_win(self) -> None:
item = {
@@ -168,10 +180,10 @@ class ProcRunner:
}
self._wins.append(item)
if len(self._wins) > self._wins_cap:
self._wins = self._wins[-self._wins_cap:]
self._wins = self._wins[-self._wins_cap :]
@staticmethod
def _parse_countdown_seconds(text: str) -> int | None:
def _parse_countdown_seconds(text: str) -> int | None: # type: ignore[misc]
t = str(text or "").strip()
if not t:
return None
@@ -213,7 +225,7 @@ class ProcRunner:
return None
@staticmethod
def _bucket(value: float, edges: list[float]) -> str:
def _bucket(value: float, edges: list[float]) -> str: # type: ignore[misc]
# edges 例如 [0,10,50,100] => 0-10,10-50,50-100,100+
if not edges:
return "all"
@@ -225,7 +237,7 @@ class ProcRunner:
return f"{edges[-1]:g}+"
@staticmethod
def _inc_map(m: dict, k: str, n: int = 1) -> None:
def _inc_map(m: dict, k: str, n: int = 1) -> None: # type: ignore[misc]
m[k] = int(m.get(k, 0)) + int(n)
def _snapshot_fudai(self) -> dict:
@@ -296,22 +308,34 @@ class ProcRunner:
# --- 福袋:跳过/过滤原因 ---
if "参与人数" in s and "< 阈值" in s and "不参与" in s:
self._inc("fudai_skip_participants_low")
self._record_event("fudai_skip", {"reason": "participants_low", **self._snapshot_fudai()})
self._record_event(
"fudai_skip", {"reason": "participants_low", **self._snapshot_fudai()}
)
if "参与人数" in s and "> 阈值" in s and "不参与" in s:
self._inc("fudai_skip_participants_high")
self._record_event("fudai_skip", {"reason": "participants_high", **self._snapshot_fudai()})
self._record_event(
"fudai_skip", {"reason": "participants_high", **self._snapshot_fudai()}
)
if "奖品价值" in s and "< 阈值" in s and "不参与" in s:
self._inc("fudai_skip_value_low")
self._record_event("fudai_skip", {"reason": "value_low", **self._snapshot_fudai()})
self._record_event(
"fudai_skip", {"reason": "value_low", **self._snapshot_fudai()}
)
if "福袋内容不理想" in s:
self._inc("fudai_skip_content")
self._record_event("fudai_skip", {"reason": "content", **self._snapshot_fudai()})
self._record_event(
"fudai_skip", {"reason": "content", **self._snapshot_fudai()}
)
if "抽奖倒计时时间小于" in s and "不参与" in s:
self._inc("fudai_skip_countdown_short")
self._record_event("fudai_skip", {"reason": "countdown_short", **self._snapshot_fudai()})
self._record_event(
"fudai_skip", {"reason": "countdown_short", **self._snapshot_fudai()}
)
if "抽奖倒计时时间大于" in s and "暂不参与" in s:
self._inc("fudai_skip_countdown_long")
self._record_event("fudai_skip", {"reason": "countdown_long", **self._snapshot_fudai()})
self._record_event(
"fudai_skip", {"reason": "countdown_long", **self._snapshot_fudai()}
)
# 看播门槛:默认不参与(新结构化日志)
if (
"需要看播时长:默认不参与" in s
@@ -319,7 +343,9 @@ class ProcRunner:
or ("[参与]" in s and "结果=看播门槛" in s)
):
self._inc("fudai_skip_watch_required")
self._record_event("fudai_skip", {"reason": "watch_required", **self._snapshot_fudai()})
self._record_event(
"fudai_skip", {"reason": "watch_required", **self._snapshot_fudai()}
)
if "打开福袋异常" in s:
self._inc("fudai_open_error")
self._record_event("fudai_open_error", self._snapshot_fudai())
@@ -339,13 +365,17 @@ class ProcRunner:
self._record_event("fansclub_unresolved", self._snapshot_fudai())
# --- 预约队列/回退校验 ---
if ("[预约]" in s and "回退校验通过" in s) or "回退校验通过:已回到目标直播间" in s:
if (
"[预约]" in s and "回退校验通过" in s
) or "回退校验通过:已回到目标直播间" in s:
self._inc("reservation_back_verify_ok")
self._record_event("reservation_back_verify_ok", {})
if ("[预约]" in s and "回退校验失败" in s) or "回退校验失败" in s:
self._inc("reservation_back_verify_fail")
self._record_event("reservation_back_verify_fail", {})
if ("[预约]" in s and "预约队列已满,丢弃最低价值" in s) or "预约队列已满,丢弃最低价值" in s:
if (
"[预约]" in s and "预约队列已满,丢弃最低价值" in s
) or "预约队列已满,丢弃最低价值" in s:
self._inc("reservation_drop_low_value")
self._record_event("reservation_drop_low_value", {})
if ("[预约]" in s and "清空预约队列" in s) or "清空预约队列" in s:
@@ -386,10 +416,15 @@ class ProcRunner:
elif "参与抽奖失败" in s:
self._inc("switch_room_attend_fail")
meta_reason = "attend_fail"
self._record_event("switch_room", {"reason": meta_reason, **self._snapshot_fudai()})
self._record_event(
"switch_room", {"reason": meta_reason, **self._snapshot_fudai()}
)
# --- 性能:进入直播间到识别福袋耗时 ---
m = re.search(r"进入直播间到识别福袋耗时:\s*([0-9]+(?:\.[0-9]+)?)\s*秒(?:\s*进入原因=(.*))?", s)
m = re.search(
r"进入直播间到识别福袋耗时:\s*([0-9]+(?:\.[0-9]+)?)\s*秒(?:\s*进入原因=(.*))?",
s,
)
if m:
try:
secs = float(m.group(1))
@@ -397,7 +432,10 @@ class ProcRunner:
secs = None
reason = str(m.group(2) or "")
# 记录为事件,便于后续做分布/趋势分析
self._record_event("enter_to_fudai_seen", {"secs": secs, "enter_reason": reason, **self._snapshot_fudai()})
self._record_event(
"enter_to_fudai_seen",
{"secs": secs, "enter_reason": reason, **self._snapshot_fudai()},
)
# 同时做一个计数器
try:
self._inc("enter_to_fudai_seen")
@@ -418,8 +456,18 @@ class ProcRunner:
if isinstance(data, dict):
return data
except Exception:
return {"reservations": [], "room_pos": 0, "updated_ts": 0.0, "reason": "state_read_or_parse_failed"}
return {"reservations": [], "room_pos": 0, "updated_ts": 0.0, "reason": "no_state_file"}
return {
"reservations": [],
"room_pos": 0,
"updated_ts": 0.0,
"reason": "state_read_or_parse_failed",
}
return {
"reservations": [],
"room_pos": 0,
"updated_ts": 0.0,
"reason": "no_state_file",
}
def get_high_value_rooms(self) -> dict:
"""获取永久记录的高价值直播间列表(来自 state/high_value_rooms.json)。"""
@@ -431,9 +479,19 @@ class ProcRunner:
if isinstance(data, dict):
return data
if isinstance(data, list):
return {"updated_ts": 0.0, "reason": "legacy_list", "total": len(data), "rooms": data}
return {
"updated_ts": 0.0,
"reason": "legacy_list",
"total": len(data),
"rooms": data,
}
except Exception:
return {"updated_ts": 0.0, "reason": "state_read_or_parse_failed", "total": 0, "rooms": []}
return {
"updated_ts": 0.0,
"reason": "state_read_or_parse_failed",
"total": 0,
"rooms": [],
}
return {"updated_ts": 0.0, "reason": "no_state_file", "total": 0, "rooms": []}
def stop(self) -> None:
@@ -545,33 +603,34 @@ class ProcRunner:
series["switch_room"][bi] += 1
# 分布/Top
if typ == "fudai_skip":
r = str(meta.get("reason") or "unknown")
self._inc_map(skip_reason, r, 1)
if typ == "switch_room":
r = str(meta.get("reason") or "unknown")
self._inc_map(switch_reason, r, 1)
if meta is not None:
if typ == "fudai_skip":
r = str(meta.get("reason") or "unknown")
self._inc_map(skip_reason, r, 1)
if typ == "switch_room":
r = str(meta.get("reason") or "unknown")
self._inc_map(switch_reason, r, 1)
content = str(meta.get("content") or "").strip()
if content:
# 只取前 60 字符作为展示 key,避免超长撑爆
key = (content[:60] + "…") if len(content) > 60 else content
self._inc_map(content_top, key, 1)
content = str(meta.get("content") or "").strip()
if content:
# 只取前 60 字符作为展示 key,避免超长撑爆
key = (content[:60] + "…") if len(content) > 60 else content
self._inc_map(content_top, key, 1)
v = meta.get("prize_value_yuan")
if isinstance(v, (int, float)):
b = self._bucket(float(v), value_edges)
self._inc_map(value_buckets, b, 1)
p = meta.get("participants")
if isinstance(p, int):
b = self._bucket(float(p), participants_edges)
self._inc_map(participants_buckets, b, 1)
cd = meta.get("countdown")
if isinstance(cd, str) and cd.strip():
sec = self._parse_countdown_seconds(cd)
if isinstance(sec, int):
b = self._bucket(float(sec), countdown_edges)
self._inc_map(countdown_buckets, b, 1)
v = meta.get("prize_value_yuan")
if isinstance(v, (int, float)):
b = self._bucket(float(v), value_edges)
self._inc_map(value_buckets, b, 1)
p = meta.get("participants")
if isinstance(p, int):
b = self._bucket(float(p), [float(e) for e in participants_edges])
self._inc_map(participants_buckets, b, 1)
cd = meta.get("countdown")
if isinstance(cd, str) and cd.strip():
sec = self._parse_countdown_seconds(cd)
if isinstance(sec, int):
b = self._bucket(float(sec), [float(e) for e in countdown_edges])
self._inc_map(countdown_buckets, b, 1)
def _top_k(m: dict, k: int = 10) -> list[dict]:
items = [{"key": kk, "count": int(vv)} for kk, vv in m.items()]
@@ -679,7 +738,11 @@ class ProcRunner:
cfg = {}
def _pick(key: str, default):
if isinstance(params, dict) and key in params and params.get(key) is not None:
if (
isinstance(params, dict)
and key in params
and params.get(key) is not None
):
return params.get(key)
if isinstance(cfg, dict) and key in cfg and cfg.get(key) is not None:
return cfg.get(key)
@@ -690,11 +753,12 @@ class ProcRunner:
needswitch = bool(_pick("needswitch", False))
reset_after_swipes_enabled = bool(_pick("reset_after_swipes_enabled", False))
wait_minutes = int(_pick("wait_minutes", 5) or 5)
# 启动时自动截图
if device_id:
try:
from Underlying_Operations import underlying_operations
ops = underlying_operations()
self._append_log(f"[启动] 自动截图: device={device_id}")
result = ops.get_screenshot(device_id)
@@ -709,7 +773,9 @@ class ProcRunner:
min_prize_value_yuan = float(_pick("min_prize_value_yuan", 0) or 0)
min_participants = int(_pick("min_participants", 0) or 0)
max_participants = int(_pick("max_participants", 0) or 0)
skip_if_countdown_lt_seconds = int(_pick("skip_if_countdown_lt_seconds", 15) or 15)
skip_if_countdown_lt_seconds = int(
_pick("skip_if_countdown_lt_seconds", 15) or 15
)
try:
reset_after_swipes = int(_pick("reset_after_swipes", 10))
except Exception:
@@ -717,7 +783,9 @@ class ProcRunner:
if reset_after_swipes < 1:
reset_after_swipes = 1
auto_join_fansclub = bool(_pick("auto_join_fansclub", False))
fansclub_fail_action = str(_pick("fansclub_fail_action", "") or "").strip().lower()
fansclub_fail_action = (
str(_pick("fansclub_fail_action", "") or "").strip().lower()
)
cmd = [
sys.executable,
@@ -750,8 +818,12 @@ class ProcRunner:
cmd += ["--fansclub-fail-action", fansclub_fail_action]
# 高价值直播间回访运行时开关(由 GUI 在启动时覆盖)
high_value_room_revisit_enabled = bool(_pick("high_value_room_revisit_enabled", True))
high_value_room_revisit_only_current_run = bool(_pick("high_value_room_revisit_only_current_run", False))
high_value_room_revisit_enabled = bool(
_pick("high_value_room_revisit_enabled", True)
)
high_value_room_revisit_only_current_run = bool(
_pick("high_value_room_revisit_only_current_run", False)
)
if high_value_room_revisit_enabled:
cmd.append("--high-value-room-revisit-enabled")
else:
@@ -760,7 +832,9 @@ class ProcRunner:
cmd.append("--high-value-room-revisit-only-current-run")
# 预约回退校验开关(由 Run 面板控制)
reservation_back_verify_enabled = bool(_pick("reservation_back_verify_enabled", True))
reservation_back_verify_enabled = bool(
_pick("reservation_back_verify_enabled", True)
)
if reservation_back_verify_enabled:
cmd.append("--reservation-back-verify-enabled")
else:
@@ -863,7 +937,7 @@ class ProcRunner:
# 使用迭代器读取,Python会自动处理缓冲
# 配合PYTHONUNBUFFERED=1和line_buffering=True,应该能实时获取输出
# iter(out.readline, '') 会在readline返回空字符串(EOF)时自动停止
for line in iter(out.readline, ''):
for line in iter(out.readline, ""):
try:
cleaned_line = line.rstrip("\n\r")
if cleaned_line: # 忽略空行
@@ -962,7 +1036,11 @@ class Handler(BaseHTTPRequestHandler):
return self._send_json(cfg)
if u.path == "/api/stats":
qs = parse_qs(u.query)
detail = str((qs.get("detail") or [""])[0] or "").strip().lower() in ("1", "true", "yes")
detail = str((qs.get("detail") or [""])[0] or "").strip().lower() in (
"1",
"true",
"yes",
)
return self._send_json(RUNNER.get_stats(include_events=detail))
if api_path in ("/api/reservations", "/api/reservation"):
# 返回当前预约队列信息
@@ -983,12 +1061,23 @@ class Handler(BaseHTTPRequestHandler):
since = 0
try:
next_idx, lines = RUNNER.get_logs_since(since)
return self._send_json({"next": next_idx, "lines": lines, "running": RUNNER.is_running()})
return self._send_json(
{
"next": next_idx,
"lines": lines,
"running": RUNNER.is_running(),
}
)
except Exception as e:
# 记录错误但不中断请求,返回空日志
import traceback
print(f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}")
return self._send_json({"next": 0, "lines": [], "running": RUNNER.is_running()})
print(
f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}"
)
return self._send_json(
{"next": 0, "lines": [], "running": RUNNER.is_running()}
)
if u.path == "/api/logfile-tail":
# 返回统一日志文件的尾部若干行,便于在内存日志不同步时调试
qs = parse_qs(u.query)
@@ -996,7 +1085,11 @@ class Handler(BaseHTTPRequestHandler):
n = int((qs.get("lines") or [100])[0])
except Exception:
n = 100
path = RUNNER._log_file_path if hasattr(RUNNER, "_log_file_path") else os.path.join(BASE_DIR, "logs", "unified.log")
path = (
RUNNER._log_file_path
if hasattr(RUNNER, "_log_file_path")
else os.path.join(BASE_DIR, "logs", "unified.log")
)
out_lines = []
try:
if os.path.exists(path):
@@ -1050,7 +1143,11 @@ class Handler(BaseHTTPRequestHandler):
self.send_error(HTTPStatus.NOT_FOUND)
return
ext = os.path.splitext(full)[1].lower()
ctype = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg"}.get(ext, "application/octet-stream")
ctype = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
}.get(ext, "application/octet-stream")
with open(full, "rb") as f:
data = f.read()
self.send_response(HTTPStatus.OK)
@@ -1068,7 +1165,9 @@ class Handler(BaseHTTPRequestHandler):
if u.path == "/api/config":
body = self._read_json()
cfg = read_config()
update = body.get("config") if isinstance(body.get("config"), dict) else body
update = (
body.get("config") if isinstance(body.get("config"), dict) else body
)
int_keys = {
"min_participants",
@@ -1152,7 +1251,11 @@ class Handler(BaseHTTPRequestHandler):
if isinstance(v, list):
cfg[k] = [str(x) for x in v if str(x).strip()]
else:
cfg[k] = [str(x).strip() for x in str(v).splitlines() if str(x).strip()]
cfg[k] = [
str(x).strip()
for x in str(v).splitlines()
if str(x).strip()
]
else:
cfg[k] = v
@@ -1196,19 +1299,22 @@ class Handler(BaseHTTPRequestHandler):
if u.path == "/api/stop":
RUNNER.stop()
return self._send_json({"ok": True})
if u.path == "/api/screenshot":
# 手动截图接口
body = self._read_json()
device_id = str(body.get("device_id") or "").strip()
try:
from Underlying_Operations import underlying_operations
ops = underlying_operations()
result = ops.get_screenshot(device_id)
if result:
return self._send_json({"ok": True, "message": "截图成功"})
else:
return self._send_json({"ok": False, "error": "截图失败"}, status=500)
return self._send_json(
{"ok": False, "error": "截图失败"}, status=500
)
except Exception as e:
return self._send_json({"ok": False, "error": str(e)}, status=500)
@@ -1233,7 +1339,9 @@ def main() -> int:
httpd = ThreadingHTTPServer((host, port), Handler)
except OSError as e:
print(f"[WEBGUI] 端口 {port} 启动失败:{e}")
print("[WEBGUI] 处理建议:1) 关闭占用该端口的进程 2) 改为其他端口,例如前置设置 PORT=8001")
print(
"[WEBGUI] 处理建议:1) 关闭占用该端口的进程 2) 改为其他端口,例如前置设置 PORT=8001"
)
raise
print(f"Web GUI: http://{host}:{port}")
print("- 可在页面里设置养号时长/间隔并保存到 config.json")