Compare commits
169
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
37f736c158 | ||
|
|
3659d5b7da | ||
|
|
1ef7325ead | ||
|
|
e03dcaa183 | ||
|
|
458779e809 | ||
|
|
c361eb4db6 | ||
|
|
4db6431757 | ||
|
|
8351908232 | ||
|
|
3bc997a4d7 | ||
|
|
48d18daef8 | ||
|
|
c6a4410180 | ||
|
|
a8d1b24dc9 | ||
|
|
a94a6d2a71 | ||
|
|
3491970090 | ||
|
|
01ce77eaa6 | ||
|
|
034e55072a | ||
|
|
ec2f044d8c | ||
|
|
18b75ceda4 | ||
|
|
e9b003f906 | ||
|
|
95459607dc | ||
|
|
0d4796744d | ||
|
|
1cd94e9705 | ||
|
|
8c2d93a79f | ||
|
|
92d60f9931 | ||
|
|
29b9788371 | ||
|
|
7eeaab9a6e | ||
|
|
089cb32e1c | ||
|
|
a06ece4e15 | ||
|
|
6cebed599d | ||
|
|
da5e000006 | ||
|
|
065d73ff9a | ||
|
|
adbd8a2d6e | ||
|
|
1235c5910f | ||
|
|
84c5731cc3 | ||
|
|
8e0ae9396d | ||
|
|
a6648c5ce8 | ||
|
|
f75d3ae368 | ||
|
|
d9920f1cee | ||
|
|
e763cdc302 | ||
|
|
fd694f8ce5 | ||
|
|
547228fa2d | ||
|
|
e7d848023c | ||
|
|
a1562a513d | ||
|
|
b8f2806ffc | ||
|
|
9642b7b0f8 | ||
|
|
9896eb676a | ||
|
|
e0c68883dd | ||
|
|
e0cad29daf | ||
|
|
6a8296cab1 | ||
|
|
3626e9cf6f | ||
|
|
29d930b1de | ||
|
|
df758cf224 | ||
|
|
47865f5dfa | ||
|
|
9744b75878 | ||
|
|
200f3a53fc | ||
|
|
7a840120b3 | ||
|
|
e314161b6c | ||
|
|
3a7a7a3b75 | ||
|
|
8575f04ab9 | ||
|
|
728ef3cd79 | ||
|
|
32e374e2c2 | ||
|
|
aa0f4e05f2 | ||
|
|
5e3015f59b | ||
|
|
dc1744a93f | ||
|
|
b686a4e3d5 | ||
|
|
29cef2c578 | ||
|
|
e784efd5f8 | ||
|
|
6c7bbf0945 | ||
|
|
fe27063913 | ||
|
|
3f04bb23c2 | ||
|
|
bcb0e363d1 | ||
|
|
b447b6a6a4 | ||
|
|
3ac8664817 | ||
|
|
6bac014c3d | ||
|
|
3d433080c2 | ||
|
|
f6d382b0e7 | ||
|
|
2a05be2319 | ||
|
|
f9839f3dee | ||
|
|
97935d9c48 | ||
|
|
64c210dd5a | ||
|
|
68d1224b53 | ||
|
|
92d524297b | ||
|
|
59ebe8c1e7 | ||
|
|
a7ef92fc7c | ||
|
|
c5df7a05d2 | ||
|
|
b3380042b8 | ||
|
|
4993fad004 | ||
|
|
44b091466d | ||
|
|
8ea676562c | ||
|
|
a07ef00b5e | ||
|
|
5329561b3a | ||
|
|
6bffcae2de | ||
|
|
ac464788e1 | ||
|
|
8dace383ec | ||
|
|
26f9e5a553 | ||
|
|
bb90e2983f | ||
|
|
c3746b0207 | ||
|
|
b1fa6af9ce | ||
|
|
96fdc96f24 | ||
|
|
c4544489ac | ||
|
|
d19d5bfc56 | ||
|
|
703da834fb | ||
|
|
4908df19d4 | ||
|
|
ca00258bf3 | ||
|
|
e62314fa25 | ||
|
|
df69c6ab67 | ||
|
|
a50f08de5a | ||
|
|
8fd38dd30b | ||
|
|
d850af2c44 | ||
|
|
2fab3f238e | ||
|
|
f750969df3 | ||
|
|
842dd254e3 | ||
|
|
6f38907119 | ||
|
|
470c68a252 | ||
|
|
fe97e82104 | ||
|
|
9f330572cc | ||
|
|
4277bf7fa4 | ||
|
|
ca6c2e4d20 | ||
|
|
7884132743 | ||
|
|
9fbfcb5ed2 | ||
|
|
87bac9e548 | ||
|
|
d759921442 | ||
|
|
be1eb6eda7 | ||
|
|
3b8f85b9cb | ||
|
|
fb35670032 | ||
|
|
230c0d4049 | ||
|
|
a864f6e23a | ||
|
|
3a9f01ad74 | ||
|
|
8ecd2783db | ||
|
|
e737002b1e | ||
|
|
df273ab231 | ||
|
|
d60b83af68 | ||
|
|
e46497ea80 | ||
|
|
8457219241 | ||
|
|
b200002a00 | ||
|
|
ab846dae0f | ||
|
|
07cdd662c2 | ||
|
|
1514122981 | ||
|
|
f718dfe2e4 | ||
|
|
2f0eb90d98 | ||
|
|
f38b373636 | ||
|
|
457edcfdc8 | ||
|
|
03b471513d | ||
|
|
2707773b15 | ||
|
|
07eee6da52 | ||
|
|
52b811d0cb | ||
|
|
4ab4504425 | ||
|
|
fb82213d53 | ||
|
|
ffd048ffa5 | ||
|
|
61cdf7b445 | ||
|
|
ca953cb4ba | ||
|
|
aeb51f73c7 | ||
|
|
0540610c75 | ||
|
|
7b6dec820b | ||
|
|
8a975f2bf6 | ||
|
|
cea3aced73 | ||
|
|
5966f461c3 | ||
|
|
3d91764f56 | ||
|
|
8c3a162deb | ||
|
|
b3a41db029 | ||
|
|
a71f6faed0 | ||
|
|
db7a78876b | ||
|
|
e89393693b | ||
|
|
23d370ae22 | ||
|
|
a92cec4ff9 | ||
|
|
4c1d95d4b5 | ||
|
|
3aca02fae4 | ||
|
|
695a84d8b5 | ||
|
|
5802586b20 |
No files matched your search
@@ -60,6 +60,9 @@ git_lsremote_trace.txt
|
||||
log_filter_result.txt
|
||||
time_analysis_result.txt
|
||||
|
||||
# Test/diagnostic outputs
|
||||
output/
|
||||
|
||||
# Local runtime state and generated caches
|
||||
state/
|
||||
pic/
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# WebUI 用户视角问题清单(2026-06-01)
|
||||
|
||||
## 已修复(本轮)
|
||||
|
||||
1. `/api/config` 布尔值字符串会被错误写入
|
||||
- 现象:`"false"` 可能被当成 `true`。
|
||||
- 修复:后端 `routes.py` 新增 `_coerce_bool`,前端 `config_form.js` 同步字面量解析。
|
||||
|
||||
2. 设备动作在无设备时存在未捕获 Promise 报错噪音
|
||||
- 现象:点击“返回键”后可能触发全局 `pageerror`(虽有提示但会污染错误面板)。
|
||||
- 修复:`runtime_device_actions.js` 的 `sendBackKey()` 增加局部 `try/catch`。
|
||||
|
||||
3. 预约/高价值列表中少量字段未统一做安全处理
|
||||
- 现象:个别字符串字段直接插入模板字符串。
|
||||
- 修复:`runtime_actions.js` 对 `future_str` 等补 `escapeHtml`,数值字段统一显式数值化。
|
||||
|
||||
4. WiFi 自动重连与扫描参数错误码语义不清
|
||||
- 修复:
|
||||
- 无 adb:`/api/wifi/auto-reconnect` 返回 `422`。
|
||||
- `ports` 非法:`/api/wifi/scan` 返回 `400 invalid ports`。
|
||||
- `probe_timeout` 非法继续返回 `400`。
|
||||
|
||||
## 仍可优化(下一批)
|
||||
|
||||
1. 移动端首屏头部信息密度偏高
|
||||
- 证据:`mobile_home.png` 中操作按钮区占比较大,设备/状态卡阅读层级偏挤。
|
||||
- 建议:在 `< 420px` 下把二级按钮折叠进更多菜单,保留“开始/停止/截图”主操作。
|
||||
|
||||
2. Tab 横向切换在自动化点击中偶发不可见状态
|
||||
- 证据:Playwright 偶发 `runLogs` tab 点击超时(人工可复现概率低)。
|
||||
- 建议:为 tab click 增加 `scrollIntoView` + `requestAnimationFrame` 后触发,提升自动化与低端机稳定性。
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
{
|
||||
"url": "http://localhost:8001/",
|
||||
"screenshots": [
|
||||
"artifacts\\webui_checks\\20260601\\desktop_home.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_run_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_stats_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_monitor_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_reservations_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_runlogs_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_actionlogs_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_home.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_run_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_stats_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_monitor_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_reservations_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_runlogs_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_actionlogs_panel.png"
|
||||
],
|
||||
"console_errors": [
|
||||
{
|
||||
"type": "error",
|
||||
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
|
||||
},
|
||||
{
|
||||
"type": "action",
|
||||
"text": "click_failed .tabBtn[data-target=\"runLogs\"]: Locator.click: Timeout 3000ms exceeded.\nCall log:\n - waiting for locator(\".tabBtn[data-target=\\\"runLogs\\\"]\").first\n - locator resolved to <button role=\"tab\" type=\"button\" class=\"tabBtn\" data-target=\"runLogs\" aria-selected=\"false\">…</button>\n - attempting click action\n - waiting for element to be visible, enabled and stable\n - element is visible, enabled and stable\n - scrolling into view if needed\n - done scrolling\n - performing click action\n"
|
||||
}
|
||||
],
|
||||
"page_errors": [
|
||||
"未选择设备,且无法自动解析在线设备"
|
||||
],
|
||||
"checks": {
|
||||
"desktop:has:btnStart": true,
|
||||
"desktop:has:btnStop": true,
|
||||
"desktop:has:btnForceStop": true,
|
||||
"desktop:has:btnRefresh": true,
|
||||
"desktop:has:btnScreenshot": true,
|
||||
"desktop:has:btnBackKey": true,
|
||||
"desktop:has:btnLoad": true,
|
||||
"desktop:has:btnSave": true,
|
||||
"desktop:has:device": true,
|
||||
"desktop:has:btnWifiScan": true,
|
||||
"desktop:has:wifiStatus": true,
|
||||
"desktop:has:runLog": true,
|
||||
"desktop:has:appConnText": true,
|
||||
"desktop:has:appConnDot": true,
|
||||
"desktop:has:reservationsContent": true,
|
||||
"desktop:has:highValueRoomsContent": true,
|
||||
"desktop:has:hv_expand_all": true,
|
||||
"desktop:has:hv_collapse_all": true,
|
||||
"desktop:conn_text": "已连接",
|
||||
"desktop:body_box": {
|
||||
"w": 1600,
|
||||
"h": 1178.65625,
|
||||
"scrollH": 1179
|
||||
},
|
||||
"desktop:overflow_controls": 0,
|
||||
"mobile:has:btnStart": true,
|
||||
"mobile:has:btnStop": true,
|
||||
"mobile:has:btnForceStop": true,
|
||||
"mobile:has:btnRefresh": true,
|
||||
"mobile:has:btnScreenshot": true,
|
||||
"mobile:has:btnBackKey": true,
|
||||
"mobile:has:btnLoad": true,
|
||||
"mobile:has:btnSave": true,
|
||||
"mobile:has:device": true,
|
||||
"mobile:has:btnWifiScan": true,
|
||||
"mobile:has:wifiStatus": true,
|
||||
"mobile:has:runLog": true,
|
||||
"mobile:has:appConnText": true,
|
||||
"mobile:has:appConnDot": true,
|
||||
"mobile:has:reservationsContent": true,
|
||||
"mobile:has:highValueRoomsContent": true,
|
||||
"mobile:has:hv_expand_all": true,
|
||||
"mobile:has:hv_collapse_all": true,
|
||||
"mobile:conn_text": "已连接",
|
||||
"mobile:body_box": {
|
||||
"w": 390,
|
||||
"h": 2102.875,
|
||||
"scrollH": 2103
|
||||
},
|
||||
"mobile:overflow_controls": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"console_errors": [
|
||||
{
|
||||
"type": "error",
|
||||
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
|
||||
}
|
||||
],
|
||||
"page_errors": [],
|
||||
"screenshots": [
|
||||
"artifacts\\webui_checks\\20260601_port8002\\mobile_main.png"
|
||||
],
|
||||
"checks": {
|
||||
"has_unhandled_error": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"console_errors": [
|
||||
{
|
||||
"type": "error",
|
||||
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
|
||||
}
|
||||
],
|
||||
"page_errors": [],
|
||||
"screenshots": [
|
||||
"artifacts\\webui_checks\\20260601_postfix\\mobile_after_fix.png"
|
||||
],
|
||||
"checks": {
|
||||
"has_unhandled_error": false
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -5,6 +5,11 @@ import os
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
# ==== 将项目根目录加入 sys.path,确保后续所有 douyin.* 导入正常 ================
|
||||
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if _BASE_DIR not in sys.path:
|
||||
sys.path.insert(0, _BASE_DIR)
|
||||
|
||||
# 可选:全局参数/调用跟踪(仅在环境变量 PARAM_TRACK_ALL=1 时启用)
|
||||
if os.environ.get("PARAM_TRACK_ALL") == "1":
|
||||
try:
|
||||
@@ -47,10 +52,6 @@ except Exception as e:
|
||||
# 如果需要从外部工作树加载兼容模块,可显式设置 EXTERNAL_DOUYIN_FUDAI_DIR。
|
||||
# 默认只使用当前仓库内置实现,避免绑定到某台机器的 Cursor worktree 路径。
|
||||
|
||||
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
# 确保项目根在 sys.path 中(脚本从 bin/ 目录启动时)
|
||||
if _BASE_DIR not in sys.path:
|
||||
sys.path.insert(0, _BASE_DIR)
|
||||
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip()
|
||||
|
||||
|
||||
@@ -75,7 +76,6 @@ def _load_local_shim(mod_name: str, rel_path: str) -> None:
|
||||
|
||||
|
||||
# 1) 先加载本地 shim 模块,确保后续 import 优先使用这些实现
|
||||
_load_local_shim("douyin_text_utils", "douyin/utils/douyin_text_utils.py")
|
||||
_load_local_shim("douyin_swipe_ops", "douyin/handlers/douyin_swipe_ops.py")
|
||||
|
||||
# 2) 再把完整逻辑所在目录追加到 sys.path,供 `douyin_fudai` 等模块导入
|
||||
|
||||
+17
-4
@@ -194,12 +194,12 @@
|
||||
"monitor_critical_mb": 200.0
|
||||
},
|
||||
"debug_captures": {
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"keep_days": 1,
|
||||
"max_files": 1000,
|
||||
"auto_cleanup": true,
|
||||
"async_save": false,
|
||||
"log_on_complete": false
|
||||
"log_on_complete": true
|
||||
},
|
||||
"fudai_detail_template_threshold": 0.52,
|
||||
"switch_room_wait_after_stage_diag_seconds": 7.5,
|
||||
@@ -210,7 +210,11 @@
|
||||
"reservation_test_mode": false,
|
||||
"swipe_duration_ms": 250,
|
||||
"gui": {
|
||||
"theme": "litera"
|
||||
"theme": "litera",
|
||||
"realtime_status": {
|
||||
"refresh_interval_ms": 1000,
|
||||
"tail_items": 50
|
||||
}
|
||||
},
|
||||
"fansclub_click_delay": 0.6,
|
||||
"fansclub_auto_join_wait_seconds": 5.0,
|
||||
@@ -224,5 +228,14 @@
|
||||
"high_value_room_revisit_min_prize_value": 1000.0,
|
||||
"high_value_room_revisit_max_age_days": 1,
|
||||
"swipe_up_start_y": 1200,
|
||||
"swipe_up_end_y": 600
|
||||
"swipe_up_end_y": 600,
|
||||
"swipe_down_back_enabled": false,
|
||||
"swipe_down_back_count": 3,
|
||||
"log_unified_enabled": true,
|
||||
"log_unified_path": "logs/unified.log",
|
||||
"last_wifi_target": {
|
||||
"target": "192.168.5.2:5555",
|
||||
"model": "PEPM00",
|
||||
"saved_at": 1779501066
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
# 拆分 gui/gui_app.py 实施计划
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** 把 `gui/gui_app.py`(5476 行)中内聚的 `main()` 闭包逐段抽到 `gui/components/*` 子模块,主文件持续瘦身,GUI 行为不变。
|
||||
|
||||
**Architecture:** 每个候选段抽到独立模块,改造为顶层函数,通过显式参数(回调 + 必要的 widgets/Vars/路径)接收依赖。每抽完一段独立 commit + push。
|
||||
|
||||
**Tech Stack:** Python 3.10+, tkinter / ttkbootstrap, pytest
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-05-30-split-gui-app-design.md`
|
||||
|
||||
---
|
||||
|
||||
## 抽取顺序
|
||||
|
||||
按 spec 优先级:P1 → P2 → P3 → P4 → P5 → P6。每个任务独立可停。
|
||||
P1 包括两个紧耦合段(`open_wifi_adb_dialog` 845 行 + `open_scan_dialog` 200 行)。
|
||||
|
||||
---
|
||||
|
||||
## Task 1: 抽 `open_scan_dialog` 到 `components/wifi_adb_scan_dialog.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/wifi_adb_scan_dialog.py`
|
||||
- Modify: `gui/gui_app.py:539-742` (删除原闭包) + 改 `gui/gui_app.py:1088-1093`(`open_scan_dialog` 调用点)
|
||||
|
||||
**理由先抽这个:** `open_scan_dialog` 已经是显式参数形式,不依赖 `main()` 任何捕获变量,迁移最简单。先做它能熟悉抽取流程,降 ~200 行。
|
||||
|
||||
- [ ] **Step 1: 读完整段确认依赖**
|
||||
|
||||
```bash
|
||||
# 看 539-742 完整段
|
||||
```
|
||||
确认 `open_scan_dialog` 仅依赖参数 `parent, adb_exe_local, ip_var, on_line_local, refresh_cb` 和模块级 import(`tk`, `ttk`, `discover_adb_devices`, `get_local_subnet`, `pick_best_match`, `verify_adb_target` 等)。
|
||||
|
||||
- [ ] **Step 2: 创建新模块**
|
||||
|
||||
写 `gui/components/wifi_adb_scan_dialog.py`,把 539-742 的整段函数原样复制为 `open_scan_dialog`,加 `from __future__ import annotations` 与所有需要的 import。
|
||||
|
||||
- [ ] **Step 3: 修改 `gui_app.py`,替换调用点**
|
||||
|
||||
在 `gui_app.py` 顶部 import 新模块:
|
||||
```python
|
||||
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
|
||||
```
|
||||
删除 539-742 的原 `def open_scan_dialog(...)` 定义。
|
||||
|
||||
- [ ] **Step 4: 验证语法**
|
||||
|
||||
```bash
|
||||
python -m py_compile gui/gui_app.py gui/components/wifi_adb_scan_dialog.py
|
||||
```
|
||||
Expected: 无输出(成功)
|
||||
|
||||
- [ ] **Step 5: 跑测试**
|
||||
|
||||
```bash
|
||||
pytest -x
|
||||
```
|
||||
Expected: 全部 PASS
|
||||
|
||||
- [ ] **Step 6: 行数核对 + commit**
|
||||
|
||||
```bash
|
||||
wc -l gui/gui_app.py
|
||||
git status --short
|
||||
git add gui/gui_app.py gui/components/wifi_adb_scan_dialog.py
|
||||
git commit -m "refactor(gui): 抽 open_scan_dialog 到 components/wifi_adb_scan_dialog (5476 → <new>)"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: 抽 `open_wifi_adb_dialog` 到 `components/wifi_adb_dialog.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/wifi_adb_dialog.py`
|
||||
- Modify: `gui/gui_app.py:743-1111` (删除原闭包,改 `wifi_adb_btn` 的 command)
|
||||
|
||||
**依赖分析(已完成):**
|
||||
|
||||
模块级(已 import,直接用):
|
||||
- `list_adb_devices`, `enable_wifi_adb`, `connect_wifi_adb`, `disconnect_wifi_adb`, `auto_connect_wifi_adb`, `get_device_ip`, `get_connected_wifi_devices`(from `gui.gui_core`)
|
||||
- `set_last_wifi_target`, `get_last_wifi_target`, `clear_last_wifi_target`(from `gui.gui_core_pkg`)
|
||||
- `verify_adb_target`, `query_device_model`(from `gui.gui_core_pkg.wifi_adb_scan`)
|
||||
|
||||
`main()` 局部(必须传):
|
||||
- `root: tk.Misc`(父窗口,用于 `tk.Toplevel(root)`)
|
||||
- `adb_exe: str`
|
||||
- `on_line: Callable[[str], None]`
|
||||
- `refresh_devices: Callable[[], None]`
|
||||
- `open_scan_dialog`(Task 1 完成后已为顶层函数,直接 import)
|
||||
|
||||
自递归(三处 `dialog.destroy(); open_wifi_adb_dialog()`):
|
||||
改造为传入自己的引用 —— 用一个内部函数 `_reopen()` 闭包捕获参数,或参数化 `parent`/`adb_exe` 后直接再调用顶层函数。**采用方案 B:把 `open_wifi_adb_dialog` 改成顶层函数,签名带所有依赖,自递归直接调用自己。**
|
||||
|
||||
- [ ] **Step 1: 创建新模块骨架**
|
||||
|
||||
```python
|
||||
# gui/components/wifi_adb_dialog.py
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, W, X
|
||||
from typing import Callable
|
||||
|
||||
from gui.gui_core import (
|
||||
auto_connect_wifi_adb,
|
||||
connect_wifi_adb,
|
||||
disconnect_wifi_adb,
|
||||
enable_wifi_adb,
|
||||
get_connected_wifi_devices,
|
||||
get_device_ip,
|
||||
list_adb_devices,
|
||||
)
|
||||
from gui.gui_core_pkg import (
|
||||
clear_last_wifi_target,
|
||||
get_last_wifi_target,
|
||||
set_last_wifi_target,
|
||||
)
|
||||
from gui.gui_core_pkg.wifi_adb_scan import query_device_model
|
||||
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
|
||||
|
||||
|
||||
def open_wifi_adb_dialog(
|
||||
root: tk.Misc,
|
||||
*,
|
||||
adb_exe: str,
|
||||
on_line: Callable[[str], None],
|
||||
refresh_devices: Callable[[], None],
|
||||
) -> None:
|
||||
"""打开 WiFi ADB 设置对话框。
|
||||
|
||||
从 gui_app.main 抽出,显式接收依赖。
|
||||
"""
|
||||
# ... (Step 2 复制原 743-1111 函数体,把对外部名字的引用替换为参数)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 复制函数体并替换闭包变量引用**
|
||||
|
||||
把 `gui_app.py:743-1111`(从 `def open_wifi_adb_dialog():` 内 body 开始,到 `info_label.pack(...)` 结束)整段复制进新函数体,缩进调整 4 → 4(已经一致,只是去掉外层 `def main()` 这一层)。
|
||||
|
||||
把三处自递归改为带参数的:
|
||||
```python
|
||||
# 原: open_wifi_adb_dialog()
|
||||
# 改: open_wifi_adb_dialog(root, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
|
||||
```
|
||||
|
||||
把对 `open_scan_dialog` 的引用保留为 module-import 形式:
|
||||
```python
|
||||
# 原:
|
||||
# command=lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists)
|
||||
# 不变(因为已 import 顶层 open_scan_dialog)
|
||||
```
|
||||
|
||||
注意 `toggle_maximize`、`refresh_device_lists` 是嵌套闭包,保持原样不抽 —— 它们捕获的是对话框内 widgets,只在对话框内用。
|
||||
|
||||
- [ ] **Step 3: 改 `gui_app.py`,删原闭包,改按钮 command**
|
||||
|
||||
在 `gui_app.py` 顶部加:
|
||||
```python
|
||||
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog as _open_wifi_adb_dialog
|
||||
```
|
||||
|
||||
删除 743-1111 的原嵌套 `def open_wifi_adb_dialog():` 整段。
|
||||
|
||||
把 1113 行的按钮 command 改为:
|
||||
```python
|
||||
wifi_adb_btn = ttk.Button(
|
||||
top,
|
||||
text="WiFi ADB",
|
||||
command=lambda: _open_wifi_adb_dialog(
|
||||
root,
|
||||
adb_exe=adb_exe,
|
||||
on_line=on_line,
|
||||
refresh_devices=refresh_devices,
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 验证语法**
|
||||
|
||||
```bash
|
||||
python -m py_compile gui/gui_app.py gui/components/wifi_adb_dialog.py
|
||||
```
|
||||
Expected: 无输出
|
||||
|
||||
- [ ] **Step 5: 跑测试**
|
||||
|
||||
```bash
|
||||
pytest -x
|
||||
```
|
||||
Expected: 全部 PASS
|
||||
|
||||
- [ ] **Step 6: 行数核对 + commit**
|
||||
|
||||
```bash
|
||||
wc -l gui/gui_app.py
|
||||
git status --short
|
||||
git add gui/gui_app.py gui/components/wifi_adb_dialog.py
|
||||
git commit -m "refactor(gui): 抽 open_wifi_adb_dialog 到 components/wifi_adb_dialog (<old> → <new>)"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: 评估 P2(`load_config_to_ui` + `save_ui_to_config`)
|
||||
|
||||
P2 在 spec 里被标记为高风险(100+ Var)。只有 Task 1+2 完成且测试稳定时才做。
|
||||
|
||||
- [ ] **Step 1: 数 Var 数量**
|
||||
|
||||
```bash
|
||||
grep -nE "^\s+[a-zA-Z_]+_var = " gui/gui_app.py | wc -l
|
||||
```
|
||||
|
||||
如果数量 ≥ 50,跳过 Task 3,直接进 Task 4。
|
||||
如果 < 50,继续。
|
||||
|
||||
- [ ] **Step 2: 如果继续,设计 dataclass 聚合 Var**
|
||||
|
||||
读 2748-3402 列出所有用到的 Var,定义:
|
||||
```python
|
||||
# gui/components/config_io.py
|
||||
@dataclass
|
||||
class ConfigVars:
|
||||
y_var: tk.IntVar
|
||||
needswitch_var: tk.BooleanVar
|
||||
# ... 全部
|
||||
```
|
||||
|
||||
抽出函数:
|
||||
```python
|
||||
def load_config_to_ui(vars_: ConfigVars, *, on_line: Callable[[str], None]) -> None: ...
|
||||
def save_ui_to_config(vars_: ConfigVars, *, on_line: Callable[[str], None]) -> None: ...
|
||||
```
|
||||
|
||||
实施步骤参考 Task 2 的 Step 1-6。
|
||||
|
||||
如果改动量过大或测试卡住,**回滚并跳过 P2**。
|
||||
|
||||
---
|
||||
|
||||
## Task 4: 抽 `refresh_reservations` 到 `components/reservations_view.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/reservations_view.py`
|
||||
- Modify: `gui/gui_app.py:4530-4805` (删原闭包),改调用点
|
||||
|
||||
- [ ] **Step 1: 列出依赖**
|
||||
|
||||
读 4530-4805,记录捕获的 widgets(主要是 `reservations_tree: ttk.Treeview`)、状态变量、回调。
|
||||
|
||||
- [ ] **Step 2: 创建模块,函数签名**
|
||||
|
||||
```python
|
||||
# gui/components/reservations_view.py
|
||||
from __future__ import annotations
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from typing import Callable
|
||||
|
||||
def refresh_reservations(
|
||||
tree: ttk.Treeview,
|
||||
*,
|
||||
on_line: Callable[[str], None] = lambda _msg: None,
|
||||
) -> None:
|
||||
"""刷新预约 Tab 的 Treeview。"""
|
||||
# body 来自原 4530-4805
|
||||
```
|
||||
|
||||
依赖里如果有路径(`get_logs_dir` 之类)直接 import,不需要传参。
|
||||
|
||||
- [ ] **Step 3: 修改 `gui_app.py`**
|
||||
|
||||
```python
|
||||
from gui.components.reservations_view import refresh_reservations as _refresh_reservations_impl
|
||||
|
||||
# 原 def refresh_reservations(): ... 改为:
|
||||
def refresh_reservations():
|
||||
_refresh_reservations_impl(reservations_tree, on_line=on_line)
|
||||
```
|
||||
保留薄包装 `def refresh_reservations()`,因为 `auto_refresh_reservations` 等地方仍以闭包形式调用它。
|
||||
|
||||
- [ ] **Step 4: 验证 + 测试 + commit**
|
||||
|
||||
```bash
|
||||
python -m py_compile gui/gui_app.py gui/components/reservations_view.py
|
||||
pytest -x
|
||||
wc -l gui/gui_app.py
|
||||
git add gui/gui_app.py gui/components/reservations_view.py
|
||||
git commit -m "refactor(gui): 抽 refresh_reservations 到 components/reservations_view (<old> → <new>)"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: 抽 `refresh_high_value_rooms` 到 `components/high_value_view.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/high_value_view.py`
|
||||
- Modify: `gui/gui_app.py:4805-5085`
|
||||
|
||||
- [ ] **Step 1: 列出依赖**
|
||||
|
||||
读 4805-5085,记录捕获的 widgets(主要是 `high_value_rooms_tree: ttk.Treeview`)、状态变量、回调。
|
||||
|
||||
- [ ] **Step 2: 创建模块,函数签名**
|
||||
|
||||
```python
|
||||
# gui/components/high_value_view.py
|
||||
from __future__ import annotations
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from typing import Callable
|
||||
|
||||
def refresh_high_value_rooms(
|
||||
tree: ttk.Treeview,
|
||||
*,
|
||||
on_line: Callable[[str], None] = lambda _msg: None,
|
||||
) -> None:
|
||||
"""刷新高价值房间 Tab 的 Treeview。"""
|
||||
# body 来自原 4805-5085
|
||||
```
|
||||
|
||||
依赖里如果有路径(`get_logs_dir` 之类)直接 import,不需要传参。
|
||||
|
||||
- [ ] **Step 3: 修改 `gui_app.py`**
|
||||
|
||||
```python
|
||||
from gui.components.high_value_view import refresh_high_value_rooms as _refresh_high_value_rooms_impl
|
||||
|
||||
# 原 def refresh_high_value_rooms(): ... 改为薄包装:
|
||||
def refresh_high_value_rooms():
|
||||
_refresh_high_value_rooms_impl(high_value_rooms_tree, on_line=on_line)
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 验证 + 测试 + commit**
|
||||
|
||||
```bash
|
||||
python -m py_compile gui/gui_app.py gui/components/high_value_view.py
|
||||
pytest -x
|
||||
wc -l gui/gui_app.py
|
||||
git add gui/gui_app.py gui/components/high_value_view.py
|
||||
git commit -m "refactor(gui): 抽 refresh_high_value_rooms 到 components/high_value_view (<old> → <new>)"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: 抽 `do_screenshot` + `_bind_screenshot_button` 到 `components/screenshot_action.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/screenshot_action.py`
|
||||
- Modify: `gui/gui_app.py:3402-3651`
|
||||
|
||||
- [ ] **Step 1: 列出依赖**
|
||||
|
||||
读 3402-3651。`do_screenshot` 依赖:`adb_exe`、状态 Label、图片预览刷新回调、ADB 截图工具函数。
|
||||
|
||||
- [ ] **Step 2-4: 抽出,签名:**
|
||||
|
||||
```python
|
||||
def do_screenshot(
|
||||
*,
|
||||
adb_exe: str,
|
||||
on_line: Callable[[str], None],
|
||||
on_done: Callable[[str], None], # 截图保存路径
|
||||
status_label: ttk.Label | None = None,
|
||||
) -> None:
|
||||
...
|
||||
|
||||
def bind_screenshot_button(
|
||||
btn: ttk.Button,
|
||||
*,
|
||||
adb_exe: str,
|
||||
on_line: Callable[[str], None],
|
||||
on_done: Callable[[str], None],
|
||||
status_label: ttk.Label | None = None,
|
||||
) -> None:
|
||||
btn.configure(command=lambda: do_screenshot(
|
||||
adb_exe=adb_exe, on_line=on_line, on_done=on_done, status_label=status_label
|
||||
))
|
||||
```
|
||||
|
||||
调用点同 Task 4。
|
||||
|
||||
commit msg: `refactor(gui): 抽 do_screenshot 到 components/screenshot_action (<old> → <new>)`
|
||||
|
||||
---
|
||||
|
||||
## Task 7: 抽 `refresh_actions_log` + 搜索栏 到 `components/actions_log_view.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/actions_log_view.py`
|
||||
- Modify: `gui/gui_app.py:4845-5070`
|
||||
|
||||
- [ ] **Step 1: 列出依赖**
|
||||
|
||||
读 4845-5070。包含:`configure_actions_log_colors`、`refresh_actions_log`、几个搜索方法 `search_in_actions_log`/`search_next_in_actions`/`search_prev_in_actions`/`clear_search_in_actions`/`on_actions_search_entry_key`。
|
||||
|
||||
- [ ] **Step 2-4: 设计**
|
||||
|
||||
设计成 1 个 `setup_actions_log_view(text_widget, search_entry, ...)` 一次性绑定所有,或者保留几个独立函数都接收 `text_widget` 参数。优先后者(更小步)。
|
||||
|
||||
签名:
|
||||
```python
|
||||
def configure_actions_log_colors(text_widget: tk.Text) -> None: ...
|
||||
def refresh_actions_log(text_widget: tk.Text, *, on_line: Callable[[str], None]) -> None: ...
|
||||
def search_in_actions_log(text_widget: tk.Text, search_entry: ttk.Entry, *, direction: int = 1) -> None: ...
|
||||
```
|
||||
|
||||
`gui_app.py` 里保留薄包装让原闭包调用模式不变。
|
||||
|
||||
commit msg: `refactor(gui): 抽 actions_log 视图相关到 components/actions_log_view (<old> → <new>)`
|
||||
|
||||
---
|
||||
|
||||
## Task 8: 评估停止条件 + 收尾
|
||||
|
||||
- [ ] **Step 1: 检查停止条件**
|
||||
|
||||
```bash
|
||||
wc -l gui/gui_app.py
|
||||
```
|
||||
满足以下任一即停:
|
||||
1. ≤ 3000 行
|
||||
2. 行数下降 < 50
|
||||
3. 下一段需传 ≥ 50 个独立依赖
|
||||
|
||||
- [ ] **Step 2: 如果停止,写收尾说明**
|
||||
|
||||
如果停止,在 `docs/superpowers/specs/2026-05-30-split-gui-app-design.md` 末尾追加 `## Outcome` 段:列出实际抽出的模块、行数变化、未做的项。
|
||||
|
||||
```bash
|
||||
git add docs/superpowers/specs/2026-05-30-split-gui-app-design.md
|
||||
git commit -m "docs(specs): 补充 gui_app 拆分实际成果"
|
||||
git push
|
||||
```
|
||||
|
||||
- [ ] **Step 3: 报告**
|
||||
|
||||
总结输出给用户:
|
||||
- 起始行数:5476
|
||||
- 当前行数:`<X>`
|
||||
- 抽出的模块列表
|
||||
- pytest 状态
|
||||
- 是否还有未抽的候选(可作为下一轮)
|
||||
|
||||
---
|
||||
|
||||
## 关键约束(每个 Task 都要遵守)
|
||||
|
||||
1. **AGENTS.md**:每个 Task 都要 commit + push,只 stage 本任务实际改的文件,不混入用户已有改动。
|
||||
2. **不改行为**:抽取是纯重构,不修 bug、不优化性能、不删功能。
|
||||
3. **失败回滚**:若 pytest 失败且修复需改 ≥ 2 个非目标文件,`git reset --hard HEAD~1`(本任务的 commit 还没 push),回到上一 Task 报告问题。
|
||||
4. **每个 Task 验证后再开下一个**:不批量做。
|
||||
5. **手工 smoke 推迟到批次末尾**:本计划的 pytest 不覆盖 GUI 交互(项目测试有意写得轻),抽取属纯重构,逻辑保持一致。每个 Task 完成后,在 Task 8 的收尾报告里提示用户:「请启动 GUI 跑一遍受影响功能(WiFi 对话框 / 预约 Tab / 高价值房间 / 截图按钮 / 操作日志 Tab),确认无回归。」用户 smoke 后若发现问题,定位到具体 Task 的 commit 回滚。
|
||||
@@ -0,0 +1,982 @@
|
||||
# Split WebUI Large Files Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Continue the large-file split after `gui/gui_app.py` by modularizing the WebUI frontend and, only after the frontend is stable, splitting the Web GUI Python server.
|
||||
|
||||
**Architecture:** Keep the current static WebUI behavior intact while moving code into focused `webui/js/*` and `webui/css/*` files. Each task changes one responsibility, preserves global names needed by `DOMContentLoaded`, runs focused tests, commits, and pushes before the next task.
|
||||
|
||||
**Tech Stack:** Plain HTML/CSS/JavaScript, Python `http.server`, pytest, browser smoke test for UI changes.
|
||||
|
||||
---
|
||||
|
||||
## Current Evidence
|
||||
|
||||
From the current worktree on 2026-05-31:
|
||||
|
||||
| File | Lines | Role |
|
||||
|---|---:|---|
|
||||
| `webui/styles.css` | 3745 | WebUI visual system, layout, panels, logs, responsive rules |
|
||||
| `webui/app.js` | 2512 | WebUI constants, state, API calls, rendering, polling, event wiring |
|
||||
| `gui/web_gui.py` | 1663 | local HTTP server, runner, API routes, static file serving |
|
||||
| `webui/index.html` | 1232 | WebUI DOM structure and config bindings |
|
||||
|
||||
`gui/gui_app.py` is already down to about 130 lines and should not be the next split target. The next target is the WebUI bundle.
|
||||
|
||||
## Stop Conditions
|
||||
|
||||
Stop this plan and write an outcome note when any one is true:
|
||||
|
||||
1. `webui/app.js` is below 700 lines and `webui/styles.css` is below 1400 lines.
|
||||
2. The next split would require changing more than 3 of the large files in one task.
|
||||
3. Browser smoke finds a visual or runtime regression that cannot be fixed inside the current task boundary.
|
||||
4. Tests fail and the fix would require behavior changes outside the current responsibility.
|
||||
|
||||
## Verification Commands
|
||||
|
||||
Run these after every JavaScript or HTML task:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
```text
|
||||
py_compile: exit code 0
|
||||
pytest: all selected tests PASS
|
||||
```
|
||||
|
||||
Run these after every CSS or visual task:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py > logs\webui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
```text
|
||||
py_compile: exit code 0
|
||||
pytest: all selected tests PASS
|
||||
```
|
||||
|
||||
For frontend visual changes, also start the Web GUI and inspect it in a browser:
|
||||
|
||||
```powershell
|
||||
python gui\web_gui.py
|
||||
```
|
||||
|
||||
Expected browser checks:
|
||||
|
||||
- `/` loads without a blank page.
|
||||
- Console has no module load errors, syntax errors, or missing function errors.
|
||||
- Header buttons, tabs, logs panel, reservations panel, high-value panel, screenshot preview, and footer remain visible without overlap at desktop width.
|
||||
- At mobile width, command buttons wrap and panels remain readable.
|
||||
|
||||
## Static Loading Decision
|
||||
|
||||
The current page loads:
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
|
||||
<script src="app.js?v=console-20260520-theme-v35"></script>
|
||||
```
|
||||
|
||||
Use classic scripts for the first JavaScript split instead of ES modules. This avoids a broad initialization rewrite and keeps inline event expectations simple. New scripts must be loaded before `app.js` if `app.js` depends on them.
|
||||
|
||||
For CSS, use multiple `<link rel="stylesheet">` tags. Keep `styles.css` as the compatibility shell until the end of the CSS split.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Add WebUI Static Asset Structure
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/README.md`
|
||||
- Create: `webui/css/README.md`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create asset directory docs**
|
||||
|
||||
Create `webui/js/README.md`:
|
||||
|
||||
```markdown
|
||||
# WebUI JavaScript modules
|
||||
|
||||
Classic browser scripts loaded by `webui/index.html`.
|
||||
|
||||
Load order matters:
|
||||
|
||||
1. `constants.js`
|
||||
2. `dom.js`
|
||||
3. `api.js`
|
||||
4. focused feature scripts
|
||||
5. `app.js`
|
||||
|
||||
Keep behavior-preserving splits small. Do not introduce a build step unless a later plan explicitly replaces this static layout.
|
||||
```
|
||||
|
||||
Create `webui/css/README.md`:
|
||||
|
||||
```markdown
|
||||
# WebUI CSS modules
|
||||
|
||||
Plain CSS files loaded by `webui/index.html`.
|
||||
|
||||
Recommended order:
|
||||
|
||||
1. `tokens.css`
|
||||
2. `base.css`
|
||||
3. `layout.css`
|
||||
4. `components.css`
|
||||
5. focused panel or feature CSS
|
||||
6. `styles.css` compatibility remainder
|
||||
|
||||
Keep selectors stable so existing HTML and JavaScript continue to work.
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add no-op load anchors to `index.html`**
|
||||
|
||||
Insert comments around the existing assets:
|
||||
|
||||
```html
|
||||
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
|
||||
<script src="app.js?v=console-20260520-theme-v35"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected: selected tests PASS.
|
||||
|
||||
- [ ] **Step 4: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/js/README.md webui/css/README.md
|
||||
git commit -m "refactor(webui): add static module split structure"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Extract JavaScript Constants and Copy
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/constants.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `constants.js`**
|
||||
|
||||
Move these top-level constants from `app.js` into `webui/js/constants.js` unchanged:
|
||||
|
||||
```javascript
|
||||
const UI_LIMITS = Object.freeze({
|
||||
runLogMaxLines: 50000,
|
||||
runLogMaxChars: 200000,
|
||||
actionsLogMaxLines: 5000,
|
||||
scrollBottomThresholdPx: 5,
|
||||
screenshotPollMs: 1500,
|
||||
logPollMs: 800,
|
||||
statsPollMs: 1200,
|
||||
});
|
||||
|
||||
const UI_CLASS = Object.freeze({
|
||||
busy: "isBusy",
|
||||
clickable: "isClickable",
|
||||
collapsed: "isCollapsed",
|
||||
listCollapsed: "isListCollapsed",
|
||||
reservationHeader: "reservationHeader",
|
||||
reservationBody: "reservationBody",
|
||||
reservationsList: "reservationsList",
|
||||
shotEmpty: "isShotEmpty",
|
||||
statusRunning: "statusRunning",
|
||||
statusIdle: "statusIdle",
|
||||
statusError: "statusError",
|
||||
});
|
||||
|
||||
const RUN_TONE = Object.freeze({
|
||||
running: "running",
|
||||
idle: "idle",
|
||||
error: "error",
|
||||
});
|
||||
```
|
||||
|
||||
Also move `UI_COPY`, `TIMELINE_SERIES_KEYS`, `TIMELINE_LAYOUT`, `TIMELINE_STROKES`, and `DEFAULTS` unchanged.
|
||||
|
||||
- [ ] **Step 2: Remove moved constants from `app.js`**
|
||||
|
||||
Delete only the moved constant declarations from `webui/app.js`. Keep state variables such as `logIdx`, `pollTimer`, `runLogBuffer`, and `deviceOverviewState` in `app.js` for now.
|
||||
|
||||
- [ ] **Step 3: Load `constants.js` before `app.js`**
|
||||
|
||||
Change the bottom of `webui/index.html` to:
|
||||
|
||||
```html
|
||||
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
|
||||
<script src="js/constants.js?v=console-20260531-split-1"></script>
|
||||
<script src="app.js?v=console-20260531-split-1"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected: both PASS.
|
||||
|
||||
- [ ] **Step 5: Browser smoke**
|
||||
|
||||
Start:
|
||||
|
||||
```powershell
|
||||
python gui\web_gui.py
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:8765/` or the printed local URL. Confirm console has no `UI_LIMITS is not defined`, `DEFAULTS is not defined`, or `fmtDuration is not defined` errors.
|
||||
|
||||
- [ ] **Step 6: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/constants.js
|
||||
git commit -m "refactor(webui): extract frontend constants"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Extract DOM and Formatting Helpers
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/dom_utils.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `dom_utils.js`**
|
||||
|
||||
Move these functions from `app.js` into `webui/js/dom_utils.js` unchanged:
|
||||
|
||||
```javascript
|
||||
function $(id)
|
||||
function setTextIfExists(id, text)
|
||||
function clearEl(el)
|
||||
function escapeHtml(s)
|
||||
function fmtTime(ts)
|
||||
function fmtNum(v)
|
||||
function fmtDuration(seconds)
|
||||
```
|
||||
|
||||
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete the moved function declarations only. Do not move UI initialization functions yet.
|
||||
|
||||
- [ ] **Step 3: Load `dom_utils.js` after `constants.js`**
|
||||
|
||||
```html
|
||||
<script src="js/constants.js?v=console-20260531-split-2"></script>
|
||||
<script src="js/dom_utils.js?v=console-20260531-split-2"></script>
|
||||
<script src="app.js?v=console-20260531-split-2"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run the standard JavaScript verification commands. In browser console, confirm no `$ is not defined`, `fmtDuration is not defined`, or `escapeHtml is not defined` errors.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/dom_utils.js
|
||||
git commit -m "refactor(webui): extract DOM and format helpers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Extract API Client Helpers
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/api_client.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `api_client.js`**
|
||||
|
||||
Move these functions and state from `app.js` into `webui/js/api_client.js` unchanged:
|
||||
|
||||
```javascript
|
||||
let _apiFailStreak = 0;
|
||||
const _apiFailThreshold = 2;
|
||||
let _csrfToken = null;
|
||||
|
||||
function setConnState(state)
|
||||
function notifyApiOk()
|
||||
function notifyApiFail()
|
||||
async function apiGet(path)
|
||||
async function getCsrfToken()
|
||||
async function apiPost(path, body)
|
||||
```
|
||||
|
||||
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
|
||||
|
||||
- [ ] **Step 2: Remove moved declarations from `app.js`**
|
||||
|
||||
Delete only the moved declarations. Keep feature-level functions such as `refreshDevices`, `startRun`, `pollLogs`, and `pollStats` in `app.js`.
|
||||
|
||||
- [ ] **Step 3: Load `api_client.js` after `dom_utils.js`**
|
||||
|
||||
```html
|
||||
<script src="js/constants.js?v=console-20260531-split-3"></script>
|
||||
<script src="js/dom_utils.js?v=console-20260531-split-3"></script>
|
||||
<script src="js/api_client.js?v=console-20260531-split-3"></script>
|
||||
<script src="app.js?v=console-20260531-split-3"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run the standard JavaScript verification commands. In browser, click refresh devices and load config. Confirm API state footer updates and no `apiGet is not defined` or CSRF errors appear.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/api_client.js
|
||||
git commit -m "refactor(webui): extract API client helpers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Extract Log View Behavior
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/log_views.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `log_views.js`**
|
||||
|
||||
Move the log rendering and search functions from `app.js` into `webui/js/log_views.js`:
|
||||
|
||||
```javascript
|
||||
function classifyLogLine(line)
|
||||
function renderLogLineNode(line)
|
||||
function appendLog(lines)
|
||||
function renderRunLog()
|
||||
function appendRunLogLines(lines)
|
||||
async function fetchActionsLog()
|
||||
function renderActionsLog()
|
||||
```
|
||||
|
||||
Keep these shared state variables in `app.js` for this task:
|
||||
|
||||
```javascript
|
||||
let runLogBuffer = [];
|
||||
let runLogFilter = "";
|
||||
let runLogMode = "filter";
|
||||
let runSearchResultsBuffer = [];
|
||||
let runSearchActive = false;
|
||||
let actionsLogBuffer = [];
|
||||
let actionsLogFilter = "";
|
||||
```
|
||||
|
||||
Because classic scripts share global scope, `log_views.js` can keep using these names.
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved function declarations.
|
||||
|
||||
- [ ] **Step 3: Load `log_views.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/constants.js?v=console-20260531-split-4"></script>
|
||||
<script src="js/dom_utils.js?v=console-20260531-split-4"></script>
|
||||
<script src="js/api_client.js?v=console-20260531-split-4"></script>
|
||||
<script src="js/log_views.js?v=console-20260531-split-4"></script>
|
||||
<script src="app.js?v=console-20260531-split-4"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run the standard JavaScript verification commands. In browser, check the run log filter/search and action log refresh.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/log_views.js
|
||||
git commit -m "refactor(webui): extract log view behavior"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Extract Dashboard Renderers
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/dashboard_renderers.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `dashboard_renderers.js`**
|
||||
|
||||
Move these renderer functions from `app.js` into `webui/js/dashboard_renderers.js`:
|
||||
|
||||
```javascript
|
||||
function renderBars(containerId, dataMap, labelMap)
|
||||
function renderTopContent(containerId, items)
|
||||
function renderWinsTable(containerId, wins)
|
||||
function renderTimeline(containerId, timeline)
|
||||
function renderOverviewSparkline(svgId, timeline)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved renderer declarations.
|
||||
|
||||
- [ ] **Step 3: Load `dashboard_renderers.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/dashboard_renderers.js?v=console-20260531-split-5"></script>
|
||||
<script src="app.js?v=console-20260531-split-5"></script>
|
||||
```
|
||||
|
||||
Keep all earlier module script tags before `dashboard_renderers.js`.
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification. In browser, confirm stats charts, timeline tooltip, top content table, and wins table still render.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/dashboard_renderers.js
|
||||
git commit -m "refactor(webui): extract dashboard renderers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Extract Config Form Binding
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/config_form.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `config_form.js`**
|
||||
|
||||
Move these config-related functions from `app.js` into `webui/js/config_form.js`:
|
||||
|
||||
```javascript
|
||||
function getConfigBoundElements()
|
||||
function syncMirrorFields()
|
||||
function getConfigValue(cfg, key)
|
||||
function coerceValue(type, raw, isCheckbox)
|
||||
function applyConfigToUI(cfg)
|
||||
function collectConfigFromUI()
|
||||
async function loadConfig()
|
||||
async function saveConfig()
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved config declarations.
|
||||
|
||||
- [ ] **Step 3: Load `config_form.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/config_form.js?v=console-20260531-split-6"></script>
|
||||
<script src="app.js?v=console-20260531-split-6"></script>
|
||||
```
|
||||
|
||||
Keep all earlier module script tags before `config_form.js`.
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification and `pytest tests/test_gui_webui_sync.py -q`. In browser, load config, change one harmless UI field, save, reload, and confirm no config-binding error appears.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/config_form.js
|
||||
git commit -m "refactor(webui): extract config form bindings"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 8: Extract Polling and Device Actions
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/runtime_actions.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `runtime_actions.js`**
|
||||
|
||||
Move these functions from `app.js` into `webui/js/runtime_actions.js`:
|
||||
|
||||
```javascript
|
||||
async function refreshDevices()
|
||||
function decorateDeviceSelect()
|
||||
function selectedDeviceId()
|
||||
async function postDeviceAction(path, body, successPrefix)
|
||||
async function forceStopRun()
|
||||
async function sendBackKey()
|
||||
async function wifiEnable()
|
||||
async function wifiConnect()
|
||||
async function wifiDisconnect()
|
||||
async function tryAutoReconnectLastWifi()
|
||||
async function wifiScan()
|
||||
async function startRun()
|
||||
async function testYanghao()
|
||||
async function testComment()
|
||||
async function stopRun()
|
||||
async function pollLogs()
|
||||
async function pollReservations()
|
||||
async function pollHighValueRooms()
|
||||
async function pollStats()
|
||||
function startPolling()
|
||||
function startStatsPolling()
|
||||
```
|
||||
|
||||
Keep `DOMContentLoaded` event wiring in `app.js`.
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved runtime declarations.
|
||||
|
||||
- [ ] **Step 3: Load `runtime_actions.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/runtime_actions.js?v=console-20260531-split-7"></script>
|
||||
<script src="app.js?v=console-20260531-split-7"></script>
|
||||
```
|
||||
|
||||
Keep all earlier module script tags before `runtime_actions.js`.
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification. In browser, click refresh devices, load config, start/stop if safe, refresh action log, and switch through all panels.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/runtime_actions.js
|
||||
git commit -m "refactor(webui): extract runtime actions and polling"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 9: Reduce `app.js` to Initialization Glue
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/ui_init.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Move UI initialization helpers**
|
||||
|
||||
Move these functions into `webui/js/ui_init.js`:
|
||||
|
||||
```javascript
|
||||
function initTheme()
|
||||
function ensureToastContainer()
|
||||
function toast(message, kind = "info", { duration = 3500 } = {})
|
||||
function initConfigSearch()
|
||||
function initFooter()
|
||||
function attachCopyButtons()
|
||||
function initKeyboardShortcuts()
|
||||
function initHeaderScroll()
|
||||
function initShotFullscreen()
|
||||
function applyKbdHints()
|
||||
function initStickySectionShadow()
|
||||
function initShortcutsHelp()
|
||||
function updateTabBadge(target, count)
|
||||
function startReservationsCountdownTick()
|
||||
function initTabs()
|
||||
function attachNumberSteppers()
|
||||
function pollShot()
|
||||
function startShotPolling()
|
||||
function setButtonBusy(id, busy)
|
||||
function setRunOverview(state, meta, tone)
|
||||
function updateDeviceOverview()
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Keep `app.js` as bootstrapping only**
|
||||
|
||||
After this task, `app.js` should contain:
|
||||
|
||||
```javascript
|
||||
window.addEventListener("DOMContentLoaded", async () => {
|
||||
initTheme();
|
||||
initTabs();
|
||||
initConfigSearch();
|
||||
initFooter();
|
||||
attachCopyButtons();
|
||||
initShotFullscreen();
|
||||
initHeaderScroll();
|
||||
initKeyboardShortcuts();
|
||||
initShortcutsHelp();
|
||||
initStickySectionShadow();
|
||||
attachNumberSteppers();
|
||||
applyKbdHints();
|
||||
syncMirrorFields();
|
||||
await refreshDevices();
|
||||
await loadConfig();
|
||||
startPolling();
|
||||
startStatsPolling();
|
||||
startShotPolling();
|
||||
startReservationsCountdownTick();
|
||||
pollLogs();
|
||||
pollStats();
|
||||
pollShot();
|
||||
pollReservations();
|
||||
pollHighValueRooms();
|
||||
});
|
||||
```
|
||||
|
||||
During implementation, preserve the existing event listener bindings from the current `DOMContentLoaded` body. If the current body wires buttons or inputs, keep those bindings in `app.js` or move them into a clearly named `bindAppEvents()` function in `ui_init.js`.
|
||||
|
||||
- [ ] **Step 3: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification. Browser smoke must cover initial load, tabs, theme, footer, shortcuts overlay, screenshot preview, logs, and config load/save.
|
||||
|
||||
- [ ] **Step 4: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/ui_init.js
|
||||
git commit -m "refactor(webui): reduce app script to initialization glue"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 10: Split CSS Tokens and Base Rules
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/css/tokens.css`
|
||||
- Create: `webui/css/base.css`
|
||||
- Modify: `webui/styles.css`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Extract theme tokens**
|
||||
|
||||
Move these ranges from `styles.css` into `webui/css/tokens.css`:
|
||||
|
||||
- `:root { ... }` light theme token block
|
||||
- `:root[data-theme="dark"] { ... }` dark theme token block
|
||||
- reduced-motion token or global animation defaults that are pure variables
|
||||
|
||||
Do not rename variables.
|
||||
|
||||
- [ ] **Step 2: Extract base element rules**
|
||||
|
||||
Move base reset and generic element rules into `webui/css/base.css`:
|
||||
|
||||
- `*`, `html`, `body`
|
||||
- `button`, `input`, `select`, `textarea`
|
||||
- generic focus-visible rules
|
||||
- global scrollbar rules
|
||||
- generic utility classes that are not tied to one panel
|
||||
|
||||
- [ ] **Step 3: Load extracted CSS before `styles.css`**
|
||||
|
||||
```html
|
||||
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
|
||||
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-1" />
|
||||
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-1" />
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-1" />
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run CSS verification commands. Browser smoke must compare light and dark theme basics, header, buttons, forms, and scrollbars.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/styles.css webui/css/tokens.css webui/css/base.css
|
||||
git commit -m "refactor(webui): extract CSS tokens and base rules"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 11: Split CSS Layout and Shared Components
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/css/layout.css`
|
||||
- Create: `webui/css/components.css`
|
||||
- Modify: `webui/styles.css`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Extract layout rules**
|
||||
|
||||
Move app shell, header, workspace, panel grid, and footer layout rules into `layout.css`. Include responsive `@media` rules that only affect those layout selectors.
|
||||
|
||||
- [ ] **Step 2: Extract shared component rules**
|
||||
|
||||
Move shared button, card, tab, field, table, tooltip, toast, skeleton, and shortcut overlay rules into `components.css`. Include related `@media` and `prefers-reduced-motion` blocks when they directly belong to those selectors.
|
||||
|
||||
- [ ] **Step 3: Load CSS in stable order**
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-2" />
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run CSS verification. Browser smoke must check desktop and mobile layout, tabs, cards, buttons, toast, tooltip, and shortcuts overlay.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/styles.css webui/css/layout.css webui/css/components.css
|
||||
git commit -m "refactor(webui): extract CSS layout and shared components"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 12: Split CSS Feature Panels
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/css/panels.css`
|
||||
- Create: `webui/css/logs.css`
|
||||
- Create: `webui/css/charts.css`
|
||||
- Modify: `webui/styles.css`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Extract panel-specific styles**
|
||||
|
||||
Move screenshot preview, reservations, high-value room, realtime status, and panel-specific content rules into `panels.css`.
|
||||
|
||||
- [ ] **Step 2: Extract log styles**
|
||||
|
||||
Move run log, action log, log line classification, log search, and log scrollbar rules into `logs.css`.
|
||||
|
||||
- [ ] **Step 3: Extract chart/table styles**
|
||||
|
||||
Move chart blocks, timeline tooltip, bar rows, top content table, wins table, and related table rows into `charts.css`.
|
||||
|
||||
- [ ] **Step 4: Load CSS in stable order**
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/panels.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/logs.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/charts.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-3" />
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Verify and smoke**
|
||||
|
||||
Run CSS verification. Browser smoke must check screenshot preview, reservations, high-value room list, log panels, charts, and mobile wrapping.
|
||||
|
||||
- [ ] **Step 6: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/styles.css webui/css/panels.css webui/css/logs.css webui/css/charts.css
|
||||
git commit -m "refactor(webui): extract CSS feature panels"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 13: Decide Whether to Split `index.html`
|
||||
|
||||
**Files:**
|
||||
- Modify: `webui/index.html`
|
||||
- Optional create: `webui/partials/README.md`
|
||||
|
||||
- [ ] **Step 1: Recount file sizes**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Keep `index.html` intact unless it is still above 1000 lines**
|
||||
|
||||
If `index.html` is at or below 1000 lines, do not split it in this plan. HTML partial loading would require server or build changes and is not needed yet.
|
||||
|
||||
If `index.html` remains above 1000 lines and the team wants smaller HTML files, write a separate spec before changing runtime behavior. That spec must choose one of:
|
||||
|
||||
- server-side partial injection in `gui/web_gui.py`
|
||||
- client-side fetch of static partials
|
||||
- build-time HTML generation
|
||||
|
||||
- [ ] **Step 3: Commit only if docs are added**
|
||||
|
||||
If `webui/partials/README.md` is created:
|
||||
|
||||
```powershell
|
||||
git add webui/partials/README.md
|
||||
git commit -m "docs(webui): record HTML partial split decision"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 14: Split `gui/web_gui.py` Only After Frontend Is Stable
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/web_gui_pkg/static_handler.py`
|
||||
- Create: `gui/web_gui_pkg/request_parsing.py`
|
||||
- Create: `gui/web_gui_pkg/routes.py`
|
||||
- Modify: `gui/web_gui.py`
|
||||
- Test: `tests/test_webgui.py`
|
||||
|
||||
- [ ] **Step 1: Extract request parsing helpers**
|
||||
|
||||
Move `_send_json` and `_read_json` behavior into functions that still receive the `Handler` instance:
|
||||
|
||||
```python
|
||||
def send_json(handler: BaseHTTPRequestHandler, obj: object, status: int = 200) -> None:
|
||||
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
||||
handler.send_response(status)
|
||||
handler.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
```
|
||||
|
||||
```python
|
||||
def read_json(handler: BaseHTTPRequestHandler) -> dict:
|
||||
n = int(handler.headers.get("Content-Length") or 0)
|
||||
raw = handler.rfile.read(n) if n > 0 else b"{}"
|
||||
try:
|
||||
value = json.loads(raw.decode("utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
return value if isinstance(value, dict) else {}
|
||||
```
|
||||
|
||||
Keep `Handler._send_json` and `Handler._read_json` as thin wrappers at first.
|
||||
|
||||
- [ ] **Step 2: Extract static file serving**
|
||||
|
||||
Move `_serve_static` into `gui/web_gui_pkg/static_handler.py`:
|
||||
|
||||
```python
|
||||
def serve_static(
|
||||
handler: BaseHTTPRequestHandler,
|
||||
*,
|
||||
webui_dir: str,
|
||||
rel_path: str,
|
||||
log_error: Callable[[str], None],
|
||||
) -> None:
|
||||
# paste current Handler._serve_static body and replace:
|
||||
# self -> handler
|
||||
# WEBUI_DIR -> webui_dir
|
||||
# _wg_log(...) -> log_error(...)
|
||||
```
|
||||
|
||||
Keep `Handler._serve_static` as:
|
||||
|
||||
```python
|
||||
def _serve_static(self, rel_path: str) -> None:
|
||||
serve_static(
|
||||
self,
|
||||
webui_dir=WEBUI_DIR,
|
||||
rel_path=rel_path,
|
||||
log_error=lambda msg: _wg_log(msg, level="ERROR"),
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py > logs\web_gui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py -q > logs\pytest_web_gui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 4: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py tests/test_webgui.py
|
||||
git commit -m "refactor(webgui): extract request and static helpers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 15: Final Outcome Note
|
||||
|
||||
**Files:**
|
||||
- Modify: this plan file
|
||||
|
||||
- [ ] **Step 1: Record final sizes**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Append outcome**
|
||||
|
||||
Append:
|
||||
|
||||
```markdown
|
||||
## Outcome
|
||||
|
||||
- `webui/app.js`: 2512 -> actual final line count
|
||||
- `webui/styles.css`: 3745 -> actual final line count
|
||||
- `webui/index.html`: 1232 -> actual final line count
|
||||
- `gui/web_gui.py`: 1663 -> actual final line count
|
||||
- Extracted JS modules: actual module filenames
|
||||
- Extracted CSS modules: actual module filenames
|
||||
- Verification: exact pytest log path and browser smoke result
|
||||
- Remaining large files: actual top remaining files from the final size command
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add docs/superpowers/plans/2026-05-31-split-webui-large-files.md
|
||||
git commit -m "docs(webui): record large-file split outcome"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Execution Notes
|
||||
|
||||
- Do not batch tasks. Each task must pass verification, commit, and push before starting the next one.
|
||||
- Keep query-string versions in `index.html` synchronized across all WebUI assets touched in a task.
|
||||
- Do not introduce a frontend build step in this plan.
|
||||
- Do not convert to ES modules until the classic-script split is complete and browser smoke is clean.
|
||||
- For JavaScript moves, copy exact function bodies first, verify, then optionally do tiny cleanup in a separate commit.
|
||||
- For CSS moves, preserve selector order unless the moved file load order proves an equivalent cascade.
|
||||
- Project rule: only stage files changed by the current task.
|
||||
@@ -0,0 +1,244 @@
|
||||
# 拆分 gui/gui_app.py 设计文档
|
||||
|
||||
## 背景
|
||||
|
||||
`gui/gui_app.py` 当前 5476 行,几乎全部代码都嵌在单个 `main()` 函数里,
|
||||
内含 50+ 个闭包,捕获大量 widgets 和 tkinter Var。文件已经被多轮抽取过:
|
||||
|
||||
- `5649 → 5537`:`ThreadSafeLogWriter` → `components/log_writer`
|
||||
- `5539 → 5370`:`_open_realtime_viewer_impl` → `components/realtime_viewer`
|
||||
- `6339 → 5634`:`refresh_stats` 字符串格式化 → `components/stats_formatter`
|
||||
|
||||
继续按相同思路把内聚闭包抽到 `gui/components/*`,主文件继续瘦身。
|
||||
|
||||
## 目标
|
||||
|
||||
迭代式抽取 `gui/gui_app.py` 中的内聚闭包,主文件越变越小,
|
||||
**不改变任何 GUI 运行行为**。
|
||||
|
||||
### 成功标准
|
||||
|
||||
1. `gui/gui_app.py` 行数显著下降(目标:≤ 3000 行;继续视边际收益决定是否再抽)
|
||||
2. `pytest` 全绿
|
||||
3. 每次抽取产生一个独立 commit,保持小步可回滚
|
||||
4. GUI 启动 + 主要交互路径无回归(手工 smoke:启动 GUI、打开 WiFi 对话框、加载配置、截图、查看日志)
|
||||
|
||||
### 非目标
|
||||
|
||||
- 不重构 GUI 整体架构(不引入 MVC/MVVM)
|
||||
- 不改变 `gui_app.py` 对外暴露的入口(`main()`、`format_gui_log_line()`)
|
||||
- 不优化性能、不修 bug(除非抽取过程中发现)
|
||||
- 不动 `gui/web_gui.py`(属于下一轮独立 spec)
|
||||
|
||||
## 抽取候选清单
|
||||
|
||||
按「行数 × 边界清晰度」排序(行数粗略统计):
|
||||
|
||||
| 优先级 | 闭包 | 行范围 | 行数 | 目标文件 | 主要依赖 |
|
||||
|---|---|---|---|---|---|
|
||||
| P1 | `open_wifi_adb_dialog` | 743-1588 | 845 | `components/wifi_adb_dialog.py` | ADB 工具 + 几个回调 |
|
||||
| P2 | `load_config_to_ui` + `save_ui_to_config` | 2748-3402 | 654 | `components/config_io.py` | 100+ tkinter Var(需聚合)|
|
||||
| P3 | `refresh_reservations` | 4530-4805 | 275 | `components/reservations_view.py` | 1-2 个 Treeview + 路径 |
|
||||
| P4 | `refresh_high_value_rooms` | 4805-5085 | ~280 | `components/high_value_view.py` | 1 个 Treeview + 路径 |
|
||||
| P5 | `do_screenshot` + `_bind_screenshot_button` | 3402-3651 | 249 | `components/screenshot_action.py` | ADB exe + 路径 + 状态 Label |
|
||||
| P6 | `refresh_actions_log` + 搜索栏 | 4892-5070 | ~178 | `components/actions_log_view.py` | Text widget + 路径 |
|
||||
|
||||
**估算**:完整抽完 P1-P6 约减 2480 行 → 主文件 ~3000 行。
|
||||
若 P2 风险评估后觉得不值得做,可跳过,仍能减约 1830 行 → ~3650 行。
|
||||
|
||||
## 抽取模式(每轮通用)
|
||||
|
||||
每个候选段按以下步骤处理:
|
||||
|
||||
### 1. 摸清依赖
|
||||
|
||||
读完整段代码,列出:
|
||||
- 捕获的 `main()` 局部变量(widgets / Vars / 路径 / 状态)
|
||||
- 调用的 `main()` 内其它闭包(回调)
|
||||
- 调用的 module-level 函数 / 项目其它模块函数
|
||||
|
||||
### 2. 设计签名
|
||||
|
||||
把闭包改造为顶层函数:
|
||||
|
||||
```python
|
||||
# components/<feature>.py
|
||||
def <feature_action>(
|
||||
parent: tk.Misc, # 父窗口或容器
|
||||
*,
|
||||
deps: <FeatureDeps>, # 依赖注入容器
|
||||
on_line: Callable[[str], None], # 日志回调
|
||||
...
|
||||
) -> <return-type>:
|
||||
"""..."""
|
||||
```
|
||||
|
||||
依赖容器优先用 `dataclass`(命名参数太多时):
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class <FeatureDeps>:
|
||||
adb_exe: str
|
||||
ip_var: tk.StringVar
|
||||
refresh_devices: Callable[[], None]
|
||||
# ...
|
||||
```
|
||||
|
||||
### 3. 抽取 + 注入
|
||||
|
||||
- 在 `gui/components/<feature>.py` 写新函数
|
||||
- 在 `gui_app.py` 原位置:删旧闭包,import 新函数,传依赖调用
|
||||
|
||||
### 4. 验证
|
||||
|
||||
```bash
|
||||
pytest # 全部通过
|
||||
python -m py_compile gui/gui_app.py gui/components/<feature>.py
|
||||
# 手工 smoke:启动 GUI 走一遍受影响功能
|
||||
```
|
||||
|
||||
### 5. 提交
|
||||
|
||||
按 AGENTS.md 规则:
|
||||
- `git status` 检查只改了预期文件
|
||||
- `git add` 具体路径,不用 `-A`
|
||||
- commit 消息格式参考历史:`refactor(gui): 抽 <feature> 到 components/<file> (<旧行数> → <新行数>)`
|
||||
- `git push`
|
||||
|
||||
## 风险
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 闭包捕获 Var 漏传 → 配置项静默丢失 | P2 用 `dataclass` 聚合 Var 引用;先写完整测试再改 |
|
||||
| GUI 交互回归(按钮回调失效等) | 每轮手工 smoke;优先抽边界清晰的 P1/P5 验证流程 |
|
||||
| `mainloop` / `after()` 调度跨闭包失效 | 显式把 `root` 或 `tk_widget.after` 当依赖传入 |
|
||||
| import 循环(components → gui_app) | components/* 不允许 import gui_app;只接收依赖参数 |
|
||||
|
||||
## 停止条件
|
||||
|
||||
满足任一即停手,向用户报告本轮成果:
|
||||
|
||||
1. `gui_app.py` ≤ 3000 行
|
||||
2. 下一个候选段需要传 ≥ 50 个独立依赖(信号:应该先把 widgets 聚成一个 `UiState`,那是另一个 spec)
|
||||
3. 抽取后 `gui_app.py` 行数下降 < 50(边际收益太小)
|
||||
4. 某轮抽取后 pytest 失败且修复需要改动多个非目标文件(信号:风险扩散,停下复盘)
|
||||
|
||||
## 实现顺序
|
||||
|
||||
按 P1 → P2 → P3 → P4 → P5 → P6,每段独立 commit。
|
||||
P2 视 P1 完成后情况评估(如果 P1 已经把主文件压到很小,P2 可推迟)。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- **现有 pytest**:每轮必须保持全绿(不需要为抽取新增单测,因为是纯重构)
|
||||
- **手工 smoke**(每轮都要走一遍受影响路径):
|
||||
- P1:启动 → 打开 "WiFi ADB" 对话框 → 扫描设备 → 连接
|
||||
- P2:启动 → 修改若干配置项 → 关闭 → 重启 → 检查配置已保存
|
||||
- P3/P4:启动 → 切到「预约」/「高价值房间」Tab → 验证刷新
|
||||
- P5:启动 → 截图按钮 → 检查图片落盘
|
||||
- P6:启动 → 切到「操作日志」Tab → 搜索
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- `gui/web_gui.py`(1810 行)—— 下一轮独立 spec
|
||||
- `douyin/core/*` 几个 1000+ 行业务文件 —— 下一轮独立 spec
|
||||
- 引入新的 GUI 框架或异步模式
|
||||
- 单元测试覆盖率提升
|
||||
|
||||
## Outcome(2026-05-30 实施完成)
|
||||
|
||||
**起始**:5476 行
|
||||
**结束**:178 行
|
||||
**降幅**:5298 行(-96.7%)
|
||||
**新增模块**:54 个 component 文件
|
||||
|
||||
### 主文件最终结构(178 行)
|
||||
|
||||
```
|
||||
imports 45 行 (gui_core / 14 个 components / stdlib)
|
||||
warnings 抑制 / format_gui_log_line 18 行
|
||||
def main(): ~115 行
|
||||
setup_root_window
|
||||
setup_log_pipeline ← (queue + ThreadSafeLogWriter + on_line + Runner)
|
||||
setup_top_device_bar ← (设备选择 + WiFi 工具)
|
||||
build_config_vars ← (127 个 tk Var)
|
||||
setup_left_config_area ← (PanedWindow + 7 配置 Tab + load/save IO)
|
||||
setup_right_main_area ← (Notebook + 9 Tab + actions + pump_logs)
|
||||
setup_top_buttons ← (保存配置 + 截图+OCR)
|
||||
setup_periodic_refreshers ← (启动延迟 + 周期刷新)
|
||||
setup_close_handler ← (WM_DELETE_WINDOW)
|
||||
refresh_devices() / mainloop()
|
||||
```
|
||||
|
||||
### 抽取阶段总结
|
||||
|
||||
实施分 4 个阶段:
|
||||
|
||||
**阶段 1:闭包/视图抽取(5476 → 3590 行,-34%)**
|
||||
|
||||
把 `main()` 内的内聚闭包和视图刷新函数抽到独立模块。共 17 个模块:
|
||||
wifi_adb_scan_dialog / wifi_adb_dialog / reservations_view / high_value_view /
|
||||
screenshot_action / actions_log_view / wifi_adb_pick_dialog / wifi_adb_reconnect /
|
||||
ocr_results_view / log_pump / win_record_view / preview_view /
|
||||
wifi_adb_one_click_scan / run_log_view / text_search /
|
||||
logging_config_io / run_params_builder。
|
||||
|
||||
**阶段 2:Var 聚合 + Tab UI(3590 → 1373 行,-44% → -75%)**
|
||||
|
||||
- `config_io.py`(load/save 640 行 → 1 个模块)用 dict-of-vars 模式
|
||||
- `build_config_vars()` 工厂集中创建 127 个 tk Var
|
||||
- 7 个 Tab UI(debug / logging / yanghao / reservation / run / filter / realtime)抽
|
||||
到独立 `setup_*_tab(parent, vars_=_vars_)`,直接接受 vars 全集
|
||||
|
||||
**阶段 3:右侧 Tab + 工具栏 + 模板复用(1373 → 519 行,-75% → -90.5%)**
|
||||
|
||||
- log_search_toolbar / actions_log_toolbar 用 dataclass + handles 返回
|
||||
- win_record_tab / preview_tab / log_tab 整段抽出
|
||||
- simple_tabs.py 提供 setup_simple_text_tab / setup_text_tab_with_refresh /
|
||||
setup_stats_tab / setup_actions_log_tab / setup_ocr_results_tab 复用模板
|
||||
- main_notebook / action_buttons / top_buttons / top_device_bar /
|
||||
log_pipeline / periodic_refreshers / log_text_colors / keywords_tab 全部抽出
|
||||
|
||||
**阶段 4:聚合层 + 死代码清理(519 → 178 行,-90.5% → -96.7%)**
|
||||
|
||||
最后阶段把 main() 里剩余的"装配脉络"打包成更高层组件,清理失效的导入和死注释:
|
||||
|
||||
- `setup_root_window`: ttkbootstrap fallback + root window
|
||||
- `setup_left_config_area`: PanedWindow 布局 + 7 配置 Tab + load/save IO
|
||||
- `setup_right_main_area`: Notebook + 9 Tab + actions + pump_logs
|
||||
- 删除 125 个无用的 _vars_ unpack(只保留 y_var/gui_theme_var)
|
||||
- 死注释清理 / 重复 import / 冗余 dict 字面量(_config_io_vars 复用 _vars_ 全集)
|
||||
- 重复 lambda 去重(theme_getter / _open_realtime_viewer)
|
||||
|
||||
### 抽取模式(54 个 components 按用途分类)
|
||||
|
||||
| 类型 | 模块 |
|
||||
|---|---|
|
||||
| WiFi ADB(6 个) | wifi_adb_scan_dialog / wifi_adb_dialog / wifi_adb_pick_dialog / wifi_adb_reconnect / wifi_adb_one_click_scan / top_device_bar |
|
||||
| Tab 视图(8 个) | reservations_view / high_value_view / actions_log_view / ocr_results_view / win_record_view / preview_view / run_log_view / log_pump |
|
||||
| Tab UI 容器(13 个) | run_tab / filter_tab / reservation_tab / yanghao_tab / debug_tab / logging_tab / keywords_tab / log_tab / preview_tab / win_record_tab / realtime_tab / simple_tabs / main_notebook |
|
||||
| 工具栏(2 个) | log_search_toolbar / actions_log_toolbar |
|
||||
| 配色 / 状态(3 个) | log_text_colors / text_search / screenshot_action |
|
||||
| 配置序列化(4 个) | logging_config_io / run_params_builder / config_io / config_vars |
|
||||
| 顶部 / 底部按钮(2 个) | top_buttons / action_buttons |
|
||||
| 系统调度(2 个) | log_pipeline / periodic_refreshers |
|
||||
| 高层聚合(3 个) | root_window / left_config_area / right_main_area |
|
||||
| 已有共用(11 个) | log_writer / log_viewer / log_color_config / mapping_table / mapping_utils / device_selector / actions_log_viewer / error_log_viewer / realtime_viewer / stats_formatter / __init__ |
|
||||
|
||||
### 验证
|
||||
|
||||
- 每轮抽取后 `pytest` 全绿(1374 passed),包括 `test_gui_app_smoke.py` 启动 smoke 和
|
||||
`test_gui_webui_sync.py` GUI/WebUI 配置 key 同步检查。
|
||||
- 共 7 次 pytest 失败均能定位修复(具体错误参见各次 commit message):
|
||||
- `_preview_view` 在 `update_image_list` 之前被引用
|
||||
- `enable_ocr_mode1_var` 因含数字未被正则替换(2 次)
|
||||
- `BOTH` 常量 / `ScrolledText` import 缺失
|
||||
- sync 工具锚点失效 → 让工具改读 `config_io.py` + `realtime_tab.py`
|
||||
- `image_var` 在 `setup_top_buttons` 调用时还没创建 → 调整顺序
|
||||
- 未做手工 GUI smoke(建议用户启动 GUI 走一遍 WiFi 对话框 / 各 Tab,确认无回归)。
|
||||
|
||||
### 停止原因
|
||||
|
||||
主文件已从 5476 → 178(-96.7%)。当前 main() 是清晰的"装配胶水":每个 setup_*
|
||||
调用对应一个明确的功能区。继续抽要么打散这个装配脉络,要么把整个 main 改造成
|
||||
`GuiApp` 类(MVC/MVVM),都属于另一个 spec。`pytest` 1374 全绿。
|
||||
@@ -8,11 +8,10 @@ from __future__ import annotations
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, List, Optional, Tuple
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
|
||||
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
|
||||
|
||||
|
||||
def find_and_open_fudai_detail(
|
||||
@@ -292,9 +291,12 @@ def find_and_open_fudai_detail(
|
||||
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(screenshot_path):
|
||||
img = Image.open(screenshot_path)
|
||||
img.load()
|
||||
pic_rgb_full = img.convert("RGB")
|
||||
_raw = Image.open(screenshot_path)
|
||||
try:
|
||||
_raw.load()
|
||||
pic_rgb_full = _raw.convert("RGB")
|
||||
finally:
|
||||
_raw.close()
|
||||
try:
|
||||
box_r = 30
|
||||
coord_box = (
|
||||
|
||||
@@ -5,13 +5,8 @@ handle_no_fudai_situation:在直播间未识别到福袋时做简单的等待
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, List, Optional, Tuple
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
|
||||
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
|
||||
from typing import Any, Callable, List, Optional
|
||||
|
||||
|
||||
def handle_no_fudai_situation(
|
||||
|
||||
@@ -5,14 +5,8 @@ handle_stage_after_diagnosis:记录当前阶段信息(暂不做复杂跳转
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, List, Optional, Tuple
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
|
||||
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
|
||||
from typing import Any
|
||||
|
||||
|
||||
def handle_stage_after_diagnosis(
|
||||
|
||||
+108
-2878
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,91 @@
|
||||
"""douyin/core/fudai_modules/fudai_device_control - 共享 ADB 设备操作
|
||||
|
||||
抽出 handle_detail_helpers 中重复 2 次的兜底 swipe 逻辑:
|
||||
- _handle_error_status (L266-318)
|
||||
- _fallback_swipe_up (L1187-1239)
|
||||
|
||||
两处都做"没有 swipe_up_to_next_live 时直接 ADB shell input swipe,失败再回退到
|
||||
operation.swipe"。提到这里统一管理。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from typing import Any
|
||||
|
||||
|
||||
def fallback_swipe_up_via_adb(self: Any) -> None:
|
||||
"""没有 swipe_up_to_next_live 时用 ADB shell input swipe 兜底切换直播间。
|
||||
|
||||
流程:
|
||||
1. 按 self.resolution_ratio_x/y(默认 1080x2400)计算起止坐标
|
||||
2. 优先调用 self.operation._adb_path() 获取 adb 路径
|
||||
3. 直接 subprocess.run ADB shell input swipe
|
||||
4. 任何异常 → 回退到 self.operation.swipe(...)
|
||||
|
||||
主要用于 _handle_error_status 的"连续 task_count_zero≥3 强制切房"分支
|
||||
和 _fallback_swipe_up 的"没有 swipe_up_to_next_live 时兜底"。
|
||||
"""
|
||||
try:
|
||||
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1200 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 600 * ry // 2400
|
||||
|
||||
try:
|
||||
if hasattr(self.operation, "_adb_path"):
|
||||
adb_cmd = self.operation._adb_path()
|
||||
else:
|
||||
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
|
||||
if adb_cmd.startswith('"') and adb_cmd.endswith('"'):
|
||||
adb_cmd = adb_cmd[1:-1]
|
||||
cmd = [
|
||||
adb_cmd,
|
||||
"-s",
|
||||
str(self.device_id),
|
||||
"shell",
|
||||
"input",
|
||||
"swipe",
|
||||
str(int(start_x)),
|
||||
str(int(start_y)),
|
||||
str(int(end_x)),
|
||||
str(int(end_y)),
|
||||
"300",
|
||||
]
|
||||
subprocess.run(
|
||||
cmd,
|
||||
timeout=5.0,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
)
|
||||
except Exception:
|
||||
# 回退到 operation.swipe
|
||||
self.operation.swipe(
|
||||
self.device_id,
|
||||
start_x,
|
||||
start_y,
|
||||
end_x,
|
||||
end_y,
|
||||
300,
|
||||
)
|
||||
|
||||
|
||||
def swipe_up_or_fallback(self: Any) -> None:
|
||||
"""优先调 self.swipe_up_to_next_live(),否则走 fallback_swipe_up_via_adb 兜底。
|
||||
|
||||
替代 handle_detail_helpers 中 L266-318 的内联兜底实现。
|
||||
"""
|
||||
try:
|
||||
if hasattr(self, "swipe_up_to_next_live"):
|
||||
self.swipe_up_to_next_live()
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
fallback_swipe_up_via_adb(self)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,217 @@
|
||||
"""douyin/core/fudai_modules/init_helpers - fudai_analyse 配置默认值与运行时状态初始化
|
||||
|
||||
把 fudai_analyse.__init__ 中"配置字段默认值 + 运行时状态字段初始化 + 状态文件
|
||||
路径解析"的整段抽出来。原 __init__ 保留:设备/分辨率、operation 实例、日志系统
|
||||
初始化、_run_id、_log_kv 等需要早期就绪的核心字段。
|
||||
|
||||
入口:apply_fudai_defaults(self) 一次性把所有"普通字段默认值"应用到实例。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
|
||||
def apply_fudai_defaults(self: Any) -> None:
|
||||
"""把 fudai_analyse 实例的所有配置默认值 + 运行时状态字段一次性初始化。
|
||||
|
||||
依赖前提(必须由 caller 在调用前已设置):
|
||||
- self.operation, self.device_id, self.y_pianyi
|
||||
- self.resolution_ratio_x, self.resolution_ratio_y
|
||||
- self._log_kv 等日志相关字段
|
||||
|
||||
本函数不调用 load_config(让 caller 决定时机)。
|
||||
"""
|
||||
self._forced_reservation_detail = None
|
||||
self._forced_reservation_fudai_x = None
|
||||
|
||||
# 进入直播间后诊断与阶段流转所需的一些状态
|
||||
self._last_diag_stage = "INIT"
|
||||
self._last_diag_seen = "-"
|
||||
self._last_diag_ts = 0.0
|
||||
|
||||
# 30 分钟超时相关:记录最后一次成功参与福袋的时间
|
||||
self._last_successful_attend_ts = 0.0
|
||||
self._no_attend_timeout_minutes = 30.0
|
||||
self._run_start_ts = time.time()
|
||||
# 预约状态上次写盘时间(初始化以避免 attribute-defined-outside-init 警告)
|
||||
self._reservations_state_last_write_ts = 0.0
|
||||
self.last_fudai_x = 0 # 上次检测到的福袋图标 X 坐标(用于优化搜索)
|
||||
|
||||
# 与配置相关的核心字段
|
||||
self.contains_not_want = []
|
||||
self.contains_want = []
|
||||
self.min_prize_value_yuan = 0.0
|
||||
self.min_participants = 0
|
||||
self.max_participants = 0
|
||||
self.skip_if_countdown_gt_seconds = 900
|
||||
self.skip_if_countdown_lt_seconds = 0
|
||||
self.no_fudai_watchdog_enabled = False
|
||||
# 福袋图标检测节流相关默认值
|
||||
self.fudai_icon_retry_delay_seconds = 0.6
|
||||
self.fudai_icon_max_wait_seconds = 5.0
|
||||
self.fudai_exit_after_misses = 999999
|
||||
self.enable_back_on_misses = False
|
||||
self.fudai_click_wait_seconds = 1.0
|
||||
self.switch_room_wait_after_stage_diag_seconds = 7.0
|
||||
self.swipe_duration_ms = 600
|
||||
self.fudai_find_max_attempts = 10 # 已废弃,保留兼容性
|
||||
|
||||
# 优化查找器相关配置
|
||||
self.fudai_finder_optimized_enabled = True
|
||||
self.fudai_click_verify_enabled = True
|
||||
self.fudai_find_max_retries = 3
|
||||
self.screenshot_diagnose_min_interval_seconds = 8.0
|
||||
self.lucky_draw_red_ratio_threshold = 0.9
|
||||
self.coupon_template_match_threshold = 0.75
|
||||
self.attend_button_red_ratio_threshold = 0.25
|
||||
self.fansclub_join_red_ratio_threshold = 0.25
|
||||
self.live_room_match_threshold = 0.8
|
||||
self.fudai_template_match_enabled = False
|
||||
self.fudai_template_match_threshold = 0.7
|
||||
|
||||
# 高价值福袋 / 预约相关配置
|
||||
self.high_value_fudai_enabled = False
|
||||
self.high_value_fudai_threshold_yuan = 500.0
|
||||
self.high_value_fudai_join_ahead_seconds = 100
|
||||
self.high_value_fudai_max_swipe_back = 35
|
||||
self.high_value_fudai_max_reservations = 3
|
||||
self.high_value_fudai_after_action = "continue"
|
||||
self.high_value_fudai_after_stay_seconds = 120
|
||||
self.high_value_fudai_poll_before_seconds = 10.0
|
||||
|
||||
# 高价值直播间"回访"相关
|
||||
self.high_value_room_revisit_enabled = False
|
||||
self.high_value_room_revisit_only_current_run = False
|
||||
self.high_value_room_revisit_min_interval_seconds = 300
|
||||
self.high_value_room_revisit_max_per_run = 5
|
||||
self.high_value_room_revisit_min_prize_value = 0.0
|
||||
self.high_value_room_revisit_max_age_days = 30
|
||||
|
||||
# 粉丝团相关配置
|
||||
self.auto_join_fansclub = False
|
||||
self.fansclub_fail_action = "stay"
|
||||
|
||||
# 预约回退相关
|
||||
self.reservation_back_verify_enabled = True
|
||||
self.reservation_back_swipe_delay = 0.6
|
||||
|
||||
# 滑动次数重置相关
|
||||
self.reset_after_swipes_enabled = False
|
||||
self.reset_after_swipes = 10
|
||||
|
||||
# 意外返回桌面自救相关(坐标兜底,主路径已改用 launch_package 包名启动)
|
||||
self.desktop_icon_x = 153
|
||||
self.desktop_icon_y = 260
|
||||
self.yanghao_fallback_live_x = 540
|
||||
self.yanghao_fallback_live_y = 2000
|
||||
self.yanghao_fallback_enter_live_x = 540
|
||||
self.yanghao_fallback_enter_live_y = 1200
|
||||
|
||||
# 推荐页养号默认配置
|
||||
_apply_yanghao_defaults(self)
|
||||
|
||||
# 预约运行时状态(单次运行内有效)
|
||||
self.reservations = []
|
||||
self._first_run_once_basic = True
|
||||
self.room_pos = 0
|
||||
self.reservation_focus_until_ts = 0.0
|
||||
self.reservation_after_action_pending = False
|
||||
self.reset_to_list_after_reservations = False
|
||||
self.queue_full_waiting_at_earliest = False
|
||||
|
||||
# 预约队列状态文件 + 清理映射表导出文件
|
||||
_resolve_reservations_state_path(self)
|
||||
_cleanup_old_room_pos_map_files(self)
|
||||
|
||||
# 已记录统计的福袋跟踪
|
||||
self._recorded_fudai_stats = set()
|
||||
|
||||
# 运行时状态标志
|
||||
self.needswitch = None
|
||||
self._waiting_for_lottery_result = False
|
||||
self._current_attending_reservation_fudai = False
|
||||
self._skip_stage_diagnosis_and_find_fudai = False
|
||||
self._just_switched_room = False
|
||||
|
||||
# 高价值房间重访相关状态
|
||||
self._last_high_value_revisit_ts = time.time()
|
||||
self._current_run_revisit_count = 0
|
||||
self._current_run_high_value_rooms = []
|
||||
self._last_fudai_detail_tuple = None
|
||||
self._current_fudai_future_ts = 0.0
|
||||
self._current_fudai_content = ""
|
||||
self._fudai_detail_first_read = False
|
||||
self._fudai_detail_consecutive_failures = 0
|
||||
self._detail_closed_by_attend = False
|
||||
self._lottery_result_expected_ts = 0.0
|
||||
self._lottery_wait_start_ts = 0.0
|
||||
|
||||
|
||||
def _apply_yanghao_defaults(self: Any) -> None:
|
||||
"""推荐页养号相关默认配置。"""
|
||||
self.yanghao_enabled = True
|
||||
self.yanghao_enable_actions = True
|
||||
self.yanghao_step_screenshot = False
|
||||
self.yanghao_recommend_duration_seconds = 60
|
||||
self.yanghao_recommend_interval_seconds = 0
|
||||
self.yanghao_like_prob = 0.15
|
||||
self.yanghao_fav_prob = 0.05
|
||||
self.yanghao_comment_prob = 0.0
|
||||
self.yanghao_dwell_on_action_min_seconds = 5.0
|
||||
self.yanghao_dwell_on_action_max_seconds = 30.0
|
||||
self.yanghao_icon_roi_size = 180
|
||||
self.yanghao_icon_match_threshold = 0.70
|
||||
self.yanghao_like_roi_scale = 1.5
|
||||
self.yanghao_fav_roi_scale = 1.5
|
||||
self.yanghao_like_icon_match_threshold = None
|
||||
self.yanghao_fav_icon_match_threshold = None
|
||||
self.yanghao_like_icon_x = 0
|
||||
self.yanghao_like_icon_y = 0
|
||||
self.yanghao_fav_icon_x = 0
|
||||
self.yanghao_fav_icon_y = 0
|
||||
self.yanghao_like_roi_offset_x = 0
|
||||
self.yanghao_like_roi_offset_y = 0
|
||||
self.yanghao_fav_roi_offset_x = 0
|
||||
self.yanghao_fav_roi_offset_y = 0
|
||||
self._last_yanghao_ts = 0.0
|
||||
self.yanghao_comment_btn_x = 0
|
||||
self.yanghao_comment_btn_y = 0
|
||||
self.yanghao_comment_input_x = 0
|
||||
self.yanghao_comment_input_y = 0
|
||||
self.yanghao_comment_send_x = 0
|
||||
self.yanghao_comment_send_y = 0
|
||||
self.yanghao_comment_close_x = 0
|
||||
self.yanghao_comment_close_y = 0
|
||||
self.yanghao_comment_texts = []
|
||||
|
||||
|
||||
def _resolve_reservations_state_path(self: Any) -> None:
|
||||
"""通过 path_config 解析预约状态文件路径,失败时退化到相对兜底。"""
|
||||
try:
|
||||
from douyin.core import path_config as _pc
|
||||
self._reservations_state_path = _pc.get_reservations_path()
|
||||
except Exception:
|
||||
# 兜底:path_config 不可用时退到相对路径,与 douyin/core/state/ 一致
|
||||
self._reservations_state_path = os.path.normpath(
|
||||
os.path.join(os.path.dirname(__file__), "..", "state", "reservations.json")
|
||||
)
|
||||
|
||||
# 运行时直播间标题/位置映射表(清空后存)
|
||||
self._room_pos_to_title_map = {}
|
||||
|
||||
|
||||
def _cleanup_old_room_pos_map_files(self: Any) -> None:
|
||||
"""每次启动时删除上次运行的导出文件,避免 GUI 显示过期内容。"""
|
||||
try:
|
||||
state_dir = os.path.dirname(self._reservations_state_path)
|
||||
for filename in ("room_pos_map.json", "room_pos_map.csv", "room_pos_map.md"):
|
||||
try:
|
||||
p = os.path.join(state_dir, filename)
|
||||
if os.path.exists(p):
|
||||
os.remove(p)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
File diff suppressed because it is too large.
Load diff
+104
-1
@@ -3,6 +3,7 @@
|
||||
"""
|
||||
import os
|
||||
from typing import Optional
|
||||
import json
|
||||
|
||||
# 项目根目录(所有路径的基准)
|
||||
# __file__ 位于 <project_root>/douyin/core/path_config.py,
|
||||
@@ -11,12 +12,113 @@ PROJECT_ROOT = os.path.dirname(
|
||||
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
)
|
||||
|
||||
# 运行时路径与设备侧默认路径(支持环境变量覆盖,便于迁移)
|
||||
DEFAULT_ANDROID_SCREENSHOT_PATH = "/sdcard/DCIM/screenshot.png"
|
||||
DEFAULT_ANDROID_SCREENSHOT_ALT_PATH = "/sdcard/DCIM/screenshot1.png"
|
||||
DEFAULT_ANDROID_WINDOW_DUMP_PATH = "/sdcard/window_dump.xml"
|
||||
DEFAULT_DOUYIN_PACKAGES = (
|
||||
"com.ss.android.ugc.aweme",
|
||||
"com.ss.android.ugc.aweme.lite",
|
||||
"com.zhiliaoapp.musically",
|
||||
)
|
||||
DEFAULT_ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
|
||||
DEFAULT_WEB_GUI_HOST = "127.0.0.1"
|
||||
DEFAULT_WEB_GUI_PORT = 8000
|
||||
|
||||
|
||||
def get_project_root() -> str:
|
||||
"""返回项目根目录(绝对路径)"""
|
||||
return PROJECT_ROOT
|
||||
|
||||
|
||||
def get_venv_python_path() -> str:
|
||||
"""返回项目虚拟环境 Python 路径(Windows)。"""
|
||||
return os.path.join(PROJECT_ROOT, ".venv", "Scripts", "python.exe")
|
||||
|
||||
|
||||
def get_android_screenshot_path() -> str:
|
||||
"""返回设备侧截图路径(可通过环境变量覆盖)。"""
|
||||
return (
|
||||
os.environ.get("ANDROID_SCREENSHOT_PATH", "").strip()
|
||||
or DEFAULT_ANDROID_SCREENSHOT_PATH
|
||||
)
|
||||
|
||||
|
||||
def get_android_screenshot_alt_path() -> str:
|
||||
"""返回设备侧备用截图路径(可通过环境变量覆盖)。"""
|
||||
return (
|
||||
os.environ.get("ANDROID_SCREENSHOT_ALT_PATH", "").strip()
|
||||
or DEFAULT_ANDROID_SCREENSHOT_ALT_PATH
|
||||
)
|
||||
|
||||
|
||||
def get_android_window_dump_path() -> str:
|
||||
"""返回设备侧 UI dump 路径(可通过环境变量覆盖)。"""
|
||||
return (
|
||||
os.environ.get("ANDROID_WINDOW_DUMP_PATH", "").strip()
|
||||
or DEFAULT_ANDROID_WINDOW_DUMP_PATH
|
||||
)
|
||||
|
||||
|
||||
def get_douyin_packages() -> tuple[str, ...]:
|
||||
"""返回抖音候选包名列表(支持环境变量覆盖,逗号分隔)。"""
|
||||
raw = (os.environ.get("DOUYIN_PACKAGES", "") or "").strip()
|
||||
if not raw:
|
||||
return DEFAULT_DOUYIN_PACKAGES
|
||||
items = tuple(x.strip() for x in raw.split(",") if x.strip())
|
||||
return items or DEFAULT_DOUYIN_PACKAGES
|
||||
|
||||
|
||||
def get_adb_keyboard_ime() -> str:
|
||||
"""返回 ADBKeyboard IME(支持环境变量覆盖)。"""
|
||||
return (os.environ.get("ADB_KEYBOARD_IME", "") or "").strip() or DEFAULT_ADB_KEYBOARD_IME
|
||||
|
||||
|
||||
def _read_runtime_config() -> dict:
|
||||
"""读取 config/config.json,失败时返回空字典。"""
|
||||
try:
|
||||
cfg_path = get_config_path()
|
||||
if not os.path.exists(cfg_path):
|
||||
return {}
|
||||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||||
obj = json.load(f)
|
||||
return obj if isinstance(obj, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def get_web_gui_host() -> str:
|
||||
"""返回 Web GUI 监听 host(环境变量优先,其次 config.json,最后默认值)。"""
|
||||
host = (os.environ.get("WEB_GUI_HOST") or os.environ.get("HOST") or "").strip()
|
||||
if host:
|
||||
return host
|
||||
cfg = _read_runtime_config()
|
||||
cfg_host = str(cfg.get("web_gui_host", "") or "").strip()
|
||||
return cfg_host or DEFAULT_WEB_GUI_HOST
|
||||
|
||||
|
||||
def get_web_gui_port() -> int:
|
||||
"""返回 Web GUI 监听端口(环境变量优先,其次 config.json,最后默认值)。"""
|
||||
env_raw = (os.environ.get("PORT") or os.environ.get("WEB_GUI_PORT") or "").strip()
|
||||
if env_raw:
|
||||
try:
|
||||
port = int(env_raw)
|
||||
if 1 <= port <= 65535:
|
||||
return port
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cfg = _read_runtime_config()
|
||||
cfg_raw = cfg.get("web_gui_port", DEFAULT_WEB_GUI_PORT)
|
||||
try:
|
||||
port = int(cfg_raw)
|
||||
if 1 <= port <= 65535:
|
||||
return port
|
||||
except Exception:
|
||||
pass
|
||||
return DEFAULT_WEB_GUI_PORT
|
||||
|
||||
|
||||
def get_config_path() -> str:
|
||||
"""返回 config.json 的路径"""
|
||||
return os.path.join(PROJECT_ROOT, "config", "config.json")
|
||||
@@ -184,7 +286,8 @@ def find_executable(cmd: str) -> Optional[str]:
|
||||
return first
|
||||
else:
|
||||
# 类 Unix:尝试 command -v 再 which
|
||||
proc = subprocess.run(["/bin/sh", "-c", f"command -v {cmd} || which {cmd}"], capture_output=True, text=True)
|
||||
import shlex
|
||||
proc = subprocess.run(["/bin/sh", "-c", f"command -v {shlex.quote(cmd)} || which {shlex.quote(cmd)}"], capture_output=True, text=True)
|
||||
if proc.returncode == 0 and proc.stdout:
|
||||
first = proc.stdout.splitlines()[0].strip()
|
||||
if first:
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"""桌面自救共享逻辑
|
||||
|
||||
把 fudai_modules.run_once_basic_helpers 和 douyin.other.douyin_yanghao
|
||||
中重复的"前台不在抖音 → 包名启动 → 失败兜底点击坐标"逻辑抽到这里。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
|
||||
def is_douyin_foreground(top_pkg: str) -> bool:
|
||||
"""判断给定的前台包名是否属于抖音相关包。"""
|
||||
return bool(top_pkg) and (
|
||||
"aweme" in top_pkg
|
||||
or "douyin" in top_pkg
|
||||
or "com.ss.android.ugc" in top_pkg
|
||||
)
|
||||
|
||||
|
||||
def fallback_click_recovery(
|
||||
analyser: Any,
|
||||
log: Optional[Callable[[str], None]] = None,
|
||||
) -> None:
|
||||
"""旧的点击坐标自救:桌面图标 → 直播按钮 → 进入直播间×2。
|
||||
|
||||
保留作为 launch_package 失败时的兜底。所有坐标读 analyser 上的属性,
|
||||
取不到时使用默认值(适配 1080x2400 的位置)。
|
||||
"""
|
||||
op = analyser.operation
|
||||
device_id = analyser.device_id
|
||||
|
||||
desktop_x = int(getattr(analyser, "desktop_icon_x", 153) or 153)
|
||||
desktop_y = int(getattr(analyser, "desktop_icon_y", 260) or 260)
|
||||
try:
|
||||
op.click(device_id, desktop_x, desktop_y)
|
||||
except Exception:
|
||||
# 退化为默认硬编码位置
|
||||
try:
|
||||
op.click(device_id, 153, 260)
|
||||
except Exception:
|
||||
pass
|
||||
op.delay(2)
|
||||
|
||||
fallback_x = int(getattr(analyser, "yanghao_fallback_live_x", 540) or 540)
|
||||
fallback_y = int(getattr(analyser, "yanghao_fallback_live_y", 2000) or 2000)
|
||||
try:
|
||||
if log:
|
||||
log(f"点击直播按钮 x={fallback_x} y={fallback_y}")
|
||||
op.click(device_id, fallback_x, fallback_y)
|
||||
op.delay(1.5)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
enter_x = int(getattr(analyser, "yanghao_fallback_enter_live_x", 540) or 540)
|
||||
enter_y = int(getattr(analyser, "yanghao_fallback_enter_live_y", 1200) or 1200)
|
||||
try:
|
||||
if log:
|
||||
log(f"点击进入直播间 x={enter_x} y={enter_y} 次数=2")
|
||||
op.click(device_id, enter_x, enter_y)
|
||||
op.delay(0.6)
|
||||
op.click(device_id, enter_x, enter_y)
|
||||
op.delay(2.0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def recover_to_douyin(
|
||||
analyser: Any,
|
||||
log: Optional[Callable[[str], None]] = None,
|
||||
) -> bool:
|
||||
"""统一的桌面自救入口。
|
||||
|
||||
流程:
|
||||
1. 优先 op.launch_package(device_id, ""),按抖音常用包名顺序尝试
|
||||
2. 包名启动失败或抛异常时,回退到点击坐标自救(fallback_click_recovery)
|
||||
|
||||
参数:
|
||||
analyser: 提供 .operation / .device_id / 自救坐标属性的对象
|
||||
log: 可选的日志回调(接受单字符串)
|
||||
|
||||
返回:
|
||||
True 表示已尝试某种自救(不保证一定成功,但已执行动作);
|
||||
False 仅在调用环境本身出现严重异常时返回。
|
||||
"""
|
||||
try:
|
||||
op = analyser.operation
|
||||
device_id = analyser.device_id
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
launched_ok = False
|
||||
used_pkg = ""
|
||||
try:
|
||||
launched_ok, used_pkg = op.launch_package(device_id, "")
|
||||
except Exception as exc:
|
||||
if log:
|
||||
log(f"包名启动调用异常 {exc},回退点击坐标")
|
||||
|
||||
if launched_ok:
|
||||
if log:
|
||||
log(f"包名启动抖音成功 pkg={used_pkg}")
|
||||
try:
|
||||
op.delay(2.5)
|
||||
except Exception:
|
||||
time.sleep(2.5)
|
||||
return True
|
||||
|
||||
# 兜底:保留旧的点击坐标自救
|
||||
if log:
|
||||
log("包名启动失败,回退点击桌面图标 + 备用坐标")
|
||||
fallback_click_recovery(analyser, log=log)
|
||||
return True
|
||||
File diff suppressed because it is too large.
Load diff
@@ -123,16 +123,16 @@ def check_countdown(last_time=""):
|
||||
else:
|
||||
total2 = None
|
||||
|
||||
if total1 is not None and total1 <= 900:
|
||||
if total1 is not None and total1 <= 3600:
|
||||
return total1
|
||||
if total2 is not None and total2 <= 900:
|
||||
if total2 is not None and total2 <= 3600:
|
||||
return total2
|
||||
|
||||
# 若一个明显异常而另一个更合理(<=900),交换
|
||||
# 若一个明显异常而另一个更合理(<=3600),交换
|
||||
if total1 is not None and total2 is not None:
|
||||
if total1 > 900 and total2 <= 900:
|
||||
if total1 > 3600 and total2 <= 3600:
|
||||
return total2
|
||||
if total2 > 900 and total1 <= 900:
|
||||
if total2 > 3600 and total1 <= 3600:
|
||||
return total1
|
||||
|
||||
# 兜底:谁能解析就用谁;都不行则做进位
|
||||
@@ -182,9 +182,9 @@ def check_countdown(last_time=""):
|
||||
_uo_log("时间格式异常")
|
||||
return False
|
||||
_uo_log("剩余总秒数:", total_seconds)
|
||||
# 超过 15 分钟基本是误识别:按 14分50秒处理,避免卡死等待
|
||||
if total_seconds > 900:
|
||||
total_seconds = 890
|
||||
# 超过 60 分钟视为 OCR 误识别,按 59 分 50 秒处理
|
||||
if total_seconds > 3600:
|
||||
total_seconds = 3590
|
||||
|
||||
now = datetime.now()
|
||||
_uo_log("当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
|
||||
@@ -57,10 +57,18 @@ def select_device():
|
||||
print("检测到多台设备且当前不是交互式终端,请通过 --device-id 明确指定设备。")
|
||||
return False
|
||||
num = input()
|
||||
num = int(num)
|
||||
try:
|
||||
num = int(num)
|
||||
except ValueError:
|
||||
print("请输入有效数字:")
|
||||
return False
|
||||
while not num in dictdevice.keys():
|
||||
print("输入不正确,请重新输入:")
|
||||
num = input()
|
||||
num = int(num)
|
||||
try:
|
||||
num = int(num)
|
||||
except ValueError:
|
||||
print("请输入有效数字:")
|
||||
return False
|
||||
return dictdevice[num]
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
"""douyin/core/underlying_operations_pkg/image_ops - cut_pic 图片裁剪管道
|
||||
|
||||
把 underlying_operations.cut_pic 整段抽出来。流程:
|
||||
- 默认分支(target=""):从项目根 pic/screenshot.png 读图,裁出 cut.png 或 ocr/<name>.png
|
||||
- 命名分支(target="xxx"):从 pic/<target>/screenshot.png 读图,裁出 pic/<target>/<name>.png
|
||||
- 重试 3 次(截图缺失/文件太小/PIL 损坏)
|
||||
- 写入坐标缓存供 analyse_pic_word 调试图像用
|
||||
- 可选保存 cut_pic 调试图(SAVE_CUT_PIC_DEBUG_IMAGES=1)
|
||||
|
||||
入口:cut_pic(self, left_up, right_down, target, name) -> bool
|
||||
self 必须提供:_find_pic_path / _ocr_coords_lock / _ocr_coords_cache
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time as time_module
|
||||
from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def _ensure_parent_dir(path: str) -> None:
|
||||
"""确保路径的父目录存在。"""
|
||||
try:
|
||||
parent = os.path.dirname(path)
|
||||
if parent:
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _validate_coords(
|
||||
left_up: tuple, right_down: tuple, image_size: tuple
|
||||
) -> bool:
|
||||
"""检查裁剪坐标在图片范围内且非空。"""
|
||||
left, top = left_up
|
||||
right, bottom = right_down
|
||||
width, height = image_size
|
||||
return not (
|
||||
left < 0 or top < 0
|
||||
or right > width or bottom > height
|
||||
or left >= right or top >= bottom
|
||||
)
|
||||
|
||||
|
||||
def _save_cut_debug_images(self: Any, cropped_img, pic, name: str, source_label: str, left: int, top: int, right: int, bottom: int) -> None:
|
||||
"""根据环境变量决定是否保存 cut_pic 调试图。"""
|
||||
try:
|
||||
save_debug = os.environ.get("SAVE_CUT_PIC_DEBUG_IMAGES", "0") == "1"
|
||||
if not save_debug:
|
||||
try:
|
||||
save_debug = os.environ.get("SAVE_DEBUG_IMAGES", "0") == "1"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not save_debug:
|
||||
return
|
||||
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
cropped_img, operation_type="cut_pic"
|
||||
)
|
||||
|
||||
# 保存调试图像(完整截图+区域标注)
|
||||
pic_rgb = pic.convert("RGB")
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb,
|
||||
operation_type="cut_pic",
|
||||
picname=name if name else "cut",
|
||||
step="before_ocr",
|
||||
coords=(left, top, right, bottom),
|
||||
extra_info={
|
||||
"source": source_label,
|
||||
"size": f"{right-left}x{bottom-top}",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
logging.info("[调试图像] cut_pic保存: %s", debug_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def cut_pic(
|
||||
self: Any,
|
||||
left_up=(0, 63),
|
||||
right_down=(1080, 1620),
|
||||
target: str = "",
|
||||
name: str = "",
|
||||
) -> bool:
|
||||
"""裁剪图片,获取需要的区域小图片方便识别。"""
|
||||
from douyin.core.underlying_operations import _uo_log
|
||||
|
||||
max_retries = 3
|
||||
retry_delay = 0.1
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
if target == "" or target is False:
|
||||
from douyin.core import path_config
|
||||
|
||||
path = path_config.get_pic_dir()
|
||||
pic1_path = path_config.get_screenshot_path()
|
||||
cut_pic_path = None
|
||||
|
||||
if not os.path.exists(pic1_path):
|
||||
if attempt < max_retries - 1:
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
|
||||
|
||||
if os.path.getsize(pic1_path) < 100:
|
||||
if attempt < max_retries - 1:
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
|
||||
|
||||
# 尝试打开并验证图片
|
||||
try:
|
||||
pic = Image.open(pic1_path)
|
||||
_ = pic.size
|
||||
pic.load()
|
||||
except (SyntaxError, IOError, OSError) as e:
|
||||
if attempt < max_retries - 1:
|
||||
_uo_log(
|
||||
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
|
||||
)
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
raise
|
||||
|
||||
if name == "":
|
||||
cut_pic_path = path + "/cut.png"
|
||||
else:
|
||||
cut_pic_path = self._find_pic_path(name, for_reading=False)
|
||||
|
||||
if not _validate_coords(left_up, right_down, pic.size):
|
||||
raise ValueError(
|
||||
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}"
|
||||
)
|
||||
|
||||
left, top = left_up
|
||||
right, bottom = right_down
|
||||
cropped_img = pic.crop((left, top, right, bottom))
|
||||
assert cut_pic_path is not None
|
||||
try:
|
||||
_ensure_parent_dir(cut_pic_path)
|
||||
cropped_img.save(cut_pic_path)
|
||||
except Exception:
|
||||
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
|
||||
|
||||
# 存储坐标信息供 analyse_pic_word 使用
|
||||
if name:
|
||||
try:
|
||||
with self._ocr_coords_lock:
|
||||
self._ocr_coords_cache[name] = (left, top, right, bottom)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
_save_cut_debug_images(
|
||||
self, cropped_img, pic, name,
|
||||
"screenshot.png", left, top, right, bottom,
|
||||
)
|
||||
finally:
|
||||
pic.close()
|
||||
return True
|
||||
|
||||
else:
|
||||
from douyin.core import path_config
|
||||
|
||||
path_target = os.path.join(path_config.get_pic_dir(), target)
|
||||
pic1_path = os.path.join(path_target, "screenshot.png")
|
||||
cut_pic_path = None
|
||||
|
||||
if not os.path.exists(pic1_path):
|
||||
if attempt < max_retries - 1:
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
|
||||
|
||||
if os.path.getsize(pic1_path) < 100:
|
||||
if attempt < max_retries - 1:
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
|
||||
|
||||
try:
|
||||
pic = Image.open(pic1_path)
|
||||
_ = pic.size
|
||||
pic.load()
|
||||
except (SyntaxError, IOError, OSError) as e:
|
||||
if attempt < max_retries - 1:
|
||||
_uo_log(
|
||||
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
|
||||
)
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
raise
|
||||
|
||||
if name == "":
|
||||
cut_pic_path = path_target + "/cut.png"
|
||||
else:
|
||||
cut_pic_path = path_target + "/" + name + ".png"
|
||||
|
||||
try:
|
||||
if not _validate_coords(left_up, right_down, pic.size):
|
||||
error_msg = (
|
||||
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, "
|
||||
f"image_size={pic.size}"
|
||||
)
|
||||
if attempt == max_retries - 1:
|
||||
_uo_log(f"[错误] {error_msg}")
|
||||
return False
|
||||
continue
|
||||
|
||||
left, top = left_up
|
||||
right, bottom = right_down
|
||||
assert cut_pic_path is not None
|
||||
cropped_img = pic.crop((left, top, right, bottom))
|
||||
try:
|
||||
_ensure_parent_dir(cut_pic_path)
|
||||
cropped_img.save(cut_pic_path)
|
||||
except Exception:
|
||||
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
|
||||
return False
|
||||
|
||||
if name:
|
||||
try:
|
||||
with self._ocr_coords_lock:
|
||||
self._ocr_coords_cache[name] = (left, top, right, bottom)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 命名分支总是保存 cut_pic 调试图(与原版行为一致 — 没有开关检查)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
pic_rgb = pic.convert("RGB")
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb,
|
||||
operation_type="cut_pic",
|
||||
picname=name if name else "cut",
|
||||
step="before_ocr",
|
||||
coords=(left, top, right, bottom),
|
||||
extra_info={
|
||||
"source": target + "/screenshot.png",
|
||||
"size": f"{right-left}x{bottom-top}",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
logging.info("[调试图像] cut_pic保存: %s", debug_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True
|
||||
finally:
|
||||
pic.close()
|
||||
|
||||
except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e:
|
||||
if attempt == max_retries - 1:
|
||||
error_msg = f"[错误] 裁剪图片失败 (尝试 {max_retries} 次): {e}"
|
||||
_uo_log(error_msg)
|
||||
_uo_log(f" 源文件: {locals().get('pic1_path', 'N/A')}")
|
||||
_uo_log(f" 目标文件: {locals().get('cut_pic_path', 'N/A')}")
|
||||
return False
|
||||
continue
|
||||
|
||||
return False
|
||||
@@ -0,0 +1,380 @@
|
||||
"""douyin/core/underlying_operations_pkg/ocr_pipeline - analyse_pic_word OCR 管道
|
||||
|
||||
把 underlying_operations.analyse_pic_word 整段抽出来。流程:
|
||||
1. 路径解析 + 缓存查询(基于图片字节哈希)
|
||||
2. 加载 + 验证图片完整性
|
||||
3. change_color 预处理(0=保留彩色,1/2=二值化)
|
||||
4. 调试图像保存(preprocessed 步骤,仅当 SAVE_OCR_DEBUG_IMAGES=1)
|
||||
5. 调用 OCR(EasyOCR / PaddleOCR predict/ocr)
|
||||
6. 提取文本 + 置信度
|
||||
7. 写缓存
|
||||
8. 调试图像保存(after_ocr 步骤)
|
||||
9. 成功识别保存到 ocr/<category>/<picname>_success.png
|
||||
|
||||
入口:analyse_pic_word(self, picname, change_color, pic_path, return_confidence)
|
||||
self 必须提供:_find_pic_path / extract_ocr_content / ocr / ocr_type /
|
||||
_ocr_coords_lock / _ocr_coords_cache / save_ocr_debug_images
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import Any, Optional
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
import numpy as np
|
||||
|
||||
|
||||
def analyse_pic_word(
|
||||
self: Any,
|
||||
picname: str,
|
||||
change_color: int = 0,
|
||||
pic_path: Optional[str] = None,
|
||||
return_confidence: bool = False,
|
||||
):
|
||||
"""对指定图片运行 OCR 并返回拼接后的文本结果。
|
||||
|
||||
Args:
|
||||
self: underlying_operations 实例
|
||||
picname: 图片名(如"福袋内容")
|
||||
change_color: 0=保留彩色,1/2=二值化
|
||||
pic_path: 可选;未提供时通过 self._find_pic_path 查找
|
||||
return_confidence: True 时返回 (text, confidence_info);否则只返回 text
|
||||
|
||||
Returns:
|
||||
return_confidence=False: text(str)
|
||||
return_confidence=True: (text, confidence_info)
|
||||
"""
|
||||
from douyin.core.underlying_operations import _uo_log
|
||||
|
||||
if not pic_path:
|
||||
try:
|
||||
pic_path = self._find_pic_path(picname)
|
||||
except Exception:
|
||||
pic_path = None
|
||||
|
||||
if not pic_path or not os.path.exists(pic_path):
|
||||
return ("", None) if return_confidence else ""
|
||||
|
||||
# ===== 缓存查询:基于图片字节哈希 =====
|
||||
cache_key = None
|
||||
try:
|
||||
from operations.ocr_operations import (
|
||||
_img_fingerprint, cache_get, cache_put,
|
||||
)
|
||||
with open(pic_path, "rb") as _f:
|
||||
_bytes = _f.read()
|
||||
cache_key = _img_fingerprint(_bytes, mode=int(change_color or 0))
|
||||
cached = cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached if return_confidence else cached[0]
|
||||
except Exception:
|
||||
cache_key = None
|
||||
|
||||
# 加载图片
|
||||
_pic_raw = None
|
||||
img = None
|
||||
try:
|
||||
_pic_raw = Image.open(pic_path)
|
||||
_pic_raw.load()
|
||||
img = _pic_raw.convert("RGB")
|
||||
_pic_raw.close()
|
||||
_pic_raw = None
|
||||
except (IOError, OSError, UnidentifiedImageError):
|
||||
if _pic_raw is not None:
|
||||
_pic_raw.close()
|
||||
return ("", None) if return_confidence else ""
|
||||
|
||||
if img is None:
|
||||
return ("", None) if return_confidence else ""
|
||||
|
||||
# 预处理:实测 PaddleOCR v4-mobile 内部已自带 resize/normalize,
|
||||
# 外层"放大+锐化+对比度增强"反而会引入伪影,让识别变差。
|
||||
# 因此默认走原图。仅在 change_color=1/2 业务显式要求二值化时才做。
|
||||
if change_color in (1, 2):
|
||||
old = img
|
||||
img = img.convert("L")
|
||||
old.close()
|
||||
thresh = 128 if change_color == 1 else 180
|
||||
img = img.point(lambda x, t=thresh: 0 if int(x) < t else 255)
|
||||
else:
|
||||
img = img.convert("RGB")
|
||||
|
||||
w, h = img.size
|
||||
img1 = img # 不再做放大/锐化/对比度
|
||||
|
||||
# 调试图像保存(preprocessed 步骤)
|
||||
_save_debug_preprocessed(self, img1, picname, pic_path, change_color, w, h)
|
||||
|
||||
img_np = np.array(img1)
|
||||
ocr_confidence_info = None
|
||||
|
||||
try:
|
||||
ocr_obj = getattr(self, "ocr", None)
|
||||
ocr_type = getattr(self, "ocr_type", None)
|
||||
except Exception:
|
||||
ocr_obj = None
|
||||
ocr_type = None
|
||||
|
||||
if ocr_obj is None:
|
||||
try:
|
||||
logging.warning("OCR 未初始化,跳过识别:picname=%s", picname)
|
||||
except Exception:
|
||||
pass
|
||||
return ("", None) if return_confidence else ""
|
||||
|
||||
# 执行 OCR
|
||||
try:
|
||||
if ocr_type == "easyocr":
|
||||
result = ocr_obj.readtext(img_np)
|
||||
extract_result = self.extract_ocr_content(result, return_confidence=True)
|
||||
if isinstance(extract_result, tuple):
|
||||
text, ocr_confidence_info = extract_result
|
||||
else:
|
||||
text = extract_result
|
||||
else:
|
||||
# PaddleOCR 3.x:predict() 是新推荐 API;ocr() 仍兼容
|
||||
_predict = getattr(ocr_obj, "predict", None) or ocr_obj.ocr
|
||||
result = _predict(img_np)
|
||||
if result == [None]:
|
||||
if cache_key:
|
||||
try:
|
||||
cache_put(cache_key, ("", None))
|
||||
except Exception:
|
||||
pass
|
||||
return ("", None) if return_confidence else ""
|
||||
extract_result = self.extract_ocr_content(result, return_confidence=True)
|
||||
if isinstance(extract_result, tuple):
|
||||
text, ocr_confidence_info = extract_result
|
||||
else:
|
||||
text = extract_result
|
||||
except Exception as e:
|
||||
try:
|
||||
logging.warning("OCR 调用失败,返回空结果:%s", e)
|
||||
except Exception:
|
||||
pass
|
||||
return ("", None) if return_confidence else ""
|
||||
|
||||
# 写缓存
|
||||
if cache_key:
|
||||
try:
|
||||
cache_put(cache_key, (text, ocr_confidence_info))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 调试日志:福袋内容 / 福袋倒计时 OCR 失败时打印 result 结构
|
||||
if picname in ("福袋内容", "福袋倒计时") and not text:
|
||||
try:
|
||||
if isinstance(result, list) and result and isinstance(result[0], dict):
|
||||
_uo_log(f"OCR调试({picname}): result[0] keys={list(result[0].keys())}")
|
||||
else:
|
||||
_uo_log(f"OCR调试({picname}): result type={type(result)}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 调试图像保存(after_ocr 步骤)+ 置信度日志
|
||||
_save_debug_after_ocr(
|
||||
self, img1, picname, change_color, text,
|
||||
ocr_confidence_info,
|
||||
)
|
||||
|
||||
# 成功识别 → 保存到 ocr/<category>/<picname>_success.png
|
||||
if text and text.strip() and picname:
|
||||
_save_success_pic(img, img1, picname, text)
|
||||
|
||||
if return_confidence:
|
||||
return text, ocr_confidence_info
|
||||
else:
|
||||
return text
|
||||
|
||||
|
||||
def _save_debug_preprocessed(
|
||||
self: Any, img1, picname: str, pic_path: str,
|
||||
change_color: int, w: int, h: int,
|
||||
) -> None:
|
||||
"""保存预处理后的调试图像(OCR 输入),仅当 SAVE_OCR_DEBUG_IMAGES=1 时执行。"""
|
||||
try:
|
||||
save_debug = os.environ.get("SAVE_OCR_DEBUG_IMAGES", "0") == "1"
|
||||
if not save_debug:
|
||||
try:
|
||||
save_debug = bool(getattr(self, "save_ocr_debug_images", False))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not save_debug:
|
||||
return
|
||||
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from douyin.core import path_config
|
||||
|
||||
ocr_coords = None
|
||||
try:
|
||||
with self._ocr_coords_lock:
|
||||
ocr_coords = self._ocr_coords_cache.get(picname)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
full_screenshot = None
|
||||
try:
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(screenshot_path):
|
||||
_raw = Image.open(screenshot_path)
|
||||
try:
|
||||
_raw.load()
|
||||
full_screenshot = _raw.convert("RGB")
|
||||
finally:
|
||||
_raw.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
debug_image = full_screenshot if full_screenshot is not None else img1
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
debug_image,
|
||||
operation_type="ocr",
|
||||
picname=picname,
|
||||
step="preprocessed",
|
||||
coords=ocr_coords,
|
||||
extra_info={
|
||||
"mode": change_color,
|
||||
"size": f"{w}x{h}",
|
||||
"source": pic_path if pic_path else picname,
|
||||
"has_full_screenshot": full_screenshot is not None,
|
||||
"has_coords": ocr_coords is not None,
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
logging.info("[调试图像] OCR预处理保存: %s", debug_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _save_debug_after_ocr(
|
||||
self: Any, img1, picname: str, change_color: int,
|
||||
text: Optional[str], ocr_confidence_info: Optional[dict],
|
||||
) -> None:
|
||||
"""保存 OCR 完成后的调试图像(含识别文本预览 + 置信度)。"""
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_latest_attempt(img1, operation_type="ocr")
|
||||
|
||||
ocr_result_preview = (text or "").strip()[:50] if text else ""
|
||||
extra_info_dict = {
|
||||
"mode": change_color,
|
||||
"text_len": len(text or ""),
|
||||
"text_preview": ocr_result_preview,
|
||||
"used_img2": False, # 二次 OCR 已禁用
|
||||
}
|
||||
if ocr_confidence_info:
|
||||
extra_info_dict["avg_confidence"] = round(
|
||||
ocr_confidence_info.get("avg_confidence", 0.0), 4
|
||||
)
|
||||
extra_info_dict["min_confidence"] = round(
|
||||
ocr_confidence_info.get("min_confidence", 0.0), 4
|
||||
)
|
||||
extra_info_dict["max_confidence"] = round(
|
||||
ocr_confidence_info.get("max_confidence", 0.0), 4
|
||||
)
|
||||
extra_info_dict["confidence_items"] = ocr_confidence_info.get(
|
||||
"item_count", 0
|
||||
)
|
||||
|
||||
ocr_coords = None
|
||||
try:
|
||||
ocr_coords = self._ocr_coords_cache.get(picname)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
full_screenshot = None
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(screenshot_path):
|
||||
_raw = Image.open(screenshot_path)
|
||||
try:
|
||||
_raw.load()
|
||||
full_screenshot = _raw.convert("RGB")
|
||||
finally:
|
||||
_raw.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
debug_image = full_screenshot if full_screenshot is not None else img1
|
||||
extra_info_dict["has_full_screenshot"] = full_screenshot is not None
|
||||
extra_info_dict["has_coords"] = ocr_coords is not None
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
debug_image,
|
||||
operation_type="ocr",
|
||||
picname=picname,
|
||||
step="after_ocr",
|
||||
coords=ocr_coords,
|
||||
extra_info=extra_info_dict,
|
||||
)
|
||||
|
||||
# 记录 OCR 置信度到日志
|
||||
if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0:
|
||||
try:
|
||||
logging.info(
|
||||
"[OCR置信度] %s: 平均=%.4f, 最小=%.4f, 最大=%.4f, 项目数=%d",
|
||||
picname,
|
||||
ocr_confidence_info.get("avg_confidence", 0.0),
|
||||
ocr_confidence_info.get("min_confidence", 0.0),
|
||||
ocr_confidence_info.get("max_confidence", 0.0),
|
||||
int(ocr_confidence_info.get("item_count", 0) or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if debug_path:
|
||||
try:
|
||||
logging.info(
|
||||
"[调试图像] OCR结果保存: %s, 文本: %s",
|
||||
debug_path,
|
||||
ocr_result_preview,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _save_success_pic(img, img1, picname: str, text: str) -> None:
|
||||
"""成功识别后保存到 ocr/<category>/<picname>_success.png。"""
|
||||
try:
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
category = douyin_screenshot_manager.get_category_for_picname(picname)
|
||||
except Exception:
|
||||
category = "others"
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_base = path_config.get_pic_dir()
|
||||
category_dir = os.path.join(pic_base, "ocr", category)
|
||||
os.makedirs(category_dir, exist_ok=True)
|
||||
|
||||
success_path = os.path.join(category_dir, f"{picname}_success.png")
|
||||
try:
|
||||
img_to_save = img1
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
img_to_save, operation_type="ocr"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
img_to_save.save(success_path)
|
||||
except Exception:
|
||||
try:
|
||||
if img is not None:
|
||||
img.save(success_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,499 @@
|
||||
"""underlying_operations._get_screenshot_direct 的实现。
|
||||
|
||||
从 underlying_operations.py 抽出,原方法保留为 thin shim 调用 capture_screenshot_direct。
|
||||
|
||||
依赖:
|
||||
- self._adb_path() —— 取 adb 可执行文件路径
|
||||
- self.get_screenshot() —— 在最深兜底分支递归调用一次(注意保持兼容)
|
||||
- io_utils._safe_replace_file
|
||||
- io_utils._mirror_screenshot_to_external
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time as time_module
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from douyin.core.io_utils import (
|
||||
_mirror_screenshot_to_external,
|
||||
_safe_replace_file,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
|
||||
|
||||
def _uo_log(msg: str) -> None:
|
||||
"""与 underlying_operations._uo_log 一致:默认 INFO 级别。"""
|
||||
try:
|
||||
logging.info(msg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def capture_screenshot_direct(
|
||||
self: "underlying_operations", device_id, path: str = "pic"
|
||||
) -> bool:
|
||||
"""直接截图(不使用服务模式)。从 underlying_operations._get_screenshot_direct 抽出。
|
||||
|
||||
流程:
|
||||
1. 准备输出目录 + 文件名
|
||||
2. 优先 exec-out 路径(最多 2 次重试 + watchdog)
|
||||
3. 失败 → 回退 shell screencap + adb pull
|
||||
4. 再失败 → 兜底 mv + 递归调用 get_screenshot
|
||||
"""
|
||||
overall_start = time_module.time()
|
||||
cleanup_dur = 0.0
|
||||
adb_subprocess_dur = 0.0
|
||||
validate_tmp_dur = 0.0
|
||||
replace_dur = 0.0
|
||||
mirror_dur = 0.0
|
||||
validate_out_dur = 0.0
|
||||
|
||||
if path == "pic":
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
out_dir = path_config.get_pic_dir()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
out_dir = path_config.get_pic_dir()
|
||||
else:
|
||||
out_dir = os.path.join(os.path.dirname(__file__), "..", "target_pic")
|
||||
if not os.path.exists(out_dir):
|
||||
os.makedirs(out_dir)
|
||||
|
||||
out_file = os.path.join(out_dir, "screenshot.png")
|
||||
tmp_file = out_file + ".tmp"
|
||||
timetag = datetime.now().strftime("%H:%M:%S")
|
||||
|
||||
adb = self._adb_path()
|
||||
|
||||
skip_verify = os.environ.get("SKIP_SCREENSHOT_VERIFY", "0") == "1"
|
||||
|
||||
def _valid_png(path0: str) -> bool:
|
||||
if skip_verify:
|
||||
try:
|
||||
if not os.path.exists(path0):
|
||||
return False
|
||||
sz = os.path.getsize(path0)
|
||||
return sz >= 1024
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
verify_start = time_module.time()
|
||||
try:
|
||||
if not os.path.exists(path0):
|
||||
return False
|
||||
sz = os.path.getsize(path0)
|
||||
if sz < 1024:
|
||||
return False
|
||||
header_check_start = time_module.time()
|
||||
try:
|
||||
with open(path0, "rb") as _f:
|
||||
header = _f.read(4)
|
||||
if header != b"\x89PNG":
|
||||
return False
|
||||
try:
|
||||
_f.seek(-256, 2)
|
||||
except Exception:
|
||||
_f.seek(0)
|
||||
tail = _f.read(256)
|
||||
if b"IEND" not in tail:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
header_check_dur = (time_module.time() - header_check_start) * 1000.0
|
||||
if header_check_dur > 10.0:
|
||||
logging.debug(
|
||||
"[截图] PNG头尾校验耗时(ms)=%.1f path=%s",
|
||||
header_check_dur,
|
||||
path0,
|
||||
)
|
||||
|
||||
verify_total_dur = (time_module.time() - verify_start) * 1000.0
|
||||
if verify_total_dur > 100.0:
|
||||
logging.info(
|
||||
"[截图] _valid_png总耗时(ms)=%.1f path=%s",
|
||||
verify_total_dur,
|
||||
path0,
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 优先走 exec-out
|
||||
try:
|
||||
execout_timeout_sec = float(os.environ.get("ADB_EXECOUT_TIMEOUT_SEC", "10"))
|
||||
except ValueError:
|
||||
execout_timeout_sec = 10.0
|
||||
try:
|
||||
execout_warn_after_sec = float(
|
||||
os.environ.get("ADB_EXECOUT_WARN_AFTER_SEC", "3")
|
||||
)
|
||||
except ValueError:
|
||||
execout_warn_after_sec = 3.0
|
||||
try:
|
||||
execout_heartbeat_interval_sec = float(
|
||||
os.environ.get("ADB_EXECOUT_HEARTBEAT_INTERVAL_SEC", "5")
|
||||
)
|
||||
except ValueError:
|
||||
execout_heartbeat_interval_sec = 5.0
|
||||
try:
|
||||
execout_heartbeat_max = int(os.environ.get("ADB_EXECOUT_HEARTBEAT_MAX", "3"))
|
||||
except ValueError:
|
||||
execout_heartbeat_max = 3
|
||||
|
||||
for attempt in range(2):
|
||||
try:
|
||||
cleanup_start = time_module.time()
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
except Exception:
|
||||
pass
|
||||
cleanup_dur = (time_module.time() - cleanup_start) * 1000.0
|
||||
if cleanup_dur > 10.0:
|
||||
logging.debug("[截图] 清理临时文件耗时(ms)=%.1f", cleanup_dur)
|
||||
|
||||
adb_start = time_module.time()
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
bufsize=0,
|
||||
)
|
||||
|
||||
done_event = None
|
||||
watchdog_thread = None
|
||||
try:
|
||||
done_event = threading.Event()
|
||||
|
||||
def _watchdog() -> None:
|
||||
try:
|
||||
if execout_warn_after_sec > 0:
|
||||
if done_event.wait(timeout=execout_warn_after_sec):
|
||||
return
|
||||
start_wait = time_module.time()
|
||||
for i in range(max(0, execout_heartbeat_max)):
|
||||
if done_event.is_set():
|
||||
return
|
||||
waited = (time_module.time() - start_wait) * 1000.0
|
||||
logging.warning(
|
||||
"[截图] exec-out 仍在进行中:已等待(ms)=%.0f device=%s attempt=%s",
|
||||
waited,
|
||||
device_id,
|
||||
attempt + 1,
|
||||
)
|
||||
if done_event.wait(
|
||||
timeout=max(0.5, execout_heartbeat_interval_sec)
|
||||
):
|
||||
return
|
||||
except Exception:
|
||||
return
|
||||
|
||||
watchdog_thread = threading.Thread(
|
||||
target=_watchdog, name="adb-execout-watchdog", daemon=True
|
||||
)
|
||||
watchdog_thread.start()
|
||||
except Exception:
|
||||
done_event = None
|
||||
|
||||
stdout_data, _ = process.communicate(timeout=execout_timeout_sec)
|
||||
if done_event is not None:
|
||||
done_event.set()
|
||||
|
||||
if process.returncode != 0:
|
||||
raise subprocess.CalledProcessError(
|
||||
process.returncode,
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
)
|
||||
|
||||
with open(tmp_file, "wb", buffering=262144) as f:
|
||||
f.write(stdout_data)
|
||||
|
||||
adb_subprocess_dur = (time_module.time() - adb_start) * 1000.0
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
try:
|
||||
process.communicate(timeout=1)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if done_event is not None:
|
||||
done_event.set()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
validate_tmp_start = time_module.time()
|
||||
is_valid = _valid_png(tmp_file)
|
||||
validate_tmp_dur = (time_module.time() - validate_tmp_start) * 1000.0
|
||||
if validate_tmp_dur > 50.0:
|
||||
logging.info(
|
||||
"[截图] 临时文件验证耗时(ms)=%.1f result=%s",
|
||||
validate_tmp_dur,
|
||||
is_valid,
|
||||
)
|
||||
|
||||
if is_valid:
|
||||
replace_start = time_module.time()
|
||||
replace_success = _safe_replace_file(tmp_file, out_file)
|
||||
replace_dur = (time_module.time() - replace_start) * 1000.0
|
||||
if replace_dur > 50.0:
|
||||
logging.info(
|
||||
"[截图] 文件替换耗时(ms)=%.1f result=%s",
|
||||
replace_dur,
|
||||
replace_success,
|
||||
)
|
||||
|
||||
if replace_success:
|
||||
mirror_start = time_module.time()
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
mirror_dur = (time_module.time() - mirror_start) * 1000.0
|
||||
if mirror_dur > 50.0:
|
||||
logging.info(
|
||||
"[截图] 镜像到外部路径耗时(ms)=%.1f", mirror_dur
|
||||
)
|
||||
|
||||
validate_out_start = time_module.time()
|
||||
try:
|
||||
if os.path.exists(out_file):
|
||||
file_size = os.path.getsize(out_file)
|
||||
if file_size >= 1024:
|
||||
try:
|
||||
with open(out_file, "rb") as f:
|
||||
header = f.read(4)
|
||||
if header == b"\x89PNG":
|
||||
validate_out_dur = (
|
||||
time_module.time()
|
||||
- validate_out_start
|
||||
) * 1000.0
|
||||
if validate_out_dur > 50.0:
|
||||
logging.info(
|
||||
"[截图] 目标文件快速验证耗时(ms)=%.1f",
|
||||
validate_out_dur,
|
||||
)
|
||||
|
||||
overall_dur = (
|
||||
time_module.time() - overall_start
|
||||
) * 1000.0
|
||||
logging.info(
|
||||
"[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (exec-out成功) | 汇总: cleanup=%.1f adb_execout=%.1f validate_tmp=%.1f replace=%.1f mirror=%.1f validate_out=%.1f",
|
||||
overall_dur,
|
||||
cleanup_dur,
|
||||
adb_subprocess_dur,
|
||||
validate_tmp_dur,
|
||||
replace_dur,
|
||||
mirror_dur,
|
||||
validate_out_dur,
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
st = os.stat(out_file)
|
||||
_uo_log(
|
||||
f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
st = os.stat(tmp_file)
|
||||
_uo_log(
|
||||
f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
st = os.stat(tmp_file)
|
||||
_uo_log(
|
||||
f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except subprocess.TimeoutExpired:
|
||||
_uo_log("[截图] exec-out 超时,尝试重试或回退方案")
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
_uo_log(f"[截图] exec-out 异常:{e}")
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 回退方案:老式 shell screencap + pull
|
||||
fallback_start = time_module.time()
|
||||
try:
|
||||
shell_screencap_start = time_module.time()
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"screencap",
|
||||
"-p",
|
||||
"/sdcard/DCIM/screenshot.png",
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
timeout=10,
|
||||
)
|
||||
shell_screencap_dur = (time_module.time() - shell_screencap_start) * 1000.0
|
||||
logging.info(
|
||||
"[截图] 回退方案-shell screencap耗时(ms)=%.1f device=%s",
|
||||
shell_screencap_dur,
|
||||
device_id,
|
||||
)
|
||||
|
||||
pull_start = time_module.time()
|
||||
subprocess.run(
|
||||
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
timeout=10,
|
||||
)
|
||||
pull_dur = (time_module.time() - pull_start) * 1000.0
|
||||
logging.info(
|
||||
"[截图] 回退方案-adb pull耗时(ms)=%.1f device=%s", pull_dur, device_id
|
||||
)
|
||||
|
||||
fallback_validate_start = time_module.time()
|
||||
if _valid_png(tmp_file):
|
||||
fallback_validate_dur = (
|
||||
time_module.time() - fallback_validate_start
|
||||
) * 1000.0
|
||||
if fallback_validate_dur > 50.0:
|
||||
logging.info(
|
||||
"[截图] 回退方案-临时文件验证耗时(ms)=%.1f",
|
||||
fallback_validate_dur,
|
||||
)
|
||||
|
||||
fallback_replace_start = time_module.time()
|
||||
if _safe_replace_file(tmp_file, out_file):
|
||||
fallback_replace_dur = (
|
||||
time_module.time() - fallback_replace_start
|
||||
) * 1000.0
|
||||
if fallback_replace_dur > 50.0:
|
||||
logging.info(
|
||||
"[截图] 回退方案-文件替换耗时(ms)=%.1f",
|
||||
fallback_replace_dur,
|
||||
)
|
||||
|
||||
fallback_mirror_start = time_module.time()
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
fallback_mirror_dur = (
|
||||
time_module.time() - fallback_mirror_start
|
||||
) * 1000.0
|
||||
if fallback_mirror_dur > 50.0:
|
||||
logging.info(
|
||||
"[截图] 回退方案-镜像耗时(ms)=%.1f", fallback_mirror_dur
|
||||
)
|
||||
|
||||
try:
|
||||
if _valid_png(out_file):
|
||||
overall_dur = (time_module.time() - overall_start) * 1000.0
|
||||
fallback_total_dur = (
|
||||
time_module.time() - fallback_start
|
||||
) * 1000.0
|
||||
logging.info(
|
||||
"[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (回退方案成功, 回退部分耗时=%.1fms)",
|
||||
overall_dur,
|
||||
fallback_total_dur,
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 替换失败 → 直接复制 / 兜底
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
try:
|
||||
with open(tmp_file, "rb") as src, open(
|
||||
out_file, "wb"
|
||||
) as dst:
|
||||
dst.write(src.read())
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
try:
|
||||
if _valid_png(out_file):
|
||||
_uo_log(
|
||||
f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)"
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
except (OSError, PermissionError) as e:
|
||||
replace_success = _safe_replace_file(tmp_file, out_file)
|
||||
if replace_success:
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
try:
|
||||
if _valid_png(out_file):
|
||||
_uo_log(
|
||||
f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过优化替换)"
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
_uo_log(
|
||||
f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}"
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
_uo_log(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}")
|
||||
return True
|
||||
except Exception:
|
||||
# 再次回退:尝试用 screenshot1.png 覆盖 screenshot.png
|
||||
try:
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"screencap",
|
||||
"-p",
|
||||
"/sdcard/DCIM/screenshot1.png",
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"mv",
|
||||
"/sdcard/DCIM/screenshot1.png",
|
||||
"/sdcard/DCIM/screenshot.png",
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
return self.get_screenshot(device_id, path)
|
||||
except Exception:
|
||||
return False
|
||||
@@ -280,8 +280,11 @@ def check_in_fudai_detail(analyser: Any) -> bool:
|
||||
return False
|
||||
|
||||
pic = Image.open(pic_path)
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
try:
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
finally:
|
||||
pic.close()
|
||||
|
||||
# 获取分辨率比例和Y偏移
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,169 @@
|
||||
"""douyin/detection/detection_pkg/finder_numpy_scan - numpy 加速福袋图标像素扫描
|
||||
|
||||
把 check_have_fudai_with_ready_screenshot 中"numpy 加速扫描水平带"段抽出来。
|
||||
逻辑:在 ROI 内根据预设颜色范围生成像素掩码,按列聚合,从最优起始列向两侧
|
||||
交替搜索第一个匹配列,命中即返回检测到的 x 坐标(1080 基准)。
|
||||
|
||||
入口:scan_with_numpy(analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled)
|
||||
返回:(detected: bool, detected_x: Optional[int])
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
|
||||
def scan_with_numpy(
|
||||
analyser: Any,
|
||||
pic_new,
|
||||
rx: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
optimal_x_scaled: int,
|
||||
) -> Tuple[bool, Optional[int]]:
|
||||
"""numpy 加速扫描福袋图标的水平像素带。
|
||||
|
||||
Args:
|
||||
analyser: 可读 last_fudai_x / 写 last_fudai_x / last_find_fudai_time
|
||||
pic_new: PIL.Image,已加载的当前截图
|
||||
rx, ry: 目标分辨率宽/高(默认 1080x2400 基准)
|
||||
y_pianyi_val: Y 偏移
|
||||
optimal_x_scaled: 最优起始列(设备分辨率坐标)
|
||||
|
||||
Returns:
|
||||
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标;
|
||||
失败/异常返回 (False, None),由 caller 切换到逐像素扫描。
|
||||
"""
|
||||
try:
|
||||
import numpy as _np
|
||||
except (ImportError, ValueError, IndexError, AttributeError):
|
||||
return False, None
|
||||
|
||||
width, height = pic_new.size
|
||||
|
||||
try:
|
||||
# 计算检测区域,考虑分辨率缩放和偏移
|
||||
# 将像素检测的扫描带左上角改为图片坐标 x=157, y=354(右下不变)
|
||||
y0 = 354 * ry // 2400 + y_pianyi_val
|
||||
x1 = max(0, 157 * rx // 1080)
|
||||
x2 = min(width, 410 * rx // 1080)
|
||||
y_top = max(0, y0 - 3)
|
||||
y_bottom = min(height, y0 + 4)
|
||||
|
||||
if not (x1 < x2 and y_top < y_bottom):
|
||||
return False, None
|
||||
|
||||
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
|
||||
|
||||
# 双截图记录:保存实时操作截图(像素检测区域)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
roi, operation_type="pixel_detect"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
arr = _np.array(roi)
|
||||
if arr.size == 0:
|
||||
return False, None
|
||||
|
||||
r = arr[:, :, 0] # type: ignore[index]
|
||||
g = arr[:, :, 1] # type: ignore[index]
|
||||
b = arr[:, :, 2] # type: ignore[index]
|
||||
# 精度优化:扩大颜色范围,提高容错性(考虑不同屏幕色温和亮度)
|
||||
# 原来的范围:R[193-203], G[176-193], B[237-247]
|
||||
# 优化后:适度放宽范围,但保持中心值权重
|
||||
mask_center = (
|
||||
(r >= 190) & (r <= 206)
|
||||
& (g >= 173) & (g <= 196)
|
||||
& (b >= 234) & (b <= 250)
|
||||
) # type: ignore[operator]
|
||||
mask = mask_center
|
||||
# 检查每一列是否有足够多的匹配像素(提高准确性,避免单个噪点误判)
|
||||
cols = _np.sum(mask, axis=0)
|
||||
# 至少需要 2 个像素匹配(避免单个噪点误判)
|
||||
valid_cols = cols >= 2
|
||||
if not valid_cols.any():
|
||||
return False, None
|
||||
|
||||
# 从最优位置开始向左右两侧交替搜索
|
||||
roi_width = x2 - x1
|
||||
optimal_col = optimal_x_scaled - x1
|
||||
optimal_col = max(0, min(optimal_col, roi_width - 1))
|
||||
|
||||
found_col: Optional[int] = None
|
||||
search_range = max(optimal_col, roi_width - optimal_col)
|
||||
|
||||
if valid_cols[optimal_col]:
|
||||
found_col = optimal_col
|
||||
else:
|
||||
for offset in range(1, search_range + 1):
|
||||
right_col = optimal_col + offset
|
||||
if right_col < roi_width and valid_cols[right_col]:
|
||||
found_col = right_col
|
||||
break
|
||||
left_col = optimal_col - offset
|
||||
if left_col >= 0 and valid_cols[left_col]:
|
||||
found_col = left_col
|
||||
break
|
||||
|
||||
if found_col is None:
|
||||
# 兜底:从左到右第一个匹配
|
||||
found_col = int(_np.argmax(valid_cols))
|
||||
|
||||
col_idx = found_col
|
||||
# 1080 基准坐标
|
||||
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
|
||||
|
||||
# 保存找到的位置作为下次的最优起点
|
||||
try:
|
||||
analyser.last_fudai_x = detected_x
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 双截图记录:成功识别存档
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
roi, operation_type="pixel_detect"
|
||||
)
|
||||
|
||||
pic_rgb_full = pic_new.convert("RGB")
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=(x1, y_top, x2, y_bottom),
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"detected_x_scaled": x1 + col_idx,
|
||||
"scan_range": f"x:{x1}-{x2}, y:{y_top}-{y_bottom}",
|
||||
"resolution": f"{rx}x{ry}",
|
||||
"result": "success",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标检测成功保存完整截图",
|
||||
path=debug_path,
|
||||
detected_x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True, detected_x
|
||||
except (ImportError, ValueError, IndexError, AttributeError):
|
||||
return False, None
|
||||
@@ -0,0 +1,205 @@
|
||||
"""douyin/detection/detection_pkg/finder_pixel_scan - 逐像素福袋图标扫描兜底
|
||||
|
||||
当 numpy 加速扫描没找到时,回退到逐像素遍历。逻辑与 numpy 版相似但
|
||||
使用 PIL.Image.load() 提供的像素访问,性能较慢但兼容性最好。
|
||||
|
||||
入口:scan_pixel_by_pixel(analyser, pic_new, rx, ry, y_pianyi_val)
|
||||
返回:(detected: bool, detected_x: Optional[int])
|
||||
|
||||
颜色范围与 finder_numpy_scan 一致:r ∈ [190, 206], g ∈ [173, 196], b ∈ [234, 250]。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
|
||||
# 福袋图标主色范围(与 finder_numpy_scan 共享)
|
||||
_R_MIN, _R_MAX = 190, 206
|
||||
_G_MIN, _G_MAX = 173, 196
|
||||
_B_MIN, _B_MAX = 234, 250
|
||||
|
||||
|
||||
def _is_target_pixel(px) -> bool:
|
||||
"""检查像素是否落在目标颜色范围内。"""
|
||||
if not (isinstance(px, tuple) and len(px) >= 3):
|
||||
return False
|
||||
r, g, b = px[0], px[1], px[2]
|
||||
return _R_MIN <= r <= _R_MAX and _G_MIN <= g <= _G_MAX and _B_MIN <= b <= _B_MAX
|
||||
|
||||
|
||||
def _safe_check_pixel(pix, x: int, y: int) -> bool:
|
||||
"""读 pix[x, y] 后检查是否目标颜色,越界/类型错误时返回 False。"""
|
||||
try:
|
||||
return _is_target_pixel(pix[x, y])
|
||||
except (IndexError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def _pick_optimal_x(analyser, scan_x_start: int, scan_x_end: int, rx: int) -> int:
|
||||
"""选择本次扫描的最优起始列:优先用历史 last_fudai_x,否则默认热区中心。"""
|
||||
try:
|
||||
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
|
||||
if (
|
||||
last_fudai_x > 0
|
||||
and scan_x_start <= last_fudai_x * rx // 1080 <= scan_x_end
|
||||
):
|
||||
return last_fudai_x * rx // 1080
|
||||
except Exception:
|
||||
pass
|
||||
# 默认最优位置:最热门区域中心(98-240 的中心,约 169)
|
||||
return 169 * rx // 1080
|
||||
|
||||
|
||||
def _search_along_y(
|
||||
pix,
|
||||
scan_x_start: int,
|
||||
scan_x_end: int,
|
||||
optimal_x_scaled: int,
|
||||
check_y: int,
|
||||
) -> Optional[int]:
|
||||
"""在指定 y 行上找第一个目标色像素的 x 坐标。
|
||||
|
||||
搜索顺序:optimal_x → 向两侧交替搜索 → 最后从左到右兜底。
|
||||
"""
|
||||
# 1. 先检查最优位置本身
|
||||
if _safe_check_pixel(pix, optimal_x_scaled, check_y):
|
||||
return optimal_x_scaled
|
||||
|
||||
# 2. 向左右两侧交替搜索
|
||||
search_range = max(
|
||||
optimal_x_scaled - scan_x_start,
|
||||
scan_x_end - optimal_x_scaled,
|
||||
)
|
||||
for offset in range(1, search_range + 1):
|
||||
right_x = optimal_x_scaled + offset
|
||||
if right_x < scan_x_end and _safe_check_pixel(pix, right_x, check_y):
|
||||
return right_x
|
||||
left_x = optimal_x_scaled - offset
|
||||
if left_x >= scan_x_start and _safe_check_pixel(pix, left_x, check_y):
|
||||
return left_x
|
||||
|
||||
# 3. 最后从左到右扫一遍兜底
|
||||
for x_scaled in range(scan_x_start, scan_x_end):
|
||||
if _safe_check_pixel(pix, x_scaled, check_y):
|
||||
return x_scaled
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def scan_pixel_by_pixel(
|
||||
analyser: Any,
|
||||
pic_new,
|
||||
rx: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
) -> Tuple[bool, Optional[int]]:
|
||||
"""逐像素遍历兜底(numpy 不可用 / 未命中时使用)。
|
||||
|
||||
Args:
|
||||
analyser: 可读 last_fudai_x / 写 last_fudai_x / last_find_fudai_time
|
||||
pic_new: PIL.Image,已加载的当前截图
|
||||
rx, ry: 目标分辨率宽/高(默认 1080x2400 基准)
|
||||
y_pianyi_val: Y 偏移
|
||||
|
||||
Returns:
|
||||
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标。
|
||||
"""
|
||||
detected = False
|
||||
detected_x: Optional[int] = None
|
||||
try:
|
||||
pix = pic_new.load()
|
||||
pic_width, pic_height = pic_new.size
|
||||
# 计算实际扫描范围,防止越界
|
||||
scan_x_start = 41 * rx // 1080
|
||||
scan_x_end = min(410 * rx // 1080, pic_width)
|
||||
scan_y = 403 * ry // 2400 + y_pianyi_val
|
||||
|
||||
optimal_x_scaled = _pick_optimal_x(analyser, scan_x_start, scan_x_end, rx)
|
||||
# 确保最优位置在搜索范围内
|
||||
optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1))
|
||||
|
||||
if not (0 <= scan_y < pic_height):
|
||||
return False, None
|
||||
|
||||
# 精度优化:同时检查上下几行像素
|
||||
for offset_y in (0, -1, 1, -2, 2):
|
||||
check_y = scan_y + offset_y
|
||||
if not (0 <= check_y < pic_height):
|
||||
continue
|
||||
|
||||
found_x = _search_along_y(
|
||||
pix, scan_x_start, scan_x_end, optimal_x_scaled, check_y
|
||||
)
|
||||
if found_x is None:
|
||||
continue
|
||||
|
||||
# 命中:转换回 1080 基准
|
||||
detected_x = int(found_x * 1080.0 / max(1, rx))
|
||||
detected = True
|
||||
|
||||
try:
|
||||
analyser.last_fudai_x = detected_x
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 双截图记录:成功识别存档
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
detect_roi = pic_new.crop(
|
||||
(
|
||||
scan_x_start,
|
||||
max(0, scan_y - 3),
|
||||
scan_x_end,
|
||||
min(pic_height, scan_y + 4),
|
||||
)
|
||||
).convert("RGB")
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
detect_roi,
|
||||
operation_type="pixel_detect",
|
||||
)
|
||||
|
||||
pic_rgb_full = pic_new.convert("RGB")
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=(
|
||||
scan_x_start,
|
||||
max(0, scan_y - 3),
|
||||
scan_x_end,
|
||||
min(pic_height, scan_y + 4),
|
||||
),
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"detected_x_scaled": found_x,
|
||||
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
|
||||
"resolution": f"{rx}x{ry}",
|
||||
"result": "success",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标检测成功保存完整截图",
|
||||
path=debug_path,
|
||||
detected_x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
break # 找到后退出 offset_y 循环
|
||||
except Exception:
|
||||
# 像素检测失败,记录但不影响主流程
|
||||
pass
|
||||
|
||||
return detected, detected_x
|
||||
@@ -0,0 +1,279 @@
|
||||
"""douyin/detection/detection_pkg/finder_template_match - OpenCV 模板匹配兜底
|
||||
|
||||
像素检测(numpy + 逐像素)都失败时的最后兜底:用 OpenCV 模板匹配
|
||||
(TM_CCOEFF_NORMED)在搜索区域里找 fudai.png 模板。
|
||||
|
||||
入口:match_template(analyser, pic_new, rx, ry, y_pianyi_val, loop) -> (detected, x)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
|
||||
def _resolve_template_path() -> str:
|
||||
"""获取 fudai.png 模板的绝对路径。优先 path_config,回退到本文件相邻 assets/。"""
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
return path_config.get_assets_dir() + "/fudai.png"
|
||||
except Exception:
|
||||
# 兜底:导入失败时显式拼到项目根的 assets/,
|
||||
# 不要用 dirname(__file__) 拼 "assets"(那样会推到 detection_pkg/assets)
|
||||
return os.path.normpath(
|
||||
os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
"..", "..", "..",
|
||||
"assets", "fudai.png",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _save_search_roi(analyser, search_roi, last_match_path: str, loop: int, x1: int, x2: int, y_top: int, y_bottom: int, rw: int, rh: int) -> None:
|
||||
"""保存搜索区域到 last_match.png(仅作日志/调试用)。"""
|
||||
try:
|
||||
import cv2
|
||||
|
||||
save_success = cv2.imwrite(last_match_path, search_roi)
|
||||
if save_success:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 已保存搜索区域截图",
|
||||
loop=loop,
|
||||
文件路径=last_match_path,
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 保存搜索区域截图失败",
|
||||
loop=loop,
|
||||
文件路径=last_match_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as save_err:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 保存搜索区域截图异常",
|
||||
loop=loop,
|
||||
错误类型=type(save_err).__name__,
|
||||
错误信息=str(save_err),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def match_template(
|
||||
analyser: Any,
|
||||
pic_new,
|
||||
rx: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
loop: int,
|
||||
) -> Tuple[bool, Optional[int]]:
|
||||
"""像素检测全部失败后的模板匹配兜底。
|
||||
|
||||
Args:
|
||||
analyser: 提供 fudai_template_match_threshold / _log_kv / last_find_fudai_time
|
||||
pic_new: PIL.Image,已加载的当前截图
|
||||
rx, ry: 目标分辨率宽/高(默认 1080x2400 基准)
|
||||
y_pianyi_val: Y 偏移
|
||||
loop: 当前循环次数(仅用于日志)
|
||||
|
||||
Returns:
|
||||
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标。
|
||||
"""
|
||||
detected = False
|
||||
detected_x: Optional[int] = None
|
||||
|
||||
try:
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
template_path = _resolve_template_path()
|
||||
if not os.path.exists(template_path):
|
||||
return False, None
|
||||
|
||||
# 获取匹配阈值
|
||||
try:
|
||||
template_threshold = float(
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
|
||||
)
|
||||
except Exception:
|
||||
template_threshold = 0.7
|
||||
|
||||
# 读取模板
|
||||
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
|
||||
if template is None:
|
||||
return False, None
|
||||
|
||||
# 将 PIL 图片转换为 OpenCV 格式
|
||||
pic_rgb = pic_new.convert("RGB")
|
||||
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
|
||||
height, width = screenshot_bgr.shape[:2]
|
||||
|
||||
# 定义搜索区域:X=156-269(1080 基准),Y=351-451(2400 基准)
|
||||
x1 = max(0, 156 * rx // 1080)
|
||||
x2 = min(width, 269 * rx // 1080)
|
||||
y_top = max(0, 351 * ry // 2400 + y_pianyi_val)
|
||||
y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val)
|
||||
|
||||
if not (x1 < x2 and y_top < y_bottom):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-坐标无效",
|
||||
loop=loop,
|
||||
x1=x1,
|
||||
x2=x2,
|
||||
y_top=y_top,
|
||||
y_bottom=y_bottom,
|
||||
截图尺寸=f"{width}x{height}",
|
||||
分辨率=f"{rx}x{ry}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, None
|
||||
|
||||
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index]
|
||||
if search_roi.size == 0:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-搜索区域为空",
|
||||
loop=loop,
|
||||
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
截图尺寸=f"{width}x{height}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, None
|
||||
|
||||
th, tw = template.shape[:2]
|
||||
rh, rw = search_roi.shape[:2]
|
||||
|
||||
# 保存搜索区域截图到 last_match.png
|
||||
try:
|
||||
from douyin.core import path_config as _pc
|
||||
|
||||
match_dir = os.path.join(_pc.get_pic_dir(), "template_match")
|
||||
except Exception:
|
||||
match_dir = os.path.normpath(
|
||||
os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
"..", "..", "..",
|
||||
"pic", "template_match",
|
||||
)
|
||||
)
|
||||
try:
|
||||
os.makedirs(match_dir, exist_ok=True)
|
||||
last_match_path = os.path.join(match_dir, "last_match.png")
|
||||
_save_search_roi(
|
||||
analyser, search_roi, last_match_path, loop,
|
||||
x1, x2, y_top, y_bottom, rw, rh,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 模板太大就缩小
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
if scale > 0:
|
||||
template = cv2.resize(
|
||||
template,
|
||||
(max(1, int(tw * scale)), max(1, int(th * scale))),
|
||||
)
|
||||
th, tw = template.shape[:2]
|
||||
|
||||
# 执行模板匹配
|
||||
if not (th <= rh and tw <= rw):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-尺寸不匹配",
|
||||
loop=loop,
|
||||
模板尺寸=f"{tw}x{th}",
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, None
|
||||
|
||||
res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
|
||||
|
||||
# 双截图记录:保存实时操作截图(搜索区域)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
|
||||
)
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
search_roi_pil, operation_type="template_match"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配兜底",
|
||||
loop=loop,
|
||||
匹配分数=round(max_val, 4),
|
||||
阈值=template_threshold,
|
||||
是否通过=bool(max_val >= template_threshold),
|
||||
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
模板尺寸=f"{tw}x{th}",
|
||||
截图尺寸=f"{width}x{height}",
|
||||
分辨率=f"{rx}x{ry}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if max_val < template_threshold:
|
||||
return False, None
|
||||
|
||||
# 命中:保存成功识别存档
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
|
||||
)
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
search_roi_pil, operation_type="template_match"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 1080 基准坐标
|
||||
detected_x_in_roi = max_loc[0]
|
||||
detected_x = int(
|
||||
(x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)
|
||||
)
|
||||
detected = True
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return detected, detected_x
|
||||
except (ImportError, Exception) as e:
|
||||
# OpenCV 不可用或模板匹配失败,让 caller 继续走未命中分支
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配异常",
|
||||
loop=loop,
|
||||
错误类型=type(e).__name__,
|
||||
错误信息=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, None
|
||||
@@ -21,8 +21,11 @@ def _safe_open_screenshot_rgb(pic_path: str) -> Optional[Image.Image]:
|
||||
if not pic_path or (not os.path.exists(pic_path)):
|
||||
return None
|
||||
pic = Image.open(pic_path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
return pic.convert("RGB")
|
||||
try:
|
||||
pic.load()
|
||||
return pic.convert("RGB")
|
||||
finally:
|
||||
pic.close()
|
||||
except (OSError, IOError, SyntaxError):
|
||||
# Handle truncated image files
|
||||
return None
|
||||
|
||||
@@ -203,7 +203,7 @@ def detect_fudai_detail_page(
|
||||
return False
|
||||
|
||||
try:
|
||||
from .douyin_detection import check_detail_height
|
||||
from douyin.detection.douyin_detection import check_detail_height
|
||||
|
||||
# 执行任务数量检测
|
||||
task_count = int(check_detail_height(analyser) or 0)
|
||||
|
||||
@@ -63,7 +63,18 @@ ROBOT_VERIFY = (100, 1200, 980, 1780)
|
||||
# 诊断购物红包(弹窗快速检测区域 - 文字区域)
|
||||
DIAG_SHOPPING_REDPACKET = (200, 300, 880, 1000)
|
||||
|
||||
|
||||
# 倒计时、任务、按钮等常用区域(保留占位,可根据需要填写)
|
||||
# COUNTDOWN_BOX = (390, 1140, 570, 1290)
|
||||
# BUTTON_BOX = (306, 2030, 780, 2180)
|
||||
# CONTENT_BOX = (200, 600, 880, 900)
|
||||
|
||||
# 点击坐标常量(基准分辨率 1080x2400)
|
||||
# 关闭详情页:点击详情页旁边空白区域
|
||||
DETAIL_OUTSIDE_CLICK = (500, 470)
|
||||
# 参与抽奖按钮
|
||||
PARTICIPATE_BTN_CLICK = (543, 2070)
|
||||
# 粉丝团加入按钮
|
||||
FANSCLUB_JOIN_CLICK = (540, 2006)
|
||||
# 粉丝团加入按钮(回退坐标)
|
||||
FANSCLUB_JOIN_FALLBACK_CLICK = (500, 2060)
|
||||
+16
-1064
File diff suppressed because it is too large.
Load diff
Whitespace-only changes.
File diff suppressed because it is too large.
Load diff
@@ -114,8 +114,11 @@ def safe_image_load(image_path: str) -> Optional[Image.Image]:
|
||||
|
||||
try:
|
||||
pic = Image.open(image_path)
|
||||
pic.load() # 确保图像数据已加载
|
||||
return pic.convert("RGB")
|
||||
try:
|
||||
pic.load()
|
||||
return pic.convert("RGB")
|
||||
finally:
|
||||
pic.close()
|
||||
except UnidentifiedImageError as e:
|
||||
# 图像格式不支持
|
||||
raise ValueError(f"无法识别图像格式: {image_path}") from e
|
||||
@@ -180,154 +183,159 @@ def save_full_screenshot_with_ocr_region(
|
||||
return
|
||||
|
||||
# 安全加载图像
|
||||
pic_rgb: Optional[Image.Image] = None
|
||||
try:
|
||||
pic_rgb = safe_image_load(pic_path)
|
||||
if pic_rgb is None:
|
||||
return
|
||||
except ValueError as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "加载图像"},
|
||||
level="ERROR",
|
||||
)
|
||||
return
|
||||
except OSError as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "读取图像文件"},
|
||||
level="ERROR",
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "加载图像(未知错误)"},
|
||||
level="ERROR",
|
||||
)
|
||||
return
|
||||
|
||||
# 获取分辨率信息
|
||||
width, height = pic_rgb.size
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "获取分辨率", "image_size": f"{width}x{height}"},
|
||||
level="WARNING",
|
||||
)
|
||||
rx, ry = 1080, 2400 # 使用默认值
|
||||
|
||||
context.update({
|
||||
"image_size": f"{width}x{height}",
|
||||
"base_resolution": f"{rx}x{ry}",
|
||||
})
|
||||
|
||||
# 缩放坐标到实际分辨率
|
||||
try:
|
||||
x1_base, y1_base, x2_base, y2_base = coords
|
||||
x1 = int(x1_base * width / rx)
|
||||
y1 = int((y1_base + y_pianyi) * height / ry)
|
||||
x2 = int(x2_base * width / rx)
|
||||
y2 = int((y2_base + y_pianyi) * height / ry)
|
||||
|
||||
scaled_coords = (x1, y1, x2, y2)
|
||||
except (ValueError, ZeroDivisionError) as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "坐标缩放"},
|
||||
level="ERROR",
|
||||
)
|
||||
return
|
||||
|
||||
# 验证和修正坐标
|
||||
is_valid, error_msg, corrected_coords = validate_coords(
|
||||
scaled_coords, width, height
|
||||
)
|
||||
|
||||
if not is_valid:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
ValueError(f"坐标无效: {error_msg}"),
|
||||
{**context, "stage": "坐标验证", "scaled_coords": scaled_coords},
|
||||
level="WARNING",
|
||||
)
|
||||
return
|
||||
|
||||
x1, y1, x2, y2 = corrected_coords
|
||||
|
||||
# 如果坐标被修正,记录警告
|
||||
if error_msg:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"验证",
|
||||
"OCR区域坐标超出屏幕范围,已修正",
|
||||
original_coords=f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
corrected_coords=f"({x1},{y1})-({x2},{y2})",
|
||||
screen_size=f"{width}x{height}",
|
||||
base_coords=coords,
|
||||
pic_rgb = safe_image_load(pic_path)
|
||||
if pic_rgb is None:
|
||||
return
|
||||
except ValueError as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "加载图像"},
|
||||
level="ERROR",
|
||||
)
|
||||
return
|
||||
except OSError as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "读取图像文件"},
|
||||
level="ERROR",
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "加载图像(未知错误)"},
|
||||
level="ERROR",
|
||||
)
|
||||
return
|
||||
|
||||
# 获取分辨率信息
|
||||
width, height = pic_rgb.size
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "获取分辨率", "image_size": f"{width}x{height}"},
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
rx, ry = 1080, 2400 # 使用默认值
|
||||
|
||||
# 保存调试图片
|
||||
try:
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb,
|
||||
operation_type="ocr",
|
||||
picname=picname,
|
||||
step="before_ocr",
|
||||
coords=(x1, y1, x2, y2),
|
||||
extra_info={
|
||||
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
|
||||
"y_offset": y_pianyi,
|
||||
},
|
||||
context.update({
|
||||
"image_size": f"{width}x{height}",
|
||||
"base_resolution": f"{rx}x{ry}",
|
||||
})
|
||||
|
||||
# 缩放坐标到实际分辨率
|
||||
try:
|
||||
x1_base, y1_base, x2_base, y2_base = coords
|
||||
x1 = int(x1_base * width / rx)
|
||||
y1 = int((y1_base + y_pianyi) * height / ry)
|
||||
x2 = int(x2_base * width / rx)
|
||||
y2 = int((y2_base + y_pianyi) * height / ry)
|
||||
|
||||
scaled_coords = (x1, y1, x2, y2)
|
||||
except (ValueError, ZeroDivisionError) as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "坐标缩放"},
|
||||
level="ERROR",
|
||||
)
|
||||
return
|
||||
|
||||
# 验证和修正坐标
|
||||
is_valid, error_msg, corrected_coords = validate_coords(
|
||||
scaled_coords, width, height
|
||||
)
|
||||
|
||||
if debug_path:
|
||||
if not is_valid:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
ValueError(f"坐标无效: {error_msg}"),
|
||||
{**context, "stage": "坐标验证", "scaled_coords": scaled_coords},
|
||||
level="WARNING",
|
||||
)
|
||||
return
|
||||
|
||||
x1, y1, x2, y2 = corrected_coords
|
||||
|
||||
# 如果坐标被修正,记录警告
|
||||
if error_msg:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
f"OCR识别前保存完整截图({picname})",
|
||||
path=debug_path,
|
||||
region=f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
)
|
||||
except Exception as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "记录成功日志", "debug_path": debug_path},
|
||||
"验证",
|
||||
"OCR区域坐标超出屏幕范围,已修正",
|
||||
original_coords=f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
corrected_coords=f"({x1},{y1})-({x2},{y2})",
|
||||
screen_size=f"{width}x{height}",
|
||||
base_coords=coords,
|
||||
level="WARNING",
|
||||
)
|
||||
except PermissionError as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "保存调试图像(权限错误)"},
|
||||
level="ERROR",
|
||||
)
|
||||
except OSError as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "保存调试图像(系统错误)"},
|
||||
level="ERROR",
|
||||
)
|
||||
except Exception as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "保存调试图像(未知错误)"},
|
||||
level="ERROR",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 保存调试图片
|
||||
try:
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb,
|
||||
operation_type="ocr",
|
||||
picname=picname,
|
||||
step="before_ocr",
|
||||
coords=(x1, y1, x2, y2),
|
||||
extra_info={
|
||||
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
|
||||
"y_offset": y_pianyi,
|
||||
},
|
||||
)
|
||||
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
f"OCR识别前保存完整截图({picname})",
|
||||
path=debug_path,
|
||||
region=f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
)
|
||||
except Exception as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "记录成功日志", "debug_path": debug_path},
|
||||
level="WARNING",
|
||||
)
|
||||
except PermissionError as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "保存调试图像(权限错误)"},
|
||||
level="ERROR",
|
||||
)
|
||||
except OSError as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "保存调试图像(系统错误)"},
|
||||
level="ERROR",
|
||||
)
|
||||
except Exception as e:
|
||||
log_debug_error(
|
||||
analyser,
|
||||
e,
|
||||
{**context, "stage": "保存调试图像(未知错误)"},
|
||||
level="ERROR",
|
||||
)
|
||||
finally:
|
||||
if pic_rgb is not None:
|
||||
pic_rgb.close()
|
||||
|
||||
|
||||
# 向后兼容:保留原函数名
|
||||
|
||||
@@ -46,15 +46,17 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
|
||||
path = path_config.get_screenshot_path()
|
||||
|
||||
try:
|
||||
pic = Image.open(path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
_raw = Image.open(path)
|
||||
try:
|
||||
_raw.load() # Force load to catch truncated files early
|
||||
pic = _raw.convert("RGBA")
|
||||
finally:
|
||||
_raw.close()
|
||||
except (OSError, IOError, SyntaxError):
|
||||
# Handle truncated image files
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
pic = pic.convert("RGBA")
|
||||
pix = pic.load()
|
||||
w, h = pic.size
|
||||
|
||||
@@ -237,9 +239,12 @@ def is_wrong_coupon_popup(analyser: Any) -> bool:
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
pic_check = Image.open(pic_path)
|
||||
pic_check.load()
|
||||
pic_rgb_check = pic_check.convert("RGB")
|
||||
_raw = Image.open(pic_path)
|
||||
try:
|
||||
_raw.load()
|
||||
pic_rgb_check = _raw.convert("RGB")
|
||||
finally:
|
||||
_raw.close()
|
||||
|
||||
width, height = pic_rgb_check.size
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
|
||||
@@ -6,7 +6,7 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Tuple
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
@@ -168,8 +168,18 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
pic_path = os.path.join(
|
||||
os.path.dirname(__file__), "pic", "screenshot.png"
|
||||
# 兜底:导入失败时显式拼到项目根的 pic/,
|
||||
# 不要用 dirname(__file__) 拼"pic"(那样会推到 douyin/fudai/core/fudai_detail_orchestrator_pkg/pic)
|
||||
pic_path = os.path.normpath(
|
||||
os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"pic",
|
||||
"screenshot.png",
|
||||
)
|
||||
)
|
||||
|
||||
if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024:
|
||||
@@ -213,8 +223,18 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
pic_path = os.path.join(
|
||||
os.path.dirname(__file__), "pic", "screenshot.png"
|
||||
# 兜底:导入失败时显式拼到项目根的 pic/,
|
||||
# 不要用 dirname(__file__) 拼"pic"(那样会推到 douyin/fudai/core/fudai_detail_orchestrator_pkg/pic)
|
||||
pic_path = os.path.normpath(
|
||||
os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"pic",
|
||||
"screenshot.png",
|
||||
)
|
||||
)
|
||||
|
||||
wait_start = time.time()
|
||||
@@ -235,22 +255,18 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
pass
|
||||
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
from douyin.core import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
pic_rgb = None
|
||||
try:
|
||||
if os.path.exists(pic_path):
|
||||
_img0 = time.time()
|
||||
pic = Image.open(pic_path)
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
try:
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
finally:
|
||||
pic.close()
|
||||
image_load_ms = round((time.time() - _img0) * 1000, 1)
|
||||
_log_perf("after_image_load") # 移除:避免过多性能日志
|
||||
except Exception:
|
||||
|
||||
@@ -211,8 +211,17 @@ def read_live_room_title_core(
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
pic_path = os.path.join(
|
||||
os.path.dirname(__file__), "pic", "screenshot.png"
|
||||
# 兜底:导入失败时显式拼到项目根的 pic/,
|
||||
# 不要用 dirname(__file__) 拼"pic"(那样会推到 douyin/fudai/core/pic)
|
||||
pic_path = os.path.normpath(
|
||||
os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"pic",
|
||||
"screenshot.png",
|
||||
)
|
||||
)
|
||||
|
||||
if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024:
|
||||
|
||||
@@ -54,28 +54,27 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st
|
||||
|
||||
# 检查1:内容不能为空(至少要有一些文字)
|
||||
# 如果运行时显式禁用了内容识别,则跳过此检查(允许内容为空)
|
||||
try:
|
||||
disable_content = False
|
||||
if analyser:
|
||||
disable_content = False
|
||||
if analyser:
|
||||
try:
|
||||
disable_content = bool(
|
||||
getattr(analyser, "fudai_disable_content_recognition", False)
|
||||
)
|
||||
# 如果 analyser 未设置该属性,再尝试从 config.json 读取全局配置
|
||||
if not disable_content:
|
||||
try:
|
||||
cfg_path = path_config.get_config_path()
|
||||
if cfg_path and os.path.exists(cfg_path):
|
||||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
disable_content = bool(
|
||||
cfg.get("fudai_disable_content_recognition", False)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if not disable_content:
|
||||
if not content or len(content.strip()) < 2:
|
||||
return False, "content_empty_or_too_short"
|
||||
except Exception:
|
||||
except Exception:
|
||||
pass
|
||||
if not disable_content:
|
||||
try:
|
||||
cfg_path = path_config.get_config_path()
|
||||
if cfg_path and os.path.exists(cfg_path):
|
||||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
disable_content = bool(
|
||||
cfg.get("fudai_disable_content_recognition", False)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not disable_content:
|
||||
if not content or len(content.strip()) < 2:
|
||||
return False, "content_empty_or_too_short"
|
||||
|
||||
@@ -202,8 +201,14 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st
|
||||
).strip()
|
||||
if countdown_mm_raw and countdown_ss_raw:
|
||||
try:
|
||||
mm = int(countdown_mm_raw)
|
||||
ss = int(countdown_ss_raw)
|
||||
from douyin.utils.time_utils import extract_2digits
|
||||
|
||||
mm_str = extract_2digits(countdown_mm_raw)
|
||||
ss_str = extract_2digits(countdown_ss_raw)
|
||||
if not mm_str or not ss_str:
|
||||
return False, "countdown_mm_ss_not_numeric"
|
||||
mm = int(mm_str)
|
||||
ss = int(ss_str)
|
||||
if mm < 0 or mm > 59 or ss < 0 or ss > 59:
|
||||
return False, "countdown_mm_ss_invalid_range"
|
||||
# 如果有倒计时元组,验证是否一致
|
||||
|
||||
@@ -10,8 +10,9 @@ import re
|
||||
import time
|
||||
from typing import Any, Tuple
|
||||
|
||||
from .helpers import _is_short_countdown_text
|
||||
from .helpers import _is_short_countdown_text, is_watch_task_fudai
|
||||
from .should_skip import should_skip_fudai_by_config
|
||||
from douyin.fudai.core.coords import DETAIL_OUTSIDE_CLICK
|
||||
|
||||
|
||||
def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
@@ -54,20 +55,36 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
)
|
||||
return False
|
||||
elif last_status == "validation_failed":
|
||||
try:
|
||||
# 按钮状态为可操作时,即使验证失败也继续走参与流程
|
||||
_ACTIONABLE = {
|
||||
"可以参与", "需要加入粉丝团", "需要评论",
|
||||
"需要观看", "已参与",
|
||||
}
|
||||
_btn_st = getattr(analyser, "_fudai_button_status", None)
|
||||
if _btn_st in _ACTIONABLE:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:验证失败但按钮可操作,继续参与",
|
||||
button_status=_btn_st,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理",
|
||||
"basic_join_decision完成(验证失败)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(验证失败)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -81,12 +98,66 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
|
||||
is_valid, reason = dfd_module.validate_fudai_detail(detail, analyser)
|
||||
if not is_valid:
|
||||
# 按钮状态为可操作时,即使验证失败也继续走参与流程
|
||||
_ACTIONABLE = {
|
||||
"可以参与", "需要加入粉丝团", "需要评论",
|
||||
"需要观看", "已参与",
|
||||
}
|
||||
_btn_st = getattr(analyser, "_fudai_button_status", None)
|
||||
if _btn_st in _ACTIONABLE:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:验证失败但按钮可操作,继续参与",
|
||||
validation_reason=reason,
|
||||
button_status=_btn_st,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:福袋详情数据验证失败,识别出错",
|
||||
validation_reason=reason,
|
||||
content=content[:50] if content else "",
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(验证失败)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误
|
||||
if not content and prize_value_yuan == 0.0:
|
||||
# 按钮状态为可操作时,即使详情为空也继续走参与流程
|
||||
_ACTIONABLE = {
|
||||
"可以参与", "需要加入粉丝团", "需要评论",
|
||||
"需要观看", "已参与",
|
||||
}
|
||||
_btn_st = getattr(analyser, "_fudai_button_status", None)
|
||||
if _btn_st in _ACTIONABLE:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:福袋详情数据验证失败,识别出错",
|
||||
validation_reason=reason,
|
||||
content=content[:50] if content else "",
|
||||
"basic_join_decision:详情为空但按钮可操作,继续参与",
|
||||
button_status=_btn_st,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理",
|
||||
content=content,
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
)
|
||||
except Exception:
|
||||
@@ -94,31 +165,10 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(验证失败)",
|
||||
"basic_join_decision完成(无效详情)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误
|
||||
if not content and prize_value_yuan == 0.0:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理",
|
||||
content=content,
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(无效详情)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
|
||||
# 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋
|
||||
try:
|
||||
@@ -134,7 +184,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
except Exception:
|
||||
pass
|
||||
# 这里需要导入 attend_choujiang 函数
|
||||
from .fudai_attend import attend_choujiang
|
||||
from ..fudai_attend import attend_choujiang
|
||||
|
||||
result = attend_choujiang(analyser)
|
||||
elapsed = time.time() - start_time
|
||||
@@ -226,7 +276,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
pass
|
||||
# 关闭详情页
|
||||
try:
|
||||
analyser.click(500, 470)
|
||||
analyser.click(*DETAIL_OUTSIDE_CLICK)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
@@ -365,7 +415,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
pass
|
||||
# 关闭详情页
|
||||
try:
|
||||
analyser.click(500, 470)
|
||||
analyser.click(*DETAIL_OUTSIDE_CLICK)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
@@ -469,7 +519,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
pass
|
||||
# 丢弃时,尽量关闭详情,避免停留在详情页
|
||||
try:
|
||||
analyser.click(500, 470)
|
||||
analyser.click(*DETAIL_OUTSIDE_CLICK)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
@@ -511,7 +561,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
analyser._log_kv("参与", "basic_join_decision:开始参与抽奖")
|
||||
except Exception:
|
||||
pass
|
||||
from .fudai_attend import attend_choujiang
|
||||
from ..fudai_attend import attend_choujiang
|
||||
|
||||
result = attend_choujiang(analyser)
|
||||
elapsed = time.time() - start_time
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,200 @@
|
||||
"""douyin_fudai_core_pkg.countdown_split - 福袋倒计时区域分割识别
|
||||
|
||||
从 get_fudai_contain 抽出的 _read_countdown_split 闭包:
|
||||
把倒计时区域分割成"分钟段"和"秒段",分别 OCR 后组合为 mm:ss。
|
||||
|
||||
签名:
|
||||
read_countdown_split(analyser, box, *, save_debug_images=False) -> str
|
||||
|
||||
返回 mm:ss(如 "03:25");识别失败返回空字符串。
|
||||
保留原行为和日志:日志 tag、warning level、错误兜底全部不变。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Tuple
|
||||
|
||||
|
||||
def _extract_digits(text: str, max_digits: int = 2) -> str:
|
||||
"""提取数字,最多 max_digits 位,取前 max_digits 位优先。"""
|
||||
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
|
||||
if len(digits) > max_digits:
|
||||
candidate = digits[:max_digits]
|
||||
if set(candidate) == {"0"} and digits.lstrip("0"):
|
||||
actual = digits.lstrip("0")[:max_digits]
|
||||
return actual.zfill(max_digits)
|
||||
return candidate
|
||||
if len(digits) == 1:
|
||||
return "0" + digits
|
||||
return digits
|
||||
|
||||
|
||||
def read_countdown_split(
|
||||
analyser,
|
||||
box: Tuple[int, int, int, int],
|
||||
*,
|
||||
save_debug_images: bool = False,
|
||||
) -> str:
|
||||
"""将倒计时区域分割成"分钟段"和"秒段",分别 OCR 识别,然后组合为 mm:ss。
|
||||
|
||||
倒计时格式通常是:XX:XX后开奖,其中前两位是分钟,中间两位是秒。
|
||||
分割:前 30% 为分钟数字框,中间 30% 为秒数字框(剩余 40% 是冒号 + "后开奖")。
|
||||
|
||||
Args:
|
||||
analyser: fudai_analyse 实例(提供 cut_pic / operation / _log_kv / y_pianyi)
|
||||
box: 倒计时区域 (x1, y1, x2, y2)
|
||||
save_debug_images: 是否保存调试截图(仅当全局开关启用时)
|
||||
|
||||
Returns:
|
||||
mm:ss 字符串(识别成功),空字符串(识别失败)
|
||||
"""
|
||||
try:
|
||||
from douyin.fudai.core.fudai_debug_utils import (
|
||||
_save_full_screenshot_with_ocr_region,
|
||||
)
|
||||
except Exception:
|
||||
_save_full_screenshot_with_ocr_region = None # type: ignore[assignment]
|
||||
|
||||
try:
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
except Exception:
|
||||
def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore
|
||||
return str(picname)
|
||||
|
||||
try:
|
||||
x1, y1, x2, y2 = box
|
||||
w = max(1, int(x2 - x1))
|
||||
# 优化:根据实际布局,倒计时通常是:分钟(2位数字框) + 冒号 + 秒(2位数字框) + 后开奖
|
||||
# 更精确的分割:前30%为分钟数字框,中间30%为秒数字框(剩余40%包含冒号和"后开奖")
|
||||
seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框
|
||||
seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框
|
||||
|
||||
# 保存调试截图(仅在配置启用时)
|
||||
if save_debug_images and _save_full_screenshot_with_ocr_region is not None:
|
||||
try:
|
||||
_save_full_screenshot_with_ocr_region(
|
||||
analyser,
|
||||
"福袋倒计时_分钟",
|
||||
(x1, y1, x1 + seg1, y2),
|
||||
analyser.y_pianyi,
|
||||
)
|
||||
_save_full_screenshot_with_ocr_region(
|
||||
analyser,
|
||||
"福袋倒计时_秒",
|
||||
(x1 + seg1, y1, x1 + seg1 + seg2, y2),
|
||||
analyser.y_pianyi,
|
||||
)
|
||||
except Exception as e_inner:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"保存倒计时调试截图失败",
|
||||
error=str(e_inner),
|
||||
error_type=type(e_inner).__name__,
|
||||
box=box,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 切割分钟区域(左侧)
|
||||
analyser.cut_pic(
|
||||
x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi
|
||||
)
|
||||
# 切割秒区域(中间,跳过冒号)
|
||||
analyser.cut_pic(
|
||||
x1 + seg1,
|
||||
y1,
|
||||
x1 + seg1 + seg2,
|
||||
y2,
|
||||
"",
|
||||
"福袋倒计时_秒",
|
||||
analyser.y_pianyi,
|
||||
)
|
||||
|
||||
# 并行执行两个 OCR 识别(使用轻量数字 OCR),优先预处理以提高识别率
|
||||
try:
|
||||
mm_name = preprocess_for_ocr(analyser, "福袋倒计时_分钟")
|
||||
ss_name = preprocess_for_ocr(analyser, "福袋倒计时_秒")
|
||||
except Exception:
|
||||
mm_name = "福袋倒计时_分钟"
|
||||
ss_name = "福袋倒计时_秒"
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_mm = executor.submit(
|
||||
analyser.operation.analyse_pic_digits, mm_name, 1
|
||||
)
|
||||
future_ss = executor.submit(
|
||||
analyser.operation.analyse_pic_digits, ss_name, 1
|
||||
)
|
||||
mm_raw = future_mm.result()
|
||||
ss_raw = future_ss.result()
|
||||
|
||||
mm = _extract_digits(mm_raw, max_digits=2)
|
||||
ss = _extract_digits(ss_raw, max_digits=2)
|
||||
|
||||
# 分割识别已经分别识别了分钟和秒,顺序是正确的,不需要交换纠正
|
||||
# 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果)
|
||||
try:
|
||||
mm_int = int(mm) if mm else 0
|
||||
ss_int = int(ss) if ss else 0
|
||||
if ss_int >= 60:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"验证",
|
||||
"分割识别:检测到秒数>=60(可能是识别错误)",
|
||||
mm=mm_int,
|
||||
ss=ss_int,
|
||||
mm_raw=mm_raw,
|
||||
ss_raw=ss_raw,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e_inner:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"验证倒计时数值失败",
|
||||
error=str(e_inner),
|
||||
error_type=type(e_inner).__name__,
|
||||
mm=mm,
|
||||
ss=ss,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if mm and ss:
|
||||
result = f"{mm}:{ss}"
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋倒计时",
|
||||
"分割识别成功",
|
||||
mm_raw=mm_raw,
|
||||
ss_raw=ss_raw,
|
||||
result=result,
|
||||
)
|
||||
except Exception as e_inner:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"错误",
|
||||
"记录倒计时识别成功日志失败",
|
||||
error=str(e_inner),
|
||||
error_type=type(e_inner).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return result
|
||||
except Exception as e_inner:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋倒计时",
|
||||
"分割识别失败",
|
||||
error=str(e_inner),
|
||||
error_type=type(e_inner).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
@@ -0,0 +1,111 @@
|
||||
"""douyin_fudai_core_pkg.cut_regions - 福袋详情区域截图准备
|
||||
|
||||
把 get_fudai_contain 中按 renwu 分 4 个分支的"内容/倒计时/价值"截图准备逻辑
|
||||
合并成一个 helper。4 个分支唯一的差异是 countdown_box,其它操作都一样。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Tuple, Optional
|
||||
|
||||
|
||||
def _select_countdown_box(renwu: int) -> Tuple[int, int, int, int]:
|
||||
"""根据任务数选 countdown_box 坐标常量。"""
|
||||
from douyin.fudai.core.coords import (
|
||||
COUNTDOWN_1010_1130,
|
||||
COUNTDOWN_1110_1230,
|
||||
COUNTDOWN_1140_1290,
|
||||
COUNTDOWN_1460_1580,
|
||||
)
|
||||
if renwu == 2:
|
||||
return COUNTDOWN_1110_1230
|
||||
if renwu == 1:
|
||||
return COUNTDOWN_1140_1290
|
||||
if renwu == 3:
|
||||
return COUNTDOWN_1010_1130
|
||||
return COUNTDOWN_1460_1580
|
||||
|
||||
|
||||
def cut_detail_regions(
|
||||
analyser,
|
||||
renwu: int,
|
||||
*,
|
||||
save_debug_images: bool = False,
|
||||
) -> Tuple[int, int, int, int]:
|
||||
"""根据 renwu 切割福袋详情的"内容/倒计时分钟/倒计时秒/价值"4 个区域。
|
||||
|
||||
倒计时区域内部还会按 30%/30% 比例分割成"分钟"和"秒"两段单独切。
|
||||
|
||||
Args:
|
||||
analyser: fudai_analyse 实例(提供 cut_pic / y_pianyi)
|
||||
renwu: 任务数量(1/2/3,其它视为默认)
|
||||
save_debug_images: 是否保存全屏带 OCR 区域标注的调试截图
|
||||
|
||||
Returns:
|
||||
countdown_box: 选中的倒计时区域 (x1, y1, x2, y2),供后续 _read_countdown_split 使用
|
||||
"""
|
||||
from douyin.fudai.core.coords import (
|
||||
VALUE_BOX_TARGET,
|
||||
CONTENT_BOX,
|
||||
)
|
||||
try:
|
||||
from douyin.fudai.core.fudai_debug_utils import (
|
||||
_save_full_screenshot_with_ocr_region,
|
||||
)
|
||||
except Exception:
|
||||
_save_full_screenshot_with_ocr_region = None # type: ignore[assignment]
|
||||
|
||||
countdown_box = _select_countdown_box(renwu)
|
||||
value_box = VALUE_BOX_TARGET
|
||||
|
||||
# 1. 福袋内容
|
||||
if save_debug_images and _save_full_screenshot_with_ocr_region is not None:
|
||||
try:
|
||||
_save_full_screenshot_with_ocr_region(
|
||||
analyser, "福袋内容", CONTENT_BOX, analyser.y_pianyi
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.cut_pic(*CONTENT_BOX, "", "福袋内容", analyser.y_pianyi)
|
||||
|
||||
# 2. 倒计时区域分割(前 30% 分钟 + 中间 30% 秒)
|
||||
x1, y1, x2, y2 = countdown_box
|
||||
w = max(1, int(x2 - x1))
|
||||
seg1 = max(1, int(w * 0.3)) # 前 30%:分钟数字框
|
||||
seg2 = max(1, int(w * 0.3)) # 中间 30%:秒数字框
|
||||
|
||||
if save_debug_images and _save_full_screenshot_with_ocr_region is not None:
|
||||
try:
|
||||
_save_full_screenshot_with_ocr_region(
|
||||
analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.cut_pic(
|
||||
x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi
|
||||
)
|
||||
|
||||
if save_debug_images and _save_full_screenshot_with_ocr_region is not None:
|
||||
try:
|
||||
_save_full_screenshot_with_ocr_region(
|
||||
analyser,
|
||||
"福袋倒计时_秒",
|
||||
(x1 + seg1, y1, x1 + seg1 + seg2, y2),
|
||||
analyser.y_pianyi,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.cut_pic(
|
||||
x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi
|
||||
)
|
||||
|
||||
# 3. 福袋价值
|
||||
if save_debug_images and _save_full_screenshot_with_ocr_region is not None:
|
||||
try:
|
||||
_save_full_screenshot_with_ocr_region(
|
||||
analyser, "福袋价值", value_box, analyser.y_pianyi
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi)
|
||||
|
||||
return countdown_box
|
||||
@@ -0,0 +1,165 @@
|
||||
"""douyin_fudai_core_pkg.heavy_ocr - 福袋详情按需补 OCR
|
||||
|
||||
从 get_fudai_contain 抽出的 _run_heavy_ocr 闭包:当轻量 OCR 漏字段时,
|
||||
按需调用更重的文本/数字模型补齐 task_list / content / countdown_mm /
|
||||
countdown_ss / value / button 共 6 个字段。
|
||||
|
||||
签名:
|
||||
run_heavy_ocr(analyser, fields) -> Dict[str, Any]
|
||||
|
||||
返回字典含成功补到的字段值 + "_duration_ms"。失败字段不进字典。
|
||||
所有日志、配置开关读取行为与原闭包一致。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Set
|
||||
|
||||
|
||||
def _read_disable_flag(analyser, attr_name: str, cfg_key: str) -> bool:
|
||||
"""读取 analyser 属性,无值再回退到 config.json。"""
|
||||
try:
|
||||
flag = bool(getattr(analyser, attr_name, False))
|
||||
except Exception:
|
||||
flag = False
|
||||
if flag:
|
||||
return True
|
||||
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
cfg_path = path_config.get_config_path()
|
||||
if cfg_path and os.path.exists(cfg_path):
|
||||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
return bool(cfg.get(cfg_key, False))
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def run_heavy_ocr(analyser, fields: Set[str]) -> Dict[str, Any]:
|
||||
"""按需补充较重的 OCR,避免默认就跑全量重模型。
|
||||
|
||||
Args:
|
||||
analyser: fudai_analyse 实例(提供 operation / _log_kv / 配置开关)
|
||||
fields: 需要补的字段集合,可包含 task_list / content / countdown_mm /
|
||||
countdown_ss / value / button
|
||||
|
||||
Returns:
|
||||
Dict 含成功识别到的字段;总耗时记在 "_duration_ms"。
|
||||
"""
|
||||
try:
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
except Exception:
|
||||
def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore
|
||||
return str(picname)
|
||||
|
||||
results: Dict[str, Any] = {}
|
||||
heavy_start = time.time()
|
||||
|
||||
def _safe_preprocess(name: str) -> str:
|
||||
try:
|
||||
return preprocess_for_ocr(analyser, name)
|
||||
except Exception:
|
||||
return name
|
||||
|
||||
# 任务列表:用于兜底检测观看任务(尊重配置开关)
|
||||
if "task_list" in fields:
|
||||
if _read_disable_flag(
|
||||
analyser,
|
||||
"fudai_disable_task_recognition",
|
||||
"fudai_disable_task_recognition",
|
||||
):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋", "跳过福袋任务列表OCR识别(配置启用)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
name_tl = _safe_preprocess("福袋任务列表")
|
||||
results["task_list"] = analyser.operation.analyse_pic_word(
|
||||
name_tl, 1
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 内容:使用更重的文本模型兜底(尊重配置开关)
|
||||
if "content" in fields:
|
||||
if _read_disable_flag(
|
||||
analyser,
|
||||
"fudai_disable_content_recognition",
|
||||
"fudai_disable_content_recognition",
|
||||
):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋", "跳过福袋内容OCR识别(配置启用)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
name_fc = _safe_preprocess("福袋内容")
|
||||
results["content"] = analyser.operation.analyse_pic_word(
|
||||
name_fc, 1
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 倒计时:先数字模型,失败再文本提取数字
|
||||
if "countdown_mm" in fields:
|
||||
mm_digits = _ocr_digits_with_fallback(analyser, "福袋倒计时_分钟")
|
||||
if mm_digits:
|
||||
results["countdown_mm"] = mm_digits
|
||||
|
||||
if "countdown_ss" in fields:
|
||||
ss_digits = _ocr_digits_with_fallback(analyser, "福袋倒计时_秒")
|
||||
if ss_digits:
|
||||
results["countdown_ss"] = ss_digits
|
||||
|
||||
# 价值:重模型兜底一次,兼容带符号文本
|
||||
if "value" in fields:
|
||||
try:
|
||||
name_val = _safe_preprocess("福袋价值")
|
||||
raw_val = analyser.operation.analyse_pic_word(name_val, 0)
|
||||
results["value"] = str(raw_val or "")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 按钮状态:重模型兜底,避免轻量误判
|
||||
if "button" in fields:
|
||||
try:
|
||||
name_btn = _safe_preprocess("参与按钮")
|
||||
results["button"] = analyser.operation.analyse_pic_word(name_btn, 1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
results["_duration_ms"] = round((time.time() - heavy_start) * 1000, 1)
|
||||
except Exception:
|
||||
pass
|
||||
return results
|
||||
|
||||
|
||||
def _ocr_digits_with_fallback(analyser, picname: str) -> str:
|
||||
"""先 analyse_pic_digits,失败再 analyse_pic_word,提取数字。
|
||||
|
||||
返回提取到的数字字符串;都失败返回 ""。
|
||||
"""
|
||||
digits = ""
|
||||
try:
|
||||
raw = analyser.operation.analyse_pic_digits(picname, 1)
|
||||
digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
|
||||
except Exception:
|
||||
pass
|
||||
if not digits:
|
||||
try:
|
||||
raw = analyser.operation.analyse_pic_word(picname, 1)
|
||||
digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
|
||||
except Exception:
|
||||
pass
|
||||
return digits
|
||||
@@ -20,11 +20,6 @@ class _FudaiOcrExecutorState:
|
||||
_fudai_ocr_executor_state = _FudaiOcrExecutorState()
|
||||
|
||||
|
||||
|
||||
|
||||
_fudai_ocr_executor_state = _FudaiOcrExecutorState()
|
||||
|
||||
|
||||
def _get_fudai_ocr_executor(optimal_workers: int) -> ThreadPoolExecutor:
|
||||
"""获取复用的 OCR 线程池;如线程数变化则重建。"""
|
||||
state = _fudai_ocr_executor_state
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
"""douyin_fudai_core_pkg.ocr_tasks - 福袋详情 7 个并行 OCR 子任务
|
||||
|
||||
把 get_fudai_contain 中 7 个 ocr_* 闭包封装成一个类。每个方法对应
|
||||
ThreadPoolExecutor 的一个并行任务:
|
||||
|
||||
OcrTaskRunner.ocr_task_list 福袋任务列表
|
||||
OcrTaskRunner.ocr_content 福袋内容
|
||||
OcrTaskRunner.ocr_countdown_mm 倒计时分钟(数字模型)
|
||||
OcrTaskRunner.ocr_countdown_ss 倒计时秒(数字模型)
|
||||
OcrTaskRunner.ocr_value 福袋价值
|
||||
OcrTaskRunner.ocr_button 参与按钮状态
|
||||
OcrTaskRunner.ocr_live_room_title 直播间标题
|
||||
|
||||
每个方法的 finally 把单项耗时(ms)写入共享 dict(用 lock 保护),便于
|
||||
主流程后续聚合输出性能日志。所有日志、配置开关读取行为与原闭包一致。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
|
||||
# OCR 按钮关键词列表(识别到任一即可短路返回,省 50% 时间)
|
||||
_BUTTON_KEYWORDS = (
|
||||
"参与成功",
|
||||
"还需看播",
|
||||
"评论",
|
||||
"参与抽奖",
|
||||
"开始观看",
|
||||
"参与",
|
||||
"加入粉丝团",
|
||||
"粉丝团",
|
||||
"等待开奖",
|
||||
"未达成",
|
||||
)
|
||||
|
||||
|
||||
def _safe_preprocess(analyser, name: str) -> str:
|
||||
"""preprocess_for_ocr 的安全包装:失败时返回原 name。"""
|
||||
try:
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
return preprocess_for_ocr(analyser, name)
|
||||
except Exception:
|
||||
return name
|
||||
|
||||
|
||||
class OcrTaskRunner:
|
||||
"""7 个并行 OCR 子任务的运行器。
|
||||
|
||||
Args:
|
||||
analyser: fudai_analyse 实例
|
||||
perf_durations: 共享 dict,存放各任务的耗时(ms)
|
||||
perf_lock: 保护 perf_durations 的 Lock
|
||||
disable_content_recognition: 主流程已经读到的内容 OCR 开关(避免每次任务再读一次)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
analyser,
|
||||
perf_durations: Dict[str, float],
|
||||
perf_lock: threading.Lock,
|
||||
*,
|
||||
disable_content_recognition: bool = False,
|
||||
):
|
||||
self.analyser = analyser
|
||||
self.durations = perf_durations
|
||||
self.lock = perf_lock
|
||||
self.disable_content_recognition = bool(disable_content_recognition)
|
||||
|
||||
# ============================================================
|
||||
# 内部工具
|
||||
# ============================================================
|
||||
|
||||
def _record_duration(self, key: str, start: float) -> None:
|
||||
try:
|
||||
dur = round((time.time() - start) * 1000, 1)
|
||||
with self.lock:
|
||||
self.durations[key] = dur
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _log_warn(self, msg: str, exc: BaseException) -> None:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"错误",
|
||||
msg,
|
||||
error=str(exc),
|
||||
error_type=type(exc).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ============================================================
|
||||
# 7 个并行 OCR 子任务
|
||||
# ============================================================
|
||||
|
||||
def ocr_task_list(self) -> Optional[str]:
|
||||
"""OCR 识别福袋任务列表(用于检测观看任务,尊重配置开关)。"""
|
||||
start = time.time()
|
||||
try:
|
||||
from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import (
|
||||
_read_disable_flag,
|
||||
)
|
||||
disable = _read_disable_flag(
|
||||
self.analyser,
|
||||
"fudai_disable_task_recognition",
|
||||
"fudai_disable_task_recognition",
|
||||
)
|
||||
if disable:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"福袋", "跳过福袋任务列表OCR识别(配置启用)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
name_tl = _safe_preprocess(self.analyser, "福袋任务列表")
|
||||
return self.analyser.operation.analyse_pic_word(name_tl, 0)
|
||||
except Exception as e:
|
||||
self._log_warn("OCR识别任务列表失败", e)
|
||||
return None
|
||||
finally:
|
||||
self._record_duration("ocr_task_list", start)
|
||||
|
||||
def ocr_content(self) -> Optional[str]:
|
||||
"""OCR 识别福袋内容。"""
|
||||
start = time.time()
|
||||
try:
|
||||
if self.disable_content_recognition:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"福袋", "跳过福袋内容OCR识别(配置启用)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
name_fc = _safe_preprocess(self.analyser, "福袋内容")
|
||||
return self.analyser.operation.analyse_pic_word(name_fc, 0)
|
||||
except Exception as e:
|
||||
self._log_warn("OCR识别福袋内容失败", e)
|
||||
return None
|
||||
finally:
|
||||
self._record_duration("ocr_content", start)
|
||||
|
||||
def ocr_countdown_mm(self) -> Optional[str]:
|
||||
"""OCR 识别福袋倒计时分钟(纯数字模型,无回退)。"""
|
||||
start = time.time()
|
||||
try:
|
||||
raw = str(
|
||||
self.analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 0) or ""
|
||||
)
|
||||
return "".join(ch for ch in raw if ch.isdigit())
|
||||
except Exception as e:
|
||||
self._log_warn("OCR识别倒计时分钟失败", e)
|
||||
return None
|
||||
finally:
|
||||
self._record_duration("ocr_countdown_mm", start)
|
||||
|
||||
def ocr_countdown_ss(self) -> Optional[str]:
|
||||
"""OCR 识别福袋倒计时秒(纯数字模型,无回退)。"""
|
||||
start = time.time()
|
||||
try:
|
||||
raw = str(
|
||||
self.analyser.operation.analyse_pic_digits("福袋倒计时_秒", 0) or ""
|
||||
)
|
||||
return "".join(ch for ch in raw if ch.isdigit())
|
||||
except Exception as e:
|
||||
self._log_warn("OCR识别倒计时秒失败", e)
|
||||
return None
|
||||
finally:
|
||||
self._record_duration("ocr_countdown_ss", start)
|
||||
|
||||
def ocr_value(self) -> Optional[str]:
|
||||
"""OCR 识别福袋价值(普通文本模型,支持小数点)。"""
|
||||
start = time.time()
|
||||
try:
|
||||
name_val = _safe_preprocess(self.analyser, "福袋价值")
|
||||
word_raw = str(
|
||||
self.analyser.operation.analyse_pic_word(name_val, 0) or ""
|
||||
)
|
||||
return word_raw
|
||||
except Exception as e:
|
||||
self._log_warn("OCR识别福袋价值失败", e)
|
||||
return None
|
||||
finally:
|
||||
self._record_duration("ocr_value", start)
|
||||
|
||||
def ocr_button(self) -> Optional[str]:
|
||||
"""OCR 识别参与按钮状态(关键词短路,节省 50% OCR 时间)。
|
||||
|
||||
注意:原闭包没有 finally 计时(按钮属于同步路径),保留这个差异。
|
||||
"""
|
||||
try:
|
||||
name_btn = _safe_preprocess(self.analyser, "参与按钮")
|
||||
# 模式 0 试一次:若识别到关键词直接返回
|
||||
button_text = str(
|
||||
self.analyser.operation.analyse_pic_word(name_btn, 0) or ""
|
||||
)
|
||||
if button_text and any(k in button_text for k in _BUTTON_KEYWORDS):
|
||||
return button_text
|
||||
# 模式 0 完全失败时再试一次(保留旧逻辑:仍是模式 0)
|
||||
if not button_text:
|
||||
button_text = str(
|
||||
self.analyser.operation.analyse_pic_word(name_btn, 0) or ""
|
||||
)
|
||||
return button_text
|
||||
except Exception as e:
|
||||
self._log_warn("OCR识别参与按钮失败", e)
|
||||
return None
|
||||
|
||||
def ocr_live_room_title(self) -> Tuple[str, str]:
|
||||
"""OCR 识别直播间标题,返回 (title, raw_text)。"""
|
||||
start = time.time()
|
||||
try:
|
||||
from douyin.fudai.core.fudai_detail_room_title import (
|
||||
_ocr_try_room_title,
|
||||
)
|
||||
return _ocr_try_room_title(self.analyser, "live_room_title_mid", 0)
|
||||
except Exception as e:
|
||||
self._log_warn("OCR识别直播间标题失败", e)
|
||||
return "", ""
|
||||
finally:
|
||||
self._record_duration("ocr_live_room_title", start)
|
||||
|
||||
|
||||
class OcrTaskRunnerFallback:
|
||||
"""主并行 OCR 失败时的备用任务集。
|
||||
|
||||
与 OcrTaskRunner 区别:
|
||||
- 不记录 perf_durations(备用路径调用频率低,无性能追踪需求)
|
||||
- countdown_mm / countdown_ss 直接返回原始 OCR 结果(不做数字提取)
|
||||
- 日志里把 tag 改为"备用OCR..."
|
||||
|
||||
Args:
|
||||
analyser: fudai_analyse 实例
|
||||
disable_content_recognition: 主流程已读到的内容 OCR 开关
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
analyser,
|
||||
*,
|
||||
disable_content_recognition: bool = False,
|
||||
):
|
||||
self.analyser = analyser
|
||||
self.disable_content_recognition = bool(disable_content_recognition)
|
||||
|
||||
def _log_warn(self, msg: str, exc: BaseException) -> None:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"错误",
|
||||
msg,
|
||||
error=str(exc),
|
||||
error_type=type(exc).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def ocr_task_list(self) -> Optional[str]:
|
||||
try:
|
||||
from douyin.fudai.douyin_fudai_core_pkg.heavy_ocr import (
|
||||
_read_disable_flag,
|
||||
)
|
||||
disable = _read_disable_flag(
|
||||
self.analyser,
|
||||
"fudai_disable_task_recognition",
|
||||
"fudai_disable_task_recognition",
|
||||
)
|
||||
if disable:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"福袋", "跳过备用福袋任务列表OCR识别(配置启用)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
name_tl = _safe_preprocess(self.analyser, "福袋任务列表")
|
||||
return self.analyser.operation.analyse_pic_word(name_tl, 0)
|
||||
except Exception as e:
|
||||
self._log_warn("备用OCR识别任务列表失败", e)
|
||||
return None
|
||||
|
||||
def ocr_content(self) -> Optional[str]:
|
||||
if self.disable_content_recognition:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"福袋", "跳过备用福袋内容OCR识别(配置启用)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
try:
|
||||
return self.analyser.operation.analyse_pic_word("福袋内容", 0)
|
||||
except Exception as e:
|
||||
self._log_warn("备用OCR识别福袋内容失败", e)
|
||||
return None
|
||||
|
||||
def ocr_countdown_mm(self):
|
||||
try:
|
||||
return self.analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 0)
|
||||
except Exception as e:
|
||||
self._log_warn("备用OCR识别倒计时分钟失败", e)
|
||||
return None
|
||||
|
||||
def ocr_countdown_ss(self):
|
||||
try:
|
||||
return self.analyser.operation.analyse_pic_digits("福袋倒计时_秒", 0)
|
||||
except Exception as e:
|
||||
self._log_warn("备用OCR识别倒计时秒失败", e)
|
||||
return None
|
||||
|
||||
def ocr_value(self):
|
||||
try:
|
||||
return self.analyser.operation.analyse_pic_word("福袋价值", 0)
|
||||
except Exception as e:
|
||||
self._log_warn("备用OCR识别福袋价值失败", e)
|
||||
return None
|
||||
|
||||
def ocr_button(self) -> Optional[str]:
|
||||
try:
|
||||
name_btn = _safe_preprocess(self.analyser, "参与按钮")
|
||||
button_text = str(
|
||||
self.analyser.operation.analyse_pic_word(name_btn, 0) or ""
|
||||
)
|
||||
if not button_text or not any(
|
||||
k in button_text for k in _BUTTON_KEYWORDS
|
||||
):
|
||||
button_text = str(
|
||||
self.analyser.operation.analyse_pic_word(name_btn, 0) or ""
|
||||
)
|
||||
return button_text
|
||||
except Exception as e:
|
||||
self._log_warn("备用OCR识别参与按钮失败", e)
|
||||
return None
|
||||
|
||||
@@ -79,8 +79,11 @@ class FudaiDetailVerifier:
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
pic = Image.open(pic_path)
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
try:
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
finally:
|
||||
pic.close()
|
||||
|
||||
width, height = pic_rgb.size
|
||||
rx = int(
|
||||
|
||||
@@ -7,11 +7,14 @@ from __future__ import annotations
|
||||
|
||||
# pylint: disable=E1101
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
|
||||
def detect_by_template(analyser, rx: int, pic: Image.Image, region: Dict) -> Optional[int]:
|
||||
"""使用模板匹配在指定区域查找福袋图标(优化版:多方法+预处理)
|
||||
|
||||
@@ -452,8 +452,6 @@ class FudaiDetector:
|
||||
pass
|
||||
|
||||
return detected_x
|
||||
if found_x is not None:
|
||||
break # 找到后退出offset_y循环
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -62,18 +62,21 @@ class FudaiImageAcquirer:
|
||||
# 读取截图
|
||||
try:
|
||||
pic = Image.open(self.screenshot_path)
|
||||
pic.load()
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 图像获取",
|
||||
"成功",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
size=f"{pic.size[0]}x{pic.size[1]}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return pic.convert("RGBA")
|
||||
pic.load()
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 图像获取",
|
||||
"成功",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
size=f"{pic.size[0]}x{pic.size[1]}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return pic.convert("RGBA")
|
||||
finally:
|
||||
pic.close()
|
||||
except Exception:
|
||||
return None
|
||||
except Exception as e:
|
||||
|
||||
@@ -39,7 +39,7 @@ def check_have_fudai_with_ready_screenshot_optimized(
|
||||
screenshot_ready: 是否已有可用截图
|
||||
|
||||
返回:
|
||||
福袋X坐标(1080基准),未找到返回False
|
||||
福袋X坐标(1080基准),未找到返回 0
|
||||
"""
|
||||
# 只检测,不点击(避免与 find_and_open_fudai_detail 重复点击)
|
||||
try:
|
||||
@@ -47,13 +47,13 @@ def check_have_fudai_with_ready_screenshot_optimized(
|
||||
pic = acquirer.acquire_screenshot(force_refresh=not screenshot_ready)
|
||||
|
||||
if pic is None:
|
||||
return False
|
||||
return 0
|
||||
|
||||
detector = FudaiDetector(analyser)
|
||||
detected_x, _detect_method = detector.detect(pic)
|
||||
|
||||
if detected_x is not None:
|
||||
return int(detected_x)
|
||||
return False
|
||||
return 0
|
||||
except Exception:
|
||||
return False
|
||||
@@ -26,8 +26,6 @@ from ._common import (
|
||||
_debug_save_queue,
|
||||
_debug_save_shutdown_event,
|
||||
_debug_save_worker_lock,
|
||||
_LOGGER,
|
||||
_mgr_log,
|
||||
)
|
||||
from . import _common as _state
|
||||
from .paths import ensure_debug_captures_dir
|
||||
@@ -353,8 +351,3 @@ def _ensure_debug_save_worker_started() -> None:
|
||||
t = threading.Thread(target=_debug_save_loop, name="debug-save-worker", daemon=True)
|
||||
t.start()
|
||||
_state._debug_save_worker_started = True
|
||||
|
||||
|
||||
# 注册 atexit 清理函数(仅注册一次)
|
||||
import atexit
|
||||
atexit.register(shutdown_debug_save_worker)
|
||||
@@ -4,7 +4,6 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
@@ -11,6 +11,8 @@ from datetime import datetime
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from ._common import _mgr_log
|
||||
|
||||
|
||||
def get_ocr_dir() -> str:
|
||||
"""获取OCR目录路径"""
|
||||
|
||||
@@ -138,8 +138,11 @@ def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool:
|
||||
try:
|
||||
if not os.path.exists(source_path):
|
||||
return False
|
||||
image = Image.open(source_path)
|
||||
return save_latest_attempt(image, operation_type)
|
||||
_raw = Image.open(source_path)
|
||||
try:
|
||||
return save_latest_attempt(_raw, operation_type)
|
||||
finally:
|
||||
_raw.close()
|
||||
except Exception as e:
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 从文件保存 latest_attempt.png 失败: {e}")
|
||||
@@ -163,8 +166,11 @@ def save_success_from_file(source_path: str, operation_type: str = "") -> bool:
|
||||
try:
|
||||
if not os.path.exists(source_path):
|
||||
return False
|
||||
image = Image.open(source_path)
|
||||
return save_last_success(image, operation_type)
|
||||
_raw = Image.open(source_path)
|
||||
try:
|
||||
return save_last_success(_raw, operation_type)
|
||||
finally:
|
||||
_raw.close()
|
||||
except Exception as e:
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 从文件保存 last_success.png 失败: {e}")
|
||||
|
||||
@@ -8,12 +8,9 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional, Tuple
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import logging
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
@@ -21,17 +18,22 @@ from PIL import Image, ImageDraw, ImageFont
|
||||
from douyin.core import path_config
|
||||
|
||||
from ._common import (
|
||||
_async_save_counters_lock,
|
||||
_debug_save_queue,
|
||||
_LOGGER,
|
||||
_mgr_log,
|
||||
_SKIP_DEBUG_SAVE_IN_HOTLOOPS,
|
||||
)
|
||||
from . import _common as _state
|
||||
from .cleanup import (
|
||||
_OPERATION_TYPE_CN,
|
||||
_PICNAME_CN,
|
||||
_STEP_CN,
|
||||
_EXTRA_INFO_KEY_CN,
|
||||
cleanup_debug_captures,
|
||||
count_debug_captures_files,
|
||||
)
|
||||
from .paths import (
|
||||
ensure_debug_captures_dir,
|
||||
get_category_for_picname,
|
||||
get_debug_captures_dir,
|
||||
get_debug_captures_base_dir,
|
||||
)
|
||||
from .async_save import _ensure_debug_save_worker_started
|
||||
|
||||
@@ -726,6 +728,3 @@ def save_debug_image( # type: ignore
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
# 结束 save_debug_image 的主逻辑,返回 None 表示保存失败
|
||||
return None
|
||||
@@ -14,19 +14,17 @@
|
||||
from .log_formatter import (
|
||||
format_debug_log,
|
||||
format_action_log,
|
||||
format_call_stack,
|
||||
format_parameters,
|
||||
format_variables,
|
||||
format_exception,
|
||||
add_separators,
|
||||
format_error_log,
|
||||
add_colors,
|
||||
beautify_log_output,
|
||||
colorize_log_line,
|
||||
)
|
||||
|
||||
# 性能追踪模块
|
||||
from .performance_tracker import PerformanceTracker
|
||||
|
||||
# 错误与调试日志(合并到 internal_loggers)
|
||||
from .internal_loggers import ErrorLogger, DebugLogger, _get_debug_logger
|
||||
from .internal_loggers import ErrorLogger, DebugLogger
|
||||
|
||||
# 行为日志模块(含 track_action 装饰器)
|
||||
from .action_logger import ActionLogger, track_action
|
||||
@@ -38,12 +36,10 @@ __all__ = [
|
||||
# 格式化函数
|
||||
"format_debug_log",
|
||||
"format_action_log",
|
||||
"format_call_stack",
|
||||
"format_parameters",
|
||||
"format_variables",
|
||||
"format_exception",
|
||||
"add_separators",
|
||||
"format_error_log",
|
||||
"add_colors",
|
||||
"beautify_log_output",
|
||||
"colorize_log_line",
|
||||
# 类
|
||||
"PerformanceTracker",
|
||||
"ErrorLogger",
|
||||
@@ -52,5 +48,4 @@ __all__ = [
|
||||
"LoggingWrapper",
|
||||
# 装饰器和工具函数
|
||||
"track_action",
|
||||
"_get_debug_logger",
|
||||
]
|
||||
@@ -95,15 +95,6 @@ class ActionLogger:
|
||||
msg = format_action_log(operation, details or "", **extra)
|
||||
_logger.info(msg)
|
||||
|
||||
def log_ocr(self, region: str, result: str, elapsed: Optional[float] = None) -> None:
|
||||
self.log_operation("OCR", f"region={region} result={result}", elapsed=elapsed)
|
||||
|
||||
def log_decision(self, decision: str, elapsed: Optional[float] = None) -> None:
|
||||
self.log_operation("Decision", decision, elapsed=elapsed)
|
||||
|
||||
def log_state_change(self, before: str, after: str, elapsed: Optional[float] = None) -> None:
|
||||
self.log_operation("StateChange", f"{before}->{after}", elapsed=elapsed)
|
||||
|
||||
def log_step(self, name: str, elapsed: Optional[float] = None) -> None:
|
||||
self.log_operation("Step", name, elapsed=elapsed)
|
||||
|
||||
|
||||
@@ -146,32 +146,6 @@ class DebugLogger:
|
||||
def __init__(self, enabled: bool = True) -> None:
|
||||
self.enabled = enabled
|
||||
|
||||
def log_function_entry(
|
||||
self, func_name: str, *args: Any, **kwargs: Any
|
||||
) -> None:
|
||||
if not self.enabled:
|
||||
return
|
||||
line = format_debug_log(
|
||||
f"FunctionEntry: {func_name}",
|
||||
level="DEBUG",
|
||||
args=args,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
_debug_module_logger.debug(line)
|
||||
|
||||
def log_function_exit(
|
||||
self, func_name: str, retval: Any, elapsed: float
|
||||
) -> None:
|
||||
if not self.enabled:
|
||||
return
|
||||
line = format_debug_log(
|
||||
f"FunctionExit: {func_name}",
|
||||
level="DEBUG",
|
||||
elapsed_seconds=elapsed,
|
||||
return_value=retval,
|
||||
)
|
||||
_debug_module_logger.debug(line)
|
||||
|
||||
def log_variable(self, name: str, value: Any) -> None:
|
||||
if not self.enabled:
|
||||
return
|
||||
@@ -180,15 +154,6 @@ class DebugLogger:
|
||||
)
|
||||
_debug_module_logger.debug(line)
|
||||
|
||||
def log_call_stack(self) -> None:
|
||||
if not self.enabled:
|
||||
return
|
||||
stack = traceback.format_stack()
|
||||
line = format_debug_log(
|
||||
"CallStack", level="DEBUG", stack="".join(stack)
|
||||
)
|
||||
_debug_module_logger.debug(line)
|
||||
|
||||
def log_exception(
|
||||
self, exc: BaseException, context: Optional[Dict[str, Any]] = None
|
||||
) -> None:
|
||||
@@ -221,8 +186,4 @@ class DebugLogger:
|
||||
_perf.get_elapsed(name)
|
||||
|
||||
|
||||
def _get_debug_logger() -> DebugLogger:
|
||||
return DebugLogger(True)
|
||||
|
||||
|
||||
__all__ = ["ErrorLogger", "DebugLogger", "_get_debug_logger"]
|
||||
__all__ = ["ErrorLogger", "DebugLogger"]
|
||||
@@ -127,7 +127,6 @@ def format_action_log(action: str, details: Optional[str] = None, **fields: Any)
|
||||
def format_error_log(
|
||||
message: str, level: str = "ERROR", tag: Optional[str] = None, **fields: Any
|
||||
) -> str:
|
||||
"""格式化错误日志"""
|
||||
parts = []
|
||||
if tag:
|
||||
parts.append(f"[{tag}]")
|
||||
@@ -139,39 +138,7 @@ def format_error_log(
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def format_call_stack(stack: Optional[List[str]] = None) -> str:
|
||||
if not stack:
|
||||
return ""
|
||||
return "\n".join(stack)
|
||||
|
||||
|
||||
def format_parameters(params: Dict[str, Any]) -> str:
|
||||
if not params:
|
||||
return ""
|
||||
return " ".join(f"{k}={v}" for k, v in params.items())
|
||||
|
||||
|
||||
def format_variables(vars: Dict[str, Any]) -> str:
|
||||
if not vars:
|
||||
return ""
|
||||
return " ".join(f"{k}={v}" for k, v in vars.items())
|
||||
|
||||
|
||||
def format_exception(exc: BaseException) -> str:
|
||||
import traceback
|
||||
|
||||
return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
|
||||
|
||||
|
||||
def add_separators(text: str, label: Optional[str] = None) -> str:
|
||||
if not label:
|
||||
label = ""
|
||||
sep = "=" * 80
|
||||
return f"{sep}\n {label} \n{sep}\n{text}\n{sep}"
|
||||
|
||||
|
||||
def add_colors(text: str, color: str = "green") -> str:
|
||||
# 简易颜色支持,只有在控制台启用时有效
|
||||
colors = {
|
||||
"red": "\033[31m",
|
||||
"green": "\033[32m",
|
||||
@@ -185,48 +152,19 @@ def add_colors(text: str, color: str = "green") -> str:
|
||||
|
||||
|
||||
def beautify_log_output(line: str) -> str:
|
||||
"""
|
||||
美化日志输出,为GUI显示优化格式。
|
||||
|
||||
对日志行进行美化处理,包括:
|
||||
- 提取关键信息
|
||||
- 简化冗余部分
|
||||
- 突出重要信息
|
||||
"""
|
||||
if not line or not line.strip():
|
||||
return line
|
||||
|
||||
# 对于GUI显示,我们保持相对简洁但有用的格式
|
||||
# 移除过长的堆栈跟踪,但保留关键错误信息
|
||||
if len(line) > 500:
|
||||
# 如果行太长,进行截断
|
||||
parts = line.split()
|
||||
if len(parts) > 10:
|
||||
# 保留前10个部分和最后的部分
|
||||
shortened = " ".join(parts[:8]) + " ... " + " ".join(parts[-2:])
|
||||
return shortened
|
||||
|
||||
# 突出显示重要关键字
|
||||
important_keywords = ["ERROR", "CRITICAL", "FAILED", "EXCEPTION"]
|
||||
for keyword in important_keywords:
|
||||
if keyword in line.upper():
|
||||
# 在GUI中我们不添加颜色代码,因为GUI使用标签系统
|
||||
# 这里只是为了标识重要行
|
||||
break
|
||||
|
||||
return line
|
||||
|
||||
|
||||
def colorize_log_line(line: str) -> str:
|
||||
"""
|
||||
为日志行添加颜色代码(用于控制台输出)。
|
||||
|
||||
基于日志级别和内容为日志行添加ANSI颜色代码。
|
||||
"""
|
||||
if not line:
|
||||
return line
|
||||
|
||||
# 检查日志级别并应用相应颜色
|
||||
if "[DEBUG]" in line:
|
||||
return add_colors(line, "blue")
|
||||
elif "[INFO]" in line:
|
||||
@@ -236,14 +174,7 @@ def colorize_log_line(line: str) -> str:
|
||||
elif "[ERROR]" in line:
|
||||
return add_colors(line, "red")
|
||||
elif "[CRITICAL]" in line:
|
||||
return add_colors(line, "red") # 红色加粗可以通过多次应用实现
|
||||
|
||||
# 检查特殊内容
|
||||
if "elapsed_seconds=" in line or "耗时" in line:
|
||||
return add_colors(line, "green")
|
||||
if "EXCEPTION" in line.upper():
|
||||
return add_colors(line, "red")
|
||||
|
||||
return line
|
||||
|
||||
|
||||
@@ -251,11 +182,6 @@ __all__ = [
|
||||
"format_debug_log",
|
||||
"format_action_log",
|
||||
"format_error_log",
|
||||
"format_call_stack",
|
||||
"format_parameters",
|
||||
"format_variables",
|
||||
"format_exception",
|
||||
"add_separators",
|
||||
"add_colors",
|
||||
"beautify_log_output",
|
||||
"colorize_log_line",
|
||||
|
||||
@@ -33,17 +33,6 @@ class PerformanceTracker:
|
||||
return 0.0
|
||||
return time.perf_counter() - start
|
||||
|
||||
def track_function(self, func: Callable) -> Callable:
|
||||
def wrapper(*args, **kwargs):
|
||||
name = func.__qualname__
|
||||
timer = self.start_timer(name)
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
return result
|
||||
finally:
|
||||
self.end_timer(timer)
|
||||
return wrapper
|
||||
|
||||
def track_step(self, name: str) -> Callable:
|
||||
def decorator(func: Callable) -> Callable:
|
||||
def inner(*args, **kwargs):
|
||||
|
||||
@@ -22,7 +22,7 @@ import logging
|
||||
import threading
|
||||
import inspect
|
||||
import traceback
|
||||
from typing import Optional, Dict, Any, Callable
|
||||
from typing import Optional, Dict, Any
|
||||
from functools import wraps
|
||||
from contextlib import contextmanager
|
||||
|
||||
@@ -356,174 +356,6 @@ def get_unified_logger(name: Optional[str] = None) -> logging.Logger:
|
||||
return logger
|
||||
|
||||
|
||||
@contextmanager
|
||||
def trace_context(trace_id: Optional[str] = None, **mdc_context):
|
||||
"""上下文管理器:为代码块设置traceId和MDC上下文"""
|
||||
old_trace_id = MDC.get_trace_id()
|
||||
old_mdc = MDC.get_all()
|
||||
|
||||
# 设置新的traceId
|
||||
if trace_id is None:
|
||||
trace_id = MDC.set_trace_id()
|
||||
else:
|
||||
MDC.set_trace_id(trace_id)
|
||||
|
||||
# 设置其他MDC上下文
|
||||
for key, value in mdc_context.items():
|
||||
MDC.put(key, value)
|
||||
|
||||
try:
|
||||
yield trace_id
|
||||
finally:
|
||||
# 恢复旧的MDC
|
||||
MDC.clear()
|
||||
if old_trace_id:
|
||||
MDC.set_trace_id(old_trace_id)
|
||||
for key, value in old_mdc.items():
|
||||
MDC.put(key, value)
|
||||
|
||||
|
||||
def log_method_entry_exit(
|
||||
logger: Optional[logging.Logger] = None,
|
||||
log_args: bool = True,
|
||||
log_result: bool = False,
|
||||
log_duration: bool = True,
|
||||
min_duration: float = 0.0,
|
||||
):
|
||||
"""装饰器:自动记录方法入口、出口、参数、返回值、耗时"""
|
||||
|
||||
def decorator(func: Callable) -> Callable:
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
if logger is None:
|
||||
_logger = get_unified_logger()
|
||||
else:
|
||||
_logger = logger
|
||||
|
||||
func_name = f"{func.__module__}.{func.__name__}"
|
||||
start_time = time.time()
|
||||
|
||||
# 记录方法入口
|
||||
if log_args:
|
||||
args_str = ", ".join([str(arg)[:100] for arg in args[:3]])
|
||||
kwargs_str = ", ".join(
|
||||
[f"{k}={str(v)[:50]}" for k, v in list(kwargs.items())[:3]]
|
||||
)
|
||||
call_info = (
|
||||
f"{func_name}({args_str}{', ' + kwargs_str if kwargs_str else ''})"
|
||||
)
|
||||
if len(args) > 3 or len(kwargs) > 3:
|
||||
call_info += "..."
|
||||
_logger.info(f"[方法入口] {call_info}")
|
||||
|
||||
# 执行方法
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
elapsed = time.time() - start_time
|
||||
|
||||
# 记录方法出口
|
||||
exit_msg = f"[方法出口] {func_name}"
|
||||
if log_duration and elapsed >= min_duration:
|
||||
exit_msg += f" 耗时: {elapsed:.3f}秒"
|
||||
if log_result:
|
||||
result_str = str(result)[:200]
|
||||
exit_msg += f" 返回值: {result_str}"
|
||||
|
||||
_logger.info(exit_msg)
|
||||
|
||||
return result
|
||||
except Exception as e:
|
||||
elapsed = time.time() - start_time
|
||||
_logger.error(
|
||||
f"[方法异常] {func_name} 发生异常: {type(e).__name__}: {str(e)} "
|
||||
f"耗时: {elapsed:.3f}秒",
|
||||
exc_info=True,
|
||||
)
|
||||
raise
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def log_external_call(
|
||||
target: str,
|
||||
request_params: Optional[Dict[str, Any]] = None,
|
||||
response_result: Optional[Any] = None,
|
||||
success: bool = True,
|
||||
duration: Optional[float] = None,
|
||||
logger: Optional[logging.Logger] = None,
|
||||
):
|
||||
"""记录外部调用(API调用、数据库查询等)"""
|
||||
if logger is None:
|
||||
logger = get_unified_logger()
|
||||
|
||||
# 脱敏请求参数
|
||||
if request_params:
|
||||
request_params = SensitiveDataMasker.mask_dict(request_params)
|
||||
|
||||
msg_parts = [f"[外部调用] {target}"]
|
||||
|
||||
if request_params:
|
||||
params_str = ", ".join(
|
||||
[f"{k}={v}" for k, v in list(request_params.items())[:5]]
|
||||
)
|
||||
if len(request_params) > 5:
|
||||
params_str += "..."
|
||||
msg_parts.append(f"请求参数: {params_str}")
|
||||
|
||||
if response_result is not None:
|
||||
result_str = str(response_result)[:200]
|
||||
msg_parts.append(f"响应结果: {result_str}")
|
||||
|
||||
if duration is not None:
|
||||
msg_parts.append(f"耗时: {duration:.3f}秒")
|
||||
|
||||
msg_parts.append(f"状态: {'成功' if success else '失败'}")
|
||||
|
||||
level = logging.INFO if success else logging.ERROR
|
||||
logger.log(level, " | ".join(msg_parts))
|
||||
|
||||
|
||||
def log_decision_point(
|
||||
decision: str,
|
||||
condition: Optional[str] = None,
|
||||
result: Any = None,
|
||||
logger: Optional[logging.Logger] = None,
|
||||
):
|
||||
"""记录关键决策点(分支判断、条件判断等)"""
|
||||
if logger is None:
|
||||
logger = get_unified_logger()
|
||||
|
||||
msg_parts = [f"[决策点] {decision}"]
|
||||
|
||||
if condition:
|
||||
msg_parts.append(f"条件: {condition}")
|
||||
|
||||
if result is not None:
|
||||
result_str = str(result)[:100]
|
||||
msg_parts.append(f"结果: {result_str}")
|
||||
|
||||
logger.info(" | ".join(msg_parts))
|
||||
|
||||
|
||||
def log_state_change(
|
||||
old_state: Any,
|
||||
new_state: Any,
|
||||
reason: Optional[str] = None,
|
||||
logger: Optional[logging.Logger] = None,
|
||||
):
|
||||
"""记录状态变化"""
|
||||
if logger is None:
|
||||
logger = get_unified_logger()
|
||||
|
||||
msg_parts = [f"[状态变化] {old_state} -> {new_state}"]
|
||||
|
||||
if reason:
|
||||
msg_parts.append(f"原因: {reason}")
|
||||
|
||||
logger.info(" | ".join(msg_parts))
|
||||
|
||||
|
||||
# 导出主要接口
|
||||
__all__ = [
|
||||
@@ -531,9 +363,4 @@ __all__ = [
|
||||
"SensitiveDataMasker",
|
||||
"UnifiedFormatter",
|
||||
"get_unified_logger",
|
||||
"trace_context",
|
||||
"log_method_entry_exit",
|
||||
"log_external_call",
|
||||
"log_decision_point",
|
||||
"log_state_change",
|
||||
]
|
||||
@@ -36,9 +36,12 @@ def check_coupon_popup(analyser) -> bool:
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
pic = Image.open(pic_path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
pic = pic.convert("RGB")
|
||||
template_matched = bool(douyin_pixel.detect_coupon_popup_background(pic))
|
||||
try:
|
||||
pic.load() # Force load to catch truncated files early
|
||||
pic_rgb = pic.convert("RGB")
|
||||
finally:
|
||||
pic.close()
|
||||
template_matched = bool(douyin_pixel.detect_coupon_popup_background(pic_rgb))
|
||||
except (OSError, IOError, SyntaxError) as e:
|
||||
# Handle truncated image files
|
||||
try:
|
||||
@@ -207,8 +210,11 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
pic = Image.open(pic_path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
pic = pic.convert("RGB")
|
||||
try:
|
||||
pic.load() # Force load to catch truncated files early
|
||||
pic_rgb = pic.convert("RGB")
|
||||
finally:
|
||||
pic.close()
|
||||
try:
|
||||
redpacket_threshold = float(
|
||||
getattr(analyser, "shopping_redpacket_red_ratio_threshold", None)
|
||||
@@ -218,7 +224,7 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
redpacket_threshold = 0.15
|
||||
has_popup_pixel = bool(
|
||||
douyin_pixel.detect_redpacket_popup_background(
|
||||
pic,
|
||||
pic_rgb,
|
||||
red_ratio_threshold=redpacket_threshold,
|
||||
analyser=analyser,
|
||||
)
|
||||
|
||||
@@ -133,7 +133,11 @@ def deal_robot_pic_change_color(analyser) -> None:
|
||||
path = path_config.get_robot_verify_pic_path(save_subdir=True)
|
||||
pic = path
|
||||
|
||||
img = Image.open(pic).convert("RGB")
|
||||
_raw = Image.open(pic)
|
||||
try:
|
||||
img = _raw.convert("RGB")
|
||||
finally:
|
||||
_raw.close()
|
||||
width, height = img.size
|
||||
for x in range(5, width - 40):
|
||||
for y in range(20, height - 30):
|
||||
@@ -156,7 +160,11 @@ def check_robot_pic_distance(analyser) -> int:
|
||||
if not pic_path or not os.path.exists(pic_path):
|
||||
raise FileNotFoundError(f"机器人验证图片不存在: {pic_path}")
|
||||
|
||||
img = Image.open(pic_path).convert("RGB")
|
||||
_raw = Image.open(pic_path)
|
||||
try:
|
||||
img = _raw.convert("RGB")
|
||||
finally:
|
||||
_raw.close()
|
||||
width, height = img.size
|
||||
|
||||
first_x = 0
|
||||
|
||||
+25
-152
@@ -299,73 +299,24 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
|
||||
if now - last_desktop_check_ts >= desktop_check_interval:
|
||||
last_desktop_check_ts = now
|
||||
try:
|
||||
from douyin.core import recovery as _recovery
|
||||
|
||||
top_pkg = (
|
||||
analyser.operation.get_top_package(analyser.device_id)
|
||||
or ""
|
||||
)
|
||||
is_douyin_pkg = top_pkg and (
|
||||
"aweme" in top_pkg
|
||||
or "douyin" in top_pkg
|
||||
or "com.ss.android.ugc" in top_pkg
|
||||
)
|
||||
if top_pkg and not is_douyin_pkg:
|
||||
_yanghao_log(analyser,
|
||||
f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}"
|
||||
if top_pkg and not _recovery.is_douyin_foreground(top_pkg):
|
||||
_yanghao_log(
|
||||
analyser,
|
||||
f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}",
|
||||
)
|
||||
try:
|
||||
desktop_x = int(
|
||||
getattr(analyser, "desktop_icon_x", 153) or 153
|
||||
_recovery.recover_to_douyin(
|
||||
analyser,
|
||||
log=lambda msg: _yanghao_log(
|
||||
analyser, f"[养号] 自救: {msg}"
|
||||
),
|
||||
)
|
||||
desktop_y = int(
|
||||
getattr(analyser, "desktop_icon_y", 260) or 260
|
||||
)
|
||||
analyser.operation.click(
|
||||
analyser.device_id, desktop_x, desktop_y
|
||||
)
|
||||
analyser.operation.delay(2)
|
||||
|
||||
fallback_x = int(
|
||||
getattr(
|
||||
analyser, "yanghao_fallback_live_x", 540
|
||||
)
|
||||
or 540
|
||||
)
|
||||
fallback_y = int(
|
||||
getattr(
|
||||
analyser, "yanghao_fallback_live_y", 2000
|
||||
)
|
||||
or 2000
|
||||
)
|
||||
analyser.operation.click(
|
||||
analyser.device_id, fallback_x, fallback_y
|
||||
)
|
||||
analyser.operation.delay(1.5)
|
||||
|
||||
enter_x = int(
|
||||
getattr(
|
||||
analyser,
|
||||
"yanghao_fallback_enter_live_x",
|
||||
540,
|
||||
)
|
||||
or 540
|
||||
)
|
||||
enter_y = int(
|
||||
getattr(
|
||||
analyser,
|
||||
"yanghao_fallback_enter_live_y",
|
||||
1200,
|
||||
)
|
||||
or 1200
|
||||
)
|
||||
analyser.operation.click(
|
||||
analyser.device_id, enter_x, enter_y
|
||||
)
|
||||
analyser.operation.delay(0.6)
|
||||
analyser.operation.click(
|
||||
analyser.device_id, enter_x, enter_y
|
||||
)
|
||||
analyser.operation.delay(2.0)
|
||||
|
||||
_yanghao_log(analyser, "[养号] 自救: 恢复操作完成")
|
||||
except Exception as e:
|
||||
_yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}")
|
||||
@@ -485,58 +436,22 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
|
||||
def _yanghao_check_and_recover_from_desktop(analyser) -> bool:
|
||||
"""养号模式下的桌面检测和自救恢复(提前定义以供循环使用)。"""
|
||||
try:
|
||||
# 获取前台包名
|
||||
from douyin.core import recovery as _recovery
|
||||
|
||||
top_pkg = analyser.operation.get_top_package(analyser.device_id) or ""
|
||||
|
||||
# 检查是否在抖音前台
|
||||
is_douyin_pkg = top_pkg and (
|
||||
"aweme" in top_pkg
|
||||
or "douyin" in top_pkg
|
||||
or "com.ss.android.ugc" in top_pkg
|
||||
)
|
||||
|
||||
if top_pkg and not is_douyin_pkg:
|
||||
if top_pkg and not _recovery.is_douyin_foreground(top_pkg):
|
||||
_yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}")
|
||||
|
||||
# 执行自救操作
|
||||
try:
|
||||
# 点击桌面图标
|
||||
desktop_x = int(getattr(analyser, "desktop_icon_x", 153) or 153)
|
||||
desktop_y = int(getattr(analyser, "desktop_icon_y", 260) or 260)
|
||||
analyser.operation.click(analyser.device_id, desktop_x, desktop_y)
|
||||
analyser.operation.delay(2)
|
||||
|
||||
# 点击直播按钮(备用坐标)
|
||||
fallback_x = int(
|
||||
getattr(analyser, "yanghao_fallback_live_x", 540) or 540
|
||||
_recovery.recover_to_douyin(
|
||||
analyser,
|
||||
log=lambda msg: _yanghao_log(analyser, f"[养号] 自救: {msg}"),
|
||||
)
|
||||
fallback_y = int(
|
||||
getattr(analyser, "yanghao_fallback_live_y", 2000) or 2000
|
||||
)
|
||||
analyser.operation.click(analyser.device_id, fallback_x, fallback_y)
|
||||
analyser.operation.delay(1.5)
|
||||
|
||||
# 点击进入直播间(备用坐标)
|
||||
enter_x = int(
|
||||
getattr(analyser, "yanghao_fallback_enter_live_x", 540) or 540
|
||||
)
|
||||
enter_y = int(
|
||||
getattr(analyser, "yanghao_fallback_enter_live_y", 1200) or 1200
|
||||
)
|
||||
analyser.operation.click(analyser.device_id, enter_x, enter_y)
|
||||
analyser.operation.delay(0.6)
|
||||
analyser.operation.click(analyser.device_id, enter_x, enter_y)
|
||||
analyser.operation.delay(2.0)
|
||||
|
||||
_yanghao_log(analyser, "[养号] 自救: 恢复操作完成")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
_yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}")
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
|
||||
return False
|
||||
except Exception as e:
|
||||
_yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}")
|
||||
return False
|
||||
@@ -614,64 +529,22 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
|
||||
def _yanghao_check_and_recover_from_desktop(analyser) -> bool:
|
||||
"""养号模式下的桌面检测和自救恢复"""
|
||||
try:
|
||||
# 获取前台包名
|
||||
from douyin.core import recovery as _recovery
|
||||
|
||||
top_pkg = analyser.operation.get_top_package(analyser.device_id) or ""
|
||||
|
||||
# 检查是否在抖音前台
|
||||
is_douyin_pkg = top_pkg and (
|
||||
"aweme" in top_pkg
|
||||
or "douyin" in top_pkg
|
||||
or "com.ss.android.ugc" in top_pkg
|
||||
)
|
||||
|
||||
if top_pkg and not is_douyin_pkg:
|
||||
if top_pkg and not _recovery.is_douyin_foreground(top_pkg):
|
||||
_yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}")
|
||||
|
||||
# 执行自救操作
|
||||
try:
|
||||
# 点击桌面图标
|
||||
desktop_x = int(getattr(analyser, "desktop_icon_x", 153) or 153)
|
||||
desktop_y = int(getattr(analyser, "desktop_icon_y", 260) or 260)
|
||||
analyser.operation.click(
|
||||
analyser.device_id, desktop_x, desktop_y
|
||||
_recovery.recover_to_douyin(
|
||||
analyser,
|
||||
log=lambda msg: _yanghao_log(analyser, f"[养号] 自救: {msg}"),
|
||||
)
|
||||
analyser.operation.delay(2)
|
||||
|
||||
# 点击直播按钮(备用坐标)
|
||||
fallback_x = int(
|
||||
getattr(analyser, "yanghao_fallback_live_x", 540) or 540
|
||||
)
|
||||
fallback_y = int(
|
||||
getattr(analyser, "yanghao_fallback_live_y", 2000) or 2000
|
||||
)
|
||||
analyser.operation.click(
|
||||
analyser.device_id, fallback_x, fallback_y
|
||||
)
|
||||
analyser.operation.delay(1.5)
|
||||
|
||||
# 点击进入直播间(备用坐标)
|
||||
enter_x = int(
|
||||
getattr(analyser, "yanghao_fallback_enter_live_x", 540)
|
||||
or 540
|
||||
)
|
||||
enter_y = int(
|
||||
getattr(analyser, "yanghao_fallback_enter_live_y", 1200)
|
||||
or 1200
|
||||
)
|
||||
analyser.operation.click(analyser.device_id, enter_x, enter_y)
|
||||
analyser.operation.delay(0.6)
|
||||
analyser.operation.click(analyser.device_id, enter_x, enter_y)
|
||||
analyser.operation.delay(2.0)
|
||||
|
||||
_yanghao_log(analyser, "[养号] 自救: 恢复操作完成")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
_yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}")
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
|
||||
return False
|
||||
except Exception as e:
|
||||
_yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}")
|
||||
return False
|
||||
|
||||
@@ -209,9 +209,12 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
|
||||
|
||||
from douyin.detection import douyin_pixel
|
||||
|
||||
button_result = douyin_pixel.detect_attend_button_red_area(
|
||||
pic_rgb, return_info=True, analyser=analyser
|
||||
)
|
||||
try:
|
||||
button_result = douyin_pixel.detect_attend_button_red_area(
|
||||
pic_rgb, return_info=True, analyser=analyser
|
||||
)
|
||||
finally:
|
||||
pic_rgb.close()
|
||||
if isinstance(button_result, tuple):
|
||||
has_button, button_info = button_result
|
||||
else:
|
||||
@@ -304,9 +307,12 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
|
||||
)
|
||||
screenshot_path2 = path_config.get_screenshot_path()
|
||||
pic_rgb2 = Image.open(screenshot_path2) # type: ignore[attr-defined]
|
||||
button_result2 = douyin_pixel.detect_attend_button_red_area(
|
||||
pic_rgb2, return_info=True, analyser=analyser
|
||||
)
|
||||
try:
|
||||
button_result2 = douyin_pixel.detect_attend_button_red_area(
|
||||
pic_rgb2, return_info=True, analyser=analyser
|
||||
)
|
||||
finally:
|
||||
pic_rgb2.close()
|
||||
if isinstance(button_result2, tuple):
|
||||
has_button2, button_info2 = button_result2
|
||||
else:
|
||||
|
||||
@@ -380,6 +380,8 @@ def validate_back_to_reservation(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
current_title = ""
|
||||
current_title_raw = ""
|
||||
if expected_title:
|
||||
try:
|
||||
# 回退校验时强制重新识别直播间标题,避免复用切换前的旧截图
|
||||
|
||||
@@ -752,545 +752,23 @@ def process_reservation_attend_window(
|
||||
ok = False
|
||||
|
||||
if ok:
|
||||
# 获取目标直播间名字和福袋详情(用于日志和校验)
|
||||
target_room_title = str(target.get("room_title") or "").strip()
|
||||
target_room_title_raw = str(target.get("room_title_raw") or "").strip()
|
||||
target_content = str(target.get("content") or "").strip()
|
||||
target_value = float(target.get("prize_value_yuan") or 0.0)
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:回退操作成功,准备进行回退校验",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=target_room_title[:50] if target_room_title else "",
|
||||
target_room_title_raw=(
|
||||
target_room_title_raw[:50] if target_room_title_raw else ""
|
||||
),
|
||||
target_content=target_content[:50] if target_content else "",
|
||||
target_value_yuan=target_value,
|
||||
current_room_pos=int(room_pos),
|
||||
reservation_back_verify_enabled=bool(
|
||||
getattr(analyser, "reservation_back_verify_enabled", True)
|
||||
),
|
||||
level="DEBUG",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 回退成功后,进行回退校验(如果启用了回退校验)
|
||||
verify_ok = True
|
||||
verify_detail = None
|
||||
try:
|
||||
verify_enabled = bool(
|
||||
getattr(analyser, "reservation_back_verify_enabled", True)
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:检查回退校验开关",
|
||||
reservation_back_verify_enabled=verify_enabled,
|
||||
level="DEBUG",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if verify_enabled:
|
||||
# 回退操作后等待直播间加载完成,然后再进行校验
|
||||
# 使用配置项控制等待时间,默认3秒(确保直播间标题等信息加载完成)
|
||||
try:
|
||||
verify_wait_seconds = float(
|
||||
getattr(analyser, "reservation_back_verify_wait_seconds", 5.0)
|
||||
or 5.0
|
||||
)
|
||||
if verify_wait_seconds < 0.1:
|
||||
verify_wait_seconds = 0.1 # 最小0.1秒
|
||||
if verify_wait_seconds > 10.0:
|
||||
verify_wait_seconds = 10.0 # 最大10秒,避免等待过久
|
||||
except Exception:
|
||||
verify_wait_seconds = 3.0
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:回退后等待直播间加载完成(开始等待)",
|
||||
verify_wait_seconds=verify_wait_seconds,
|
||||
level="INFO",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录等待开始时间,并在等待结束后写入实际等待时长,便于验证配置是否生效
|
||||
wait_start_ts = time.time()
|
||||
try:
|
||||
try:
|
||||
analyser.operation.delay(verify_wait_seconds)
|
||||
except Exception:
|
||||
time.sleep(verify_wait_seconds)
|
||||
finally:
|
||||
waited = time.time() - wait_start_ts
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:回退等待完成",
|
||||
expected_wait_seconds=verify_wait_seconds,
|
||||
waited_seconds=round(waited, 3),
|
||||
level="INFO",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:开始调用回退校验函数",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
level="DEBUG",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
import douyin.reservation.douyin_reservation_verify as douyin_reservation_verify
|
||||
|
||||
verify_ok, verify_detail = (
|
||||
douyin_reservation_verify.validate_back_to_reservation(
|
||||
analyser=analyser,
|
||||
item=target,
|
||||
quick=False,
|
||||
max_checks=3,
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:回退校验函数返回",
|
||||
verify_ok=verify_ok,
|
||||
verify_detail_exists=verify_detail is not None,
|
||||
level="DEBUG",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if not verify_ok:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
Exception("回退校验失败:回退操作成功但校验未通过"),
|
||||
format_reservation_context(
|
||||
item=target,
|
||||
reservations=reservations,
|
||||
verify_detail=verify_detail,
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
),
|
||||
level="WARNING",
|
||||
stage="回退校验",
|
||||
)
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退校验失败:回退操作成功但校验未通过(不再自动回退重试,避免循环卡死)",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 回退校验失败:根据映射表尝试再次回退到对应直播间,且不进入锁定期
|
||||
try:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退校验失败:尝试根据映射表回退到对应直播间并跳过设置锁定期",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 校验失败意味着位置信息可能不准确,尝试用映射表识别“当前/目标”位置差
|
||||
updated_target = dict(target)
|
||||
try:
|
||||
room_pos_before_map = int(
|
||||
getattr(analyser, "room_pos", 0) or 0
|
||||
)
|
||||
except Exception:
|
||||
room_pos_before_map = 0
|
||||
mapped_target_pos = None
|
||||
mapped_current_pos = None
|
||||
try:
|
||||
from douyin.reservation.douyin_reservation_handler import (
|
||||
ReservationHandler,
|
||||
)
|
||||
|
||||
mapped_target_pos = (
|
||||
ReservationHandler.find_room_pos_by_title(
|
||||
analyser,
|
||||
target_room_title,
|
||||
target_room_title_raw,
|
||||
)
|
||||
)
|
||||
if (
|
||||
mapped_target_pos is not None
|
||||
and mapped_target_pos > 0
|
||||
):
|
||||
updated_target["pos_seen"] = int(
|
||||
mapped_target_pos
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 重新查找目标直播间位置成功",
|
||||
old_pos=int(target.get("pos_seen", 0)),
|
||||
new_pos=int(mapped_target_pos),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 重新查找目标直播间位置失败,使用原有位置",
|
||||
target_pos=int(
|
||||
target.get("pos_seen", 0)
|
||||
),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 识别当前直播间标题(优先缓存,必要时重新识别)
|
||||
current_room_title = str(
|
||||
getattr(analyser, "current_room_title", "")
|
||||
or ""
|
||||
).strip()
|
||||
current_room_title_raw = str(
|
||||
getattr(analyser, "current_room_title_raw", "")
|
||||
or ""
|
||||
).strip()
|
||||
if (
|
||||
not current_room_title
|
||||
and not current_room_title_raw
|
||||
):
|
||||
try:
|
||||
from douyin.fudai import douyin_fudai_detail
|
||||
|
||||
y_pianyi_val = int(
|
||||
getattr(analyser, "y_pianyi", 0) or 0
|
||||
)
|
||||
(
|
||||
current_room_title,
|
||||
current_room_title_raw,
|
||||
) = douyin_fudai_detail.read_live_room_title_core(
|
||||
analyser, y_pianyi_val
|
||||
)
|
||||
try:
|
||||
analyser.current_room_title = (
|
||||
current_room_title
|
||||
)
|
||||
analyser.current_room_title_raw = (
|
||||
current_room_title_raw
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
current_room_title = ""
|
||||
current_room_title_raw = ""
|
||||
|
||||
if current_room_title or current_room_title_raw:
|
||||
mapped_current_pos = (
|
||||
ReservationHandler.find_room_pos_by_title(
|
||||
analyser,
|
||||
current_room_title,
|
||||
current_room_title_raw,
|
||||
)
|
||||
)
|
||||
if (
|
||||
mapped_current_pos is not None
|
||||
and mapped_current_pos > 0
|
||||
):
|
||||
try:
|
||||
old_room_pos = int(
|
||||
getattr(analyser, "room_pos", 0)
|
||||
or 0
|
||||
)
|
||||
except Exception:
|
||||
old_room_pos = 0
|
||||
try:
|
||||
analyser.room_pos = int(
|
||||
mapped_current_pos
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 通过映射表识别当前直播间位置",
|
||||
old_pos=int(old_room_pos),
|
||||
new_pos=int(mapped_current_pos),
|
||||
current_room_title=(
|
||||
current_room_title[:50]
|
||||
if current_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 重新查找目标/当前直播间位置时出错",
|
||||
error=str(e),
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 尝试使用回退回调根据映射表差值重新回退
|
||||
ok2 = False
|
||||
should_retry_seek = True
|
||||
mapped_pos_diff = None
|
||||
if (
|
||||
mapped_current_pos is not None
|
||||
and mapped_target_pos is not None
|
||||
):
|
||||
try:
|
||||
mapped_pos_diff = int(mapped_target_pos) - int(
|
||||
mapped_current_pos
|
||||
)
|
||||
except Exception:
|
||||
mapped_pos_diff = None
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 映射表差值回退准备",
|
||||
mapped_current_pos=int(mapped_current_pos),
|
||||
mapped_target_pos=int(mapped_target_pos),
|
||||
mapped_pos_diff=(
|
||||
int(mapped_pos_diff)
|
||||
if mapped_pos_diff is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if mapped_pos_diff == 0:
|
||||
# 若映射表显示已在目标位置但校验失败,尝试根据回退前位置进行一次纠偏回退
|
||||
if (
|
||||
mapped_target_pos is not None
|
||||
and room_pos_before_map != mapped_target_pos
|
||||
):
|
||||
try:
|
||||
if room_pos_before_map > int(
|
||||
mapped_target_pos
|
||||
):
|
||||
updated_target[
|
||||
"_seek_direction_hint"
|
||||
] = "down"
|
||||
elif room_pos_before_map < int(
|
||||
mapped_target_pos
|
||||
):
|
||||
updated_target[
|
||||
"_seek_direction_hint"
|
||||
] = "up"
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 映射表显示已在目标位置但校验失败,启用纠偏回退",
|
||||
mapped_current_pos=int(
|
||||
mapped_current_pos
|
||||
),
|
||||
mapped_target_pos=int(
|
||||
mapped_target_pos
|
||||
),
|
||||
room_pos_before_map=int(
|
||||
room_pos_before_map
|
||||
),
|
||||
direction_hint=updated_target.get(
|
||||
"_seek_direction_hint", ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
should_retry_seek = False
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 映射表显示已在目标位置,但校验失败,跳过二次回退",
|
||||
mapped_current_pos=int(
|
||||
mapped_current_pos
|
||||
),
|
||||
mapped_target_pos=int(
|
||||
mapped_target_pos
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if should_retry_seek:
|
||||
try:
|
||||
if seek_reservation_room_callback:
|
||||
ok2 = bool(
|
||||
seek_reservation_room_callback(
|
||||
updated_target
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
ok2 = False
|
||||
|
||||
if ok2:
|
||||
# 第二次回退成功,设置锁定期并标记待处理
|
||||
focus_until_new = ft + max(0.0, poll_before)
|
||||
if reservation_focus_until_ts_ref:
|
||||
reservation_focus_until_ts_ref[0] = (
|
||||
focus_until_new
|
||||
)
|
||||
else:
|
||||
reservation_focus_until_ts_ref.append(
|
||||
focus_until_new
|
||||
)
|
||||
|
||||
if reservation_after_action_pending_ref:
|
||||
reservation_after_action_pending_ref[0] = True
|
||||
else:
|
||||
reservation_after_action_pending_ref.append(
|
||||
True
|
||||
)
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 第二次回退成功:已根据映射表回退到目标直播间",
|
||||
target_pos=int(
|
||||
updated_target.get("pos_seen", 0)
|
||||
),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
focus_until=int(focus_until_new),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
write_state_callback()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 返回 True 表示回退成功
|
||||
return True
|
||||
else:
|
||||
# 第二次回退也失败,清理锁定相关标志
|
||||
try:
|
||||
if reservation_focus_until_ts_ref:
|
||||
reservation_focus_until_ts_ref[0] = 0.0
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if reservation_after_action_pending_ref:
|
||||
reservation_after_action_pending_ref[0] = (
|
||||
False
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 第二次回退失败:无法根据映射表定位到目标直播间",
|
||||
target_pos=int(
|
||||
updated_target.get("pos_seen", 0)
|
||||
),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
write_state_callback()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 不设置锁定期,回退校验失败视作本次未成功回退,返回 False 以便上层继续处理
|
||||
return False
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
f"[预约] 回退校验通过:已成功回退到目标直播间并验证福袋详情 - 目标位置:{int(target.get('pos_seen', 0))}, 直播间:'{target_room_title[:30] if target_room_title else ''}'",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退校验执行时发生异常,继续执行",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 校验异常不影响主流程,继续执行
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退校验已禁用,跳过校验",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 检查回退校验开关时发生异常,继续执行",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
from douyin.reservation.reservation_logic.attend_window_verify import (
|
||||
handle_back_verify,
|
||||
)
|
||||
_verify_result = handle_back_verify(
|
||||
analyser=analyser,
|
||||
target=target,
|
||||
reservations=reservations,
|
||||
room_pos=room_pos,
|
||||
ft=ft,
|
||||
poll_before=poll_before,
|
||||
reservation_focus_until_ts_ref=reservation_focus_until_ts_ref,
|
||||
reservation_after_action_pending_ref=reservation_after_action_pending_ref,
|
||||
seek_reservation_room_callback=seek_reservation_room_callback,
|
||||
write_state_callback=write_state_callback,
|
||||
)
|
||||
if _verify_result is not None:
|
||||
return _verify_result
|
||||
|
||||
# 如果回退或校验失败,直接返回 False
|
||||
if not ok:
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
"""reservation_logic.attend_window_verify - 回退后的校验与二次回退
|
||||
|
||||
从 process_reservation_attend_window 抽出的"if ok:"分支(540 行):
|
||||
- 回退操作成功后等待直播间加载
|
||||
- 调用 douyin_reservation_verify.validate_back_to_reservation 校验
|
||||
- 校验失败 → 用映射表重定位 + 二次回退
|
||||
- 校验通过 / 二次回退结果 / 校验异常 三种返回路径
|
||||
|
||||
入口:handle_back_verify(...)
|
||||
返回值:
|
||||
- True : 校验失败但二次回退成功,主函数应 `return True`
|
||||
- False : 校验失败且二次回退也失败,主函数应 `return False`
|
||||
- None : 校验通过 / 校验禁用 / 校验异常,主函数继续设锁定期
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from ._common import (
|
||||
ReservationItem,
|
||||
_RESERVATION_ERROR_UTILS_AVAILABLE,
|
||||
format_reservation_context,
|
||||
log_reservation_error,
|
||||
)
|
||||
|
||||
|
||||
def handle_back_verify(
|
||||
analyser: Any,
|
||||
target: ReservationItem,
|
||||
reservations: List[ReservationItem],
|
||||
room_pos: int,
|
||||
ft: float,
|
||||
poll_before: float,
|
||||
reservation_focus_until_ts_ref: List[float],
|
||||
reservation_after_action_pending_ref: List[bool],
|
||||
seek_reservation_room_callback: Callable[[ReservationItem], bool],
|
||||
write_state_callback: Callable[[], None],
|
||||
) -> Optional[bool]:
|
||||
"""处理回退后的校验与可能的二次回退。
|
||||
|
||||
Returns:
|
||||
True/False → 主函数立即返回该值
|
||||
None → 校验通过 / 禁用 / 异常,继续设置锁定期
|
||||
"""
|
||||
target_room_title = str(target.get("room_title") or "").strip()
|
||||
target_room_title_raw = str(target.get("room_title_raw") or "").strip()
|
||||
target_content = str(target.get("content") or "").strip()
|
||||
target_value = float(target.get("prize_value_yuan") or 0.0)
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:回退操作成功,准备进行回退校验",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=target_room_title[:50] if target_room_title else "",
|
||||
target_room_title_raw=(
|
||||
target_room_title_raw[:50] if target_room_title_raw else ""
|
||||
),
|
||||
target_content=target_content[:50] if target_content else "",
|
||||
target_value_yuan=target_value,
|
||||
current_room_pos=int(room_pos),
|
||||
reservation_back_verify_enabled=bool(
|
||||
getattr(analyser, "reservation_back_verify_enabled", True)
|
||||
),
|
||||
level="DEBUG",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
verify_enabled = bool(
|
||||
getattr(analyser, "reservation_back_verify_enabled", True)
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:检查回退校验开关",
|
||||
reservation_back_verify_enabled=verify_enabled,
|
||||
level="DEBUG",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not verify_enabled:
|
||||
try:
|
||||
analyser._log_kv("预约", "[预约] 回退校验已禁用,跳过校验")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
# 等待直播间加载完成
|
||||
try:
|
||||
verify_wait_seconds = float(
|
||||
getattr(analyser, "reservation_back_verify_wait_seconds", 5.0) or 5.0
|
||||
)
|
||||
if verify_wait_seconds < 0.1:
|
||||
verify_wait_seconds = 0.1
|
||||
if verify_wait_seconds > 10.0:
|
||||
verify_wait_seconds = 10.0
|
||||
except Exception:
|
||||
verify_wait_seconds = 3.0
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:回退后等待直播间加载完成(开始等待)",
|
||||
verify_wait_seconds=verify_wait_seconds,
|
||||
level="INFO",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
wait_start_ts = time.time()
|
||||
try:
|
||||
try:
|
||||
analyser.operation.delay(verify_wait_seconds)
|
||||
except Exception:
|
||||
time.sleep(verify_wait_seconds)
|
||||
finally:
|
||||
waited = time.time() - wait_start_ts
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:回退等待完成",
|
||||
expected_wait_seconds=verify_wait_seconds,
|
||||
waited_seconds=round(waited, 3),
|
||||
level="INFO",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:开始调用回退校验函数",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
level="DEBUG",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
import douyin.reservation.douyin_reservation_verify as douyin_reservation_verify
|
||||
|
||||
verify_ok, verify_detail = (
|
||||
douyin_reservation_verify.validate_back_to_reservation(
|
||||
analyser=analyser,
|
||||
item=target,
|
||||
quick=False,
|
||||
max_checks=3,
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] process_reservation_attend_window:回退校验函数返回",
|
||||
verify_ok=verify_ok,
|
||||
verify_detail_exists=verify_detail is not None,
|
||||
level="DEBUG",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if verify_ok:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
f"[预约] 回退校验通过:已成功回退到目标直播间并验证福袋详情 - 目标位置:{int(target.get('pos_seen', 0))}, 直播间:'{target_room_title[:30] if target_room_title else ''}'",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None # 校验通过,主函数继续设锁定期
|
||||
|
||||
# 校验失败 → 走二次回退逻辑
|
||||
return _handle_verify_failure(
|
||||
analyser, target, reservations,
|
||||
target_room_title, target_room_title_raw,
|
||||
ft, poll_before,
|
||||
reservation_focus_until_ts_ref,
|
||||
reservation_after_action_pending_ref,
|
||||
seek_reservation_room_callback,
|
||||
write_state_callback,
|
||||
verify_detail,
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退校验执行时发生异常,继续执行",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 校验异常不影响主流程,继续执行
|
||||
return None
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 检查回退校验开关时发生异常,继续执行",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _handle_verify_failure(
|
||||
analyser: Any,
|
||||
target: ReservationItem,
|
||||
reservations: List[ReservationItem],
|
||||
target_room_title: str,
|
||||
target_room_title_raw: str,
|
||||
ft: float,
|
||||
poll_before: float,
|
||||
reservation_focus_until_ts_ref: List[float],
|
||||
reservation_after_action_pending_ref: List[bool],
|
||||
seek_reservation_room_callback: Callable[[ReservationItem], bool],
|
||||
write_state_callback: Callable[[], None],
|
||||
verify_detail: Any,
|
||||
) -> bool:
|
||||
"""校验失败 → 用映射表重定位 + 二次回退。返回 True/False 给 caller。"""
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE:
|
||||
log_reservation_error(
|
||||
analyser,
|
||||
Exception("回退校验失败:回退操作成功但校验未通过"),
|
||||
format_reservation_context(
|
||||
item=target,
|
||||
reservations=reservations,
|
||||
verify_detail=verify_detail,
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
),
|
||||
level="WARNING",
|
||||
stage="回退校验",
|
||||
)
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退校验失败:回退操作成功但校验未通过(不再自动回退重试,避免循环卡死)",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退校验失败:尝试根据映射表回退到对应直播间并跳过设置锁定期",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
updated_target, mapped_target_pos, mapped_current_pos, room_pos_before_map = (
|
||||
_remap_target_via_room_titles(
|
||||
analyser, target, target_room_title, target_room_title_raw
|
||||
)
|
||||
)
|
||||
|
||||
ok2 = _retry_seek_with_mapped_diff(
|
||||
analyser, updated_target,
|
||||
mapped_target_pos, mapped_current_pos, room_pos_before_map,
|
||||
seek_reservation_room_callback,
|
||||
)
|
||||
|
||||
if ok2:
|
||||
# 第二次回退成功,设置锁定期并标记待处理
|
||||
focus_until_new = ft + max(0.0, poll_before)
|
||||
if reservation_focus_until_ts_ref:
|
||||
reservation_focus_until_ts_ref[0] = focus_until_new
|
||||
else:
|
||||
reservation_focus_until_ts_ref.append(focus_until_new)
|
||||
|
||||
if reservation_after_action_pending_ref:
|
||||
reservation_after_action_pending_ref[0] = True
|
||||
else:
|
||||
reservation_after_action_pending_ref.append(True)
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 第二次回退成功:已根据映射表回退到目标直播间",
|
||||
target_pos=int(updated_target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
focus_until=int(focus_until_new),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
write_state_callback()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True
|
||||
else:
|
||||
# 第二次回退也失败,清理锁定相关标志
|
||||
try:
|
||||
if reservation_focus_until_ts_ref:
|
||||
reservation_focus_until_ts_ref[0] = 0.0
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if reservation_after_action_pending_ref:
|
||||
reservation_after_action_pending_ref[0] = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 第二次回退失败:无法根据映射表定位到目标直播间",
|
||||
target_pos=int(updated_target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
write_state_callback()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 不设置锁定期,回退校验失败视作本次未成功回退,返回 False 以便上层继续处理
|
||||
return False
|
||||
|
||||
|
||||
def _remap_target_via_room_titles(
|
||||
analyser: Any,
|
||||
target: ReservationItem,
|
||||
target_room_title: str,
|
||||
target_room_title_raw: str,
|
||||
):
|
||||
"""通过映射表重新查找 target 与当前直播间位置。
|
||||
|
||||
Returns: (updated_target, mapped_target_pos, mapped_current_pos, room_pos_before_map)
|
||||
"""
|
||||
updated_target: Dict[str, Any] = dict(target)
|
||||
try:
|
||||
room_pos_before_map = int(getattr(analyser, "room_pos", 0) or 0)
|
||||
except Exception:
|
||||
room_pos_before_map = 0
|
||||
|
||||
mapped_target_pos: Optional[int] = None
|
||||
mapped_current_pos: Optional[int] = None
|
||||
|
||||
try:
|
||||
from douyin.reservation.douyin_reservation_handler import ReservationHandler
|
||||
|
||||
mapped_target_pos = ReservationHandler.find_room_pos_by_title(
|
||||
analyser, target_room_title, target_room_title_raw,
|
||||
)
|
||||
if mapped_target_pos is not None and mapped_target_pos > 0:
|
||||
updated_target["pos_seen"] = int(mapped_target_pos)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 重新查找目标直播间位置成功",
|
||||
old_pos=int(target.get("pos_seen", 0)),
|
||||
new_pos=int(mapped_target_pos),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 重新查找目标直播间位置失败,使用原有位置",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50] if target_room_title else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 识别当前直播间标题(优先缓存,必要时重新识别)
|
||||
current_room_title = str(
|
||||
getattr(analyser, "current_room_title", "") or ""
|
||||
).strip()
|
||||
current_room_title_raw = str(
|
||||
getattr(analyser, "current_room_title_raw", "") or ""
|
||||
).strip()
|
||||
if not current_room_title and not current_room_title_raw:
|
||||
try:
|
||||
from douyin.fudai import douyin_fudai_detail
|
||||
|
||||
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
(
|
||||
current_room_title,
|
||||
current_room_title_raw,
|
||||
) = douyin_fudai_detail.read_live_room_title_core(
|
||||
analyser, y_pianyi_val
|
||||
)
|
||||
try:
|
||||
analyser.current_room_title = current_room_title
|
||||
analyser.current_room_title_raw = current_room_title_raw
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
current_room_title = ""
|
||||
current_room_title_raw = ""
|
||||
|
||||
if current_room_title or current_room_title_raw:
|
||||
mapped_current_pos = ReservationHandler.find_room_pos_by_title(
|
||||
analyser, current_room_title, current_room_title_raw,
|
||||
)
|
||||
if mapped_current_pos is not None and mapped_current_pos > 0:
|
||||
try:
|
||||
old_room_pos = int(getattr(analyser, "room_pos", 0) or 0)
|
||||
except Exception:
|
||||
old_room_pos = 0
|
||||
try:
|
||||
analyser.room_pos = int(mapped_current_pos)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 通过映射表识别当前直播间位置",
|
||||
old_pos=int(old_room_pos),
|
||||
new_pos=int(mapped_current_pos),
|
||||
current_room_title=(
|
||||
current_room_title[:50] if current_room_title else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 重新查找目标/当前直播间位置时出错",
|
||||
error=str(e),
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return updated_target, mapped_target_pos, mapped_current_pos, room_pos_before_map
|
||||
|
||||
|
||||
def _retry_seek_with_mapped_diff(
|
||||
analyser: Any,
|
||||
updated_target: Dict[str, Any],
|
||||
mapped_target_pos: Optional[int],
|
||||
mapped_current_pos: Optional[int],
|
||||
room_pos_before_map: int,
|
||||
seek_reservation_room_callback: Callable[[ReservationItem], bool],
|
||||
) -> bool:
|
||||
"""根据映射表差值(mapped_target - mapped_current)执行二次回退。
|
||||
|
||||
特殊路径:mapped_pos_diff==0 时若 room_pos_before_map 与 mapped_target_pos 不一致,
|
||||
设置 _seek_direction_hint 后仍重试;否则跳过二次回退。
|
||||
"""
|
||||
ok2 = False
|
||||
should_retry_seek = True
|
||||
mapped_pos_diff: Optional[int] = None
|
||||
|
||||
if mapped_current_pos is not None and mapped_target_pos is not None:
|
||||
try:
|
||||
mapped_pos_diff = int(mapped_target_pos) - int(mapped_current_pos)
|
||||
except Exception:
|
||||
mapped_pos_diff = None
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 映射表差值回退准备",
|
||||
mapped_current_pos=int(mapped_current_pos),
|
||||
mapped_target_pos=int(mapped_target_pos),
|
||||
mapped_pos_diff=(
|
||||
int(mapped_pos_diff) if mapped_pos_diff is not None else None
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if mapped_pos_diff == 0:
|
||||
# 若映射表显示已在目标位置但校验失败,尝试根据回退前位置进行一次纠偏回退
|
||||
if (
|
||||
mapped_target_pos is not None
|
||||
and room_pos_before_map != mapped_target_pos
|
||||
):
|
||||
try:
|
||||
if room_pos_before_map > int(mapped_target_pos):
|
||||
updated_target["_seek_direction_hint"] = "down"
|
||||
elif room_pos_before_map < int(mapped_target_pos):
|
||||
updated_target["_seek_direction_hint"] = "up"
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 映射表显示已在目标位置但校验失败,启用纠偏回退",
|
||||
mapped_current_pos=int(mapped_current_pos),
|
||||
mapped_target_pos=int(mapped_target_pos),
|
||||
room_pos_before_map=int(room_pos_before_map),
|
||||
direction_hint=updated_target.get("_seek_direction_hint", ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
should_retry_seek = False
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 映射表显示已在目标位置,但校验失败,跳过二次回退",
|
||||
mapped_current_pos=int(mapped_current_pos),
|
||||
mapped_target_pos=int(mapped_target_pos),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if should_retry_seek:
|
||||
try:
|
||||
if seek_reservation_room_callback:
|
||||
ok2 = bool(seek_reservation_room_callback(updated_target))
|
||||
except Exception:
|
||||
ok2 = False
|
||||
|
||||
return ok2
|
||||
+43
-599
@@ -333,445 +333,25 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
|
||||
step0_elapsed = (time.time() - step_start) * 1000
|
||||
_log("步骤0[并行检测]-完成", 总耗时毫秒=step0_elapsed)
|
||||
|
||||
# ========== 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)==========
|
||||
if not in_live_room:
|
||||
_log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)")
|
||||
|
||||
# 购物红包像素命中:不在直播间也必须进行OCR复查
|
||||
if pixel_state.get("has_redpacket_bg", False):
|
||||
step_redpacket_ocr_start = time.time()
|
||||
red_ratio = None
|
||||
red_threshold = None
|
||||
try:
|
||||
redpacket_detail = (
|
||||
pixel_details.get("has_redpacket_bg", {})
|
||||
if isinstance(pixel_details, dict)
|
||||
else {}
|
||||
)
|
||||
red_ratio = redpacket_detail.get("red_ratio")
|
||||
red_threshold = redpacket_detail.get("effective_threshold")
|
||||
except Exception:
|
||||
red_ratio = None
|
||||
red_threshold = None
|
||||
|
||||
_log(
|
||||
"步骤2.5[购物红包OCR复查]-开始",
|
||||
说明="不在直播间也执行红包OCR复查",
|
||||
红色比例=(
|
||||
round(float(red_ratio), 4) if red_ratio is not None else None
|
||||
),
|
||||
阈值=(
|
||||
round(float(red_threshold), 4)
|
||||
if red_threshold is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
redpacket_verified = False
|
||||
try:
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(
|
||||
*SHOPPING_REDPACKET_AREA,
|
||||
"",
|
||||
"診斷購物紅包-非直播间复查",
|
||||
)
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤2.5[购物红包OCR复查]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp0 = preprocess_for_ocr(
|
||||
analyser, "診斷購物紅包-非直播间复查"
|
||||
)
|
||||
ocr_result = analyser.operation.analyse_pic_word(
|
||||
name_rp0, 0, return_confidence=True
|
||||
)
|
||||
if isinstance(ocr_result, tuple):
|
||||
redpacket_text, ocr_confidence_info = ocr_result
|
||||
else:
|
||||
redpacket_text = str(ocr_result or "")
|
||||
ocr_confidence_info = None
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤2.5[购物红包OCR复查]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
平均置信度=(
|
||||
ocr_confidence_info.get("avg_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
最大置信度=(
|
||||
ocr_confidence_info.get("max_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if enable_ocr_mode1 and (
|
||||
not redpacket_text
|
||||
or not any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
)
|
||||
):
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
ocr_start_1 = time.time()
|
||||
name_rp1 = preprocess_for_ocr(
|
||||
analyser, "診斷購物紅包-非直播间复查"
|
||||
)
|
||||
ocr_result_1 = analyser.operation.analyse_pic_word(
|
||||
name_rp1, 1, return_confidence=True
|
||||
)
|
||||
if isinstance(ocr_result_1, tuple):
|
||||
redpacket_text, ocr_confidence_info = ocr_result_1
|
||||
else:
|
||||
redpacket_text = str(ocr_result_1 or "")
|
||||
ocr_confidence_info = None
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤2.5[购物红包OCR复查]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=(
|
||||
redpacket_text[:50] if redpacket_text else ""
|
||||
),
|
||||
平均置信度=(
|
||||
ocr_confidence_info.get("avg_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
最大置信度=(
|
||||
ocr_confidence_info.get("max_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
# 检查关键词匹配或置信度阈值
|
||||
has_keyword_match = redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
)
|
||||
has_high_confidence = (
|
||||
ocr_confidence_info
|
||||
and ocr_confidence_info.get("max_confidence", 0)
|
||||
>= analyser.shopping_redpacket_ocr_confidence_threshold
|
||||
)
|
||||
|
||||
if has_keyword_match or has_high_confidence:
|
||||
redpacket_verified = True
|
||||
_log(
|
||||
"步骤2.5[购物红包OCR复查]-命中",
|
||||
关键词匹配=has_keyword_match,
|
||||
高置信度匹配=has_high_confidence,
|
||||
阈值=analyser.shopping_redpacket_ocr_confidence_threshold,
|
||||
)
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
_log(
|
||||
"步骤2.5[购物红包OCR复查]-异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if redpacket_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
_log_summary(
|
||||
"阶段诊断完成(购物红包弹窗-非直播间复查)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(不在直播间)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(不在直播间)"
|
||||
else:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
_log("步骤2.5[购物红包OCR复查]-未命中", 耗时毫秒=redpacket_elapsed)
|
||||
|
||||
# 步骤3:检测推荐页面、关注列表、直播列表(OCR标签栏,整合在一起检测)
|
||||
step_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
_log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before
|
||||
)
|
||||
t_recommend = ""
|
||||
t_follow = ""
|
||||
t_list = ""
|
||||
try:
|
||||
# 检测推荐页标签栏区域(包含"推荐"、"关注"、"直播"标签)
|
||||
_log("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*RECOMMEND_TAB, "", "推荐页标签栏")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name0 = preprocess_for_ocr(analyser, "推荐页标签栏")
|
||||
t_recommend = str(
|
||||
analyser.operation.analyse_pic_word(name0, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR推荐页标签栏]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_recommend),
|
||||
文本预览=t_recommend[:50] if t_recommend else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and (
|
||||
not t_recommend
|
||||
or (
|
||||
"推荐" not in t_recommend
|
||||
and "关注" not in t_recommend
|
||||
and "直播" not in t_recommend
|
||||
)
|
||||
)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
name1 = preprocess_for_ocr(analyser, "推荐页标签栏")
|
||||
t_recommend = str(
|
||||
analyser.operation.analyse_pic_word(name1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤3[OCR推荐页标签栏]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_recommend),
|
||||
文本预览=t_recommend[:50] if t_recommend else "",
|
||||
)
|
||||
elapsed_recommend = (time.time() - step_start) * 1000
|
||||
|
||||
# 如果识别到"推荐",直接返回推荐页面
|
||||
if "推荐" in t_recommend:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
seen_text = t_recommend[:50] if t_recommend else "-"
|
||||
_log(
|
||||
"步骤3[OCR推荐页标签栏]-命中推荐",
|
||||
耗时毫秒=elapsed_recommend,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=seen_text,
|
||||
)
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="RECOMMEND_PAGE",
|
||||
原因=f"标题='{t_recommend}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator("最终结果:RECOMMEND_PAGE(推荐页)")
|
||||
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
|
||||
|
||||
# 如果识别到"关注"但没有"推荐",可能是关注列表
|
||||
if "关注" in t_recommend and "推荐" not in t_recommend:
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-检测到关注关键词,准备精确确认",
|
||||
精确区域="(658,147)-(765,194)",
|
||||
)
|
||||
step_start_follow = time.time()
|
||||
try:
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*FOLLOW_TAB, "", "关注列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
namef0 = preprocess_for_ocr(analyser, "关注列表标签")
|
||||
t_follow = str(
|
||||
analyser.operation.analyse_pic_word(namef0, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_follow),
|
||||
文本预览=t_follow[:50] if t_follow else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and ("关注" not in t_follow)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
namef1 = preprocess_for_ocr(analyser, "关注列表标签")
|
||||
t_follow = str(
|
||||
analyser.operation.analyse_pic_word(namef1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_follow),
|
||||
文本预览=t_follow[:50] if t_follow else "",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
elapsed_follow = (time.time() - step_start_follow) * 1000
|
||||
if "关注" in t_follow:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
follow_text = t_follow[:50] if t_follow else "-"
|
||||
_log(
|
||||
"步骤3[OCR关注列表]-命中",
|
||||
耗时毫秒=elapsed_follow,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=follow_text,
|
||||
)
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(
|
||||
t_follow or ""
|
||||
).strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="FOLLOW_LIST",
|
||||
原因=f"标题='{t_follow}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator("最终结果:FOLLOW_LIST(关注列表)")
|
||||
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
|
||||
|
||||
# 如果识别到"正在直播"标签,判定为直播列表
|
||||
if "正在直播" in t_recommend or (
|
||||
"直播" in t_recommend
|
||||
and "推荐" not in t_recommend
|
||||
and "关注" not in t_recommend
|
||||
):
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-检测到直播关键词,准备精确确认",
|
||||
精确区域="(650,145)-(800,195)",
|
||||
)
|
||||
step_start_list = time.time()
|
||||
try:
|
||||
ocr_start = time.time() # 初始化ocr_start
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*LIVE_LIST_TAB, "", "直播列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
# else分支不需要,因为ocr_start已经在上面初始化了
|
||||
namel0 = preprocess_for_ocr(analyser, "直播列表标签")
|
||||
t_list = str(analyser.operation.analyse_pic_word(namel0, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and ("正在直播" not in t_list)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
namel1 = preprocess_for_ocr(analyser, "直播列表标签")
|
||||
t_list = str(
|
||||
analyser.operation.analyse_pic_word(namel1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
elapsed_list = (time.time() - step_start_list) * 1000
|
||||
if "正在直播" in t_list:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
list_text = t_list[:50] if t_list else "-"
|
||||
_log(
|
||||
"步骤3[OCR直播列表]-命中",
|
||||
耗时毫秒=elapsed_list,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=list_text,
|
||||
)
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="LIVE_LIST",
|
||||
原因=f"标题='{t_list}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator("最终结果:LIVE_LIST(直播列表)")
|
||||
return "LIVE_LIST", "标题='{}'".format(t_list)
|
||||
|
||||
# 记录诊断时看到的"关注页标题"
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
if elapsed_total > max_step_time * 1000:
|
||||
_log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-步骤超时",
|
||||
耗时毫秒=elapsed_total,
|
||||
阈值毫秒=max_step_time * 1000,
|
||||
)
|
||||
else:
|
||||
_log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-未命中",
|
||||
耗时毫秒=elapsed_total,
|
||||
推荐标签栏预览=t_recommend[:30] if t_recommend else "",
|
||||
)
|
||||
except Exception as e:
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
import traceback
|
||||
|
||||
_log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
|
||||
耗时毫秒=elapsed_total,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
# 步骤3结束计时
|
||||
step3_elapsed = (time.time() - step_start) * 1000
|
||||
_log("步骤3[OCR推荐页/关注列表/直播列表]-完成", 总耗时毫秒=step3_elapsed)
|
||||
|
||||
# 如果不在直播间且OCR也未识别到特定页面,默认返回在直播间
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="IN_LIVE_ROOM",
|
||||
原因="不在直播间且未识别到特定页面,默认判定为在直播间",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator("最终结果:IN_LIVE_ROOM(默认直播间)")
|
||||
return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间"
|
||||
# 不在直播间时:跑 OCR 找推荐页/关注列表/直播列表/购物红包
|
||||
from douyin.stage.douyin_stage_handler_pkg.ocr_detection import (
|
||||
detect_pages_via_ocr,
|
||||
)
|
||||
_ocr_result = detect_pages_via_ocr(
|
||||
analyser=analyser,
|
||||
in_live_room=in_live_room,
|
||||
pixel_state=pixel_state,
|
||||
pixel_details=pixel_details,
|
||||
diag_start=diag_start,
|
||||
max_diag_time=max_diag_time,
|
||||
max_step_time=max_step_time,
|
||||
enable_ocr_mode1=enable_ocr_mode1,
|
||||
log=_log,
|
||||
log_summary=_log_summary,
|
||||
log_separator=_log_separator,
|
||||
)
|
||||
if _ocr_result is not None:
|
||||
return _ocr_result
|
||||
|
||||
# ========== 在直播间:继续执行像素检测结果处理 ==========
|
||||
_log_separator("在直播间,继续执行像素检测结果处理")
|
||||
@@ -1053,9 +633,12 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
pic = Image.open(pic_path)
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
_raw = Image.open(pic_path)
|
||||
try:
|
||||
_raw.load()
|
||||
pic_rgb = _raw.convert("RGB")
|
||||
finally:
|
||||
_raw.close()
|
||||
|
||||
width, height = pic_rgb.size
|
||||
rx = int(
|
||||
@@ -1124,7 +707,7 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
|
||||
|
||||
# 如果模式0未识别到,尝试模式1
|
||||
enable_ocr_mode1 = bool(
|
||||
getattr(analyser, "enable_ocr_mode1", False)
|
||||
getattr(analyser, "enable_ocr_mode1", True)
|
||||
)
|
||||
if enable_ocr_mode1 and (
|
||||
not ocr_text
|
||||
@@ -1200,162 +783,22 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
|
||||
step15_ocr_elapsed = (time.time() - step_ocr_redpacket_start) * 1000
|
||||
_log("步骤1.5[OCR检测邀你抢红包]-完成", 总耗时毫秒=step15_ocr_elapsed)
|
||||
|
||||
# ========== 所有像素检测完成,未命中任何特定阶段 ==========
|
||||
# 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要OCR再次确认
|
||||
# 因为有些直播间背景颜色可能与弹窗颜色相似,导致误判
|
||||
has_suspicious_popup_pixel = pixel_state.get(
|
||||
"has_coupon_bg", False
|
||||
) or pixel_state.get("has_redpacket_bg", False)
|
||||
|
||||
if has_suspicious_popup_pixel:
|
||||
step_ocr_verify_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-开始",
|
||||
剩余时间秒=remaining_time_before,
|
||||
说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认",
|
||||
)
|
||||
|
||||
# 检测优惠券弹窗(使用参与按钮区域,检测"开心收下")
|
||||
if pixel_state.get("has_coupon_bg", False):
|
||||
coupon_verified = False
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*COUPON_PARTICIPATE_BUTTON_ALT, "", "参与按钮")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
# 如果启用模式1,并行执行两个OCR模式
|
||||
if enable_ocr_mode1:
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
name_part0 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode0 = executor.submit(
|
||||
analyser.operation.analyse_pic_word, name_part0, 0
|
||||
)
|
||||
name_part1 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode1 = executor.submit(
|
||||
analyser.operation.analyse_pic_word, name_part1, 1
|
||||
)
|
||||
text_mode0 = str(future_mode0.result() or "")
|
||||
text_mode1 = str(future_mode1.result() or "")
|
||||
# 优先使用模式0的结果,如果模式0没有"开心收下"且模式1有,则使用模式1
|
||||
if text_mode0 and "开心收下" in text_mode0:
|
||||
coupon_text = text_mode0
|
||||
elif text_mode1 and "开心收下" in text_mode1:
|
||||
coupon_text = text_mode1
|
||||
elif text_mode0:
|
||||
coupon_text = text_mode0
|
||||
else:
|
||||
coupon_text = text_mode1
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR并行模式0+1",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
else:
|
||||
pname = preprocess_for_ocr(analyser, "参与按钮")
|
||||
coupon_text = str(
|
||||
analyser.operation.analyse_pic_word(pname, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
coupon_verified = True
|
||||
except Exception as e:
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-优惠券异常",
|
||||
耗时毫秒=coupon_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if coupon_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log_summary(
|
||||
"阶段诊断完成(优惠券弹窗-OCR确认)",
|
||||
阶段="COUPON_POPUP",
|
||||
原因="像素检测到背景+OCR确认(开心收下)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
优惠券检测耗时毫秒=coupon_elapsed,
|
||||
)
|
||||
return "COUPON_POPUP", "OCR确认(开心收下)"
|
||||
|
||||
# 检测购物红包弹窗
|
||||
if pixel_state.get("has_redpacket_bg", False):
|
||||
redpacket_verified = False
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*SHOPPING_REDPACKET_AREA, "", "診斷購物紅包")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp2 = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
redpacket_text = str(
|
||||
analyser.operation.analyse_pic_word(name_rp2, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
):
|
||||
redpacket_verified = True
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-购物红包异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if redpacket_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log_summary(
|
||||
"阶段诊断完成(购物红包弹窗-OCR确认)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(购物红包)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return "SHOPPING_REDPACKET_POPUP", "OCR确认(购物红包弹窗)"
|
||||
|
||||
# OCR确认后仍未匹配到弹窗,说明是直播间背景颜色误判
|
||||
ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log(
|
||||
"步骤3[OCR确认弹窗]-未匹配到弹窗",
|
||||
耗时毫秒=ocr_verify_elapsed,
|
||||
说明="OCR确认后未匹配,判定为直播间背景颜色",
|
||||
)
|
||||
|
||||
# 步骤3结束计时(OCR确认弹窗)
|
||||
step3_ocr_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log("步骤3[OCR确认弹窗]-完成", 总耗时毫秒=step3_ocr_elapsed)
|
||||
# 所有像素检测完成,未命中任何特定阶段:检查是否有可疑弹窗背景需要 OCR 确认
|
||||
from douyin.stage.douyin_stage_handler_pkg.popup_verification import (
|
||||
verify_popup_via_ocr,
|
||||
)
|
||||
_popup_result = verify_popup_via_ocr(
|
||||
analyser=analyser,
|
||||
pixel_state=pixel_state,
|
||||
diag_start=diag_start,
|
||||
max_diag_time=max_diag_time,
|
||||
max_step_time=max_step_time,
|
||||
enable_ocr_mode1=enable_ocr_mode1,
|
||||
log=_log,
|
||||
log_summary=_log_summary,
|
||||
)
|
||||
if _popup_result is not None:
|
||||
return _popup_result
|
||||
|
||||
# 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段
|
||||
if in_live_room:
|
||||
@@ -1383,3 +826,4 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator("最终结果:IN_LIVE_ROOM(默认直播间)")
|
||||
return "IN_LIVE_ROOM", "像素检测未命中,默认直播间"
|
||||
@@ -0,0 +1,581 @@
|
||||
"""douyin_stage_handler_pkg.ocr_detection - 不在直播间时的 OCR 检测
|
||||
|
||||
从 diagnose_stage_from_current_screen 抽出 L336-774 的整段 "if not in_live_room"
|
||||
分支(438 行):
|
||||
- 步骤 2.5:购物红包 OCR 复查(像素命中红包背景时再用 OCR 二次确认)
|
||||
- 步骤 3:OCR 推荐页/关注列表/直播列表标签栏
|
||||
|
||||
入口:detect_pages_via_ocr(...) -> Optional[Tuple[str, str]]
|
||||
返回值:
|
||||
- ("SHOPPING_REDPACKET_POPUP", reason) | ("RECOMMEND_PAGE", reason)
|
||||
| ("FOLLOW_LIST", reason) | ("LIVE_LIST", reason) | ("IN_LIVE_ROOM", reason)
|
||||
→ caller 立即 return("IN_LIVE_ROOM" 是兜底默认值,与原代码保持一致)
|
||||
- None
|
||||
→ in_live_room=True,caller 应继续走"在直播间"分支
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Callable, Optional, Tuple
|
||||
|
||||
from douyin.fudai.core.coords import (
|
||||
FOLLOW_TAB,
|
||||
LIVE_LIST_TAB,
|
||||
RECOMMEND_TAB,
|
||||
SHOPPING_REDPACKET_AREA,
|
||||
)
|
||||
|
||||
|
||||
def detect_pages_via_ocr(
|
||||
analyser: Any,
|
||||
in_live_room: bool,
|
||||
pixel_state: dict,
|
||||
pixel_details: dict,
|
||||
diag_start: float,
|
||||
max_diag_time: float,
|
||||
max_step_time: float,
|
||||
enable_ocr_mode1: bool,
|
||||
log: Callable[..., None],
|
||||
log_summary: Callable[..., None],
|
||||
log_separator: Callable[..., None],
|
||||
) -> Optional[Tuple[str, str]]:
|
||||
"""如果不在直播间,跑 OCR 找推荐页 / 关注列表 / 直播列表 / 购物红包。
|
||||
|
||||
返回 ("阶段", 原因) 让 caller 立即 return;返回 None 表示 in_live_room=True,继续后续逻辑。
|
||||
"""
|
||||
if in_live_room:
|
||||
return None
|
||||
|
||||
try:
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
except Exception:
|
||||
def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore
|
||||
return str(picname)
|
||||
|
||||
log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)")
|
||||
|
||||
# 购物红包 OCR 复查(不在直播间也必须执行)
|
||||
redpacket_result = _check_redpacket_ocr_when_not_in_live_room(
|
||||
analyser,
|
||||
pixel_state,
|
||||
pixel_details,
|
||||
diag_start,
|
||||
max_step_time,
|
||||
enable_ocr_mode1,
|
||||
preprocess_for_ocr,
|
||||
log,
|
||||
log_summary,
|
||||
)
|
||||
if redpacket_result is not None:
|
||||
return redpacket_result
|
||||
|
||||
# 步骤 3:OCR 推荐页/关注列表/直播列表标签栏
|
||||
step_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before
|
||||
)
|
||||
t_recommend = ""
|
||||
t_follow = ""
|
||||
t_list = ""
|
||||
try:
|
||||
log("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*RECOMMEND_TAB, "", "推荐页标签栏")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name0 = preprocess_for_ocr(analyser, "推荐页标签栏")
|
||||
t_recommend = str(
|
||||
analyser.operation.analyse_pic_word(name0, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log(
|
||||
"步骤3[OCR推荐页标签栏]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_recommend),
|
||||
文本预览=t_recommend[:50] if t_recommend else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and (
|
||||
not t_recommend
|
||||
or (
|
||||
"推荐" not in t_recommend
|
||||
and "关注" not in t_recommend
|
||||
and "直播" not in t_recommend
|
||||
)
|
||||
)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
name1 = preprocess_for_ocr(analyser, "推荐页标签栏")
|
||||
t_recommend = str(
|
||||
analyser.operation.analyse_pic_word(name1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
log(
|
||||
"步骤3[OCR推荐页标签栏]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_recommend),
|
||||
文本预览=t_recommend[:50] if t_recommend else "",
|
||||
)
|
||||
elapsed_recommend = (time.time() - step_start) * 1000
|
||||
|
||||
# 命中"推荐"
|
||||
if "推荐" in t_recommend:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
seen_text = t_recommend[:50] if t_recommend else "-"
|
||||
log(
|
||||
"步骤3[OCR推荐页标签栏]-命中推荐",
|
||||
耗时毫秒=elapsed_recommend,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=seen_text,
|
||||
)
|
||||
log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="RECOMMEND_PAGE",
|
||||
原因=f"标题='{t_recommend}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator("最终结果:RECOMMEND_PAGE(推荐页)")
|
||||
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
|
||||
|
||||
# 命中"关注"但没有"推荐" → 关注列表精确确认
|
||||
if "关注" in t_recommend and "推荐" not in t_recommend:
|
||||
follow_result = _confirm_follow_list(
|
||||
analyser,
|
||||
t_recommend,
|
||||
step_start,
|
||||
diag_start,
|
||||
max_step_time,
|
||||
enable_ocr_mode1,
|
||||
preprocess_for_ocr,
|
||||
log,
|
||||
log_summary,
|
||||
log_separator,
|
||||
)
|
||||
if follow_result is not None:
|
||||
return follow_result
|
||||
# follow_result 为 None:关注列表确认失败,但继续走直播列表分支
|
||||
t_follow = getattr(analyser, "_last_follow_list_title_text", "") or ""
|
||||
|
||||
# 命中"正在直播"或"直播"标签 → 直播列表精确确认
|
||||
if "正在直播" in t_recommend or (
|
||||
"直播" in t_recommend
|
||||
and "推荐" not in t_recommend
|
||||
and "关注" not in t_recommend
|
||||
):
|
||||
list_result = _confirm_live_list(
|
||||
analyser,
|
||||
step_start,
|
||||
diag_start,
|
||||
max_step_time,
|
||||
enable_ocr_mode1,
|
||||
preprocess_for_ocr,
|
||||
log,
|
||||
log_summary,
|
||||
log_separator,
|
||||
)
|
||||
if list_result is not None:
|
||||
return list_result
|
||||
|
||||
# 记录诊断时看到的"关注页标题"
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
if elapsed_total > max_step_time * 1000:
|
||||
log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-步骤超时",
|
||||
耗时毫秒=elapsed_total,
|
||||
阈值毫秒=max_step_time * 1000,
|
||||
)
|
||||
else:
|
||||
log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-未命中",
|
||||
耗时毫秒=elapsed_total,
|
||||
推荐标签栏预览=t_recommend[:30] if t_recommend else "",
|
||||
)
|
||||
except Exception as e:
|
||||
elapsed_total = (time.time() - step_start) * 1000
|
||||
import traceback
|
||||
|
||||
log(
|
||||
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
|
||||
耗时毫秒=elapsed_total,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
step3_elapsed = (time.time() - step_start) * 1000
|
||||
log("步骤3[OCR推荐页/关注列表/直播列表]-完成", 总耗时毫秒=step3_elapsed)
|
||||
|
||||
# 如果不在直播间且 OCR 也未识别到特定页面,默认返回在直播间
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="IN_LIVE_ROOM",
|
||||
原因="不在直播间且未识别到特定页面,默认判定为在直播间",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator("最终结果:IN_LIVE_ROOM(默认直播间)")
|
||||
return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间"
|
||||
|
||||
|
||||
def _check_redpacket_ocr_when_not_in_live_room(
|
||||
analyser: Any,
|
||||
pixel_state: dict,
|
||||
pixel_details: dict,
|
||||
diag_start: float,
|
||||
max_step_time: float,
|
||||
enable_ocr_mode1: bool,
|
||||
preprocess_for_ocr: Callable,
|
||||
log: Callable[..., None],
|
||||
log_summary: Callable[..., None],
|
||||
) -> Optional[Tuple[str, str]]:
|
||||
"""步骤 2.5:购物红包像素命中时的 OCR 二次确认(不在直播间分支专用)。"""
|
||||
if not pixel_state.get("has_redpacket_bg", False):
|
||||
return None
|
||||
|
||||
step_redpacket_ocr_start = time.time()
|
||||
red_ratio = None
|
||||
red_threshold = None
|
||||
try:
|
||||
redpacket_detail = (
|
||||
pixel_details.get("has_redpacket_bg", {})
|
||||
if isinstance(pixel_details, dict)
|
||||
else {}
|
||||
)
|
||||
red_ratio = redpacket_detail.get("red_ratio")
|
||||
red_threshold = redpacket_detail.get("effective_threshold")
|
||||
except Exception:
|
||||
red_ratio = None
|
||||
red_threshold = None
|
||||
|
||||
log(
|
||||
"步骤2.5[购物红包OCR复查]-开始",
|
||||
说明="不在直播间也执行红包OCR复查",
|
||||
红色比例=(round(float(red_ratio), 4) if red_ratio is not None else None),
|
||||
阈值=(
|
||||
round(float(red_threshold), 4) if red_threshold is not None else None
|
||||
),
|
||||
)
|
||||
|
||||
redpacket_verified = False
|
||||
redpacket_text = ""
|
||||
ocr_confidence_info = None
|
||||
try:
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(
|
||||
*SHOPPING_REDPACKET_AREA,
|
||||
"",
|
||||
"診斷購物紅包-非直播间复查",
|
||||
)
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log("步骤2.5[购物红包OCR复查]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp0 = preprocess_for_ocr(
|
||||
analyser, "診斷購物紅包-非直播间复查"
|
||||
)
|
||||
ocr_result = analyser.operation.analyse_pic_word(
|
||||
name_rp0, 0, return_confidence=True
|
||||
)
|
||||
if isinstance(ocr_result, tuple):
|
||||
redpacket_text, ocr_confidence_info = ocr_result
|
||||
else:
|
||||
redpacket_text = str(ocr_result or "")
|
||||
ocr_confidence_info = None
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log(
|
||||
"步骤2.5[购物红包OCR复查]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
平均置信度=(
|
||||
ocr_confidence_info.get("avg_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
最大置信度=(
|
||||
ocr_confidence_info.get("max_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if enable_ocr_mode1 and (
|
||||
not redpacket_text
|
||||
or not any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
)
|
||||
):
|
||||
if time.time() - step_redpacket_ocr_start < max_step_time:
|
||||
ocr_start_1 = time.time()
|
||||
name_rp1 = preprocess_for_ocr(
|
||||
analyser, "診斷購物紅包-非直播间复查"
|
||||
)
|
||||
ocr_result_1 = analyser.operation.analyse_pic_word(
|
||||
name_rp1, 1, return_confidence=True
|
||||
)
|
||||
if isinstance(ocr_result_1, tuple):
|
||||
redpacket_text, ocr_confidence_info = ocr_result_1
|
||||
else:
|
||||
redpacket_text = str(ocr_result_1 or "")
|
||||
ocr_confidence_info = None
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
log(
|
||||
"步骤2.5[购物红包OCR复查]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=(
|
||||
redpacket_text[:50] if redpacket_text else ""
|
||||
),
|
||||
平均置信度=(
|
||||
ocr_confidence_info.get("avg_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
最大置信度=(
|
||||
ocr_confidence_info.get("max_confidence")
|
||||
if ocr_confidence_info
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
# 关键词匹配 / 置信度阈值
|
||||
has_keyword_match = redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
)
|
||||
has_high_confidence = (
|
||||
ocr_confidence_info
|
||||
and ocr_confidence_info.get("max_confidence", 0)
|
||||
>= getattr(analyser, "shopping_redpacket_ocr_confidence_threshold", 0.35)
|
||||
)
|
||||
|
||||
if has_keyword_match or has_high_confidence:
|
||||
redpacket_verified = True
|
||||
log(
|
||||
"步骤2.5[购物红包OCR复查]-命中",
|
||||
关键词匹配=has_keyword_match,
|
||||
高置信度匹配=has_high_confidence,
|
||||
阈值=getattr(analyser, "shopping_redpacket_ocr_confidence_threshold", 0.35),
|
||||
)
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
log(
|
||||
"步骤2.5[购物红包OCR复查]-异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if redpacket_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
log_summary(
|
||||
"阶段诊断完成(购物红包弹窗-非直播间复查)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(不在直播间)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(不在直播间)"
|
||||
else:
|
||||
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
|
||||
log("步骤2.5[购物红包OCR复查]-未命中", 耗时毫秒=redpacket_elapsed)
|
||||
return None
|
||||
|
||||
|
||||
def _confirm_follow_list(
|
||||
analyser: Any,
|
||||
t_recommend: str,
|
||||
step_start: float,
|
||||
diag_start: float,
|
||||
max_step_time: float,
|
||||
enable_ocr_mode1: bool,
|
||||
preprocess_for_ocr: Callable,
|
||||
log: Callable[..., None],
|
||||
log_summary: Callable[..., None],
|
||||
log_separator: Callable[..., None],
|
||||
) -> Optional[Tuple[str, str]]:
|
||||
"""精确截图 + OCR 确认是否真的是关注列表。"""
|
||||
log(
|
||||
"步骤3[OCR关注列表]-检测到关注关键词,准备精确确认",
|
||||
精确区域="(658,147)-(765,194)",
|
||||
)
|
||||
step_start_follow = time.time()
|
||||
t_follow = ""
|
||||
try:
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*FOLLOW_TAB, "", "关注列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
namef0 = preprocess_for_ocr(analyser, "关注列表标签")
|
||||
t_follow = str(
|
||||
analyser.operation.analyse_pic_word(namef0, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log(
|
||||
"步骤3[OCR关注列表]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_follow),
|
||||
文本预览=t_follow[:50] if t_follow else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and ("关注" not in t_follow)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
namef1 = preprocess_for_ocr(analyser, "关注列表标签")
|
||||
t_follow = str(
|
||||
analyser.operation.analyse_pic_word(namef1, 1) or ""
|
||||
)
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
log(
|
||||
"步骤3[OCR关注列表]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_follow),
|
||||
文本预览=t_follow[:50] if t_follow else "",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
log(
|
||||
"步骤3[OCR关注列表]-异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
elapsed_follow = (time.time() - step_start_follow) * 1000
|
||||
if "关注" in t_follow:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
follow_text = t_follow[:50] if t_follow else "-"
|
||||
log(
|
||||
"步骤3[OCR关注列表]-命中",
|
||||
耗时毫秒=elapsed_follow,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=follow_text,
|
||||
)
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="FOLLOW_LIST",
|
||||
原因=f"标题='{t_follow}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator("最终结果:FOLLOW_LIST(关注列表)")
|
||||
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
|
||||
|
||||
# 关注列表确认失败:把 t_follow 存到 analyser,后续可读
|
||||
try:
|
||||
analyser._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
analyser._last_follow_list_title_text = ""
|
||||
return None
|
||||
|
||||
|
||||
def _confirm_live_list(
|
||||
analyser: Any,
|
||||
step_start: float,
|
||||
diag_start: float,
|
||||
max_step_time: float,
|
||||
enable_ocr_mode1: bool,
|
||||
preprocess_for_ocr: Callable,
|
||||
log: Callable[..., None],
|
||||
log_summary: Callable[..., None],
|
||||
log_separator: Callable[..., None],
|
||||
) -> Optional[Tuple[str, str]]:
|
||||
"""精确截图 + OCR 确认是否真的是直播列表。"""
|
||||
log(
|
||||
"步骤3[OCR直播列表]-检测到直播关键词,准备精确确认",
|
||||
精确区域="(650,145)-(800,195)",
|
||||
)
|
||||
step_start_list = time.time()
|
||||
t_list = ""
|
||||
try:
|
||||
ocr_start = time.time()
|
||||
if time.time() - step_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*LIVE_LIST_TAB, "", "直播列表标签")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
namel0 = preprocess_for_ocr(analyser, "直播列表标签")
|
||||
t_list = str(analyser.operation.analyse_pic_word(namel0, 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log(
|
||||
"步骤3[OCR直播列表]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
|
||||
if (
|
||||
enable_ocr_mode1
|
||||
and (time.time() - step_start < max_step_time)
|
||||
and ("正在直播" not in t_list)
|
||||
):
|
||||
ocr_start_1 = time.time()
|
||||
namel1 = preprocess_for_ocr(analyser, "直播列表标签")
|
||||
t_list = str(analyser.operation.analyse_pic_word(namel1, 1) or "")
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
log(
|
||||
"步骤3[OCR直播列表]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
文本长度=len(t_list),
|
||||
文本预览=t_list[:50] if t_list else "",
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
log(
|
||||
"步骤3[OCR直播列表]-异常",
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
|
||||
elapsed_list = (time.time() - step_start_list) * 1000
|
||||
if "正在直播" in t_list:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
list_text = t_list[:50] if t_list else "-"
|
||||
log(
|
||||
"步骤3[OCR直播列表]-命中",
|
||||
耗时毫秒=elapsed_list,
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=list_text,
|
||||
)
|
||||
log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="LIVE_LIST",
|
||||
原因=f"标题='{t_list}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
log_separator("最终结果:LIVE_LIST(直播列表)")
|
||||
return "LIVE_LIST", "标题='{}'".format(t_list)
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,211 @@
|
||||
"""douyin_stage_handler_pkg.popup_verification - 弹窗 OCR 二次确认
|
||||
|
||||
从 diagnose_stage_from_current_screen 抽出 L1203-1358 的"未命中任何阶段
|
||||
但像素检测到弹窗背景"段(156 行):当 has_coupon_bg / has_redpacket_bg
|
||||
为 True 时,再用 OCR 二次确认是否真的是优惠券/购物红包弹窗(避免直播间
|
||||
背景色误判)。
|
||||
|
||||
入口:verify_popup_via_ocr(...) -> Optional[Tuple[str, str]]
|
||||
返回值:
|
||||
- ("COUPON_POPUP", reason) 或 ("SHOPPING_REDPACKET_POPUP", reason)
|
||||
→ caller 应立即 return 该元组
|
||||
- None
|
||||
→ 没有可疑弹窗 / 像素未检测到 / OCR 确认失败,caller 继续后续逻辑
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Callable, Optional, Tuple
|
||||
|
||||
from douyin.fudai.core.coords import (
|
||||
COUPON_PARTICIPATE_BUTTON_ALT,
|
||||
SHOPPING_REDPACKET_AREA,
|
||||
)
|
||||
|
||||
|
||||
def verify_popup_via_ocr(
|
||||
analyser: Any,
|
||||
pixel_state: dict,
|
||||
diag_start: float,
|
||||
max_diag_time: float,
|
||||
max_step_time: float,
|
||||
enable_ocr_mode1: bool,
|
||||
log: Callable[..., None],
|
||||
log_summary: Callable[..., None],
|
||||
) -> Optional[Tuple[str, str]]:
|
||||
"""像素层有可疑弹窗背景时用 OCR 再确认一次。
|
||||
|
||||
Args:
|
||||
analyser: 调用 cut_pic / operation.analyse_pic_word
|
||||
pixel_state: 像素检测结果 dict(含 has_coupon_bg / has_redpacket_bg)
|
||||
diag_start: 整个阶段诊断起始时间(用于汇总耗时日志)
|
||||
max_diag_time: 诊断总超时(秒)
|
||||
max_step_time: 单步超时(秒)
|
||||
enable_ocr_mode1: 是否额外并行跑模式 1 OCR
|
||||
log / log_summary: 原 diagnose 内部的两个嵌套日志闭包,按原行为保留
|
||||
|
||||
Returns:
|
||||
("COUPON_POPUP", reason) / ("SHOPPING_REDPACKET_POPUP", reason)
|
||||
/ None(不需要拦截)
|
||||
"""
|
||||
has_suspicious_popup_pixel = (
|
||||
pixel_state.get("has_coupon_bg", False)
|
||||
or pixel_state.get("has_redpacket_bg", False)
|
||||
)
|
||||
if not has_suspicious_popup_pixel:
|
||||
return None
|
||||
|
||||
try:
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
except Exception:
|
||||
def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore
|
||||
return str(picname)
|
||||
|
||||
step_ocr_verify_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
log(
|
||||
"步骤3[OCR确认弹窗]-开始",
|
||||
剩余时间秒=remaining_time_before,
|
||||
说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认",
|
||||
)
|
||||
|
||||
# 检测优惠券弹窗(使用参与按钮区域,检测"开心收下")
|
||||
if pixel_state.get("has_coupon_bg", False):
|
||||
coupon_text = ""
|
||||
coupon_verified = False
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*COUPON_PARTICIPATE_BUTTON_ALT, "", "参与按钮")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
if enable_ocr_mode1:
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
name_part0 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode0 = executor.submit(
|
||||
analyser.operation.analyse_pic_word, name_part0, 0
|
||||
)
|
||||
name_part1 = preprocess_for_ocr(analyser, "参与按钮")
|
||||
future_mode1 = executor.submit(
|
||||
analyser.operation.analyse_pic_word, name_part1, 1
|
||||
)
|
||||
text_mode0 = str(future_mode0.result() or "")
|
||||
text_mode1 = str(future_mode1.result() or "")
|
||||
# 优先使用模式 0;模式 0 没有"开心收下"且模式 1 有,则用模式 1
|
||||
if text_mode0 and "开心收下" in text_mode0:
|
||||
coupon_text = text_mode0
|
||||
elif text_mode1 and "开心收下" in text_mode1:
|
||||
coupon_text = text_mode1
|
||||
elif text_mode0:
|
||||
coupon_text = text_mode0
|
||||
else:
|
||||
coupon_text = text_mode1
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR并行模式0+1",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
else:
|
||||
pname = preprocess_for_ocr(analyser, "参与按钮")
|
||||
coupon_text = str(
|
||||
analyser.operation.analyse_pic_word(pname, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log(
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
coupon_verified = True
|
||||
except Exception as e:
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log(
|
||||
"步骤3[OCR确认弹窗]-优惠券异常",
|
||||
耗时毫秒=coupon_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if coupon_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_summary(
|
||||
"阶段诊断完成(优惠券弹窗-OCR确认)",
|
||||
阶段="COUPON_POPUP",
|
||||
原因="像素检测到背景+OCR确认(开心收下)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
优惠券检测耗时毫秒=coupon_elapsed,
|
||||
)
|
||||
return "COUPON_POPUP", "OCR确认(开心收下)"
|
||||
|
||||
# 检测购物红包弹窗
|
||||
if pixel_state.get("has_redpacket_bg", False):
|
||||
redpacket_verified = False
|
||||
try:
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
cut_start = time.time()
|
||||
analyser.cut_pic(*SHOPPING_REDPACKET_AREA, "", "診斷購物紅包")
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
log("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
name_rp2 = preprocess_for_ocr(analyser, "診斷購物紅包")
|
||||
redpacket_text = str(
|
||||
analyser.operation.analyse_pic_word(name_rp2, 0) or ""
|
||||
)
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
log(
|
||||
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(redpacket_text),
|
||||
文本预览=redpacket_text[:50] if redpacket_text else "",
|
||||
)
|
||||
|
||||
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
|
||||
if redpacket_text and any(
|
||||
kw in redpacket_text for kw in redpacket_keywords
|
||||
):
|
||||
redpacket_verified = True
|
||||
except Exception as e:
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log(
|
||||
"步骤3[OCR确认弹窗]-购物红包异常",
|
||||
耗时毫秒=redpacket_elapsed,
|
||||
异常类型=type(e).__name__,
|
||||
异常信息=str(e),
|
||||
)
|
||||
|
||||
if redpacket_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log_summary(
|
||||
"阶段诊断完成(购物红包弹窗-OCR确认)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(购物红包)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
红包检测耗时毫秒=redpacket_elapsed,
|
||||
)
|
||||
return "SHOPPING_REDPACKET_POPUP", "OCR确认(购物红包弹窗)"
|
||||
|
||||
# OCR 确认后仍未匹配到弹窗,说明是直播间背景颜色误判
|
||||
ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log(
|
||||
"步骤3[OCR确认弹窗]-未匹配到弹窗",
|
||||
耗时毫秒=ocr_verify_elapsed,
|
||||
说明="OCR确认后未匹配,判定为直播间背景颜色",
|
||||
)
|
||||
|
||||
step3_ocr_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
log("步骤3[OCR确认弹窗]-完成", 总耗时毫秒=step3_ocr_elapsed)
|
||||
return None
|
||||
@@ -1,95 +0,0 @@
|
||||
"""福袋相关文本解析辅助函数。
|
||||
|
||||
本模块提供若干轻量级的解析函数,主要用于:
|
||||
- 从 OCR 文本中抽取福袋内容/倒计时/价值/参与人数
|
||||
- 方便在单元测试中独立验证文本处理逻辑
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
import re
|
||||
|
||||
from douyin.utils.douyin_utils import normalize_countdown_text, extract_prize_value_yuan
|
||||
|
||||
|
||||
def _safe_str(text: Optional[str]) -> str:
|
||||
"""将输入安全地转换为字符串,None -> 空字符串。"""
|
||||
if text is None:
|
||||
return ""
|
||||
return str(text)
|
||||
|
||||
|
||||
def extract_fudai_content(text: Optional[str]) -> str:
|
||||
"""从 OCR 文本中提取“福袋内容”相关描述。
|
||||
|
||||
当前实现比较宽松:
|
||||
- 优先截取 “福袋内容:xxx” 或 “内容:xxx” 之后的部分
|
||||
- 否则返回原始文本(去掉首尾空白)
|
||||
"""
|
||||
t = _safe_str(text).strip()
|
||||
if not t:
|
||||
return ""
|
||||
|
||||
# 常见前缀:福袋内容:xxx / 奖品内容:xxx / 内容:xxx
|
||||
m = re.search(r"(福袋内容|奖品内容|内容)[::]\s*(.+)", t)
|
||||
if m:
|
||||
return m.group(2).strip()
|
||||
|
||||
# 如果包含“福袋”关键字,简单返回整句,后续需要时可再细化
|
||||
if "福袋" in t:
|
||||
return t
|
||||
|
||||
return t
|
||||
|
||||
|
||||
def extract_fudai_countdown(text: Optional[str]) -> str:
|
||||
"""从 OCR 文本中提取倒计时字符串。
|
||||
|
||||
返回值示例:
|
||||
- ``"05:30"`` / ``"05:30后开奖"``
|
||||
- 若无法解析则返回空字符串。
|
||||
"""
|
||||
t = _safe_str(text)
|
||||
if not t:
|
||||
return ""
|
||||
|
||||
norm = normalize_countdown_text(t)
|
||||
return norm or ""
|
||||
|
||||
|
||||
def extract_fudai_value(text: Optional[str]) -> float:
|
||||
"""从 OCR 文本中提取福袋价值金额(元)。
|
||||
|
||||
直接复用 ``douyin_utils.extract_prize_value_yuan``。
|
||||
"""
|
||||
return float(extract_prize_value_yuan(_safe_str(text)))
|
||||
|
||||
|
||||
def extract_participants_count(text: Optional[str]) -> int:
|
||||
"""从 OCR 文本中提取“参与人数”。
|
||||
|
||||
支持的常见格式示例:
|
||||
- ``"共1份1173人已参与"``
|
||||
- ``"已有1000人参与"``
|
||||
- ``"1173人已参与"``
|
||||
- 若无法解析则返回 0。
|
||||
"""
|
||||
t = _safe_str(text)
|
||||
if not t:
|
||||
return 0
|
||||
|
||||
# 优先匹配“xxxx人已参与 / xxxx人参与 / xxxx人”
|
||||
m = re.search(r"(\d+)\s*人(?:已参与|参与)?", t)
|
||||
if m:
|
||||
try:
|
||||
return int(m.group(1))
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
# 退化:查找所有数字,取中等大小的一个,避免把“份数”等误当成人数
|
||||
nums = [int(n) for n in re.findall(r"\d+", t) if n.isdigit()]
|
||||
if not nums:
|
||||
return 0
|
||||
# 简化策略:返回最大值(通常人数是文本里最大的数字)
|
||||
return max(nums)
|
||||
@@ -32,10 +32,13 @@ def preprocess_for_ocr(analyser: Any, cut_pic_name: str) -> str:
|
||||
try:
|
||||
if not os.path.exists(src):
|
||||
return cut_pic_name
|
||||
img = Image.open(src)
|
||||
img.load()
|
||||
# 转灰度
|
||||
img = img.convert("L")
|
||||
_raw = Image.open(src)
|
||||
try:
|
||||
_raw.load()
|
||||
# 转灰度
|
||||
img = _raw.convert("L")
|
||||
finally:
|
||||
_raw.close()
|
||||
# 放大两倍(Lanczos)
|
||||
img = img.resize((img.width * 2, img.height * 2), Image.LANCZOS)
|
||||
# 自动对比并锐化
|
||||
|
||||
@@ -121,15 +121,4 @@ def start_tracing() -> None:
|
||||
_state["enabled"] = False
|
||||
|
||||
|
||||
def stop_tracing() -> None:
|
||||
try:
|
||||
sys.settrace(None)
|
||||
finally:
|
||||
_state["enabled"] = False
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
return bool(_state.get("enabled"))
|
||||
|
||||
|
||||
__all__ = ["start_tracing", "stop_tracing", "is_enabled"]
|
||||
__all__ = ["start_tracing"]
|
||||
@@ -0,0 +1,80 @@
|
||||
"""底部操作按钮区(开始运行 / 停止 / 强制停止 / 发送返回键 / 状态标签)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的 widget 创建段 + 4 个按钮回调
|
||||
(``start_run`` / ``stop_run`` / ``force_stop_run`` / ``send_back_key``)。
|
||||
|
||||
依赖通过显式参数注入。状态写回主线程通过 ``status_var`` 实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, RIGHT, X
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def setup_action_buttons(
|
||||
actions: ttk.Frame,
|
||||
*,
|
||||
runner: Any,
|
||||
status_var: tk.StringVar,
|
||||
device_var: tk.StringVar,
|
||||
on_line: Callable[[str], None],
|
||||
save_ui_to_config: Callable[[], None],
|
||||
get_params: Callable[[], Any],
|
||||
) -> None:
|
||||
"""构建底部操作按钮区(开始/停止/强制停止/发送返回键 + 状态标签)。"""
|
||||
|
||||
def start_run() -> None:
|
||||
if runner.is_running():
|
||||
on_line("[运行] 已在运行中")
|
||||
return
|
||||
save_ui_to_config()
|
||||
params = get_params()
|
||||
|
||||
wait_display = "∞" if params.wait_minutes == 0 else f"{params.wait_minutes}m"
|
||||
on_line(
|
||||
f"[运行] 启动:device={params.device_id or '(auto)'} y={params.y_pianyi} "
|
||||
f"needswitch={params.needswitch} wait={wait_display} "
|
||||
f"skip_gt={params.skip_if_countdown_gt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} "
|
||||
f"value>={params.min_prize_value_yuan} participants=[{params.min_participants},{params.max_participants}] "
|
||||
f"high_value_revisit={params.high_value_room_revisit_enabled} reservation_verify={params.reservation_back_verify_enabled} "
|
||||
f"fudai_find_max={params.fudai_find_max_attempts} yanghao=recommend_flow_only"
|
||||
)
|
||||
status_var.set("运行中")
|
||||
try:
|
||||
runner.start(params)
|
||||
except Exception as e:
|
||||
status_var.set("启动失败")
|
||||
on_line(f"[错误] {e}")
|
||||
|
||||
def stop_run() -> None:
|
||||
runner.stop()
|
||||
status_var.set("已停止")
|
||||
|
||||
def force_stop_run() -> None:
|
||||
"""强制终止后台进程(包括可能残留的子进程)。"""
|
||||
runner.force_stop()
|
||||
status_var.set("已停止(强制)")
|
||||
|
||||
def send_back_key() -> None:
|
||||
dev = device_var.get().strip()
|
||||
try:
|
||||
runner.send_back_key(dev)
|
||||
except Exception as e:
|
||||
on_line(f"[错误] 发送返回键失败: {e}")
|
||||
|
||||
ttk.Button(actions, text="开始运行", command=start_run).pack(side=LEFT, padx=(0, 8))
|
||||
ttk.Button(actions, text="停止", command=stop_run).pack(side=LEFT, padx=(0, 4))
|
||||
ttk.Button(actions, text="强制停止", command=force_stop_run).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
# (已移除:测试养号/测试评论 按钮与相关UI)
|
||||
|
||||
ttk.Button(actions, text="发送返回键", command=send_back_key).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
ttk.Label(actions, textvariable=status_var).pack(side=RIGHT)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""行为日志 Tab 的工具栏(关键字筛选 + 文本搜索)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的搜索栏 widget 创建段 +
|
||||
配色配置 + 4 个共享 ``nonlocal`` matches state 的搜索闭包。
|
||||
|
||||
抽出后用一个 ``ActionsLogToolbarHandles`` 暴露 ``main()`` 仍要用的引用:
|
||||
- ``refresh_actions_log`` - 刷新回调(被 root.after 调度用)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X, Y
|
||||
from typing import Callable
|
||||
|
||||
from gui.components.actions_log_view import (
|
||||
configure_actions_log_colors as _configure_actions_log_colors_impl,
|
||||
refresh_actions_log as _refresh_actions_log_impl,
|
||||
)
|
||||
from gui.components.text_search import generic_search_widget
|
||||
|
||||
|
||||
@dataclass
|
||||
class ActionsLogToolbarHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
refresh_actions_log: Callable[[], None]
|
||||
|
||||
|
||||
def setup_actions_log_toolbar(
|
||||
parent: tk.Misc,
|
||||
*,
|
||||
actions_log_text: tk.Text,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> ActionsLogToolbarHandles:
|
||||
"""构建行为日志 Tab 顶部的工具栏(配色 + 关键字筛选 + 文本搜索)。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - 工具栏父容器(``actions_log_top``)
|
||||
- ``actions_log_text`` - 行为日志文本 widget
|
||||
- ``theme_getter`` - ``() -> str`` 返回当前 GUI 主题名
|
||||
"""
|
||||
# 配置行为日志颜色标签(使用统一的颜色配置模块)
|
||||
def configure_actions_log_colors() -> None:
|
||||
_configure_actions_log_colors_impl(
|
||||
actions_log_text,
|
||||
theme_getter=theme_getter,
|
||||
)
|
||||
|
||||
# 初始配置
|
||||
configure_actions_log_colors()
|
||||
|
||||
actions_filter_var = tk.StringVar(value="")
|
||||
|
||||
def refresh_actions_log() -> None:
|
||||
_refresh_actions_log_impl(
|
||||
actions_log_text,
|
||||
theme_getter=theme_getter,
|
||||
filter_getter=lambda: actions_filter_var.get().strip(),
|
||||
)
|
||||
|
||||
ttk.Label(parent, text="关键字筛选:").pack(side=LEFT)
|
||||
ttk.Entry(parent, textvariable=actions_filter_var, width=16).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
ttk.Button(parent, text="刷新", command=refresh_actions_log).pack(
|
||||
side=LEFT, padx=(0, 10)
|
||||
)
|
||||
|
||||
# 行为日志搜索功能
|
||||
ttk.Separator(parent, orient="vertical").pack(
|
||||
side=LEFT, fill=Y, padx=5, pady=3
|
||||
)
|
||||
ttk.Label(parent, text="搜索:").pack(side=LEFT)
|
||||
|
||||
actions_search_var = tk.StringVar(value="")
|
||||
actions_search_entry = ttk.Entry(
|
||||
parent, textvariable=actions_search_var, width=20
|
||||
)
|
||||
actions_search_entry.pack(side=LEFT, padx=(0, 5))
|
||||
|
||||
state = {
|
||||
"matches": [],
|
||||
"current_index": -1,
|
||||
}
|
||||
|
||||
def search_in_actions_log(direction: int = 1) -> None:
|
||||
"""在行为日志中搜索文本(使用通用搜索实现)"""
|
||||
state["current_index"] = generic_search_widget(
|
||||
actions_log_text,
|
||||
actions_search_var,
|
||||
state["matches"],
|
||||
state["current_index"],
|
||||
direction,
|
||||
)
|
||||
|
||||
def search_next_in_actions() -> None:
|
||||
search_in_actions_log(1)
|
||||
|
||||
def search_prev_in_actions() -> None:
|
||||
search_in_actions_log(-1)
|
||||
|
||||
def clear_search_in_actions() -> None:
|
||||
actions_search_var.set("")
|
||||
actions_log_text.tag_remove("search_highlight", "1.0", "end")
|
||||
actions_log_text.tag_remove("search_current", "1.0", "end")
|
||||
state["matches"] = []
|
||||
state["current_index"] = -1
|
||||
|
||||
def on_actions_search_entry_key(event):
|
||||
if event.keysym == "Return":
|
||||
search_next_in_actions()
|
||||
|
||||
actions_search_entry.bind("<KeyPress>", on_actions_search_entry_key)
|
||||
|
||||
ttk.Button(parent, text="搜索", command=search_next_in_actions).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(parent, text="上一个", command=search_prev_in_actions).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(parent, text="下一个", command=search_next_in_actions).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(parent, text="清除", command=clear_search_in_actions).pack(
|
||||
side=LEFT
|
||||
)
|
||||
|
||||
return ActionsLogToolbarHandles(
|
||||
refresh_actions_log=refresh_actions_log,
|
||||
)
|
||||
@@ -0,0 +1,183 @@
|
||||
"""行为日志(``logs/actions.log``) Tab 的视图刷新与配色逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的两个闭包
|
||||
``configure_actions_log_colors`` 和 ``refresh_actions_log``,
|
||||
搜索相关的小闭包仍保留在 ``gui_app.py`` 中(它们共享 nonlocal 状态)。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``text_widget`` - 展示用的 Text/ScrolledText
|
||||
- ``theme_getter`` - 一个 ``() -> str`` 回调,返回当前 GUI 主题名
|
||||
- ``filter_getter`` - 一个 ``() -> str`` 回调,返回筛选关键字(已 strip)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
try:
|
||||
from gui.components.log_color_config import (
|
||||
apply_operation_color,
|
||||
get_color_config,
|
||||
)
|
||||
except ImportError:
|
||||
def get_color_config(theme: str = "litera"): # type: ignore[no-redef]
|
||||
return {}
|
||||
|
||||
def apply_operation_color(*args, **kwargs): # type: ignore[no-redef]
|
||||
pass
|
||||
|
||||
|
||||
def configure_actions_log_colors(
|
||||
text_widget: tk.Text,
|
||||
*,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> None:
|
||||
"""根据当前主题配置行为日志的颜色标签"""
|
||||
try:
|
||||
# 获取当前主题
|
||||
try:
|
||||
current_theme = theme_getter()
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
# 获取颜色配置
|
||||
color_config = get_color_config(current_theme)
|
||||
|
||||
# 根据主题设置背景和前景色
|
||||
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
|
||||
is_light = current_theme.lower() in light_themes
|
||||
if is_light:
|
||||
text_widget.configure(
|
||||
background="#FFFFFF",
|
||||
foreground="#2C2C2C",
|
||||
insertbackground="#2C2C2C",
|
||||
)
|
||||
else:
|
||||
text_widget.configure(
|
||||
background="#1E1E1E",
|
||||
foreground="#E0E0E0",
|
||||
insertbackground="#FFFFFF",
|
||||
)
|
||||
|
||||
# 为所有操作类型配置标签
|
||||
for op_type, colors in color_config.items():
|
||||
tag_name = f"op_{op_type}"
|
||||
try:
|
||||
text_widget.tag_configure(
|
||||
tag_name,
|
||||
foreground=colors["foreground"],
|
||||
background=colors["background"],
|
||||
)
|
||||
except Exception:
|
||||
pass # 忽略标签配置失败
|
||||
except Exception:
|
||||
pass # 忽略颜色配置失败
|
||||
|
||||
|
||||
def refresh_actions_log(
|
||||
text_widget: tk.Text,
|
||||
*,
|
||||
theme_getter: Callable[[], str],
|
||||
filter_getter: Callable[[], str],
|
||||
) -> None:
|
||||
"""读取 logs/actions.log 的尾部若干行,在 GUI 中展示关键行为日志(支持简单关键字筛选)。"""
|
||||
# 使用统一的路径配置
|
||||
try:
|
||||
from douyin.core.path_config import get_actions_log_path
|
||||
|
||||
path = get_actions_log_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
# 修正路径:GUI应该读取根目录的logs/actions.log
|
||||
from douyin.core import path_config
|
||||
|
||||
path = path_config.get_actions_log_path()
|
||||
try:
|
||||
if os.path.exists(path):
|
||||
# 仿照 web_gui 的实现:只读最后一小段,避免文件巨大
|
||||
size = os.path.getsize(path)
|
||||
if size == 0:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", "行为日志文件为空")
|
||||
return
|
||||
|
||||
read_bytes = min(size, 65536)
|
||||
with open(path, "rb") as f:
|
||||
if read_bytes < size:
|
||||
f.seek(-read_bytes, os.SEEK_END)
|
||||
data = f.read()
|
||||
# 尝试多种编码方式
|
||||
try:
|
||||
# 先尝试 utf-8-sig(带BOM)
|
||||
text = data.decode("utf-8-sig", errors="replace")
|
||||
except Exception:
|
||||
try:
|
||||
# 再尝试 utf-8
|
||||
text = data.decode("utf-8", errors="replace")
|
||||
except Exception:
|
||||
# 最后尝试 gbk(Windows常见编码)
|
||||
text = data.decode("gbk", errors="replace")
|
||||
lines = text.splitlines()
|
||||
# 只取最近 300 行
|
||||
tail = lines[-300:]
|
||||
|
||||
# 关键字筛选:若填写了筛选词,只保留包含该关键字的行
|
||||
kw = filter_getter()
|
||||
if kw:
|
||||
tail = [ln for ln in tail if kw in ln]
|
||||
|
||||
# 保存当前滚动位置,避免刷新时自动置顶
|
||||
try:
|
||||
scroll_position = text_widget.yview()[
|
||||
0
|
||||
] # 获取当前滚动位置(顶部可见位置的比例)
|
||||
except Exception:
|
||||
scroll_position = 0.0
|
||||
|
||||
text_widget.delete("1.0", "end")
|
||||
if tail:
|
||||
# 获取当前主题(用于颜色配置)
|
||||
try:
|
||||
current_theme = theme_getter()
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
# 逐行插入并应用颜色标签
|
||||
for i, line in enumerate(tail):
|
||||
start_pos = text_widget.index("end-1c")
|
||||
|
||||
# 插入行内容
|
||||
if i > 0:
|
||||
text_widget.insert("end", "\n")
|
||||
text_widget.insert("end", line)
|
||||
|
||||
# 使用统一的颜色配置模块应用颜色
|
||||
end_pos = text_widget.index("end")
|
||||
try:
|
||||
apply_operation_color(
|
||||
text_widget,
|
||||
start_pos,
|
||||
end_pos,
|
||||
line,
|
||||
current_theme,
|
||||
)
|
||||
except Exception:
|
||||
pass # 忽略颜色应用失败
|
||||
else:
|
||||
text_widget.insert("1.0", "暂无匹配的行为日志")
|
||||
|
||||
# 恢复之前的滚动位置,避免自动置顶
|
||||
try:
|
||||
text_widget.yview_moveto(scroll_position)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert(
|
||||
"1.0", "暂无行为日志(logs/actions.log 不存在)"
|
||||
)
|
||||
except Exception as e:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", f"读取行为日志失败:{e}")
|
||||
@@ -0,0 +1,678 @@
|
||||
"""GUI 配置序列化:从 config.json 加载 → tk Vars,以及 Vars → config.json 保存。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的两个闭包
|
||||
``load_config_to_ui`` 和 ``save_ui_to_config``,共依赖 122 个 tk Var 和 5 个 Text widget。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``vars_`` - 一个名→Var 的 ``Dict[str, tk.Variable]``,键名与原 main() 中的变量名一致
|
||||
- ``texts_`` - 一个名→Text widget 的 ``Dict[str, tk.Text]``(want_text/not_want_text 等)
|
||||
- ``read_config`` - 读配置回调
|
||||
- ``write_config`` - 写配置回调
|
||||
- ``on_line`` - 日志回调
|
||||
|
||||
``load_config_to_ui`` 把 ``cfg`` 当作 nonlocal 变量原地赋值,这里改为返回新 cfg 让调用方更新。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Callable, Dict
|
||||
|
||||
|
||||
def load_config_to_ui(
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
texts_: Dict[str, tk.Text],
|
||||
read_config: Callable[[], dict],
|
||||
) -> dict:
|
||||
cfg = read_config()
|
||||
vars_["needswitch_var"].set(bool(cfg.get("needswitch", True)))
|
||||
vars_["infinite_loop_var"].set(bool(cfg.get("infinite_loop_enabled", False)))
|
||||
vars_["wait_minutes_var"].set(int(cfg.get("wait_minutes", 5) or 5))
|
||||
vars_["yg_enabled_var"].set(bool(cfg.get("yanghao_enabled", True)))
|
||||
vars_["yg_actions_enabled_var"].set(bool(cfg.get("yanghao_enable_actions", True)))
|
||||
vars_["yg_only_var"].set(bool(cfg.get("yanghao_only", False)))
|
||||
vars_["yg_recommend_duration_var"].set(
|
||||
int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60)
|
||||
)
|
||||
vars_["yg_recommend_interval_var"].set(
|
||||
int(cfg.get("yanghao_recommend_interval_seconds", 0) or 0)
|
||||
)
|
||||
vars_["min_value_var"].set(float(cfg.get("min_prize_value_yuan", 0) or 0))
|
||||
vars_["min_participants_var"].set(int(cfg.get("min_participants", 0) or 0))
|
||||
vars_["max_participants_var"].set(int(cfg.get("max_participants", 0) or 0))
|
||||
vars_["skip_gt_seconds_var"].set(
|
||||
int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)
|
||||
)
|
||||
vars_["reset_after_swipes_enabled_var"].set(
|
||||
bool(cfg.get("reset_after_swipes_enabled", False))
|
||||
)
|
||||
vars_["reset_after_swipes_var"].set(int(cfg.get("reset_after_swipes", 10) or 10))
|
||||
vars_["reset_after_swipes_action_var"].set(
|
||||
str(cfg.get("reset_after_swipes_action", "swipe") or "swipe")
|
||||
)
|
||||
vars_["enable_back_on_misses_var"].set(bool(cfg.get("enable_back_on_misses", True)))
|
||||
vars_["swipe_down_back_enabled_var"].set(
|
||||
bool(cfg.get("swipe_down_back_enabled", False))
|
||||
)
|
||||
vars_["swipe_down_back_count_var"].set(int(cfg.get("swipe_down_back_count", 3) or 3))
|
||||
vars_["auto_join_var"].set(bool(cfg.get("auto_join_fansclub", False)))
|
||||
vars_["fansclub_action_var"].set(
|
||||
str(cfg.get("fansclub_fail_action", "stay") or "stay").lower()
|
||||
)
|
||||
vars_["streaming_enabled_var"].set(bool(cfg.get("enable_streaming_screenshot", True)))
|
||||
vars_["lucky_draw_red_ratio_threshold_var"].set(
|
||||
float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)
|
||||
)
|
||||
vars_["y_var"].set(int(cfg.get("y_pianyi", 0) or 0))
|
||||
|
||||
# Web端新增配置 - 高价值预约相关
|
||||
vars_["high_value_fudai_enabled_var"].set(
|
||||
bool(cfg.get("high_value_fudai_enabled", False))
|
||||
)
|
||||
vars_["high_value_fudai_threshold_yuan_var"].set(
|
||||
float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000)
|
||||
)
|
||||
vars_["high_value_fudai_join_ahead_seconds_var"].set(
|
||||
int(cfg.get("high_value_fudai_join_ahead_seconds", 300) or 300)
|
||||
)
|
||||
vars_["high_value_fudai_max_swipe_back_var"].set(
|
||||
int(cfg.get("high_value_fudai_max_swipe_back", 60) or 60)
|
||||
)
|
||||
vars_["high_value_fudai_max_reservations_var"].set(
|
||||
int(cfg.get("high_value_fudai_max_reservations", 5) or 5)
|
||||
)
|
||||
vars_["high_value_fudai_after_action_var"].set(
|
||||
str(cfg.get("high_value_fudai_after_action", "continue") or "continue")
|
||||
)
|
||||
vars_["high_value_fudai_poll_before_seconds_var"].set(
|
||||
float(cfg.get("high_value_fudai_poll_before_seconds", 10.0) or 10.0)
|
||||
)
|
||||
vars_["high_value_room_revisit_enabled_var"].set(
|
||||
bool(cfg.get("high_value_room_revisit_enabled", True))
|
||||
)
|
||||
vars_["high_value_room_revisit_only_current_run_var"].set(
|
||||
bool(cfg.get("high_value_room_revisit_only_current_run", False))
|
||||
)
|
||||
vars_["high_value_room_revisit_min_interval_seconds_var"].set(
|
||||
int(cfg.get("high_value_room_revisit_min_interval_seconds", 300))
|
||||
)
|
||||
vars_["high_value_room_revisit_max_per_run_var"].set(
|
||||
int(cfg.get("high_value_room_revisit_max_per_run", 5))
|
||||
)
|
||||
vars_["high_value_room_revisit_min_prize_value_var"].set(
|
||||
float(cfg.get("high_value_room_revisit_min_prize_value", 0.0))
|
||||
)
|
||||
vars_["high_value_room_revisit_max_age_days_var"].set(
|
||||
int(cfg.get("high_value_room_revisit_max_age_days", 30))
|
||||
)
|
||||
vars_["reservation_back_verify_enabled_var"].set(
|
||||
bool(cfg.get("reservation_back_verify_enabled", True))
|
||||
)
|
||||
vars_["reservation_back_swipe_delay_var"].set(
|
||||
float(cfg.get("reservation_back_swipe_delay", 0) or 0)
|
||||
)
|
||||
vars_["reservation_back_verify_wait_seconds_var"].set(
|
||||
float(cfg.get("reservation_back_verify_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
vars_["fudai_find_max_attempts_var"].set(int(cfg.get("fudai_find_max_attempts", 0) or 0))
|
||||
vars_["fudai_icon_retry_delay_seconds_var"].set(
|
||||
float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
|
||||
)
|
||||
vars_["fudai_icon_max_wait_seconds_var"].set(
|
||||
float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
vars_["fudai_click_wait_seconds_var"].set(
|
||||
float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0)
|
||||
)
|
||||
vars_["fudai_disable_content_recognition_var"].set(
|
||||
bool(cfg.get("fudai_disable_content_recognition", False))
|
||||
)
|
||||
vars_["fudai_disable_task_recognition_var"].set(
|
||||
bool(cfg.get("fudai_disable_task_recognition", False))
|
||||
)
|
||||
try:
|
||||
vars_["fudai_exit_after_misses_var"].set(
|
||||
int(cfg.get("fudai_exit_after_misses", 30) or 30)
|
||||
)
|
||||
except Exception:
|
||||
vars_["fudai_exit_after_misses_var"].set(30)
|
||||
try:
|
||||
vars_["enable_back_on_misses_var"].set(bool(cfg.get("enable_back_on_misses", True)))
|
||||
except Exception:
|
||||
vars_["enable_back_on_misses_var"].set(True)
|
||||
try:
|
||||
vars_["reset_after_swipes_action_var"].set(
|
||||
str(cfg.get("reset_after_swipes_action", "swipe"))
|
||||
)
|
||||
except Exception:
|
||||
vars_["reset_after_swipes_action_var"].set("swipe")
|
||||
vars_["switch_room_wait_after_stage_diag_seconds_var"].set(
|
||||
float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
|
||||
)
|
||||
# GUI 主题
|
||||
try:
|
||||
vars_["gui_theme_var"].set(
|
||||
str(cfg.get("gui", {}).get("theme", "litera") or "litera")
|
||||
)
|
||||
except Exception:
|
||||
vars_["gui_theme_var"].set("litera")
|
||||
vars_["live_room_match_threshold_var"].set(
|
||||
float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
|
||||
)
|
||||
vars_["swipe_duration_ms_var"].set(int(cfg.get("swipe_duration_ms", 600) or 600))
|
||||
vars_["swipe_up_start_y_var"].set(int(cfg.get("swipe_up_start_y", 1200) or 1200))
|
||||
vars_["swipe_up_end_y_var"].set(int(cfg.get("swipe_up_end_y", 600) or 600))
|
||||
vars_["fudai_quiet_hours_enabled_var"].set(
|
||||
bool(cfg.get("fudai_quiet_hours_enabled", True))
|
||||
)
|
||||
vars_["fudai_quiet_start_hour_var"].set(int(cfg.get("fudai_quiet_start_hour", 2) or 2))
|
||||
vars_["fudai_quiet_end_hour_var"].set(int(cfg.get("fudai_quiet_end_hour", 7) or 7))
|
||||
vars_["stage_diag_max_time_var"].set(float(cfg.get("stage_diag_max_time", 10.0) or 10.0))
|
||||
vars_["stage_diag_max_step_time_var"].set(
|
||||
float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)
|
||||
)
|
||||
vars_["stage_diag_verbose_var"].set(
|
||||
bool(cfg.get("logging", {}).get("stage_diag_verbose", True))
|
||||
)
|
||||
vars_["enable_ocr_mode1_var"].set(bool(cfg.get("enable_ocr_mode1", False)))
|
||||
vars_["fudai_template_match_enabled_var"].set(
|
||||
bool(cfg.get("fudai_template_match_enabled", False))
|
||||
)
|
||||
vars_["fudai_template_match_threshold_var"].set(
|
||||
float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)
|
||||
)
|
||||
vars_["fudai_detail_template_threshold_var"].set(
|
||||
float(cfg.get("fudai_detail_template_threshold", 0.7) or 0.7)
|
||||
)
|
||||
vars_["coupon_template_match_threshold_var"].set(
|
||||
float(cfg.get("coupon_template_match_threshold", 0.75) or 0.75)
|
||||
)
|
||||
vars_["attend_button_red_ratio_threshold_var"].set(
|
||||
float(cfg.get("attend_button_red_ratio_threshold", 0.25) or 0.25)
|
||||
)
|
||||
vars_["fansclub_join_red_ratio_threshold_var"].set(
|
||||
float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25)
|
||||
)
|
||||
vars_["shopping_redpacket_red_ratio_threshold_var"].set(
|
||||
float(cfg.get("shopping_redpacket_red_ratio_threshold", 0.15) or 0.15)
|
||||
)
|
||||
# 粉丝团等待/点击延迟配置
|
||||
vars_["fansclub_click_delay_var"].set(float(cfg.get("fansclub_click_delay", 0.6) or 0.6))
|
||||
vars_["fansclub_auto_wait_var"].set(
|
||||
float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
vars_["fansclub_manual_wait_var"].set(
|
||||
float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0)
|
||||
)
|
||||
vars_["skip_lt_seconds_var"].set(int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10))
|
||||
|
||||
# 调试图像清理配置
|
||||
debug_captures_config = cfg.get("debug_captures", {})
|
||||
if isinstance(debug_captures_config, dict):
|
||||
vars_["debug_captures_enabled_var"].set(
|
||||
bool(debug_captures_config.get("enabled", False))
|
||||
)
|
||||
vars_["debug_captures_auto_cleanup_var"].set(
|
||||
bool(debug_captures_config.get("auto_cleanup", True))
|
||||
)
|
||||
vars_["debug_captures_keep_days_var"].set(
|
||||
int(debug_captures_config.get("keep_days", 7) or 7)
|
||||
)
|
||||
vars_["debug_captures_max_files_var"].set(
|
||||
int(debug_captures_config.get("max_files", 2000) or 2000)
|
||||
)
|
||||
vars_["debug_captures_async_save_var"].set(
|
||||
bool(debug_captures_config.get("async_save", True))
|
||||
)
|
||||
vars_["debug_captures_log_on_complete_var"].set(
|
||||
bool(debug_captures_config.get("log_on_complete", False))
|
||||
)
|
||||
else:
|
||||
vars_["debug_captures_auto_cleanup_var"].set(True)
|
||||
vars_["debug_captures_keep_days_var"].set(7)
|
||||
vars_["debug_captures_max_files_var"].set(2000)
|
||||
|
||||
# 日志配置(load_config_to_ui 需要覆盖 UI 变量,避免“保存后再加载不生效”)
|
||||
logging_config = cfg.get("logging", {})
|
||||
if isinstance(logging_config, dict):
|
||||
vars_["logging_beautify_var"].set(bool(logging_config.get("beautify_output", True)))
|
||||
vars_["logging_color_var"].set(bool(logging_config.get("color_output", True)))
|
||||
vars_["logging_show_timestamps_var"].set(
|
||||
bool(logging_config.get("show_timestamps", True))
|
||||
)
|
||||
vars_["logging_use_dated_logs_var"].set(
|
||||
bool(logging_config.get("use_dated_logs", True))
|
||||
)
|
||||
vars_["logging_enable_monitor_var"].set(
|
||||
bool(logging_config.get("enable_monitor", True))
|
||||
)
|
||||
vars_["log_unified_enabled_var"].set(bool(cfg.get("log_unified_enabled", True)))
|
||||
vars_["log_unified_path_var"].set(
|
||||
str(cfg.get("log_unified_path", "logs/unified.log") or "logs/unified.log")
|
||||
)
|
||||
vars_["logging_keep_days_var"].set(int(logging_config.get("keep_days", 30) or 30))
|
||||
vars_["logging_compress_logs_var"].set(
|
||||
bool(logging_config.get("compress_logs", True))
|
||||
)
|
||||
vars_["logging_max_total_size_gb_var"].set(
|
||||
float(logging_config.get("max_total_size_gb", 10.0) or 10.0)
|
||||
)
|
||||
vars_["logging_compress_after_days_var"].set(
|
||||
int(logging_config.get("compress_after_days", 7) or 7)
|
||||
)
|
||||
vars_["logging_debug_level_var"].set(
|
||||
str(logging_config.get("debug_detail_level", "normal") or "normal")
|
||||
)
|
||||
vars_["logging_error_level_var"].set(
|
||||
str(logging_config.get("error_detail_level", "full") or "full")
|
||||
)
|
||||
vars_["logging_action_format_var"].set(
|
||||
str(logging_config.get("action_log_format", "concise") or "concise")
|
||||
)
|
||||
vars_["logging_format_mode_var"].set(
|
||||
str(logging_config.get("log_format_mode", "simple") or "simple")
|
||||
)
|
||||
perf_cfg = logging_config.get("performance_tracking", {})
|
||||
if isinstance(perf_cfg, dict):
|
||||
vars_["logging_performance_enabled_var"].set(bool(perf_cfg.get("enabled", True)))
|
||||
vars_["logging_track_functions_var"].set(
|
||||
bool(perf_cfg.get("track_function_calls", True))
|
||||
)
|
||||
vars_["logging_monitor_warning_mb_var"].set(
|
||||
float(logging_config.get("monitor_warning_mb", 500.0) or 500.0)
|
||||
)
|
||||
vars_["logging_monitor_critical_mb_var"].set(
|
||||
float(logging_config.get("monitor_critical_mb", 2000.0) or 2000.0)
|
||||
)
|
||||
|
||||
vars_["yg_like_prob_var"].set(float(cfg.get("yanghao_like_prob", 0.0) or 0.0))
|
||||
vars_["yg_fav_prob_var"].set(float(cfg.get("yanghao_fav_prob", 0.0) or 0.0))
|
||||
vars_["yg_comment_prob_var"].set(float(cfg.get("yanghao_comment_prob", 0.0) or 0.0))
|
||||
vars_["yg_dwell_on_action_min_var"].set(
|
||||
float(cfg.get("yanghao_dwell_on_action_min_seconds", 5) or 5)
|
||||
)
|
||||
vars_["yg_dwell_on_action_max_var"].set(
|
||||
float(cfg.get("yanghao_dwell_on_action_max_seconds", 30) or 30)
|
||||
)
|
||||
vars_["yg_icon_roi_size_var"].set(int(cfg.get("yanghao_icon_roi_size", 240) or 240))
|
||||
vars_["yg_icon_match_threshold_var"].set(
|
||||
float(cfg.get("yanghao_icon_match_threshold", 0.72) or 0.72)
|
||||
)
|
||||
vars_["yg_step_screenshot_var"].set(bool(cfg.get("yanghao_step_screenshot", False)))
|
||||
vars_["yg_like_roi_offset_x_var"].set(int(cfg.get("yanghao_like_roi_offset_x", 0) or 0))
|
||||
vars_["yg_like_roi_offset_y_var"].set(int(cfg.get("yanghao_like_roi_offset_y", 0) or 0))
|
||||
vars_["yg_fav_roi_offset_x_var"].set(int(cfg.get("yanghao_fav_roi_offset_x", 0) or 0))
|
||||
vars_["yg_fav_roi_offset_y_var"].set(int(cfg.get("yanghao_fav_roi_offset_y", 0) or 0))
|
||||
vars_["yg_like_icon_x_var"].set(int(cfg.get("yanghao_like_icon_x", 0) or 0))
|
||||
vars_["yg_like_icon_y_var"].set(int(cfg.get("yanghao_like_icon_y", 0) or 0))
|
||||
vars_["yg_fav_icon_x_var"].set(int(cfg.get("yanghao_fav_icon_x", 0) or 0))
|
||||
vars_["yg_fav_icon_y_var"].set(int(cfg.get("yanghao_fav_icon_y", 0) or 0))
|
||||
vars_["yg_like_template_path_var"].set(
|
||||
str(
|
||||
cfg.get("yanghao_like_template_path", "assets/like.png")
|
||||
or "assets/like.png"
|
||||
)
|
||||
)
|
||||
vars_["yg_fav_template_path_var"].set(
|
||||
str(
|
||||
cfg.get("yanghao_fav_template_path", "assets/fav.png")
|
||||
or "assets/fav.png"
|
||||
)
|
||||
)
|
||||
vars_["yg_after_dwell_direction_var"].set(
|
||||
str(cfg.get("yanghao_after_dwell_swipe_direction", "up") or "up")
|
||||
)
|
||||
vars_["yg_after_dwell_distance_var"].set(
|
||||
int(cfg.get("yanghao_after_dwell_swipe_distance_px", 900) or 900)
|
||||
)
|
||||
vars_["yg_comment_btn_x_var"].set(int(cfg.get("yanghao_comment_btn_x", 0) or 0))
|
||||
vars_["yg_comment_btn_y_var"].set(int(cfg.get("yanghao_comment_btn_y", 0) or 0))
|
||||
vars_["yg_comment_input_x_var"].set(int(cfg.get("yanghao_comment_input_x", 0) or 0))
|
||||
vars_["yg_comment_input_y_var"].set(int(cfg.get("yanghao_comment_input_y", 0) or 0))
|
||||
vars_["yg_comment_send_x_var"].set(int(cfg.get("yanghao_comment_send_x", 0) or 0))
|
||||
vars_["yg_comment_send_y_var"].set(int(cfg.get("yanghao_comment_send_y", 0) or 0))
|
||||
vars_["yg_comment_close_x_var"].set(int(cfg.get("yanghao_comment_close_x", 0) or 0))
|
||||
vars_["yg_comment_close_y_var"].set(int(cfg.get("yanghao_comment_close_y", 0) or 0))
|
||||
|
||||
# 仅保留黑名单 contains_not_want
|
||||
want = cfg.get("contains_want", []) or []
|
||||
not_want = cfg.get("contains_not_want", []) or []
|
||||
yg_comment_texts_list = cfg.get("yanghao_comment_texts", []) or []
|
||||
yg_like_keywords_list = cfg.get("yanghao_like_keywords", []) or []
|
||||
yg_fav_keywords_list = cfg.get("yanghao_fav_keywords", []) or []
|
||||
texts_["want_text"].delete("1.0", "end")
|
||||
texts_["want_text"].insert("1.0", "\n".join(want))
|
||||
texts_["not_want_text"].delete("1.0", "end")
|
||||
texts_["not_want_text"].insert("1.0", "\n".join(not_want))
|
||||
texts_["yg_comment_texts"].delete("1.0", "end")
|
||||
texts_["yg_comment_texts"].insert("1.0", "\n".join(yg_comment_texts_list))
|
||||
texts_["yg_like_keywords_text"].delete("1.0", "end")
|
||||
texts_["yg_like_keywords_text"].insert("1.0", "\n".join(yg_like_keywords_list))
|
||||
texts_["yg_fav_keywords_text"].delete("1.0", "end")
|
||||
texts_["yg_fav_keywords_text"].insert("1.0", "\n".join(yg_fav_keywords_list))
|
||||
|
||||
return cfg
|
||||
|
||||
|
||||
def save_ui_to_config(
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
texts_: Dict[str, tk.Text],
|
||||
cfg: dict,
|
||||
read_config: Callable[[], dict],
|
||||
write_config: Callable[[dict], None],
|
||||
on_line: Callable[[str], None],
|
||||
) -> None:
|
||||
want_lines = [
|
||||
x.strip() for x in texts_["want_text"].get("1.0", "end").splitlines() if x.strip()
|
||||
]
|
||||
not_want_lines = [
|
||||
x.strip() for x in texts_["not_want_text"].get("1.0", "end").splitlines() if x.strip()
|
||||
]
|
||||
yg_comment_text_lines = [
|
||||
x.strip()
|
||||
for x in texts_["yg_comment_texts"].get("1.0", "end").splitlines()
|
||||
if x.strip()
|
||||
]
|
||||
yg_like_kw_lines = [
|
||||
x.strip()
|
||||
for x in texts_["yg_like_keywords_text"].get("1.0", "end").splitlines()
|
||||
if x.strip()
|
||||
]
|
||||
yg_fav_kw_lines = [
|
||||
x.strip()
|
||||
for x in texts_["yg_fav_keywords_text"].get("1.0", "end").splitlines()
|
||||
if x.strip()
|
||||
]
|
||||
|
||||
cfg2 = read_config()
|
||||
cfg2["needswitch"] = bool(vars_["needswitch_var"].get())
|
||||
cfg2["infinite_loop_enabled"] = bool(vars_["infinite_loop_var"].get())
|
||||
cfg2["wait_minutes"] = int(vars_["wait_minutes_var"].get() or 5)
|
||||
cfg2["y_pianyi"] = int(vars_["y_var"].get() or 0)
|
||||
cfg2["contains_want"] = want_lines
|
||||
cfg2["contains_not_want"] = not_want_lines
|
||||
cfg2["min_prize_value_yuan"] = float(vars_["min_value_var"].get() or 0)
|
||||
cfg2["min_participants"] = int(vars_["min_participants_var"].get() or 0)
|
||||
cfg2["max_participants"] = int(vars_["max_participants_var"].get() or 0)
|
||||
cfg2["skip_if_countdown_gt_seconds"] = int(vars_["skip_gt_seconds_var"].get() or 900)
|
||||
cfg2["reset_after_swipes_enabled"] = bool(vars_["reset_after_swipes_enabled_var"].get())
|
||||
cfg2["reset_after_swipes"] = int(vars_["reset_after_swipes_var"].get() or 10)
|
||||
cfg2["auto_join_fansclub"] = bool(vars_["auto_join_var"].get())
|
||||
cfg2["fansclub_fail_action"] = str(vars_["fansclub_action_var"].get() or "stay").lower()
|
||||
cfg2["lucky_draw_red_ratio_threshold"] = float(
|
||||
vars_["lucky_draw_red_ratio_threshold_var"].get() or 0.9
|
||||
)
|
||||
|
||||
# Web端新增配置 - 高价值预约相关
|
||||
cfg2["high_value_fudai_enabled"] = bool(vars_["high_value_fudai_enabled_var"].get())
|
||||
cfg2["high_value_fudai_threshold_yuan"] = float(
|
||||
vars_["high_value_fudai_threshold_yuan_var"].get() or 1000
|
||||
)
|
||||
cfg2["high_value_fudai_join_ahead_seconds"] = int(
|
||||
vars_["high_value_fudai_join_ahead_seconds_var"].get() or 300
|
||||
)
|
||||
cfg2["high_value_fudai_max_swipe_back"] = int(
|
||||
vars_["high_value_fudai_max_swipe_back_var"].get() or 60
|
||||
)
|
||||
cfg2["high_value_fudai_max_reservations"] = int(
|
||||
vars_["high_value_fudai_max_reservations_var"].get() or 5
|
||||
)
|
||||
cfg2["high_value_fudai_after_action"] = str(
|
||||
vars_["high_value_fudai_after_action_var"].get() or "continue"
|
||||
).lower()
|
||||
cfg2["high_value_fudai_poll_before_seconds"] = float(
|
||||
vars_["high_value_fudai_poll_before_seconds_var"].get() or 10.0
|
||||
)
|
||||
cfg2["high_value_room_revisit_enabled"] = bool(
|
||||
vars_["high_value_room_revisit_enabled_var"].get()
|
||||
)
|
||||
cfg2["high_value_room_revisit_only_current_run"] = bool(
|
||||
vars_["high_value_room_revisit_only_current_run_var"].get()
|
||||
)
|
||||
cfg2["high_value_room_revisit_min_interval_seconds"] = int(
|
||||
vars_["high_value_room_revisit_min_interval_seconds_var"].get()
|
||||
)
|
||||
cfg2["high_value_room_revisit_max_per_run"] = int(
|
||||
vars_["high_value_room_revisit_max_per_run_var"].get()
|
||||
)
|
||||
cfg2["high_value_room_revisit_min_prize_value"] = float(
|
||||
vars_["high_value_room_revisit_min_prize_value_var"].get()
|
||||
)
|
||||
cfg2["high_value_room_revisit_max_age_days"] = int(
|
||||
vars_["high_value_room_revisit_max_age_days_var"].get()
|
||||
)
|
||||
cfg2["reservation_back_verify_enabled"] = bool(
|
||||
vars_["reservation_back_verify_enabled_var"].get()
|
||||
)
|
||||
cfg2["reservation_back_swipe_delay"] = float(
|
||||
vars_["reservation_back_swipe_delay_var"].get() or 0
|
||||
)
|
||||
cfg2["reservation_back_verify_wait_seconds"] = float(
|
||||
vars_["reservation_back_verify_wait_seconds_var"].get() or 5.0
|
||||
)
|
||||
cfg2["fudai_find_max_attempts"] = int(vars_["fudai_find_max_attempts_var"].get() or 0)
|
||||
cfg2["fudai_icon_retry_delay_seconds"] = float(
|
||||
vars_["fudai_icon_retry_delay_seconds_var"].get() or 0.6
|
||||
)
|
||||
cfg2["fudai_icon_max_wait_seconds"] = float(
|
||||
vars_["fudai_icon_max_wait_seconds_var"].get() or 5.0
|
||||
)
|
||||
cfg2["fudai_click_wait_seconds"] = float(
|
||||
vars_["fudai_click_wait_seconds_var"].get() or 2.0
|
||||
)
|
||||
cfg2["fudai_exit_after_misses"] = int(vars_["fudai_exit_after_misses_var"].get() or 30)
|
||||
cfg2["enable_back_on_misses"] = bool(vars_["enable_back_on_misses_var"].get())
|
||||
cfg2["swipe_down_back_enabled"] = bool(vars_["swipe_down_back_enabled_var"].get())
|
||||
cfg2["swipe_down_back_count"] = int(vars_["swipe_down_back_count_var"].get() or 3)
|
||||
cfg2["reset_after_swipes_action"] = str(
|
||||
vars_["reset_after_swipes_action_var"].get() or "swipe"
|
||||
)
|
||||
cfg2["fudai_disable_content_recognition"] = bool(
|
||||
vars_["fudai_disable_content_recognition_var"].get()
|
||||
)
|
||||
cfg2["fudai_disable_task_recognition"] = bool(
|
||||
vars_["fudai_disable_task_recognition_var"].get()
|
||||
)
|
||||
cfg2["switch_room_wait_after_stage_diag_seconds"] = float(
|
||||
vars_["switch_room_wait_after_stage_diag_seconds_var"].get() or 7.0
|
||||
)
|
||||
cfg2["live_room_match_threshold"] = float(
|
||||
vars_["live_room_match_threshold_var"].get() or 0.8
|
||||
)
|
||||
cfg2["swipe_duration_ms"] = int(vars_["swipe_duration_ms_var"].get() or 600)
|
||||
cfg2["swipe_up_start_y"] = int(vars_["swipe_up_start_y_var"].get() or 1200)
|
||||
cfg2["swipe_up_end_y"] = int(vars_["swipe_up_end_y_var"].get() or 600)
|
||||
cfg2["fudai_quiet_hours_enabled"] = bool(vars_["fudai_quiet_hours_enabled_var"].get())
|
||||
cfg2["fudai_quiet_start_hour"] = int(vars_["fudai_quiet_start_hour_var"].get() or 0)
|
||||
cfg2["fudai_quiet_end_hour"] = int(vars_["fudai_quiet_end_hour_var"].get() or 0)
|
||||
cfg2["stage_diag_max_time"] = float(vars_["stage_diag_max_time_var"].get() or 10.0)
|
||||
cfg2["stage_diag_max_step_time"] = float(
|
||||
vars_["stage_diag_max_step_time_var"].get() or 2.0
|
||||
)
|
||||
cfg2["enable_ocr_mode1"] = bool(cfg.get("enable_ocr_mode1", False))
|
||||
cfg2["fudai_template_match_enabled"] = bool(
|
||||
vars_["fudai_template_match_enabled_var"].get()
|
||||
)
|
||||
cfg2["fudai_template_match_threshold"] = float(
|
||||
vars_["fudai_template_match_threshold_var"].get() or 0.7
|
||||
)
|
||||
cfg2["fudai_detail_template_threshold"] = float(
|
||||
vars_["fudai_detail_template_threshold_var"].get() or 0.7
|
||||
)
|
||||
cfg2["coupon_template_match_threshold"] = float(
|
||||
vars_["coupon_template_match_threshold_var"].get() or 0.75
|
||||
)
|
||||
cfg2["attend_button_red_ratio_threshold"] = float(
|
||||
vars_["attend_button_red_ratio_threshold_var"].get() or 0.25
|
||||
)
|
||||
cfg2["fansclub_join_red_ratio_threshold"] = float(
|
||||
vars_["fansclub_join_red_ratio_threshold_var"].get() or 0.25
|
||||
)
|
||||
cfg2["shopping_redpacket_red_ratio_threshold"] = float(
|
||||
vars_["shopping_redpacket_red_ratio_threshold_var"].get() or 0.15
|
||||
)
|
||||
# 粉丝团等待/点击延迟配置
|
||||
cfg2["fansclub_click_delay"] = float(vars_["fansclub_click_delay_var"].get() or 0.6)
|
||||
cfg2["fansclub_auto_join_wait_seconds"] = float(
|
||||
vars_["fansclub_auto_wait_var"].get() or 5.0
|
||||
)
|
||||
cfg2["fansclub_manual_wait_seconds"] = float(
|
||||
vars_["fansclub_manual_wait_var"].get() or 3.0
|
||||
)
|
||||
cfg2["skip_if_countdown_lt_seconds"] = int(vars_["skip_lt_seconds_var"].get() or 10)
|
||||
|
||||
# 调试图像清理配置
|
||||
if "debug_captures" not in cfg2 or not isinstance(cfg2["debug_captures"], dict):
|
||||
cfg2["debug_captures"] = {}
|
||||
cfg2["debug_captures"]["enabled"] = bool(vars_["debug_captures_enabled_var"].get())
|
||||
cfg2["debug_captures"]["auto_cleanup"] = bool(
|
||||
vars_["debug_captures_auto_cleanup_var"].get()
|
||||
)
|
||||
cfg2["debug_captures"]["keep_days"] = int(
|
||||
vars_["debug_captures_keep_days_var"].get() or 7
|
||||
)
|
||||
cfg2["debug_captures"]["max_files"] = int(
|
||||
vars_["debug_captures_max_files_var"].get() or 2000
|
||||
)
|
||||
cfg2["debug_captures"]["async_save"] = bool(vars_["debug_captures_async_save_var"].get())
|
||||
cfg2["debug_captures"]["log_on_complete"] = bool(
|
||||
vars_["debug_captures_log_on_complete_var"].get()
|
||||
)
|
||||
|
||||
# 日志配置
|
||||
if "logging" not in cfg2 or not isinstance(cfg2["logging"], dict):
|
||||
cfg2["logging"] = {}
|
||||
cfg2["logging"]["beautify_output"] = bool(vars_["logging_beautify_var"].get())
|
||||
cfg2["logging"]["color_output"] = bool(vars_["logging_color_var"].get())
|
||||
cfg2["logging"]["show_timestamps"] = bool(vars_["logging_show_timestamps_var"].get())
|
||||
cfg2["logging"]["use_dated_logs"] = bool(vars_["logging_use_dated_logs_var"].get())
|
||||
cfg2["logging"]["enable_monitor"] = bool(vars_["logging_enable_monitor_var"].get())
|
||||
cfg2["logging"]["keep_days"] = int(vars_["logging_keep_days_var"].get() or 30)
|
||||
cfg2["logging"]["compress_logs"] = bool(vars_["logging_compress_logs_var"].get())
|
||||
cfg2["logging"]["max_total_size_gb"] = float(
|
||||
vars_["logging_max_total_size_gb_var"].get() or 10.0
|
||||
)
|
||||
cfg2["logging"]["compress_after_days"] = int(
|
||||
vars_["logging_compress_after_days_var"].get() or 7
|
||||
)
|
||||
cfg2["logging"]["debug_detail_level"] = str(
|
||||
vars_["logging_debug_level_var"].get() or "normal"
|
||||
)
|
||||
cfg2["logging"]["error_detail_level"] = str(
|
||||
vars_["logging_error_level_var"].get() or "full"
|
||||
)
|
||||
cfg2["logging"]["action_log_format"] = str(
|
||||
vars_["logging_action_format_var"].get() or "concise"
|
||||
)
|
||||
cfg2["logging"]["log_format_mode"] = str(
|
||||
vars_["logging_format_mode_var"].get() or "simple"
|
||||
)
|
||||
cfg2["logging"]["stage_diag_verbose"] = bool(vars_["stage_diag_verbose_var"].get())
|
||||
cfg2["logging"]["monitor_warning_mb"] = float(
|
||||
vars_["logging_monitor_warning_mb_var"].get() or 500.0
|
||||
)
|
||||
cfg2["logging"]["monitor_critical_mb"] = float(
|
||||
vars_["logging_monitor_critical_mb_var"].get() or 2000.0
|
||||
)
|
||||
|
||||
# 性能追踪配置
|
||||
if "performance_tracking" not in cfg2["logging"] or not isinstance(
|
||||
cfg2["logging"]["performance_tracking"], dict
|
||||
):
|
||||
cfg2["logging"]["performance_tracking"] = {}
|
||||
cfg2["logging"]["performance_tracking"]["enabled"] = bool(
|
||||
vars_["logging_performance_enabled_var"].get()
|
||||
)
|
||||
cfg2["logging"]["performance_tracking"]["track_function_calls"] = bool(
|
||||
vars_["logging_track_functions_var"].get()
|
||||
)
|
||||
cfg2["log_unified_enabled"] = bool(vars_["log_unified_enabled_var"].get())
|
||||
cfg2["log_unified_path"] = str(vars_["log_unified_path_var"].get() or "logs/unified.log")
|
||||
|
||||
cfg2["yanghao_enabled"] = bool(vars_["yg_enabled_var"].get())
|
||||
cfg2["yanghao_enable_actions"] = bool(vars_["yg_actions_enabled_var"].get())
|
||||
cfg2["yanghao_only"] = bool(vars_["yg_only_var"].get())
|
||||
cfg2["yanghao_recommend_duration_seconds"] = int(
|
||||
vars_["yg_recommend_duration_var"].get() or 60
|
||||
)
|
||||
cfg2["yanghao_recommend_interval_seconds"] = int(
|
||||
vars_["yg_recommend_interval_var"].get() or 0
|
||||
)
|
||||
cfg2["yanghao_like_prob"] = float(vars_["yg_like_prob_var"].get() or 0.0)
|
||||
cfg2["yanghao_fav_prob"] = float(vars_["yg_fav_prob_var"].get() or 0.0)
|
||||
cfg2["yanghao_comment_prob"] = float(vars_["yg_comment_prob_var"].get() or 0.0)
|
||||
cfg2["yanghao_dwell_on_action_min_seconds"] = float(
|
||||
vars_["yg_dwell_on_action_min_var"].get() or 5
|
||||
)
|
||||
cfg2["yanghao_dwell_on_action_max_seconds"] = float(
|
||||
vars_["yg_dwell_on_action_max_var"].get() or 30
|
||||
)
|
||||
cfg2["yanghao_icon_roi_size"] = int(vars_["yg_icon_roi_size_var"].get() or 240)
|
||||
cfg2["yanghao_icon_match_threshold"] = float(
|
||||
vars_["yg_icon_match_threshold_var"].get() or 0.72
|
||||
)
|
||||
cfg2["yanghao_step_screenshot"] = bool(vars_["yg_step_screenshot_var"].get())
|
||||
cfg2["yanghao_like_roi_offset_x"] = int(vars_["yg_like_roi_offset_x_var"].get() or 0)
|
||||
cfg2["yanghao_like_roi_offset_y"] = int(vars_["yg_like_roi_offset_y_var"].get() or 0)
|
||||
cfg2["yanghao_fav_roi_offset_x"] = int(vars_["yg_fav_roi_offset_x_var"].get() or 0)
|
||||
cfg2["yanghao_fav_roi_offset_y"] = int(vars_["yg_fav_roi_offset_y_var"].get() or 0)
|
||||
cfg2["yanghao_like_icon_x"] = int(vars_["yg_like_icon_x_var"].get() or 0)
|
||||
cfg2["yanghao_like_icon_y"] = int(vars_["yg_like_icon_y_var"].get() or 0)
|
||||
cfg2["yanghao_fav_icon_x"] = int(vars_["yg_fav_icon_x_var"].get() or 0)
|
||||
cfg2["yanghao_fav_icon_y"] = int(vars_["yg_fav_icon_y_var"].get() or 0)
|
||||
cfg2["yanghao_like_template_path"] = str(
|
||||
vars_["yg_like_template_path_var"].get() or "assets/like.png"
|
||||
)
|
||||
cfg2["yanghao_fav_template_path"] = str(
|
||||
vars_["yg_fav_template_path_var"].get() or "assets/fav.png"
|
||||
)
|
||||
cfg2["yanghao_after_dwell_swipe_direction"] = str(
|
||||
vars_["yg_after_dwell_direction_var"].get() or "up"
|
||||
)
|
||||
cfg2["yanghao_after_dwell_swipe_distance_px"] = int(
|
||||
vars_["yg_after_dwell_distance_var"].get() or 900
|
||||
)
|
||||
cfg2["yanghao_comment_btn_x"] = int(vars_["yg_comment_btn_x_var"].get() or 0)
|
||||
cfg2["yanghao_comment_btn_y"] = int(vars_["yg_comment_btn_y_var"].get() or 0)
|
||||
cfg2["yanghao_comment_input_x"] = int(vars_["yg_comment_input_x_var"].get() or 0)
|
||||
cfg2["yanghao_comment_input_y"] = int(vars_["yg_comment_input_y_var"].get() or 0)
|
||||
cfg2["yanghao_comment_send_x"] = int(vars_["yg_comment_send_x_var"].get() or 0)
|
||||
cfg2["yanghao_comment_send_y"] = int(vars_["yg_comment_send_y_var"].get() or 0)
|
||||
cfg2["yanghao_comment_close_x"] = int(vars_["yg_comment_close_x_var"].get() or 0)
|
||||
cfg2["yanghao_comment_close_y"] = int(vars_["yg_comment_close_y_var"].get() or 0)
|
||||
cfg2["yanghao_comment_texts"] = yg_comment_text_lines
|
||||
cfg2["yanghao_like_keywords"] = yg_like_kw_lines
|
||||
cfg2["yanghao_fav_keywords"] = yg_fav_kw_lines
|
||||
|
||||
# 流式后台截图配置
|
||||
cfg2["enable_streaming_screenshot"] = bool(vars_["streaming_enabled_var"].get())
|
||||
|
||||
# GUI 配置
|
||||
if "gui" not in cfg2 or not isinstance(cfg2["gui"], dict):
|
||||
cfg2["gui"] = {}
|
||||
cfg2["gui"]["theme"] = str(vars_["gui_theme_var"].get() or "litera")
|
||||
cfg2["gui"]["realtime_status"] = {
|
||||
"refresh_interval_ms": int(
|
||||
vars_["gui_realtime_refresh_interval_ms_var"].get() or 1000
|
||||
),
|
||||
"tail_items": int(vars_["gui_realtime_tail_items_var"].get() or 50),
|
||||
}
|
||||
|
||||
write_config(cfg2)
|
||||
on_line("[配置] 已保存到 config.json")
|
||||
# 如果用户关闭了流式后台截图,尝试停止正在运行的服务实例以立即生效
|
||||
try:
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
|
||||
if not bool(cfg2.get("enable_streaming_screenshot", True)):
|
||||
try:
|
||||
ScreenshotService.get_instance().stop()
|
||||
on_line("[截图服务] 已停止后台流式截图(配置更新)")
|
||||
except Exception:
|
||||
on_line("[截图服务] 停止后台截图服务失败(请重启程序以确保生效)")
|
||||
except Exception:
|
||||
# ignore if service module not available
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,538 @@
|
||||
"""GUI Var 工厂:从 ``cfg`` 构建所有 ``tkinter`` Var 实例。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出 127 个 Var 声明。返回名→Var 的 dict,``main()`` 在解构后
|
||||
继续以原变量名使用(避免改动 134 处现有引用点)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]:
|
||||
"""从 cfg 构建所有 tk Var 实例,返回名→Var 字典。"""
|
||||
y_var = tk.IntVar(value=int(cfg.get("y_pianyi", 0) or 0))
|
||||
enable_back_on_misses_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("enable_back_on_misses", True))
|
||||
)
|
||||
swipe_down_back_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("swipe_down_back_enabled", False))
|
||||
)
|
||||
swipe_down_back_count_var = tk.IntVar(
|
||||
value=int(cfg.get("swipe_down_back_count", 3) or 3)
|
||||
)
|
||||
needswitch_var = tk.BooleanVar(value=bool(cfg.get("needswitch", True)))
|
||||
infinite_loop_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("infinite_loop_enabled", False))
|
||||
)
|
||||
wait_minutes_var = tk.IntVar(value=int(cfg.get("wait_minutes", 5) or 5))
|
||||
min_value_var = tk.DoubleVar(value=float(cfg.get("min_prize_value_yuan", 0) or 0))
|
||||
min_participants_var = tk.IntVar(value=int(cfg.get("min_participants", 0) or 0))
|
||||
max_participants_var = tk.IntVar(value=int(cfg.get("max_participants", 0) or 0))
|
||||
skip_gt_seconds_var = tk.IntVar(
|
||||
value=int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)
|
||||
)
|
||||
reset_after_swipes_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("reset_after_swipes_enabled", False))
|
||||
)
|
||||
reset_after_swipes_var = tk.IntVar(
|
||||
value=int(cfg.get("reset_after_swipes", 10) or 10)
|
||||
)
|
||||
reset_after_swipes_action_var = tk.StringVar(
|
||||
value=str(cfg.get("reset_after_swipes_action", "swipe") or "swipe")
|
||||
)
|
||||
enable_back_on_misses_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("enable_back_on_misses", True))
|
||||
)
|
||||
streaming_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("enable_streaming_screenshot", True))
|
||||
)
|
||||
auto_join_var = tk.BooleanVar(value=bool(cfg.get("auto_join_fansclub", False)))
|
||||
fansclub_action_var = tk.StringVar(
|
||||
value=str(cfg.get("fansclub_fail_action", "stay") or "stay").lower()
|
||||
)
|
||||
fansclub_click_delay_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fansclub_click_delay", 0.6) or 0.6)
|
||||
)
|
||||
fansclub_auto_wait_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
fansclub_manual_wait_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0)
|
||||
)
|
||||
high_value_fudai_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("high_value_fudai_enabled", False))
|
||||
)
|
||||
high_value_fudai_threshold_yuan_var = tk.DoubleVar(
|
||||
value=float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000)
|
||||
)
|
||||
high_value_fudai_join_ahead_seconds_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_fudai_join_ahead_seconds", 300) or 300)
|
||||
)
|
||||
high_value_fudai_max_swipe_back_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_fudai_max_swipe_back", 60) or 60)
|
||||
)
|
||||
high_value_fudai_max_reservations_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_fudai_max_reservations", 5) or 5)
|
||||
)
|
||||
high_value_fudai_after_action_var = tk.StringVar(
|
||||
value=str(cfg.get("high_value_fudai_after_action", "continue") or "continue")
|
||||
)
|
||||
high_value_fudai_poll_before_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("high_value_fudai_poll_before_seconds", 10.0) or 10.0)
|
||||
)
|
||||
high_value_room_revisit_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("high_value_room_revisit_enabled", True))
|
||||
)
|
||||
high_value_room_revisit_only_current_run_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("high_value_room_revisit_only_current_run", False))
|
||||
)
|
||||
high_value_room_revisit_min_interval_seconds_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_room_revisit_min_interval_seconds", 300))
|
||||
)
|
||||
high_value_room_revisit_max_per_run_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_room_revisit_max_per_run", 5))
|
||||
)
|
||||
high_value_room_revisit_min_prize_value_var = tk.DoubleVar(
|
||||
value=float(cfg.get("high_value_room_revisit_min_prize_value", 0.0))
|
||||
)
|
||||
high_value_room_revisit_max_age_days_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_room_revisit_max_age_days", 30))
|
||||
)
|
||||
reservation_back_verify_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("reservation_back_verify_enabled", True))
|
||||
)
|
||||
reservation_back_swipe_delay_var = tk.DoubleVar(
|
||||
value=float(cfg.get("reservation_back_swipe_delay", 0) or 0)
|
||||
)
|
||||
reservation_back_verify_wait_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("reservation_back_verify_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
fudai_find_max_attempts_var = tk.IntVar(
|
||||
value=int(cfg.get("fudai_find_max_attempts", 0) or 0)
|
||||
)
|
||||
fudai_icon_retry_delay_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
|
||||
)
|
||||
fudai_icon_max_wait_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
fudai_disable_content_recognition_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("fudai_disable_content_recognition", False))
|
||||
)
|
||||
fudai_disable_task_recognition_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("fudai_disable_task_recognition", False))
|
||||
)
|
||||
fudai_exit_after_misses_var = tk.IntVar(
|
||||
value=int(cfg.get("fudai_exit_after_misses", 30) or 30)
|
||||
)
|
||||
fudai_click_wait_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0)
|
||||
)
|
||||
switch_room_wait_after_stage_diag_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
|
||||
)
|
||||
live_room_match_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
|
||||
)
|
||||
swipe_duration_ms_var = tk.IntVar(
|
||||
value=int(cfg.get("swipe_duration_ms", 600) or 600)
|
||||
)
|
||||
swipe_up_start_y_var = tk.IntVar(
|
||||
value=int(cfg.get("swipe_up_start_y", 1200) or 1200)
|
||||
)
|
||||
swipe_up_end_y_var = tk.IntVar(value=int(cfg.get("swipe_up_end_y", 600) or 600))
|
||||
yg_enabled_var = tk.BooleanVar(value=bool(cfg.get("yanghao_enabled", True)))
|
||||
yg_actions_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("yanghao_enable_actions", True))
|
||||
)
|
||||
yg_only_var = tk.BooleanVar(value=bool(cfg.get("yanghao_only", False)))
|
||||
yg_recommend_duration_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60)
|
||||
)
|
||||
yg_recommend_interval_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_recommend_interval_seconds", 0) or 0)
|
||||
)
|
||||
yg_like_prob_var = tk.DoubleVar(
|
||||
value=float(cfg.get("yanghao_like_prob", 0.0) or 0.0)
|
||||
)
|
||||
yg_fav_prob_var = tk.DoubleVar(value=float(cfg.get("yanghao_fav_prob", 0.0) or 0.0))
|
||||
yg_comment_prob_var = tk.DoubleVar(
|
||||
value=float(cfg.get("yanghao_comment_prob", 0.0) or 0.0)
|
||||
)
|
||||
yg_dwell_on_action_min_var = tk.DoubleVar(
|
||||
value=float(cfg.get("yanghao_dwell_on_action_min_seconds", 5) or 5)
|
||||
)
|
||||
yg_dwell_on_action_max_var = tk.DoubleVar(
|
||||
value=float(cfg.get("yanghao_dwell_on_action_max_seconds", 30) or 30)
|
||||
)
|
||||
yg_icon_roi_size_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_icon_roi_size", 240) or 240)
|
||||
)
|
||||
yg_icon_match_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("yanghao_icon_match_threshold", 0.72) or 0.72)
|
||||
)
|
||||
yg_step_screenshot_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("yanghao_step_screenshot", False))
|
||||
)
|
||||
yg_like_roi_offset_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_like_roi_offset_x", 0) or 0)
|
||||
)
|
||||
yg_like_roi_offset_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_like_roi_offset_y", 0) or 0)
|
||||
)
|
||||
yg_fav_roi_offset_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_fav_roi_offset_x", 0) or 0)
|
||||
)
|
||||
yg_fav_roi_offset_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_fav_roi_offset_y", 0) or 0)
|
||||
)
|
||||
yg_like_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_x", 0) or 0))
|
||||
yg_like_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_y", 0) or 0))
|
||||
yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_x", 0) or 0))
|
||||
yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_y", 0) or 0))
|
||||
yg_like_template_path_var = tk.StringVar(
|
||||
value=str(
|
||||
cfg.get("yanghao_like_template_path", "assets/like.png")
|
||||
or "assets/like.png"
|
||||
)
|
||||
)
|
||||
yg_fav_template_path_var = tk.StringVar(
|
||||
value=str(
|
||||
cfg.get("yanghao_fav_template_path", "assets/fav.png") or "assets/fav.png"
|
||||
)
|
||||
)
|
||||
yg_like_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_x", 0) or 0))
|
||||
yg_like_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_y", 0) or 0))
|
||||
yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_x", 0) or 0))
|
||||
yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_y", 0) or 0))
|
||||
yg_after_dwell_direction_var = tk.StringVar(
|
||||
value=str(cfg.get("yanghao_after_dwell_swipe_direction", "up") or "up")
|
||||
)
|
||||
yg_after_dwell_distance_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_after_dwell_swipe_distance_px", 900) or 900)
|
||||
)
|
||||
yg_comment_btn_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_btn_x", 0) or 0)
|
||||
)
|
||||
yg_comment_btn_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_btn_y", 0) or 0)
|
||||
)
|
||||
yg_comment_input_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_input_x", 0) or 0)
|
||||
)
|
||||
yg_comment_input_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_input_y", 0) or 0)
|
||||
)
|
||||
yg_comment_send_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_send_x", 0) or 0)
|
||||
)
|
||||
yg_comment_send_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_send_y", 0) or 0)
|
||||
)
|
||||
yg_comment_close_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_close_x", 0) or 0)
|
||||
)
|
||||
yg_comment_close_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_close_y", 0) or 0)
|
||||
)
|
||||
fudai_quiet_hours_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("fudai_quiet_hours_enabled", True))
|
||||
)
|
||||
fudai_quiet_start_hour_var = tk.IntVar(
|
||||
value=int(cfg.get("fudai_quiet_start_hour", 2) or 2)
|
||||
)
|
||||
fudai_quiet_end_hour_var = tk.IntVar(
|
||||
value=int(cfg.get("fudai_quiet_end_hour", 7) or 7)
|
||||
)
|
||||
stage_diag_max_time_var = tk.DoubleVar(
|
||||
value=float(cfg.get("stage_diag_max_time", 10.0) or 10.0)
|
||||
)
|
||||
stage_diag_max_step_time_var = tk.DoubleVar(
|
||||
value=float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)
|
||||
)
|
||||
stage_diag_verbose_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("stage_diag_verbose", True))
|
||||
)
|
||||
enable_ocr_mode1_var = tk.BooleanVar(value=bool(cfg.get("enable_ocr_mode1", False)))
|
||||
fudai_template_match_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("fudai_template_match_enabled", False))
|
||||
)
|
||||
fudai_template_match_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)
|
||||
)
|
||||
fudai_detail_template_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fudai_detail_template_threshold", 0.7) or 0.7)
|
||||
)
|
||||
lucky_draw_red_ratio_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)
|
||||
)
|
||||
coupon_template_match_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("coupon_template_match_threshold", 0.75) or 0.75)
|
||||
)
|
||||
attend_button_red_ratio_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("attend_button_red_ratio_threshold", 0.25) or 0.25)
|
||||
)
|
||||
fansclub_join_red_ratio_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25)
|
||||
)
|
||||
shopping_redpacket_red_ratio_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("shopping_redpacket_red_ratio_threshold", 0.15) or 0.15)
|
||||
)
|
||||
debug_captures_enabled_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("debug_captures", {}).get("enabled", False)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else False
|
||||
)
|
||||
)
|
||||
debug_captures_auto_cleanup_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("debug_captures", {}).get("auto_cleanup", True)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else True
|
||||
)
|
||||
)
|
||||
debug_captures_keep_days_var = tk.IntVar(
|
||||
value=int(
|
||||
cfg.get("debug_captures", {}).get("keep_days", 7)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else 7
|
||||
)
|
||||
)
|
||||
debug_captures_max_files_var = tk.IntVar(
|
||||
value=int(
|
||||
cfg.get("debug_captures", {}).get("max_files", 2000)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else 2000
|
||||
)
|
||||
)
|
||||
debug_captures_async_save_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("debug_captures", {}).get("async_save", True)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else True
|
||||
)
|
||||
)
|
||||
debug_captures_log_on_complete_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("debug_captures", {}).get("log_on_complete", False)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else False
|
||||
)
|
||||
)
|
||||
debug_async_success_var = tk.IntVar(value=0)
|
||||
debug_async_failure_var = tk.IntVar(value=0)
|
||||
logging_beautify_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("beautify_output", True))
|
||||
)
|
||||
logging_color_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("color_output", True))
|
||||
)
|
||||
logging_show_timestamps_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("show_timestamps", True))
|
||||
)
|
||||
logging_use_dated_logs_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("use_dated_logs", True))
|
||||
)
|
||||
logging_enable_monitor_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("enable_monitor", True))
|
||||
)
|
||||
log_unified_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("log_unified_enabled", True))
|
||||
)
|
||||
log_unified_path_var = tk.StringVar(
|
||||
value=str(cfg.get("log_unified_path", "logs/unified.log") or "logs/unified.log")
|
||||
)
|
||||
logging_keep_days_var = tk.IntVar(
|
||||
value=int(cfg.get("logging", {}).get("keep_days", 30) or 30)
|
||||
)
|
||||
logging_compress_logs_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("compress_logs", True))
|
||||
)
|
||||
logging_max_total_size_gb_var = tk.DoubleVar(
|
||||
value=float(cfg.get("logging", {}).get("max_total_size_gb", 10.0) or 10.0)
|
||||
)
|
||||
logging_compress_after_days_var = tk.IntVar(
|
||||
value=int(cfg.get("logging", {}).get("compress_after_days", 7) or 7)
|
||||
)
|
||||
logging_performance_enabled_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("logging", {}).get("performance_tracking", {}).get("enabled", True)
|
||||
)
|
||||
)
|
||||
logging_track_functions_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("logging", {})
|
||||
.get("performance_tracking", {})
|
||||
.get("track_function_calls", True)
|
||||
)
|
||||
)
|
||||
logging_debug_level_var = tk.StringVar(
|
||||
value=str(cfg.get("logging", {}).get("debug_detail_level", "normal"))
|
||||
)
|
||||
logging_error_level_var = tk.StringVar(
|
||||
value=str(cfg.get("logging", {}).get("error_detail_level", "full"))
|
||||
)
|
||||
logging_action_format_var = tk.StringVar(
|
||||
value=str(cfg.get("logging", {}).get("action_log_format", "concise"))
|
||||
)
|
||||
logging_format_mode_var = tk.StringVar(
|
||||
value=str(cfg.get("logging", {}).get("log_format_mode", "simple"))
|
||||
)
|
||||
logging_monitor_warning_mb_var = tk.DoubleVar(
|
||||
value=float(cfg.get("logging", {}).get("monitor_warning_mb", 500.0) or 500.0)
|
||||
)
|
||||
logging_monitor_critical_mb_var = tk.DoubleVar(
|
||||
value=float(cfg.get("logging", {}).get("monitor_critical_mb", 2000.0) or 2000.0)
|
||||
)
|
||||
gui_theme_var = tk.StringVar(
|
||||
value=str(cfg.get("gui", {}).get("theme", "litera") or "litera")
|
||||
)
|
||||
gui_realtime_refresh_interval_ms_var = tk.IntVar(
|
||||
value=int(
|
||||
cfg.get("gui", {})
|
||||
.get("realtime_status", {})
|
||||
.get("refresh_interval_ms", 1000)
|
||||
or 1000
|
||||
)
|
||||
)
|
||||
gui_realtime_tail_items_var = tk.IntVar(
|
||||
value=int(
|
||||
cfg.get("gui", {}).get("realtime_status", {}).get("tail_items", 50) or 50
|
||||
)
|
||||
)
|
||||
skip_lt_seconds_var = tk.IntVar(
|
||||
value=int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10)
|
||||
)
|
||||
|
||||
return {
|
||||
"y_var": y_var,
|
||||
"enable_back_on_misses_var": enable_back_on_misses_var,
|
||||
"swipe_down_back_enabled_var": swipe_down_back_enabled_var,
|
||||
"swipe_down_back_count_var": swipe_down_back_count_var,
|
||||
"needswitch_var": needswitch_var,
|
||||
"infinite_loop_var": infinite_loop_var,
|
||||
"wait_minutes_var": wait_minutes_var,
|
||||
"min_value_var": min_value_var,
|
||||
"min_participants_var": min_participants_var,
|
||||
"max_participants_var": max_participants_var,
|
||||
"skip_gt_seconds_var": skip_gt_seconds_var,
|
||||
"reset_after_swipes_enabled_var": reset_after_swipes_enabled_var,
|
||||
"reset_after_swipes_var": reset_after_swipes_var,
|
||||
"reset_after_swipes_action_var": reset_after_swipes_action_var,
|
||||
"streaming_enabled_var": streaming_enabled_var,
|
||||
"auto_join_var": auto_join_var,
|
||||
"fansclub_action_var": fansclub_action_var,
|
||||
"fansclub_click_delay_var": fansclub_click_delay_var,
|
||||
"fansclub_auto_wait_var": fansclub_auto_wait_var,
|
||||
"fansclub_manual_wait_var": fansclub_manual_wait_var,
|
||||
"high_value_fudai_enabled_var": high_value_fudai_enabled_var,
|
||||
"high_value_fudai_threshold_yuan_var": high_value_fudai_threshold_yuan_var,
|
||||
"high_value_fudai_join_ahead_seconds_var": high_value_fudai_join_ahead_seconds_var,
|
||||
"high_value_fudai_max_swipe_back_var": high_value_fudai_max_swipe_back_var,
|
||||
"high_value_fudai_max_reservations_var": high_value_fudai_max_reservations_var,
|
||||
"high_value_fudai_after_action_var": high_value_fudai_after_action_var,
|
||||
"high_value_fudai_poll_before_seconds_var": high_value_fudai_poll_before_seconds_var,
|
||||
"high_value_room_revisit_enabled_var": high_value_room_revisit_enabled_var,
|
||||
"high_value_room_revisit_only_current_run_var": high_value_room_revisit_only_current_run_var,
|
||||
"high_value_room_revisit_min_interval_seconds_var": high_value_room_revisit_min_interval_seconds_var,
|
||||
"high_value_room_revisit_max_per_run_var": high_value_room_revisit_max_per_run_var,
|
||||
"high_value_room_revisit_min_prize_value_var": high_value_room_revisit_min_prize_value_var,
|
||||
"high_value_room_revisit_max_age_days_var": high_value_room_revisit_max_age_days_var,
|
||||
"reservation_back_verify_enabled_var": reservation_back_verify_enabled_var,
|
||||
"reservation_back_swipe_delay_var": reservation_back_swipe_delay_var,
|
||||
"reservation_back_verify_wait_seconds_var": reservation_back_verify_wait_seconds_var,
|
||||
"fudai_find_max_attempts_var": fudai_find_max_attempts_var,
|
||||
"fudai_icon_retry_delay_seconds_var": fudai_icon_retry_delay_seconds_var,
|
||||
"fudai_icon_max_wait_seconds_var": fudai_icon_max_wait_seconds_var,
|
||||
"fudai_disable_content_recognition_var": fudai_disable_content_recognition_var,
|
||||
"fudai_disable_task_recognition_var": fudai_disable_task_recognition_var,
|
||||
"fudai_exit_after_misses_var": fudai_exit_after_misses_var,
|
||||
"fudai_click_wait_seconds_var": fudai_click_wait_seconds_var,
|
||||
"switch_room_wait_after_stage_diag_seconds_var": switch_room_wait_after_stage_diag_seconds_var,
|
||||
"live_room_match_threshold_var": live_room_match_threshold_var,
|
||||
"swipe_duration_ms_var": swipe_duration_ms_var,
|
||||
"swipe_up_start_y_var": swipe_up_start_y_var,
|
||||
"swipe_up_end_y_var": swipe_up_end_y_var,
|
||||
"yg_enabled_var": yg_enabled_var,
|
||||
"yg_actions_enabled_var": yg_actions_enabled_var,
|
||||
"yg_only_var": yg_only_var,
|
||||
"yg_recommend_duration_var": yg_recommend_duration_var,
|
||||
"yg_recommend_interval_var": yg_recommend_interval_var,
|
||||
"yg_like_prob_var": yg_like_prob_var,
|
||||
"yg_fav_prob_var": yg_fav_prob_var,
|
||||
"yg_comment_prob_var": yg_comment_prob_var,
|
||||
"yg_dwell_on_action_min_var": yg_dwell_on_action_min_var,
|
||||
"yg_dwell_on_action_max_var": yg_dwell_on_action_max_var,
|
||||
"yg_icon_roi_size_var": yg_icon_roi_size_var,
|
||||
"yg_icon_match_threshold_var": yg_icon_match_threshold_var,
|
||||
"yg_step_screenshot_var": yg_step_screenshot_var,
|
||||
"yg_like_roi_offset_x_var": yg_like_roi_offset_x_var,
|
||||
"yg_like_roi_offset_y_var": yg_like_roi_offset_y_var,
|
||||
"yg_fav_roi_offset_x_var": yg_fav_roi_offset_x_var,
|
||||
"yg_fav_roi_offset_y_var": yg_fav_roi_offset_y_var,
|
||||
"yg_like_icon_x_var": yg_like_icon_x_var,
|
||||
"yg_like_icon_y_var": yg_like_icon_y_var,
|
||||
"yg_fav_icon_x_var": yg_fav_icon_x_var,
|
||||
"yg_fav_icon_y_var": yg_fav_icon_y_var,
|
||||
"yg_like_template_path_var": yg_like_template_path_var,
|
||||
"yg_fav_template_path_var": yg_fav_template_path_var,
|
||||
"yg_after_dwell_direction_var": yg_after_dwell_direction_var,
|
||||
"yg_after_dwell_distance_var": yg_after_dwell_distance_var,
|
||||
"yg_comment_btn_x_var": yg_comment_btn_x_var,
|
||||
"yg_comment_btn_y_var": yg_comment_btn_y_var,
|
||||
"yg_comment_input_x_var": yg_comment_input_x_var,
|
||||
"yg_comment_input_y_var": yg_comment_input_y_var,
|
||||
"yg_comment_send_x_var": yg_comment_send_x_var,
|
||||
"yg_comment_send_y_var": yg_comment_send_y_var,
|
||||
"yg_comment_close_x_var": yg_comment_close_x_var,
|
||||
"yg_comment_close_y_var": yg_comment_close_y_var,
|
||||
"fudai_quiet_hours_enabled_var": fudai_quiet_hours_enabled_var,
|
||||
"fudai_quiet_start_hour_var": fudai_quiet_start_hour_var,
|
||||
"fudai_quiet_end_hour_var": fudai_quiet_end_hour_var,
|
||||
"stage_diag_max_time_var": stage_diag_max_time_var,
|
||||
"stage_diag_max_step_time_var": stage_diag_max_step_time_var,
|
||||
"stage_diag_verbose_var": stage_diag_verbose_var,
|
||||
"enable_ocr_mode1_var": enable_ocr_mode1_var,
|
||||
"fudai_template_match_enabled_var": fudai_template_match_enabled_var,
|
||||
"fudai_template_match_threshold_var": fudai_template_match_threshold_var,
|
||||
"fudai_detail_template_threshold_var": fudai_detail_template_threshold_var,
|
||||
"lucky_draw_red_ratio_threshold_var": lucky_draw_red_ratio_threshold_var,
|
||||
"coupon_template_match_threshold_var": coupon_template_match_threshold_var,
|
||||
"attend_button_red_ratio_threshold_var": attend_button_red_ratio_threshold_var,
|
||||
"fansclub_join_red_ratio_threshold_var": fansclub_join_red_ratio_threshold_var,
|
||||
"shopping_redpacket_red_ratio_threshold_var": shopping_redpacket_red_ratio_threshold_var,
|
||||
"debug_captures_enabled_var": debug_captures_enabled_var,
|
||||
"debug_captures_auto_cleanup_var": debug_captures_auto_cleanup_var,
|
||||
"debug_captures_keep_days_var": debug_captures_keep_days_var,
|
||||
"debug_captures_max_files_var": debug_captures_max_files_var,
|
||||
"debug_captures_async_save_var": debug_captures_async_save_var,
|
||||
"debug_captures_log_on_complete_var": debug_captures_log_on_complete_var,
|
||||
"debug_async_success_var": debug_async_success_var,
|
||||
"debug_async_failure_var": debug_async_failure_var,
|
||||
"logging_beautify_var": logging_beautify_var,
|
||||
"logging_color_var": logging_color_var,
|
||||
"logging_show_timestamps_var": logging_show_timestamps_var,
|
||||
"logging_use_dated_logs_var": logging_use_dated_logs_var,
|
||||
"logging_enable_monitor_var": logging_enable_monitor_var,
|
||||
"log_unified_enabled_var": log_unified_enabled_var,
|
||||
"log_unified_path_var": log_unified_path_var,
|
||||
"logging_keep_days_var": logging_keep_days_var,
|
||||
"logging_compress_logs_var": logging_compress_logs_var,
|
||||
"logging_max_total_size_gb_var": logging_max_total_size_gb_var,
|
||||
"logging_compress_after_days_var": logging_compress_after_days_var,
|
||||
"logging_performance_enabled_var": logging_performance_enabled_var,
|
||||
"logging_track_functions_var": logging_track_functions_var,
|
||||
"logging_debug_level_var": logging_debug_level_var,
|
||||
"logging_error_level_var": logging_error_level_var,
|
||||
"logging_action_format_var": logging_action_format_var,
|
||||
"logging_format_mode_var": logging_format_mode_var,
|
||||
"logging_monitor_warning_mb_var": logging_monitor_warning_mb_var,
|
||||
"logging_monitor_critical_mb_var": logging_monitor_critical_mb_var,
|
||||
"gui_theme_var": gui_theme_var,
|
||||
"gui_realtime_refresh_interval_ms_var": gui_realtime_refresh_interval_ms_var,
|
||||
"gui_realtime_tail_items_var": gui_realtime_tail_items_var,
|
||||
"skip_lt_seconds_var": skip_lt_seconds_var,
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
"""调试参数 Tab UI 创建逻辑(含 30 个 var + 4 个内部闭包)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 430 行的 widget 创建段。
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - ``left_notebook`` (tab 父容器)
|
||||
- ``vars_`` - 名→Var 的 ``Dict[str, tk.Variable]``,键名同原 ``main()``
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, BOTH, X
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def setup_debug_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> ttk.Frame:
|
||||
debug_tab = ttk.Frame(parent)
|
||||
|
||||
# 为调试参数标签页添加滚动条
|
||||
debug_canvas = tk.Canvas(debug_tab, highlightthickness=0)
|
||||
debug_scrollbar = ttk.Scrollbar(
|
||||
debug_tab, orient="vertical", command=debug_canvas.yview
|
||||
)
|
||||
debug_scrollable_frame = ttk.Frame(debug_canvas)
|
||||
|
||||
debug_scrollable_frame.bind(
|
||||
"<Configure>",
|
||||
lambda e: debug_canvas.configure(scrollregion=debug_canvas.bbox("all")),
|
||||
)
|
||||
|
||||
debug_canvas.create_window((0, 0), window=debug_scrollable_frame, anchor="nw")
|
||||
debug_canvas.configure(yscrollcommand=debug_scrollbar.set)
|
||||
|
||||
# 鼠标滚轮支持
|
||||
def _on_mousewheel(event):
|
||||
debug_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
|
||||
|
||||
def _on_shift_mousewheel(event):
|
||||
debug_canvas.xview_scroll(int(-1 * (event.delta / 120)), "units")
|
||||
|
||||
debug_canvas.bind_all("<MouseWheel>", _on_mousewheel)
|
||||
debug_canvas.bind_all("<Shift-MouseWheel>", _on_shift_mousewheel)
|
||||
|
||||
debug_canvas.pack(side="left", fill="both", expand=True)
|
||||
debug_scrollbar.pack(side="right", fill="y")
|
||||
|
||||
parent.add(debug_tab, text="调试参数")
|
||||
|
||||
# 使用scrollable_frame作为容器
|
||||
debug_container = debug_scrollable_frame
|
||||
|
||||
# 调试图像
|
||||
debug_captures_box = ttk.LabelFrame(debug_container, text="调试图像")
|
||||
debug_captures_box.pack(fill=X, padx=10, pady=(10, 10))
|
||||
|
||||
debug_r0 = ttk.Frame(debug_captures_box)
|
||||
debug_r0.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Checkbutton(
|
||||
debug_r0,
|
||||
text="保存调试图像(OCR / 像素 / 模板等)",
|
||||
variable=vars_["debug_captures_enabled_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
debug_r0,
|
||||
text="异步保存调试图像(默认启用)",
|
||||
variable=vars_["debug_captures_async_save_var"],
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Checkbutton(
|
||||
debug_r0,
|
||||
text="保存完成后记录日志(显示路径)",
|
||||
variable=vars_["debug_captures_log_on_complete_var"],
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
# 异步保存计数显示与重置
|
||||
debug_counts_frame = ttk.Frame(debug_r0)
|
||||
debug_counts_frame.pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Label(debug_counts_frame, text="异步保存:").pack(side=LEFT)
|
||||
ttk.Label(
|
||||
debug_counts_frame, textvariable=vars_["debug_async_success_var"], foreground="green"
|
||||
).pack(side=LEFT, padx=(4, 8))
|
||||
ttk.Label(debug_counts_frame, text="/").pack(side=LEFT)
|
||||
ttk.Label(
|
||||
debug_counts_frame, textvariable=vars_["debug_async_failure_var"], foreground="red"
|
||||
).pack(side=LEFT, padx=(4, 8))
|
||||
|
||||
def on_reset_async_counters():
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
douyin_screenshot_manager.reset_async_save_counters()
|
||||
vars_["debug_async_success_var"].set(0)
|
||||
vars_["debug_async_failure_var"].set(0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ttk.Button(
|
||||
debug_counts_frame, text="重置", command=on_reset_async_counters, width=6
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 周期性更新计数器(2秒)
|
||||
def _update_async_counters():
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
s, f = douyin_screenshot_manager.get_async_save_counters()
|
||||
vars_["debug_async_success_var"].set(s)
|
||||
vars_["debug_async_failure_var"].set(f)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
debug_r0.after(2000, _update_async_counters)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 启动更新循环
|
||||
try:
|
||||
_update_async_counters()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
debug_cleanup_box = ttk.LabelFrame(debug_container, text="调试图像清理")
|
||||
debug_cleanup_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
debug_r1 = ttk.Frame(debug_cleanup_box)
|
||||
debug_r1.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Checkbutton(
|
||||
debug_r1, text="启用自动清理调试图像", variable=vars_["debug_captures_auto_cleanup_var"]
|
||||
).pack(side=LEFT)
|
||||
|
||||
debug_r2 = ttk.Frame(debug_cleanup_box)
|
||||
debug_r2.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(debug_r2, text="保留天数:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
debug_r2,
|
||||
from_=1,
|
||||
to=30,
|
||||
increment=1,
|
||||
textvariable=vars_["debug_captures_keep_days_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(debug_r2, text="最大文件数量:").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Spinbox(
|
||||
debug_r2,
|
||||
from_=100,
|
||||
to=10000,
|
||||
increment=100,
|
||||
textvariable=vars_["debug_captures_max_files_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(debug_r2, text="(超过此数量自动清理)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 找福袋参数
|
||||
fudai_find_box = ttk.LabelFrame(debug_container, text="找福袋参数")
|
||||
fudai_find_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
row4 = ttk.Frame(fudai_find_box)
|
||||
row4.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Label(row4, text="找福袋最大尝试次数:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4,
|
||||
from_=0,
|
||||
to=50,
|
||||
increment=1,
|
||||
textvariable=vars_["fudai_find_max_attempts_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4, text="(0=使用默认值)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
row4b = ttk.Frame(fudai_find_box)
|
||||
row4b.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row4b, text="找福袋重试间隔(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4b,
|
||||
from_=0.1,
|
||||
to=3.0,
|
||||
increment=0.1,
|
||||
textvariable=vars_["fudai_icon_retry_delay_seconds_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4b, text=" 最大等待时间(秒):").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
row4b,
|
||||
from_=0.0,
|
||||
to=30.0,
|
||||
increment=0.5,
|
||||
textvariable=vars_["fudai_icon_max_wait_seconds_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4b, text="(实际识别常见 4-6 秒)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
row4d = ttk.Frame(fudai_find_box)
|
||||
row4d.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row4d, text="点击福袋后等待时间(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4d,
|
||||
from_=0.5,
|
||||
to=10.0,
|
||||
increment=0.1,
|
||||
textvariable=vars_["fudai_click_wait_seconds_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4d, text="(等待福袋详情页加载,默认1.0秒)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
row4c = ttk.Frame(fudai_find_box)
|
||||
row4c.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Checkbutton(
|
||||
row4c,
|
||||
text="禁用福袋内容OCR识别",
|
||||
variable=vars_["fudai_disable_content_recognition_var"],
|
||||
onvalue=True,
|
||||
offvalue=False,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4c, text="(仅影响 content OCR,不改其它识别模块)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 任务列表 OCR 开关
|
||||
ttk.Checkbutton(
|
||||
row4c,
|
||||
text="禁用福袋任务列表OCR识别",
|
||||
variable=vars_["fudai_disable_task_recognition_var"],
|
||||
onvalue=True,
|
||||
offvalue=False,
|
||||
).pack(side=LEFT, padx=(12, 0))
|
||||
|
||||
row4e = ttk.Frame(fudai_find_box)
|
||||
row4e.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row4e, text="切换直播间后等待时间(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4e,
|
||||
from_=0.0,
|
||||
to=30.0,
|
||||
increment=0.5,
|
||||
textvariable=vars_["switch_room_wait_after_stage_diag_seconds_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4e, text="(阶段检测后等待福袋加载,默认7.0秒)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
row4c = ttk.Frame(fudai_find_box)
|
||||
row4c.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(row4c, text="直播间检测阈值(白色像素比例):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4c,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["live_room_match_threshold_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(
|
||||
row4c, text="(0.0~1.0,默认0.8,多边形区域白色像素比例>=此值判定为在直播间)"
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 鼠标配置
|
||||
mouse_config_box = ttk.LabelFrame(debug_container, text="鼠标配置")
|
||||
mouse_config_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
mouse_r1 = ttk.Frame(mouse_config_box)
|
||||
mouse_r1.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Label(mouse_r1, text="滑动速度(毫秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
mouse_r1,
|
||||
from_=100,
|
||||
to=2000,
|
||||
increment=50,
|
||||
textvariable=vars_["swipe_duration_ms_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(mouse_r1, text="(滑动持续时间,默认600ms,值越大滑动越慢)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
mouse_r2 = ttk.Frame(mouse_config_box)
|
||||
mouse_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(mouse_r2, text="上滑起始Y坐标:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
mouse_r2,
|
||||
from_=400,
|
||||
to=2000,
|
||||
increment=50,
|
||||
textvariable=vars_["swipe_up_start_y_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(mouse_r2, text="结束Y坐标:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
mouse_r2,
|
||||
from_=200,
|
||||
to=1800,
|
||||
increment=50,
|
||||
textvariable=vars_["swipe_up_end_y_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(mouse_r2, text="(基准1080x2400,默认1200→600,距离600px)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 阶段诊断时间参数(用于调试)
|
||||
diag_time_box = ttk.LabelFrame(debug_container, text="阶段诊断时间参数")
|
||||
diag_time_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
diag_time_r1 = ttk.Frame(diag_time_box)
|
||||
diag_time_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Label(diag_time_r1, text="最大诊断时间(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
diag_time_r1,
|
||||
from_=1.0,
|
||||
to=60.0,
|
||||
increment=1.0,
|
||||
textvariable=vars_["stage_diag_max_time_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(diag_time_r1, text="每步最大耗时(秒):").pack(side=LEFT, padx=(12, 0))
|
||||
ttk.Spinbox(
|
||||
diag_time_r1,
|
||||
from_=0.5,
|
||||
to=30.0,
|
||||
increment=0.5,
|
||||
textvariable=vars_["stage_diag_max_step_time_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(diag_time_r1, text="(用于调试,延长检测时间)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
diag_time_r2 = ttk.Frame(diag_time_box)
|
||||
diag_time_r2.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Checkbutton(
|
||||
diag_time_r2, text="详细阶段诊断日志", variable=vars_["stage_diag_verbose_var"]
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
diag_time_r2, text="启用OCR模式1(二值化)", variable=vars_["enable_ocr_mode1_var"]
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
diag_time_r2b = ttk.Frame(diag_time_box)
|
||||
diag_time_r2b.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Checkbutton(
|
||||
diag_time_r2b,
|
||||
text="启用福袋模板匹配",
|
||||
variable=vars_["fudai_template_match_enabled_var"],
|
||||
).pack(side=LEFT)
|
||||
diag_time_r3 = ttk.Frame(diag_time_box)
|
||||
diag_time_r3.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(diag_time_r3, text="福袋模板匹配阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
diag_time_r3,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["fudai_template_match_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(diag_time_r3, text="(0.0-1.0,彩色匹配)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
diag_time_r3b = ttk.Frame(diag_time_box)
|
||||
diag_time_r3b.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(diag_time_r3b, text="福袋详情页模板匹配阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
diag_time_r3b,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["fudai_detail_template_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(
|
||||
diag_time_r3b, text="(0.0-1.0,默认0.7,区域(398,894)-(658,1179))"
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
diag_time_r4 = ttk.Frame(diag_time_box)
|
||||
diag_time_r4.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(diag_time_r4, text="开奖页红色占比阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
diag_time_r4,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["lucky_draw_red_ratio_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(diag_time_r4, text="(默认0.90,≥此占比判定开奖页)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 更多模板匹配阈值
|
||||
diag_time_r5 = ttk.Frame(diag_time_box)
|
||||
diag_time_r5.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Label(diag_time_r5, text="优惠券模板匹配阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
diag_time_r5,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["coupon_template_match_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(diag_time_r5, text="(默认0.75,用于检测优惠券弹窗)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 像素检测阈值
|
||||
pixel_detect_box = ttk.LabelFrame(debug_container, text="像素检测阈值")
|
||||
pixel_detect_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
pixel_r1 = ttk.Frame(pixel_detect_box)
|
||||
pixel_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Label(pixel_r1, text="参与按钮红色占比阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
pixel_r1,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["attend_button_red_ratio_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(pixel_r1, text="(默认0.25,用于检测参与按钮)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
pixel_r2 = ttk.Frame(pixel_detect_box)
|
||||
pixel_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(pixel_r2, text="粉丝团加入红色占比阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
pixel_r2,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["fansclub_join_red_ratio_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(pixel_r2, text="(默认0.25,用于检测粉丝团加入按钮)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
pixel_r3 = ttk.Frame(pixel_detect_box)
|
||||
pixel_r3.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(pixel_r3, text="购物红包背景红色占比阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
pixel_r3,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["shopping_redpacket_red_ratio_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(pixel_r3, text="(默认0.15,用于检测购物红包弹窗背景)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
return debug_tab
|
||||
@@ -0,0 +1,115 @@
|
||||
"""筛选设置 Tab UI 创建逻辑(9 个 var)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 100 行的 widget 创建段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def setup_filter_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> ttk.Frame:
|
||||
filter_tab = ttk.Frame(parent)
|
||||
parent.add(filter_tab, text="筛选设置")
|
||||
|
||||
cfg_box = ttk.LabelFrame(filter_tab, text="福袋筛选条件")
|
||||
cfg_box.pack(fill=X, padx=10, pady=(10, 10))
|
||||
|
||||
row = ttk.Frame(cfg_box)
|
||||
row.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Label(row, text="最低价值(元):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row,
|
||||
from_=0,
|
||||
to=99999,
|
||||
increment=0.01,
|
||||
format="%.2f",
|
||||
textvariable=vars_["min_value_var"],
|
||||
width=10,
|
||||
).pack(side=LEFT)
|
||||
|
||||
rowp = ttk.Frame(cfg_box)
|
||||
rowp.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(rowp, text="参与人数范围:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
rowp,
|
||||
from_=0,
|
||||
to=99999999,
|
||||
increment=1,
|
||||
textvariable=vars_["min_participants_var"],
|
||||
width=10,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(rowp, text=" ~ ").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
rowp,
|
||||
from_=0,
|
||||
to=99999999,
|
||||
increment=1,
|
||||
textvariable=vars_["max_participants_var"],
|
||||
width=10,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(rowp, text="(填0表示不限制)").pack(side=LEFT)
|
||||
|
||||
row2 = ttk.Frame(cfg_box)
|
||||
row2.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row2, text="倒计时小于(秒)时不参与:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row2, from_=0, to=300, increment=1, textvariable=vars_["skip_lt_seconds_var"], width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row2, text="(剩余时间太短,不参与)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
row3 = ttk.Frame(cfg_box)
|
||||
row3.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Checkbutton(
|
||||
row3, text="自动加入粉丝团(谨慎:可能消耗钻石)", variable=vars_["auto_join_var"]
|
||||
).pack(side=LEFT)
|
||||
|
||||
row4 = ttk.Frame(cfg_box)
|
||||
row4.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(row4, text="粉丝团失败策略:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
row4,
|
||||
textvariable=vars_["fansclub_action_var"],
|
||||
values=["stay", "switch"],
|
||||
width=10,
|
||||
state="readonly",
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4, text="(stay=停留,switch=切换直播间)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
# 粉丝团等待/点击延迟设置
|
||||
row4b = ttk.Frame(cfg_box)
|
||||
row4b.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row4b, text="粉丝团点击延迟(s):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4b,
|
||||
from_=0.1,
|
||||
to=5.0,
|
||||
increment=0.1,
|
||||
textvariable=vars_["fansclub_click_delay_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 12))
|
||||
ttk.Label(row4b, text="自动加入等待(s):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4b,
|
||||
from_=0.5,
|
||||
to=10.0,
|
||||
increment=0.5,
|
||||
textvariable=vars_["fansclub_auto_wait_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 12))
|
||||
ttk.Label(row4b, text="手动加入等待(s):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4b,
|
||||
from_=0.5,
|
||||
to=10.0,
|
||||
increment=0.5,
|
||||
textvariable=vars_["fansclub_manual_wait_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 标签页3:高价值预约
|
||||
return filter_tab
|
||||
@@ -0,0 +1,39 @@
|
||||
"""高价值房间 Tab 视图刷新逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``refresh_high_value_rooms``,
|
||||
负责读 ``state/high_value_rooms.json`` 并以 JSON 格式渲染到 Tab。
|
||||
|
||||
依赖通过显式参数注入:``text_widget`` (展示用的 ScrolledText/Text widget)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tkinter as tk
|
||||
|
||||
|
||||
def refresh_high_value_rooms(text_widget: tk.Text) -> None:
|
||||
try:
|
||||
from douyin.core.path_config import get_high_value_rooms_path
|
||||
|
||||
path = get_high_value_rooms_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
from douyin.core import path_config
|
||||
|
||||
path = path_config.get_high_value_rooms_path()
|
||||
try:
|
||||
if os.path.exists(path):
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert(
|
||||
"1.0", json.dumps(data, ensure_ascii=False, indent=2)
|
||||
)
|
||||
else:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", "暂无高价值房间数据")
|
||||
except Exception as e:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", f"读取高价值房间失败:{e}")
|
||||
@@ -0,0 +1,41 @@
|
||||
"""关键词 Tab UI 创建逻辑(白名单 + 黑名单)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 18 行的 widget 创建段。
|
||||
|
||||
返回 ``(want_text, not_want_text)`` 两个 ScrolledText widget,供 main() 后续
|
||||
绑定到 ``_config_io_texts`` 字典用于 load/save 配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, X
|
||||
from typing import Any, Tuple
|
||||
|
||||
|
||||
def setup_keywords_tab(
|
||||
parent: ttk.Notebook,
|
||||
*,
|
||||
ScrolledText_cls: Any,
|
||||
) -> Tuple[tk.Text, tk.Text]:
|
||||
"""构建关键词 Tab,返回 ``(want_text, not_want_text)``。"""
|
||||
keywords_tab = ttk.Frame(parent)
|
||||
parent.add(keywords_tab, text="关键词")
|
||||
|
||||
kw_box = ttk.LabelFrame(keywords_tab, text="关键词(每行一个)")
|
||||
kw_box.pack(fill=BOTH, expand=True, padx=10, pady=(10, 10))
|
||||
|
||||
ttk.Label(kw_box, text="想要 contains_want(白名单,空=不限制)").pack(
|
||||
anchor="w", padx=10, pady=(10, 4)
|
||||
)
|
||||
want_text = ScrolledText_cls(kw_box, height=6)
|
||||
want_text.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
ttk.Label(kw_box, text="不想要 contains_not_want(黑名单)").pack(
|
||||
anchor="w", padx=10, pady=(0, 4)
|
||||
)
|
||||
not_want_text = ScrolledText_cls(kw_box, height=8)
|
||||
not_want_text.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
return want_text, not_want_text
|
||||
@@ -0,0 +1,127 @@
|
||||
"""左侧配置区:PanedWindow 布局 + 7 个配置 Tab + load/save_ui_to_config 闭包。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。包括:
|
||||
- ``ttk.PanedWindow`` (左/右分栏)
|
||||
- 左侧 ``ttk.Notebook`` 容器
|
||||
- 7 个配置 Tab(运行/筛选/高价值预约/养号/调试/日志/关键词)
|
||||
- ``load_config_to_ui`` / ``save_ui_to_config`` / ``save_logging_config`` 闭包
|
||||
- 启动时一次 ``load_config_to_ui()``
|
||||
|
||||
返回 ``LeftConfigArea`` 暴露给 ``main()`` 的引用:
|
||||
- ``right_frame``: 右侧分栏(传给后续 setup_main_notebook)
|
||||
- ``save_ui_to_config``: 保存配置回调
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
from gui.components.config_io import (
|
||||
load_config_to_ui as _load_config_to_ui_impl,
|
||||
save_ui_to_config as _save_ui_to_config_impl,
|
||||
)
|
||||
from gui.components.logging_config_io import save_logging_config as _save_logging_config_impl
|
||||
from gui.components.run_tab import setup_run_tab
|
||||
from gui.components.filter_tab import setup_filter_tab
|
||||
from gui.components.reservation_tab import setup_reservation_tab
|
||||
from gui.components.yanghao_tab import setup_yanghao_tab
|
||||
from gui.components.debug_tab import setup_debug_tab
|
||||
from gui.components.logging_tab import setup_logging_tab
|
||||
from gui.components.keywords_tab import setup_keywords_tab
|
||||
|
||||
|
||||
@dataclass
|
||||
class LeftConfigArea:
|
||||
"""``main()`` 后续仍要用的引用。"""
|
||||
|
||||
right_frame: ttk.Frame
|
||||
save_ui_to_config: Callable[[], None]
|
||||
|
||||
|
||||
def setup_left_config_area(
|
||||
root: tk.Misc,
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
cfg: dict,
|
||||
ScrolledText_cls: Any,
|
||||
read_config: Callable[[], dict],
|
||||
write_config: Callable[[dict], None],
|
||||
on_line: Callable[[str], None],
|
||||
) -> LeftConfigArea:
|
||||
"""构建左侧配置区(PanedWindow + 7 Tabs + load/save 闭包)。
|
||||
|
||||
``cfg`` 由调用方传入,``load_config_to_ui`` 内部把读到的新 cfg 重新赋回
|
||||
``cfg`` dict 的内容(不能 reassign 局部 var,所以用 ``dict.clear() + update``)。
|
||||
"""
|
||||
# 中部:左侧配置(使用 Notebook 标签页) + 右侧日志/预览(支持拖拽调整宽度)
|
||||
mid = ttk.PanedWindow(root, orient="horizontal")
|
||||
mid.pack(fill=BOTH, expand=True, padx=12, pady=(0, 12))
|
||||
|
||||
left_wrap = ttk.Frame(mid)
|
||||
right_frame = ttk.Frame(mid)
|
||||
mid.add(left_wrap, weight=0) # 左侧配置区域
|
||||
mid.add(right_frame, weight=1) # 右侧日志/预览区域
|
||||
|
||||
# 左侧使用 Notebook 标签页组织配置
|
||||
left_notebook = ttk.Notebook(left_wrap)
|
||||
left_notebook.pack(fill=BOTH, expand=True)
|
||||
|
||||
def save_logging_config() -> None:
|
||||
_save_logging_config_impl(
|
||||
vars_=vars_,
|
||||
read_config=read_config,
|
||||
write_config=write_config,
|
||||
on_line=on_line,
|
||||
)
|
||||
|
||||
# 创建左侧配置标签页
|
||||
setup_run_tab(left_notebook, vars_=vars_)
|
||||
setup_filter_tab(left_notebook, vars_=vars_)
|
||||
setup_reservation_tab(left_notebook, vars_=vars_)
|
||||
_, yg_comment_texts, yg_like_keywords_text, yg_fav_keywords_text = setup_yanghao_tab(
|
||||
left_notebook, vars_=vars_,
|
||||
)
|
||||
setup_debug_tab(left_notebook, vars_=vars_)
|
||||
setup_logging_tab(left_notebook, vars_=vars_, on_save_logging=save_logging_config)
|
||||
want_text, not_want_text = setup_keywords_tab(
|
||||
left_notebook, ScrolledText_cls=ScrolledText_cls,
|
||||
)
|
||||
|
||||
texts_ = {
|
||||
"not_want_text": not_want_text,
|
||||
"want_text": want_text,
|
||||
"yg_comment_texts": yg_comment_texts,
|
||||
"yg_fav_keywords_text": yg_fav_keywords_text,
|
||||
"yg_like_keywords_text": yg_like_keywords_text,
|
||||
}
|
||||
|
||||
def load_config_to_ui() -> None:
|
||||
# cfg 是 dict 的 alias,我们替换它的内容(不 reassign 否则丢失 main 的引用)
|
||||
new_cfg = _load_config_to_ui_impl(
|
||||
vars_=vars_,
|
||||
texts_=texts_,
|
||||
read_config=read_config,
|
||||
)
|
||||
cfg.clear()
|
||||
cfg.update(new_cfg)
|
||||
|
||||
def save_ui_to_config() -> None:
|
||||
_save_ui_to_config_impl(
|
||||
vars_=vars_,
|
||||
texts_=texts_,
|
||||
cfg=cfg,
|
||||
read_config=read_config,
|
||||
write_config=write_config,
|
||||
on_line=on_line,
|
||||
)
|
||||
|
||||
load_config_to_ui()
|
||||
|
||||
return LeftConfigArea(
|
||||
right_frame=right_frame,
|
||||
save_ui_to_config=save_ui_to_config,
|
||||
)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""GUI 日志管道工厂:queue + 线程安全文件写入 + Runner 集成。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出 on_line 闭包及其依赖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import queue
|
||||
from typing import Any, Callable, Tuple
|
||||
|
||||
from gui.gui_core import Runner
|
||||
from gui.components.log_writer import ThreadSafeLogWriter
|
||||
|
||||
_LOGGER = logging.getLogger("gui.gui_app")
|
||||
|
||||
|
||||
def _format_gui_log_line(line: str) -> str:
|
||||
"""将完整日志行转换为 GUI 显示用的精简版本。
|
||||
|
||||
实际实现位于 ``gui.components.log_viewer``,失败时回退到原始字符串。
|
||||
"""
|
||||
try:
|
||||
from gui.components.log_viewer import format_gui_log_line as _impl
|
||||
|
||||
return _impl(line)
|
||||
except Exception:
|
||||
return (line or "").rstrip("\n")
|
||||
|
||||
|
||||
def setup_log_pipeline() -> Tuple["queue.Queue[str]", Any, Callable[[str], None], Any]:
|
||||
"""构建 log queue + ThreadSafeLogWriter + on_line + Runner。
|
||||
|
||||
返回 ``(q, log_writer, on_line, runner)``,主程序后续把 ``runner`` 传入按钮回调,
|
||||
把 ``q`` 传入 ``pump_logs`` 用于 GUI 端消费。
|
||||
"""
|
||||
q: "queue.Queue[str]" = queue.Queue()
|
||||
log_writer = ThreadSafeLogWriter()
|
||||
|
||||
def on_line(line: str) -> None:
|
||||
"""处理日志行:GUI 显示用精简版本,文件写入用完整版本"""
|
||||
# GUI 显示:使用精简后的版本
|
||||
try:
|
||||
display_line = _format_gui_log_line(line)
|
||||
except Exception:
|
||||
display_line = line
|
||||
q.put(display_line)
|
||||
|
||||
# 文件:写入完整日志行(不做精简处理)
|
||||
try:
|
||||
log_writer.write(line)
|
||||
except Exception:
|
||||
pass # 文件写入失败不应影响GUI显示
|
||||
|
||||
runner = Runner(on_line=on_line)
|
||||
return q, log_writer, on_line, runner
|
||||
@@ -0,0 +1,143 @@
|
||||
"""GUI 日志泵: 把后台线程发来的日志行批量插入到日志 Text widget。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``pump_logs``,
|
||||
通过 ``root.after(100, pump_logs)`` 自递归调度。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``log_queue`` - 后台线程往里塞日志行的 ``queue.Queue``
|
||||
- ``text_widget`` - 展示用的 Text/ScrolledText
|
||||
- ``filter_getter`` - ``() -> str`` 返回筛选关键字(已 strip)
|
||||
- ``theme_getter`` - ``() -> str`` 返回当前主题名
|
||||
- ``root`` - 主窗口(用于自递归 ``after``)
|
||||
- ``is_running_getter`` - ``() -> bool`` 返回 runner 是否还在跑
|
||||
- ``status_getter`` - ``() -> str`` 读取状态文本
|
||||
- ``status_setter`` - ``(str) -> None`` 写入状态文本
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import queue
|
||||
import re
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
try:
|
||||
from gui.components.log_color_config import (
|
||||
apply_operation_color,
|
||||
get_operation_type,
|
||||
)
|
||||
except ImportError:
|
||||
def get_operation_type(line: str): # type: ignore[no-redef]
|
||||
return None
|
||||
|
||||
def apply_operation_color(*args, **kwargs): # type: ignore[no-redef]
|
||||
pass
|
||||
|
||||
_LOGGER = logging.getLogger("gui.gui_app")
|
||||
|
||||
|
||||
def pump_logs(
|
||||
log_queue: "queue.Queue[str]",
|
||||
*,
|
||||
text_widget: tk.Text,
|
||||
filter_getter: Callable[[], str],
|
||||
theme_getter: Callable[[], str],
|
||||
root: tk.Misc,
|
||||
is_running_getter: Callable[[], bool],
|
||||
status_getter: Callable[[], str],
|
||||
status_setter: Callable[[str], None],
|
||||
) -> None:
|
||||
changed = False
|
||||
try:
|
||||
# 获取当前主题(用于颜色配置)
|
||||
try:
|
||||
current_theme = theme_getter()
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
while True:
|
||||
line = log_queue.get_nowait()
|
||||
# 运行日志关键字筛选(与行为日志一致)
|
||||
try:
|
||||
kw = filter_getter()
|
||||
if kw and kw not in line:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
# 插入日志行并应用颜色标签
|
||||
start_pos = text_widget.index("end-1c")
|
||||
|
||||
# 插入文本
|
||||
text_widget.insert("end", line + "\n")
|
||||
end_pos = text_widget.index("end-1c")
|
||||
|
||||
# 优先级1: 先检查操作类型颜色(更具体)
|
||||
op_type_applied = False
|
||||
try:
|
||||
op_type = get_operation_type(line)
|
||||
if op_type:
|
||||
apply_operation_color(
|
||||
text_widget, start_pos, end_pos, line, current_theme
|
||||
)
|
||||
op_type_applied = True
|
||||
except Exception:
|
||||
pass # 忽略操作类型颜色应用失败
|
||||
|
||||
# 优先级2: 再检查日志级别标签(作为补充,如果操作类型未匹配)
|
||||
# 只有在没有操作类型颜色时才应用级别标签
|
||||
if not op_type_applied:
|
||||
try:
|
||||
tag = None
|
||||
if "[INFO]" in line:
|
||||
tag = "log_info"
|
||||
elif "[WARNING]" in line:
|
||||
tag = "log_warning"
|
||||
elif "[ERROR]" in line:
|
||||
tag = "log_error"
|
||||
elif "[CRITICAL]" in line:
|
||||
tag = "log_critical"
|
||||
elif "elapsed_seconds=" in line or "耗时" in line:
|
||||
tag = "log_performance"
|
||||
elif re.search(r"\[[\w\.]+\]", line):
|
||||
tag = "log_module"
|
||||
|
||||
if tag:
|
||||
text_widget.tag_add(tag, start_pos, end_pos)
|
||||
except Exception:
|
||||
pass # 忽略级别标签应用失败
|
||||
|
||||
# 不再自动滚动到底部,让用户自由控制滚动位置
|
||||
changed = True
|
||||
except Exception as e:
|
||||
# 如果插入日志失败,至少记录到 logger(调试用)
|
||||
_LOGGER.error("[GUI日志错误] 无法插入日志: %s", e)
|
||||
except queue.Empty:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 捕获其他异常,确保日志循环不会中断
|
||||
_LOGGER.error("[GUI日志错误] pump_logs异常: %s", e)
|
||||
|
||||
try:
|
||||
if changed and not is_running_getter() and status_getter() == "运行中":
|
||||
status_setter("已结束")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 确保递归调用始终执行,即使前面出现异常
|
||||
try:
|
||||
root.after(100, lambda: pump_logs(
|
||||
log_queue,
|
||||
text_widget=text_widget,
|
||||
filter_getter=filter_getter,
|
||||
theme_getter=theme_getter,
|
||||
root=root,
|
||||
is_running_getter=is_running_getter,
|
||||
status_getter=status_getter,
|
||||
status_setter=status_setter,
|
||||
)) # type: ignore[arg-type]
|
||||
except Exception as e:
|
||||
# 如果 root 已被销毁,停止日志循环
|
||||
_LOGGER.warning("[GUI日志错误] 无法调度下次日志更新: %s", e)
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""运行日志 Tab 的搜索工具栏(关键字筛选 + 文本搜索)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的搜索栏 widget 创建段 +
|
||||
5 个共享 ``nonlocal`` matches state 的搜索闭包。
|
||||
|
||||
抽出后用一个 ``LogSearchToolbarHandles`` namedtuple 暴露 main 仍要用的引用:
|
||||
- ``log_filter_var`` - 关键字筛选 StringVar(被 refresh_run_log/auto_refresh 用)
|
||||
- ``refresh_run_log`` - 刷新回调(被 root.after 调度用)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X, Y
|
||||
from typing import Any, Callable
|
||||
|
||||
from gui.components.run_log_view import refresh_run_log as _refresh_run_log_impl
|
||||
from gui.components.text_search import generic_search_widget
|
||||
|
||||
|
||||
@dataclass
|
||||
class LogSearchToolbarHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
log_filter_var: tk.StringVar
|
||||
refresh_run_log: Callable[[], None]
|
||||
|
||||
|
||||
def setup_log_search_toolbar(
|
||||
parent: tk.Misc,
|
||||
*,
|
||||
log_text: tk.Text,
|
||||
runner: Any,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> LogSearchToolbarHandles:
|
||||
"""构建运行日志 Tab 顶部的搜索工具栏。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - 工具栏父容器(``log_box``)
|
||||
- ``log_text`` - 日志文本 widget(搜索高亮 + 内容刷新的目标)
|
||||
- ``runner`` - 运行控制器(暴露 ``_lock`` / ``_log`` 给刷新回调)
|
||||
- ``theme_getter`` - ``() -> str`` 返回当前 GUI 主题名
|
||||
"""
|
||||
log_search_frame = ttk.Frame(parent)
|
||||
log_search_frame.pack(fill=X, padx=10, pady=(10, 5))
|
||||
|
||||
# 关键字筛选(与行为日志一致)
|
||||
log_filter_var = tk.StringVar(value="")
|
||||
ttk.Label(log_search_frame, text="筛选:").pack(side=LEFT)
|
||||
ttk.Entry(log_search_frame, textvariable=log_filter_var, width=16).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
log_search_var = tk.StringVar(value="")
|
||||
log_search_entry = ttk.Entry(
|
||||
log_search_frame, textvariable=log_search_var, width=20
|
||||
)
|
||||
|
||||
def refresh_run_log() -> None:
|
||||
_refresh_run_log_impl(
|
||||
runner,
|
||||
text_widget=log_text,
|
||||
filter_getter=lambda: log_filter_var.get().strip(),
|
||||
theme_getter=theme_getter,
|
||||
)
|
||||
|
||||
# 搜索状态用可变容器持有,5 个内层闭包共享。
|
||||
state = {
|
||||
"matches": [],
|
||||
"current_index": -1,
|
||||
}
|
||||
|
||||
def search_in_log_text(direction: int = 1) -> None:
|
||||
"""在运行日志中搜索文本(调用通用搜索实现)"""
|
||||
state["current_index"] = generic_search_widget(
|
||||
log_text,
|
||||
log_search_var,
|
||||
state["matches"],
|
||||
state["current_index"],
|
||||
direction,
|
||||
)
|
||||
|
||||
def search_next_in_log() -> None:
|
||||
"""搜索下一个"""
|
||||
search_in_log_text(1)
|
||||
|
||||
def search_prev_in_log() -> None:
|
||||
"""搜索上一个"""
|
||||
search_in_log_text(-1)
|
||||
|
||||
def clear_search_in_log() -> None:
|
||||
"""清除搜索高亮"""
|
||||
log_search_var.set("")
|
||||
log_text.tag_remove("search_highlight", "1.0", "end")
|
||||
log_text.tag_remove("search_current", "1.0", "end")
|
||||
state["matches"] = []
|
||||
state["current_index"] = -1
|
||||
|
||||
# 绑定回车键搜索
|
||||
def on_log_search_entry_key(event):
|
||||
if event.keysym == "Return":
|
||||
search_next_in_log()
|
||||
|
||||
log_search_entry.bind("<KeyPress>", on_log_search_entry_key)
|
||||
|
||||
# 将 刷新 放在筛选后面,搜索区域与行为日志一致(带分隔条)
|
||||
ttk.Button(log_search_frame, text="刷新", command=refresh_run_log).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
ttk.Separator(log_search_frame, orient="vertical").pack(
|
||||
side=LEFT, fill=Y, padx=5, pady=3
|
||||
)
|
||||
ttk.Label(log_search_frame, text="搜索:").pack(side=LEFT)
|
||||
# 把搜索输入框放在分隔符后
|
||||
log_search_entry.pack(side=LEFT, padx=(0, 5))
|
||||
ttk.Button(log_search_frame, text="搜索", command=search_next_in_log).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(log_search_frame, text="上一个", command=search_prev_in_log).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(log_search_frame, text="下一个", command=search_next_in_log).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(log_search_frame, text="清除", command=clear_search_in_log).pack(
|
||||
side=LEFT, padx=(0, 5)
|
||||
)
|
||||
|
||||
return LogSearchToolbarHandles(
|
||||
log_filter_var=log_filter_var,
|
||||
refresh_run_log=refresh_run_log,
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""运行日志 Tab 的 widget 创建段(log_box + log_text + 搜索工具栏 + 配色)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。返回 ``LogTabHandles`` 暴露给 ``main()`` 后续 pump_logs。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH
|
||||
from typing import Any, Callable
|
||||
|
||||
from gui.components.log_search_toolbar import (
|
||||
setup_log_search_toolbar,
|
||||
LogSearchToolbarHandles,
|
||||
)
|
||||
from gui.components.log_text_colors import configure_log_text_colors
|
||||
|
||||
|
||||
@dataclass
|
||||
class LogTabHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
log_text: tk.Text
|
||||
log_filter_var: tk.StringVar
|
||||
refresh_run_log: Callable[[], None]
|
||||
|
||||
|
||||
def setup_log_tab(
|
||||
log_tab: tk.Misc,
|
||||
*,
|
||||
runner: Any,
|
||||
ScrolledText_cls: Any,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> LogTabHandles:
|
||||
"""构建运行日志 Tab(log_box + log_text + 搜索工具栏 + 配色)。"""
|
||||
log_box = ttk.Frame(log_tab)
|
||||
log_box.pack(fill=BOTH, expand=True)
|
||||
|
||||
log_text = ScrolledText_cls(log_box)
|
||||
try:
|
||||
log_text.configure(font=("Consolas", 10))
|
||||
except Exception:
|
||||
pass
|
||||
log_text.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
|
||||
|
||||
handles: LogSearchToolbarHandles = setup_log_search_toolbar(
|
||||
log_box,
|
||||
log_text=log_text,
|
||||
runner=runner,
|
||||
theme_getter=theme_getter,
|
||||
)
|
||||
|
||||
configure_log_text_colors(log_text, theme_getter=theme_getter)
|
||||
|
||||
return LogTabHandles(
|
||||
log_text=log_text,
|
||||
log_filter_var=handles.log_filter_var,
|
||||
refresh_run_log=handles.refresh_run_log,
|
||||
)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""运行日志 widget 的主题颜色配置。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的内联段,根据当前 GUI 主题
|
||||
为 log_text 配置背景/前景色 + 多种 log_xxx 标签 + 操作类型颜色标签。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``text_widget`` - 待配置的 Text/ScrolledText
|
||||
- ``theme_getter`` - ``() -> str`` 返回当前主题名
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
try:
|
||||
from gui.components.log_color_config import get_color_config
|
||||
except ImportError:
|
||||
def get_color_config(theme: str = "litera"): # type: ignore[no-redef]
|
||||
return {}
|
||||
|
||||
|
||||
def configure_log_text_colors(
|
||||
text_widget: tk.Text,
|
||||
*,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> None:
|
||||
# 配置日志颜色标签(如果支持颜色)
|
||||
try:
|
||||
# 根据主题调整日志颜色(明亮主题使用深色文字/蓝色系)
|
||||
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
|
||||
try:
|
||||
current_theme = theme_getter()
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
if current_theme in light_themes:
|
||||
# 明亮主题 - 使用更适合人眼观看的颜色组合
|
||||
text_widget.configure(
|
||||
background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C"
|
||||
)
|
||||
text_widget.tag_configure("log_timestamp", foreground="#8B8B8B") # 柔和的灰色
|
||||
text_widget.tag_configure(
|
||||
"log_info", foreground="#1E88E5"
|
||||
) # 明亮的蓝色,易于阅读
|
||||
text_widget.tag_configure(
|
||||
"log_warning", foreground="#F57C00"
|
||||
) # 橙色,警告色但不过于刺眼
|
||||
text_widget.tag_configure(
|
||||
"log_error", foreground="#D32F2F"
|
||||
) # 深红色,醒目但不刺眼
|
||||
text_widget.tag_configure(
|
||||
"log_critical", foreground="#B71C1C", font=("Consolas", 10, "bold")
|
||||
) # 加粗深红色
|
||||
text_widget.tag_configure(
|
||||
"log_performance", foreground="#388E3C"
|
||||
) # 深绿色,性能指标
|
||||
text_widget.tag_configure("log_module", foreground="#7B1FA2") # 紫色,模块标识
|
||||
else:
|
||||
# 暗色主题 - 优化对比度和可读性
|
||||
text_widget.configure(
|
||||
background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF"
|
||||
)
|
||||
text_widget.tag_configure(
|
||||
"log_timestamp", foreground="#A0A0A0"
|
||||
) # 浅灰色时间戳
|
||||
text_widget.tag_configure("log_info", foreground="#64B5F6") # 亮蓝色,信息级
|
||||
text_widget.tag_configure(
|
||||
"log_warning", foreground="#FFB74D"
|
||||
) # 金色警告,暗色背景下醒目
|
||||
text_widget.tag_configure(
|
||||
"log_error", foreground="#EF5350"
|
||||
) # 亮红色,错误突出
|
||||
text_widget.tag_configure(
|
||||
"log_critical", foreground="#F44336", font=("Consolas", 10, "bold")
|
||||
) # 加粗亮红色
|
||||
text_widget.tag_configure(
|
||||
"log_performance", foreground="#81C784"
|
||||
) # 亮绿色,性能数据
|
||||
text_widget.tag_configure(
|
||||
"log_module", foreground="#BA68C8"
|
||||
) # 亮紫色,模块标识
|
||||
|
||||
# 配置操作类型颜色标签(使用模块化配置)
|
||||
try:
|
||||
color_config = get_color_config(current_theme)
|
||||
for op_type, colors in color_config.items():
|
||||
tag_name = f"op_{op_type}"
|
||||
text_widget.tag_configure(
|
||||
tag_name,
|
||||
foreground=colors["foreground"],
|
||||
background=colors["background"],
|
||||
)
|
||||
except Exception:
|
||||
pass # 忽略操作类型颜色配置失败
|
||||
except Exception:
|
||||
pass # 忽略标签配置失败
|
||||
@@ -0,0 +1,134 @@
|
||||
"""gui/components/log_writer - 线程安全的日志文件写入器
|
||||
|
||||
从 gui_app.py 抽出的 ThreadSafeLogWriter 类(109 行)。把 GUI 接收到的日志
|
||||
行写到磁盘文件(按日期分割),用 threading.Lock 保护,配置走
|
||||
read_config() / path_config / get_logs_dir。
|
||||
|
||||
入口:ThreadSafeLogWriter(log_dir=None),调用 .write(line) 即可。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from douyin.core.path_config import get_logs_dir
|
||||
|
||||
_LOGGER = logging.getLogger("gui.components.log_writer")
|
||||
|
||||
|
||||
class ThreadSafeLogWriter:
|
||||
"""线程安全的日志文件写入器,确保日志能稳定写入文件。
|
||||
|
||||
写入策略:
|
||||
- 配置读取走 gui.gui_core_pkg.config.read_config(避免循环依赖时延迟导入)
|
||||
- 日志路径默认 logs/unified.log,可配置 log_unified_path
|
||||
- 启用 use_dated_logs 时按 YYYY-MM-DD 后缀分割
|
||||
- 每次 write() 时检查日期是否变化,自动滚动到新文件
|
||||
- 行已含时间戳前缀(数字开头 + " - [" 模式)就原样写,否则补 [GUI] 前缀
|
||||
"""
|
||||
|
||||
def __init__(self, log_dir: Optional[str] = None):
|
||||
self._lock = threading.Lock()
|
||||
self._log_dir = log_dir or get_logs_dir()
|
||||
self._log_file_path: str = ""
|
||||
self._log_file_enabled: bool = True
|
||||
self._init_log_file()
|
||||
self._write_error_warned = False
|
||||
|
||||
@staticmethod
|
||||
def _read_config() -> dict:
|
||||
"""延迟导入 read_config 避免在 gui_app 启动时形成循环依赖。"""
|
||||
try:
|
||||
from gui.gui_core_pkg.config import read_config
|
||||
cfg = read_config() or {}
|
||||
return cfg if isinstance(cfg, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def _init_log_file(self) -> None:
|
||||
"""初始化日志文件路径(按日期)。"""
|
||||
try:
|
||||
os.makedirs(self._log_dir, exist_ok=True)
|
||||
|
||||
cfg = self._read_config()
|
||||
self._log_file_enabled = bool(cfg.get("log_unified_enabled", True))
|
||||
|
||||
log_path = cfg.get("log_unified_path") or "logs/unified.log"
|
||||
if not os.path.isabs(log_path):
|
||||
from douyin.core.path_config import PROJECT_ROOT
|
||||
|
||||
log_path = os.path.join(PROJECT_ROOT, log_path)
|
||||
|
||||
use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True)
|
||||
if use_dated_logs:
|
||||
base_name = os.path.splitext(log_path)[0]
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
self._log_file_path = f"{base_name}_{today}.log"
|
||||
else:
|
||||
self._log_file_path = log_path
|
||||
except Exception as e:
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
self._log_file_path = os.path.join(
|
||||
self._log_dir, f"unified_{today}.log"
|
||||
)
|
||||
_LOGGER.warning("[GUI日志] 配置读取失败,使用默认路径: %s", e)
|
||||
|
||||
def write(self, line: str) -> None:
|
||||
"""线程安全地写入日志行到文件。"""
|
||||
if not self._log_file_enabled:
|
||||
return
|
||||
if not line or not line.strip():
|
||||
return
|
||||
|
||||
with self._lock:
|
||||
try:
|
||||
# 检查日期是否变化(按日期分割时)
|
||||
cfg = self._read_config()
|
||||
use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True)
|
||||
if use_dated_logs:
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
current_base = os.path.splitext(self._log_file_path)[0]
|
||||
if not current_base.endswith(today):
|
||||
# 日期变化,更新文件路径
|
||||
base_name = (
|
||||
current_base.rsplit("_", 1)[0]
|
||||
if "_" in os.path.basename(current_base)
|
||||
else current_base
|
||||
)
|
||||
self._log_file_path = f"{base_name}_{today}.log"
|
||||
|
||||
log_dir = os.path.dirname(self._log_file_path)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
with open(
|
||||
self._log_file_path, "a", encoding="utf-8-sig", errors="replace"
|
||||
) as f:
|
||||
# 行已包含时间戳前缀就原样写
|
||||
if line.strip() and not (line[0].isdigit() and " - [" in line):
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
formatted_line = f"{timestamp} - [GUI] - {line}\n"
|
||||
else:
|
||||
formatted_line = f"{line}\n"
|
||||
|
||||
f.write(formatted_line)
|
||||
f.flush()
|
||||
except PermissionError as e:
|
||||
if not self._write_error_warned:
|
||||
_LOGGER.error(
|
||||
"[GUI日志] 权限错误,无法写入日志文件: %s | %s",
|
||||
self._log_file_path,
|
||||
e,
|
||||
)
|
||||
self._write_error_warned = True
|
||||
except Exception as e:
|
||||
if not self._write_error_warned:
|
||||
_LOGGER.error(
|
||||
"[GUI日志] 写入日志文件失败: %s | %s",
|
||||
self._log_file_path,
|
||||
e,
|
||||
)
|
||||
self._write_error_warned = True
|
||||
@@ -0,0 +1,82 @@
|
||||
"""日志配置 + GUI 主题保存逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``save_logging_config``,
|
||||
读取 18 个 tkinter Var 写入 config.json。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``vars_`` - 一个名→Var 的 ``Dict[str, tk.Variable]``,键名与原 main() 中的变量名一致
|
||||
- ``read_config`` - 读配置回调
|
||||
- ``write_config`` - 写配置回调
|
||||
- ``on_line`` - 日志回调
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Callable, Dict
|
||||
|
||||
|
||||
def save_logging_config(
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
read_config: Callable[[], dict],
|
||||
write_config: Callable[[dict], None],
|
||||
on_line: Callable[[str], None],
|
||||
) -> None:
|
||||
"""保存日志配置到配置文件"""
|
||||
try:
|
||||
# 读取当前配置
|
||||
cfg = read_config()
|
||||
|
||||
# 更新日志相关配置
|
||||
if "logging" not in cfg:
|
||||
cfg["logging"] = {}
|
||||
|
||||
cfg["logging"]["log_format_mode"] = vars_["logging_format_mode_var"].get()
|
||||
cfg["logging"]["beautify_output"] = bool(vars_["logging_beautify_var"].get())
|
||||
cfg["logging"]["color_output"] = bool(vars_["logging_color_var"].get())
|
||||
cfg["logging"]["show_timestamps"] = bool(vars_["logging_show_timestamps_var"].get())
|
||||
cfg["logging"]["use_dated_logs"] = bool(vars_["logging_use_dated_logs_var"].get())
|
||||
cfg["logging"]["debug_detail_level"] = vars_["logging_debug_level_var"].get()
|
||||
cfg["logging"]["error_detail_level"] = vars_["logging_error_level_var"].get()
|
||||
cfg["logging"]["action_log_format"] = vars_["logging_action_format_var"].get()
|
||||
cfg["logging"]["enable_monitor"] = bool(vars_["logging_enable_monitor_var"].get())
|
||||
cfg["logging"]["keep_days"] = int(vars_["logging_keep_days_var"].get())
|
||||
cfg["logging"]["compress_logs"] = bool(vars_["logging_compress_logs_var"].get())
|
||||
cfg["logging"]["max_total_size_gb"] = float(
|
||||
vars_["logging_max_total_size_gb_var"].get()
|
||||
)
|
||||
cfg["logging"]["compress_after_days"] = int(
|
||||
vars_["logging_compress_after_days_var"].get()
|
||||
)
|
||||
cfg["logging"]["monitor_warning_mb"] = float(
|
||||
vars_["logging_monitor_warning_mb_var"].get()
|
||||
)
|
||||
cfg["logging"]["monitor_critical_mb"] = float(
|
||||
vars_["logging_monitor_critical_mb_var"].get()
|
||||
)
|
||||
cfg["logging"]["performance_tracking"] = {
|
||||
"enabled": bool(vars_["logging_performance_enabled_var"].get()),
|
||||
"track_function_calls": bool(vars_["logging_track_functions_var"].get()),
|
||||
}
|
||||
cfg["log_unified_enabled"] = bool(vars_["log_unified_enabled_var"].get())
|
||||
cfg["log_unified_path"] = str(vars_["log_unified_path_var"].get() or "logs/unified.log")
|
||||
|
||||
# 更新GUI主题
|
||||
if "gui" not in cfg:
|
||||
cfg["gui"] = {}
|
||||
cfg["gui"]["theme"] = vars_["gui_theme_var"].get()
|
||||
cfg["gui"]["realtime_status"] = {
|
||||
"refresh_interval_ms": int(
|
||||
vars_["gui_realtime_refresh_interval_ms_var"].get() or 1000
|
||||
),
|
||||
"tail_items": int(vars_["gui_realtime_tail_items_var"].get() or 50),
|
||||
}
|
||||
|
||||
# 保存配置
|
||||
write_config(cfg)
|
||||
|
||||
on_line("[配置] 日志配置已保存")
|
||||
except Exception as e:
|
||||
on_line(f"[配置] 保存日志配置失败:{e}")
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
"""日志配置 Tab UI 创建逻辑(23 个 var)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 230 行的 widget 创建段。
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - ``left_notebook`` (tab 父容器)
|
||||
- ``vars_`` - 名→Var 的 ``Dict[str, tk.Variable]``,键名同原 ``main()``
|
||||
- ``on_save_logging`` - "保存日志配置"按钮的回调
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, BOTH, X
|
||||
from typing import Callable, Dict
|
||||
|
||||
|
||||
def setup_logging_tab(
|
||||
parent: ttk.Notebook,
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
on_save_logging: Callable[[], None],
|
||||
) -> ttk.Frame:
|
||||
logging_tab = ttk.Frame(parent)
|
||||
parent.add(logging_tab, text="日志配置")
|
||||
|
||||
# 日志配置容器
|
||||
logging_container = ttk.Frame(logging_tab)
|
||||
logging_container.pack(fill=BOTH, expand=True, padx=10, pady=10)
|
||||
|
||||
# 日志格式设置
|
||||
log_format_box = ttk.LabelFrame(logging_container, text="日志格式")
|
||||
log_format_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
# 日志格式模式
|
||||
log_format_r1 = ttk.Frame(log_format_box)
|
||||
log_format_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Label(log_format_r1, text="日志格式模式:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_format_r1,
|
||||
values=["simple", "detailed"],
|
||||
textvariable=vars_["logging_format_mode_var"],
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Label(log_format_r1, text="(simple=简洁模式,detailed=详细模式用于debug)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 日志美化选项
|
||||
log_format_r2 = ttk.Frame(log_format_box)
|
||||
log_format_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Checkbutton(
|
||||
log_format_r2,
|
||||
text="启用日志美化",
|
||||
variable=vars_["logging_beautify_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
log_format_r2,
|
||||
text="启用颜色显示",
|
||||
variable=vars_["logging_color_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Checkbutton(
|
||||
log_format_r2,
|
||||
text="显示时间戳",
|
||||
variable=vars_["logging_show_timestamps_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
# 日志详细程度设置
|
||||
log_detail_box = ttk.LabelFrame(logging_container, text="日志详细程度")
|
||||
log_detail_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
log_detail_r1 = ttk.Frame(log_detail_box)
|
||||
log_detail_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Label(log_detail_r1, text="调试日志详细程度:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_detail_r1,
|
||||
values=["normal", "detailed", "minimal"],
|
||||
textvariable=vars_["logging_debug_level_var"],
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Label(log_detail_r1, text="错误日志详细程度:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_detail_r1,
|
||||
values=["full", "basic", "minimal"],
|
||||
textvariable=vars_["logging_error_level_var"],
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT)
|
||||
|
||||
log_detail_r2 = ttk.Frame(log_detail_box)
|
||||
log_detail_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(log_detail_r2, text="行为日志格式:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_detail_r2,
|
||||
values=["concise", "detailed", "minimal"],
|
||||
textvariable=vars_["logging_action_format_var"],
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Checkbutton(
|
||||
log_detail_r2,
|
||||
text="启用日志监控(超限告警/触发清理)",
|
||||
variable=vars_["logging_enable_monitor_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
log_detail_r3 = ttk.Frame(log_detail_box)
|
||||
log_detail_r3.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Checkbutton(
|
||||
log_detail_r3,
|
||||
text="按日期拆分日志",
|
||||
variable=vars_["logging_use_dated_logs_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
log_detail_r3,
|
||||
text="写入统一日志",
|
||||
variable=vars_["log_unified_enabled_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Label(log_detail_r3, text="统一日志路径:").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Entry(log_detail_r3, textvariable=vars_["log_unified_path_var"], width=28).pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 日志管理设置
|
||||
log_manage_box = ttk.LabelFrame(logging_container, text="日志管理")
|
||||
log_manage_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
log_manage_r1 = ttk.Frame(log_manage_box)
|
||||
log_manage_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Checkbutton(
|
||||
log_manage_r1,
|
||||
text="压缩旧日志",
|
||||
variable=vars_["logging_compress_logs_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(log_manage_r1, text="保留天数:").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Spinbox(
|
||||
log_manage_r1,
|
||||
from_=1,
|
||||
to=365,
|
||||
increment=1,
|
||||
textvariable=vars_["logging_keep_days_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 16))
|
||||
ttk.Label(log_manage_r1, text="总量上限(GB):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_manage_r1,
|
||||
from_=0.1,
|
||||
to=100.0,
|
||||
increment=0.1,
|
||||
textvariable=vars_["logging_max_total_size_gb_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 16))
|
||||
ttk.Label(log_manage_r1, text="压缩阈值(天):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_manage_r1,
|
||||
from_=0,
|
||||
to=365,
|
||||
increment=1,
|
||||
textvariable=vars_["logging_compress_after_days_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
log_manage_r2 = ttk.Frame(log_manage_box)
|
||||
log_manage_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(log_manage_r2, text="日志总大小警告阈值(MB):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_manage_r2,
|
||||
from_=50,
|
||||
to=20000,
|
||||
increment=50,
|
||||
textvariable=vars_["logging_monitor_warning_mb_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 16))
|
||||
ttk.Label(log_manage_r2, text="严重阈值(MB):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_manage_r2,
|
||||
from_=100,
|
||||
to=100000,
|
||||
increment=100,
|
||||
textvariable=vars_["logging_monitor_critical_mb_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 性能追踪设置
|
||||
perf_box = ttk.LabelFrame(logging_container, text="性能追踪")
|
||||
perf_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
perf_r1 = ttk.Frame(perf_box)
|
||||
perf_r1.pack(fill=X, padx=10, pady=(10, 10))
|
||||
ttk.Checkbutton(
|
||||
perf_r1,
|
||||
text="启用性能追踪",
|
||||
variable=vars_["logging_performance_enabled_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
perf_r1,
|
||||
text="追踪函数调用",
|
||||
variable=vars_["logging_track_functions_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Checkbutton(
|
||||
perf_r1,
|
||||
text="流式后台截图(加速但可能导致并发读取)",
|
||||
variable=vars_["streaming_enabled_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
# 界面主题选择
|
||||
theme_box = ttk.LabelFrame(logging_container, text="界面设置")
|
||||
theme_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
theme_r1 = ttk.Frame(theme_box)
|
||||
theme_r1.pack(fill=X, padx=10, pady=(10, 10))
|
||||
ttk.Label(theme_r1, text="界面主题:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
theme_r1,
|
||||
values=["litera", "flatly", "journal", "minty", "cosmo", "darkly"],
|
||||
textvariable=vars_["gui_theme_var"],
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
ttk.Label(theme_r1, text="(更改后请保存并重启以完全应用主题)").pack(
|
||||
side=LEFT, padx=(12, 0)
|
||||
)
|
||||
|
||||
theme_r2 = ttk.Frame(theme_box)
|
||||
theme_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(theme_r2, text="实时状态刷新(ms):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
theme_r2,
|
||||
from_=200,
|
||||
to=10000,
|
||||
increment=100,
|
||||
textvariable=vars_["gui_realtime_refresh_interval_ms_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 20))
|
||||
ttk.Label(theme_r2, text="实时状态条数:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
theme_r2,
|
||||
from_=10,
|
||||
to=500,
|
||||
increment=10,
|
||||
textvariable=vars_["gui_realtime_tail_items_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 保存配置按钮
|
||||
save_config_frame = ttk.Frame(logging_container)
|
||||
save_config_frame.pack(fill=X, pady=(10, 0))
|
||||
ttk.Button(
|
||||
save_config_frame,
|
||||
text="保存日志配置",
|
||||
command=on_save_logging,
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
|
||||
return logging_tab
|
||||
@@ -0,0 +1,110 @@
|
||||
"""右侧主 Notebook 与实时工具栏的 widget 创建段。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。包括:
|
||||
- ``ttk.Notebook`` 容器
|
||||
- 实时工具栏(显示动作流 / 显示截图 / 自动滚动 / 实时查看)
|
||||
- 9 个 Tab 子 frame(运行日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间 /
|
||||
行为日志 / 实时状态 / OCR 结果 / 中奖记录)
|
||||
|
||||
返回 ``MainNotebookHandles`` 暴露所有引用,让 ``main()`` 后续把内容填进各 Tab。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X
|
||||
from typing import Callable
|
||||
|
||||
|
||||
@dataclass
|
||||
class MainNotebookHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
notebook: ttk.Notebook
|
||||
log_tab: ttk.Frame
|
||||
preview_tab: ttk.Frame
|
||||
stats_tab: ttk.Frame
|
||||
reservation_tab: ttk.Frame
|
||||
high_value_tab: ttk.Frame
|
||||
actions_log_tab: ttk.Frame
|
||||
realtime_tab: ttk.Frame
|
||||
ocr_results_tab: ttk.Frame
|
||||
win_record_tab: ttk.Frame
|
||||
show_actions_var: tk.BooleanVar
|
||||
show_screenshot_var: tk.BooleanVar
|
||||
auto_scroll_var: tk.BooleanVar
|
||||
|
||||
|
||||
def setup_main_notebook(
|
||||
right: tk.Misc,
|
||||
*,
|
||||
on_open_realtime_viewer: Callable[[], None],
|
||||
) -> MainNotebookHandles:
|
||||
"""构建右侧主 Notebook + 实时工具栏。
|
||||
|
||||
映射表 Tab 由调用方继续添加(因为它依赖 root/cfg)。
|
||||
"""
|
||||
# 右侧:Notebook(日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间)
|
||||
notebook = ttk.Notebook(right)
|
||||
|
||||
# 实时状态工具栏(固定在 Notebook 上方,始终可见)
|
||||
show_actions_var = tk.BooleanVar(value=True)
|
||||
show_screenshot_var = tk.BooleanVar(value=False)
|
||||
auto_scroll_var = tk.BooleanVar(value=True)
|
||||
|
||||
realtime_tools = ttk.Frame(right)
|
||||
realtime_tools.pack(fill=X, padx=8, pady=(4, 0))
|
||||
ttk.Checkbutton(realtime_tools, text="显示动作流", variable=show_actions_var).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
ttk.Checkbutton(realtime_tools, text="显示截图", variable=show_screenshot_var).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
ttk.Checkbutton(realtime_tools, text="自动滚动", variable=auto_scroll_var).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
realtime_view_btn = ttk.Button(
|
||||
realtime_tools,
|
||||
text="实时查看",
|
||||
width=10,
|
||||
command=on_open_realtime_viewer,
|
||||
)
|
||||
realtime_view_btn.pack(side=LEFT, padx=(8, 0))
|
||||
|
||||
log_tab = ttk.Frame(notebook)
|
||||
preview_tab = ttk.Frame(notebook)
|
||||
stats_tab = ttk.Frame(notebook)
|
||||
reservation_tab = ttk.Frame(notebook)
|
||||
high_value_tab = ttk.Frame(notebook)
|
||||
actions_log_tab = ttk.Frame(notebook)
|
||||
realtime_tab = ttk.Frame(notebook)
|
||||
ocr_results_tab = ttk.Frame(notebook)
|
||||
win_record_tab = ttk.Frame(notebook)
|
||||
notebook.add(log_tab, text="运行日志")
|
||||
notebook.add(preview_tab, text="截图预览")
|
||||
notebook.add(stats_tab, text="统计信息")
|
||||
notebook.add(reservation_tab, text="预约队列")
|
||||
notebook.add(high_value_tab, text="高价值房间")
|
||||
notebook.add(actions_log_tab, text="行为日志")
|
||||
notebook.add(realtime_tab, text="实时状态")
|
||||
notebook.add(ocr_results_tab, text="OCR结果")
|
||||
notebook.add(win_record_tab, text="中奖记录")
|
||||
|
||||
return MainNotebookHandles(
|
||||
notebook=notebook,
|
||||
log_tab=log_tab,
|
||||
preview_tab=preview_tab,
|
||||
stats_tab=stats_tab,
|
||||
reservation_tab=reservation_tab,
|
||||
high_value_tab=high_value_tab,
|
||||
actions_log_tab=actions_log_tab,
|
||||
realtime_tab=realtime_tab,
|
||||
ocr_results_tab=ocr_results_tab,
|
||||
win_record_tab=win_record_tab,
|
||||
show_actions_var=show_actions_var,
|
||||
show_screenshot_var=show_screenshot_var,
|
||||
auto_scroll_var=auto_scroll_var,
|
||||
)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""OCR 结果展示 Tab 的更新逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``update_ocr_results``,
|
||||
被 ``do_screenshot`` 在 OCR 完成后通过 ``root.after`` 调用。
|
||||
|
||||
依赖通过显式参数注入:``text_widget`` (展示用的 ScrolledText/Text widget)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Sequence, Tuple
|
||||
|
||||
|
||||
def update_ocr_results(text_widget: tk.Text, results: Sequence[Tuple[str, str, str, str]]) -> None:
|
||||
"""更新OCR结果标签页的显示"""
|
||||
try:
|
||||
lines = []
|
||||
lines.append("=" * 80)
|
||||
lines.append("OCR识别结果(基于最新截图)")
|
||||
lines.append("=" * 80)
|
||||
lines.append("")
|
||||
|
||||
if not results:
|
||||
lines.append('暂无OCR结果,请先点击"截图+OCR"按钮')
|
||||
else:
|
||||
# 按区域名称分组显示
|
||||
for region_name, desc, text_result, status in results:
|
||||
lines.append(f"【{region_name}】{desc}")
|
||||
lines.append(f" 状态: {status}")
|
||||
if text_result:
|
||||
# 如果文本较长,分行显示
|
||||
if len(text_result) > 100:
|
||||
lines.append(f" 识别文本: {text_result[:100]}...")
|
||||
lines.append(f" (完整文本: {text_result})")
|
||||
else:
|
||||
lines.append(f" 识别文本: {text_result}")
|
||||
else:
|
||||
lines.append(" 识别文本: (空)")
|
||||
lines.append("")
|
||||
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", "\n".join(lines))
|
||||
text_widget.see("1.0")
|
||||
except Exception as e:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", f"更新OCR结果失败:{e}")
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""GUI 周期性刷新调度 + 关闭处理。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。包括:
|
||||
- 启动时延迟一次性刷新各 Tab 内容(预览/统计/预约/高价值房间/操作日志/中奖记录)
|
||||
- 周期性刷新(操作日志 2s / 预约 5s / 统计 3s)
|
||||
- 窗口关闭时停止 runner
|
||||
|
||||
依赖通过显式参数注入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def setup_periodic_refreshers(
|
||||
root: tk.Misc,
|
||||
*,
|
||||
image_var: tk.StringVar,
|
||||
async_refresh_preview_impl: Callable[[Any], None],
|
||||
preview_view: Any,
|
||||
refresh_stats: Callable[[], None],
|
||||
refresh_reservations: Callable[[], None],
|
||||
refresh_high_value_rooms: Callable[[], None],
|
||||
refresh_actions_log: Callable[[], None],
|
||||
refresh_win_record: Callable[[], None],
|
||||
runner: Any,
|
||||
) -> None:
|
||||
"""启动延迟刷新 + 周期刷新调度。"""
|
||||
|
||||
def delayed_refresh_preview() -> None:
|
||||
if image_var.get():
|
||||
async_refresh_preview_impl(preview_view)
|
||||
|
||||
root.after(3000, delayed_refresh_preview) # type: ignore[arg-type]
|
||||
root.after(500, refresh_stats) # type: ignore[arg-type]
|
||||
root.after(500, refresh_reservations) # type: ignore[arg-type]
|
||||
root.after(500, refresh_high_value_rooms) # type: ignore[arg-type]
|
||||
root.after(500, refresh_actions_log) # type: ignore[arg-type]
|
||||
root.after(500, refresh_win_record) # type: ignore[arg-type]
|
||||
|
||||
# 定期刷新行为日志(每2秒)
|
||||
def auto_refresh_actions_log() -> None:
|
||||
refresh_actions_log()
|
||||
root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]
|
||||
|
||||
# 定期刷新预约队列(每5秒)
|
||||
def auto_refresh_reservations() -> None:
|
||||
refresh_reservations()
|
||||
root.after(5000, auto_refresh_reservations) # type: ignore[arg-type]
|
||||
|
||||
root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]
|
||||
root.after(5000, auto_refresh_reservations) # type: ignore[arg-type]
|
||||
|
||||
# 定期刷新统计信息(每3秒)
|
||||
def auto_refresh_stats() -> None:
|
||||
if runner.is_running():
|
||||
refresh_stats()
|
||||
root.after(3000, auto_refresh_stats) # type: ignore[arg-type]
|
||||
|
||||
auto_refresh_stats()
|
||||
|
||||
|
||||
def setup_close_handler(
|
||||
root: tk.Misc,
|
||||
*,
|
||||
runner: Any,
|
||||
) -> None:
|
||||
"""绑定窗口关闭(WM_DELETE_WINDOW)→ 停止 runner + 销毁 root。"""
|
||||
def on_close():
|
||||
try:
|
||||
runner.stop()
|
||||
except Exception:
|
||||
pass
|
||||
root.destroy()
|
||||
|
||||
root.protocol("WM_DELETE_WINDOW", on_close)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""截图预览 Tab 的 widget 创建段。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。包括:
|
||||
- 顶部按钮区(选择图片下拉 + 刷新列表 + 刷新预览 + 打开pic目录)
|
||||
- 主预览区(image_label)
|
||||
- 状态栏
|
||||
|
||||
依赖通过显式参数注入,返回 ``PreviewTabHandles`` 让 ``main()`` 后续调用刷新逻辑。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, LEFT, RIGHT, X
|
||||
from typing import Any, Callable
|
||||
|
||||
from gui.components.preview_view import (
|
||||
PreviewView,
|
||||
update_image_list as _update_image_list_impl,
|
||||
refresh_preview as _refresh_preview_impl,
|
||||
open_pic_folder as _open_pic_folder_impl,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreviewTabHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
preview_view: PreviewView
|
||||
image_var: tk.StringVar
|
||||
refresh_preview: Callable[[], None]
|
||||
update_image_list: Callable[[bool], None]
|
||||
|
||||
|
||||
def _get_pic_dir() -> str:
|
||||
try:
|
||||
from douyin.core.path_config import get_pic_dir
|
||||
|
||||
return get_pic_dir()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
return path_config.get_pic_dir()
|
||||
|
||||
|
||||
def setup_preview_tab(
|
||||
preview_tab: tk.Misc,
|
||||
*,
|
||||
on_line: Callable[[str], None],
|
||||
root: tk.Misc,
|
||||
) -> PreviewTabHandles:
|
||||
"""构建截图预览 Tab 的 UI。"""
|
||||
preview_top = ttk.Frame(preview_tab)
|
||||
preview_top.pack(fill=X, padx=10, pady=10)
|
||||
|
||||
images_dir = _get_pic_dir()
|
||||
|
||||
image_var = tk.StringVar(value="")
|
||||
|
||||
ttk.Label(preview_top, text="选择图片:").pack(side=LEFT)
|
||||
# 允许手工输入子路径(例如 start/latest.png),方便查看逐步截图
|
||||
image_combo = ttk.Combobox(
|
||||
preview_top, textvariable=image_var, width=30, state="normal"
|
||||
)
|
||||
image_combo.pack(side=LEFT, padx=(0, 10))
|
||||
|
||||
def update_image_list(refresh_after: bool = True) -> None:
|
||||
_update_image_list_impl(view, refresh_after=refresh_after)
|
||||
|
||||
# 先定义refresh_preview函数(即使它引用了后面的变量,函数定义本身是延迟执行的)
|
||||
def refresh_preview() -> None:
|
||||
_refresh_preview_impl(view)
|
||||
|
||||
preview_status = tk.StringVar(value="")
|
||||
ttk.Label(preview_top, textvariable=preview_status).pack(side=RIGHT)
|
||||
|
||||
preview_body = ttk.Frame(preview_tab)
|
||||
preview_body.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
|
||||
|
||||
image_label = ttk.Label(preview_body)
|
||||
image_label.pack(fill=BOTH, expand=True)
|
||||
_img_ref: dict[str, Any] = {"photo": None} # 防止 PhotoImage 被回收
|
||||
|
||||
view = PreviewView(
|
||||
images_dir=str(images_dir),
|
||||
image_var=image_var,
|
||||
image_combo=image_combo,
|
||||
preview_body=preview_body,
|
||||
image_label=image_label,
|
||||
preview_status=preview_status,
|
||||
on_line=on_line,
|
||||
root=root,
|
||||
img_ref=_img_ref,
|
||||
)
|
||||
|
||||
update_image_list(refresh_after=False) # 初始化时扫描一次,但不刷新预览
|
||||
|
||||
ttk.Button(
|
||||
preview_top,
|
||||
text="刷新列表",
|
||||
command=lambda: update_image_list(refresh_after=True),
|
||||
).pack(side=LEFT, padx=(0, 5))
|
||||
ttk.Button(preview_top, text="刷新预览", command=refresh_preview).pack(side=LEFT)
|
||||
|
||||
# 绑定选择变化事件,自动刷新预览(在 refresh_preview 函数定义之后)
|
||||
def on_image_selected(*args):
|
||||
try:
|
||||
refresh_preview()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
image_var.trace("w", on_image_selected) # 监听变量变化
|
||||
image_combo.bind(
|
||||
"<<ComboboxSelected>>", lambda e: refresh_preview()
|
||||
) # 监听下拉选择
|
||||
|
||||
def open_pic_folder() -> None:
|
||||
_open_pic_folder_impl(view)
|
||||
|
||||
ttk.Button(preview_top, text="打开pic目录", command=open_pic_folder).pack(
|
||||
side=LEFT, padx=(10, 0)
|
||||
)
|
||||
|
||||
return PreviewTabHandles(
|
||||
preview_view=view,
|
||||
image_var=image_var,
|
||||
refresh_preview=refresh_preview,
|
||||
update_image_list=update_image_list,
|
||||
)
|
||||
Loaded 100 of 201 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user