feat: Optimize OCR performance and enhance debugging features
- Implemented parallel execution for OCR tasks, significantly improving recognition speed for content, countdown, and value detection. - Updated configuration settings to support automatic cleanup of debug captures, including retention days and maximum file limits. - Enhanced GUI to include new options for debugging parameters, allowing users to configure debug capture settings directly. - Improved documentation to reflect changes in OCR functionality and debugging features, ensuring clarity for users. - Refined error handling and logging across various modules to facilitate better monitoring and troubleshooting.
This commit is contained in:
1 parent
42bd51cc70
commit
533943620c
33 files changed
+19279
-540
No files matched your search
+1047
-1
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -105,3 +105,8 @@ python cleanup_unused_files.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -203,3 +203,8 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -174,3 +174,8 @@ python check_dependencies.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -153,3 +153,8 @@ douyin_guaji
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -94,3 +94,8 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -306,3 +306,8 @@ douyin_fudai_finder.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
基于 ADB + OCR + 像素检测 + 模板匹配技术
|
||||
|
||||
[](version.py)
|
||||
[](version.py)
|
||||
[](https://www.python.org/)
|
||||
[](https://www.microsoft.com/windows)
|
||||
|
||||
@@ -46,6 +46,8 @@
|
||||
- ✅ **多界面支持**:提供桌面 GUI、Web GUI 和命令行三种使用方式
|
||||
- ✅ **模块化设计**:代码结构清晰,易于维护和扩展
|
||||
- ✅ **详细日志**:完整的运行日志记录,便于问题排查
|
||||
- ✅ **性能优化**:并行OCR执行,识别速度提升约50%
|
||||
- ✅ **代码质量**:通过 Pylance 类型检查,代码健壮性高
|
||||
|
||||
### 适用场景
|
||||
|
||||
@@ -138,7 +140,7 @@
|
||||
|
||||
- 支持上划切换直播间
|
||||
- 可配置切换策略(倒计时阈值)
|
||||
- 支持切换N次后回到第一个直播间(循环模式)
|
||||
- 支持切换N次后回到第一个直播间(循环模式,向上回退)
|
||||
- 智能处理直播结束、网络异常等情况
|
||||
|
||||
---
|
||||
@@ -170,11 +172,13 @@
|
||||
- 使用 PaddleOCR 识别文字内容
|
||||
- 用于识别福袋内容、倒计时、价值等
|
||||
- 支持中英文识别
|
||||
- **并行执行优化**:多个 OCR 操作并行执行,显著提升识别速度
|
||||
|
||||
4. **阶段诊断**
|
||||
- 综合使用像素检测、模板匹配和OCR
|
||||
- 判断当前页面状态(直播间、推荐页、详情页等)
|
||||
- 支持并行检测,提高效率
|
||||
- **并行OCR优化**:倒计时分割识别、模式0+模式1并行执行等
|
||||
|
||||
### 架构设计
|
||||
|
||||
@@ -414,7 +418,7 @@ python run_cli.py \
|
||||
| `wait_minutes` | integer | `5` | 倒计时超过该分钟数时切换直播间(仅在 needswitch=true 时生效) |
|
||||
| `skip_if_countdown_lt_seconds` | integer | `5` | 倒计时小于该秒数时不参与(高价值福袋可预约) |
|
||||
| `reset_after_swipes_enabled` | boolean | `true` | 是否启用"切换N次后回到第一个直播间"功能 |
|
||||
| `reset_after_swipes` | integer | `30` | 切换直播间达到该次数后,下滑回退到第一个直播间 |
|
||||
| `reset_after_swipes` | integer | `30` | 切换直播间达到该次数后,向上回退到第一个直播间 |
|
||||
| `fudai_find_max_attempts` | integer | `10` | 找福袋图标的最大尝试次数 |
|
||||
| `fudai_icon_retry_delay_seconds` | float | `0.6` | 找福袋图标的重试间隔(秒) |
|
||||
| `fudai_icon_max_wait_seconds` | float | `5.0` | 找福袋图标的最大等待时间(秒),实际识别常见 4-6 秒 |
|
||||
@@ -585,6 +589,10 @@ python run_cli.py \
|
||||
- 配置端口转发,实现外网访问
|
||||
|
||||
4. **性能优化**
|
||||
- **并行OCR执行**(V3.3.2+):多个OCR操作并行执行,识别速度提升约50%
|
||||
- 福袋内容、倒计时、价值识别并行执行
|
||||
- 倒计时分割识别(分钟+秒)并行执行
|
||||
- OCR模式0+模式1并行执行(启用时)
|
||||
- 调整阶段诊断时间参数,平衡速度和准确性
|
||||
- 优化 OCR 缓存设置,减少重复识别
|
||||
- 根据设备性能调整截图频率
|
||||
@@ -663,10 +671,12 @@ python run_cli.py \
|
||||
- 处理各种弹窗干扰
|
||||
|
||||
3. **信息提取**
|
||||
- **并行OCR识别**:内容、倒计时、价值、任务数量检测并行执行
|
||||
- OCR 识别福袋内容区域
|
||||
- OCR 识别倒计时区域
|
||||
- OCR 识别倒计时区域(支持分割识别)
|
||||
- OCR 识别价值区域
|
||||
- OCR 识别参与人数区域
|
||||
- 任务数量检测(像素检测)
|
||||
|
||||
4. **信息解析**
|
||||
- 解析倒计时文本(支持多种格式)
|
||||
@@ -940,10 +950,11 @@ python run_cli.py \
|
||||
**问题**:OCR 识别速度慢
|
||||
|
||||
**解决方案**:
|
||||
1. 减少 OCR 识别频率
|
||||
2. 启用 OCR 缓存(如果支持)
|
||||
3. 优化识别区域大小
|
||||
4. 使用 GPU 版本的 PaddleOCR(如果有 GPU)
|
||||
1. **已优化**:V3.3.2+ 版本已实现并行OCR,识别速度显著提升
|
||||
2. 减少 OCR 识别频率
|
||||
3. 启用 OCR 缓存(如果支持)
|
||||
4. 优化识别区域大小
|
||||
5. 使用 GPU 版本的 PaddleOCR(如果有 GPU)
|
||||
|
||||
### 运行异常问题
|
||||
|
||||
@@ -1176,10 +1187,21 @@ python run_cli.py \
|
||||
|
||||
## 📜 版本历史
|
||||
|
||||
### V3.3.1 (2025-12-14)
|
||||
### V3.3.2 (2025-12-22)
|
||||
|
||||
**当前版本**
|
||||
|
||||
- 🚀 **性能优化**:所有串行OCR改为并行执行,显著提升识别速度
|
||||
- 福袋内容、倒计时、价值识别并行执行
|
||||
- 倒计时分割识别(分钟+秒)并行执行
|
||||
- OCR模式0+模式1并行执行(启用时)
|
||||
- 异常回退流程也使用并行执行
|
||||
- 🐛 修复:修复"切换N次后回到第一个"的回退方向(改为向上回退)
|
||||
- 🔧 优化:代码质量改进,通过 Pylance 类型检查
|
||||
- 📝 更新:完善文档和 README
|
||||
|
||||
### V3.3.1 (2025-12-14)
|
||||
|
||||
- ✨ 新增:直播间检测阈值可配置(`live_room_match_threshold`)
|
||||
- ✨ 新增:福袋图标检测等待时间可配置
|
||||
- 🐛 修复:修复直播间检测模板文件路径警告
|
||||
|
||||
@@ -217,7 +217,7 @@ class underlying_operations:
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||||
devnull
|
||||
):
|
||||
import easyocr
|
||||
import easyocr # type: ignore[import-untyped]
|
||||
|
||||
# 只加载中文和英文,加快初始化速度
|
||||
self.ocr = easyocr.Reader(
|
||||
@@ -301,7 +301,7 @@ class underlying_operations:
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(
|
||||
devnull
|
||||
):
|
||||
import easyocr
|
||||
import easyocr # type: ignore[import-untyped]
|
||||
|
||||
self.ocr = easyocr.Reader(["ch_sim", "en"], gpu=False, verbose=False)
|
||||
self.ocr_type = "easyocr"
|
||||
@@ -1529,8 +1529,8 @@ class underlying_operations:
|
||||
pass
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _escape_shell_double_quotes(text: str) -> str: # type: ignore[misc]
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _escape_shell_double_quotes(text: str) -> str:
|
||||
return str(text).replace("\\", "\\\\").replace('"', '\\"')
|
||||
|
||||
def set_clipboard_text(self, device_id: str, text: str) -> bool:
|
||||
@@ -1623,8 +1623,8 @@ class underlying_operations:
|
||||
lines = [ln.strip() for ln in (out2 or "").splitlines() if ln.strip()]
|
||||
return lines
|
||||
|
||||
@staticmethod
|
||||
def _pick_adbkeyboard_ime(imes: list[str]) -> str: # type: ignore[misc]
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _pick_adbkeyboard_ime(imes: list[str]) -> str:
|
||||
# 兼容不同包名/组件名写法,优先匹配常见的 AdbIME
|
||||
for cand in imes or []:
|
||||
s = str(cand).strip()
|
||||
@@ -1856,8 +1856,8 @@ class underlying_operations:
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _parse_bounds(bounds: str): # type: ignore[misc]
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _parse_bounds(bounds: str):
|
||||
m = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", str(bounds or ""))
|
||||
if not m:
|
||||
return None
|
||||
|
||||
@@ -65,3 +65,7 @@ python 生成WPS流程图.py
|
||||
- 如果SVG太大,可以在mermaid.live中调整导出设置
|
||||
- 文本格式适合手动创建更详细的流程图
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -78,3 +78,8 @@ else:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+6
-1
@@ -7,7 +7,7 @@
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 150,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 50,
|
||||
"reset_after_swipes": 2,
|
||||
"auto_join_fansclub": true,
|
||||
"fansclub_fail_action": "switch",
|
||||
"high_value_fudai_enabled": true,
|
||||
@@ -89,5 +89,10 @@
|
||||
"when": "midnight",
|
||||
"interval": 1
|
||||
}
|
||||
},
|
||||
"debug_captures": {
|
||||
"keep_days": 7,
|
||||
"max_files": 2000,
|
||||
"auto_cleanup": true
|
||||
}
|
||||
}
|
||||
+114
-5
@@ -1525,6 +1525,40 @@ class fudai_analyse:
|
||||
# 未识别出特殊阶段:尽量保持原地,交给上层循环
|
||||
self._log_kv("阶段", "未匹配到特定阶段", stage=stage)
|
||||
|
||||
def _shot_and_diagnose(
|
||||
self, tag: str, msg: str, device_id: str, diagnose: bool = True
|
||||
) -> None:
|
||||
"""截图并执行阶段诊断(兼容旧版调用方式)。
|
||||
|
||||
Args:
|
||||
tag: 日志标签
|
||||
msg: 日志消息
|
||||
device_id: 设备ID
|
||||
diagnose: 是否执行阶段诊断(默认True)
|
||||
"""
|
||||
try:
|
||||
# 截图
|
||||
ok = self.operation.get_screenshot(device_id)
|
||||
if not ok:
|
||||
self._log_kv(tag, f"{msg} - 获取截图失败", ok=0)
|
||||
return
|
||||
|
||||
# 如果启用诊断,执行阶段诊断
|
||||
if diagnose:
|
||||
stage, seen = self._diagnose_stage_from_current_screen()
|
||||
self._last_diag_stage = stage
|
||||
self._last_diag_seen = seen
|
||||
self._last_diag_ts = time.time()
|
||||
self._log_kv(tag, msg, stage=stage, seen=seen)
|
||||
else:
|
||||
self._log_kv(tag, msg)
|
||||
except Exception as e:
|
||||
# 避免异常影响主流程
|
||||
try:
|
||||
self._log_kv(tag, f"{msg} - 异常: {type(e).__name__}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ========== 基础动作封装 ==========
|
||||
def swipe_up_to_next_live(self) -> None:
|
||||
"""上滑切换直播间(简单版封装)。"""
|
||||
@@ -1593,7 +1627,7 @@ class fudai_analyse:
|
||||
try:
|
||||
self._log_kv(
|
||||
"流程",
|
||||
"已切换直播间{}次,达到阈值{}:下滑回退到第一个直播间".format(
|
||||
"已切换直播间{}次,达到阈值{}:向上回退到第一个直播间".format(
|
||||
swipe_times, threshold
|
||||
),
|
||||
swipe_times=swipe_times,
|
||||
@@ -1607,7 +1641,7 @@ class fudai_analyse:
|
||||
if back_times <= 0:
|
||||
return 0
|
||||
|
||||
# 下滑回退:与上划切换相反方向
|
||||
# 向上回退:从上往下滑动(与上划切换相反方向)
|
||||
try:
|
||||
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
|
||||
@@ -1616,11 +1650,11 @@ class fudai_analyse:
|
||||
|
||||
for i in range(back_times):
|
||||
try:
|
||||
# 下滑:从下往上滑动
|
||||
# 向上回退:从上往下滑动(start_y < end_y)
|
||||
start_x = 760 * rx // 1080
|
||||
start_y = 1600 * ry // 2400
|
||||
start_y = 800 * ry // 2400 # 上方起始位置
|
||||
end_x = 760 * rx // 1080
|
||||
end_y = 800 * ry // 2400
|
||||
end_y = 1600 * ry // 2400 # 下方结束位置
|
||||
self.operation.swipe(
|
||||
self.device_id, start_x, start_y, end_x, end_y, 200
|
||||
)
|
||||
@@ -1799,6 +1833,81 @@ class fudai_analyse:
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
elif last_status == "error":
|
||||
# 检查是否是任务数量为0的错误
|
||||
try:
|
||||
last_extra = getattr(self, "_last_fudai_detail_extra", {})
|
||||
if isinstance(last_extra, dict) and last_extra.get("reason") == "task_count_zero":
|
||||
# 记录连续失败次数
|
||||
consecutive_failures = getattr(self, "_fudai_detail_consecutive_failures", 0) or 0
|
||||
consecutive_failures += 1
|
||||
try:
|
||||
self._fudai_detail_consecutive_failures = consecutive_failures
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果连续失败3次,强制关闭详情页并切换直播间,避免卡死
|
||||
if consecutive_failures >= 3:
|
||||
try:
|
||||
self._log_kv(
|
||||
"流程",
|
||||
"_handle_in_fudai_detail:连续3次识别到任务数量为0,强制关闭详情页并切换直播间,避免卡死",
|
||||
consecutive_failures=consecutive_failures,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 强制关闭详情页
|
||||
try:
|
||||
douyin_fudai_detail.close_fudai_detail(self)
|
||||
self.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
# 切换直播间
|
||||
try:
|
||||
needswitch = bool(getattr(self, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if needswitch:
|
||||
try:
|
||||
if hasattr(self, "swipe_up_to_next_live"):
|
||||
self.swipe_up_to_next_live()
|
||||
else:
|
||||
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1700 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 700 * ry // 2400
|
||||
self.operation.swipe(
|
||||
self.device_id, start_x, start_y, end_x, end_y, 300
|
||||
)
|
||||
self.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
# 重置失败计数
|
||||
try:
|
||||
self._fudai_detail_consecutive_failures = 0
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
else:
|
||||
try:
|
||||
self._log_kv(
|
||||
"流程",
|
||||
"_handle_in_fudai_detail:检测到任务数量为0,跳过后续处理",
|
||||
consecutive_failures=consecutive_failures,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果成功读取,重置失败计数
|
||||
try:
|
||||
self._fudai_detail_consecutive_failures = 0
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
+248
-27
@@ -101,20 +101,24 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
return ""
|
||||
|
||||
def _read_countdown_split(box: tuple[int, int, int, int]) -> str:
|
||||
"""将倒计时区域按三等分切成“分钟段/秒段/后开奖段”,分别OCR分钟与秒,组合为 mm:ss。"""
|
||||
"""将倒计时区域按三等分切成"分钟段/秒段/后开奖段",分别OCR分钟与秒,组合为 mm:ss。"""
|
||||
try:
|
||||
x1, y1, x2, y2 = box
|
||||
w = max(1, int(x2 - x1))
|
||||
seg = max(1, w // 3)
|
||||
# 前 1/3:分钟;中 1/3:秒(第三段通常包含“后开奖”)
|
||||
# 前 1/3:分钟;中 1/3:秒(第三段通常包含"后开奖")
|
||||
analyser.cut_pic(
|
||||
x1, y1, x1 + seg, y2, "", "福袋倒计时_分钟", analyser.y_pianyi
|
||||
)
|
||||
analyser.cut_pic(
|
||||
x1 + seg, y1, x1 + 2 * seg, y2, "", "福袋倒计时_秒", analyser.y_pianyi
|
||||
)
|
||||
mm_raw = analyser.operation.analyse_pic_word("福袋倒计时_分钟", 0)
|
||||
ss_raw = analyser.operation.analyse_pic_word("福袋倒计时_秒", 0)
|
||||
# 并行执行两个OCR识别
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_mm = executor.submit(analyser.operation.analyse_pic_word, "福袋倒计时_分钟", 0)
|
||||
future_ss = executor.submit(analyser.operation.analyse_pic_word, "福袋倒计时_秒", 0)
|
||||
mm_raw = future_mm.result()
|
||||
ss_raw = future_ss.result()
|
||||
mm = _extract_2digits(mm_raw)
|
||||
ss = _extract_2digits(ss_raw)
|
||||
if mm and ss:
|
||||
@@ -144,12 +148,12 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
|
||||
countdown_box = None
|
||||
if renwu == 2: # 如果是2个任务的
|
||||
# 优化:稍微缩小宽度(1000->980),增加高度(1460->1470),减少右侧干扰,确保内容完整
|
||||
# 保存完整截图并标注OCR区域
|
||||
_save_full_screenshot_with_ocr_region(analyser, "福袋内容", (390, 1240, 980, 1470), analyser.y_pianyi)
|
||||
# 优化:扩大Y范围向上,确保包含任务描述(如"观看X分钟"等)
|
||||
# 从1240向上扩展到1100,确保包含任务描述区域
|
||||
_save_full_screenshot_with_ocr_region(analyser, "福袋内容", (390, 1100, 980, 1470), analyser.y_pianyi)
|
||||
analyser.cut_pic(
|
||||
390, 1240, 980, 1470, "", "福袋内容", analyser.y_pianyi
|
||||
) # 福袋内容详情
|
||||
390, 1100, 980, 1470, "", "福袋内容", analyser.y_pianyi
|
||||
) # 福袋内容详情(包含任务描述)
|
||||
# 优化:稍微扩大高度(1220->1230),确保包含完整的"后开奖"文字
|
||||
countdown_box = (390, 1110, 690, 1230)
|
||||
_save_full_screenshot_with_ocr_region(analyser, "福袋倒计时", countdown_box, analyser.y_pianyi)
|
||||
@@ -162,11 +166,11 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
390, 1460, 1000, 1580, "", "福袋价值", analyser.y_pianyi
|
||||
) # 奖品价值/价格
|
||||
elif renwu == 1: # 如果是1个任务的
|
||||
# 优化:稍微缩小宽度,增加高度,减少干扰
|
||||
_save_full_screenshot_with_ocr_region(analyser, "福袋内容", (390, 1300, 980, 1530), analyser.y_pianyi)
|
||||
# 优化:扩大Y范围向上,确保包含任务描述
|
||||
_save_full_screenshot_with_ocr_region(analyser, "福袋内容", (390, 1160, 980, 1530), analyser.y_pianyi)
|
||||
analyser.cut_pic(
|
||||
390, 1300, 980, 1530, "", "福袋内容", analyser.y_pianyi
|
||||
) # 福袋内容详情
|
||||
390, 1160, 980, 1530, "", "福袋内容", analyser.y_pianyi
|
||||
) # 福袋内容详情(包含任务描述)
|
||||
# 优化:稍微扩大高度,确保完整
|
||||
countdown_box = (390, 1180, 690, 1300)
|
||||
_save_full_screenshot_with_ocr_region(analyser, "福袋倒计时", countdown_box, analyser.y_pianyi)
|
||||
@@ -179,11 +183,11 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
390, 1520, 1000, 1630, "", "福袋价值", analyser.y_pianyi
|
||||
) # 奖品价值/价格
|
||||
elif renwu == 3: # 如果是3个任务的
|
||||
# 优化:稍微缩小宽度,增加高度
|
||||
_save_full_screenshot_with_ocr_region(analyser, "福袋内容", (390, 1160, 980, 1390), analyser.y_pianyi)
|
||||
# 优化:扩大Y范围向上,确保包含任务描述
|
||||
_save_full_screenshot_with_ocr_region(analyser, "福袋内容", (390, 1020, 980, 1390), analyser.y_pianyi)
|
||||
analyser.cut_pic(
|
||||
390, 1160, 980, 1390, "", "福袋内容", analyser.y_pianyi
|
||||
) # 福袋内容详情
|
||||
390, 1020, 980, 1390, "", "福袋内容", analyser.y_pianyi
|
||||
) # 福袋内容详情(包含任务描述)
|
||||
# 优化:稍微扩大高度
|
||||
countdown_box = (390, 1010, 690, 1130)
|
||||
_save_full_screenshot_with_ocr_region(analyser, "福袋倒计时", countdown_box, analyser.y_pianyi)
|
||||
@@ -213,11 +217,61 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
390, 1820, 1000, 1930, "", "福袋价值", analyser.y_pianyi
|
||||
) # 奖品价值/价格
|
||||
|
||||
# 并行执行三个OCR操作以提高性能
|
||||
# 先OCR识别任务列表区域(任务位置:50,1621到1032,1960),检查是否包含"观看X分钟"任务
|
||||
# 这个区域包含具体的任务描述,是检测观看任务的关键区域
|
||||
task_list_raw = None
|
||||
try:
|
||||
# 保存任务列表区域的调试截图
|
||||
_save_full_screenshot_with_ocr_region(analyser, "福袋任务列表", (50, 1621, 1032, 1960), analyser.y_pianyi)
|
||||
analyser.cut_pic(
|
||||
50, 1621, 1032, 1960, "", "福袋任务列表", analyser.y_pianyi
|
||||
)
|
||||
# OCR识别任务列表
|
||||
task_list_raw = analyser.operation.analyse_pic_word("福袋任务列表", 0)
|
||||
if task_list_raw:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋",
|
||||
"OCR识别任务列表区域",
|
||||
task_list_text=task_list_raw[:200] if task_list_raw else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 检查任务列表中是否包含"观看X分钟"任务
|
||||
is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw))
|
||||
if is_watch_task_in_list:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋",
|
||||
"任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理",
|
||||
task_list_text=task_list_raw[:200] if task_list_raw else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 设置标志,让调用方知道这是观看任务
|
||||
try:
|
||||
analyser._is_watch_task_detected = True
|
||||
except Exception:
|
||||
pass
|
||||
# 直接返回空内容,后续流程会跳过
|
||||
return "", "", 0, 0, 0.0
|
||||
except Exception as e:
|
||||
# 任务列表OCR失败不影响后续流程,记录日志即可
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋",
|
||||
"任务列表OCR识别失败,继续后续流程",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 并行执行四个操作:OCR识别内容/倒计时/价值 + 任务数量检测
|
||||
ocr_start_time = time.time()
|
||||
fudai_content_raw = None
|
||||
time_raw = None
|
||||
value_raw = None
|
||||
detected_task_count = None
|
||||
|
||||
def ocr_content():
|
||||
"""OCR识别福袋内容"""
|
||||
@@ -240,40 +294,207 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
# 使用线程池并行执行OCR
|
||||
def detect_task_count():
|
||||
"""检测任务数量(像素检测参与按钮位置)"""
|
||||
try:
|
||||
from douyin_detection import check_detail_height
|
||||
task_count = int(check_detail_height(analyser) or 0)
|
||||
return task_count
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
# 使用线程池并行执行OCR和任务数量检测
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=3) as executor:
|
||||
with ThreadPoolExecutor(max_workers=4) as executor:
|
||||
future_content = executor.submit(ocr_content)
|
||||
future_countdown = executor.submit(ocr_countdown)
|
||||
future_value = executor.submit(ocr_value)
|
||||
future_task_count = executor.submit(detect_task_count)
|
||||
|
||||
# 等待所有OCR完成
|
||||
# 等待所有操作完成
|
||||
fudai_content_raw = future_content.result()
|
||||
time_raw = future_countdown.result()
|
||||
value_raw = future_value.result()
|
||||
detected_task_count = future_task_count.result()
|
||||
|
||||
ocr_elapsed = time.time() - ocr_start_time
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"性能",
|
||||
"并行OCR识别完成",
|
||||
"并行OCR识别完成(包含任务数量检测)",
|
||||
elapsed_seconds=round(ocr_elapsed, 3),
|
||||
task_count=detected_task_count,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检测到任务数量后,点击一次返回,然后切换到下一个直播间,并直接返回
|
||||
# 注意:任务数量为0时说明没有正确打开福袋,不执行返回和切换操作
|
||||
if detected_task_count is not None and detected_task_count > 0:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"并行OCR检测到任务数量",
|
||||
task_count=detected_task_count,
|
||||
)
|
||||
# 点击一次返回
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
analyser._log_kv("福袋详情", "检测到任务数量后点击返回")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 切换到下一个直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if needswitch:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"检测到任务数量后切换直播间",
|
||||
task_count=detected_task_count,
|
||||
)
|
||||
# 优先使用封装好的上滑切房方法
|
||||
if hasattr(analyser, "swipe_up_to_next_live"):
|
||||
analyser.swipe_up_to_next_live()
|
||||
else:
|
||||
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1700 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 700 * ry // 2400
|
||||
analyser.operation.swipe(
|
||||
analyser.device_id, start_x, start_y, end_x, end_y, 300
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 检测到任务数量后直接返回,不继续后续处理
|
||||
return "", "", 0, 0, 0.0
|
||||
except Exception:
|
||||
pass
|
||||
elif detected_task_count == 0:
|
||||
# 任务数量为0,说明没有正确打开福袋详情页,记录日志但不执行返回操作
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"并行OCR检测到任务数量为0,认为未正确打开福袋详情页,跳过返回操作",
|
||||
task_count=detected_task_count,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 如果并行执行失败,回退到串行执行
|
||||
# 如果并行执行失败,回退到并行执行(使用新的线程池)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"性能",
|
||||
"并行OCR失败,回退到串行执行",
|
||||
"并行OCR失败,使用备用并行执行",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
fudai_content_raw = analyser.operation.analyse_pic_word("福袋内容", 0)
|
||||
time_raw = analyser.operation.analyse_pic_word("福袋倒计时", 0)
|
||||
value_raw = analyser.operation.analyse_pic_word("福袋价值", 0)
|
||||
# 使用线程池并行执行OCR和任务数量检测
|
||||
try:
|
||||
def ocr_content_fallback():
|
||||
try:
|
||||
return analyser.operation.analyse_pic_word("福袋内容", 0)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def ocr_countdown_fallback():
|
||||
try:
|
||||
return analyser.operation.analyse_pic_word("福袋倒计时", 0)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def ocr_value_fallback():
|
||||
try:
|
||||
return analyser.operation.analyse_pic_word("福袋价值", 0)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def detect_task_count_fallback():
|
||||
try:
|
||||
from douyin_detection import check_detail_height
|
||||
return int(check_detail_height(analyser) or 0)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as executor:
|
||||
future_content = executor.submit(ocr_content_fallback)
|
||||
future_countdown = executor.submit(ocr_countdown_fallback)
|
||||
future_value = executor.submit(ocr_value_fallback)
|
||||
future_task_count = executor.submit(detect_task_count_fallback)
|
||||
|
||||
# 等待所有操作完成
|
||||
fudai_content_raw = future_content.result()
|
||||
time_raw = future_countdown.result()
|
||||
value_raw = future_value.result()
|
||||
detected_task_count = future_task_count.result()
|
||||
|
||||
# 检测任务数量后的处理逻辑
|
||||
if detected_task_count is not None and detected_task_count > 0:
|
||||
# 点击返回并切换直播间,然后直接返回
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"备用并行模式检测到任务数量",
|
||||
task_count=detected_task_count,
|
||||
)
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
if needswitch:
|
||||
if hasattr(analyser, "swipe_up_to_next_live"):
|
||||
analyser.swipe_up_to_next_live()
|
||||
else:
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1700 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 700 * ry // 2400
|
||||
analyser.operation.swipe(
|
||||
analyser.device_id, start_x, start_y, end_x, end_y, 300
|
||||
)
|
||||
# 检测到任务数量后直接返回,不继续后续处理
|
||||
return "", "", 0, 0, 0.0
|
||||
except Exception:
|
||||
pass
|
||||
elif detected_task_count == 0:
|
||||
# 任务数量为0,说明没有正确打开福袋详情页,记录日志但不执行返回操作
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"备用并行模式检测到任务数量为0,认为未正确打开福袋详情页,跳过返回操作",
|
||||
task_count=detected_task_count,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as fallback_error:
|
||||
# 如果备用并行执行也失败,使用串行执行作为最后兜底
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"性能",
|
||||
"备用并行OCR也失败,使用串行执行作为最后兜底",
|
||||
error=str(fallback_error),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
fudai_content_raw = analyser.operation.analyse_pic_word("福袋内容", 0)
|
||||
time_raw = analyser.operation.analyse_pic_word("福袋倒计时", 0)
|
||||
value_raw = analyser.operation.analyse_pic_word("福袋价值", 0)
|
||||
detected_task_count = None
|
||||
|
||||
# 先检查原始OCR内容是否是"观看X分钟"任务(在清理之前检查,避免丢失关键信息)
|
||||
is_watch_task = False
|
||||
|
||||
+228
-32
@@ -359,12 +359,30 @@ def _is_wrong_coupon_popup(analyser: Any) -> bool:
|
||||
pass
|
||||
|
||||
analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
|
||||
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
|
||||
|
||||
# 如果模式0未识别到,尝试模式1
|
||||
# 并行执行模式0和模式1的OCR(如果启用模式1)
|
||||
enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False))
|
||||
if enable_ocr_mode1 and (not coupon_text or "开心收下" not in coupon_text):
|
||||
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "")
|
||||
coupon_text = ""
|
||||
if enable_ocr_mode1:
|
||||
# 并行执行两个OCR模式
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_mode0 = executor.submit(analyser.operation.analyse_pic_word, "参与按钮", 0)
|
||||
future_mode1 = executor.submit(analyser.operation.analyse_pic_word, "参与按钮", 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
|
||||
else:
|
||||
# 只使用模式0
|
||||
coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
|
||||
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
# 模板匹配 + OCR 都确认,判定为优惠券弹窗
|
||||
@@ -470,7 +488,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
5. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值;
|
||||
6. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。
|
||||
"""
|
||||
# 步骤1:获取截图(模板匹配已在阶段诊断中完成,这里直接开始OCR识别)
|
||||
# 步骤1:获取截图并模板匹配"超级福袋"标题,确认是否在福袋详情页
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except Exception:
|
||||
@@ -495,14 +513,117 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
return "error", tup_err, {"reason": "screenshot_failed"}
|
||||
|
||||
# 注意:模板匹配"超级福袋"已在阶段诊断中完成(步骤0.5),这里直接开始OCR识别
|
||||
# 模板匹配"超级福袋"标题
|
||||
is_in_fudai_detail = False
|
||||
template_match_score = None
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:阶段诊断已确认在福袋详情页,开始OCR识别",
|
||||
import douyin_pixel
|
||||
import douyin_screenshot_manager
|
||||
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
|
||||
# 计算检测区域(用于保存调试图片)
|
||||
width, height = pic_rgb.size
|
||||
scale_x = width / 1080.0
|
||||
scale_y = height / 2400.0
|
||||
x1 = int(414 * scale_x)
|
||||
y1 = int(1110 * scale_y) + y_pianyi
|
||||
x2 = int(661 * scale_x)
|
||||
y2 = int(1176 * scale_y) + y_pianyi
|
||||
|
||||
# 边界检查
|
||||
x1 = max(0, min(x1, width))
|
||||
y1 = max(0, min(y1, height))
|
||||
x2 = max(0, min(x2, width))
|
||||
y2 = max(0, min(y2, height))
|
||||
|
||||
# 执行模板匹配
|
||||
is_in_fudai_detail = douyin_pixel.detect_fudai_detail_page(
|
||||
pic_rgb, resolution_ratio_x=rx, resolution_ratio_y=ry, y_pianyi=y_pianyi
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 尝试获取模板匹配分数(如果可能)
|
||||
try:
|
||||
import cv2
|
||||
import numpy as np
|
||||
base_dir = os.path.dirname(__file__)
|
||||
template_path = os.path.join(base_dir, "assets", "xiangqing.png")
|
||||
if os.path.exists(template_path) and x1 < x2 and y1 < y2:
|
||||
bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
|
||||
roi = bgr[y1:y2, x1:x2] # type: ignore[index]
|
||||
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
|
||||
if template is not None and roi.size > 0:
|
||||
roi_h, roi_w = roi.shape[:2] # type: ignore[attr-defined]
|
||||
tpl_h, tpl_w = template.shape[:2] # type: ignore[attr-defined]
|
||||
if roi_h >= tpl_h and roi_w >= tpl_w:
|
||||
res = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
|
||||
template_match_score = float(max_val)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 保存调试图片
|
||||
try:
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb,
|
||||
operation_type="template_match",
|
||||
picname="超级福袋标题",
|
||||
step="fudai_detail_verification",
|
||||
coords=(x1, y1, x2, y2) if x1 < x2 and y1 < y2 else None,
|
||||
extra_info={
|
||||
"detected": is_in_fudai_detail,
|
||||
"score": template_match_score,
|
||||
"region": f"({414},{1110})-({661},{1176})",
|
||||
"threshold": 0.7,
|
||||
}
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"超级福袋标题模板匹配",
|
||||
path=debug_path,
|
||||
detected=is_in_fudai_detail,
|
||||
score=template_match_score,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not is_in_fudai_detail:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:模板匹配未检测到'超级福袋'标题,不在福袋详情页",
|
||||
score=template_match_score,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
now = time.time()
|
||||
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
return "error", tup_err, {"reason": "not_in_fudai_detail", "template_match": False, "score": template_match_score}
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:模板匹配检测到'超级福袋'标题,确认在福袋详情页",
|
||||
score=template_match_score,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:模板匹配检测异常",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 模板匹配失败时,继续后续流程(兼容旧逻辑)
|
||||
|
||||
# 步骤2:检测弹窗(优惠券等)
|
||||
if _is_wrong_coupon_popup(analyser):
|
||||
@@ -594,26 +715,6 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
content, time_text, participants, copies, prize_value_yuan = get_fudai_contain(
|
||||
analyser, renwu=task_count
|
||||
)
|
||||
|
||||
# 检查是否在OCR阶段检测到"观看X分钟"任务
|
||||
is_watch_task = bool(getattr(analyser, "_is_watch_task_detected", False) or False)
|
||||
if is_watch_task:
|
||||
# 清除标志
|
||||
try:
|
||||
analyser._is_watch_task_detected = False
|
||||
except Exception:
|
||||
pass
|
||||
# 直接返回观看任务状态,跳过后续处理
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:检测到'观看X分钟'任务,直接跳过",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
now = time.time()
|
||||
tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
return "watch_task", tup_watch, {"reason": "watch_task_detected"}
|
||||
except Exception as e:
|
||||
# 出现异常时,记录错误并返回占位结果
|
||||
try:
|
||||
@@ -628,6 +729,32 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
return "error", tup_err, {}
|
||||
|
||||
# 检查是否检测到观看任务(通过 _is_watch_task_detected 标志)
|
||||
is_watch_task = False
|
||||
try:
|
||||
is_watch_task = bool(getattr(analyser, "_is_watch_task_detected", False))
|
||||
# 清除标志,避免影响后续调用
|
||||
if is_watch_task:
|
||||
try:
|
||||
analyser._is_watch_task_detected = False
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果检测到观看任务,返回 watch_task 状态
|
||||
if is_watch_task:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:检测到'观看X分钟'任务,直接跳过",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
now = time.time()
|
||||
tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
return "watch_task", tup_watch, {"reason": "watch_task_detected", "task_count": task_count}
|
||||
|
||||
# 解析倒计时 -> (剩余秒数, 未来时间戳)
|
||||
countdown_start = time.time()
|
||||
countdown_end = countdown_start + 60.0
|
||||
@@ -820,6 +947,38 @@ def read_fudai_detail_with_retries(
|
||||
# 如果成功读取,或者检测到优惠券弹窗(已处理完毕),或者检测到观看任务,都停止重试
|
||||
if status == "ok" or status == "coupon_popup" or status == "watch_task":
|
||||
break
|
||||
|
||||
# 如果任务数量为0,说明没有正确打开福袋详情页,尝试重新打开
|
||||
if status == "error" and isinstance(extra, dict) and extra.get("reason") == "task_count_zero":
|
||||
if attempt < max_attempts - 1:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:任务数量为0,尝试重新打开福袋详情页",
|
||||
attempt=attempt + 1,
|
||||
max_attempts=max_attempts,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 调用回调函数重新打开福袋详情页
|
||||
try:
|
||||
if ensure_open_callback:
|
||||
ensure_open_callback(analyser, fudai_x)
|
||||
# 重新打开后等待一段时间,确保页面加载完成
|
||||
try:
|
||||
analyser.operation.delay(retry_delay + 0.5)
|
||||
except Exception:
|
||||
time.sleep(retry_delay + 0.5)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:重新打开福袋详情页失败",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if attempt < max_attempts - 1:
|
||||
try:
|
||||
analyser.operation.delay(retry_delay)
|
||||
@@ -861,9 +1020,41 @@ def read_fudai_detail_with_retries(
|
||||
pass
|
||||
# 关闭详情页
|
||||
try:
|
||||
close_fudai_detail(analyser)
|
||||
close_detail_callback(analyser)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
# 切换直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if needswitch:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"检测到观看任务后切换直播间",
|
||||
)
|
||||
# 优先使用封装好的上滑切房方法
|
||||
if hasattr(analyser, "swipe_up_to_next_live"):
|
||||
analyser.swipe_up_to_next_live()
|
||||
else:
|
||||
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1700 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 700 * ry // 2400
|
||||
analyser.operation.swipe(
|
||||
analyser.device_id, start_x, start_y, end_x, end_y, 300
|
||||
)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -885,6 +1076,11 @@ def read_fudai_detail_with_retries(
|
||||
# 将状态信息存储在 analyser 中,供调用方检查
|
||||
try:
|
||||
analyser._last_fudai_detail_status = last_status # type: ignore[attr-defined]
|
||||
# 同时保存 extra 信息,用于检查错误原因
|
||||
if isinstance(extra, dict):
|
||||
analyser._last_fudai_detail_extra = extra # type: ignore[attr-defined]
|
||||
else:
|
||||
analyser._last_fudai_detail_extra = {} # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -250,11 +250,11 @@ class FudaiDetector:
|
||||
|
||||
# 福袋图标颜色范围(优化后的范围)
|
||||
mask = (
|
||||
(r >= 190)
|
||||
(r >= 190) # type: ignore[operator]
|
||||
& (r <= 206) # type: ignore[operator]
|
||||
& (g >= 173)
|
||||
& (g >= 173) # type: ignore[operator]
|
||||
& (g <= 196) # type: ignore[operator]
|
||||
& (b >= 234)
|
||||
& (b >= 234) # type: ignore[operator]
|
||||
& (b <= 250) # type: ignore[operator]
|
||||
)
|
||||
|
||||
@@ -292,7 +292,8 @@ class FudaiDetector:
|
||||
# 回退到逐像素检测(从右往左查找)
|
||||
try:
|
||||
pix = pic.load()
|
||||
for offset_y in range(-y_range // 2, y_range // 2 + 1):
|
||||
y_range_int = int(y_range) if y_range is not None else 7
|
||||
for offset_y in range(-y_range_int // 2, y_range_int // 2 + 1):
|
||||
check_y = scan_y + offset_y
|
||||
if not (0 <= check_y < height):
|
||||
continue
|
||||
|
||||
@@ -282,6 +282,217 @@ def ensure_debug_captures_dir() -> None:
|
||||
os.makedirs(debug_dir, exist_ok=True)
|
||||
|
||||
|
||||
def get_debug_captures_base_dir() -> str:
|
||||
"""获取调试图像存档根目录路径(不包含日期)"""
|
||||
pic_dir = path_config.get_pic_dir()
|
||||
return os.path.join(pic_dir, "debug_captures")
|
||||
|
||||
|
||||
def count_debug_captures_files() -> int:
|
||||
"""统计所有调试图像文件的总数量
|
||||
|
||||
返回:
|
||||
文件总数
|
||||
"""
|
||||
try:
|
||||
debug_base_dir = get_debug_captures_base_dir()
|
||||
if not os.path.exists(debug_base_dir):
|
||||
return 0
|
||||
|
||||
total_count = 0
|
||||
# 遍历所有日期目录
|
||||
for item in os.listdir(debug_base_dir):
|
||||
# 跳过隐藏文件和标记文件
|
||||
if item.startswith('.'):
|
||||
continue
|
||||
|
||||
item_path = os.path.join(debug_base_dir, item)
|
||||
if not os.path.isdir(item_path):
|
||||
continue
|
||||
|
||||
# 统计该目录下的所有PNG文件
|
||||
try:
|
||||
for root, dirs, files in os.walk(item_path):
|
||||
for f in files:
|
||||
if f.lower().endswith('.png'):
|
||||
total_count += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return total_count
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int:
|
||||
"""清理旧的调试图像存档目录
|
||||
|
||||
参数:
|
||||
keep_days: 保留天数,默认7天,超过此天数的目录将被删除
|
||||
max_files: 最大文件数量,默认2000,超过此数量时删除最旧的目录
|
||||
|
||||
返回:
|
||||
清理的目录数量
|
||||
"""
|
||||
try:
|
||||
debug_base_dir = get_debug_captures_base_dir()
|
||||
if not os.path.exists(debug_base_dir):
|
||||
return 0
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# 计算截止日期
|
||||
cutoff_date = datetime.now() - timedelta(days=keep_days)
|
||||
|
||||
deleted_count = 0
|
||||
deleted_dirs = []
|
||||
total_size_freed = 0
|
||||
|
||||
# 收集所有日期目录及其信息
|
||||
dirs_info = []
|
||||
for item in os.listdir(debug_base_dir):
|
||||
# 跳过隐藏文件和标记文件
|
||||
if item.startswith('.'):
|
||||
continue
|
||||
|
||||
item_path = os.path.join(debug_base_dir, item)
|
||||
if not os.path.isdir(item_path):
|
||||
continue
|
||||
|
||||
# 尝试解析目录名为日期(格式:YYYY-MM-DD)
|
||||
try:
|
||||
dir_date = datetime.strptime(item, "%Y-%m-%d")
|
||||
|
||||
# 统计该目录下的文件数量和大小
|
||||
file_count = 0
|
||||
dir_size = 0
|
||||
try:
|
||||
for root, dirs, files in os.walk(item_path):
|
||||
for f in files:
|
||||
if f.lower().endswith('.png'):
|
||||
file_count += 1
|
||||
file_path = os.path.join(root, f)
|
||||
try:
|
||||
dir_size += os.path.getsize(file_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
dirs_info.append({
|
||||
'name': item,
|
||||
'path': item_path,
|
||||
'date': dir_date,
|
||||
'file_count': file_count,
|
||||
'size': dir_size
|
||||
})
|
||||
except ValueError:
|
||||
# 如果目录名不是日期格式,跳过
|
||||
continue
|
||||
|
||||
# 按日期排序(最旧的在前)
|
||||
dirs_info.sort(key=lambda x: x['date'])
|
||||
|
||||
# 先按天数清理:删除超过保留天数的目录
|
||||
for dir_info in dirs_info[:]:
|
||||
if dir_info['date'] < cutoff_date:
|
||||
try:
|
||||
shutil.rmtree(dir_info['path'])
|
||||
deleted_count += 1
|
||||
deleted_dirs.append(dir_info['name'])
|
||||
total_size_freed += dir_info['size']
|
||||
dirs_info.remove(dir_info)
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 再按文件数量清理:如果文件总数超过max_files,删除最旧的目录
|
||||
total_files = sum(d['file_count'] for d in dirs_info)
|
||||
if total_files > max_files:
|
||||
# 计算需要删除的文件数量
|
||||
need_delete_count = total_files - max_files
|
||||
|
||||
# 从最旧的目录开始删除,直到文件数量降到max_files以下
|
||||
deleted_files_count = 0
|
||||
for dir_info in dirs_info[:]:
|
||||
if deleted_files_count >= need_delete_count:
|
||||
break
|
||||
|
||||
try:
|
||||
shutil.rmtree(dir_info['path'])
|
||||
deleted_count += 1
|
||||
deleted_dirs.append(dir_info['name'])
|
||||
total_size_freed += dir_info['size']
|
||||
deleted_files_count += dir_info['file_count']
|
||||
dirs_info.remove(dir_info)
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if deleted_count > 0:
|
||||
try:
|
||||
size_mb = total_size_freed / (1024 * 1024)
|
||||
reason_parts = []
|
||||
if total_files > max_files:
|
||||
reason_parts.append(f"文件数量超过{max_files}")
|
||||
if any(d['date'] < cutoff_date for d in dirs_info if d not in [{'name': name} for name in deleted_dirs]):
|
||||
reason_parts.append(f"超过{keep_days}天")
|
||||
reason = ",".join(reason_parts) if reason_parts else "自动清理"
|
||||
|
||||
print(
|
||||
f"[调试图像清理] 已删除 {deleted_count} 个调试图像目录: {', '.join(deleted_dirs)}"
|
||||
)
|
||||
print(f"[调试图像清理] 清理原因: {reason}")
|
||||
if size_mb > 0.1: # 只显示大于0.1MB的清理
|
||||
print(f"[调试图像清理] 释放空间: {size_mb:.2f} MB")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return deleted_count
|
||||
except Exception as e:
|
||||
# 清理失败不应影响程序运行
|
||||
try:
|
||||
print(f"[调试图像清理] 清理旧调试图像时出错: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
def init_debug_captures_cleanup() -> None:
|
||||
"""初始化调试图像清理(在程序启动时调用)
|
||||
|
||||
从 config.json 读取配置并执行清理
|
||||
"""
|
||||
try:
|
||||
import json
|
||||
config_path = path_config.get_config_path()
|
||||
if not os.path.exists(config_path):
|
||||
return
|
||||
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
|
||||
# 检查是否启用自动清理
|
||||
auto_cleanup = True
|
||||
keep_days = 7
|
||||
max_files = 2000
|
||||
|
||||
if 'debug_captures' in config and isinstance(config['debug_captures'], dict):
|
||||
auto_cleanup = config['debug_captures'].get('auto_cleanup', True)
|
||||
keep_days = int(config['debug_captures'].get('keep_days', 7))
|
||||
max_files = int(config['debug_captures'].get('max_files', 2000))
|
||||
|
||||
if auto_cleanup:
|
||||
cleanup_debug_captures(keep_days=keep_days, max_files=max_files)
|
||||
except Exception:
|
||||
# 初始化失败不影响程序运行
|
||||
pass
|
||||
|
||||
|
||||
def _sanitize_filename_part(text: str) -> str:
|
||||
"""清理文件名部分,移除Windows不允许的字符
|
||||
|
||||
@@ -330,6 +541,7 @@ def save_debug_image(
|
||||
extra_info: Optional[dict] = None,
|
||||
session_id: Optional[str] = None,
|
||||
annotate: bool = True,
|
||||
auto_cleanup: bool = True,
|
||||
) -> Optional[str]:
|
||||
"""保存调试图像到存档目录
|
||||
|
||||
@@ -342,11 +554,88 @@ def save_debug_image(
|
||||
extra_info: 额外信息字典(可选)
|
||||
session_id: 会话ID(可选,默认使用当前日期)
|
||||
annotate: 是否在图像上添加标注信息(默认True)
|
||||
auto_cleanup: 是否自动清理旧目录(默认True)
|
||||
|
||||
返回:
|
||||
保存的文件路径,失败返回None
|
||||
"""
|
||||
try:
|
||||
# 自动清理旧目录(仅在每天第一次保存时执行)
|
||||
if auto_cleanup:
|
||||
try:
|
||||
# 检查今天是否已经清理过(使用简单的标记文件)
|
||||
debug_base_dir = get_debug_captures_base_dir()
|
||||
cleanup_marker = os.path.join(debug_base_dir, ".cleanup_marker")
|
||||
from datetime import datetime
|
||||
today_str = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# 读取标记文件,检查今天是否已清理
|
||||
need_cleanup = True
|
||||
if os.path.exists(cleanup_marker):
|
||||
try:
|
||||
with open(cleanup_marker, 'r', encoding='utf-8') as f:
|
||||
last_cleanup_date = f.read().strip()
|
||||
if last_cleanup_date == today_str:
|
||||
need_cleanup = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if need_cleanup:
|
||||
# 从配置读取保留天数、最大文件数和自动清理设置
|
||||
keep_days = 7 # 默认7天
|
||||
max_files = 2000 # 默认2000个文件
|
||||
cleanup_enabled = True
|
||||
try:
|
||||
import json
|
||||
config_path = path_config.get_config_path()
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
if 'debug_captures' in config and isinstance(config['debug_captures'], dict):
|
||||
cleanup_enabled = config['debug_captures'].get('auto_cleanup', True)
|
||||
keep_days = int(config['debug_captures'].get('keep_days', 7))
|
||||
max_files = int(config['debug_captures'].get('max_files', 2000))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果启用自动清理,执行清理
|
||||
if cleanup_enabled:
|
||||
cleanup_debug_captures(keep_days=keep_days, max_files=max_files)
|
||||
else:
|
||||
# 即使今天已经清理过,也要检查文件数量是否超过限制
|
||||
# 如果超过,立即清理(不更新标记文件,避免频繁清理)
|
||||
try:
|
||||
import json
|
||||
config_path = path_config.get_config_path()
|
||||
max_files = 2000
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
if 'debug_captures' in config and isinstance(config['debug_captures'], dict):
|
||||
max_files = int(config['debug_captures'].get('max_files', 2000))
|
||||
|
||||
# 检查当前文件数量
|
||||
current_count = count_debug_captures_files()
|
||||
if current_count > max_files:
|
||||
# 文件数量超过限制,立即清理
|
||||
try:
|
||||
print(f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理")
|
||||
except Exception:
|
||||
pass
|
||||
cleanup_debug_captures(keep_days=999, max_files=max_files) # keep_days设为999表示只按文件数量清理
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 更新标记文件
|
||||
try:
|
||||
with open(cleanup_marker, 'w', encoding='utf-8') as f:
|
||||
f.write(today_str)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 清理失败不影响保存操作
|
||||
pass
|
||||
|
||||
ensure_debug_captures_dir()
|
||||
debug_dir = get_debug_captures_dir()
|
||||
|
||||
|
||||
+61
-31
@@ -3,12 +3,14 @@ from __future__ import annotations
|
||||
import douyin_pixel
|
||||
|
||||
|
||||
def diagnose_stage_from_current_screen(self):
|
||||
def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C901
|
||||
"""完整抽離自 `douyin_fudai.fudai_analyse._diagnose_stage_from_current_screen`。
|
||||
|
||||
日志輸出已從 print 改為 _log_kv,方便結構化查看。
|
||||
|
||||
当前模式:优先使用像素检测,OCR检测已暂时关闭用于测试像素检测精准度。
|
||||
|
||||
注意:此函数复杂度较高,包含多个检测步骤和条件分支,这是设计上的权衡。
|
||||
"""
|
||||
import time
|
||||
|
||||
@@ -468,22 +470,36 @@ def diagnose_stage_from_current_screen(self):
|
||||
|
||||
if time.time() - step_coupon_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤2[检测优惠券弹窗]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
|
||||
if enable_ocr_mode1 and (time.time() - step_coupon_start < max_step_time) and (not coupon_text or "开心收下" not in coupon_text):
|
||||
ocr_start_1 = time.time()
|
||||
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 1) or "")
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
# 如果启用模式1,并行执行两个OCR模式
|
||||
if enable_ocr_mode1:
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_mode0 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 0)
|
||||
future_mode1 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 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(
|
||||
"步骤2[检测优惠券弹窗]-OCR模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
"步骤2[检测优惠券弹窗]-OCR并行模式0+1",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
else:
|
||||
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
_log(
|
||||
"步骤2[检测优惠券弹窗]-OCR模式0",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
@@ -829,22 +845,36 @@ def diagnose_stage_from_current_screen(self):
|
||||
|
||||
if time.time() - step_ocr_verify_start < max_step_time:
|
||||
ocr_start = time.time()
|
||||
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 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 enable_ocr_mode1 and (time.time() - step_ocr_verify_start < max_step_time) and (not coupon_text or "开心收下" not in coupon_text):
|
||||
ocr_start_1 = time.time()
|
||||
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 1) or "")
|
||||
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
|
||||
# 如果启用模式1,并行执行两个OCR模式
|
||||
if enable_ocr_mode1:
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_mode0 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 0)
|
||||
future_mode1 = executor.submit(self.operation.analyse_pic_word, "参与按钮", 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模式1",
|
||||
耗时毫秒=ocr_elapsed_1,
|
||||
"步骤3[OCR确认弹窗]-优惠券OCR并行模式0+1",
|
||||
耗时毫秒=ocr_elapsed,
|
||||
文本长度=len(coupon_text),
|
||||
文本预览=coupon_text[:50] if coupon_text else "",
|
||||
)
|
||||
else:
|
||||
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 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 "",
|
||||
)
|
||||
|
||||
+275
-352
@@ -47,7 +47,7 @@ def main():
|
||||
root = tk.Tk()
|
||||
|
||||
root.title("抖音福袋挂机 - 可视化控制台")
|
||||
root.geometry("1180x760")
|
||||
root.geometry("1400x900") # 增大窗口尺寸,提供更多空间
|
||||
|
||||
q: queue.Queue[str] = queue.Queue()
|
||||
|
||||
@@ -93,35 +93,18 @@ def main():
|
||||
side=LEFT, padx=(0, 12)
|
||||
)
|
||||
|
||||
# 中部:左侧配置 + 右侧日志/预览(支持拖拽调整宽度;左侧可滚动)
|
||||
# 中部:左侧配置(使用Notebook标签页)+ 右侧日志/预览(支持拖拽调整宽度)
|
||||
mid = ttk.PanedWindow(root, orient="horizontal")
|
||||
mid.pack(fill=BOTH, expand=True, padx=12, pady=(0, 12))
|
||||
|
||||
left_wrap = ttk.Frame(mid)
|
||||
right = ttk.Frame(mid)
|
||||
mid.add(left_wrap, weight=0)
|
||||
mid.add(left_wrap, weight=0, minsize=450) # 设置最小宽度
|
||||
mid.add(right, weight=1)
|
||||
|
||||
left_canvas = tk.Canvas(left_wrap, highlightthickness=0, borderwidth=0)
|
||||
left_scroll = ttk.Scrollbar(left_wrap, orient="vertical", command=left_canvas.yview)
|
||||
left_canvas.configure(yscrollcommand=left_scroll.set)
|
||||
left_scroll.pack(side=RIGHT, fill=Y)
|
||||
left_canvas.pack(side=LEFT, fill=BOTH, expand=True)
|
||||
|
||||
left = ttk.Frame(left_canvas)
|
||||
_left_win = left_canvas.create_window((0, 0), window=left, anchor="nw")
|
||||
|
||||
def _left_on_configure(_evt=None):
|
||||
left_canvas.configure(scrollregion=left_canvas.bbox("all"))
|
||||
|
||||
def _left_on_canvas_configure(evt):
|
||||
try:
|
||||
left_canvas.itemconfigure(_left_win, width=evt.width)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
left.bind("<Configure>", _left_on_configure)
|
||||
left_canvas.bind("<Configure>", _left_on_canvas_configure)
|
||||
# 左侧使用Notebook标签页组织配置
|
||||
left_notebook = ttk.Notebook(left_wrap)
|
||||
left_notebook.pack(fill=BOTH, expand=True)
|
||||
needswitch_var = tk.BooleanVar(value=bool(cfg.get("needswitch", True)))
|
||||
infinite_loop_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("infinite_loop_enabled", False))
|
||||
@@ -295,7 +278,10 @@ def main():
|
||||
value=float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)
|
||||
)
|
||||
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)
|
||||
)
|
||||
@@ -303,9 +289,30 @@ def main():
|
||||
lucky_draw_red_ratio_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)
|
||||
)
|
||||
|
||||
# 调试图像清理相关变量
|
||||
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)
|
||||
)
|
||||
|
||||
# 倒计时小于阈值参数
|
||||
skip_lt_seconds_var = tk.IntVar(
|
||||
value=int(cfg.get("skip_if_countdown_lt_seconds", 5) or 5)
|
||||
)
|
||||
|
||||
run_box = ttk.LabelFrame(left, text="运行设置")
|
||||
run_box.pack(fill=X, pady=(0, 10))
|
||||
# 创建左侧配置标签页
|
||||
# 标签页1:运行设置
|
||||
run_tab = ttk.Frame(left_notebook)
|
||||
left_notebook.add(run_tab, text="运行设置")
|
||||
|
||||
run_box = ttk.LabelFrame(run_tab, text="基本运行参数")
|
||||
run_box.pack(fill=X, padx=10, pady=(10, 10))
|
||||
|
||||
r0 = ttk.Frame(run_box)
|
||||
r0.pack(fill=X, padx=10, pady=(10, 6))
|
||||
@@ -344,273 +351,15 @@ def main():
|
||||
ttk.Spinbox(
|
||||
r2, from_=1, to=9999, textvariable=reset_after_swipes_var, width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(r2, text="(触发后会下滑回退)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 说明:推荐页养号流程始终启用;具体养号动作请在下方“推荐页养号(爱心/收藏/评论)”配置。
|
||||
|
||||
yg_box = ttk.LabelFrame(left, text="推荐页养号(爱心/收藏/评论)")
|
||||
yg_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
yg_switch = ttk.Frame(yg_box)
|
||||
yg_switch.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Checkbutton(
|
||||
yg_switch, text="养号总开关(关闭则跳过推荐页养号)", variable=yg_enabled_var
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
yg_switch,
|
||||
text="启用养号动作(爱心/收藏/评论)",
|
||||
variable=yg_actions_enabled_var,
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
|
||||
yg0 = ttk.Frame(yg_box)
|
||||
yg0.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Checkbutton(
|
||||
yg0,
|
||||
text="逐步截图(调试用,生成 pic/*/latest.png)",
|
||||
variable=yg_step_screenshot_var,
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg_time = ttk.Frame(yg_box)
|
||||
yg_time.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg_time, text="养号时长(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_time,
|
||||
from_=1,
|
||||
to=3600,
|
||||
increment=5,
|
||||
textvariable=yg_recommend_duration_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_time, text="养号间隔(秒):").pack(side=LEFT, padx=(12, 0))
|
||||
ttk.Spinbox(
|
||||
yg_time,
|
||||
from_=0,
|
||||
to=3600,
|
||||
increment=10,
|
||||
textvariable=yg_recommend_interval_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_time, text="(0=每次触发都执行)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
yg1 = ttk.Frame(yg_box)
|
||||
yg1.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg1, text="爱心概率:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_like_prob_var, width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1, text="收藏概率:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_fav_prob_var, width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1, text="评论概率:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg1,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.05,
|
||||
textvariable=yg_comment_prob_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1, text="(0~1)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
yg2 = ttk.Frame(yg_box)
|
||||
yg2.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg2, text="图标ROI大小(px):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg2, from_=80, to=600, increment=10, textvariable=yg_icon_roi_size_var, width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg2, text="匹配阈值:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg2,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=yg_icon_match_threshold_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg3 = ttk.Frame(yg_box)
|
||||
yg3.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg3, text="爱心ROI偏移(x,y):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg3,
|
||||
from_=-300,
|
||||
to=300,
|
||||
increment=5,
|
||||
textvariable=yg_like_roi_offset_x_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg3, text=",").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg3,
|
||||
from_=-300,
|
||||
to=300,
|
||||
increment=5,
|
||||
textvariable=yg_like_roi_offset_y_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg3, text=" 收藏ROI偏移(x,y):").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg3,
|
||||
from_=-300,
|
||||
to=300,
|
||||
increment=5,
|
||||
textvariable=yg_fav_roi_offset_x_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg3, text=",").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg3,
|
||||
from_=-300,
|
||||
to=300,
|
||||
increment=5,
|
||||
textvariable=yg_fav_roi_offset_y_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg_icons = ttk.Frame(yg_box)
|
||||
yg_icons.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg_icons, text="爱心图标坐标(x,y):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_icons, from_=-1, to=4000, textvariable=yg_like_icon_x_var, width=8
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_icons, text=",").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_icons, from_=-1, to=4000, textvariable=yg_like_icon_y_var, width=8
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_icons, text=" 收藏图标坐标(x,y):").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg_icons, from_=-1, to=4000, textvariable=yg_fav_icon_x_var, width=8
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_icons, text=",").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_icons, from_=-1, to=4000, textvariable=yg_fav_icon_y_var, width=8
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg_tpl = ttk.Frame(yg_box)
|
||||
yg_tpl.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg_tpl, text="爱心模板路径:").pack(side=LEFT)
|
||||
ttk.Entry(yg_tpl, textvariable=yg_like_template_path_var, width=18).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
ttk.Label(yg_tpl, text="收藏模板路径:").pack(side=LEFT)
|
||||
ttk.Entry(yg_tpl, textvariable=yg_fav_template_path_var, width=18).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
yg_comment_coords1 = ttk.Frame(yg_box)
|
||||
yg_comment_coords1.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg_comment_coords1, text="评论按钮坐标(x,y):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_comment_coords1,
|
||||
from_=-1,
|
||||
to=4000,
|
||||
textvariable=yg_comment_btn_x_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_comment_coords1, text=",").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_comment_coords1,
|
||||
from_=-1,
|
||||
to=4000,
|
||||
textvariable=yg_comment_btn_y_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_comment_coords1, text=" 评论输入框坐标(x,y):").pack(
|
||||
side=LEFT, padx=(10, 0)
|
||||
)
|
||||
ttk.Spinbox(
|
||||
yg_comment_coords1,
|
||||
from_=-1,
|
||||
to=4000,
|
||||
textvariable=yg_comment_input_x_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_comment_coords1, text=",").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_comment_coords1,
|
||||
from_=-1,
|
||||
to=4000,
|
||||
textvariable=yg_comment_input_y_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg_comment_coords2 = ttk.Frame(yg_box)
|
||||
yg_comment_coords2.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg_comment_coords2, text="评论发送坐标(x,y):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_comment_coords2,
|
||||
from_=-1,
|
||||
to=4000,
|
||||
textvariable=yg_comment_send_x_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_comment_coords2, text=",").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_comment_coords2,
|
||||
from_=-1,
|
||||
to=4000,
|
||||
textvariable=yg_comment_send_y_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_comment_coords2, text=" 评论关闭坐标(x,y):").pack(
|
||||
side=LEFT, padx=(10, 0)
|
||||
)
|
||||
ttk.Spinbox(
|
||||
yg_comment_coords2,
|
||||
from_=-1,
|
||||
to=4000,
|
||||
textvariable=yg_comment_close_x_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_comment_coords2, text=",").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_comment_coords2,
|
||||
from_=-1,
|
||||
to=4000,
|
||||
textvariable=yg_comment_close_y_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg_swipe = ttk.Frame(yg_box)
|
||||
yg_swipe.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg_swipe, text="停留后滑动方向:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
yg_swipe,
|
||||
textvariable=yg_after_dwell_direction_var,
|
||||
values=["up", "down"],
|
||||
width=8,
|
||||
state="readonly",
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_swipe, text="滑动距离(px):").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg_swipe,
|
||||
from_=100,
|
||||
to=2000,
|
||||
increment=10,
|
||||
textvariable=yg_after_dwell_distance_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg_texts = ttk.Frame(yg_box)
|
||||
yg_texts.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
|
||||
ttk.Label(yg_texts, text="评论文案库(每行一条):").pack(anchor="w")
|
||||
yg_comment_texts = ScrolledText(yg_texts, height=4)
|
||||
yg_comment_texts.pack(fill=X, pady=(0, 6))
|
||||
yg_kw = ttk.Frame(yg_texts)
|
||||
yg_kw.pack(fill=BOTH, expand=True)
|
||||
ttk.Label(yg_kw, text="爱心关键词(每行一条):").pack(anchor="w")
|
||||
yg_like_keywords_text = ScrolledText(yg_kw, height=3)
|
||||
yg_like_keywords_text.pack(fill=X, pady=(0, 6))
|
||||
ttk.Label(yg_kw, text="收藏关键词(每行一条):").pack(anchor="w")
|
||||
yg_fav_keywords_text = ScrolledText(yg_kw, height=3)
|
||||
yg_fav_keywords_text.pack(fill=X)
|
||||
|
||||
# 删除自动养号后,无需联动控件
|
||||
|
||||
cfg_box = ttk.LabelFrame(left, text="筛选设置")
|
||||
cfg_box.pack(fill=X, pady=(0, 10))
|
||||
ttk.Label(r2, text="(触发后会向上回退)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 标签页2:筛选设置
|
||||
filter_tab = ttk.Frame(left_notebook)
|
||||
left_notebook.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)
|
||||
@@ -642,71 +391,36 @@ def main():
|
||||
|
||||
row2 = ttk.Frame(cfg_box)
|
||||
row2.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Checkbutton(
|
||||
row2, text="自动加入粉丝团(谨慎:可能消耗钻石)", variable=auto_join_var
|
||||
ttk.Label(row2, text="倒计时小于(秒)时不参与:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row2, from_=0, to=300, increment=1, textvariable=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.Label(row3, text="粉丝团失败策略:").pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
row3, text="自动加入粉丝团(谨慎:可能消耗钻石)", variable=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(
|
||||
row3,
|
||||
row4,
|
||||
textvariable=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))
|
||||
|
||||
row4 = ttk.Frame(cfg_box)
|
||||
row4.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row4, text="找福袋最大尝试次数:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4, from_=0, to=20, textvariable=fudai_find_max_attempts_var, width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4, text="(0=使用默认值)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
row4b = ttk.Frame(cfg_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=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=15.0,
|
||||
increment=0.5,
|
||||
textvariable=fudai_icon_max_wait_seconds_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4b, text="(实际识别常见 4-6 秒,可按需调整)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
row4c = ttk.Frame(cfg_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=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)
|
||||
)
|
||||
|
||||
# 高价值房间和预约配置
|
||||
reservation_box = ttk.LabelFrame(left, text="高价值福袋预约参与")
|
||||
reservation_box.pack(fill=X, pady=(0, 10))
|
||||
# 标签页3:高价值预约
|
||||
reservation_tab_left = ttk.Frame(left_notebook)
|
||||
left_notebook.add(reservation_tab_left, text="高价值预约")
|
||||
|
||||
reservation_box = ttk.LabelFrame(reservation_tab_left, text="高价值福袋预约参与")
|
||||
reservation_box.pack(fill=X, padx=10, pady=(10, 10))
|
||||
|
||||
# 预约启用开关
|
||||
res_r0 = ttk.Frame(reservation_box)
|
||||
@@ -812,8 +526,107 @@ def main():
|
||||
width=10,
|
||||
).pack(side=LEFT)
|
||||
|
||||
quiet_box = ttk.LabelFrame(left, text="定时禁抢(仅养号)")
|
||||
quiet_box.pack(fill=X, pady=(0, 10))
|
||||
# 标签页4:养号设置
|
||||
yanghao_tab = ttk.Frame(left_notebook)
|
||||
left_notebook.add(yanghao_tab, text="养号设置")
|
||||
|
||||
yg_box = ttk.LabelFrame(yanghao_tab, text="推荐页养号(爱心/收藏/评论)")
|
||||
yg_box.pack(fill=X, padx=10, pady=(10, 10))
|
||||
|
||||
yg_switch = ttk.Frame(yg_box)
|
||||
yg_switch.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Checkbutton(
|
||||
yg_switch, text="养号总开关(关闭则跳过推荐页养号)", variable=yg_enabled_var
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
yg_switch,
|
||||
text="启用养号动作(爱心/收藏/评论)",
|
||||
variable=yg_actions_enabled_var,
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
|
||||
yg0 = ttk.Frame(yg_box)
|
||||
yg0.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Checkbutton(
|
||||
yg0,
|
||||
text="逐步截图(调试用,生成 pic/*/latest.png)",
|
||||
variable=yg_step_screenshot_var,
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg_time = ttk.Frame(yg_box)
|
||||
yg_time.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg_time, text="养号时长(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_time,
|
||||
from_=1,
|
||||
to=3600,
|
||||
increment=5,
|
||||
textvariable=yg_recommend_duration_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_time, text="养号间隔(秒):").pack(side=LEFT, padx=(12, 0))
|
||||
ttk.Spinbox(
|
||||
yg_time,
|
||||
from_=0,
|
||||
to=3600,
|
||||
increment=10,
|
||||
textvariable=yg_recommend_interval_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_time, text="(0=每次触发都执行)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
yg1 = ttk.Frame(yg_box)
|
||||
yg1.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg1, text="爱心概率:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_like_prob_var, width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1, text="收藏概率:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_fav_prob_var, width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1, text="评论概率:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg1,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.05,
|
||||
textvariable=yg_comment_prob_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1, text="(0~1)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
yg2 = ttk.Frame(yg_box)
|
||||
yg2.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg2, text="图标ROI大小(px):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg2, from_=80, to=600, increment=10, textvariable=yg_icon_roi_size_var, width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg2, text="匹配阈值:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg2,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=yg_icon_match_threshold_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg_texts = ttk.Frame(yg_box)
|
||||
yg_texts.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
|
||||
ttk.Label(yg_texts, text="评论文案库(每行一条):").pack(anchor="w")
|
||||
yg_comment_texts = ScrolledText(yg_texts, height=4)
|
||||
yg_comment_texts.pack(fill=X, pady=(0, 6))
|
||||
yg_kw = ttk.Frame(yg_texts)
|
||||
yg_kw.pack(fill=BOTH, expand=True)
|
||||
ttk.Label(yg_kw, text="爱心关键词(每行一条):").pack(anchor="w")
|
||||
yg_like_keywords_text = ScrolledText(yg_kw, height=3)
|
||||
yg_like_keywords_text.pack(fill=X, pady=(0, 6))
|
||||
ttk.Label(yg_kw, text="收藏关键词(每行一条):").pack(anchor="w")
|
||||
yg_fav_keywords_text = ScrolledText(yg_kw, height=3)
|
||||
yg_fav_keywords_text.pack(fill=X)
|
||||
|
||||
quiet_box = ttk.LabelFrame(yanghao_tab, text="定时禁抢(仅养号)")
|
||||
quiet_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
quiet_r0 = ttk.Frame(quiet_box)
|
||||
quiet_r0.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Checkbutton(
|
||||
@@ -830,9 +643,86 @@ def main():
|
||||
quiet_r1, from_=0, to=23, textvariable=fudai_quiet_end_hour_var, width=6
|
||||
).pack(side=LEFT)
|
||||
|
||||
# 标签页5:调试参数
|
||||
debug_tab = ttk.Frame(left_notebook)
|
||||
left_notebook.add(debug_tab, text="调试参数")
|
||||
|
||||
# 调试图像清理
|
||||
debug_captures_box = ttk.LabelFrame(debug_tab, 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="启用自动清理调试图像", variable=debug_captures_auto_cleanup_var
|
||||
).pack(side=LEFT)
|
||||
|
||||
debug_r1 = ttk.Frame(debug_captures_box)
|
||||
debug_r1.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(debug_r1, text="保留天数:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
debug_r1, from_=1, to=30, increment=1, textvariable=debug_captures_keep_days_var, width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(debug_r1, text="最大文件数量:").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Spinbox(
|
||||
debug_r1, from_=100, to=10000, increment=100, textvariable=debug_captures_max_files_var, width=8
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(debug_r1, text="(超过此数量自动清理)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 找福袋参数
|
||||
fudai_find_box = ttk.LabelFrame(debug_tab, 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=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=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=fudai_icon_max_wait_seconds_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4b, text="(实际识别常见 4-6 秒)").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=live_room_match_threshold_var,
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4c, text="(0.0~1.0,默认0.7,值越高越严格)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 阶段诊断时间参数(用于调试)
|
||||
diag_time_box = ttk.LabelFrame(left, text="阶段诊断时间参数(调试用)")
|
||||
diag_time_box.pack(fill=X, pady=(0, 10))
|
||||
diag_time_box = ttk.LabelFrame(debug_tab, 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)
|
||||
@@ -861,6 +751,11 @@ def main():
|
||||
ttk.Checkbutton(
|
||||
diag_time_r2, text="启用OCR模式1(二值化)", variable=enable_ocr_mode1_var
|
||||
).pack(side=LEFT)
|
||||
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=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)
|
||||
@@ -889,8 +784,12 @@ def main():
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
kw_box = ttk.LabelFrame(left, text="关键词(每行一个,仅黑名单)")
|
||||
kw_box.pack(fill=BOTH, expand=True)
|
||||
# 标签页6:关键词
|
||||
keywords_tab = ttk.Frame(left_notebook)
|
||||
left_notebook.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_not_want(黑名单)").pack(
|
||||
anchor="w", padx=10, pady=(10, 4)
|
||||
@@ -985,9 +884,24 @@ def main():
|
||||
float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)
|
||||
)
|
||||
enable_ocr_mode1_var.set(bool(cfg.get("enable_ocr_mode1", False)))
|
||||
fudai_template_match_enabled_var.set(
|
||||
bool(cfg.get("fudai_template_match_enabled", False))
|
||||
)
|
||||
fudai_template_match_threshold_var.set(
|
||||
float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)
|
||||
)
|
||||
skip_lt_seconds_var.set(int(cfg.get("skip_if_countdown_lt_seconds", 5) or 5))
|
||||
|
||||
# 调试图像清理配置
|
||||
debug_captures_config = cfg.get("debug_captures", {})
|
||||
if isinstance(debug_captures_config, dict):
|
||||
debug_captures_auto_cleanup_var.set(bool(debug_captures_config.get("auto_cleanup", True)))
|
||||
debug_captures_keep_days_var.set(int(debug_captures_config.get("keep_days", 7) or 7))
|
||||
debug_captures_max_files_var.set(int(debug_captures_config.get("max_files", 2000) or 2000))
|
||||
else:
|
||||
debug_captures_auto_cleanup_var.set(True)
|
||||
debug_captures_keep_days_var.set(7)
|
||||
debug_captures_max_files_var.set(2000)
|
||||
|
||||
yg_like_prob_var.set(float(cfg.get("yanghao_like_prob", 0.0) or 0.0))
|
||||
yg_fav_prob_var.set(float(cfg.get("yanghao_fav_prob", 0.0) or 0.0))
|
||||
@@ -1135,9 +1049,18 @@ def main():
|
||||
stage_diag_max_step_time_var.get() or 2.0
|
||||
)
|
||||
cfg2["enable_ocr_mode1"] = bool(enable_ocr_mode1_var.get())
|
||||
cfg2["fudai_template_match_enabled"] = bool(fudai_template_match_enabled_var.get())
|
||||
cfg2["fudai_template_match_threshold"] = float(
|
||||
fudai_template_match_threshold_var.get() or 0.7
|
||||
)
|
||||
cfg2["skip_if_countdown_lt_seconds"] = int(skip_lt_seconds_var.get() or 5)
|
||||
|
||||
# 调试图像清理配置
|
||||
if "debug_captures" not in cfg2 or not isinstance(cfg2["debug_captures"], dict):
|
||||
cfg2["debug_captures"] = {}
|
||||
cfg2["debug_captures"]["auto_cleanup"] = bool(debug_captures_auto_cleanup_var.get())
|
||||
cfg2["debug_captures"]["keep_days"] = int(debug_captures_keep_days_var.get() or 7)
|
||||
cfg2["debug_captures"]["max_files"] = int(debug_captures_max_files_var.get() or 2000)
|
||||
|
||||
cfg2["yanghao_enabled"] = bool(yg_enabled_var.get())
|
||||
cfg2["yanghao_enable_actions"] = bool(yg_actions_enabled_var.get())
|
||||
|
||||
@@ -21,7 +21,7 @@ def main():
|
||||
missing = []
|
||||
|
||||
try:
|
||||
import paddlepaddle
|
||||
import paddlepaddle # type: ignore[import-untyped]
|
||||
except ImportError:
|
||||
missing.append("paddlepaddle>=2.5.0,<3.0.0")
|
||||
|
||||
@@ -77,3 +77,7 @@ if __name__ == "__main__":
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -35,3 +35,8 @@ paddlepaddle>=2.5.0,<3.0.0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -51,3 +51,8 @@ ttkbootstrap>=1.10.0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+2
-2
@@ -239,11 +239,11 @@ def main(argv: list[str]) -> int:
|
||||
|
||||
# 让命令行输出更稳定(实时刷新 + UTF-8)
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
|
||||
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True) # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
sys.stderr.reconfigure(encoding="utf-8", line_buffering=True)
|
||||
sys.stderr.reconfigure(encoding="utf-8", line_buffering=True) # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
+13
-13
@@ -1,19 +1,19 @@
|
||||
{
|
||||
"updated_ts": 1766334665.3353467,
|
||||
"reason": "process_reservation",
|
||||
"room_pos": 0,
|
||||
"current_room_title": "云舍花卉",
|
||||
"current_room_title_raw": "云舍花卉",
|
||||
"updated_ts": 1766338568.2483091,
|
||||
"reason": "record_reservation",
|
||||
"room_pos": 3,
|
||||
"current_room_title": "云南名茶",
|
||||
"current_room_title_raw": "云南名茶。",
|
||||
"reservations": [
|
||||
{
|
||||
"prize_value_yuan": 2499.0,
|
||||
"content": "(粉丝专属1Matepadse2024款平板电脑颜色随。",
|
||||
"future_ts": 1766334718.604828,
|
||||
"future_str": "2025-12-22 00:31:58",
|
||||
"pos_seen": 0,
|
||||
"room_title": "紫蠡贴大",
|
||||
"room_title_raw": "紫蠡贴?大",
|
||||
"created_ts": 1766334659.9824915
|
||||
"prize_value_yuan": 888.0,
|
||||
"content": "(福袋]云南名茶收藏馆专属盖碗+茶针",
|
||||
"future_ts": 1766338996.825995,
|
||||
"future_str": "2025-12-22 01:43:16",
|
||||
"pos_seen": 3,
|
||||
"room_title": "云南名茶",
|
||||
"room_title_raw": "云南名茶。",
|
||||
"created_ts": 1766338568.247795
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -189,9 +189,9 @@ def main(argv: list[str]) -> int:
|
||||
p: Optional[Path] = None
|
||||
if len(argv) >= 2:
|
||||
p = Path(argv[1]).expanduser()
|
||||
if not p.is_absolute():
|
||||
if p and not p.is_absolute():
|
||||
p = (Path(__file__).resolve().parent.parent / p).resolve()
|
||||
if not p.exists():
|
||||
if p and not p.exists():
|
||||
print(f"找不到图片: {p}")
|
||||
print("将弹出文件选择框,请手动选择图片。")
|
||||
p = None
|
||||
|
||||
+11
-11
@@ -36,21 +36,21 @@ _thread_local = threading.local()
|
||||
class MDC:
|
||||
"""Mapped Diagnostic Context - 用于在日志中传递上下文信息(如traceId)"""
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def put(key: str, value: Any) -> None:
|
||||
"""设置MDC值"""
|
||||
if not hasattr(_thread_local, 'mdc'):
|
||||
_thread_local.mdc = {}
|
||||
_thread_local.mdc[key] = value
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def get(key: str, default: Any = None) -> Any:
|
||||
"""获取MDC值"""
|
||||
if hasattr(_thread_local, 'mdc'):
|
||||
return _thread_local.mdc.get(key, default)
|
||||
return default
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def remove(key: str) -> None:
|
||||
"""移除MDC值"""
|
||||
if hasattr(_thread_local, 'mdc'):
|
||||
@@ -81,7 +81,7 @@ class MDC:
|
||||
if trace_id is None:
|
||||
trace_id = str(uuid.uuid4())[:16] # 使用UUID前16位作为traceId
|
||||
MDC.put('traceId', trace_id)
|
||||
return trace_id
|
||||
return str(trace_id) # 确保返回 str 类型
|
||||
|
||||
|
||||
class SensitiveDataMasker:
|
||||
@@ -109,21 +109,21 @@ class SensitiveDataMasker:
|
||||
],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def mask_password(text: str) -> str:
|
||||
"""脱敏密码"""
|
||||
for pattern in SensitiveDataMasker.PATTERNS['password']:
|
||||
text = re.sub(pattern, r'\1=***', text)
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def mask_phone(text: str) -> str:
|
||||
"""脱敏手机号"""
|
||||
# 手机号脱敏:保留前3位和后4位
|
||||
text = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', text)
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def mask_id_card(text: str) -> str:
|
||||
"""脱敏身份证号"""
|
||||
# 18位身份证:保留前6位和后4位
|
||||
@@ -132,7 +132,7 @@ class SensitiveDataMasker:
|
||||
text = re.sub(r'(\d{6})\d{6}(\d{3})', r'\1******\2', text)
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def mask_email(text: str) -> str:
|
||||
"""脱敏邮箱"""
|
||||
def replace_email(match):
|
||||
@@ -147,13 +147,13 @@ class SensitiveDataMasker:
|
||||
text = re.sub(SensitiveDataMasker.PATTERNS['email'][0], replace_email, text)
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def mask_bank_card(text: str) -> str:
|
||||
"""脱敏银行卡号"""
|
||||
text = re.sub(r'(\d{4})\d{8,12}(\d{4})', r'\1********\2', text)
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def mask_all(text: str) -> str:
|
||||
"""对所有敏感信息进行脱敏"""
|
||||
if not isinstance(text, str):
|
||||
@@ -167,7 +167,7 @@ class SensitiveDataMasker:
|
||||
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def mask_dict(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""对字典中的敏感字段进行脱敏"""
|
||||
sensitive_keys = ['password', 'pwd', 'passwd', 'phone', 'mobile', 'tel',
|
||||
|
||||
+26
-13
@@ -183,7 +183,7 @@ class ProcRunner:
|
||||
if len(self._wins) > self._wins_cap:
|
||||
self._wins = self._wins[-self._wins_cap :]
|
||||
|
||||
@staticmethod
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _parse_countdown_seconds(text: str) -> Optional[int]:
|
||||
t = str(text or "").strip()
|
||||
if not t:
|
||||
@@ -225,8 +225,8 @@ class ProcRunner:
|
||||
return None
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _bucket(value: float, edges: list[float]) -> str: # type: ignore[misc]
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _bucket(value: float, edges: list[float]) -> str:
|
||||
# edges 例如 [0,10,50,100] => 0-10,10-50,50-100,100+
|
||||
if not edges:
|
||||
return "all"
|
||||
@@ -237,8 +237,8 @@ class ProcRunner:
|
||||
return f"{a:g}-{b:g}"
|
||||
return f"{edges[-1]:g}+"
|
||||
|
||||
@staticmethod
|
||||
def _inc_map(m: dict, k: str, n: int = 1) -> None: # type: ignore[misc]
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _inc_map(m: dict, k: str, n: int = 1) -> None:
|
||||
m[k] = int(m.get(k, 0)) + int(n)
|
||||
|
||||
def _snapshot_fudai(self) -> dict:
|
||||
@@ -643,7 +643,7 @@ class ProcRunner:
|
||||
|
||||
v = meta.get("prize_value_yuan")
|
||||
if isinstance(v, (int, float)):
|
||||
b = self._bucket(float(v), value_edges)
|
||||
b = self._bucket(float(v), [float(x) for x in value_edges])
|
||||
self._inc_map(value_buckets, b, 1)
|
||||
p = meta.get("participants")
|
||||
if isinstance(p, int):
|
||||
@@ -1269,32 +1269,45 @@ class Handler(BaseHTTPRequestHandler):
|
||||
"yanghao_fallback_enter_live_y",
|
||||
}
|
||||
|
||||
def set_nested_value(obj, key, value):
|
||||
"""设置嵌套配置值,支持如 'debug_captures.auto_cleanup' 这样的键"""
|
||||
if "." in key:
|
||||
parts = key.split(".")
|
||||
current = obj
|
||||
for part in parts[:-1]:
|
||||
if part not in current or not isinstance(current[part], dict):
|
||||
current[part] = {}
|
||||
current = current[part]
|
||||
current[parts[-1]] = value
|
||||
else:
|
||||
obj[key] = value
|
||||
|
||||
for k, v in (update or {}).items():
|
||||
if k in deny_keys:
|
||||
continue
|
||||
if k in int_keys:
|
||||
try:
|
||||
cfg[k] = int(v)
|
||||
set_nested_value(cfg, k, int(v))
|
||||
except Exception:
|
||||
continue
|
||||
elif k in float_keys:
|
||||
try:
|
||||
cfg[k] = float(v)
|
||||
set_nested_value(cfg, k, float(v))
|
||||
except Exception:
|
||||
continue
|
||||
elif k in bool_keys:
|
||||
cfg[k] = bool(v)
|
||||
set_nested_value(cfg, k, bool(v))
|
||||
elif k in list_str_keys:
|
||||
if isinstance(v, list):
|
||||
cfg[k] = [str(x) for x in v if str(x).strip()]
|
||||
set_nested_value(cfg, k, [str(x) for x in v if str(x).strip()])
|
||||
else:
|
||||
cfg[k] = [
|
||||
set_nested_value(cfg, k, [
|
||||
str(x).strip()
|
||||
for x in str(v).splitlines()
|
||||
if str(x).strip()
|
||||
]
|
||||
])
|
||||
else:
|
||||
cfg[k] = v
|
||||
set_nested_value(cfg, k, v)
|
||||
|
||||
write_config(cfg)
|
||||
return self._send_json({"ok": True})
|
||||
|
||||
+57
-7
@@ -55,6 +55,18 @@ const DEFAULTS = {
|
||||
fudai_quiet_hours_enabled: true,
|
||||
fudai_quiet_start_hour: 2,
|
||||
fudai_quiet_end_hour: 7,
|
||||
|
||||
// 调试相关
|
||||
"debug_captures.auto_cleanup": true,
|
||||
"debug_captures.keep_days": 7,
|
||||
"debug_captures.max_files": 2000,
|
||||
enable_ocr_mode1: false,
|
||||
fudai_template_match_enabled: false,
|
||||
fudai_template_match_threshold: 0.7,
|
||||
lucky_draw_red_ratio_threshold: 0.8,
|
||||
live_room_match_threshold: 0.7,
|
||||
stage_diag_max_time: 15.0,
|
||||
stage_diag_max_step_time: 4.0,
|
||||
};
|
||||
|
||||
function $(id) { return document.getElementById(id); }
|
||||
@@ -488,13 +500,50 @@ function coerceValue(type, raw, isCheckbox) {
|
||||
return String(raw ?? "");
|
||||
}
|
||||
|
||||
function getNestedValue(obj, key) {
|
||||
if (!obj || !key) return undefined;
|
||||
// 支持嵌套键,如 "debug_captures.auto_cleanup"
|
||||
if (key.includes(".")) {
|
||||
const parts = key.split(".");
|
||||
let current = obj;
|
||||
for (const part of parts) {
|
||||
if (current && typeof current === "object" && part in current) {
|
||||
current = current[part];
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return current;
|
||||
}
|
||||
return obj[key];
|
||||
}
|
||||
|
||||
function setNestedValue(obj, key, value) {
|
||||
if (!obj || !key) return;
|
||||
// 支持嵌套键,如 "debug_captures.auto_cleanup"
|
||||
if (key.includes(".")) {
|
||||
const parts = key.split(".");
|
||||
let current = obj;
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
const part = parts[i];
|
||||
if (!(part in current) || typeof current[part] !== "object" || current[part] === null) {
|
||||
current[part] = {};
|
||||
}
|
||||
current = current[part];
|
||||
}
|
||||
current[parts[parts.length - 1]] = value;
|
||||
} else {
|
||||
obj[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
function applyConfigToUI(cfg) {
|
||||
for (const el of getConfigBoundElements()) {
|
||||
const key = el.dataset.key;
|
||||
const type = el.dataset.type || "str";
|
||||
const val = cfg ? cfg[key] : undefined;
|
||||
const val = cfg ? getNestedValue(cfg, key) : undefined;
|
||||
|
||||
// undefined/null 都视为“未配置”:保留页面默认值
|
||||
// undefined/null 都视为"未配置":保留页面默认值
|
||||
const hasVal = !(typeof val === "undefined" || val === null);
|
||||
const useVal = hasVal ? val : (Object.prototype.hasOwnProperty.call(DEFAULTS, key) ? DEFAULTS[key] : undefined);
|
||||
if (typeof useVal === "undefined") continue;
|
||||
@@ -518,11 +567,12 @@ function collectConfigFromUI() {
|
||||
const type = el.dataset.type || "str";
|
||||
if (!key) continue;
|
||||
|
||||
if (el.type === "checkbox") {
|
||||
out[key] = coerceValue(type, el.checked, true);
|
||||
} else {
|
||||
out[key] = coerceValue(type, el.value, false);
|
||||
}
|
||||
const value = el.type === "checkbox"
|
||||
? coerceValue(type, el.checked, true)
|
||||
: coerceValue(type, el.value, false);
|
||||
|
||||
// 支持嵌套键,如 "debug_captures.auto_cleanup"
|
||||
setNestedValue(out, key, value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -88,6 +88,10 @@
|
||||
<span class="tabIcon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10a7 7 0 1 1-14 0 7 7 0 0 1 14 0z"/><path d="M21 21l-6-6"/></svg></span>
|
||||
<span class="tabText">关键词</span>
|
||||
</button>
|
||||
<button class="tabBtn" type="button" data-target="debug" role="tab" aria-selected="false">
|
||||
<span class="tabIcon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg></span>
|
||||
<span class="tabText">调试</span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<div class="panels">
|
||||
@@ -634,6 +638,84 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel" data-panel="debug" role="tabpanel" hidden>
|
||||
<div class="sectionTitle">
|
||||
<span class="sectionIcon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg></span>
|
||||
调试参数
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">调试图像清理</div>
|
||||
<div class="row">
|
||||
<label class="label">启用自动清理调试图像</label>
|
||||
<label class="check">
|
||||
<input id="debug_captures_auto_cleanup" type="checkbox" data-key="debug_captures.auto_cleanup" data-type="bool" checked />
|
||||
<span>启用</span>
|
||||
</label>
|
||||
<div class="hint">每天第一次保存调试图像时自动清理旧目录</div>
|
||||
</div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">保留天数</label>
|
||||
<input id="debug_captures_keep_days" class="input" data-key="debug_captures.keep_days" data-type="int" type="number" min="1" max="30" step="1" value="7" />
|
||||
<div class="hint">超过此天数的调试图像目录将被自动删除</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">最大文件数量</label>
|
||||
<input id="debug_captures_max_files" class="input" data-key="debug_captures.max_files" data-type="int" type="number" min="100" max="10000" step="100" value="2000" />
|
||||
<div class="hint">超过此数量的调试图像将被自动清理(优先删除最旧的)</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">OCR 模式</div>
|
||||
<div class="row">
|
||||
<label class="label">启用 OCR 模式1(备用)</label>
|
||||
<label class="check">
|
||||
<input id="enable_ocr_mode1" type="checkbox" data-key="enable_ocr_mode1" data-type="bool" />
|
||||
<span>启用</span>
|
||||
</label>
|
||||
<div class="hint">当模式0识别失败时,自动尝试模式1</div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">模板匹配</div>
|
||||
<div class="row">
|
||||
<label class="label">启用福袋模板匹配</label>
|
||||
<label class="check">
|
||||
<input id="fudai_template_match_enabled" type="checkbox" data-key="fudai_template_match_enabled" data-type="bool" />
|
||||
<span>启用</span>
|
||||
</label>
|
||||
<div class="hint">使用模板匹配辅助查找福袋图标</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">模板匹配阈值</label>
|
||||
<input id="fudai_template_match_threshold" class="input" data-key="fudai_template_match_threshold" data-type="float" type="number" min="0" max="1" step="0.01" value="0.7" />
|
||||
<div class="hint">匹配分数阈值,范围 0-1,默认 0.7</div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">像素检测</div>
|
||||
<div class="row">
|
||||
<label class="label">抽奖结果红色比例阈值</label>
|
||||
<input id="lucky_draw_red_ratio_threshold" class="input" data-key="lucky_draw_red_ratio_threshold" data-type="float" type="number" min="0" max="1" step="0.01" value="0.8" />
|
||||
<div class="hint">用于检测抽奖结果弹窗,范围 0-1,默认 0.8</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">直播间匹配阈值</label>
|
||||
<input id="live_room_match_threshold" class="input" data-key="live_room_match_threshold" data-type="float" type="number" min="0" max="1" step="0.01" value="0.7" />
|
||||
<div class="hint">用于判断是否在直播间,范围 0-1,默认 0.7</div>
|
||||
</div>
|
||||
|
||||
<div class="sectionTitle">阶段诊断</div>
|
||||
<div class="row grid2">
|
||||
<div>
|
||||
<label class="label">最大诊断时间(秒)</label>
|
||||
<input id="stage_diag_max_time" class="input" data-key="stage_diag_max_time" data-type="float" type="number" min="1" max="60" step="1" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label">单步最大时间(秒)</label>
|
||||
<input id="stage_diag_max_step_time" class="input" data-key="stage_diag_max_step_time" data-type="float" type="number" min="0.5" max="10" step="0.5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# 抖音福袋挂机程序流程图(完整版)
|
||||
|
||||
**版本**: V3.3.2+
|
||||
**最后更新**: 2025-12-22
|
||||
**主要更新**: 并行OCR优化、回退逻辑修复
|
||||
|
||||
## 主流程图
|
||||
|
||||
```mermaid
|
||||
@@ -76,21 +80,25 @@ flowchart TD
|
||||
CloseCoupon --> ReturnError[返回错误状态]
|
||||
ReturnError --> MainLoop
|
||||
|
||||
CheckCouponPopup -->|否| CheckTaskCount[检测任务数量<br/>像素检测]
|
||||
CheckTaskCount --> CheckTaskZero{任务数 = 0?}
|
||||
|
||||
CheckTaskZero -->|是| ReturnNotDetail[返回错误状态<br/>认为不在福袋详情页]
|
||||
ReturnNotDetail --> MainLoop
|
||||
|
||||
CheckTaskZero -->|否| CheckVerified{优化查找器已验证?}
|
||||
CheckCouponPopup -->|否| CheckVerified{优化查找器已验证?}
|
||||
CheckVerified -->|是| ShortWait[短暂等待0.3秒<br/>清除验证标志]
|
||||
CheckVerified -->|否| NormalWait[正常等待1.2秒]
|
||||
ShortWait --> CutRegions[裁剪OCR区域<br/>内容/倒计时/价值]
|
||||
NormalWait --> CutRegions
|
||||
|
||||
CutRegions --> ParallelOCR[并行OCR识别<br/>3个线程同时执行]
|
||||
CutRegions --> ParallelOCR[并行OCR识别<br/>4个线程同时执行<br/>V3.3.2+优化]
|
||||
|
||||
ParallelOCR --> CheckWatchTask{OCR识别内容后<br/>检查是否为观看X分钟任务?}
|
||||
ParallelOCR --> OCRContent[线程1: OCR识别福袋内容]
|
||||
ParallelOCR --> OCRCountdown[线程2: OCR识别倒计时]
|
||||
ParallelOCR --> OCRValue[线程3: OCR识别价值]
|
||||
ParallelOCR --> DetectTaskCount[线程4: 检测任务数量<br/>像素检测]
|
||||
|
||||
DetectTaskCount --> CheckTaskZero{任务数 = 0?}
|
||||
CheckTaskZero -->|是| ReturnNotDetail[返回错误状态<br/>认为不在福袋详情页]
|
||||
ReturnNotDetail --> MainLoop
|
||||
|
||||
CheckTaskZero -->|否| OCRContent
|
||||
OCRContent --> CheckWatchTask{OCR识别内容后<br/>检查是否为观看X分钟任务?}
|
||||
|
||||
CheckWatchTask -->|是| ReturnWatchTask[返回: watch_task状态<br/>关闭详情页]
|
||||
ReturnWatchTask --> MainLoop
|
||||
@@ -310,12 +318,7 @@ flowchart TD
|
||||
IsCoupon -->|是| CloseCoupon[关闭优惠券弹窗]
|
||||
CloseCoupon --> ReturnCoupon[返回: coupon_popup状态]
|
||||
|
||||
IsCoupon -->|否| CheckTaskCount[检测任务数量<br/>像素检测参与按钮位置]
|
||||
CheckTaskCount --> TaskCount{任务数 = 0?}
|
||||
|
||||
TaskCount -->|是| ReturnError[返回: error状态<br/>认为不在福袋详情页<br/>跳过OCR识别]
|
||||
|
||||
TaskCount -->|否| NormalizeTask{任务数在1-3范围内?}
|
||||
IsCoupon -->|否| NormalizeTask{任务数在1-3范围内?<br/>注意: 任务数量检测在并行OCR中执行}
|
||||
NormalizeTask -->|否| SetTask2[设置为2个任务]
|
||||
NormalizeTask -->|是| UseTaskCount[使用检测到的任务数]
|
||||
SetTask2 --> CutRegions
|
||||
@@ -325,11 +328,16 @@ flowchart TD
|
||||
CutContent --> CutCountdown[裁剪倒计时区域]
|
||||
CutCountdown --> CutValue[裁剪价值区域]
|
||||
|
||||
CutValue --> ParallelOCR[并行OCR识别<br/>3个线程同时执行]
|
||||
CutValue --> ParallelOCR[并行OCR识别<br/>4个线程同时执行<br/>V3.3.2+优化]
|
||||
|
||||
ParallelOCR --> OCRContent[线程1: OCR识别福袋内容<br/>模式0]
|
||||
ParallelOCR --> OCRCountdown[线程2: OCR识别倒计时<br/>模式0]
|
||||
ParallelOCR --> OCRValue[线程3: OCR识别价值<br/>模式0]
|
||||
ParallelOCR --> DetectTaskCount[线程4: 检测任务数量<br/>像素检测]
|
||||
|
||||
DetectTaskCount --> CheckTaskZero{任务数 = 0?}
|
||||
CheckTaskZero -->|是| ReturnError[返回: error状态<br/>认为不在福袋详情页]
|
||||
CheckTaskZero -->|否| OCRContent
|
||||
|
||||
OCRContent --> CheckWatchTask{检查原始内容<br/>是否为观看X分钟任务?}
|
||||
|
||||
@@ -344,13 +352,14 @@ flowchart TD
|
||||
CheckWatchTask2 -->|是| SetWatchFlag2[设置观看任务标志]
|
||||
SetWatchFlag2 --> ReturnWatchTask
|
||||
|
||||
CheckWatchTask2 -->|否| WaitAllOCR[等待所有OCR完成]
|
||||
CheckWatchTask2 -->|否| WaitAllOCR[等待所有OCR完成<br/>包括任务数量检测]
|
||||
|
||||
OCRCountdown --> WaitAllOCR
|
||||
OCRValue --> WaitAllOCR
|
||||
DetectTaskCount --> WaitAllOCR
|
||||
|
||||
WaitAllOCR --> CheckCountdown{倒计时识别成功?}
|
||||
CheckCountdown -->|否| SplitCountdown[分割倒计时区域<br/>分别识别分钟和秒]
|
||||
CheckCountdown -->|否| SplitCountdown[分割倒计时区域<br/>并行识别分钟和秒<br/>2个线程同时执行<br/>V3.3.2+优化]
|
||||
SplitCountdown --> ParseCountdown
|
||||
CheckCountdown -->|是| ParseCountdown[解析倒计时<br/>转换为时间戳]
|
||||
|
||||
@@ -512,9 +521,13 @@ flowchart TD
|
||||
- **验证标志**: 验证成功后设置 `_fudai_detail_verified=True`,缩短后续等待时间
|
||||
|
||||
### 3. 详情读取决策点
|
||||
- **任务数检测**: 如果任务数为0,直接返回错误,跳过OCR识别
|
||||
- **任务数检测(V3.3.2+)**: 任务数量检测与OCR并行执行,如果任务数为0,直接返回错误,跳过后续处理
|
||||
- **验证标志**: 如果优化查找器已验证,等待时间从1.2秒缩短到0.3秒
|
||||
- **并行OCR**: 内容/倒计时/价值三个OCR操作并行执行,提高效率
|
||||
- **并行OCR(V3.3.2+)**:
|
||||
- 内容/倒计时/价值/任务数量检测四个操作并行执行,提高效率
|
||||
- 倒计时分割识别(分钟+秒)并行执行,提升约50%速度
|
||||
- OCR模式0+模式1并行执行(启用时),提升约50%速度
|
||||
- 异常回退流程也使用并行执行,避免性能下降
|
||||
- **观看任务提前检测**: OCR识别内容后立即检查是否为"观看X分钟"任务,如果是则直接返回,跳过倒计时和价值识别,节省时间
|
||||
- **倒计时一致性**: 多次读取时检查倒计时是否一致,避免识别错误
|
||||
|
||||
@@ -549,7 +562,11 @@ flowchart TD
|
||||
|
||||
1. **验证标志优化**: 优化查找器验证成功后,设置标志缩短后续等待时间(1.2秒 → 0.3秒)
|
||||
2. **任务数为0优化**: 检测到任务数为0时,直接跳过OCR识别,节省约12秒
|
||||
3. **并行OCR识别**: 内容/倒计时/价值三个OCR操作并行执行,理论上可减少约2/3的OCR总耗时
|
||||
3. **并行OCR识别(V3.3.2+)**:
|
||||
- 内容/倒计时/价值/任务数量检测四个操作并行执行,理论上可减少约3/4的OCR总耗时
|
||||
- 倒计时分割识别(分钟+秒)并行执行,提升约50%速度
|
||||
- OCR模式0+模式1并行执行(启用时),提升约50%速度
|
||||
- 异常回退流程也使用并行执行,避免性能下降
|
||||
4. **观看任务提前检测**: OCR识别内容后立即检查是否为"观看X分钟"任务,如果是则直接返回,跳过倒计时和价值识别,节省时间并避免不必要的处理
|
||||
5. **倒计时一致性检查**: 多次读取时检查倒计时是否一致,避免识别错误导致的误判
|
||||
6. **并行像素检测**: 阶段诊断时所有像素特征并行检测,提高效率
|
||||
|
||||
@@ -80,3 +80,7 @@
|
||||
|
||||
==========================================
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -152,3 +152,7 @@ def main():
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user