From 9e08ed3bd02728779f258970348e9d2baa6671ce Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 3 Jan 2026 03:50:45 +0800 Subject: [PATCH] chore: remove OCR archive, delete collect_ocr_failures, update docs --- config/config.json | 7 +- docs/完整技术文档.md | 297 ++++++---- douyin/core/state/reservations.json | 2 +- douyin/fudai/core/fudai_detail_reader.py | 40 ++ douyin/fudai/douyin_fudai_core.py | 39 ++ douyin/handlers/douyin_screenshot_handler.py | 1 + douyin/handlers/douyin_screenshot_manager.py | 251 ++++++-- douyin/logging/action_logger.py | 43 +- douyin/logging/douyin_logging_wrapper.py | 153 ++++- douyin/utils/douyin_helpers.py | 24 +- fudai_detail_modules/fudai_detail_reader.py | 92 ++- gui/gui_app.py | 578 ++++++++++++++----- gui/web_gui.py | 184 ++++-- tools/README.md | 21 + tools/scan_coords.py | 97 ++++ tools/test_actions_log.py | 29 + webui/app.js | 2 + webui/index.html | 168 +++--- 18 files changed, 1516 insertions(+), 512 deletions(-) create mode 100644 tools/README.md create mode 100644 tools/scan_coords.py create mode 100644 tools/test_actions_log.py diff --git a/config/config.json b/config/config.json index eabadcc..65ef0af 100644 --- a/config/config.json +++ b/config/config.json @@ -1,16 +1,16 @@ { - "needswitch": false, + "needswitch": true, "infinite_loop_enabled": true, "wait_minutes": 5, "min_prize_value_yuan": 200.0, "min_participants": 0, "max_participants": 0, - "skip_if_countdown_gt_seconds": 180, + "skip_if_countdown_gt_seconds": 1800, "reset_after_swipes_enabled": true, "reset_after_swipes": 10, "auto_join_fansclub": true, "fansclub_fail_action": "switch", - "high_value_fudai_enabled": true, + "high_value_fudai_enabled": false, "high_value_fudai_threshold_yuan": 500.0, "high_value_fudai_join_ahead_seconds": 120, "high_value_fudai_max_swipe_back": 50, @@ -35,6 +35,7 @@ "fudai_detail_verified_wait_seconds": 0.2, "fudai_detail_retry_delay_seconds": 0.5, "fudai_detail_save_debug_images": true, + "fudai_disable_content_recognition": true, "yanghao_recommend_duration_seconds": 206, "yanghao_recommend_interval_seconds": 570, "yanghao_like_prob": 1.0, diff --git a/docs/完整技术文档.md b/docs/完整技术文档.md index 19d422d..b5ec8da 100644 --- a/docs/完整技术文档.md +++ b/docs/完整技术文档.md @@ -1,137 +1,223 @@ -# 抖音福袋挂机项目 - 完整技术文档 +# 抖音福袋挂机 — 完整技术文档(重构) -**文档版本**: V3.0 -**最后更新**: 2025-12-30 -**目标读者**: AI助手、开发者、维护人员 - ---- - -## 变更记录 (简要) - -- 2025-12-30: 文档主版本 V3.0 完成;补充流程、OCR、预约细节。 -- 2026-01-02: 补充快速开始、运行命令、重要环境变量与日志/调试图像说明。 -- 2026-01-02: 补充快速开始、运行命令、重要环境变量与日志/调试图像说明。 - - 统一整理关键裁剪区域坐标到 `douyin/fudai/core/coords.py` 并在 `douyin/stage/douyin_stage.py`、`douyin/fudai/douyin_fudai_core.py` 等模块引用常量,避免硬编码坐标。 - -# 抖音福袋挂机 — 技术总览与 AI 指南 - -文档版本: V3.1 +版本: V4.0 最后更新: 2026-01-03 -目标读者: AI 助手、维护者、贡献者 +目标读者: 开发者、维护者、运维与 AI 助手 -目的:把项目的结构、运行方式、关键文件和可改进点明确化,使 AI 能快速定位问题、提出改进并自动化辅助修改。 +说明:本文件为项目主要技术文档的重构版,聚焦“快速上手、配置规范、关键模块地图、运行与排障、验证清单”。文档同时给出可执行的诊断/采样命令,便于自动化采集与 CI 校验。 -## 目录(快速跳转) -- 概览与目标 -- 快速上手(运行与调试) -- 关键文件与模块地图 -- 核心流程与调用链(简明) -- 运行时状态与数据结构 -- 常见问题与排障步骤 -- AI 优化与改进建议(优先级与起手点) -- 给 AI 的具体任务清单(可自动执行的子任务) -- 开发与提交规范(精简) -- 附:常用命令 & 链接 +-- 变更记录 +- 2026-01-03: V4.0 — 重构文档结构,补充快速上手、配置优先级、截图/OCR/日志说明、故障排查与验证清单。 -## 概览与目标 -项目用途:在抖音直播中自动检测并参与“福袋”类抽奖,包含检测、筛选、参与、预约与开奖处理等流程。 -核心目标:可靠、低误报、高并发 OCR 效率、在多分辨率设备上稳定运行。 +## 快速步骤(3 分钟上手) -## 快速上手(最小可运行) +1. 克隆仓库并进入目录 -环境准备(推荐) -- Windows PowerShell: - - python -m venv .venv - - .\.venv\Scripts\Activate.ps1 -- pip install -r requirements-minimal.txt +2. 建议在 Windows PowerShell 中运行(示例): -运行示例 -- 单设备启动主流程: - - python run_cli.py --device-id --needswitch -- 单次循环(调试): - - python run_cli.py --device-id --wait-minutes 0 +```powershell +python -m venv .venv +.\.venv\Scripts\Activate.ps1 +pip install -r requirements-minimal.txt +``` -调试与日志 -- 日志入口:参见 [douyin/logging/douyin_logging.py](douyin/logging/douyin_logging.py),业务日志请使用 `analyser._log_kv(...)`。 -- 截图与调试图像控制:使用 `config/config.json` 中的 `debug_captures`,截图路径参见 `path_config.py`。 +3. 运行主流程(单设备示例): -## 关键文件与模块地图(AI 首次阅读建议顺序) +```powershell +python run_cli.py --device-id --needswitch +``` -优先阅读(按重要性) -- [run_cli.py](run_cli.py) -- [douyin/core/douyin_fudai.py](douyin/core/douyin_fudai.py) -- [Underlying_Operations.py](Underlying_Operations.py) -- [douyin/fudai/douyin_fudai_core.py](douyin/fudai/douyin_fudai_core.py) -- [douyin/detection/douyin_pixel.py](douyin/detection/douyin_pixel.py) -- [douyin/reservation/douyin_reservation_logic.py](douyin/reservation/douyin_reservation_logic.py) -- [path_config.py](path_config.py) +4. 调试单次循环: -辅助参考 -- [config/config.json](config/config.json) -- [douyin/logging/douyin_logging_wrapper.py](douyin/logging/douyin_logging_wrapper.py) +```powershell +python run_cli.py --device-id --wait-minutes 0 +``` -## 核心流程(简要调用链) -1) run_cli.py -> 创建 `fudai_analyse` -> load_config() -> fudai_choujiang() -2) fudai_choujiang -> 循环调用 run_once_basic() -3) run_once_basic:预约处理 -> 获取截图 -> 阶段诊断 -> 根据阶段执行(直播间/详情页/开奖结果) -4) 福袋详情页使用并行 OCR(ThreadPoolExecutor)解析价值/倒计时/按钮,并调用 `attend_choujiang()` 完成参与 +说明:如需快速禁用 OCR 启动耗时,可设置环境变量 `SKIP_OCR_INIT=1`。 -## 运行时核心状态(AI 应关注) -- `_waiting_for_lottery_result`:是否在等待开奖结果 -- `reservations`(内存)与 `state/reservations.json`(持久化) -- `_last_successful_attend_ts`:最后成功参与时间(30 分钟保护) -- `_swipe_times`:滑动计数(重置策略触发) +## 文档结构(建议阅读顺序) +- 快速上手(本节) +- 配置与覆盖优先级(重要) +- 截图/OCR/日志与状态文件(实现细节 + 开关) +- 核心模块地图(文件 + 关键符号) +- 运行流程概览(简要调用链) +- 故障排查与采样操作(可执行命令) +- 验证清单与 CI 建议 +- FAQ -## 常见故障与排障步骤(可自动化检查项) -1) 截图失败:验证 `Underlying_Operations.get_screenshot()`,检查 `pic/screenshot.png` 文件存在与大小。 -2) OCR 识别失败:保存失败裁剪图到 `pic/ocr_failures/`,比对 EasyOCR/PaddleOCR 输出。 -3) 阶段误判:在 `douyin/detection/douyin_pixel.py` 中调整区域或阈值,并保存对比图。 +## 配置加载与覆盖优先级 -## 给 AI 的优化与改进建议(优先级起手点) -目标:提升稳定性与识别准确率。 +生效顺序(从低到高): -高优先级 -- 强化截图可靠性:改进原子写入与 Windows 文件锁重试逻辑(`Underlying_Operations.get_screenshot`)。 -- 自动收集 OCR 失败样本并统计(便于训练/规则调整)。 +1. 代码内默认值(常量/类属性) +2. `config/config.json`(通过 `path_config.get_config_path()` 获取) +3. 环境变量(例如 `SKIP_OCR_INIT`, `DISABLE_SCREENSHOT_MIRROR`) +4. 命令行参数(`run_cli.py` 解析,优先级最高,运行时覆盖实例属性) -中优先级 -- 参数 A/B 测试:暴露阈值并自动化小范围调参(记录误报/漏报)。 -- 对 `extract_prize_value_yuan()` 增加更全面的正则测试用例。 +示例:通过命令行临时指定设备优先于 `config/config.json` 中的默认设备。 -可观测性 -- 在日志中增加 `traceId/device_id/stage/ocr_confidence/fudai_value`,便于聚合分析。 +关联文件:`config/config.json`,`douyin/utils/douyin_config.py`,`path_config.py`,`run_cli.py`。 -## 给 AI 的可执行任务清单(可自动在 CI/本地运行) -短期自动任务 -- 扫描仓库并列出所有“硬编码坐标/裁剪区域”位置(文件、行号)。 -- 运行 `python -m py_compile` 检查语法错误并输出清单。 -- 收集 `pic/` 中 OCR 失败样本并生成按区域统计报告。 +## 截图 / OCR / 日志 / 状态(实现细节与故障采样) -中期任务(需人工复核) -- 生成阈值建议报告:在安全回放下试验阈值变化并记录效果。 -- 为关键解析函数添加单元测试样例(放在 tests/)。 +1) 截图(实现要点) -长期计划(研究类) -- 使用小型图像分类器作为 OCR 与模板的二次验真器以降低误识率。 +- 优先方式:`adb exec-out screencap -p`(单次 adb 调用,速度最快)。 +- 回退方式:`adb shell screencap -p /sdcard/screen.png` + `adb pull`(兼容性但更慢)。 +- 写入策略:先写入临时文件(例如 `screenshot.png.tmp`),再通过原子替换或安全复制覆盖 `pic/screenshot.png`,以避免并发读取到半写入文件。见 `Underlying_Operations.get_screenshot()` 的实现。 +- Windows 文件锁与镜像:`_safe_replace_file()` 包含多重回退(`os.replace` → `shutil.copy2` → 分块复制),并可通过环境变量 `DISABLE_SCREENSHOT_MIRROR=1` 禁用将截图镜像到外部目录(`EXTERNAL_DOUYIN_FUDAI_DIR`)。 -## 开发与提交规范(精简) -- 缩进:4 空格;异常建议捕获具体异常。 -- 提交流程:分支 `feature/`、`fix/`、`docs/`,PR 说明验证步骤与影响范围。 +2) OCR(策略与初始化) -## 常用命令 -- 安装依赖:pip install -r requirements-minimal.txt -- 语法检查:python -m py_compile $(git ls-files "**/*.py") -- 运行一次:python run_cli.py --device-id --wait-minutes 0 +- 优先引擎:EasyOCR(速度与准确性通常最佳);回退:PaddleOCR。实现位于 `Underlying_Operations.analyse_pic_word()`。 +- 延迟初始化:支持 `SKIP_OCR_INIT=1`(跳过启动时初始化),首次调用时会在 `_ensure_ocr()` 进行按需初始化。 +- 回退与容错:若 OCR 未能初始化或识别失败,函数返回空字符串,上层代码需对空结果做容错与重试。建议生产环境安装 `easyocr` 并允许启动时初始化以减少首次延迟。 -## 后续建议 -- 逐步把“自动化收集样本 -> 生成报告 -> 生成 PR(小改动)”纳入 CI,AI 可以以此闭环优化识别规则。 +3) 日志(配置点与建议) -文档变更记录 -- 2026-01-03: V3.1 — 重构并精简原文档,加入 AI 优化指南与可执行任务清单。 +- 日志初始化:`douyin/logging/douyin_logging.py::configure_logging()`,业务封装见 `douyin/logging/douyin_logging_wrapper.py`。 +- 关键字段(建议在文档或 `config.json` 中说明): + - `logging.level`、`logging.file_path`、`logging.rotation.max_bytes`、`logging.rotation.backup_count`。 + - `debug_captures`:`enabled`、`keep_days`、`max_files`、`auto_cleanup` 用于调试图片的保存与清理。 +- 建议:生产默认禁用大量 debug captures,CI/调试时开启并限制 `max_files`。日志需包含 `traceId/device_id/stage` 字段以便聚合分析。 + +4) 状态文件(预约) + +- 持久化路径:通过 `path_config.get_reservations_path()` 返回 `state/reservations.json`。 +- 行为说明:当前实现“首次运行清空内存预约以避免历史污染,后续运行以内存队列为主并在变更时写回文件以供外部查看”。请在运维手册中明确该语义并在需要保留历史时修改启动策略。 + +5) 故障采样与自动化收集(建议步骤与脚本) + +- 已提供:`tools/scan_coords.py`(扫描仓库中疑似硬编码坐标/ROI,输出 `tools/coords_report.csv`)。 +- 建议采样流程(手动或自定义脚本): + 1. 运行短时主流程以产生调试图片: + +```powershell +python run_cli.py --device-id --wait-minutes 1 +``` + + 2. 手动或使用团队自定义脚本筛选 `pic/` 目录下的异常输出(例如包含 `ocr`/`analyse` 关键字或根据日志时间窗口),并将样本复制到团队约定的样本目录(例如 `tools/samples/`)。 + + 3. 记录对应的运行日志与 `pic` 路径以便人工复核或用于训练样本。 + +- 快速检查命令(采样与诊断): + +```powershell +# 扫描仓库硬编码坐标 +python tools/scan_coords.py + +# 查看前200条样例(生成的文件较大时使用) +powershell -Command "Get-Content tools/coords_report.csv -TotalCount 200 | Out-File -Encoding utf8 tools/coords_report_head.csv" +``` + +6) 参考实现与文件链接 + +- 截图与裁剪:`Underlying_Operations.get_screenshot()`、`Underlying_Operations.cut_pic()`。 +- OCR:`Underlying_Operations.analyse_pic_word()`、`Underlying_Operations.analyse_pic_digits()`。 +- 日志:`douyin/logging/douyin_logging.py`、`douyin/logging/douyin_logging_wrapper.py`。 +- 路径与状态:`path_config.py`、`state/reservations.json`。 + +以上补充将帮助运维快速定位截图/OCR/日志相关问题并提供明确采样路径供后续模型/规则优化使用。 + +## 核心模块地图(快捷索引) + +- `run_cli.py`:入口,解析命令行并创建 `fudai_analyse`。 +- `douyin/core/douyin_fudai.py`:主分析器/主循环(`fudai_choujiang`、`run_once_basic`)。 +- `Underlying_Operations.py`:底层设备/截图/OCR/文件操作。 +- `douyin/fudai/douyin_fudai_core.py`:福袋详情解析(`get_fudai_contain`、`basic_join_decision`、`attend_choujiang`)。 +- `douyin/detection/douyin_pixel.py`:像素检测与并行检测实现。 +- `douyin/stage/douyin_stage.py`:阶段诊断入口(`diagnose_stage_from_current_screen`)。 +- `douyin/reservation/douyin_reservation_logic.py`:预约加载与回退处理。 +- `path_config.py`:统一路径获取,避免硬编码。 + +在文档中引用这些文件并包含小示例会帮助维护者快速定位实现点。 + +## 运行流程概览(精简) + +1. `run_cli.py` -> 创建 `fudai_analyse` -> `load_config()` -> `fudai_choujiang()` +2. `fudai_choujiang()` 循环调用 `run_once_basic()` +3. `run_once_basic()` 流程要点: + - 处理等待开奖 / 预约回退 + - 获取截图(`operation.get_screenshot()`) + - 阶段诊断(像素/模板/OCR 回退) + - 根据阶段执行(直播间查找福袋 / 详情页解析 / 结果处理) + +## 故障排查与采样(可直接运行的命令) + +1. 验证截图是否可用: + +```powershell +python -c "from Underlying_Operations import underlying_operations; op=underlying_operations(); print(op.get_screenshot(''))" +``` + +2. 快速语法检查(仓库级): + +```powershell +python -m py_compile $(git ls-files "**/*.py") +``` + +3. 采集 OCR 失败样本(手动或自定义脚本): + +```powershell +# 伪命令示例:运行一段短时日志以产生调试图片 +python run_cli.py --device-id --wait-minutes 1 +# 手动或团队自定义脚本筛选 pic/ 下的失败图片并复制到约定目录(例如 tools/samples/) +``` + +## 预约(state/reservations.json)行为说明 + +- 预约持久化路径:`state/reservations.json`(通过 `path_config.get_reservations_path()` 获取)。 +- 启动策略(当前实现): + - 第一次运行时清空内存预约并可清空文件(避免使用旧历史);后续运行使用内存队列并在变更时写回文件以便外部查看。 + - 文档中应明确“第一次运行语义”以免运维误解。 + +## 分辨率与坐标适配(基准与缩放) + +- 基准分辨率:1080x2400(所有坐标与ROI以此为基准)。 +- 缩放公式(示例): 若基准点为 `(x0,y0)`,设备分辨率为 `(W,H)`,则实际坐标 `x = int(x0 * W / 1080)`,`y = int(y0 * H / 2400)`。 + +建议:在文档中加入 2 个常用坐标示例与验证截图(放置于 `docs/images/`)。 + +## 验证清单(可纳入 CI) + +1. `python -m py_compile` 全仓库通过。 +2. 关键路径存在检查:`run_cli.py`、`Underlying_Operations.py`、`config/config.json`、`path_config.py`。 +3. `path_config.get_reservations_path()` 返回文件夹存在性检查。 + +示例 CI 命令片段: + +```bash +python -m py_compile $(git ls-files "**/*.py") || exit 1 +python - <<'PY' +from path_config import get_reservations_path +import os +print('reservations path', get_reservations_path()) +assert os.path.isdir(os.path.dirname(get_reservations_path())) +PY +``` + +## FAQ(快速) + +- Q: 如何跳过 OCR 初始化以加速冷启动? + - A: 设置环境变量 `SKIP_OCR_INIT=1`。 +- Q: 截图镜像到外部目录导致性能问题怎么办? + - A: 设置 `DISABLE_SCREENSHOT_MIRROR=1`。 +- Q: 日志在哪查看? + - A: 参见 `douyin/logging/douyin_logging.py` 配置的 `file_path`(默认 `logs/unified.log`)。 + +## 下一步建议(可选交付) + +1. 在 `docs/images/` 添加 2 个运行时截图(基准 1080x2400),用于快速视觉检查。 +2. 将“硬编码坐标扫描”脚本放入 `tools/` 并在 CI 中运行,生成 `tools/coords_report.csv`。 +3. 将本文的验证清单脚本加入 `.github/workflows/`(可选)。 --- -如果需要,我可以先运行“硬编码坐标扫描”并把结果放到 `tools/coords_report.csv`,或开始收集 OCR 失败样本。 +如果你确认,我会: +1. 备份当前文档为 `docs/完整技术文档.md.bak`(可选) +2. 将以上内容写入 `docs/完整技术文档.md` +3. 更新任务清单(TODO)并开始下一项(补充快速开始示例截图与 coords 扫描脚本)。 + ```javascript @@ -6458,6 +6544,7 @@ debug_logger.log_exception(e, context={"step": "处理福袋"}) **行为日志文件**: `logs/actions.log` - 轮转文件(最大10MB,保留5个备份) - 包含操作记录和耗时信息 +- 每行支持 `log_type` 内容(如 `OP`, `ERR`, `DEBUG`, `SCREENSHOT`, `PERF`)以区分操作、错误、调试、截图、性能等类型;同一条输出来自 `analyser._log_kv` 的 `log_type` 或自动推断结果,GUI 侧可以据此高亮/过滤。 **错误日志文件**: `logs/errors.log` - 轮转文件(最大10MB,保留5个备份) diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index 4dba3df..adcb430 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,5 +1,5 @@ { - "updated_ts": 1767373375.3158991, + "updated_ts": 1767383106.9903107, "reason": "startup_clear", "room_pos": 0, "current_room_title": "", diff --git a/douyin/fudai/core/fudai_detail_reader.py b/douyin/fudai/core/fudai_detail_reader.py index 7839325..1a5c9ed 100644 --- a/douyin/fudai/core/fudai_detail_reader.py +++ b/douyin/fudai/core/fudai_detail_reader.py @@ -7,6 +7,7 @@ from __future__ import annotations import re import time +import os from typing import Tuple, Any from concurrent.futures import ThreadPoolExecutor @@ -425,6 +426,27 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo countdown_ss_raw = None value_raw = None + # 读取配置开关:优先使用 analyser 属性覆盖,其次读取 config.json + try: + disable_content_recognition = bool( + getattr(analyser, "fudai_disable_content_recognition", False) + ) + except Exception: + disable_content_recognition = False + if not disable_content_recognition: + try: + import json + + cfg_path = path_config.get_config_path() + if cfg_path and os.path.exists(cfg_path): + with open(cfg_path, "r", encoding="utf-8") as f: + cfg = json.load(f) + disable_content_recognition = bool( + cfg.get("fudai_disable_content_recognition", False) + ) + except Exception: + pass + def ocr_task_list(): """OCR识别任务列表(用于检测观看任务)""" try: @@ -447,6 +469,15 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo def ocr_content(): """OCR识别福袋内容""" + if disable_content_recognition: + try: + analyser._log_kv( + "福袋", + "跳过福袋内容OCR识别(配置启用)", + ) + except Exception: + pass + return None try: from douyin.utils.ocr_preprocess import preprocess_for_ocr @@ -647,6 +678,15 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo return None def ocr_content_fallback(): + if disable_content_recognition: + try: + analyser._log_kv( + "福袋", + "跳过备用福袋内容OCR识别(配置启用)", + ) + except Exception: + pass + return None try: return analyser.operation.analyse_pic_word("福袋内容", 0) except Exception as e_inner: diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index 178c411..68f97f6 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -697,10 +697,40 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass + # 读取配置开关:优先使用 analyser 属性覆盖,其次读取 config.json + try: + disable_content_recognition = bool( + getattr(analyser, "fudai_disable_content_recognition", False) + ) + except Exception: + disable_content_recognition = False + if not disable_content_recognition: + try: + import json + + cfg_path = path_config.get_config_path() + if cfg_path and os.path.exists(cfg_path): + with open(cfg_path, "r", encoding="utf-8") as f: + cfg = json.load(f) + disable_content_recognition = bool( + cfg.get("fudai_disable_content_recognition", False) + ) + except Exception: + pass + def ocr_content(): """OCR识别福袋内容""" start = time.time() try: + if disable_content_recognition: + try: + analyser._log_kv( + "福袋", + "跳过福袋内容OCR识别(配置启用)", + ) + except Exception: + pass + return None name_fc = preprocess_for_ocr(analyser, "福袋内容") return analyser.operation.analyse_pic_word(name_fc, 0) except Exception as e_inner: @@ -1175,6 +1205,15 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo return None def ocr_content_fallback(): + if disable_content_recognition: + try: + analyser._log_kv( + "福袋", + "跳过备用福袋内容OCR识别(配置启用)", + ) + except Exception: + pass + return None try: return analyser.operation.analyse_pic_word("福袋内容", 0) except Exception as e_inner2: diff --git a/douyin/handlers/douyin_screenshot_handler.py b/douyin/handlers/douyin_screenshot_handler.py index 1f5167e..84f14f0 100644 --- a/douyin/handlers/douyin_screenshot_handler.py +++ b/douyin/handlers/douyin_screenshot_handler.py @@ -58,6 +58,7 @@ class ScreenshotHandler: x_bottom=x_bottom, y_bottom=y_bottom, y_pianyi=y_pianyi, + log_type="SCREENSHOT", ) except Exception: pass diff --git a/douyin/handlers/douyin_screenshot_manager.py b/douyin/handlers/douyin_screenshot_manager.py index 210f097..bb6a348 100644 --- a/douyin/handlers/douyin_screenshot_manager.py +++ b/douyin/handlers/douyin_screenshot_manager.py @@ -18,6 +18,7 @@ import path_config import threading from queue import Queue, Empty from typing import Any + # 计数与追踪 from datetime import datetime import traceback @@ -25,7 +26,7 @@ import logging import time # 背景保存队列与工作线程(用于异步保存调试图像,避免阻塞主流程) -_debug_save_queue: "Queue[Tuple[Image.Image, str, bool, Optional[Tuple[int,int,int,int]], Optional[dict], str, str, str]]" = Queue() +_debug_save_queue: "Queue[Tuple[Image.Image, str, bool, Optional[Tuple[int,int,int,int]], Optional[dict], str, str, str]]" = (Queue()) _debug_save_worker_started = False # 异步保存计数(用于 GUI 显示) @@ -34,7 +35,9 @@ _async_save_failure_count = 0 _async_save_counters_lock = threading.Lock() # 环境开关:在高频路径中跳过调试图像保存以提升性能(默认启用跳过) -_SKIP_DEBUG_SAVE_IN_HOTLOOPS = bool(os.environ.get("SKIP_DEBUG_SAVE_IN_HOTLOOPS", "1") == "1") +_SKIP_DEBUG_SAVE_IN_HOTLOOPS = bool( + os.environ.get("SKIP_DEBUG_SAVE_IN_HOTLOOPS", "1") == "1" +) def _debug_save_loop() -> None: @@ -59,7 +62,9 @@ def _debug_save_loop() -> None: global _async_save_success_count, _async_save_failure_count try: # 执行同步保存(重复之前 save_debug_image 中的标注与保存逻辑) - def _save_image_with_retry(img_to_save: Image.Image, path: str, max_retries: int = 2) -> bool: + def _save_image_with_retry( + img_to_save: Image.Image, path: str, max_retries: int = 2 + ) -> bool: last_error = None for attempt in range(max_retries): try: @@ -105,7 +110,12 @@ def _debug_save_loop() -> None: x2 = max(0, min(x2, img_w - 1)) y2 = max(0, min(y2, img_h - 1)) if x1 < x2 and y1 < y2: - rect_coords = (float(x1), float(y1), float(x2), float(y2)) + rect_coords = ( + float(x1), + float(y1), + float(x2), + float(y2), + ) draw.rectangle(rect_coords, outline="red", width=2) if extra_info: @@ -126,23 +136,38 @@ def _debug_save_loop() -> None: except Exception: pass try: - actions_log = path_config.get_actions_log_path() - with open(actions_log, "a", encoding="utf-8") as af: - af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存完成: {file_path}\n") + import logging + + logging.getLogger("action_logger").info( + "[调试图像] 异步保存完成: %s", file_path + ) except Exception: pass # 保存完成时的可选日志(原有逻辑) try: import json, logging + cfg_path = path_config.get_config_path() log_on_complete = False if os.path.exists(cfg_path): - with open(cfg_path, "r", encoding="utf-8") as _f: + with open( + cfg_path, "r", encoding="utf-8" + ) as _f: cfg = json.load(_f) - dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {} - log_on_complete = bool(dbg_cfg.get("log_on_complete", False)) + dbg_cfg = ( + cfg.get("debug_captures", {}) + if isinstance( + cfg.get("debug_captures"), dict + ) + else {} + ) + log_on_complete = bool( + dbg_cfg.get("log_on_complete", False) + ) if log_on_complete: - logging.info("[调试图像] 异步保存完成: %s", file_path) + logging.info( + "[调试图像] 异步保存完成: %s", file_path + ) except Exception: pass except Exception: @@ -154,22 +179,39 @@ def _debug_save_loop() -> None: except Exception: pass try: - actions_log = path_config.get_actions_log_path() - with open(actions_log, "a", encoding="utf-8") as af: - af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存完成: {file_path}\n") + import logging + + logging.getLogger("action_logger").info( + "[调试图像] 异步保存完成: %s", file_path + ) except Exception: pass try: import json, logging + cfg_path = path_config.get_config_path() log_on_complete = False if os.path.exists(cfg_path): - with open(cfg_path, "r", encoding="utf-8") as _f: + with open( + cfg_path, "r", encoding="utf-8" + ) as _f: cfg = json.load(_f) - dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {} - log_on_complete = bool(dbg_cfg.get("log_on_complete", False)) + dbg_cfg = ( + cfg.get("debug_captures", {}) + if isinstance( + cfg.get("debug_captures"), dict + ) + else {} + ) + log_on_complete = bool( + dbg_cfg.get( + "log_on_complete", False + ) + ) if log_on_complete: - logging.info("[调试图像] 异步保存完成: %s", file_path) + logging.info( + "[调试图像] 异步保存完成: %s", file_path + ) except Exception: pass except Exception: @@ -177,9 +219,15 @@ def _debug_save_loop() -> None: try: logs_dir = path_config.get_logs_dir() os.makedirs(logs_dir, exist_ok=True) - err_path = os.path.join(logs_dir, "async_debug_save_errors.log") - with open(err_path, "a", encoding="utf-8") as ef: - ef.write(f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n") + err_path = os.path.join( + logs_dir, "async_debug_save_errors.log" + ) + with open( + err_path, "a", encoding="utf-8" + ) as ef: + ef.write( + f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n" + ) ef.write(traceback.format_exc()) ef.write("\n\n") except Exception: @@ -190,9 +238,11 @@ def _debug_save_loop() -> None: except Exception: pass try: - actions_log = path_config.get_actions_log_path() - with open(actions_log, "a", encoding="utf-8") as af: - af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存失败: {file_path}\n") + import logging + + logging.getLogger("action_logger").info( + "[调试图像] 异步保存失败: %s", file_path + ) except Exception: pass # 捕获标注过程中的任何异常,避免线程退出 @@ -208,20 +258,29 @@ def _debug_save_loop() -> None: except Exception: pass try: - actions_log = path_config.get_actions_log_path() - with open(actions_log, "a", encoding="utf-8") as af: - af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存完成: {file_path}\n") + import logging + + logging.getLogger("action_logger").info( + "[调试图像] 异步保存完成: %s", file_path + ) except Exception: pass try: import json, logging + cfg_path = path_config.get_config_path() log_on_complete = False if os.path.exists(cfg_path): with open(cfg_path, "r", encoding="utf-8") as _f: cfg = json.load(_f) - dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {} - log_on_complete = bool(dbg_cfg.get("log_on_complete", False)) + dbg_cfg = ( + cfg.get("debug_captures", {}) + if isinstance(cfg.get("debug_captures"), dict) + else {} + ) + log_on_complete = bool( + dbg_cfg.get("log_on_complete", False) + ) if log_on_complete: logging.info("[调试图像] 异步保存完成: %s", file_path) except Exception: @@ -231,9 +290,13 @@ def _debug_save_loop() -> None: try: logs_dir = path_config.get_logs_dir() os.makedirs(logs_dir, exist_ok=True) - err_path = os.path.join(logs_dir, "async_debug_save_errors.log") + err_path = os.path.join( + logs_dir, "async_debug_save_errors.log" + ) with open(err_path, "a", encoding="utf-8") as ef: - ef.write(f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n") + ef.write( + f"[{datetime.now().isoformat()}] 保存失败: {file_path}\n" + ) ef.write(traceback.format_exc()) ef.write("\n\n") except Exception: @@ -244,9 +307,11 @@ def _debug_save_loop() -> None: except Exception: pass try: - actions_log = path_config.get_actions_log_path() - with open(actions_log, "a", encoding="utf-8") as af: - af.write(f"[{datetime.now().isoformat()}] [调试图像] 异步保存失败: {file_path}\n") + import logging + + logging.getLogger("action_logger").info( + "[调试图像] 异步保存失败: %s", file_path + ) except Exception: pass except Exception: @@ -1131,7 +1196,9 @@ def save_debug_image( # type: ignore base_parts = [timestamp] if operation_type: # 转换为中文 - operation_type_cn = _OPERATION_TYPE_CN.get(operation_type, operation_type) + operation_type_cn = _OPERATION_TYPE_CN.get( + operation_type, operation_type + ) base_parts.append(_sanitize_filename_part(operation_type_cn)) if picname: # 转换为中文 @@ -1180,11 +1247,16 @@ def save_debug_image( # type: ignore if background is None: 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: cfg = json.load(f) - dbg_cfg = cfg.get("debug_captures", {}) if isinstance(cfg.get("debug_captures"), dict) else {} + dbg_cfg = ( + cfg.get("debug_captures", {}) + if isinstance(cfg.get("debug_captures"), dict) + else {} + ) background = bool(dbg_cfg.get("async_save", True)) else: background = True @@ -1210,7 +1282,9 @@ def save_debug_image( # type: ignore except Exception as dir_error: # 记录目录创建失败 try: - print(f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}") + print( + f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}" + ) except Exception: pass else: @@ -1243,9 +1317,17 @@ def save_debug_image( # type: ignore if background: try: # 如果在高频路径中要求跳过调试保存(通过环境变量控制),则直接跳过以免阻塞或占用IO - if _SKIP_DEBUG_SAVE_IN_HOTLOOPS and operation_type in ("pixel_detect", "cut_pic", "pixel"): + if _SKIP_DEBUG_SAVE_IN_HOTLOOPS and operation_type in ( + "pixel_detect", + "cut_pic", + "pixel", + ): try: - logging.debug("[截图管理] 跳过热路径调试保存: %s %s", operation_type, picname) + logging.debug( + "[截图管理] 跳过热路径调试保存: %s %s", + operation_type, + picname, + ) except Exception: pass return None @@ -1257,11 +1339,25 @@ def save_debug_image( # type: ignore img_copy = image t0 = time.time() _debug_save_queue.put( - (img_copy, file_path, annotate, coords, extra_info, operation_type, picname, step) + ( + img_copy, + file_path, + annotate, + coords, + extra_info, + operation_type, + picname, + step, + ) ) dur_enqueue = (time.time() - t0) * 1000.0 try: - logging.debug("[截图管理] 异步入队耗时(ms): %.1f op=%s pic=%s", dur_enqueue, operation_type, picname) + logging.debug( + "[截图管理] 异步入队耗时(ms): %.1f op=%s pic=%s", + dur_enqueue, + operation_type, + picname, + ) except Exception: pass return None @@ -1317,14 +1413,27 @@ def save_debug_image( # type: ignore # 坐标与额外信息优先展示重要字段 if coords: - info_lines.append(f"coords: ({coords[0]},{coords[1]})-({coords[2]},{coords[3]})") + info_lines.append( + f"coords: ({coords[0]},{coords[1]})-({coords[2]},{coords[3]})" + ) if extra_info: # 组织额外信息为若干行,按重要字段顺序展示 - important_keys = ["result", "detected_x", "detected_x_scaled", "match_score", "mode", "size", "avg_confidence", "text_preview"] + important_keys = [ + "result", + "detected_x", + "detected_x_scaled", + "match_score", + "mode", + "size", + "avg_confidence", + "text_preview", + ] for key in important_keys: if key in extra_info: - info_lines.append(f"{_EXTRA_INFO_KEY_CN.get(key, key)}: {extra_info.get(key)}") + info_lines.append( + f"{_EXTRA_INFO_KEY_CN.get(key, key)}: {extra_info.get(key)}" + ) # 将其余的键也加入(但限制长度) for k, v in extra_info.items(): if k in important_keys: @@ -1348,6 +1457,7 @@ def save_debug_image( # type: ignore padding_h = 8 max_width = annotated_image.size[0] - padding_h * 2 lines_to_draw = [] + # Helper to measure text size in a Pillow-version-safe way. def _measure_text(text: str): try: @@ -1373,7 +1483,11 @@ def save_debug_image( # type: ignore # Last resort: ImageDraw.textsize (may not exist in Pillow >= 10) if hasattr(odraw, "textsize"): try: - return odraw.textsize(text, font=font) if font is not None else odraw.textsize(text) + return ( + odraw.textsize(text, font=font) + if font is not None + else odraw.textsize(text) + ) except Exception: pass except Exception: @@ -1386,7 +1500,9 @@ def save_debug_image( # type: ignore w, h = _measure_text(line) if w > max_width: # 估算每行能容纳的字符数并切断 - approx_chars = max(10, int(len(line) * max_width / max(int(w), 1))) + approx_chars = max( + 10, int(len(line) * max_width / max(int(w), 1)) + ) lines_to_draw.append(line[:approx_chars] + "...") else: lines_to_draw.append(line) @@ -1402,17 +1518,26 @@ def save_debug_image( # type: ignore bar_y2 = img_h # 绘制半透明白色底栏 - odraw.rectangle((0, bar_y1, img_w, bar_y2), fill=(255, 255, 255, 200)) + odraw.rectangle( + (0, bar_y1, img_w, bar_y2), fill=(255, 255, 255, 200) + ) # 绘制文字(黑色) text_x = padding_h text_y = bar_y1 + padding_v for line in lines_to_draw: try: - odraw.text((text_x, text_y), line, fill=(10, 10, 10, 255), font=font) + odraw.text( + (text_x, text_y), + line, + fill=(10, 10, 10, 255), + font=font, + ) except Exception: try: - odraw.text((text_x, text_y), line, fill=(10, 10, 10, 255)) + odraw.text( + (text_x, text_y), line, fill=(10, 10, 10, 255) + ) except Exception: pass text_y += line_height @@ -1421,17 +1546,33 @@ def save_debug_image( # type: ignore try: if extra_info: # 模板匹配提供 match_coords 字段(tuple) - if "match_coords" in extra_info and isinstance(extra_info["match_coords"], (list, tuple)) and len(extra_info["match_coords"]) == 4: + if ( + "match_coords" in extra_info + and isinstance( + extra_info["match_coords"], (list, tuple) + ) + and len(extra_info["match_coords"]) == 4 + ): mx1, my1, mx2, my2 = extra_info["match_coords"] # 在 overlay 上画红框 - odraw.rectangle((mx1, my1, mx2, my2), outline=(255, 0, 0, 200), width=2) + odraw.rectangle( + (mx1, my1, mx2, my2), + outline=(255, 0, 0, 200), + width=2, + ) # 像素检测提供 detected_x_scaled:图像坐标系中的x(单点),并依赖 coords 提供 y 区域 elif "detected_x_scaled" in extra_info and coords: try: dx = int(extra_info["detected_x_scaled"]) cy = (coords[1] + coords[3]) // 2 - r = max(4, int(min(annotated_image.size) * 0.01)) - odraw.ellipse([dx - r, cy - r, dx + r, cy + r], fill=(0, 128, 255, 220), outline=(0, 64, 192, 220)) + r = max( + 4, int(min(annotated_image.size) * 0.01) + ) + odraw.ellipse( + [dx - r, cy - r, dx + r, cy + r], + fill=(0, 128, 255, 220), + outline=(0, 64, 192, 220), + ) except Exception: pass except Exception: @@ -1439,7 +1580,9 @@ def save_debug_image( # type: ignore # 合并 overlay 到原图并保存 try: - annotated_image = Image.alpha_composite(annotated_image, overlay) + annotated_image = Image.alpha_composite( + annotated_image, overlay + ) # 转回 RGB 保存为PNG,以减少兼容问题 annotated_image = annotated_image.convert("RGB") except Exception: diff --git a/douyin/logging/action_logger.py b/douyin/logging/action_logger.py index 1e0245b..143b473 100644 --- a/douyin/logging/action_logger.py +++ b/douyin/logging/action_logger.py @@ -25,13 +25,48 @@ if not _logger.handlers: actions_log_path = os.path.join(log_dir, "actions.log") - # 创建轮转文件处理器 + # 创建轮转文件处理器(使用 SafeRotatingFileHandler 以应对 Windows 上文件被外部程序占用导致的重命名失败) + import time + import shutil from logging.handlers import RotatingFileHandler - _file_handler = RotatingFileHandler( + + class SafeRotatingFileHandler(RotatingFileHandler): + """在 rotate 时对 PermissionError 做重试与回退拷贝,减少因外部进程占用文件导致的异常""" + + def rotate(self, source: str, dest: str) -> None: # type: ignore[override] + try: + super().rotate(source, dest) + return + except PermissionError: + # 重试若干次(短等待),常见于文件被短期占用 + for attempt in range(3): + try: + time.sleep(0.1 * (attempt + 1)) + super().rotate(source, dest) + return + except PermissionError: + continue + + # 回退方案:尝试拷贝到目标文件然后截断原文件 + try: + shutil.copy2(source, dest) + try: + with open(source, "w", encoding=getattr(self, "encoding", None) or "utf-8"): + pass + except Exception: + pass + return + except Exception: + try: + super().rotate(source, dest) + except Exception: + return + + _file_handler = SafeRotatingFileHandler( actions_log_path, - maxBytes=10*1024*1024, # 10MB + maxBytes=10 * 1024 * 1024, # 10MB backupCount=5, - encoding='utf-8' + encoding="utf-8", ) _file_handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s')) _logger.addHandler(_file_handler) diff --git a/douyin/logging/douyin_logging_wrapper.py b/douyin/logging/douyin_logging_wrapper.py index 94ffca9..796192f 100644 --- a/douyin/logging/douyin_logging_wrapper.py +++ b/douyin/logging/douyin_logging_wrapper.py @@ -25,18 +25,29 @@ try: from .debug_logger import DebugLogger # type: ignore[assignment] from .action_logger import ActionLogger # type: ignore[assignment] from .performance_tracker import PerformanceTracker # type: ignore[assignment] + LOGGING_MODULES_AVAILABLE = True except ImportError: # 如果导入失败,提供占位符类 class ErrorLogger: - def log_exception(self, *args, **kwargs): pass + def log_exception(self, *args, **kwargs): + pass + class DebugLogger: - def log_variable(self, *args, **kwargs): pass + def log_variable(self, *args, **kwargs): + pass + class ActionLogger: - def log_step(self, *args, **kwargs): pass + def log_step(self, *args, **kwargs): + pass + class PerformanceTracker: - def end_timer(self, *args, **kwargs): pass - def get_statistics(self, *args, **kwargs): return {} + def end_timer(self, *args, **kwargs): + pass + + def get_statistics(self, *args, **kwargs): + return {} + LOGGING_MODULES_AVAILABLE = False # 初始化日志模块实例 @@ -78,6 +89,50 @@ class LoggingWrapper: if log_level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"): log_level = "INFO" + # 支持可选的 log_type 字段,用于区分行为日志类型(OP/ERR/DEBUG/SCREENSHOT/PERF) + # 优先使用 fields 中的 `log_type` 或 `type`,并从 fields 中移除以避免重复输出 + raw_log_type = None + if "log_type" in fields: + raw_log_type = fields.pop("log_type") + elif "type" in fields: + raw_log_type = fields.pop("type") + + log_type = None + if raw_log_type: + try: + log_type_str = str(raw_log_type).strip().upper() + # 归一化常见类型 + if log_type_str in ("ERROR", "ERR", "E"): + log_type = "ERR" + elif log_type_str in ("DEBUG", "DBG", "D"): + log_type = "DEBUG" + elif log_type_str in ("SCREENSHOT", "PIC", "IMG"): + log_type = "SCREENSHOT" + elif log_type_str in ("PERF", "性能"): + log_type = "PERF" + else: + log_type = "OP" + except Exception: + log_type = "OP" + # 如果没有显式提供 log_type,尝试根据 tag 推断(保持向后兼容) + if not log_type: + try: + tag_str = str(tag or "").lower() + if any(k in tag_str for k in ("错", "异常", "error", "err")): + log_type = "ERR" + elif any(k in tag_str for k in ("调试", "debug", "dbg")): + log_type = "DEBUG" + elif any( + k in tag_str for k in ("截图", "图像", "screenshot", "pic", "img") + ): + log_type = "SCREENSHOT" + elif any(k in tag_str for k in ("性能", "耗时", "步骤耗时", "perf")): + log_type = "PERF" + else: + log_type = "OP" + except Exception: + log_type = "OP" + # 递增日志序号 try: analyser._log_seq += 1 @@ -161,6 +216,9 @@ class LoggingWrapper: log_parts.append(f"[{timestamp}]") log_parts.append(f"[{log_level}]") log_parts.append(f"[{tag}]") + # 如果有 log_type,则在可读日志中加入类型标记,方便过滤与配色 + if log_type: + log_parts.append(f"[{log_type}]") # 添加调用者信息(如果获取成功) if caller_info: @@ -361,6 +419,11 @@ class LoggingWrapper: action_parts.append(tag) else: action_parts.append("[日志]") + + # 在行为日志中也写入类型标签,便于按类型过滤(例如 ERR/DEBUG/SCREENSHOT/PERF/OP) + if log_type: + action_parts.append(f"[{log_type}]") + action_parts.append(action_desc) if elapsed_str: @@ -375,6 +438,7 @@ class LoggingWrapper: # 使用统一的路径配置 try: import path_config + actions_log_path = path_config.get_actions_log_path() log_dir = path_config.get_logs_dir() except Exception: @@ -397,22 +461,39 @@ class LoggingWrapper: analyser._last_action_tag is not None and analyser._last_action_tag != current_tag ): - # 标签变化,添加分隔符(增加到80个等号) - with open( - actions_log_path, "a", encoding="utf-8-sig", errors="replace" - ) as f: - f.write("=" * 80 + "\n") - f.flush() + # 如果标签变化,添加分隔符(增加到80个等号) + try: + import logging - # 更新上一个标签 - analyser._last_action_tag = current_tag + action_logger = logging.getLogger("action_logger") + # 使用 action_logger 写入,避免直接打开文件导致与 RotatingFileHandler 冲突 + if ( + analyser._last_action_tag is not None + and analyser._last_action_tag != current_tag + ): + action_logger.info("=" * 80) - # 写入日志行 - with open( - actions_log_path, "a", encoding="utf-8-sig", errors="replace" - ) as f: - f.write(action_log_line + "\n") - f.flush() + analyser._last_action_tag = current_tag + + # 写入精简行为日志行到 action_logger,让文件处理由 RotatingFileHandler 管理 + action_logger.info(action_log_line) + except Exception: + # 回退到直接写文件(兼容场景) + if log_dir: + with open( + actions_log_path, + "a", + encoding="utf-8-sig", + errors="replace", + ) as f: + if ( + analyser._last_action_tag is not None + and analyser._last_action_tag != current_tag + ): + f.write("=" * 80 + "\n") + analyser._last_action_tag = current_tag + f.write(action_log_line + "\n") + f.flush() except Exception: pass @@ -497,7 +578,11 @@ class LoggingWrapper: # 优化:只写入文件,不输出到控制台(避免与 print 重复) level = getattr(logging, log_level, logging.INFO) # 临时禁用控制台输出,只写入文件 - console_handlers = [h for h in root_logger.handlers if isinstance(h, logging.StreamHandler) and h.stream == sys.stdout] + console_handlers = [ + h + for h in root_logger.handlers + if isinstance(h, logging.StreamHandler) and h.stream == sys.stdout + ] for handler in console_handlers: handler.setLevel(logging.CRITICAL + 1) # 临时禁用 @@ -510,7 +595,9 @@ class LoggingWrapper: extra={"caller": caller_info}, ) else: - root_logger.log(level, log_message, extra={"caller": caller_info}) + root_logger.log( + level, log_message, extra={"caller": caller_info} + ) finally: # 恢复控制台输出级别 for handler in console_handlers: @@ -524,7 +611,9 @@ class LoggingWrapper: # 如果标准 logging 写入失败,记录详细错误信息并尝试使用根 logger 写入(作为备用) try: if _error_logger: - _error_logger.log_exception(e, context={"tag": tag, "caller": caller_info}) + _error_logger.log_exception( + e, context={"tag": tag, "caller": caller_info} + ) except Exception: pass @@ -625,7 +714,7 @@ class LoggingWrapper: analyser: Any, exc: BaseException, context: Optional[Dict[str, Any]] = None, - level: str = "ERROR" + level: str = "ERROR", ) -> None: """使用错误日志模块记录异常及上下文信息""" if LOGGING_MODULES_AVAILABLE and _error_logger: @@ -636,9 +725,13 @@ class LoggingWrapper: # 同时记录到标准日志 LoggingWrapper.enhanced_log_kv( - analyser, "错误", f"{type(exc).__name__}: {exc}", - level=level, exception_type=type(exc).__name__, - exception_message=str(exc), context=context or {} + analyser, + "错误", + f"{type(exc).__name__}: {exc}", + level=level, + exception_type=type(exc).__name__, + exception_message=str(exc), + context=context or {}, ) @staticmethod @@ -646,7 +739,7 @@ class LoggingWrapper: analyser: Any, step_name: str, elapsed_seconds: float, - details: Optional[Dict[str, Any]] = None + details: Optional[Dict[str, Any]] = None, ) -> None: """记录性能步骤信息""" if LOGGING_MODULES_AVAILABLE and _performance_tracker: @@ -673,11 +766,7 @@ class LoggingWrapper: ) @staticmethod - def log_debug_info( - analyser: Any, - message: str, - **context: Any - ) -> None: + def log_debug_info(analyser: Any, message: str, **context: Any) -> None: """记录调试信息""" if LOGGING_MODULES_AVAILABLE and _debug_logger: try: diff --git a/douyin/utils/douyin_helpers.py b/douyin/utils/douyin_helpers.py index 24f0c01..a1cb6ca 100644 --- a/douyin/utils/douyin_helpers.py +++ b/douyin/utils/douyin_helpers.py @@ -127,7 +127,7 @@ class HelperFunctions: name_res = preprocess_for_ocr(analyser, "开奖结果按钮") ocr_text = str(analyser.operation.analyse_pic_word(name_res, 0) or "") - analyser._log_kv("开奖结果", "OCR识别结果", text=ocr_text) # type: ignore[attr-defined, reportPrivateUsage] + analyser._log_kv("开奖结果", "OCR识别结果", text=ocr_text, log_type="SCREENSHOT") # type: ignore[attr-defined, reportPrivateUsage] # 检查识别到的文本 if "我知道了" in ocr_text: @@ -140,14 +140,20 @@ class HelperFunctions: # 检查是否为误识别(检查相似字记录) if HelperFunctions._is_false_positive_prize_text(ocr_text): analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] - "开奖结果", "识别到相似字,判定为误识别", text=ocr_text + "开奖结果", + "识别到相似字,判定为误识别", + text=ocr_text, + log_type="SCREENSHOT", ) return None # 如果文本不完全匹配"立即领取奖品",记录相似字用于后续检查 if ocr_text.strip() != "立即领取奖品": HelperFunctions._save_false_positive(ocr_text) analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] - "开奖结果", "记录相似字文本", text=ocr_text + "开奖结果", + "记录相似字文本", + text=ocr_text, + log_type="SCREENSHOT", ) return "立即领取奖品" else: @@ -165,20 +171,26 @@ class HelperFunctions: # 检查是否为误识别(检查相似字记录) if HelperFunctions._is_false_positive_prize_text(ocr_text_1): analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] - "开奖结果", "识别到相似字,判定为误识别", text=ocr_text_1 + "开奖结果", + "识别到相似字,判定为误识别", + text=ocr_text_1, + log_type="SCREENSHOT", ) return None # 如果文本不完全匹配"立即领取奖品",记录相似字用于后续检查 if ocr_text_1.strip() != "立即领取奖品": HelperFunctions._save_false_positive(ocr_text_1) analyser._log_kv( # type: ignore[attr-defined, reportPrivateUsage] - "开奖结果", "记录相似字文本", text=ocr_text_1 + "开奖结果", + "记录相似字文本", + text=ocr_text_1, + log_type="SCREENSHOT", ) return "立即领取奖品" return None except Exception as e: - analyser._log_kv("开奖结果", "OCR识别异常", error=str(e)) # type: ignore[attr-defined, reportPrivateUsage] + analyser._log_kv("开奖结果", "OCR识别异常", error=str(e), log_type="ERR") # type: ignore[attr-defined, reportPrivateUsage] return None @staticmethod # type: ignore[misc] diff --git a/fudai_detail_modules/fudai_detail_reader.py b/fudai_detail_modules/fudai_detail_reader.py index 918a114..7eae62a 100644 --- a/fudai_detail_modules/fudai_detail_reader.py +++ b/fudai_detail_modules/fudai_detail_reader.py @@ -60,6 +60,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: countdown_parse_ms=countdown_parse_ms, screenshot_reused=bool(screenshot_reused), tag=tag, + log_type="PERF", ) except Exception: pass @@ -76,6 +77,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "福袋详情", "read_fudai_detail_once:从阶段检测获取任务数量(无需截图)", task_count=task_count, + log_type="OP", ) except Exception: pass @@ -86,6 +88,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "福袋详情", "read_fudai_detail_once:警告:阶段检测未保存任务数量(可能为None)", task_count_from_stage=task_count_from_stage, + log_type="OP", ) except Exception: pass @@ -108,13 +111,19 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "福袋详情", "read_fudai_detail_once:任务数量为0,不在福袋详情页,跳过截图和OCR", task_count=task_count, + log_type="OP", ) except Exception: pass now = time.time() tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time - analyser._log_kv("福袋详情", "read_fudai_detail_once完成(任务数量为0)", elapsed_seconds=round(elapsed, 2)) + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once完成(任务数量为0)", + elapsed_seconds=round(elapsed, 2), + log_type="OP", + ) _log_perf("taskcount_zero") return "error", tup_err, {"reason": "not_in_fudai_detail", "task_count": task_count} @@ -155,6 +164,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "read_fudai_detail_once:复用阶段诊断截图", reason="stage_diagnosed_task_count_gt_zero", path=pic_path, + log_type="SCREENSHOT", ) except Exception: pass @@ -165,6 +175,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "read_fudai_detail_once:无法复用阶段诊断截图(文件不可用)", path=pic_path, size=os.path.getsize(pic_path) if os.path.exists(pic_path) else 0, + log_type="SCREENSHOT", ) except Exception: pass @@ -223,7 +234,14 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: if pic_rgb is None: try: - analyser._log_kv("福袋详情", "read_fudai_detail_once:无法读取截图,跳过识别") + try: + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once:无法读取截图,跳过识别", + log_type="SCREENSHOT", + ) + except Exception: + pass except Exception: pass now = time.time() @@ -251,29 +269,30 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: service_stop_ms = round((time.time() - _svc0) * 1000, 1) try: analyser._log_kv( - "截图服务", - "OCR密集操作期间停止后台截图服务", - reason="prevent_background_screenshots_during_ocr" - ) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( # pyright: ignore[reportPrivateUsage] - "截图服务", - "停止后台截图服务失败", - error=str(e), - level="WARNING" - ) - except Exception: # pyright: ignore[reportTooBroadExceptionType] - pass - - try: - ocr_start = time.time() - content, time_text, participants, copies, prize_value_yuan = get_fudai_contain( - analyser, renwu=task_count - ) - ocr_end = time.time() + try: + import traceback + tb = traceback.format_exc() + # 先尝试通过 analyser._log_kv 输出完整 trace(如果可用) + try: + analyser._log_kv( # pyright: ignore[reportPrivateUsage] + "福袋详情", + "read_fudai_detail_once 异常", + error=str(e), + error_type=type(e).__name__, + traceback=tb, + log_type="ERR", + ) + except Exception: # pyright: ignore[reportTooBroadExceptionType] + # fallback: 将 traceback 写入统一错误日志 + try: + import path_config + err_log = path_config.get_error_log_path() + with open(err_log, "a", encoding="utf-8") as ef: + ef.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] read_fudai_detail_once 异常: {e}\n") + ef.write(tb) + ef.write("\n") + except Exception: + pass _log_perf("after_get_fudai_contain") except Exception as e: # pyright: ignore[reportTooBroadExceptionType] # 出现异常时,记录详细错误和 traceback 并返回占位结果,便于排查 @@ -309,7 +328,12 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time try: - analyser._log_kv("福袋详情", "read_fudai_detail_once完成(识别异常)", elapsed_seconds=round(elapsed, 2)) # pyright: ignore[reportPrivateUsage] + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once完成(识别异常)", + elapsed_seconds=round(elapsed, 2), + log_type="ERR", + ) # pyright: ignore[reportPrivateUsage] except Exception: # pyright: ignore[reportTooBroadExceptionType] pass _log_perf("exception_in_get_fudai_contain") @@ -415,10 +439,11 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "福袋", f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析 level="DEBUG", + log_type="DEBUG", ) analyser._log_kv( "福袋详情", - f"read_fudai_detail_once 完整识别结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒", + f"read_fudai_detail_once 完整识別結果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒", status="ok", room_title=room_title, room_title_raw=room_title_raw, @@ -436,13 +461,14 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: remain_seconds=remain_seconds, elapsed_seconds=round(time.time() - start_time, 2), level="DEBUG", + log_type="DEBUG", ) # 输出到行为日志(使用更详细的格式) content_preview = (content or "")[:60] if content else "未识别到" analyser._log_kv( "行为", - f"识别福袋详情完成:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒", + f"识别福袋详情完成:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识別'},剩余{remain_seconds}秒", action="识别福袋详情", result="成功", detail={ @@ -459,6 +485,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: "剩余秒数": remain_seconds, }, level="DEBUG", + log_type="OP", ) # 输出简化的运行日志(兼容原有格式) @@ -475,6 +502,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: countdown_end=countdown_end, task_count=task_count, level="DEBUG", + log_type="DEBUG", ) except Exception as e: # 如果详细日志输出失败,至少输出基本信息 @@ -494,7 +522,13 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: pass elapsed = time.time() - start_time - analyser._log_kv("福袋详情", "read_fudai_detail_once完成(成功)", elapsed_seconds=round(elapsed, 2), level="DEBUG") + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once完成(成功)", + elapsed_seconds=round(elapsed, 2), + level="DEBUG", + log_type="DEBUG", + ) _log_perf("success") return "ok", detail_tuple, extra diff --git a/gui/gui_app.py b/gui/gui_app.py index 0cf811f..99ddc5b 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -38,11 +38,14 @@ except ImportError: # 如果模块不存在,使用空函数作为回退 def get_color_config(theme: str = "litera"): return {} + def apply_operation_color(*args, **kwargs): pass + def get_operation_type(line: str) -> str | None: return None + # 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告) warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning) warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning) @@ -57,6 +60,7 @@ def format_gui_log_line(line: str) -> str: try: # 尝试使用新的日志格式化模块 from gui.components.log_viewer import format_gui_log_line as enhanced_formatter + return enhanced_formatter(line) except ImportError: # 如果新模块不可用,回退到原来的实现 @@ -91,12 +95,7 @@ def format_gui_log_line(line: str) -> str: def _is_score_field(k: str) -> bool: kl = k.lower() - return ( - "score" in kl - or "match" in kl - or "匹配" in k - or "相似" in k - ) + return "score" in kl or "match" in kl or "匹配" in k or "相似" in k # 解析字段 words = msg_part.split() @@ -352,15 +351,23 @@ def main(): value=int(cfg.get("reset_after_swipes", 10) or 10) ) # 流式后台截图开关(默认启用) - streaming_enabled_var = tk.BooleanVar(value=bool(cfg.get("enable_streaming_screenshot", True))) + streaming_enabled_var = tk.BooleanVar( + value=bool(cfg.get("enable_streaming_screenshot", True)) + ) # 按需求:删除"自动养号/随机等待/轻微扰动/定时休息"等设置,仅保留"推荐页养号(爱心/收藏/评论)"配置。 auto_join_var = tk.BooleanVar(value=bool(cfg.get("auto_join_fansclub", False))) fansclub_action_var = tk.StringVar( value=str(cfg.get("fansclub_fail_action", "stay") or "stay").lower() ) - fansclub_click_delay_var = tk.DoubleVar(value=float(cfg.get("fansclub_click_delay", 0.6) or 0.6)) - fansclub_auto_wait_var = tk.DoubleVar(value=float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0)) - fansclub_manual_wait_var = tk.DoubleVar(value=float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0)) + fansclub_click_delay_var = tk.DoubleVar( + value=float(cfg.get("fansclub_click_delay", 0.6) or 0.6) + ) + fansclub_auto_wait_var = tk.DoubleVar( + value=float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0) + ) + fansclub_manual_wait_var = tk.DoubleVar( + value=float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0) + ) # Web端新增配置变量 - 高价值预约相关 high_value_fudai_enabled_var = tk.BooleanVar( @@ -405,6 +412,9 @@ def main(): fudai_icon_max_wait_seconds_var = tk.DoubleVar( value=float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0) ) + fudai_disable_content_recognition_var = tk.BooleanVar( + value=bool(cfg.get("fudai_disable_content_recognition", False)) + ) fudai_click_wait_seconds_var = tk.DoubleVar( value=float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0) ) @@ -608,10 +618,16 @@ def main(): value=bool(cfg.get("logging", {}).get("show_timestamps", True)) ) logging_performance_enabled_var = tk.BooleanVar( - value=bool(cfg.get("logging", {}).get("performance_tracking", {}).get("enabled", True)) + value=bool( + cfg.get("logging", {}).get("performance_tracking", {}).get("enabled", True) + ) ) logging_track_functions_var = tk.BooleanVar( - value=bool(cfg.get("logging", {}).get("performance_tracking", {}).get("track_function_calls", True)) + value=bool( + cfg.get("logging", {}) + .get("performance_tracking", {}) + .get("track_function_calls", True) + ) ) logging_debug_level_var = tk.StringVar( value=str(cfg.get("logging", {}).get("debug_detail_level", "normal")) @@ -623,7 +639,9 @@ def main(): value=str(cfg.get("logging", {}).get("action_log_format", "concise")) ) # GUI 主题变量 - gui_theme_var = tk.StringVar(value=str(cfg.get("gui", {}).get("theme", "litera") or "litera")) + gui_theme_var = tk.StringVar( + value=str(cfg.get("gui", {}).get("theme", "litera") or "litera") + ) # 倒计时小于阈值参数 skip_lt_seconds_var = tk.IntVar( @@ -744,11 +762,32 @@ def main(): row4b = ttk.Frame(cfg_box) row4b.pack(fill=X, padx=10, pady=(0, 8)) ttk.Label(row4b, text="粉丝团点击延迟(s):").pack(side=LEFT) - ttk.Spinbox(row4b, from_=0.1, to=5.0, increment=0.1, textvariable=fansclub_click_delay_var, width=6).pack(side=LEFT, padx=(6, 12)) + ttk.Spinbox( + row4b, + from_=0.1, + to=5.0, + increment=0.1, + textvariable=fansclub_click_delay_var, + width=6, + ).pack(side=LEFT, padx=(6, 12)) ttk.Label(row4b, text="自动加入等待(s):").pack(side=LEFT) - ttk.Spinbox(row4b, from_=0.5, to=10.0, increment=0.5, textvariable=fansclub_auto_wait_var, width=6).pack(side=LEFT, padx=(6, 12)) + ttk.Spinbox( + row4b, + from_=0.5, + to=10.0, + increment=0.5, + textvariable=fansclub_auto_wait_var, + width=6, + ).pack(side=LEFT, padx=(6, 12)) ttk.Label(row4b, text="手动加入等待(s):").pack(side=LEFT) - ttk.Spinbox(row4b, from_=0.5, to=10.0, increment=0.5, textvariable=fansclub_manual_wait_var, width=6).pack(side=LEFT, padx=(6, 0)) + ttk.Spinbox( + row4b, + from_=0.5, + to=10.0, + increment=0.5, + textvariable=fansclub_manual_wait_var, + width=6, + ).pack(side=LEFT, padx=(6, 0)) # 标签页3:高价值预约 reservation_tab_left = ttk.Frame(left_notebook) @@ -983,12 +1022,14 @@ def main(): # 为调试参数标签页添加滚动条 debug_canvas = tk.Canvas(debug_tab, highlightthickness=0) - debug_scrollbar = ttk.Scrollbar(debug_tab, orient="vertical", command=debug_canvas.yview) + debug_scrollbar = ttk.Scrollbar( + debug_tab, orient="vertical", command=debug_canvas.yview + ) debug_scrollable_frame = ttk.Frame(debug_canvas) debug_scrollable_frame.bind( "", - lambda e: debug_canvas.configure(scrollregion=debug_canvas.bbox("all")) + lambda e: debug_canvas.configure(scrollregion=debug_canvas.bbox("all")), ) debug_canvas.create_window((0, 0), window=debug_scrollable_frame, anchor="nw") @@ -996,9 +1037,10 @@ def main(): # 鼠标滚轮支持 def _on_mousewheel(event): - debug_canvas.yview_scroll(int(-1*(event.delta/120)), "units") + debug_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units") + def _on_shift_mousewheel(event): - debug_canvas.xview_scroll(int(-1*(event.delta/120)), "units") + debug_canvas.xview_scroll(int(-1 * (event.delta / 120)), "units") debug_canvas.bind_all("", _on_mousewheel) debug_canvas.bind_all("", _on_shift_mousewheel) @@ -1036,25 +1078,39 @@ def main(): debug_counts_frame = ttk.Frame(debug_r0) debug_counts_frame.pack(side=LEFT, padx=(10, 0)) ttk.Label(debug_counts_frame, text="异步保存:").pack(side=LEFT) - ttk.Label(debug_counts_frame, textvariable=debug_async_success_var, foreground="green").pack(side=LEFT, padx=(4, 8)) + ttk.Label( + debug_counts_frame, textvariable=debug_async_success_var, foreground="green" + ).pack(side=LEFT, padx=(4, 8)) ttk.Label(debug_counts_frame, text="/").pack(side=LEFT) - ttk.Label(debug_counts_frame, textvariable=debug_async_failure_var, foreground="red").pack(side=LEFT, padx=(4, 8)) + ttk.Label( + debug_counts_frame, textvariable=debug_async_failure_var, foreground="red" + ).pack(side=LEFT, padx=(4, 8)) + def on_reset_async_counters(): try: import importlib - douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) douyin_screenshot_manager.reset_async_save_counters() debug_async_success_var.set(0) debug_async_failure_var.set(0) except Exception: pass - ttk.Button(debug_counts_frame, text="重置", command=on_reset_async_counters, width=6).pack(side=LEFT, padx=(6,0)) + + ttk.Button( + debug_counts_frame, text="重置", command=on_reset_async_counters, width=6 + ).pack(side=LEFT, padx=(6, 0)) # 周期性更新计数器(2秒) def _update_async_counters(): try: import importlib - douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) s, f = douyin_screenshot_manager.get_async_save_counters() debug_async_success_var.set(s) debug_async_failure_var.set(f) @@ -1064,6 +1120,7 @@ def main(): debug_r0.after(2000, _update_async_counters) except Exception: pass + # 启动更新循环 try: _update_async_counters() @@ -1151,7 +1208,22 @@ def main(): textvariable=fudai_click_wait_seconds_var, width=6, ).pack(side=LEFT) - ttk.Label(row4d, text="(等待福袋详情页加载,默认1.0秒)").pack(side=LEFT, padx=(6, 0)) + ttk.Label(row4d, text="(等待福袋详情页加载,默认1.0秒)").pack( + side=LEFT, padx=(6, 0) + ) + + row4c = ttk.Frame(fudai_find_box) + row4c.pack(fill=X, padx=10, pady=(0, 8)) + ttk.Checkbutton( + row4c, + text="禁用福袋内容OCR识别", + variable=fudai_disable_content_recognition_var, + onvalue=True, + offvalue=False, + ).pack(side=LEFT) + ttk.Label(row4c, text="(仅影响 content OCR,不改其它识别模块)").pack( + side=LEFT, padx=(6, 0) + ) row4e = ttk.Frame(fudai_find_box) row4e.pack(fill=X, padx=10, pady=(0, 8)) @@ -1164,7 +1236,9 @@ def main(): textvariable=switch_room_wait_after_stage_diag_seconds_var, width=6, ).pack(side=LEFT) - ttk.Label(row4e, text="(阶段检测后等待福袋加载,默认7.0秒)").pack(side=LEFT, padx=(6, 0)) + ttk.Label(row4e, text="(阶段检测后等待福袋加载,默认7.0秒)").pack( + side=LEFT, padx=(6, 0) + ) row4f = ttk.Frame(fudai_find_box) row4f.pack(fill=X, padx=10, pady=(0, 8)) @@ -1177,7 +1251,9 @@ def main(): textvariable=swipe_duration_ms_var, width=6, ).pack(side=LEFT) - ttk.Label(row4f, text="(滑动持续时间,默认600ms,值越大滑动越慢)").pack(side=LEFT, padx=(6, 0)) + ttk.Label(row4f, text="(滑动持续时间,默认600ms,值越大滑动越慢)").pack( + side=LEFT, padx=(6, 0) + ) row4c = ttk.Frame(fudai_find_box) row4c.pack(fill=X, padx=10, pady=(0, 10)) @@ -1190,9 +1266,9 @@ def main(): 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) - ) + ttk.Label( + row4c, text="(0.0~1.0,默认0.8,多边形区域白色像素比例>=此值判定为在直播间)" + ).pack(side=LEFT, padx=(6, 0)) # 阶段诊断时间参数(用于调试) diag_time_box = ttk.LabelFrame(debug_container, text="阶段诊断时间参数") @@ -1256,7 +1332,9 @@ def main(): textvariable=fudai_detail_template_threshold_var, width=8, ).pack(side=LEFT) - ttk.Label(diag_time_r3b, text="(0.0-1.0,默认0.7,区域(398,894)-(658,1179))").pack(side=LEFT, padx=(6, 0)) + ttk.Label( + diag_time_r3b, text="(0.0-1.0,默认0.7,区域(398,894)-(658,1179))" + ).pack(side=LEFT, padx=(6, 0)) diag_time_r4 = ttk.Frame(diag_time_box) diag_time_r4.pack(fill=X, padx=10, pady=(0, 10)) @@ -1350,7 +1428,7 @@ def main(): values=["normal", "detailed", "minimal"], textvariable=logging_debug_level_var, state="readonly", - width=10 + width=10, ).pack(side=LEFT, padx=(0, 20)) ttk.Label(log_r2, text="错误日志详细程度:").pack(side=LEFT) ttk.Combobox( @@ -1358,7 +1436,7 @@ def main(): values=["full", "basic", "minimal"], textvariable=logging_error_level_var, state="readonly", - width=10 + width=10, ).pack(side=LEFT) # 行为日志格式 @@ -1370,7 +1448,7 @@ def main(): values=["concise", "detailed", "minimal"], textvariable=logging_action_format_var, state="readonly", - width=10 + width=10, ).pack(side=LEFT, padx=(0, 20)) ttk.Checkbutton( log_r3, @@ -1387,9 +1465,11 @@ def main(): values=["litera", "flatly", "journal", "minty", "cosmo", "darkly"], textvariable=gui_theme_var, state="readonly", - width=12 + width=12, ).pack(side=LEFT, padx=(6, 0)) - ttk.Label(log_theme_row, text="(更改后请保存并重启以完全应用主题)").pack(side=LEFT, padx=(12,0)) + ttk.Label(log_theme_row, text="(更改后请保存并重启以完全应用主题)").pack( + side=LEFT, padx=(12, 0) + ) # 性能追踪 log_r4 = ttk.Frame(logging_config_box) @@ -1504,20 +1584,23 @@ def main(): fudai_click_wait_seconds_var.set( float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0) ) + fudai_disable_content_recognition_var.set( + bool(cfg.get("fudai_disable_content_recognition", False)) + ) switch_room_wait_after_stage_diag_seconds_var.set( float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0) ) # GUI 主题 try: - gui_theme_var.set(str(cfg.get("gui", {}).get("theme", "litera") or "litera")) + gui_theme_var.set( + str(cfg.get("gui", {}).get("theme", "litera") or "litera") + ) except Exception: gui_theme_var.set("litera") live_room_match_threshold_var.set( float(cfg.get("live_room_match_threshold", 0.8) or 0.8) ) - swipe_duration_ms_var.set( - int(cfg.get("swipe_duration_ms", 600) or 600) - ) + swipe_duration_ms_var.set(int(cfg.get("swipe_duration_ms", 600) or 600)) fudai_quiet_hours_enabled_var.set( bool(cfg.get("fudai_quiet_hours_enabled", True)) ) @@ -1548,11 +1631,13 @@ def main(): ) # 粉丝团等待/点击延迟配置 fansclub_click_delay_var.set(float(cfg.get("fansclub_click_delay", 0.6) or 0.6)) - fansclub_auto_wait_var.set(float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0)) - fansclub_manual_wait_var.set(float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0)) - skip_lt_seconds_var.set( - int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10) + fansclub_auto_wait_var.set( + float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0) ) + fansclub_manual_wait_var.set( + float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0) + ) + skip_lt_seconds_var.set(int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10)) # 调试图像清理配置 debug_captures_config = cfg.get("debug_captures", {}) @@ -1718,15 +1803,16 @@ def main(): cfg2["fudai_click_wait_seconds"] = float( fudai_click_wait_seconds_var.get() or 2.0 ) + cfg2["fudai_disable_content_recognition"] = bool( + fudai_disable_content_recognition_var.get() + ) cfg2["switch_room_wait_after_stage_diag_seconds"] = float( switch_room_wait_after_stage_diag_seconds_var.get() or 7.0 ) cfg2["live_room_match_threshold"] = float( live_room_match_threshold_var.get() or 0.8 ) - cfg2["swipe_duration_ms"] = int( - swipe_duration_ms_var.get() or 600 - ) + cfg2["swipe_duration_ms"] = int(swipe_duration_ms_var.get() or 600) cfg2["fudai_quiet_hours_enabled"] = bool(fudai_quiet_hours_enabled_var.get()) cfg2["fudai_quiet_start_hour"] = int(fudai_quiet_start_hour_var.get() or 0) cfg2["fudai_quiet_end_hour"] = int(fudai_quiet_end_hour_var.get() or 0) @@ -1755,16 +1841,18 @@ def main(): ) # 粉丝团等待/点击延迟配置 cfg2["fansclub_click_delay"] = float(fansclub_click_delay_var.get() or 0.6) - cfg2["fansclub_auto_join_wait_seconds"] = float(fansclub_auto_wait_var.get() or 5.0) - cfg2["fansclub_manual_wait_seconds"] = float(fansclub_manual_wait_var.get() or 3.0) + cfg2["fansclub_auto_join_wait_seconds"] = float( + fansclub_auto_wait_var.get() or 5.0 + ) + cfg2["fansclub_manual_wait_seconds"] = float( + fansclub_manual_wait_var.get() or 3.0 + ) cfg2["skip_if_countdown_lt_seconds"] = int(skip_lt_seconds_var.get() or 10) # 调试图像清理配置 if "debug_captures" not in cfg2 or not isinstance(cfg2["debug_captures"], dict): cfg2["debug_captures"] = {} - cfg2["debug_captures"]["enabled"] = bool( - debug_captures_enabled_var.get() - ) + cfg2["debug_captures"]["enabled"] = bool(debug_captures_enabled_var.get()) cfg2["debug_captures"]["auto_cleanup"] = bool( debug_captures_auto_cleanup_var.get() ) @@ -1775,7 +1863,9 @@ def main(): debug_captures_max_files_var.get() or 2000 ) cfg2["debug_captures"]["async_save"] = bool(debug_captures_async_save_var.get()) - cfg2["debug_captures"]["log_on_complete"] = bool(debug_captures_log_on_complete_var.get()) + cfg2["debug_captures"]["log_on_complete"] = bool( + debug_captures_log_on_complete_var.get() + ) # 日志配置 if "logging" not in cfg2 or not isinstance(cfg2["logging"], dict): @@ -1783,15 +1873,27 @@ def main(): cfg2["logging"]["beautify_output"] = bool(logging_beautify_var.get()) cfg2["logging"]["color_output"] = bool(logging_color_var.get()) cfg2["logging"]["show_timestamps"] = bool(logging_show_timestamps_var.get()) - cfg2["logging"]["debug_detail_level"] = str(logging_debug_level_var.get() or "normal") - cfg2["logging"]["error_detail_level"] = str(logging_error_level_var.get() or "full") - cfg2["logging"]["action_log_format"] = str(logging_action_format_var.get() or "concise") + cfg2["logging"]["debug_detail_level"] = str( + logging_debug_level_var.get() or "normal" + ) + cfg2["logging"]["error_detail_level"] = str( + logging_error_level_var.get() or "full" + ) + cfg2["logging"]["action_log_format"] = str( + logging_action_format_var.get() or "concise" + ) # 性能追踪配置 - if "performance_tracking" not in cfg2["logging"] or not isinstance(cfg2["logging"]["performance_tracking"], dict): + if "performance_tracking" not in cfg2["logging"] or not isinstance( + cfg2["logging"]["performance_tracking"], dict + ): cfg2["logging"]["performance_tracking"] = {} - cfg2["logging"]["performance_tracking"]["enabled"] = bool(logging_performance_enabled_var.get()) - cfg2["logging"]["performance_tracking"]["track_function_calls"] = bool(logging_track_functions_var.get()) + cfg2["logging"]["performance_tracking"]["enabled"] = bool( + logging_performance_enabled_var.get() + ) + cfg2["logging"]["performance_tracking"]["track_function_calls"] = bool( + logging_track_functions_var.get() + ) cfg2["yanghao_enabled"] = bool(yg_enabled_var.get()) cfg2["yanghao_enable_actions"] = bool(yg_actions_enabled_var.get()) @@ -1854,6 +1956,7 @@ def main(): # 如果用户关闭了流式后台截图,尝试停止正在运行的服务实例以立即生效 try: from operations.screenshot_service import ScreenshotService + if not bool(cfg2.get("enable_streaming_screenshot", True)): try: ScreenshotService.get_instance().stop() @@ -1939,10 +2042,12 @@ def main(): # 读取截图以获取实际尺寸 try: from path_config import get_screenshot_path + screenshot_path = get_screenshot_path() except Exception: # 回退到旧路径(向后兼容) import path_config + screenshot_path = path_config.get_screenshot_path() if not os.path.exists(screenshot_path): root.after(0, log_msg("[OCR] 截图文件不存在")) # type: ignore[arg-type] @@ -2092,7 +2197,9 @@ def main(): log_search_frame.pack(fill=X, padx=10, pady=(10, 5)) log_search_var = tk.StringVar(value="") - log_search_entry = ttk.Entry(log_search_frame, textvariable=log_search_var, width=20) + log_search_entry = ttk.Entry( + log_search_frame, textvariable=log_search_var, width=20 + ) log_search_entry.pack(side=LEFT, padx=(0, 5)) log_search_matches = [] # 存储所有匹配的位置 @@ -2158,9 +2265,13 @@ def main(): # 根据方向更新当前匹配索引 if direction == 1: # 下一个 - log_current_match_index = (log_current_match_index + 1) % len(log_search_matches) + log_current_match_index = (log_current_match_index + 1) % len( + log_search_matches + ) else: # 上一个 - log_current_match_index = (log_current_match_index - 1) % len(log_search_matches) + log_current_match_index = (log_current_match_index - 1) % len( + log_search_matches + ) # 高亮当前匹配项并滚动到该位置 if log_current_match_index >= 0: @@ -2193,10 +2304,18 @@ def main(): log_search_entry.bind("", on_log_search_entry_key) - ttk.Button(log_search_frame, text="搜索", command=search_next_in_log).pack(side=LEFT, padx=(0, 2)) - ttk.Button(log_search_frame, text="上一个", command=search_prev_in_log).pack(side=LEFT, padx=(0, 2)) - ttk.Button(log_search_frame, text="下一个", command=search_next_in_log).pack(side=LEFT, padx=(0, 2)) - ttk.Button(log_search_frame, text="清除", command=clear_search_in_log).pack(side=LEFT, padx=(0, 5)) + ttk.Button(log_search_frame, text="搜索", command=search_next_in_log).pack( + side=LEFT, padx=(0, 2) + ) + ttk.Button(log_search_frame, text="上一个", command=search_prev_in_log).pack( + side=LEFT, padx=(0, 2) + ) + ttk.Button(log_search_frame, text="下一个", command=search_next_in_log).pack( + side=LEFT, padx=(0, 2) + ) + ttk.Button(log_search_frame, text="清除", command=clear_search_in_log).pack( + side=LEFT, padx=(0, 5) + ) log_text = ScrolledText(log_box) try: @@ -2216,24 +2335,50 @@ def main(): if current_theme in light_themes: # 明亮主题 - 使用更适合人眼观看的颜色组合 - log_text.configure(background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C") + log_text.configure( + background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C" + ) log_text.tag_configure("log_timestamp", foreground="#8B8B8B") # 柔和的灰色 - log_text.tag_configure("log_info", foreground="#1E88E5") # 明亮的蓝色,易于阅读 - log_text.tag_configure("log_warning", foreground="#F57C00") # 橙色,警告色但不过于刺眼 - log_text.tag_configure("log_error", foreground="#D32F2F") # 深红色,醒目但不刺眼 - log_text.tag_configure("log_critical", foreground="#B71C1C", font=("Consolas", 10, "bold")) # 加粗深红色 - log_text.tag_configure("log_performance", foreground="#388E3C") # 深绿色,性能指标 - log_text.tag_configure("log_module", foreground="#7B1FA2") # 紫色,模块标识 + log_text.tag_configure( + "log_info", foreground="#1E88E5" + ) # 明亮的蓝色,易于阅读 + log_text.tag_configure( + "log_warning", foreground="#F57C00" + ) # 橙色,警告色但不过于刺眼 + log_text.tag_configure( + "log_error", foreground="#D32F2F" + ) # 深红色,醒目但不刺眼 + log_text.tag_configure( + "log_critical", foreground="#B71C1C", font=("Consolas", 10, "bold") + ) # 加粗深红色 + log_text.tag_configure( + "log_performance", foreground="#388E3C" + ) # 深绿色,性能指标 + log_text.tag_configure("log_module", foreground="#7B1FA2") # 紫色,模块标识 else: # 暗色主题 - 优化对比度和可读性 - log_text.configure(background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF") - log_text.tag_configure("log_timestamp", foreground="#A0A0A0") # 浅灰色时间戳 - log_text.tag_configure("log_info", foreground="#64B5F6") # 亮蓝色,信息级 - log_text.tag_configure("log_warning", foreground="#FFB74D") # 金色警告,暗色背景下醒目 - log_text.tag_configure("log_error", foreground="#EF5350") # 亮红色,错误突出 - log_text.tag_configure("log_critical", foreground="#F44336", font=("Consolas", 10, "bold")) # 加粗亮红色 - log_text.tag_configure("log_performance", foreground="#81C784") # 亮绿色,性能数据 - log_text.tag_configure("log_module", foreground="#BA68C8") # 亮紫色,模块标识 + log_text.configure( + background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF" + ) + log_text.tag_configure( + "log_timestamp", foreground="#A0A0A0" + ) # 浅灰色时间戳 + log_text.tag_configure("log_info", foreground="#64B5F6") # 亮蓝色,信息级 + log_text.tag_configure( + "log_warning", foreground="#FFB74D" + ) # 金色警告,暗色背景下醒目 + log_text.tag_configure( + "log_error", foreground="#EF5350" + ) # 亮红色,错误突出 + log_text.tag_configure( + "log_critical", foreground="#F44336", font=("Consolas", 10, "bold") + ) # 加粗亮红色 + log_text.tag_configure( + "log_performance", foreground="#81C784" + ) # 亮绿色,性能数据 + log_text.tag_configure( + "log_module", foreground="#BA68C8" + ) # 亮紫色,模块标识 # 配置操作类型颜色标签(使用模块化配置) try: @@ -2256,10 +2401,12 @@ def main(): try: from path_config import get_pic_dir + images_dir = get_pic_dir() except Exception: # 回退到旧路径(向后兼容) import path_config + images_dir = path_config.get_pic_dir() def scan_image_files(): @@ -2433,15 +2580,27 @@ def main(): auto_join_fansclub=bool(auto_join_var.get()), fansclub_fail_action=str(fansclub_action_var.get() or "stay").lower(), # Web端新增参数 - high_value_room_revisit_enabled=bool(high_value_room_revisit_enabled_var.get()), - high_value_room_revisit_only_current_run=bool(high_value_room_revisit_only_current_run_var.get()), - reservation_back_verify_enabled=bool(reservation_back_verify_enabled_var.get()), - reservation_back_swipe_delay=float(reservation_back_swipe_delay_var.get() or 1.0), - reservation_preempt_min_value=float(reservation_preempt_min_value_var.get() or 1000), + high_value_room_revisit_enabled=bool( + high_value_room_revisit_enabled_var.get() + ), + high_value_room_revisit_only_current_run=bool( + high_value_room_revisit_only_current_run_var.get() + ), + reservation_back_verify_enabled=bool( + reservation_back_verify_enabled_var.get() + ), + reservation_back_swipe_delay=float( + reservation_back_swipe_delay_var.get() or 1.0 + ), + reservation_preempt_min_value=float( + reservation_preempt_min_value_var.get() or 1000 + ), fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 5), enable_ocr_mode1=bool(enable_ocr_mode1_var.get()), fudai_template_match_enabled=bool(fudai_template_match_enabled_var.get()), - fudai_template_match_threshold=float(fudai_template_match_threshold_var.get() or 0.7), + fudai_template_match_threshold=float( + fudai_template_match_threshold_var.get() or 0.7 + ), ) def start_run(): @@ -2550,7 +2709,7 @@ def main(): tag = "log_critical" elif "elapsed_seconds=" in line or "耗时" in line: tag = "log_performance" - elif re.search(r'\[[\w\.]+\]', line): + elif re.search(r"\[[\w\.]+\]", line): tag = "log_module" if tag: @@ -2688,7 +2847,9 @@ def main(): # 如果参与成功 > 点击参与,说明有检测到已参与的情况 if fudai_attend_ok > fudai_click_attend: detected_already_attended = fudai_attend_ok - fudai_click_attend - lines.append(f" (其中 {detected_already_attended} 次为检测到已参与状态)") + lines.append( + f" (其中 {detected_already_attended} 次为检测到已参与状态)" + ) elif fudai_attend_ok > 0 or fudai_attend_fail > 0: # 如果没有点击参与但有参与结果,使用原来的计算方式 total_attend = fudai_attend_ok + fudai_attend_fail @@ -2702,7 +2863,9 @@ def main(): # 检查数据一致性:参与成功次数应该 >= 开奖结果次数 if fudai_attend_ok > 0 and total_results < fudai_attend_ok: pending_results = fudai_attend_ok - total_results - lines.append(f" 注意: 有 {pending_results} 次参与成功尚未开奖(或开奖结果未识别)") + lines.append( + f" 注意: 有 {pending_results} 次参与成功尚未开奖(或开奖结果未识别)" + ) if total_results > 0: win_rate = (fudai_result_win / total_results) * 100 lines.append(f" 中奖率: {win_rate:.1f}%") @@ -2746,7 +2909,9 @@ def main(): lines.append("=" * 60) lines.append("高价值预约统计") lines.append("=" * 60) - lines.append(f"倒计时大于阈值但价值达到高价值阈值,记录预约: {fudai_reserved_high_value}") + lines.append( + f"倒计时大于阈值但价值达到高价值阈值,记录预约: {fudai_reserved_high_value}" + ) lines.append("") # 等待开奖统计 @@ -2768,7 +2933,10 @@ def main(): lines.append(f"诊断完成: {stage_diagnosis_complete}") lines.append(f"诊断失败: {stage_diagnosis_failed}") if stage_diagnosis_complete > 0: - success_rate = (stage_diagnosis_complete / (stage_diagnosis_complete + stage_diagnosis_failed)) * 100 + success_rate = ( + stage_diagnosis_complete + / (stage_diagnosis_complete + stage_diagnosis_failed) + ) * 100 lines.append(f"成功率: {success_rate:.1f}%") lines.append("") @@ -2785,7 +2953,9 @@ def main(): lines.append(f"OCR失败次数: {ocr_failed}") total_ocr_results = ocr_success + ocr_failed if total_ocr_results < ocr_attempt: - lines.append(f" 注意: 有 {ocr_attempt - total_ocr_results} 次尝试未记录结果(可能日志格式不匹配)") + lines.append( + f" 注意: 有 {ocr_attempt - total_ocr_results} 次尝试未记录结果(可能日志格式不匹配)" + ) if ocr_attempt > 0: ocr_rate = (ocr_success / ocr_attempt) * 100 lines.append(f"OCR成功率: {ocr_rate:.1f}%") @@ -2802,11 +2972,17 @@ def main(): lines.append(f"详情识别尝试: {fudai_detail_read_attempt}") lines.append(f"详情识别成功: {fudai_detail_read_success}") lines.append(f"详情识别失败: {fudai_detail_read_failed}") - total_detail_results = fudai_detail_read_success + fudai_detail_read_failed + total_detail_results = ( + fudai_detail_read_success + fudai_detail_read_failed + ) if total_detail_results < fudai_detail_read_attempt: - lines.append(f" 注意: 有 {fudai_detail_read_attempt - total_detail_results} 次尝试未记录结果(可能日志格式不匹配)") + lines.append( + f" 注意: 有 {fudai_detail_read_attempt - total_detail_results} 次尝试未记录结果(可能日志格式不匹配)" + ) if fudai_detail_read_attempt > 0: - detail_rate = (fudai_detail_read_success / fudai_detail_read_attempt) * 100 + detail_rate = ( + fudai_detail_read_success / fudai_detail_read_attempt + ) * 100 lines.append(f"详情识别成功率: {detail_rate:.1f}%") lines.append("") @@ -2814,7 +2990,11 @@ def main(): fudai_find_success = counters.get("fudai_find_success", 0) fudai_find_not_found = counters.get("fudai_find_not_found", 0) fudai_find_timeout = counters.get("fudai_find_timeout", 0) - if fudai_find_success > 0 or fudai_find_not_found > 0 or fudai_find_timeout > 0: + if ( + fudai_find_success > 0 + or fudai_find_not_found > 0 + or fudai_find_timeout > 0 + ): lines.append("=" * 60) lines.append("福袋查找统计") lines.append("=" * 60) @@ -2900,8 +3080,12 @@ def main(): reservation_window_entered = counters.get("reservation_window_entered", 0) reservation_back_success = counters.get("reservation_back_success", 0) reservation_back_verify_ok = counters.get("reservation_back_verify_ok", 0) - reservation_back_verify_fail = counters.get("reservation_back_verify_fail", 0) - reservation_window_not_reached = counters.get("reservation_window_not_reached", 0) + reservation_back_verify_fail = counters.get( + "reservation_back_verify_fail", 0 + ) + reservation_window_not_reached = counters.get( + "reservation_window_not_reached", 0 + ) reservation_expired = counters.get("reservation_expired", 0) reservation_queue_empty = counters.get("reservation_queue_empty", 0) reservation_locked = counters.get("reservation_locked", 0) @@ -2909,9 +3093,15 @@ def main(): reservation_queue_full_wait = counters.get("reservation_queue_full_wait", 0) reservation_drop_low_value = counters.get("reservation_drop_low_value", 0) reservation_clear = counters.get("reservation_clear", 0) - reservation_back_direct_attend = counters.get("reservation_back_direct_attend", 0) - reservation_queue_full_back_attend = counters.get("reservation_queue_full_back_attend", 0) - reservation_duplicate_detected = counters.get("reservation_duplicate_detected", 0) + reservation_back_direct_attend = counters.get( + "reservation_back_direct_attend", 0 + ) + reservation_queue_full_back_attend = counters.get( + "reservation_queue_full_back_attend", 0 + ) + reservation_duplicate_detected = counters.get( + "reservation_duplicate_detected", 0 + ) reservation_back_operation = counters.get("reservation_back_operation", 0) reservation_total = ( @@ -2959,7 +3149,9 @@ def main(): if reservation_window_entered > 0: lines.append(f"进入预约参与窗口: {reservation_window_entered}") if reservation_window_not_reached > 0: - lines.append(f"时间窗口未到(跳过): {reservation_window_not_reached}") + lines.append( + f"时间窗口未到(跳过): {reservation_window_not_reached}" + ) # 预约状态统计 if reservation_expired > 0: @@ -2985,14 +3177,18 @@ def main(): if reservation_back_direct_attend > 0: lines.append(f"回退后直接参与: {reservation_back_direct_attend}") if reservation_queue_full_back_attend > 0: - lines.append(f"队列满回退后参与: {reservation_queue_full_back_attend}") + lines.append( + f"队列满回退后参与: {reservation_queue_full_back_attend}" + ) if reservation_back_operation > 0: lines.append(f"回退操作次数: {reservation_back_operation}") # 预约成功率 if reservation_recorded > 0 and reservation_back_success > 0: back_rate = (reservation_back_success / reservation_recorded) * 100 - lines.append(f"预约回退成功率: {back_rate:.1f}% ({reservation_back_success}/{reservation_recorded})") + lines.append( + f"预约回退成功率: {back_rate:.1f}% ({reservation_back_success}/{reservation_recorded})" + ) lines.append("") @@ -3155,7 +3351,9 @@ def main(): lines.append(f"识别到的福袋总数: {len(prize_values)}") # 说明:价值统计只统计了成功识别到价值的福袋,可能少于总识别次数 if fudai_seen > len(prize_values): - lines.append(f" (总识别次数: {fudai_seen},其中 {len(prize_values)} 个成功识别到价值)") + lines.append( + f" (总识别次数: {fudai_seen},其中 {len(prize_values)} 个成功识别到价值)" + ) lines.append(f"总价值: {total_value:.2f} 元") lines.append(f"平均价值: {avg_value:.2f} 元") lines.append(f"最高价值: {max_value:.2f} 元") @@ -3266,10 +3464,12 @@ def main(): def refresh_reservations(): try: from path_config import get_reservations_path + path = get_reservations_path() except Exception: # 回退到旧路径(向后兼容) import path_config + path = path_config.get_reservations_path() try: if os.path.exists(path): @@ -3278,12 +3478,31 @@ def main(): reservation_text.delete("1.0", "end") from datetime import datetime - updated_ts = float(data.get("updated_ts", 0.0) or 0.0) if isinstance(data, dict) else 0.0 - room_pos = int(data.get("room_pos", 0) or 0) if isinstance(data, dict) else 0 - reason = str(data.get("reason", "") or "") if isinstance(data, dict) else "" - current_title = str(data.get("current_room_title", "") or "") if isinstance(data, dict) else "" - current_title_raw = str(data.get("current_room_title_raw", "") or "") if isinstance(data, dict) else "" - reservations = data.get("reservations", []) if isinstance(data, dict) else [] + + updated_ts = ( + float(data.get("updated_ts", 0.0) or 0.0) + if isinstance(data, dict) + else 0.0 + ) + room_pos = ( + int(data.get("room_pos", 0) or 0) if isinstance(data, dict) else 0 + ) + reason = ( + str(data.get("reason", "") or "") if isinstance(data, dict) else "" + ) + current_title = ( + str(data.get("current_room_title", "") or "") + if isinstance(data, dict) + else "" + ) + current_title_raw = ( + str(data.get("current_room_title_raw", "") or "") + if isinstance(data, dict) + else "" + ) + reservations = ( + data.get("reservations", []) if isinstance(data, dict) else [] + ) # 基本信息(中文,更详细) lines = [] @@ -3313,7 +3532,9 @@ def main(): else: lines.append("最后更新时间:暂无数据") - lines.append(f"当前所在直播间位置:第 {room_pos + 1} 个直播间(索引:{room_pos})") + lines.append( + f"当前所在直播间位置:第 {room_pos + 1} 个直播间(索引:{room_pos})" + ) lines.append(f"当前直播间名称(清洗后):{current_title or '未知'}") lines.append(f"当前直播间名称(原始):{current_title_raw or '未知'}") lines.append(f"预约队列总数:{len(reservations)} 条") @@ -3364,8 +3585,12 @@ def main(): earliest_ts = min(valid_future_times) latest_ts = max(valid_future_times) try: - earliest_str = datetime.fromtimestamp(earliest_ts).strftime("%Y-%m-%d %H:%M:%S") - latest_str = datetime.fromtimestamp(latest_ts).strftime("%Y-%m-%d %H:%M:%S") + earliest_str = datetime.fromtimestamp(earliest_ts).strftime( + "%Y-%m-%d %H:%M:%S" + ) + latest_str = datetime.fromtimestamp(latest_ts).strftime( + "%Y-%m-%d %H:%M:%S" + ) lines.append(f"最早开奖时间:{earliest_str}") lines.append(f"最晚开奖时间:{latest_str}") except Exception: @@ -3429,7 +3654,9 @@ def main(): if created_ts > 0: try: created_dt = datetime.fromtimestamp(created_ts) - created_str = created_dt.strftime("%Y年%m月%d日 %H:%M:%S") + created_str = created_dt.strftime( + "%Y年%m月%d日 %H:%M:%S" + ) # 计算距离现在的时间 time_diff = datetime.now() - created_dt if time_diff.total_seconds() < 3600: @@ -3445,7 +3672,9 @@ def main(): created_str_full = "未知" # 格式化显示 - lines.append(f"┌─ 预约 #{idx} ─────────────────────────────────────────────") + lines.append( + f"┌─ 预约 #{idx} ─────────────────────────────────────────────" + ) lines.append(f"│ 状态:{status_icon} {remain_str}") lines.append(f"│") lines.append(f"│ 💰 奖品价值:{val:.2f} 元") @@ -3455,15 +3684,23 @@ def main(): if ft > 0: try: ft_dt = datetime.fromtimestamp(ft) - ft_str_detailed = ft_dt.strftime("%Y年%m月%d日 %H:%M:%S") + ft_str_detailed = ft_dt.strftime( + "%Y年%m月%d日 %H:%M:%S" + ) if ft_str_detailed != ft_str: lines.append(f"│ 详细时间:{ft_str_detailed}") except Exception: pass lines.append(f"│") - lines.append(f"│ 📍 发现时直播间位置:第 {pos_seen + 1} 个直播间(索引:{pos_seen})") - lines.append(f"│ 🏠 直播间名称(清洗后):{room_title or '未知'}") - lines.append(f"│ 🏠 直播间名称(原始):{room_title_raw or '未知'}") + lines.append( + f"│ 📍 发现时直播间位置:第 {pos_seen + 1} 个直播间(索引:{pos_seen})" + ) + lines.append( + f"│ 🏠 直播间名称(清洗后):{room_title or '未知'}" + ) + lines.append( + f"│ 🏠 直播间名称(原始):{room_title_raw or '未知'}" + ) lines.append(f"│") lines.append(f"│ 📝 记录时间:{created_str_full}") lines.append(f"└{'─' * 58}") @@ -3473,7 +3710,9 @@ def main(): lines.append("") lines.append("暂无预约记录。") lines.append("") - lines.append("提示:当检测到高价值福袋时,系统会自动将其加入预约队列。") + lines.append( + "提示:当检测到高价值福袋时,系统会自动将其加入预约队列。" + ) reservation_text.insert("1.0", "\n".join(lines)) else: @@ -3500,10 +3739,12 @@ def main(): def refresh_high_value_rooms(): try: from path_config import get_high_value_rooms_path + path = get_high_value_rooms_path() except Exception: # 回退到旧路径(向后兼容) import path_config + path = path_config.get_high_value_rooms_path() try: if os.path.exists(path): @@ -3551,9 +3792,17 @@ def main(): light_themes = {"litera", "flatly", "journal", "minty", "cosmo"} is_light = current_theme.lower() in light_themes if is_light: - actions_log_text.configure(background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C") + actions_log_text.configure( + background="#FFFFFF", + foreground="#2C2C2C", + insertbackground="#2C2C2C", + ) else: - actions_log_text.configure(background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF") + actions_log_text.configure( + background="#1E1E1E", + foreground="#E0E0E0", + insertbackground="#FFFFFF", + ) # 为所有操作类型配置标签 for op_type, colors in color_config.items(): @@ -3579,11 +3828,13 @@ def main(): # 使用统一的路径配置 try: from path_config import get_actions_log_path + path = get_actions_log_path() except Exception: # 回退到旧路径(向后兼容) # 修正路径:GUI应该读取根目录的logs/actions.log import path_config + path = path_config.get_actions_log_path() try: if os.path.exists(path): @@ -3621,7 +3872,9 @@ def main(): # 保存当前滚动位置,避免刷新时自动置顶 try: - scroll_position = actions_log_text.yview()[0] # 获取当前滚动位置(顶部可见位置的比例) + scroll_position = actions_log_text.yview()[ + 0 + ] # 获取当前滚动位置(顶部可见位置的比例) except Exception: scroll_position = 0.0 @@ -3650,7 +3903,7 @@ def main(): start_pos, end_pos, line, - current_theme + current_theme, ) except Exception: pass # 忽略颜色应用失败 @@ -3680,11 +3933,15 @@ def main(): ) # 行为日志搜索功能 - ttk.Separator(actions_log_top, orient="vertical").pack(side=LEFT, fill=Y, padx=5, pady=3) + ttk.Separator(actions_log_top, orient="vertical").pack( + side=LEFT, fill=Y, padx=5, pady=3 + ) ttk.Label(actions_log_top, text="搜索:").pack(side=LEFT) actions_search_var = tk.StringVar(value="") - actions_search_entry = ttk.Entry(actions_log_top, textvariable=actions_search_var, width=20) + actions_search_entry = ttk.Entry( + actions_log_top, textvariable=actions_search_var, width=20 + ) actions_search_entry.pack(side=LEFT, padx=(0, 5)) actions_search_matches = [] @@ -3740,9 +3997,13 @@ def main(): actions_log_text.tag_add("search_highlight", start_idx, end_idx) if direction == 1: - actions_current_match_index = (actions_current_match_index + 1) % len(actions_search_matches) + actions_current_match_index = (actions_current_match_index + 1) % len( + actions_search_matches + ) else: - actions_current_match_index = (actions_current_match_index - 1) % len(actions_search_matches) + actions_current_match_index = (actions_current_match_index - 1) % len( + actions_search_matches + ) if actions_current_match_index >= 0: start_idx, end_idx = actions_search_matches[actions_current_match_index] @@ -3770,10 +4031,18 @@ def main(): actions_search_entry.bind("", on_actions_search_entry_key) - ttk.Button(actions_log_top, text="搜索", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2)) - ttk.Button(actions_log_top, text="上一个", command=search_prev_in_actions).pack(side=LEFT, padx=(0, 2)) - ttk.Button(actions_log_top, text="下一个", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2)) - ttk.Button(actions_log_top, text="清除", command=clear_search_in_actions).pack(side=LEFT) + ttk.Button(actions_log_top, text="搜索", command=search_next_in_actions).pack( + side=LEFT, padx=(0, 2) + ) + ttk.Button(actions_log_top, text="上一个", command=search_prev_in_actions).pack( + side=LEFT, padx=(0, 2) + ) + ttk.Button(actions_log_top, text="下一个", command=search_next_in_actions).pack( + side=LEFT, padx=(0, 2) + ) + ttk.Button(actions_log_top, text="清除", command=clear_search_in_actions).pack( + side=LEFT + ) # OCR结果显示 ocr_results_top = ttk.Frame(ocr_results_tab) @@ -3834,7 +4103,9 @@ def main(): win_record_left.pack(side=LEFT, fill=BOTH, expand=True, padx=(10, 5), pady=10) win_record_right = ttk.Frame(win_record_tab) - win_record_right.pack(side=RIGHT, fill=BOTH, expand=False, padx=(5, 10), pady=10, ipadx=10) + win_record_right.pack( + side=RIGHT, fill=BOTH, expand=False, padx=(5, 10), pady=10, ipadx=10 + ) # 左侧:中奖截图列表 win_list_label = ttk.Label(win_record_left, text="中奖截图列表:") @@ -3846,7 +4117,9 @@ def main(): win_list_scrollbar = ttk.Scrollbar(win_list_frame) win_list_scrollbar.pack(side=RIGHT, fill=Y) - win_listbox = tk.Listbox(win_list_frame, yscrollcommand=win_list_scrollbar.set, font=("Consolas", 9)) + win_listbox = tk.Listbox( + win_list_frame, yscrollcommand=win_list_scrollbar.set, font=("Consolas", 9) + ) win_listbox.pack(side=LEFT, fill=BOTH, expand=True) win_list_scrollbar.config(command=win_listbox.yview) @@ -3868,9 +4141,11 @@ def main(): """扫描中奖截图目录""" try: from path_config import get_pic_dir + pic_dir = get_pic_dir() except Exception: import path_config + pic_dir = path_config.get_pic_dir() prize_dir = os.path.join(pic_dir, "lottery_prize_captures") @@ -3902,6 +4177,7 @@ def main(): # 格式化显示:文件名 + 时间 try: from datetime import datetime + dt = datetime.fromtimestamp(mtime) time_str = dt.strftime("%Y-%m-%d %H:%M:%S") display_text = f"{file} ({time_str})" @@ -3974,15 +4250,19 @@ def main(): win_listbox.bind("<>", on_win_list_select) - ttk.Button(win_record_top, text="刷新列表", command=refresh_win_record).pack(side=LEFT, padx=(0, 10)) + ttk.Button(win_record_top, text="刷新列表", command=refresh_win_record).pack( + side=LEFT, padx=(0, 10) + ) def open_win_folder(): """打开中奖截图目录""" try: from path_config import get_pic_dir + pic_dir = get_pic_dir() except Exception: import path_config + pic_dir = path_config.get_pic_dir() prize_dir = os.path.join(pic_dir, "lottery_prize_captures") @@ -4005,12 +4285,16 @@ def main(): """加载误识别记录""" try: from path_config import get_pic_dir + pic_dir = get_pic_dir() except Exception: import path_config + pic_dir = path_config.get_pic_dir() - false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json") + false_positive_file = os.path.join( + pic_dir, "lottery_prize_captures", "false_positives.json" + ) if not os.path.exists(false_positive_file): false_positive_text.delete("1.0", "end") false_positive_text.insert("1.0", "暂无误识别记录") @@ -4018,6 +4302,7 @@ def main(): try: import json + with open(false_positive_file, "r", encoding="utf-8") as f: data = json.load(f) false_positives = data.get("false_positives", []) @@ -4034,12 +4319,16 @@ def main(): """保存误识别记录""" try: from path_config import get_pic_dir + pic_dir = get_pic_dir() except Exception: import path_config + pic_dir = path_config.get_pic_dir() - false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json") + false_positive_file = os.path.join( + pic_dir, "lottery_prize_captures", "false_positives.json" + ) os.makedirs(os.path.dirname(false_positive_file), exist_ok=True) content = false_positive_text.get("1.0", "end-1c") @@ -4047,6 +4336,7 @@ def main(): try: import json + with open(false_positive_file, "w", encoding="utf-8") as f: json.dump({"false_positives": lines}, f, ensure_ascii=False, indent=2) on_line(f"[中奖记录] 已保存 {len(lines)} 条误识别记录") @@ -4055,8 +4345,12 @@ def main(): false_positive_btn_frame = ttk.Frame(false_positive_frame) false_positive_btn_frame.pack(fill=X, padx=10, pady=(0, 10)) - ttk.Button(false_positive_btn_frame, text="刷新", command=load_false_positives).pack(side=LEFT, padx=(0, 5)) - ttk.Button(false_positive_btn_frame, text="保存", command=save_false_positives).pack(side=LEFT) + ttk.Button( + false_positive_btn_frame, text="刷新", command=load_false_positives + ).pack(side=LEFT, padx=(0, 5)) + ttk.Button( + false_positive_btn_frame, text="保存", command=save_false_positives + ).pack(side=LEFT) load_false_positives() diff --git a/gui/web_gui.py b/gui/web_gui.py index e8af26a..aea5edc 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -259,24 +259,24 @@ class ProcRunner: # --- 统一日志格式解析:提取traceId和MDC信息 --- # 格式:时间戳(毫秒) - [级别] - [线程名] - [模块名:函数名:行号] - [traceId:xxx] - 消息 | MDC: 上下文信息 - trace_id_match = re.search(r'\[traceId:([^\]]+)\]', s) + trace_id_match = re.search(r"\[traceId:([^\]]+)\]", s) if trace_id_match: trace_id = trace_id_match.group(1) # 存储当前traceId(用于统计和显示) - if not hasattr(self, '_current_trace_id'): + if not hasattr(self, "_current_trace_id"): self._current_trace_id = trace_id - elif trace_id != 'N/A': + elif trace_id != "N/A": self._current_trace_id = trace_id # 提取MDC信息 - mdc_match = re.search(r'MDC:\s*([^|]+)', s) + mdc_match = re.search(r"MDC:\s*([^|]+)", s) if mdc_match: mdc_str = mdc_match.group(1).strip() # 解析MDC键值对 - mdc_pairs = re.findall(r'(\w+)=([^,\s]+)', mdc_str) + mdc_pairs = re.findall(r"(\w+)=([^,\s]+)", mdc_str) for key, value in mdc_pairs: # 存储MDC信息(可用于统计) - if not hasattr(self, '_mdc_context'): + if not hasattr(self, "_mdc_context"): self._mdc_context = {} self._mdc_context[key] = value @@ -284,7 +284,9 @@ class ProcRunner: # 支持多种格式:旧格式"福袋内容:"和新格式"字段_内容="或"内容=" content_extracted = False if "福袋内容:" in s: - self._fudai_last["content"] = s.split("福袋内容:", 1)[1].strip().split()[0] # 只取第一个词,避免包含后续字段 + self._fudai_last["content"] = ( + s.split("福袋内容:", 1)[1].strip().split()[0] + ) # 只取第一个词,避免包含后续字段 self._fudai_last["updated_ts"] = time.time() content_extracted = True else: @@ -317,7 +319,9 @@ class ProcRunner: # 倒计时:支持多种格式 if "倒计时时间:" in s: - self._fudai_last["countdown"] = s.split("倒计时时间:", 1)[1].strip().split()[0] + self._fudai_last["countdown"] = ( + s.split("倒计时时间:", 1)[1].strip().split()[0] + ) self._fudai_last["updated_ts"] = time.time() else: m = re.search(r"(?:字段_)?倒计时[=:]?\s*([^\s]+)", s) @@ -326,7 +330,9 @@ class ProcRunner: self._fudai_last["updated_ts"] = time.time() # 奖品价值:支持多种格式 - m = re.search(r"(?:字段_)?(?:价值|价值元|奖品价值)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s) + m = re.search( + r"(?:字段_)?(?:价值|价值元|奖品价值)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s + ) if not m: m = re.search(r"奖品价值:\s*([0-9]+(?:\.[0-9]+)?)\s*元", s) if m: @@ -341,7 +347,9 @@ class ProcRunner: self._inc("fudai_open_detail") self._record_event("fudai_open_detail", self._snapshot_fudai()) # 兼容新结构化中文日志: [参与] 动作=点击参与 - if "点击参与抽奖" in s or ("[参与]" in s and ("动作=点击参与" in s or "动作=参与" in s)): + if "点击参与抽奖" in s or ( + "[参与]" in s and ("动作=点击参与" in s or "动作=参与" in s) + ): self._inc("fudai_click_attend") self._record_event("fudai_click_attend", self._snapshot_fudai()) @@ -350,7 +358,10 @@ class ProcRunner: "已经参与,等待开奖" in s or "已经参与,等待看播时间凑齐开奖" in s or "已参与成功(或看播中)" in s - or ("[参与]" in s and ("结果=已参与" in s or "结果=看播中" in s or "结果=参与成功" in s)) + or ( + "[参与]" in s + and ("结果=已参与" in s or "结果=看播中" in s or "结果=参与成功" in s) + ) or ("[参与]" in s and "已参与" in s and "等待开奖" in s) or ("预约回退后直接参与" in s and "参与成功" in s) ): @@ -377,9 +388,7 @@ class ProcRunner: meta["threshold"] = int(m.group(1)) except Exception: pass - self._record_event( - "fudai_skip", {"reason": "participants_low", **meta} - ) + self._record_event("fudai_skip", {"reason": "participants_low", **meta}) if "参与人数" in s and "> 阈值" in s and "不参与" in s: self._inc("fudai_skip_participants_high") # 提取实际参与人数和阈值 @@ -396,9 +405,7 @@ class ProcRunner: meta["threshold"] = int(m.group(1)) except Exception: pass - self._record_event( - "fudai_skip", {"reason": "participants_high", **meta} - ) + self._record_event("fudai_skip", {"reason": "participants_high", **meta}) if "奖品价值" in s and "< 阈值" in s and "不参与" in s: self._inc("fudai_skip_value_low") # 提取实际价值和阈值 @@ -415,9 +422,7 @@ class ProcRunner: meta["threshold"] = float(m.group(1)) except Exception: pass - self._record_event( - "fudai_skip", {"reason": "value_low", **meta} - ) + self._record_event("fudai_skip", {"reason": "value_low", **meta}) if "福袋内容不理想" in s or ("[筛选]" in s and "内容" in s and "黑名单" in s): self._inc("fudai_skip_content") self._record_event( @@ -433,9 +438,7 @@ class ProcRunner: meta["countdown_seconds"] = int(m.group(1)) except Exception: pass - self._record_event( - "fudai_skip", {"reason": "countdown_short", **meta} - ) + self._record_event("fudai_skip", {"reason": "countdown_short", **meta}) if "抽奖倒计时时间大于" in s and "暂不参与" in s: self._inc("fudai_skip_countdown_long") # 提取倒计时秒数 @@ -446,9 +449,7 @@ class ProcRunner: meta["countdown_seconds"] = int(m.group(1)) except Exception: pass - self._record_event( - "fudai_skip", {"reason": "countdown_long", **meta} - ) + self._record_event("fudai_skip", {"reason": "countdown_long", **meta}) # 看播门槛:默认不参与(新结构化日志) if ( "需要看播时长:默认不参与" in s @@ -466,7 +467,9 @@ class ProcRunner: self._inc("fudai_open_error_too_many") self._record_event("fudai_open_error_too_many", self._snapshot_fudai()) # 倒计时大于阈值但价值达到高价值阈值,记录预约 - if ("[流程]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s) or ("[参与]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s): + if ( + "[流程]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s + ) or ("[参与]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s): self._inc("fudai_reserved_high_value") # 提取价值和倒计时信息 meta = self._snapshot_fudai() @@ -529,7 +532,9 @@ class ProcRunner: if "load_config" in s and ("失败" in s or "错误" in s or "异常" in s): self._inc("error_config_load") self._record_event("error_config_load", {}) - if ("预约队列状态文件" in s or "reservations.json" in s) and ("失败" in s or "错误" in s): + if ("预约队列状态文件" in s or "reservations.json" in s) and ( + "失败" in s or "错误" in s + ): self._inc("error_state_file") self._record_event("error_state_file", {}) if "直播间检测" in s and ("失败" in s or "错误" in s): @@ -569,7 +574,9 @@ class ProcRunner: self._record_event("reservation_clear", {}) # --- 预约记录相关(与 gui_core.py 保持一致) --- - if ("[预约]" in s and "已记录高价值福袋" in s) or "record_high_value_reservation:已记录高价值福袋" in s: + if ( + "[预约]" in s and "已记录高价值福袋" in s + ) or "record_high_value_reservation:已记录高价值福袋" in s: self._inc("reservation_recorded") # 提取预约价值:支持多种格式 value = None @@ -591,7 +598,9 @@ class ProcRunner: pass # 提取直播间名称 room_title = None - m = re.search(r"(?:字段_)?(?:直播间|直播间名|room_title)[=:]?\s*([^\s]+)", s) + m = re.search( + r"(?:字段_)?(?:直播间|直播间名|room_title)[=:]?\s*([^\s]+)", s + ) if m: room_title = m.group(1).strip() meta = self._snapshot_fudai() @@ -602,10 +611,16 @@ class ProcRunner: if room_title: meta["room_title"] = room_title self._record_event("reservation_recorded", meta) - if ("[预约]" in s and "进入预约参与窗口" in s) or "进入预约参与窗口,准备回退到目标直播间" in s: + if ( + "[预约]" in s and "进入预约参与窗口" in s + ) or "进入预约参与窗口,准备回退到目标直播间" in s: self._inc("reservation_window_entered") self._record_event("reservation_window_entered", {}) - if ("[预约]" in s and "已回退到目标直播间" in s) or "已回退到目标直播间" in s or ("[预约]" in s and "已回退到最早开奖的预约直播间" in s): + if ( + ("[预约]" in s and "已回退到目标直播间" in s) + or "已回退到目标直播间" in s + or ("[预约]" in s and "已回退到最早开奖的预约直播间" in s) + ): self._inc("reservation_back_success") # 提取回退信息 meta = {} @@ -619,20 +634,28 @@ class ProcRunner: if ("[预约]" in s and "时间窗口未到" in s) or "时间窗口未到,跳过回退" in s: self._inc("reservation_window_not_reached") self._record_event("reservation_window_not_reached", {}) - if ("[预约]" in s and "已明显错过开奖时间" in s) or "已明显错过开奖时间,清理过期预约" in s: + if ( + "[预约]" in s and "已明显错过开奖时间" in s + ) or "已明显错过开奖时间,清理过期预约" in s: self._inc("reservation_expired") self._record_event("reservation_expired", {}) - if ("[预约]" in s and "预约队列为空" in s) or "process_reservation_attend_window:预约队列为空" in s: + if ( + "[预约]" in s and "预约队列为空" in s + ) or "process_reservation_attend_window:预约队列为空" in s: self._inc("reservation_queue_empty") if ("[预约]" in s and "锁定期未结束" in s) or "锁定期未结束" in s: self._inc("reservation_locked") self._record_event("reservation_locked", {}) - if ("[预约]" in s and "已回退到第一个直播间" in s): + if "[预约]" in s and "已回退到第一个直播间" in s: self._inc("reservation_back_to_first") self._record_event("reservation_back_to_first", {}) - if ("[预约]" in s and "run_once_basic:检查预约回退触发条件" in s): + if "[预约]" in s and "run_once_basic:检查预约回退触发条件" in s: self._inc("reservation_check_triggered") - if ("[预约]" in s and "队列已满" in s) or "handle_queue_full_wait_at_earliest" in s or ("[预约]" in s and "队列已满,回退到最早开奖的预约直播间" in s): + if ( + ("[预约]" in s and "队列已满" in s) + or "handle_queue_full_wait_at_earliest" in s + or ("[预约]" in s and "队列已满,回退到最早开奖的预约直播间" in s) + ): self._inc("reservation_queue_full_wait") self._record_event("reservation_queue_full_wait", {}) # 回退后直接参与 @@ -640,11 +663,11 @@ class ProcRunner: self._inc("reservation_back_direct_attend") self._record_event("reservation_back_direct_attend", {}) # 队列满回退后设置参与标志 - if ("[预约]" in s and "队列满回退后,直接设置参与标志" in s): + if "[预约]" in s and "队列满回退后,直接设置参与标志" in s: self._inc("reservation_queue_full_back_attend") self._record_event("reservation_queue_full_back_attend", {}) # 通过相似度匹配识别重复预约 - if ("[预约]" in s and "通过相似度匹配识别为重复预约" in s): + if "[预约]" in s and "通过相似度匹配识别为重复预约" in s: self._inc("reservation_duplicate_detected") self._record_event("reservation_duplicate_detected", {}) @@ -652,7 +675,11 @@ class ProcRunner: if "没有抽中" in s and "关闭弹窗" in s: self._inc("fudai_result_no_win") self._record_event("fudai_result_no_win", self._snapshot_fudai()) - if "恭喜中奖了" in s or "检测到中奖结果" in s or ("[开奖结果]" in s and "中奖" in s): + if ( + "恭喜中奖了" in s + or "检测到中奖结果" in s + or ("[开奖结果]" in s and "中奖" in s) + ): self._inc("fudai_result_win") # 提取中奖信息 meta = self._snapshot_fudai() @@ -666,7 +693,9 @@ class ProcRunner: self._record_event("fudai_order_success", self._snapshot_fudai()) # 等待开奖(只在设置等待开奖标志时计数,避免重复计数) # 注意:不要匹配"已经参与,等待开奖",因为那已经在参与成功时计数了 - if ("[参与]" in s and "参与成功,设置等待开奖标志" in s) or ("[参与]" in s and "设置等待开奖标志" in s): + if ("[参与]" in s and "参与成功,设置等待开奖标志" in s) or ( + "[参与]" in s and "设置等待开奖标志" in s + ): self._inc("fudai_waiting_lottery") # 提取剩余秒数 meta = self._snapshot_fudai() @@ -752,14 +781,21 @@ class ProcRunner: # 记录耗时较长的操作 if elapsed > 5.0: self._inc("slow_operation") - self._record_event("slow_operation", {"elapsed_seconds": elapsed, "operation": s[:100]}) + self._record_event( + "slow_operation", + {"elapsed_seconds": elapsed, "operation": s[:100]}, + ) except Exception: pass # --- 详情识别统计 --- if ("[福袋详情]" in s and "识别" in s) or "识别福袋详情" in s: self._inc("fudai_detail_read_attempt") - if "识别成功" in s or "识别完成" in s or "read_fudai_detail_once完成(成功)" in s: + if ( + "识别成功" in s + or "识别完成" in s + or "read_fudai_detail_once完成(成功)" in s + ): self._inc("fudai_detail_read_success") # 提取任务数量 meta = {} @@ -829,7 +865,16 @@ class ProcRunner: try: path = path_config.get_reservations_path() except Exception: - path = os.path.join(path_config.PROJECT_ROOT if hasattr(path_config, "PROJECT_ROOT") else os.getcwd(), "douyin", "state", "reservations.json") + path = os.path.join( + ( + path_config.PROJECT_ROOT + if hasattr(path_config, "PROJECT_ROOT") + else os.getcwd() + ), + "douyin", + "state", + "reservations.json", + ) else: path = os.path.join(os.getcwd(), "douyin", "state", "reservations.json") try: @@ -1012,7 +1057,9 @@ class ProcRunner: if isinstance(cd, str) and cd.strip(): sec = self._parse_countdown_seconds(cd) if isinstance(sec, int): - b = self._bucket(float(sec), [float(e) for e in countdown_edges]) + b = self._bucket( + float(sec), [float(e) for e in countdown_edges] + ) self._inc_map(countdown_buckets, b, 1) def _top_k(m: dict, k: int = 10) -> list[dict]: @@ -1280,7 +1327,9 @@ class ProcRunner: cmd.append("--disable-ocr-mode1") # 福袋模板匹配开关(命令行优先) - fudai_template_match_enabled = bool(_pick("fudai_template_match_enabled", False)) + fudai_template_match_enabled = bool( + _pick("fudai_template_match_enabled", False) + ) if fudai_template_match_enabled: cmd.append("--fudai-template-enabled") else: @@ -1288,9 +1337,14 @@ class ProcRunner: # 福袋模板匹配阈值(命令行优先) try: - fudai_template_match_threshold = float(_pick("fudai_template_match_threshold", 0.7) or 0.7) + fudai_template_match_threshold = float( + _pick("fudai_template_match_threshold", 0.7) or 0.7 + ) if 0.0 <= fudai_template_match_threshold <= 1.0: - cmd += ["--fudai-template-threshold", str(fudai_template_match_threshold)] + cmd += [ + "--fudai-template-threshold", + str(fudai_template_match_threshold), + ] except Exception: pass @@ -1438,7 +1492,10 @@ class Handler(BaseHTTPRequestHandler): try: full_real = os.path.realpath(full) webui_real = os.path.realpath(WEBUI_DIR) - if not full_real.startswith(webui_real + os.sep) and full_real != webui_real: + if ( + not full_real.startswith(webui_real + os.sep) + and full_real != webui_real + ): self.send_error(HTTPStatus.FORBIDDEN) return except Exception: @@ -1463,7 +1520,9 @@ class Handler(BaseHTTPRequestHandler): with open(full, "rb") as f: data = f.read() # 对于静态资源,使用适当的缓存策略 - cache_control = "no-store" if ext in (".html", ".js") else "public, max-age=3600" + cache_control = ( + "no-store" if ext in (".html", ".js") else "public, max-age=3600" + ) self.send_response(HTTPStatus.OK) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(data))) @@ -1583,7 +1642,15 @@ class Handler(BaseHTTPRequestHandler): try: path = path_config.get_actions_log_path() except Exception: - path = os.path.join(path_config.PROJECT_ROOT if hasattr(path_config, "PROJECT_ROOT") else os.getcwd(), "logs", "actions.log") + path = os.path.join( + ( + path_config.PROJECT_ROOT + if hasattr(path_config, "PROJECT_ROOT") + else os.getcwd() + ), + "logs", + "actions.log", + ) else: path = os.path.join(os.getcwd(), "logs", "actions.log") out_lines: list[str] = [] @@ -1701,6 +1768,7 @@ class Handler(BaseHTTPRequestHandler): "fudai_template_match_enabled", "fudai_quiet_hours_enabled", "high_value_fudai_enabled", + "fudai_disable_content_recognition", "high_value_room_revisit_enabled", "high_value_room_revisit_only_current_run", "reservation_back_verify_enabled", @@ -1760,11 +1828,15 @@ class Handler(BaseHTTPRequestHandler): if isinstance(v, list): set_nested_value(cfg, k, [str(x) for x in v if str(x).strip()]) else: - set_nested_value(cfg, k, [ - str(x).strip() - for x in str(v).splitlines() - if str(x).strip() - ]) + set_nested_value( + cfg, + k, + [ + str(x).strip() + for x in str(v).splitlines() + if str(x).strip() + ], + ) else: set_nested_value(cfg, k, v) diff --git a/tools/README.md b/tools/README.md new file mode 100644 index 0000000..e00e2e1 --- /dev/null +++ b/tools/README.md @@ -0,0 +1,21 @@ +tools/scan_coords.py — 坐标/ROI 扫描工具 + +用途 + +- 扫描仓库中疑似硬编码坐标或裁剪区域(如 `(100, 200)`、`(x1,y1,x2,y2)`)的代码行。 +- 输出 CSV 到 `tools/coords_report.csv`,便于人工或脚本进一步审查。 + +用法 + +```powershell +python tools/scan_coords.py +``` + +输出 + +- `tools/coords_report.csv` 包含字段:`file,line,match,context`。 + +注意 + +- 本脚本使用简单正则匹配,可能存在误报/漏报,建议在生成报告后人工复核。 +- 可根据需要扩展正则或关键词列表以覆盖更多模式。 \ No newline at end of file diff --git a/tools/scan_coords.py b/tools/scan_coords.py new file mode 100644 index 0000000..4ea68fe --- /dev/null +++ b/tools/scan_coords.py @@ -0,0 +1,97 @@ +""" +扫描仓库中疑似硬编码坐标/ROI 的脚本。 +输出 CSV 到 `tools/coords_report.csv`。 +用法: + python tools/scan_coords.py + +原理: 使用简单正则匹配形如 (123, 456) 或 (100, 200, 300, 400) 的元组/列表。 +""" + +from pathlib import Path +import re +import csv + +ROOT = Path(__file__).resolve().parents[1] +OUT_CSV = ROOT / "tools" / "coords_report.csv" +IGNORE_DIRS = {".git", "__pycache__", ".venv", "venv", "dist", "build"} + +# 常见坐标/ROI 正则(宽松) +PATTERNS = [ + re.compile(r"\(\s*\d{1,4}\s*,\s*\d{1,4}\s*\)"), # (123, 456) + re.compile(r"\[\s*\d{1,4}\s*,\s*\d{1,4}\s*\]"), # [123, 456] + re.compile( + r"\(\s*\d{1,4}\s*,\s*\d{1,4}\s*,\s*\d{1,4}\s*,\s*\d{1,4}\s*\)" + ), # (x1,y1,x2,y2) + re.compile( + r"\[\s*\d{1,4}\s*,\s*\d{1,4}\s*,\s*\d{1,4}\s*,\s*\d{1,4}\s*\]" + ), # [x1,y1,x2,y2] +] + +# 额外关键词匹配(ROI 变量名等) +KEYWORD_PATTERNS = [ + re.compile(p, re.IGNORECASE) + for p in [ + r"coords?", + r"roi", + r"rect", + r"left_up", + r"right_down", + r"crop", + r"cut_pic", + r"x1", + r"y1", + r"fudai_x", + ] +] + + +def scan_file(path: Path): + results = [] + try: + text = path.read_text(encoding="utf-8") + except Exception: + return results + + lines = text.splitlines() + for i, line in enumerate(lines, start=1): + for pat in PATTERNS: + for m in pat.finditer(line): + # capture some context + ctx = line.strip() + results.append((str(path.relative_to(ROOT)), i, m.group(0), ctx)) + # 额外按关键词收集可能的 ROI 定义行 + if any(k.search(line) for k in KEYWORD_PATTERNS): + # avoid duplicates: only add if it contains a digit + if re.search(r"\d{2,4}", line): + results.append( + (str(path.relative_to(ROOT)), i, "[keyword_match]", line.strip()) + ) + return results + + +def main(): + rows = [] + for f in ROOT.rglob("*"): + if f.is_dir(): + if f.name in IGNORE_DIRS: + continue + else: + continue + if f.suffix in {".py", ".pyx", ".txt", ".md", ".json", ".yaml", ".yml", ".cfg"}: + if any(part in IGNORE_DIRS for part in f.parts): + continue + hits = scan_file(f) + rows.extend(hits) + + OUT_CSV.parent.mkdir(parents=True, exist_ok=True) + with OUT_CSV.open("w", encoding="utf-8", newline="") as csvf: + writer = csv.writer(csvf) + writer.writerow(["file", "line", "match", "context"]) + for r in rows: + writer.writerow(r) + + print(f"扫描完成,发现 {len(rows)} 条疑似坐标/ROI 行,输出到: {OUT_CSV}") + + +if __name__ == "__main__": + main() diff --git a/tools/test_actions_log.py b/tools/test_actions_log.py new file mode 100644 index 0000000..295668b --- /dev/null +++ b/tools/test_actions_log.py @@ -0,0 +1,29 @@ +from douyin.logging.douyin_logging_wrapper import LoggingWrapper + + +class DummyAnalyser: + def __init__(self): + self._log_seq = 0 + self._last_log_tag = None + self._last_action_tag = None + self._run_id = "test" + self._std_logger = None + + +analyser = DummyAnalyser() + +# 普通操作 +LoggingWrapper.enhanced_log_kv(analyser, "操作", "执行点击", x=100, y=200) +# 截图相关 +LoggingWrapper.enhanced_log_kv( + analyser, "截图", "保存截图", filename="step1.png", log_type="SCREENSHOT" +) +# 错误 +try: + raise ValueError("测试错误") +except Exception as e: + LoggingWrapper.enhanced_log_kv( + analyser, "错误", "发生异常", error=str(e), log_type="ERR" + ) + +print("测试完成") diff --git a/webui/app.js b/webui/app.js index 65b13d0..c444b46 100644 --- a/webui/app.js +++ b/webui/app.js @@ -47,6 +47,8 @@ const DEFAULTS = { fudai_find_max_attempts: 5, fudai_icon_retry_delay_seconds: 0.6, fudai_icon_max_wait_seconds: 5.0, + // 是否禁用福袋内容OCR识别(仅前端默认,实际值以 config.json 为准) + fudai_disable_content_recognition: false, live_room_match_threshold: 0.8, reservation_preempt_min_value: 0, reservation_back_swipe_delay: 0.6, diff --git a/webui/index.html b/webui/index.html index ee1eb22..815d1f6 100644 --- a/webui/index.html +++ b/webui/index.html @@ -10,7 +10,7 @@
-
抖音挂机控制å�?/div> +
抖音挂机控制�?/div>
配置与运行(纯坐标点击)
@@ -18,7 +18,7 @@ - 开始运è¡? + 开始运�?
- +
-
-