Compare commits
171
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
273adbb677 | ||
|
|
7aeb0c881c | ||
|
|
0629906449 | ||
|
|
5355e52b06 | ||
|
|
8da7dcc819 | ||
|
|
2594788a8c | ||
|
|
1801e50a4c | ||
|
|
e5f7434034 | ||
|
|
ee6ce26338 | ||
|
|
61e37f6644 | ||
|
|
48d78147b5 | ||
|
|
df8942e7b8 | ||
|
|
2899c932c4 | ||
|
|
5383bbc131 | ||
|
|
2f21b2a0b4 | ||
|
|
acd8f5c387 | ||
|
|
42ef73a9ee | ||
|
|
6d5b2cfb15 | ||
|
|
01034347f4 | ||
|
|
e3daeab024 | ||
|
|
411fd96804 | ||
|
|
0bd71a5e76 | ||
|
|
cec4a2d692 | ||
|
|
ca071250be | ||
|
|
398133bbb0 | ||
|
|
06c3e54d26 | ||
|
|
28dcbc75c7 | ||
|
|
dadb0b6852 | ||
|
|
6aec4ae314 | ||
|
|
4ce62a1907 | ||
|
|
f0150cb3f4 | ||
|
|
8d426676f6 | ||
|
|
f5b603e39e | ||
|
|
b1f70aa94d | ||
|
|
81b82e6cba | ||
|
|
2ba2168665 | ||
|
|
d9323f2012 | ||
|
|
e3372fa51d | ||
|
|
0b3d69d28b | ||
|
|
0eb4670d46 | ||
|
|
5f713afc5c | ||
|
|
722b57a7b9 | ||
|
|
43da92f6e6 | ||
|
|
798286776d | ||
|
|
77d7113ca1 | ||
|
|
b8ccb899c0 | ||
|
|
d109e94c68 | ||
|
|
887f8bad3e | ||
|
|
c2a44f2544 | ||
|
|
f2b5aaa2c4 | ||
|
|
4f042f95cd | ||
|
|
23e24a9f27 | ||
|
|
c5a70d4a62 | ||
|
|
3de07d7a66 | ||
|
|
d35fadde54 | ||
|
|
241c35f21d | ||
|
|
1468d14d0e | ||
|
|
45f925b597 | ||
|
|
e21e5a5fca | ||
|
|
7694e233f9 | ||
|
|
a90a885a51 | ||
|
|
48f4af5848 | ||
|
|
3af7c6d894 | ||
|
|
6f796a8aaf | ||
|
|
e351745e92 | ||
|
|
0114af2321 | ||
|
|
849160304e | ||
|
|
7307b2abb5 | ||
|
|
c9a07cc91e | ||
|
|
b5d7943af0 | ||
|
|
da552d18cc | ||
|
|
40b4169aac | ||
|
|
265a533cf0 | ||
|
|
37b3454e32 | ||
|
|
77351bafd4 | ||
|
|
9675df2cdb | ||
|
|
d34e39ec9c | ||
|
|
34bdf44d73 | ||
|
|
6f4dbb2d8b | ||
|
|
4e89fadd2e | ||
|
|
331860ee5c | ||
|
|
4abd053957 | ||
|
|
8fea99a168 | ||
|
|
51d859150d | ||
|
|
c509bf1262 | ||
|
|
3b600c9f64 | ||
|
|
d7201866a5 | ||
|
|
a3fe7b3ef0 | ||
|
|
1c1f0abfc0 | ||
|
|
5d2a0ac3ff | ||
|
|
c8df6a1588 | ||
|
|
b1ee0e6b4e | ||
|
|
b9f0389e58 | ||
|
|
66eb05e6b1 | ||
|
|
5a40b49727 | ||
|
|
266c7f2932 | ||
|
|
59ac6a3abc | ||
|
|
df628c11dd | ||
|
|
6996c7813e | ||
|
|
0efcfff545 | ||
|
|
b0eccc5171 | ||
|
|
e8bf904fc6 | ||
|
|
8d98143df1 | ||
|
|
b5a15ecea4 | ||
|
|
73008a9763 | ||
|
|
5309aa0198 | ||
|
|
85d7bb2525 | ||
|
|
3269d3adf6 | ||
|
|
7ef5bc3e07 | ||
|
|
2c8879be7a | ||
|
|
6ecedbbde1 | ||
|
|
cdf8be0ded | ||
|
|
a6dee879e7 | ||
|
|
9f7e8da57a | ||
|
|
6bdf7b2527 | ||
|
|
af8145b8a8 | ||
|
|
e417acfb7c | ||
|
|
2d928c3856 | ||
|
|
57d99f3459 | ||
|
|
a337b4b93d | ||
|
|
57eacb3219 | ||
|
|
254820e6dc | ||
|
|
246c80498e | ||
|
|
badf64998d | ||
|
|
a6bbdcc400 | ||
|
|
ef6ca4a650 | ||
|
|
c442335b34 | ||
|
|
4ab1b88fa0 | ||
|
|
85bd488f66 | ||
|
|
7715b93eca | ||
|
|
2523668b4c | ||
|
|
e7faceeb5f | ||
|
|
9d1b0c1e36 | ||
|
|
74209035f7 | ||
|
|
787c4e8eec | ||
|
|
19e347e6c1 | ||
|
|
c0b8ff3ba6 | ||
|
|
bf7f30996e | ||
|
|
a6ce16f9c4 | ||
|
|
e35e8a85bd | ||
|
|
778c021272 | ||
|
|
ca4941b66d | ||
|
|
7d31075ce3 | ||
|
|
dba43e18f9 | ||
|
|
a39da30d16 | ||
|
|
601e701823 | ||
|
|
f6c9bb938c | ||
|
|
872722522c | ||
|
|
87d0fe2db8 | ||
|
|
ecffba94b4 | ||
|
|
818c3139b1 | ||
|
|
941bbc2475 | ||
|
|
c802f62796 | ||
|
|
b6d2836e84 | ||
|
|
af4fc9168b | ||
|
|
a84ec29145 | ||
|
|
16d9bde4a0 | ||
|
|
e5c5ce06ee | ||
|
|
20aefbb3a1 | ||
|
|
ae3f276f56 | ||
|
|
a46901ef5d | ||
|
|
9e189c711c | ||
|
|
c5c8def884 | ||
|
|
80b35bcb6c | ||
|
|
cc1d4f0897 | ||
|
|
5efa0ebc8b | ||
|
|
0e74bfba77 | ||
|
|
c92af75d02 | ||
|
|
6ac99530d6 | ||
|
|
0c62696118 | ||
|
|
9c3cf86f41 |
No files matched your search
+145
@@ -0,0 +1,145 @@
|
||||
# Changelog
|
||||
|
||||
本项目所有显著变更都会记录在这里。
|
||||
|
||||
格式遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
|
||||
版本号遵循 [Semantic Versioning](https://semver.org/lang/zh-CN/)(带 `V` 前缀,如 `V3.3.3`)。
|
||||
|
||||
变更类型:
|
||||
- `Added` 新增
|
||||
- `Changed` 调整
|
||||
- `Deprecated` 即将废弃
|
||||
- `Removed` 已移除
|
||||
- `Fixed` 修复
|
||||
- `Security` 安全相关
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- 引入完整的版本管理体系:
|
||||
- `CHANGELOG.md`(Keep a Changelog 1.1.0 格式)
|
||||
- `tools/dev/bump_version.py`(自动 bump major/minor/patch + 同步 `version.py` / `pyproject.toml` / `CHANGELOG.md` + 创建 git tag)
|
||||
- `[project]` 元数据加入 `pyproject.toml`,与 `douyin/core/version.py` 保持单一事实来源
|
||||
- 给所有历史版本(V3.0.0 → V3.3.3)补齐 git tag
|
||||
|
||||
### Changed
|
||||
|
||||
- README「版本更新日志」段简化为指向 `CHANGELOG.md` 与 git tags
|
||||
|
||||
## [V3.3.3] — 2025-12-28
|
||||
|
||||
### Added
|
||||
|
||||
- 30 分钟超时保护机制:长时间无成功参与时自动返回推荐页重启流程
|
||||
|
||||
### Fixed
|
||||
|
||||
- 模板与截图路径配置统一,使用 `douyin/core/path_config.py`
|
||||
- 直播间检测模板文件路径错误
|
||||
- GUI / Web GUI 中行为日志读取路径
|
||||
|
||||
### Changed
|
||||
|
||||
- 路径配置全量统一化:用 `path_config.py` 集中管理,简化维护
|
||||
- 行为日志路径统一为 `path_config.get_actions_log_path()`
|
||||
- 流程图与文档:反映 30 分钟超时检查、阶段诊断步骤、预约回退子流程
|
||||
|
||||
## [V3.3.2] — 2025-12-25
|
||||
|
||||
### Fixed
|
||||
|
||||
- 预约回退功能不生效:
|
||||
- `needswitch` 配置未从 `config.json` 正确加载
|
||||
- `self.reservations` 未从状态文件加载
|
||||
- 预约回退逻辑加详细调试日志
|
||||
|
||||
### Changed
|
||||
|
||||
- 每次 `run_once_basic` 自动从状态文件加载预约队列,确保始终包含最新数据
|
||||
|
||||
## [V3.3.1] — 2025-12-14
|
||||
|
||||
### Added
|
||||
|
||||
- `live_room_match_threshold`:直播间检测阈值可配置
|
||||
- `fudai_icon_max_wait_seconds`:福袋图标检测等待时间可配置
|
||||
|
||||
### Fixed
|
||||
|
||||
- 直播间检测模板文件路径警告
|
||||
|
||||
### Changed
|
||||
|
||||
- 阶段检测优先使用像素检测
|
||||
- 合并阶段 1.5 与阶段 3 的 OCR 检测以减少冗余
|
||||
|
||||
## [V3.3.0]
|
||||
|
||||
### Changed
|
||||
|
||||
- 模块化重构:核心代码按职责拆分到 `douyin/` 各子包
|
||||
- 阶段检测策略调整:像素检测优先
|
||||
|
||||
### Added
|
||||
|
||||
- GUI 截图 + OCR 联合调试功能
|
||||
- 桌面 GUI「强制停止」按钮
|
||||
|
||||
### Fixed
|
||||
|
||||
- 多个已知问题(详情见 commit 历史)
|
||||
|
||||
## [V3.2.0]
|
||||
|
||||
### Added
|
||||
|
||||
- 高价值福袋预约功能(`high_value_fudai_*` 配置族)
|
||||
- 高价值直播间回访功能(`high_value_room_revisit_*`)
|
||||
|
||||
### Changed
|
||||
|
||||
- 推荐页养号逻辑优化
|
||||
|
||||
## [V3.1.0]
|
||||
|
||||
### Added
|
||||
|
||||
- 推荐页养号功能:自动点赞 / 收藏 / 评论(按概率)
|
||||
|
||||
### Changed
|
||||
|
||||
- OCR 识别准确率提升
|
||||
|
||||
## [V3.0.0]
|
||||
|
||||
### Changed
|
||||
|
||||
- **重大更新**:OCR 引擎从 pytesseract 切换到 PaddleOCR
|
||||
|
||||
### Added
|
||||
|
||||
- 自动分辨率适配
|
||||
|
||||
### Fixed
|
||||
|
||||
- 大量已知问题
|
||||
|
||||
## V2.x
|
||||
|
||||
- 多分辨率支持
|
||||
- 稳定性提升
|
||||
- 各种 bug 修复
|
||||
|
||||
## V1.x
|
||||
|
||||
- 基础功能:福袋检测、参与、自动领奖
|
||||
|
||||
[Unreleased]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.3...HEAD
|
||||
[V3.3.3]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.2...v3.3.3
|
||||
[V3.3.2]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.1...v3.3.2
|
||||
[V3.3.1]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.0...v3.3.1
|
||||
[V3.3.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.2.0...v3.3.0
|
||||
[V3.2.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.1.0...v3.2.0
|
||||
[V3.1.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.0.0...v3.1.0
|
||||
[V3.0.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/releases/tag/v3.0.0
|
||||
+3
-2
@@ -30,11 +30,11 @@ from typing import Dict, Any
|
||||
# 添加项目根到 sys.path(从 bin/ 目录运行时需要)
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.logging.douyin_logging import (
|
||||
cleanup_old_logs,
|
||||
compress_log_file,
|
||||
get_log_stats,
|
||||
path_config
|
||||
)
|
||||
|
||||
|
||||
@@ -178,7 +178,8 @@ def show_monitor_status() -> None:
|
||||
"""显示监控器状态"""
|
||||
print("\n=== 日志监控状态 ===")
|
||||
|
||||
from douyin.logging.douyin_logging import _log_monitor
|
||||
from douyin.logging.douyin_logging_pkg import _common as _logging_state
|
||||
_log_monitor = _logging_state._log_monitor
|
||||
|
||||
if _log_monitor and _log_monitor._running:
|
||||
print("状态: 运行中")
|
||||
|
||||
@@ -59,8 +59,8 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
|
||||
- **OCR后**:保存OCR结果,包含识别文本预览
|
||||
|
||||
**实现位置:**
|
||||
- `Underlying_Operations.py::cut_pic()` - 裁剪图像时保存
|
||||
- `Underlying_Operations.py::analyse_pic_word()` - OCR识别前后保存
|
||||
- `douyin/core/underlying_operations.py::cut_pic()` - 裁剪图像时保存
|
||||
- `douyin/core/underlying_operations.py::analyse_pic_word()` - OCR识别前后保存
|
||||
|
||||
**保存信息:**
|
||||
- 预处理模式(彩色/二值化)
|
||||
@@ -171,7 +171,7 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
|
||||
|
||||
### 目录配置
|
||||
|
||||
调试图像目录通过 `path_config.py` 配置:
|
||||
调试图像目录通过 `douyin/core/path_config.py` 配置:
|
||||
- `get_pic_dir()`: 返回 pic 目录路径
|
||||
- `get_debug_captures_dir()`: 返回调试图像存档目录路径
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
- **截图服务日志说明.md** - 截图服务日志
|
||||
- **日志系统规范文档.md** - 日志系统规范
|
||||
- **日志轮转功能说明.md** - 日志轮转
|
||||
- **ocr_engine_decision.md** - OCR 引擎选型决策记录
|
||||
|
||||
### 流程图
|
||||
- **流程图.md** - 主流程图
|
||||
|
||||
@@ -62,7 +62,7 @@ v4-mobile 综合最优。
|
||||
2. 加 LRU 结果缓存(256 条),重复图直接命中(业务里 cut_pic 短时间常重读相同区域)
|
||||
3. 抽出 `PADDLE_KWARGS` / `_build_paddle()` / `_build_easyocr()` 工厂消除重复
|
||||
|
||||
`Underlying_Operations.py`:
|
||||
`douyin/core/underlying_operations.py`:
|
||||
1. `__init__` / `_ensure_ocr` 都对齐到 Paddle 优先
|
||||
2. `analyse_pic_word` 加缓存层(基于 blake2b 内容哈希 + change_color)
|
||||
3. 删掉小图自动放大+锐化+对比度增强(实测负优化)
|
||||
|
||||
+83
-64
@@ -6,6 +6,25 @@
|
||||
|
||||
说明:本文件为项目主要技术文档的重构版,聚焦“快速上手、配置规范、关键模块地图、运行与排障、验证清单”。文档同时给出可执行的诊断/采样命令,便于自动化采集与 CI 校验。
|
||||
|
||||
> **⚠️ 路径迁移说明(2026-05 之后阅读本文档时请对照)**
|
||||
>
|
||||
> 本文档主体撰写于项目大重构之前,正文里仍出现大量旧路径。重构后实际位置如下(旧 → 新):
|
||||
>
|
||||
> | 文档里写的(旧) | 当前实际位置(新) |
|
||||
> |---|---|
|
||||
> | `Underlying_Operations.py` | `douyin/core/underlying_operations.py` |
|
||||
> | `path_config.py` | `douyin/core/path_config.py` |
|
||||
> | `run_cli.py` | `bin/run_cli.py` |
|
||||
> | `gui_app.py` | `bin/gui_app.py`(launcher)/ `gui/gui_app.py`(实现) |
|
||||
> | `webgui_launcher.py` | `bin/webgui_launcher.py`(launcher)/ `gui/webgui_launcher.py`(实现) |
|
||||
> | `manage_logs.py` | `bin/manage_logs.py` |
|
||||
> | `unified_logger.py` | `douyin/logging/unified_logger.py` |
|
||||
> | `version.py` | `douyin/core/version.py` |
|
||||
> | `from Underlying_Operations import …` | `from douyin.core.underlying_operations import …` |
|
||||
> | `from path_config import …` | `from douyin.core.path_config import …` |
|
||||
>
|
||||
> 入口脚本现在统一放在 `bin/` 下,根目录已不再保留 launcher 转发。文档里所有 `python run_cli.py …` 示例命令请改读为 `python bin/run_cli.py …`,其他入口同理。
|
||||
|
||||
-- 变更记录
|
||||
- 2026-01-18: V4.5 — 修复预约更新后的循环问题,添加强制切换标志防止在同一直播间反复检测。
|
||||
- 2026-01-18: V4.4 — 修复并行OCR重试导致日志/重试噪音,参与失败自动切换直播间;购物红包像素+OCR复查(非直播间也OCR复查);并行OCR完成后写盘映射表以提升回退校验一致性;预约回退纠偏(方向提示)与二次回退改进;GUI映射表自适应列与新增购物红包阈值配置(GUI暴露)。
|
||||
@@ -133,7 +152,7 @@ PY
|
||||
|
||||
- 映射表福袋信息记录修复:
|
||||
- `douyin/fudai/douyin_fudai_core.py`:修复映射表中福袋信息记录缺失问题,在记录映射表前确保`_current_fudai_content`和`_last_fudai_detail_tuple`属性已被正确设置。
|
||||
- `fudai_detail_modules/fudai_detail_reader.py`:优化福袋详情识别完成后映射表记录时机,将并行映射表记录从OCR开始前移动到福袋详情识别完成后,确保福袋内容和详情信息完整记录到映射表。
|
||||
- `douyin/fudai/core/fudai_detail_orchestrator.py`(旧位置:`fudai_detail_modules/fudai_detail_reader.py`,2026-05 合并到 core/):优化福袋详情识别完成后映射表记录时机,将并行映射表记录从OCR开始前移动到福袋详情识别完成后,确保福袋内容和详情信息完整记录到映射表。
|
||||
|
||||
- 预约锁定期保护机制:
|
||||
- `douyin/core/douyin_fudai.py`:修复预约福袋参与成功后锁定期被提前清除的问题,实现依次参与保护机制;参与成功后检查是否还有其他预约,如果有则设置10秒保护期,确保预约福袋依次参与不被其他预约打断;如果没有其他预约则正常清除锁定期。
|
||||
@@ -187,7 +206,7 @@ else:
|
||||
|
||||
# 映射表福袋信息记录验证
|
||||
python -c "
|
||||
from fudai_detail_modules import fudai_detail_reader
|
||||
from douyin.fudai.core import fudai_detail_orchestrator as fudai_detail_reader
|
||||
import inspect
|
||||
source = inspect.getsource(fudai_detail_reader.read_fudai_detail_once)
|
||||
if 'analyser._current_fudai_content = content' in source and 'analyser._last_fudai_detail_tuple = detail_tuple' in source and '在福袋详情识别完成后记录映射表' in source:
|
||||
@@ -214,10 +233,10 @@ else:
|
||||
- 任务计数检测优化:
|
||||
- `douyin/stage/douyin_stage.py`:限制任务计数仅在触发原因 "find_and_open_fudai_detail_click_verification" 时设置,避免重复诊断。
|
||||
- `douyin/fudai/douyin_fudai_core.py`:删除备用阶段检测逻辑,默认任务计数为 0,增加警告日志。
|
||||
- `fudai_detail_modules/fudai_detail_reader.py`:默认任务计数为 0,增强警告日志输出。
|
||||
- `douyin/fudai/core/fudai_detail_orchestrator.py`(旧位置:`fudai_detail_modules/fudai_detail_reader.py`):默认任务计数为 0,增强警告日志输出。
|
||||
- 日志时间戳统一:
|
||||
- `douyin/logging/douyin_logging.py`:新增 MillisecondFormatter 类。
|
||||
- `unified_logger.py`:为 UnifiedFormatter 添加 formatTime 方法。
|
||||
- `douyin/logging/unified_logger.py`:为 UnifiedFormatter 添加 formatTime 方法。
|
||||
- `douyin/logging/action_logger.py`:更新为使用 MillisecondFormatter。
|
||||
- 截图复用优化:
|
||||
- 确保在福袋详情页关闭前复用截图,避免不必要的重复截图。
|
||||
@@ -234,10 +253,10 @@ else:
|
||||
# 语法检查
|
||||
python -m py_compile douyin/stage/douyin_stage.py
|
||||
python -m py_compile douyin/fudai/douyin_fudai_core.py
|
||||
python -m py_compile fudai_detail_modules/fudai_detail_reader.py
|
||||
python -m py_compile douyin/fudai/core/fudai_detail_orchestrator.py
|
||||
|
||||
# 运行短会话验证
|
||||
python run_cli.py --wait-minutes 0 --device-id <ADB_ID>
|
||||
python bin/run_cli.py --wait-minutes 0 --device-id <ADB_ID>
|
||||
|
||||
# 检查日志格式
|
||||
Get-Content logs/actions.log -Tail 10 | Select-String "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}"
|
||||
@@ -260,13 +279,13 @@ pip install -r requirements-minimal.txt
|
||||
3. 运行主流程(单设备示例):
|
||||
|
||||
```powershell
|
||||
python run_cli.py --device-id <ADB_ID> --needswitch
|
||||
python bin/run_cli.py --device-id <ADB_ID> --needswitch
|
||||
```
|
||||
|
||||
4. 调试单次循环:
|
||||
|
||||
```powershell
|
||||
python run_cli.py --device-id <ADB_ID> --wait-minutes 0
|
||||
python bin/run_cli.py --device-id <ADB_ID> --wait-minutes 0
|
||||
```
|
||||
|
||||
说明:如需快速禁用 OCR 启动耗时,可设置环境变量 `SKIP_OCR_INIT=1`。
|
||||
@@ -288,13 +307,13 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 0
|
||||
1. 代码内默认值(常量/类属性)
|
||||
2. `config/config.json`(通过 `path_config.get_config_path()` 获取)
|
||||
3. 环境变量(例如 `SKIP_OCR_INIT`, `DISABLE_SCREENSHOT_MIRROR`)
|
||||
4. 命令行参数(`run_cli.py` 解析,优先级最高,运行时覆盖实例属性)
|
||||
4. 命令行参数(`bin/run_cli.py` 解析,优先级最高,运行时覆盖实例属性)
|
||||
|
||||
示例:通过命令行临时指定设备优先于 `config/config.json` 中的默认设备。
|
||||
|
||||
实现建议与样例:
|
||||
|
||||
- 在 `douyin/utils/douyin_config.py` 中实现 `load_config_from_file(path)` 返回 dict,主流程使用该 dict 初始化分析器并在 `run_cli.py` 中用命令行覆盖字段。
|
||||
- 在 `douyin/utils/douyin_config.py` 中实现 `load_config_from_file(path)` 返回 dict,主流程使用该 dict 初始化分析器并在 `bin/run_cli.py` 中用命令行覆盖字段。
|
||||
- 推荐在 `config/config.json` 中采用明确分组,例如:
|
||||
|
||||
```json
|
||||
@@ -305,7 +324,7 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 0
|
||||
}
|
||||
```
|
||||
|
||||
- 命令行覆盖示例(`run_cli.py` 中解析后合并):
|
||||
- 命令行覆盖示例(`bin/run_cli.py` 中解析后合并):
|
||||
|
||||
```python
|
||||
# pseudo
|
||||
@@ -318,7 +337,7 @@ if args.device_id:
|
||||
- 使用代码内默认值并在日志中写 warning;
|
||||
- 在关键字段(如 `device`、`ocr_engine`)缺失时中断并提示用户。
|
||||
|
||||
关联文件:`config/config.json`,`douyin/utils/douyin_config.py`,`path_config.py`,`run_cli.py`。
|
||||
关联文件:`config/config.json`,`douyin/utils/douyin_config.py`,`douyin/core/path_config.py`,`bin/run_cli.py`。
|
||||
|
||||
## 截图 / OCR / 日志 / 状态(实现细节与故障采样)
|
||||
|
||||
@@ -326,12 +345,12 @@ if args.device_id:
|
||||
|
||||
- 优先方式:`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()` 的实现。
|
||||
- 写入策略:先写入临时文件(例如 `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`)。
|
||||
|
||||
2) OCR(策略与初始化)
|
||||
|
||||
- 优先引擎:EasyOCR(速度与准确性通常最佳);回退:PaddleOCR。实现位于 `Underlying_Operations.analyse_pic_word()`。
|
||||
- 优先引擎:EasyOCR(速度与准确性通常最佳);回退:PaddleOCR。实现位于 `underlying_operations.analyse_pic_word()`。
|
||||
- 延迟初始化:支持 `SKIP_OCR_INIT=1`(跳过启动时初始化),首次调用时会在 `_ensure_ocr()` 进行按需初始化。
|
||||
- 回退与容错:若 OCR 未能初始化或识别失败,函数返回空字符串,上层代码需对空结果做容错与重试。建议生产环境安装 `easyocr` 并允许启动时初始化以减少首次延迟。
|
||||
|
||||
@@ -362,7 +381,7 @@ Remove-Item pic\screenshot.png.tmp -Force -ErrorAction SilentlyContinue
|
||||
- OCR 未初始化或识别异常:
|
||||
|
||||
```python
|
||||
from Underlying_Operations import underlying_operations
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
op = underlying_operations()
|
||||
op._ensure_ocr()
|
||||
print(op.analyse_pic_word('pic/screenshot.png'))
|
||||
@@ -382,7 +401,7 @@ print(op.analyse_pic_word('pic/screenshot.png'))
|
||||
1) 在短时间窗口运行主流程以生成调试图片和日志(注意 `debug_captures.enabled`):
|
||||
|
||||
```powershell
|
||||
python run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
python bin/run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
```
|
||||
|
||||
2) 基于日志时间戳筛选 `pic/` 下的候选图片(示例:按文件修改时间):
|
||||
@@ -419,14 +438,14 @@ powershell -Command "Get-Content tools/coords_report.csv -TotalCount 200 | Out-F
|
||||
python -m py_compile $(git ls-files "**/*.py")
|
||||
```
|
||||
|
||||
- 关键文件存在性检查:确保 `run_cli.py`、`Underlying_Operations.py`、`config/config.json`、`path_config.py` 存在并可被导入。
|
||||
- 关键文件存在性检查:确保 `bin/run_cli.py`、`douyin/core/underlying_operations.py`、`config/config.json`、`douyin/core/path_config.py` 存在并可被导入。
|
||||
|
||||
示例 CI 脚本片段:
|
||||
|
||||
```bash
|
||||
python -m py_compile $(git ls-files "**/*.py") || exit 1
|
||||
python - <<'PY'
|
||||
from path_config import get_reservations_path
|
||||
from douyin.core.path_config import get_reservations_path
|
||||
import os
|
||||
print('reservations path', get_reservations_path())
|
||||
assert os.path.isdir(os.path.dirname(get_reservations_path()))
|
||||
@@ -440,14 +459,14 @@ PY
|
||||
- 项目意图(一句话):自动化在抖音直播中查找并参与“福袋”活动的流程化机器人,包含截图、像素/模板检测、OCR、决策与预约管理。
|
||||
|
||||
- 关键入口(按优先级):
|
||||
- `run_cli.py`:CLI 入口,生成 `fudai_analyse` 实例并开始主循环;适合触发最小可运行示例。
|
||||
- `bin/run_cli.py`:CLI 入口,生成 `fudai_analyse` 实例并开始主循环;适合触发最小可运行示例。
|
||||
- `douyin/core/douyin_fudai.py::fudai_choujiang()`:主循环调度;查看运行状态与错误堆栈。
|
||||
- `Underlying_Operations.py`:底层设备接口(截图、裁剪、OCR)— 对外数据采集点。
|
||||
- `douyin/core/underlying_operations.py`:底层设备接口(截图、裁剪、OCR)— 对外数据采集点。
|
||||
|
||||
- 可调用的“程序式”API(Python)示例:
|
||||
|
||||
```python
|
||||
from Underlying_Operations import underlying_operations
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
op = underlying_operations()
|
||||
# 获取当前截图路径
|
||||
img = op.get_screenshot('<ADB_ID>')
|
||||
@@ -456,7 +475,7 @@ text = op.analyse_pic_word(img)
|
||||
```
|
||||
|
||||
- 关键文件与含义速查表(便于 LLM 快速定位实现细节):
|
||||
- `path_config.py`:统一路径(logs/pic/state)——用于定位运行数据。
|
||||
- `douyin/core/path_config.py`:统一路径(logs/pic/state)——用于定位运行数据。
|
||||
- `douyin/logging/douyin_logging_wrapper.py`:业务日志封装——搜索 `traceId` 与 `stage`。
|
||||
|
||||
- 可观测数据(建议供 AI 检索):
|
||||
@@ -486,22 +505,22 @@ text = op.analyse_pic_word(img)
|
||||
|
||||
6) 参考实现与文件链接
|
||||
|
||||
- 截图与裁剪:`Underlying_Operations.get_screenshot()`、`Underlying_Operations.cut_pic()`。
|
||||
- OCR:`Underlying_Operations.analyse_pic_word()`、`Underlying_Operations.analyse_pic_digits()`。
|
||||
- 截图与裁剪:`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`。
|
||||
- 路径与状态:`douyin/core/path_config.py`、`state/reservations.json`。
|
||||
|
||||
以上补充将帮助运维快速定位截图/OCR/日志相关问题并提供明确采样路径供后续模型/规则优化使用。
|
||||
|
||||
## 核心模块地图(快捷索引)
|
||||
|
||||
- `run_cli.py`:入口,解析命令行并创建 `fudai_analyse`。
|
||||
- `bin/run_cli.py`:入口,解析命令行并创建 `fudai_analyse`。
|
||||
- `douyin/core/douyin_fudai.py`:主分析器/主循环(`fudai_choujiang`、`run_once_basic`)。
|
||||
- `Underlying_Operations.py`:底层设备/截图/OCR/文件操作。
|
||||
- `douyin/core/underlying_operations.py`:底层设备/截图/OCR/文件操作。
|
||||
- `douyin/detection/douyin_pixel.py`:像素检测与并行检测实现。
|
||||
|
||||
- `douyin/fudai/douyin_fudai_core.py`:福袋核心逻辑。
|
||||
- `get_fudai_contain`:获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。调用位置:`douyin/fudai/core/fudai_attend.py` 第214行,`fudai_detail_modules/fudai_detail_reader.py` 第15行和第315行。
|
||||
- `get_fudai_contain`:获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。调用位置:`douyin/fudai/core/fudai_attend.py`、`douyin/fudai/core/fudai_detail_orchestrator.py`(旧位置:`fudai_detail_modules/fudai_detail_reader.py`,已合并到 core/)。具体行号会随重构变化,以代码当前状态为准。
|
||||
- `basic_join_decision`:基础版参与决策,根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。调用位置:`douyin/core/douyin_fudai.py` 第3127行和第3721行。
|
||||
- `attend_choujiang`:点击参与抽奖。调用位置:`douyin/core/douyin_fudai.py` 第2892行,`douyin/core/fudai_modules/fudai_main_logic.py` 第223行,以及文件内多处。
|
||||
- `check_lucky_draw_result`:判定福袋抽奖的结果(简化)。统一只检测开奖结果按钮区域(使用 HelperFunctions.check_lottery_result_by_ocr),不再对弹窗文字或其它区域进行OCR识别。返回:1='我知道了', 2='立即领取奖品', False=未识别。调用位置:文件内第3913行。
|
||||
@@ -527,7 +546,7 @@ text = op.analyse_pic_word(img)
|
||||
|
||||
- `douyin/stage/douyin_stage.py`:阶段诊断入口(`diagnose_stage_from_current_screen`)。
|
||||
- `douyin/reservation/douyin_reservation_logic.py`:预约加载与回退处理。
|
||||
- `path_config.py`:统一路径获取,避免硬编码。
|
||||
- `douyin/core/path_config.py`:统一路径获取,避免硬编码。
|
||||
|
||||
在文档中引用这些文件并包含小示例会帮助维护者快速定位实现点。
|
||||
|
||||
@@ -573,7 +592,7 @@ text = op.analyse_pic_word(img)
|
||||
|
||||
## 运行流程概览(精简)
|
||||
|
||||
1. `run_cli.py` -> 创建 `fudai_analyse` -> `load_config()` -> `fudai_choujiang()`
|
||||
1. `bin/run_cli.py` -> 创建 `fudai_analyse` -> `load_config()` -> `fudai_choujiang()`
|
||||
2. `fudai_choujiang()` 循环调用 `run_once_basic()`
|
||||
3. `run_once_basic()` 流程要点:
|
||||
- 处理等待开奖 / 预约回退
|
||||
@@ -586,7 +605,7 @@ text = op.analyse_pic_word(img)
|
||||
1. 验证截图是否可用:
|
||||
|
||||
```powershell
|
||||
python -c "from Underlying_Operations import underlying_operations; op=underlying_operations(); print(op.get_screenshot('<DEVICE_ID>'))"
|
||||
python -c "from douyin.core.underlying_operations import underlying_operations; op=underlying_operations(); print(op.get_screenshot('<DEVICE_ID>'))"
|
||||
```
|
||||
|
||||
2. 快速语法检查(仓库级):
|
||||
@@ -599,7 +618,7 @@ python -m py_compile $(git ls-files "**/*.py")
|
||||
|
||||
```powershell
|
||||
# 伪命令示例:运行一段短时日志以产生调试图片
|
||||
python run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
python bin/run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
# 手动或团队自定义脚本筛选 pic/ 下的失败图片并复制到约定目录(例如 tools/samples/)
|
||||
```
|
||||
|
||||
@@ -620,7 +639,7 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
## 验证清单(可纳入 CI)
|
||||
|
||||
1. `python -m py_compile` 全仓库通过。
|
||||
2. 关键路径存在检查:`run_cli.py`、`Underlying_Operations.py`、`config/config.json`、`path_config.py`。
|
||||
2. 关键路径存在检查:`bin/run_cli.py`、`douyin/core/underlying_operations.py`、`config/config.json`、`douyin/core/path_config.py`。
|
||||
3. `path_config.get_reservations_path()` 返回文件夹存在性检查。
|
||||
|
||||
示例 CI 命令片段:
|
||||
@@ -628,7 +647,7 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
```bash
|
||||
python -m py_compile $(git ls-files "**/*.py") || exit 1
|
||||
python - <<'PY'
|
||||
from path_config import get_reservations_path
|
||||
from douyin.core.path_config import get_reservations_path
|
||||
import os
|
||||
print('reservations path', get_reservations_path())
|
||||
assert os.path.isdir(os.path.dirname(get_reservations_path()))
|
||||
@@ -941,7 +960,7 @@ _handle_in_fudai_detail()
|
||||
|
||||
#### `run_cli.py::main(argv: list[str]) -> int`
|
||||
|
||||
- **文件位置**: `run_cli.py`
|
||||
- **文件位置**: `bin/run_cli.py`
|
||||
- **作用**: 命令行入口函数,解析参数并启动主程序
|
||||
- **参数**:
|
||||
- `argv`: 命令行参数列表
|
||||
@@ -1860,7 +1879,7 @@ def attend_choujiang(analyser) -> bool:
|
||||
```python
|
||||
def load_reservations_from_state(analyser) -> list:
|
||||
import json
|
||||
import path_config
|
||||
from douyin.core import path_config
|
||||
|
||||
reservations_path = path_config.get_reservations_path()
|
||||
if not os.path.exists(reservations_path):
|
||||
@@ -2250,19 +2269,19 @@ is_match, reason, debug = match_reservation(item, detail)
|
||||
|
||||
## 5. 底层操作函数
|
||||
|
||||
底层操作函数封装在 `Underlying_Operations.py` 的 `underlying_operations` 类中,提供设备控制、截图、OCR、图像处理等基础功能。
|
||||
底层操作函数封装在 `douyin/core/underlying_operations.py` 的 `underlying_operations` 类中,提供设备控制、截图、OCR、图像处理等基础功能。
|
||||
|
||||
### 5.1 设备操作函数
|
||||
|
||||
#### `underlying_operations.select_device() -> str | bool`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 选择需要连接的Android设备
|
||||
- **参数**: 无
|
||||
- **返回值**:
|
||||
- `str`: 设备ID(单设备或多设备选择后)
|
||||
- `False`: 无设备连接
|
||||
- **调用位置**: `run_cli.py` 的 `main()` 函数中调用
|
||||
- **调用位置**: `bin/run_cli.py` 的 `main()` 函数中调用
|
||||
- **实现细节**:
|
||||
- 执行 `adb devices` 命令获取设备列表
|
||||
- 使用正则表达式提取设备ID(支持IP地址和序列号)
|
||||
@@ -2281,7 +2300,7 @@ if not device_id:
|
||||
|
||||
#### `underlying_operations.get_device_resolution(device_id: str) -> Tuple[int, int]`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 获取Android设备的分辨率
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2301,7 +2320,7 @@ analyser.resolution_ratio_y = height
|
||||
|
||||
#### `underlying_operations.click(device_id: str, x: int, y: int) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 在设备屏幕上点击指定坐标
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2320,7 +2339,7 @@ operation.click(device_id, 540, 1200) # 点击屏幕中心
|
||||
|
||||
#### `underlying_operations.click_back(device_id: str) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 点击Android返回键(KEYCODE_BACK)
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2331,7 +2350,7 @@ operation.click(device_id, 540, 1200) # 点击屏幕中心
|
||||
|
||||
#### `underlying_operations.click_confirm(device_id: str) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 点击确认键(KEYCODE_ENTER)
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2344,7 +2363,7 @@ operation.click(device_id, 540, 1200) # 点击屏幕中心
|
||||
|
||||
#### `underlying_operations.get_screenshot(device_id: str, path: str = "pic") -> bool`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 获取设备屏幕截图并保存到本地
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2380,7 +2399,7 @@ else:
|
||||
|
||||
#### `underlying_operations.save_reward_pic(device_id: str) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 保存中奖截图(带时间戳)
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2395,7 +2414,7 @@ else:
|
||||
|
||||
#### `underlying_operations.cut_pic(left_up: Tuple[int, int] = (0, 63), right_down: Tuple[int, int] = (1080, 1620), target: str = "", name: str = "") -> bool`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 裁剪图片,获取指定区域的子图片(用于OCR识别)
|
||||
- **参数**:
|
||||
- `left_up: Tuple[int, int]`: 左上角坐标(默认(0, 63))
|
||||
@@ -2432,7 +2451,7 @@ else:
|
||||
|
||||
#### `underlying_operations.analyse_pic_word(picname: str, change_color: int = 0, pic_path: Optional[str] = None) -> str`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 对指定图片运行OCR识别,返回拼接后的文本结果
|
||||
- **参数**:
|
||||
- `picname: str`: 图片名称(不含扩展名,如"福袋内容")
|
||||
@@ -2475,7 +2494,7 @@ else:
|
||||
|
||||
#### `underlying_operations.analyse_pic_digits(picname: str, change_color: int = 1, pic_path: Optional[str] = None) -> str`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 对指定图片运行OCR识别,专门用于识别数字(倒计时、价值、参与人数等)
|
||||
- **参数**:
|
||||
- `picname: str`: 图片名称(不含扩展名,如"倒计时")
|
||||
@@ -2496,7 +2515,7 @@ countdown_text = operation.analyse_pic_digits("倒计时")
|
||||
|
||||
#### `underlying_operations.extract_ocr_content(content: List, return_confidence: bool = False) -> str | Tuple[str, float]`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 从OCR结果中提取文本内容(去除坐标、置信度等信息)
|
||||
- **参数**:
|
||||
- `content: List`: OCR原始结果(EasyOCR或PaddleOCR格式)
|
||||
@@ -2515,7 +2534,7 @@ countdown_text = operation.analyse_pic_digits("倒计时")
|
||||
|
||||
#### `underlying_operations.swipe(device_id: str, x1: int, y1: int, x2: int, y2: int, duration_ms: int = 600) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 在设备屏幕上执行滑动操作(从起点滑动到终点)
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2543,7 +2562,7 @@ operation.swipe(device_id, 540, 1800, 540, 800, duration_ms=600)
|
||||
|
||||
#### `underlying_operations.delay(seconds: float = 1.0) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 延迟指定秒数
|
||||
- **参数**:
|
||||
- `seconds: float`: 延迟秒数(默认1.0秒)
|
||||
@@ -2552,7 +2571,7 @@ operation.swipe(device_id, 540, 1800, 540, 800, duration_ms=600)
|
||||
|
||||
#### `underlying_operations.random_delay(min_seconds: float = 1.0, max_seconds: float = 100.0) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 随机延迟指定范围内的秒数(模拟人工操作)
|
||||
- **参数**:
|
||||
- `min_seconds: float`: 最小延迟秒数(默认1.0秒)
|
||||
@@ -2562,7 +2581,7 @@ operation.swipe(device_id, 540, 1800, 540, 800, duration_ms=600)
|
||||
|
||||
#### `underlying_operations.check_countdown(last_time: str = "") -> Optional[int]`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 检查倒计时文本,转换为剩余秒数
|
||||
- **参数**:
|
||||
- `last_time: str`: 倒计时文本(格式:`mm:ss` 或 `m:ss` 或 `ss`)
|
||||
@@ -2582,7 +2601,7 @@ remaining_seconds = operation.check_countdown(countdown_text)
|
||||
|
||||
#### `underlying_operations.get_current_hour() -> int`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 获取当前时间的小时数(0-23)
|
||||
- **参数**: 无
|
||||
- **返回值**: `int` - 当前小时数(0-23)
|
||||
@@ -2916,7 +2935,7 @@ class fudai_analyse(
|
||||
- `needswitch: bool` - 是否允许切换直播间
|
||||
- `wait_minutes: int` - 每次循环等待时间(分钟)
|
||||
- **实现**: 设置设备ID和配置,然后循环调用 `run_once_basic()`
|
||||
- **调用位置**: `run_cli.py` 的 `main()` 函数中调用
|
||||
- **调用位置**: `bin/run_cli.py` 的 `main()` 函数中调用
|
||||
|
||||
#### 6.2.7 BaseFudaiMixin(基础混入类)
|
||||
|
||||
@@ -3030,7 +3049,7 @@ UNKNOWN = "UNKNOWN" # 未知阶段
|
||||
|
||||
配置文件位于 `config/config.json`,路径通过 `path_config.get_config_path()` 获取。
|
||||
|
||||
### 7.1.1 `path_config.py` 用法
|
||||
### 7.1.1 `douyin/core/path_config.py` 用法
|
||||
|
||||
- 使用 `path_config.get_config_path()` 获取配置文件的绝对路径;
|
||||
- 常用路径获取函数:
|
||||
@@ -3047,9 +3066,9 @@ UNKNOWN = "UNKNOWN" # 未知阶段
|
||||
1. 代码中内置的默认值(类属性或常量);
|
||||
2. `config/config.json`(通过 `path_config.get_config_path()` 指定的文件);
|
||||
3. 环境变量(仅少数开关被代码显式读取,如 `SKIP_OCR_INIT`, `EXTERNAL_DOUYIN_FUDAI_DIR`, `DISABLE_MODEL_SOURCE_CHECK`, `DISABLE_SCREENSHOT_MIRROR` 等);
|
||||
4. 命令行参数(`run_cli.py` 中解析的参数,会在创建 `fudai_analyse` 实例后覆盖运行时属性——命令行优先级最高)。
|
||||
4. 命令行参数(`bin/run_cli.py` 中解析的参数,会在创建 `fudai_analyse` 实例后覆盖运行时属性——命令行优先级最高)。
|
||||
|
||||
说明:实际运行时 `fudai_analyse.__init__()` 会加载 `config.json`(若存在),随后 `run_cli.py` 会将命令行参数按需覆盖分析器属性;因此临时调试请优先使用命令行参数,长期配置请写入 `config/config.json`。
|
||||
说明:实际运行时 `fudai_analyse.__init__()` 会加载 `config.json`(若存在),随后 `bin/run_cli.py` 会将命令行参数按需覆盖分析器属性;因此临时调试请优先使用命令行参数,长期配置请写入 `config/config.json`。
|
||||
|
||||
|
||||
### 7.2 配置项详解
|
||||
@@ -3940,7 +3959,7 @@ logger.error(
|
||||
```python
|
||||
# run_cli.py
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
from Underlying_Operations import underlying_operations
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
|
||||
# 初始化
|
||||
operation = underlying_operations()
|
||||
@@ -4673,7 +4692,7 @@ self.new_config_item = self.config.get("new_config_item", False)
|
||||
|
||||
#### 15.1.1 入口文件
|
||||
|
||||
- **`run_cli.py`**: 命令行入口,初始化设备和分析器
|
||||
- **`bin/run_cli.py`**: 命令行入口,初始化设备和分析器
|
||||
- **`gui/gui_app.py`**: Tkinter GUI入口
|
||||
- **`gui/web_gui.py`**: Web GUI入口
|
||||
|
||||
@@ -4706,7 +4725,7 @@ self.new_config_item = self.config.get("new_config_item", False)
|
||||
|
||||
#### 15.1.7 底层操作
|
||||
|
||||
- **`Underlying_Operations.py`**: 底层操作类(ADB、OCR、图像处理)
|
||||
- **`douyin/core/underlying_operations.py`**: 底层操作类(ADB、OCR、图像处理)
|
||||
|
||||
#### 15.1.8 配置文件
|
||||
|
||||
@@ -7097,13 +7116,13 @@ debug_logger.log_exception(e, context={"step": "处理福袋"})
|
||||
示例:快速启用截图镜像并保留调试图像(Linux/WSL 或 PowerShell 环境变量用法相似)
|
||||
|
||||
```bash
|
||||
EXTERNAL_DOUYIN_FUDAI_DIR=<外部调试目录> SKIP_OCR_INIT=1 python run_cli.py --device-id <DEVICE_ID> --needswitch
|
||||
EXTERNAL_DOUYIN_FUDAI_DIR=<外部调试目录> SKIP_OCR_INIT=1 python bin/run_cli.py --device-id <DEVICE_ID> --needswitch
|
||||
```
|
||||
|
||||
示例:禁用截图镜像以提高性能
|
||||
|
||||
```bash
|
||||
DISABLE_SCREENSHOT_MIRROR=1 python run_cli.py --device-id <DEVICE_ID>
|
||||
DISABLE_SCREENSHOT_MIRROR=1 python bin/run_cli.py --device-id <DEVICE_ID>
|
||||
```
|
||||
|
||||
|
||||
@@ -7197,7 +7216,7 @@ result = analyser.operation.analyse_pic_word(preprocessed_name, 0)
|
||||
|
||||
#### 24.2.2 OCR识别优化
|
||||
|
||||
**文件位置**: `Underlying_Operations.py`
|
||||
**文件位置**: `douyin/core/underlying_operations.py`
|
||||
|
||||
**优化措施**:
|
||||
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ python gui_app.py
|
||||
```
|
||||
|
||||
#### 方法3:在代码中修改
|
||||
修改 `Underlying_Operations.py` 中的 `_detect_gpu_available` 方法,将核显检测部分改为:
|
||||
修改 `douyin/core/underlying_operations.py` 中的 `_detect_gpu_available` 方法,将核显检测部分改为:
|
||||
```python
|
||||
if is_integrated:
|
||||
# 核显:尝试使用GPU加速
|
||||
|
||||
@@ -1,706 +1,23 @@
|
||||
"""
|
||||
Flow control main helpers (本地模块化实现,基础版)
|
||||
================================================
|
||||
"""douyin_flow_control - 兼容入口(保留外部 import 路径)。
|
||||
|
||||
当前只实现与你"基础抢福袋、不启用预约"相关的核心流程:
|
||||
- handle_stage_after_diagnosis:记录阶段信息(暂不做复杂跳转)
|
||||
- find_and_open_fudai_detail:通过像素检测福袋图标并点击打开详情
|
||||
- handle_no_fudai_situation:在没有福袋时做简单的等待/上滑切换
|
||||
- filter_fudai_detail:根据 config.json 对福袋进行基础筛选
|
||||
实际实现位于子包 ``douyin.core.douyin_flow_control_pkg``。
|
||||
本文件仅 re-export 公共符号;详见各子模块文档:
|
||||
- ``douyin_flow_control_pkg.stage_handler`` handle_stage_after_diagnosis
|
||||
- ``douyin_flow_control_pkg.find_open`` find_and_open_fudai_detail(最大头 520 行)
|
||||
- ``douyin_flow_control_pkg.filter`` filter_fudai_detail
|
||||
- ``douyin_flow_control_pkg.no_fudai`` handle_no_fudai_situation
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from douyin.core.douyin_flow_control_pkg import (
|
||||
filter_fudai_detail,
|
||||
find_and_open_fudai_detail,
|
||||
handle_no_fudai_situation,
|
||||
handle_stage_after_diagnosis,
|
||||
)
|
||||
|
||||
from typing import Any, Callable, List, Optional, Tuple
|
||||
import logging
|
||||
import time
|
||||
import os
|
||||
|
||||
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
|
||||
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
|
||||
from douyin.core import path_config
|
||||
|
||||
|
||||
def handle_stage_after_diagnosis(
|
||||
analyser: Any,
|
||||
stage: str,
|
||||
seen: str,
|
||||
func_start_time: float | None = None,
|
||||
):
|
||||
if func_start_time is None:
|
||||
func_start_time = time.time()
|
||||
|
||||
return find_and_open_fudai_detail(
|
||||
analyser=analyser,
|
||||
stage=stage,
|
||||
seen=seen,
|
||||
func_start_time=func_start_time,
|
||||
)
|
||||
|
||||
|
||||
def find_and_open_fudai_detail(
|
||||
analyser: Any,
|
||||
stage: Any = "",
|
||||
seen: Any = "",
|
||||
func_start_time: float | None = None,
|
||||
):
|
||||
"""主实现:检测福袋图标并点击打开详情页。"""
|
||||
if func_start_time is None:
|
||||
func_start_time = time.time()
|
||||
|
||||
# 如果正在等待开奖,不应该再次打开福袋详情
|
||||
try:
|
||||
if getattr(analyser, "_waiting_for_lottery_result", False):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情",
|
||||
)
|
||||
except Exception as e:
|
||||
logging.debug("日志记录失败: %s", e)
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(等待开奖中)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception as e:
|
||||
logging.debug("检查等待开奖状态失败: %s", e)
|
||||
|
||||
device_id = getattr(analyser, "device_id", "")
|
||||
|
||||
# 1. 利用像素检测福袋图标的 X 坐标(1080 基准)
|
||||
# 在配置的最大等待时间内重复检测福袋图标
|
||||
max_wait_seconds = float(
|
||||
getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0
|
||||
)
|
||||
retry_delay_seconds = float(
|
||||
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
|
||||
)
|
||||
|
||||
start_time = time.time()
|
||||
x = False
|
||||
|
||||
while (time.time() - start_time) < max_wait_seconds:
|
||||
# 在调用检测函数之前,检查是否还有足够的时间
|
||||
elapsed = time.time() - start_time
|
||||
remaining = max_wait_seconds - elapsed
|
||||
|
||||
# 如果剩余时间不足 1 秒,停止继续检测(避免子函数超时)
|
||||
if remaining < 1.0:
|
||||
break
|
||||
|
||||
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
|
||||
if not x:
|
||||
# 再次检查时间,防止第二次调用导致超时
|
||||
elapsed = time.time() - start_time
|
||||
if (elapsed + 2.0) < max_wait_seconds: # 预留 2 秒给第二次调用
|
||||
x = check_have_fudai_with_ready_screenshot(
|
||||
analyser, screenshot_ready=False
|
||||
)
|
||||
if x:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:检测到福袋图标",
|
||||
x=int(x or 0),
|
||||
elapsed_seconds=round(time.time() - start_time, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 结构化统计:检测到福袋(attempt)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_detected",
|
||||
metric_type="attempt",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
fudai_x=int(x or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
remaining = max_wait_seconds - elapsed
|
||||
if remaining <= 0:
|
||||
break
|
||||
|
||||
wait_time = min(retry_delay_seconds, remaining)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:未检测到福袋图标,等待后重试",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
remaining_seconds=round(remaining, 2),
|
||||
wait_seconds=round(wait_time, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.operation.delay(wait_time)
|
||||
except Exception:
|
||||
time.sleep(wait_time)
|
||||
|
||||
if not x:
|
||||
try:
|
||||
total_elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:等待超时,未检测到福袋图标",
|
||||
x=int(x or 0),
|
||||
max_wait_seconds=max_wait_seconds,
|
||||
total_elapsed_seconds=round(total_elapsed, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(未找到福袋)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
# 未找到福袋:增加连续未找到计数(由 analyser 维护),以便触发退出直播间动作
|
||||
try:
|
||||
cur = int(getattr(analyser, "_consecutive_no_fudai_count", 0) or 0)
|
||||
cur += 1
|
||||
setattr(analyser, "_consecutive_no_fudai_count", cur)
|
||||
threshold = (
|
||||
int(getattr(analyser, "fudai_exit_after_misses", 0) or 0) or None
|
||||
)
|
||||
if threshold is None or threshold <= 0:
|
||||
# 如果未配置阈值,则尝试读取配置属性(兼容性)
|
||||
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)
|
||||
threshold = int(
|
||||
cfg.get("fudai_exit_after_misses", 30) or 30
|
||||
)
|
||||
except Exception:
|
||||
threshold = 30
|
||||
# 如果计数达到阈值,执行返回键退出直播间并重置计数
|
||||
if threshold and cur >= threshold:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"连续未找到福袋达到阈值:按返回键退出直播间",
|
||||
consecutive_no_fudai=cur,
|
||||
threshold=threshold,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 检查是否启用了返回键回退(优先 analyser 属性,回退到配置文件)
|
||||
enabled = getattr(analyser, "enable_back_on_misses", None)
|
||||
if enabled is None:
|
||||
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)
|
||||
enabled = bool(cfg.get("enable_back_on_misses", True))
|
||||
else:
|
||||
enabled = True
|
||||
except Exception:
|
||||
enabled = True
|
||||
|
||||
if enabled:
|
||||
# 若最近已有由滑动重置触发的回退,且在短时间内,跳过本次返回键调用以避免重复
|
||||
try:
|
||||
import time as _time
|
||||
|
||||
recent_ts = getattr(analyser, "_recent_reset_ts", 0)
|
||||
if recent_ts and (_time.time() - float(recent_ts) < 5.0):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"检测到近期已由滑动重置触发回退,跳过重复按返回键",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception:
|
||||
try:
|
||||
# 兜底:使用通用 click 返回坐标
|
||||
rx = int(
|
||||
getattr(analyser, "resolution_ratio_x", 1080)
|
||||
or 1080
|
||||
)
|
||||
ry = int(
|
||||
getattr(analyser, "resolution_ratio_y", 2400)
|
||||
or 2400
|
||||
)
|
||||
back_x = int(50 * rx / 1080)
|
||||
back_y = int(50 * ry / 2400)
|
||||
analyser.operation.click(
|
||||
analyser.device_id, back_x, back_y
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 在异常情况下保守地尝试按返回键
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"返回键回退已禁用,跳过按返回键",
|
||||
consecutive_no_fudai=cur,
|
||||
threshold=threshold,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 重置计数,避免重复触发
|
||||
try:
|
||||
setattr(analyser, "_consecutive_no_fudai_count", 0)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 容错:如果处理计数或配置读取出错,忽略并继续返回 False
|
||||
pass
|
||||
return False
|
||||
|
||||
# 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度)
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
|
||||
base_y = 403 # 与检测时使用的同一水平线附近
|
||||
click_x = int(x * rx / 1080)
|
||||
click_y = int(base_y * ry / 2400)
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:检测到福袋图标并点击",
|
||||
fudai_x=int(x),
|
||||
click_x=click_x,
|
||||
click_y=click_y,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 结构化统计:点击尝试
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_click_attempt",
|
||||
metric_type="attempt",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
fudai_x=int(x or 0),
|
||||
click_x=click_x,
|
||||
click_y=click_y,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存)
|
||||
try:
|
||||
from PIL import Image # type: ignore[import]
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(screenshot_path):
|
||||
img = Image.open(screenshot_path)
|
||||
img.load()
|
||||
pic_rgb_full = img.convert("RGB")
|
||||
try:
|
||||
box_r = 30
|
||||
coord_box = (
|
||||
max(0, click_x - box_r),
|
||||
max(0, click_y - box_r),
|
||||
click_x + box_r,
|
||||
click_y + box_r,
|
||||
)
|
||||
except Exception:
|
||||
coord_box = None
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=coord_box,
|
||||
extra_info={
|
||||
"source": "flow_on_detect",
|
||||
"click_x": click_x,
|
||||
"click_y": click_y,
|
||||
"detected_x_scaled": click_x,
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"流程检测到福袋图标后保存完整截图",
|
||||
path=debug_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 优先走底层 operation.click,失败再尝试 analyser.click
|
||||
try:
|
||||
analyser.operation.click(device_id, click_x, click_y)
|
||||
|
||||
wait_seconds = float(getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后固定等待",
|
||||
wait_seconds=wait_seconds,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.operation.delay(wait_seconds)
|
||||
except Exception:
|
||||
time.sleep(wait_seconds)
|
||||
|
||||
from douyin.stage import douyin_stage
|
||||
|
||||
analyser.operation.get_screenshot(device_id, use_service=False)
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if not os.path.exists(pic_path):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后截图文件不存在,无法验证",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
try:
|
||||
result = douyin_stage.diagnose_stage_from_current_screen(
|
||||
analyser, trigger_reason="find_and_open_fudai_detail_click_verification"
|
||||
)
|
||||
if result is None:
|
||||
stage, reason = (
|
||||
"IN_LIVE_ROOM",
|
||||
"阶段诊断返回 None,默认判定为在直播间",
|
||||
)
|
||||
else:
|
||||
stage, reason = result
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后阶段检测",
|
||||
stage=stage,
|
||||
reason=reason,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if stage == "FUDai_DETAIL":
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后阶段检测确认在福袋详情页",
|
||||
stage=stage,
|
||||
reason=reason,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
# 调试信息:记录阶段诊断后是否已保存任务数量及是否可复用截图
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:阶段诊断后诊断结果状态",
|
||||
task_count_from_stage=getattr(
|
||||
analyser, "_fudai_detail_task_count_from_stage", None
|
||||
),
|
||||
screenshot_ready_for_ocr=getattr(
|
||||
analyser, "_screenshot_ready_for_ocr", False
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._fudai_detail_first_read = False
|
||||
analyser._last_fudai_detail_tuple = None
|
||||
except Exception:
|
||||
pass
|
||||
# 成功打开福袋详情:重置连续未找到计数
|
||||
try:
|
||||
setattr(analyser, "_consecutive_no_fudai_count", 0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(成功打开详情)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
try:
|
||||
# 结构化统计:成功打开详情(success)
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_open_detail",
|
||||
metric_type="success",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
fudai_x=int(x or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后阶段检测未在福袋详情页,可能误点击",
|
||||
stage=stage,
|
||||
reason=reason,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
try:
|
||||
back_click_x = int(520 * rx / 1080)
|
||||
back_click_y = int(505 * ry / 2400)
|
||||
except Exception:
|
||||
back_click_x, back_click_y = 520, 505
|
||||
|
||||
try:
|
||||
analyser.operation.click(device_id, back_click_x, back_click_y)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.click(back_click_x, back_click_y)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.operation.delay(1.0)
|
||||
except Exception:
|
||||
time.sleep(1.0)
|
||||
|
||||
try:
|
||||
analyser.last_fudai_x = 0
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(误点击)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_open_detail",
|
||||
metric_type="fail",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
fudai_x=int(x or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后阶段检测异常",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(阶段检测异常)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
try:
|
||||
analyser.click(x, base_y)
|
||||
wait_seconds = float(
|
||||
getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0
|
||||
)
|
||||
analyser.operation.delay(wait_seconds)
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(兜底成功)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(兜底失败)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def filter_fudai_detail(
|
||||
analyser: Any,
|
||||
detail: tuple,
|
||||
x: int,
|
||||
needswitch: bool,
|
||||
post_switch_delay_s: float,
|
||||
close_detail_callback,
|
||||
swipe_up_switch_callback,
|
||||
add_reservation_callback,
|
||||
) -> bool:
|
||||
"""福袋详情过滤逻辑:根据 config.json 对福袋进行基础筛选。"""
|
||||
start_time = time.time()
|
||||
skip, reason = should_skip_fudai_by_config(analyser, detail)
|
||||
try:
|
||||
content = (
|
||||
str(detail[0] or "")
|
||||
if isinstance(detail, tuple) and len(detail) >= 1
|
||||
else ""
|
||||
)
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"filter_fudai_detail",
|
||||
x=x,
|
||||
needswitch=needswitch,
|
||||
skip=int(bool(skip)),
|
||||
reason=reason,
|
||||
content_preview=content[:60] if content else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not skip:
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"filter_fudai_detail完成(筛选通过)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
close_detail_callback(analyser)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if needswitch and swipe_up_switch_callback:
|
||||
try:
|
||||
swipe_up_switch_callback()
|
||||
analyser.operation.delay(post_switch_delay_s or 1.2)
|
||||
except Exception:
|
||||
try:
|
||||
time.sleep(post_switch_delay_s or 1.2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"filter_fudai_detail完成(筛选不通过)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
reason=reason,
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def handle_no_fudai_situation(
|
||||
analyser: Any,
|
||||
x: int,
|
||||
swipe_times: int,
|
||||
wait_times_ref: List[int],
|
||||
needswitch: bool,
|
||||
reservation_focus_until_ts: float,
|
||||
reservations: list,
|
||||
room_pos: int,
|
||||
post_switch_delay_s: float,
|
||||
swipe_up_switch_callback: Optional[Callable[[], None]],
|
||||
swipe_down_back_callback: Callable[[], None],
|
||||
sort_reservations_callback: Callable[[], None],
|
||||
clear_reservations_callback: Callable[[], None],
|
||||
write_state_callback: Callable[[], None],
|
||||
back_to_list_callback: Callable[[], None],
|
||||
into_list_callback: Callable[[], None],
|
||||
reservation_focus_until_ts_ref: List[float],
|
||||
reset_to_list_after_reservations_ref: List[bool],
|
||||
swipe_times_ref: List[int],
|
||||
seek_reservation_room_callback: Optional[Callable[[dict[str, Any]], bool]] = None,
|
||||
reservation_after_action_pending_ref: Optional[List[bool]] = None,
|
||||
reservation_back_swipe_delay_s: Optional[float] = None,
|
||||
) -> bool:
|
||||
"""处理未找到福袋的逻辑(预约回退 / 切换直播间)。"""
|
||||
|
||||
handled_reservation = False
|
||||
seek_callback = seek_reservation_room_callback or (lambda item: False)
|
||||
reservation_after_action_pending_ref = (
|
||||
reservation_after_action_pending_ref
|
||||
if reservation_after_action_pending_ref
|
||||
else [False]
|
||||
)
|
||||
reservation_back_swipe_delay_s = (
|
||||
reservation_back_swipe_delay_s
|
||||
if reservation_back_swipe_delay_s is not None
|
||||
else float(getattr(analyser, "reservation_back_swipe_delay_s", 0.5) or 0.5)
|
||||
)
|
||||
|
||||
try:
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
|
||||
handled_reservation = (
|
||||
douyin_reservation_logic.process_reservation_attend_window(
|
||||
analyser,
|
||||
reservations,
|
||||
room_pos,
|
||||
reservation_focus_until_ts_ref,
|
||||
reservation_after_action_pending_ref,
|
||||
reservation_back_swipe_delay_s,
|
||||
swipe_down_back_callback,
|
||||
seek_callback,
|
||||
sort_reservations_callback,
|
||||
write_state_callback,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
handled_reservation = False
|
||||
|
||||
if handled_reservation:
|
||||
return True
|
||||
|
||||
if wait_times_ref:
|
||||
wait_times_ref[0] += 1
|
||||
|
||||
if needswitch and swipe_up_switch_callback:
|
||||
try:
|
||||
swipe_up_switch_callback()
|
||||
except Exception:
|
||||
pass
|
||||
delay_seconds = float(post_switch_delay_s or 1.0)
|
||||
try:
|
||||
analyser.operation.delay(delay_seconds)
|
||||
except Exception:
|
||||
time.sleep(delay_seconds)
|
||||
if swipe_times_ref:
|
||||
swipe_times_ref[0] += 1
|
||||
return False
|
||||
__all__ = [
|
||||
"handle_stage_after_diagnosis",
|
||||
"find_and_open_fudai_detail",
|
||||
"filter_fudai_detail",
|
||||
"handle_no_fudai_situation",
|
||||
]
|
||||
@@ -0,0 +1,25 @@
|
||||
"""douyin_flow_control_pkg - 流程控制子包。
|
||||
|
||||
原 douyin/core/douyin_flow_control.py 拆成 4 个子模块:
|
||||
|
||||
- stage_handler handle_stage_after_diagnosis 阶段后状态记录
|
||||
- find_open find_and_open_fudai_detail 找福袋并打开详情(最大头 520 行)
|
||||
- filter filter_fudai_detail 配置筛选决策
|
||||
- no_fudai handle_no_fudai_situation 无福袋时的简单流程
|
||||
|
||||
外部 import 路径不变:
|
||||
``from douyin.core.douyin_flow_control import find_and_open_fudai_detail``
|
||||
仍可用(原文件改成 re-export shim)。
|
||||
"""
|
||||
|
||||
from .stage_handler import handle_stage_after_diagnosis
|
||||
from .find_open import find_and_open_fudai_detail
|
||||
from .filter import filter_fudai_detail
|
||||
from .no_fudai import handle_no_fudai_situation
|
||||
|
||||
__all__ = [
|
||||
"handle_stage_after_diagnosis",
|
||||
"find_and_open_fudai_detail",
|
||||
"filter_fudai_detail",
|
||||
"handle_no_fudai_situation",
|
||||
]
|
||||
@@ -0,0 +1,85 @@
|
||||
"""douyin_flow_control_pkg.filter - 福袋详情筛选决策。
|
||||
|
||||
filter_fudai_detail:调用 should_skip_fudai_by_config 做配置层筛选,
|
||||
返回是否参与的决策。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, List, Optional, Tuple
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
|
||||
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
|
||||
|
||||
|
||||
def filter_fudai_detail(
|
||||
analyser: Any,
|
||||
detail: tuple,
|
||||
x: int,
|
||||
needswitch: bool,
|
||||
post_switch_delay_s: float,
|
||||
close_detail_callback,
|
||||
swipe_up_switch_callback,
|
||||
add_reservation_callback,
|
||||
) -> bool:
|
||||
"""福袋详情过滤逻辑:根据 config.json 对福袋进行基础筛选。"""
|
||||
start_time = time.time()
|
||||
skip, reason = should_skip_fudai_by_config(analyser, detail)
|
||||
try:
|
||||
content = (
|
||||
str(detail[0] or "")
|
||||
if isinstance(detail, tuple) and len(detail) >= 1
|
||||
else ""
|
||||
)
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"filter_fudai_detail",
|
||||
x=x,
|
||||
needswitch=needswitch,
|
||||
skip=int(bool(skip)),
|
||||
reason=reason,
|
||||
content_preview=content[:60] if content else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not skip:
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"filter_fudai_detail完成(筛选通过)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
close_detail_callback(analyser)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if needswitch and swipe_up_switch_callback:
|
||||
try:
|
||||
swipe_up_switch_callback()
|
||||
analyser.operation.delay(post_switch_delay_s or 1.2)
|
||||
except Exception:
|
||||
try:
|
||||
time.sleep(post_switch_delay_s or 1.2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"filter_fudai_detail完成(筛选不通过)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
reason=reason,
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
@@ -0,0 +1,537 @@
|
||||
"""douyin_flow_control_pkg.find_open - 主流程:找福袋图标并打开详情页。
|
||||
|
||||
find_and_open_fudai_detail:通过像素检测 / 模板匹配找到福袋图标位置,
|
||||
点击进入详情页,处理打开失败、被弹窗遮挡等异常情况。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, List, Optional, Tuple
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
|
||||
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
|
||||
|
||||
|
||||
def find_and_open_fudai_detail(
|
||||
analyser: Any,
|
||||
stage: Any = "",
|
||||
seen: Any = "",
|
||||
func_start_time: float | None = None,
|
||||
):
|
||||
"""主实现:检测福袋图标并点击打开详情页。"""
|
||||
if func_start_time is None:
|
||||
func_start_time = time.time()
|
||||
|
||||
# 如果正在等待开奖,不应该再次打开福袋详情
|
||||
try:
|
||||
if getattr(analyser, "_waiting_for_lottery_result", False):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情",
|
||||
)
|
||||
except Exception as e:
|
||||
logging.debug("日志记录失败: %s", e)
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(等待开奖中)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception as e:
|
||||
logging.debug("检查等待开奖状态失败: %s", e)
|
||||
|
||||
device_id = getattr(analyser, "device_id", "")
|
||||
|
||||
# 1. 利用像素检测福袋图标的 X 坐标(1080 基准)
|
||||
# 在配置的最大等待时间内重复检测福袋图标
|
||||
max_wait_seconds = float(
|
||||
getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0
|
||||
)
|
||||
retry_delay_seconds = float(
|
||||
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
|
||||
)
|
||||
|
||||
start_time = time.time()
|
||||
x = False
|
||||
|
||||
while (time.time() - start_time) < max_wait_seconds:
|
||||
# 在调用检测函数之前,检查是否还有足够的时间
|
||||
elapsed = time.time() - start_time
|
||||
remaining = max_wait_seconds - elapsed
|
||||
|
||||
# 如果剩余时间不足 1 秒,停止继续检测(避免子函数超时)
|
||||
if remaining < 1.0:
|
||||
break
|
||||
|
||||
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
|
||||
if not x:
|
||||
# 再次检查时间,防止第二次调用导致超时
|
||||
elapsed = time.time() - start_time
|
||||
if (elapsed + 2.0) < max_wait_seconds: # 预留 2 秒给第二次调用
|
||||
x = check_have_fudai_with_ready_screenshot(
|
||||
analyser, screenshot_ready=False
|
||||
)
|
||||
if x:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:检测到福袋图标",
|
||||
x=int(x or 0),
|
||||
elapsed_seconds=round(time.time() - start_time, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 结构化统计:检测到福袋(attempt)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_detected",
|
||||
metric_type="attempt",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
fudai_x=int(x or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
remaining = max_wait_seconds - elapsed
|
||||
if remaining <= 0:
|
||||
break
|
||||
|
||||
wait_time = min(retry_delay_seconds, remaining)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:未检测到福袋图标,等待后重试",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
remaining_seconds=round(remaining, 2),
|
||||
wait_seconds=round(wait_time, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.operation.delay(wait_time)
|
||||
except Exception:
|
||||
time.sleep(wait_time)
|
||||
|
||||
if not x:
|
||||
try:
|
||||
total_elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:等待超时,未检测到福袋图标",
|
||||
x=int(x or 0),
|
||||
max_wait_seconds=max_wait_seconds,
|
||||
total_elapsed_seconds=round(total_elapsed, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(未找到福袋)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
# 未找到福袋:增加连续未找到计数(由 analyser 维护),以便触发退出直播间动作
|
||||
try:
|
||||
cur = int(getattr(analyser, "_consecutive_no_fudai_count", 0) or 0)
|
||||
cur += 1
|
||||
setattr(analyser, "_consecutive_no_fudai_count", cur)
|
||||
threshold = (
|
||||
int(getattr(analyser, "fudai_exit_after_misses", 0) or 0) or None
|
||||
)
|
||||
if threshold is None or threshold <= 0:
|
||||
# 如果未配置阈值,则尝试读取配置属性(兼容性)
|
||||
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)
|
||||
threshold = int(
|
||||
cfg.get("fudai_exit_after_misses", 30) or 30
|
||||
)
|
||||
except Exception:
|
||||
threshold = 30
|
||||
# 如果计数达到阈值,执行返回键退出直播间并重置计数
|
||||
if threshold and cur >= threshold:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"连续未找到福袋达到阈值:按返回键退出直播间",
|
||||
consecutive_no_fudai=cur,
|
||||
threshold=threshold,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 检查是否启用了返回键回退(优先 analyser 属性,回退到配置文件)
|
||||
enabled = getattr(analyser, "enable_back_on_misses", None)
|
||||
if enabled is None:
|
||||
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)
|
||||
enabled = bool(cfg.get("enable_back_on_misses", True))
|
||||
else:
|
||||
enabled = True
|
||||
except Exception:
|
||||
enabled = True
|
||||
|
||||
if enabled:
|
||||
# 若最近已有由滑动重置触发的回退,且在短时间内,跳过本次返回键调用以避免重复
|
||||
try:
|
||||
import time as _time
|
||||
|
||||
recent_ts = getattr(analyser, "_recent_reset_ts", 0)
|
||||
if recent_ts and (_time.time() - float(recent_ts) < 5.0):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"检测到近期已由滑动重置触发回退,跳过重复按返回键",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception:
|
||||
try:
|
||||
# 兜底:使用通用 click 返回坐标
|
||||
rx = int(
|
||||
getattr(analyser, "resolution_ratio_x", 1080)
|
||||
or 1080
|
||||
)
|
||||
ry = int(
|
||||
getattr(analyser, "resolution_ratio_y", 2400)
|
||||
or 2400
|
||||
)
|
||||
back_x = int(50 * rx / 1080)
|
||||
back_y = int(50 * ry / 2400)
|
||||
analyser.operation.click(
|
||||
analyser.device_id, back_x, back_y
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 在异常情况下保守地尝试按返回键
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"返回键回退已禁用,跳过按返回键",
|
||||
consecutive_no_fudai=cur,
|
||||
threshold=threshold,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 重置计数,避免重复触发
|
||||
try:
|
||||
setattr(analyser, "_consecutive_no_fudai_count", 0)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 容错:如果处理计数或配置读取出错,忽略并继续返回 False
|
||||
pass
|
||||
return False
|
||||
|
||||
# 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度)
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
|
||||
base_y = 403 # 与检测时使用的同一水平线附近
|
||||
click_x = int(x * rx / 1080)
|
||||
click_y = int(base_y * ry / 2400)
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:检测到福袋图标并点击",
|
||||
fudai_x=int(x),
|
||||
click_x=click_x,
|
||||
click_y=click_y,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 结构化统计:点击尝试
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_click_attempt",
|
||||
metric_type="attempt",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
fudai_x=int(x or 0),
|
||||
click_x=click_x,
|
||||
click_y=click_y,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存)
|
||||
try:
|
||||
from PIL import Image # type: ignore[import]
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(screenshot_path):
|
||||
img = Image.open(screenshot_path)
|
||||
img.load()
|
||||
pic_rgb_full = img.convert("RGB")
|
||||
try:
|
||||
box_r = 30
|
||||
coord_box = (
|
||||
max(0, click_x - box_r),
|
||||
max(0, click_y - box_r),
|
||||
click_x + box_r,
|
||||
click_y + box_r,
|
||||
)
|
||||
except Exception:
|
||||
coord_box = None
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=coord_box,
|
||||
extra_info={
|
||||
"source": "flow_on_detect",
|
||||
"click_x": click_x,
|
||||
"click_y": click_y,
|
||||
"detected_x_scaled": click_x,
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"流程检测到福袋图标后保存完整截图",
|
||||
path=debug_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 优先走底层 operation.click,失败再尝试 analyser.click
|
||||
try:
|
||||
analyser.operation.click(device_id, click_x, click_y)
|
||||
|
||||
wait_seconds = float(getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后固定等待",
|
||||
wait_seconds=wait_seconds,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.operation.delay(wait_seconds)
|
||||
except Exception:
|
||||
time.sleep(wait_seconds)
|
||||
|
||||
from douyin.stage import douyin_stage
|
||||
|
||||
analyser.operation.get_screenshot(device_id, use_service=False)
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if not os.path.exists(pic_path):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后截图文件不存在,无法验证",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
try:
|
||||
result = douyin_stage.diagnose_stage_from_current_screen(
|
||||
analyser, trigger_reason="find_and_open_fudai_detail_click_verification"
|
||||
)
|
||||
if result is None:
|
||||
stage, reason = (
|
||||
"IN_LIVE_ROOM",
|
||||
"阶段诊断返回 None,默认判定为在直播间",
|
||||
)
|
||||
else:
|
||||
stage, reason = result
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后阶段检测",
|
||||
stage=stage,
|
||||
reason=reason,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if stage == "FUDai_DETAIL":
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后阶段检测确认在福袋详情页",
|
||||
stage=stage,
|
||||
reason=reason,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
# 调试信息:记录阶段诊断后是否已保存任务数量及是否可复用截图
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:阶段诊断后诊断结果状态",
|
||||
task_count_from_stage=getattr(
|
||||
analyser, "_fudai_detail_task_count_from_stage", None
|
||||
),
|
||||
screenshot_ready_for_ocr=getattr(
|
||||
analyser, "_screenshot_ready_for_ocr", False
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._fudai_detail_first_read = False
|
||||
analyser._last_fudai_detail_tuple = None
|
||||
except Exception:
|
||||
pass
|
||||
# 成功打开福袋详情:重置连续未找到计数
|
||||
try:
|
||||
setattr(analyser, "_consecutive_no_fudai_count", 0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(成功打开详情)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
try:
|
||||
# 结构化统计:成功打开详情(success)
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_open_detail",
|
||||
metric_type="success",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
fudai_x=int(x or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后阶段检测未在福袋详情页,可能误点击",
|
||||
stage=stage,
|
||||
reason=reason,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
try:
|
||||
back_click_x = int(520 * rx / 1080)
|
||||
back_click_y = int(505 * ry / 2400)
|
||||
except Exception:
|
||||
back_click_x, back_click_y = 520, 505
|
||||
|
||||
try:
|
||||
analyser.operation.click(device_id, back_click_x, back_click_y)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.click(back_click_x, back_click_y)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.operation.delay(1.0)
|
||||
except Exception:
|
||||
time.sleep(1.0)
|
||||
|
||||
try:
|
||||
analyser.last_fudai_x = 0
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(误点击)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_open_detail",
|
||||
metric_type="fail",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
fudai_x=int(x or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:点击后阶段检测异常",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(阶段检测异常)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
try:
|
||||
analyser.click(x, base_y)
|
||||
wait_seconds = float(
|
||||
getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0
|
||||
)
|
||||
analyser.operation.delay(wait_seconds)
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(兜底成功)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
elapsed = time.time() - func_start_time
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail完成(兜底失败)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""douyin_flow_control_pkg.no_fudai - 无福袋情况的简单流程。
|
||||
|
||||
handle_no_fudai_situation:在直播间未识别到福袋时做简单的等待 / 上滑切换。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, List, Optional, Tuple
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
|
||||
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
|
||||
|
||||
|
||||
def handle_no_fudai_situation(
|
||||
analyser: Any,
|
||||
x: int,
|
||||
swipe_times: int,
|
||||
wait_times_ref: List[int],
|
||||
needswitch: bool,
|
||||
reservation_focus_until_ts: float,
|
||||
reservations: list,
|
||||
room_pos: int,
|
||||
post_switch_delay_s: float,
|
||||
swipe_up_switch_callback: Optional[Callable[[], None]],
|
||||
swipe_down_back_callback: Callable[[], None],
|
||||
sort_reservations_callback: Callable[[], None],
|
||||
clear_reservations_callback: Callable[[], None],
|
||||
write_state_callback: Callable[[], None],
|
||||
back_to_list_callback: Callable[[], None],
|
||||
into_list_callback: Callable[[], None],
|
||||
reservation_focus_until_ts_ref: List[float],
|
||||
reset_to_list_after_reservations_ref: List[bool],
|
||||
swipe_times_ref: List[int],
|
||||
seek_reservation_room_callback: Optional[Callable[[dict[str, Any]], bool]] = None,
|
||||
reservation_after_action_pending_ref: Optional[List[bool]] = None,
|
||||
reservation_back_swipe_delay_s: Optional[float] = None,
|
||||
) -> bool:
|
||||
"""处理未找到福袋的逻辑(预约回退 / 切换直播间)。"""
|
||||
|
||||
handled_reservation = False
|
||||
seek_callback = seek_reservation_room_callback or (lambda item: False)
|
||||
reservation_after_action_pending_ref = (
|
||||
reservation_after_action_pending_ref
|
||||
if reservation_after_action_pending_ref
|
||||
else [False]
|
||||
)
|
||||
reservation_back_swipe_delay_s = (
|
||||
reservation_back_swipe_delay_s
|
||||
if reservation_back_swipe_delay_s is not None
|
||||
else float(getattr(analyser, "reservation_back_swipe_delay_s", 0.5) or 0.5)
|
||||
)
|
||||
|
||||
try:
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
|
||||
handled_reservation = (
|
||||
douyin_reservation_logic.process_reservation_attend_window(
|
||||
analyser,
|
||||
reservations,
|
||||
room_pos,
|
||||
reservation_focus_until_ts_ref,
|
||||
reservation_after_action_pending_ref,
|
||||
reservation_back_swipe_delay_s,
|
||||
swipe_down_back_callback,
|
||||
seek_callback,
|
||||
sort_reservations_callback,
|
||||
write_state_callback,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
handled_reservation = False
|
||||
|
||||
if handled_reservation:
|
||||
return True
|
||||
|
||||
if wait_times_ref:
|
||||
wait_times_ref[0] += 1
|
||||
|
||||
if needswitch and swipe_up_switch_callback:
|
||||
try:
|
||||
swipe_up_switch_callback()
|
||||
except Exception:
|
||||
pass
|
||||
delay_seconds = float(post_switch_delay_s or 1.0)
|
||||
try:
|
||||
analyser.operation.delay(delay_seconds)
|
||||
except Exception:
|
||||
time.sleep(delay_seconds)
|
||||
if swipe_times_ref:
|
||||
swipe_times_ref[0] += 1
|
||||
return False
|
||||
@@ -0,0 +1,34 @@
|
||||
"""douyin_flow_control_pkg.stage_handler - 阶段诊断后的状态记录。
|
||||
|
||||
handle_stage_after_diagnosis:记录当前阶段信息(暂不做复杂跳转),
|
||||
为基础抢福袋流程的状态机提供锚点。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, List, Optional, Tuple
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
|
||||
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
|
||||
|
||||
|
||||
def handle_stage_after_diagnosis(
|
||||
analyser: Any,
|
||||
stage: str,
|
||||
seen: str,
|
||||
func_start_time: float | None = None,
|
||||
):
|
||||
if func_start_time is None:
|
||||
func_start_time = time.time()
|
||||
|
||||
return find_and_open_fudai_detail(
|
||||
analyser=analyser,
|
||||
stage=stage,
|
||||
seen=seen,
|
||||
func_start_time=func_start_time,
|
||||
)
|
||||
|
||||
|
||||
+129
-3655
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,167 @@
|
||||
"""fudai_choujiang 辅助函数
|
||||
|
||||
从 douyin_fudai.py:fudai_choujiang 中提取的独立子块:
|
||||
- cleanup_stale_screenshot:清理启动时残留的旧截图
|
||||
- resolve_device_resolution:解析设备分辨率(带重试和默认回退)
|
||||
- write_actions_log:写运行起止标记到 actions.log
|
||||
- run_loop_with_timeout:fudai_choujiang 的主循环(定时/无限)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
# 用于 write_actions_log 的 log_dir_anchor:从 helper 文件位置回溯到 douyin_fudai.py 所在目录
|
||||
_ANCHOR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "douyin_fudai.py")
|
||||
|
||||
|
||||
def cleanup_stale_screenshot(analyser) -> None:
|
||||
"""启动时清理旧截图文件,避免复用过期截图。"""
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
os.remove(pic_path)
|
||||
analyser._log_kv(
|
||||
"启动",
|
||||
"清理旧截图文件,避免复用过期截图",
|
||||
path=pic_path,
|
||||
log_type="SCREENSHOT",
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"启动",
|
||||
f"清理旧截图文件失败 - {str(e)}",
|
||||
level="WARNING",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def resolve_device_resolution(analyser) -> None:
|
||||
"""获取设备分辨率(重试 5 次),失败回退到 1080x2400 默认值。
|
||||
|
||||
直接写入 analyser.resolution_ratio_x / analyser.resolution_ratio_y。
|
||||
"""
|
||||
resolved = False
|
||||
if analyser.device_id:
|
||||
for attempt in range(5):
|
||||
try:
|
||||
rx, ry = analyser.operation.get_device_resolution(analyser.device_id)
|
||||
analyser.resolution_ratio_x = int(rx or 1080)
|
||||
analyser.resolution_ratio_y = int(ry or 2400)
|
||||
resolved = True
|
||||
break
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"截图",
|
||||
"获取分辨率失败,重试中",
|
||||
attempt=attempt + 1,
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
logging.warning(
|
||||
f"[DEBUG] get_device_resolution attempt {attempt + 1} failed: {e}"
|
||||
)
|
||||
time.sleep(1.0)
|
||||
if not resolved:
|
||||
try:
|
||||
analyser._log_kv("截图", "使用默认分辨率回退", width=1080, height=2400)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.resolution_ratio_x, analyser.resolution_ratio_y = 1080, 2400
|
||||
|
||||
|
||||
def run_loop_with_timeout(analyser, wait_minutes: int) -> None:
|
||||
"""fudai_choujiang 主循环:定时模式 vs 无限循环模式。
|
||||
|
||||
定时模式(wait_minutes > 0):在 wait_minutes 分钟内反复跑 run_once_basic。
|
||||
无限模式(wait_minutes <= 0):直到 Ctrl+C。
|
||||
|
||||
异常时延迟 2s 后继续,每轮之间延迟 1s 避免频繁截图。
|
||||
"""
|
||||
if wait_minutes and wait_minutes > 0:
|
||||
end_ts = time.time() + int(wait_minutes) * 60
|
||||
while time.time() < end_ts:
|
||||
try:
|
||||
analyser.run_once_basic()
|
||||
except Exception as exc:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"循环",
|
||||
"run_once_basic 异常",
|
||||
error=str(exc),
|
||||
error_type=type(exc).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.delay(2.0)
|
||||
except Exception:
|
||||
time.sleep(2.0)
|
||||
continue
|
||||
|
||||
try:
|
||||
analyser.operation.delay(1.0)
|
||||
except Exception:
|
||||
time.sleep(1.0)
|
||||
|
||||
write_actions_log("程序运行结束(时间到)", _ANCHOR)
|
||||
else:
|
||||
analyser._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)")
|
||||
while True:
|
||||
try:
|
||||
analyser.run_once_basic()
|
||||
except KeyboardInterrupt:
|
||||
analyser._log_kv("循环", "收到中断信号,退出循环")
|
||||
write_actions_log("程序运行结束(中断退出)", _ANCHOR)
|
||||
raise
|
||||
except Exception as exc:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"循环",
|
||||
"run_once_basic 异常",
|
||||
error=str(exc),
|
||||
error_type=type(exc).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.delay(2.0)
|
||||
except Exception:
|
||||
time.sleep(2.0)
|
||||
continue
|
||||
|
||||
try:
|
||||
analyser.operation.delay(1.0)
|
||||
except Exception:
|
||||
time.sleep(1.0)
|
||||
|
||||
|
||||
def write_actions_log(message: str, log_dir_anchor: str) -> None:
|
||||
"""写一条带时间戳的标记到 logs/actions.log。
|
||||
|
||||
log_dir_anchor 用于定位 logs 目录(通常是 douyin_fudai 模块所在目录)。
|
||||
"""
|
||||
try:
|
||||
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(log_dir_anchor), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
with open(
|
||||
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
|
||||
) as f:
|
||||
f.write("=" * 80 + "\n")
|
||||
f.write(f"{ts} - [GUI] - [运行] {message}\n")
|
||||
f.flush()
|
||||
except Exception:
|
||||
pass
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,281 @@
|
||||
"""福袋图像辅助函数
|
||||
|
||||
从 douyin_fudai.py 中提取的图像处理工具函数:
|
||||
- capture_roi_screenshot:捕获 ROI 截图
|
||||
- match_icon_template:模板匹配
|
||||
|
||||
这两个函数原本是 fudai_analyse 类的方法 (_capture_roi_screenshot / _match_icon_template),
|
||||
对 self 的依赖很轻,提取为模块级函数后,类内方法变为薄包装。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
from typing import Tuple
|
||||
|
||||
from PIL import Image, UnidentifiedImageError # type: ignore[import]
|
||||
import numpy as np # type: ignore[import]
|
||||
|
||||
|
||||
def capture_roi_screenshot(
|
||||
analyser,
|
||||
label: str,
|
||||
sx: int,
|
||||
sy: int,
|
||||
size: int,
|
||||
screenshot_path: str | None = None,
|
||||
) -> str:
|
||||
"""捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。
|
||||
|
||||
返回 ROI 图片路径(绝对路径),失败返回空字符串。
|
||||
"""
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
if screenshot_path is None:
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
|
||||
except Exception:
|
||||
pass
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
else:
|
||||
pic_path = screenshot_path
|
||||
if not os.path.exists(pic_path):
|
||||
return ""
|
||||
|
||||
half = int(size // 2)
|
||||
left = int(max(0, sx - half))
|
||||
top = int(max(0, sy - half))
|
||||
right = int(sx + half)
|
||||
bottom = int(sy + half)
|
||||
|
||||
data = None
|
||||
for attempt in range(6):
|
||||
try:
|
||||
try:
|
||||
analyser.operation.get_screenshot(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not os.path.exists(pic_path):
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
sz = os.path.getsize(pic_path)
|
||||
if sz < 1024:
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
with open(pic_path, "rb") as f:
|
||||
data = f.read()
|
||||
if not data or not data.startswith(b"\x89PNG"):
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
if b"IEND" not in data[-512:]:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
|
||||
try:
|
||||
img_test = Image.open(io.BytesIO(data))
|
||||
img_test.verify()
|
||||
except Exception:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
|
||||
break
|
||||
except Exception:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
|
||||
if not data:
|
||||
return ""
|
||||
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img.load()
|
||||
except UnidentifiedImageError:
|
||||
return ""
|
||||
except Exception:
|
||||
try:
|
||||
try:
|
||||
analyser.operation.get_screenshot(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
with open(pic_path, "rb") as f:
|
||||
data2 = f.read()
|
||||
if (
|
||||
data2
|
||||
and data2.startswith(b"\x89PNG")
|
||||
and b"IEND" in data2[-512:]
|
||||
):
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data2))
|
||||
img.load()
|
||||
except Exception:
|
||||
return ""
|
||||
else:
|
||||
return ""
|
||||
except Exception:
|
||||
return ""
|
||||
w, h = img.size
|
||||
left = max(0, min(left, w - 1))
|
||||
top = max(0, min(top, h - 1))
|
||||
right = max(1, min(right, w))
|
||||
bottom = max(1, min(bottom, h))
|
||||
|
||||
roi = img.crop((left, top, right, bottom))
|
||||
out_dir = path_config.get_pic_dir()
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
fname = (
|
||||
f"roi_{label}_{getattr(analyser, '_run_id', 'run')}_{int(time.time())}.png"
|
||||
)
|
||||
out_path = os.path.join(out_dir, fname)
|
||||
roi.save(out_path)
|
||||
return out_path
|
||||
except Exception:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"截图",
|
||||
"_capture_roi_screenshot 失败",
|
||||
label=label,
|
||||
sx=sx,
|
||||
sy=sy,
|
||||
size=size,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def match_icon_template(
|
||||
analyser,
|
||||
roi_path: str,
|
||||
template_path: str,
|
||||
threshold: float | None = None,
|
||||
) -> Tuple[bool, float]:
|
||||
"""对比 ROI 与模板,返回 (detected: bool, score: float)。
|
||||
|
||||
使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。
|
||||
如果提供 `threshold` 则使用该阈值判断匹配,否则回退到配置 `yanghao_icon_match_threshold`。
|
||||
返回 (detected, score),若发生错误或文件缺失返回 (False, 0.0)。
|
||||
"""
|
||||
try:
|
||||
if not roi_path or not os.path.exists(roi_path):
|
||||
return False, 0.0
|
||||
if not template_path or not os.path.exists(template_path):
|
||||
return False, 0.0
|
||||
|
||||
roi_img = Image.open(roi_path).convert("RGB")
|
||||
tpl_img = Image.open(template_path).convert("RGB")
|
||||
|
||||
rw, rh = roi_img.size
|
||||
tw, th = tpl_img.size
|
||||
if tw > rw or th > rh:
|
||||
scale = min(rw / tw, rh / th, 1.0)
|
||||
new_w = max(1, int(tw * scale))
|
||||
new_h = max(1, int(th * scale))
|
||||
tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
||||
tw, th = tpl_img.size
|
||||
|
||||
roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32)
|
||||
tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32)
|
||||
|
||||
if (
|
||||
roi_gray.shape[0] == tpl_gray.shape[0]
|
||||
and roi_gray.shape[1] == tpl_gray.shape[1]
|
||||
):
|
||||
A = roi_gray.flatten()
|
||||
B = tpl_gray.flatten()
|
||||
else:
|
||||
ih, iw = roi_gray.shape
|
||||
th, tw = tpl_gray.shape
|
||||
if ih >= th and iw >= tw:
|
||||
cy = ih // 2 - th // 2
|
||||
cx = iw // 2 - tw // 2
|
||||
cy = max(0, min(cy, ih - th))
|
||||
cx = max(0, min(cx, iw - tw))
|
||||
window = roi_gray[cy : cy + th, cx : cx + tw]
|
||||
a = window.flatten()
|
||||
b = tpl_gray.flatten()
|
||||
a = a - a.mean()
|
||||
b = b - b.mean()
|
||||
denom = np.linalg.norm(a) * np.linalg.norm(b)
|
||||
if denom > 1e-6:
|
||||
score = float(np.dot(a, b) / denom)
|
||||
else:
|
||||
score = -1.0
|
||||
if score >= 0.55:
|
||||
used_thr = (
|
||||
float(threshold)
|
||||
if threshold is not None
|
||||
else float(
|
||||
getattr(analyser, "yanghao_icon_match_threshold", 0.70)
|
||||
or 0.70
|
||||
)
|
||||
)
|
||||
detected = score >= used_thr
|
||||
return bool(detected), float(score)
|
||||
|
||||
ih, iw = roi_gray.shape
|
||||
th, tw = tpl_gray.shape
|
||||
best = -1.0
|
||||
step_y = max(1, th // 6)
|
||||
step_x = max(1, tw // 6)
|
||||
for y in range(0, ih - th + 1, step_y):
|
||||
for x in range(0, iw - tw + 1, step_x):
|
||||
window = roi_gray[y : y + th, x : x + tw]
|
||||
a = window.flatten()
|
||||
b = tpl_gray.flatten()
|
||||
a = a - a.mean()
|
||||
b = b - b.mean()
|
||||
denom = np.linalg.norm(a) * np.linalg.norm(b)
|
||||
if denom <= 1e-6:
|
||||
continue
|
||||
score = float(np.dot(a, b) / denom)
|
||||
if score > best:
|
||||
best = score
|
||||
if best < -0.5:
|
||||
return False, 0.0
|
||||
score = float(best)
|
||||
used_thr = (
|
||||
float(threshold)
|
||||
if threshold is not None
|
||||
else float(
|
||||
getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70
|
||||
)
|
||||
)
|
||||
detected = score >= used_thr
|
||||
return bool(detected), float(score)
|
||||
|
||||
A = roi_gray.flatten()
|
||||
B = tpl_gray.flatten()
|
||||
A = A - A.mean()
|
||||
B = B - B.mean()
|
||||
denom = np.linalg.norm(A) * np.linalg.norm(B)
|
||||
if denom <= 1e-6:
|
||||
return False, 0.0
|
||||
score = float(np.dot(A, B) / denom)
|
||||
used_thr = (
|
||||
float(threshold)
|
||||
if threshold is not None
|
||||
else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70)
|
||||
)
|
||||
detected = score >= used_thr
|
||||
return bool(detected), float(score)
|
||||
except Exception:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"检测",
|
||||
"_match_icon_template 异常",
|
||||
roi_path=roi_path,
|
||||
template_path=template_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
@@ -0,0 +1,287 @@
|
||||
"""福袋分析器默认配置初始化
|
||||
|
||||
从 douyin_fudai.py:fudai_analyse.__init__ 中提取的默认配置块。
|
||||
所有字段都是简单的 self.X = literal 赋值,无逻辑分支。
|
||||
后续 load_config() 会从 config.json 读取覆盖这些默认值。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def init_basic_state(self) -> None:
|
||||
"""初始化基础状态字段:device、分辨率、计数器、operation、config_path。"""
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
|
||||
self.device_id: str = ""
|
||||
self.y_pianyi: int = 0
|
||||
self.resolution_ratio_x: int = 1080
|
||||
self.resolution_ratio_y: int = 2400
|
||||
self._swipe_times: int = 0
|
||||
self.operation = underlying_operations()
|
||||
self.config_path = "config/config.json"
|
||||
|
||||
|
||||
def init_log_infra(self) -> None:
|
||||
"""初始化日志相关字段:_run_id、_log_seq、_log_kv 闭包等。"""
|
||||
import logging
|
||||
import time as _time
|
||||
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
self._run_id = datetime.now().strftime("%Y%m%d%H%M%S")
|
||||
except Exception as e:
|
||||
logging.debug("生成 run_id 失败,回退到时间戳: %s", e)
|
||||
self._run_id = str(int(_time.time()))
|
||||
self._log_seq = 0
|
||||
self._log_kv_orig = None
|
||||
self._use_real_timestamp = False
|
||||
|
||||
from douyin.logging import douyin_logging_wrapper
|
||||
|
||||
self._log_kv = lambda *args, **kwargs: douyin_logging_wrapper.LoggingWrapper.enhanced_log_kv(
|
||||
self, *args, **kwargs
|
||||
)
|
||||
self._last_log_tag = None
|
||||
self._std_logger = None # type: ignore[assignment]
|
||||
|
||||
|
||||
def init_diag_timeout_state(self) -> None:
|
||||
"""初始化阶段诊断 + 30 分钟超时相关状态字段。"""
|
||||
import time as _time
|
||||
|
||||
self._last_diag_stage: str = "INIT"
|
||||
self._last_diag_seen: str = "-"
|
||||
self._last_diag_ts: float = 0.0
|
||||
|
||||
self._last_successful_attend_ts: float = 0.0
|
||||
self._no_attend_timeout_minutes: float = 30.0
|
||||
self._run_start_ts: float = _time.time()
|
||||
self._reservations_state_last_write_ts: float = 0.0
|
||||
self.last_fudai_x: int = 0
|
||||
|
||||
|
||||
def init_reservation_runtime_state(self) -> None:
|
||||
"""初始化预约运行时状态字段(单次运行内有效)。"""
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
self.reservations: list[dict[str, Any]] = []
|
||||
self._first_run_once_basic: bool = True
|
||||
self.room_pos: int = 0
|
||||
self.reservation_focus_until_ts: float = 0.0
|
||||
self.reservation_after_action_pending: bool = False
|
||||
self.reset_to_list_after_reservations: bool = False
|
||||
self.queue_full_waiting_at_earliest: bool = False
|
||||
|
||||
# 预约队列状态文件(供 WebGUI / 其他进程查看)
|
||||
try:
|
||||
from douyin.core import path_config as _pc
|
||||
|
||||
self._reservations_state_path: str = _pc.get_reservations_path()
|
||||
except Exception:
|
||||
self._reservations_state_path = os.path.join(
|
||||
os.path.dirname(__file__), "state", "reservations.json"
|
||||
)
|
||||
|
||||
|
||||
def init_logging_system(self) -> None:
|
||||
"""初始化统一日志系统 + traceId(MDC)。
|
||||
|
||||
设置 self._std_logger 和 trace_id(基于 _run_id)。
|
||||
"""
|
||||
import logging
|
||||
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
|
||||
if not getattr(douyin_logging, "_logging_configured", False):
|
||||
douyin_logging.configure_logging()
|
||||
except Exception as e:
|
||||
logging.warning("日志系统初始化失败: %s", e)
|
||||
|
||||
try:
|
||||
from douyin.logging.unified_logger import MDC, get_unified_logger
|
||||
|
||||
MDC.set_trace_id(f"run_{self._run_id}")
|
||||
self._std_logger = get_unified_logger("douyin.fudai")
|
||||
except ImportError:
|
||||
self._std_logger = logging.getLogger("douyin.fudai")
|
||||
root_logger = logging.getLogger()
|
||||
if not root_logger.handlers:
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
|
||||
douyin_logging.configure_logging()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def cleanup_old_room_pos_map_files(self) -> None:
|
||||
"""每次重新运行时丢弃磁盘上旧的映射表导出文件(JSON/CSV/MD)。"""
|
||||
import os
|
||||
|
||||
try:
|
||||
state_dir = os.path.dirname(self._reservations_state_path)
|
||||
state_path = os.path.join(state_dir, "room_pos_map.json")
|
||||
csv_path = os.path.join(state_dir, "room_pos_map.csv")
|
||||
md_path = os.path.join(state_dir, "room_pos_map.md")
|
||||
for p in (state_path, csv_path, md_path):
|
||||
try:
|
||||
if os.path.exists(p):
|
||||
os.remove(p)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def init_runtime_state_flags(self) -> None:
|
||||
"""初始化运行时状态标志(避免在外部定义属性的警告)。
|
||||
|
||||
包括等待开奖、预约参与、跳过阶段、刚切换、高价值重访、福袋详情等状态字段。
|
||||
"""
|
||||
import time
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
self.needswitch: bool | None = None
|
||||
self._waiting_for_lottery_result: bool = False
|
||||
self._current_attending_reservation_fudai: bool = False
|
||||
self._skip_stage_diagnosis_and_find_fudai: bool = False
|
||||
self._just_switched_room: bool = False
|
||||
|
||||
self._last_high_value_revisit_ts: float = time.time()
|
||||
self._current_run_revisit_count: int = 0
|
||||
self._current_run_high_value_rooms: list[dict[str, Any]] = []
|
||||
self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = None
|
||||
self._current_fudai_future_ts: float = 0.0
|
||||
self._current_fudai_content: str = ""
|
||||
self._fudai_detail_first_read: bool = False
|
||||
self._fudai_detail_consecutive_failures: int = 0
|
||||
self._detail_closed_by_attend: bool = False
|
||||
self._lottery_result_expected_ts: float = 0.0
|
||||
self._lottery_wait_start_ts: float = 0.0
|
||||
|
||||
|
||||
def init_default_config(self) -> None:
|
||||
"""初始化所有配置字段的默认值。
|
||||
|
||||
分组:
|
||||
- 福袋筛选与基础配置
|
||||
- 福袋图标检测节流
|
||||
- 优化查找器与阈值
|
||||
- 直播间检测阈值
|
||||
- 高价值福袋 / 预约
|
||||
- 粉丝团
|
||||
- 预约回退
|
||||
- 滑动次数重置
|
||||
- 意外返回桌面自救
|
||||
- 养号配置
|
||||
"""
|
||||
# 与配置相关的核心字段(只初始化最关键的几项,其余保持默认)
|
||||
self.contains_not_want: list[str] = []
|
||||
self.contains_want: list[str] = []
|
||||
self.min_prize_value_yuan: float = 0.0
|
||||
self.min_participants: int = 0
|
||||
self.max_participants: int = 0
|
||||
self.skip_if_countdown_gt_seconds: int = 900
|
||||
self.skip_if_countdown_lt_seconds: int = 0
|
||||
self.no_fudai_watchdog_enabled: bool = False
|
||||
# 福袋图标检测节流
|
||||
self.fudai_icon_retry_delay_seconds: float = 0.6
|
||||
self.fudai_icon_max_wait_seconds: float = 5.0
|
||||
self.fudai_exit_after_misses: int = 999999
|
||||
self.enable_back_on_misses: bool = False
|
||||
self.fudai_click_wait_seconds: float = 1.0
|
||||
self.switch_room_wait_after_stage_diag_seconds: float = 7.0
|
||||
self.swipe_duration_ms: int = 600
|
||||
self.fudai_find_max_attempts: int = 10
|
||||
|
||||
# 优化查找器
|
||||
self.fudai_finder_optimized_enabled: bool = True
|
||||
self.fudai_click_verify_enabled: bool = True
|
||||
self.fudai_find_max_retries: int = 3
|
||||
self.screenshot_diagnose_min_interval_seconds: float = 8.0
|
||||
self.lucky_draw_red_ratio_threshold: float = 0.9
|
||||
self.coupon_template_match_threshold: float = 0.75
|
||||
self.attend_button_red_ratio_threshold: float = 0.25
|
||||
self.fansclub_join_red_ratio_threshold: float = 0.25
|
||||
|
||||
# 直播间检测阈值
|
||||
self.live_room_match_threshold: float = 0.8
|
||||
self.fudai_template_match_enabled: bool = False
|
||||
self.fudai_template_match_threshold: float = 0.7
|
||||
|
||||
# 高价值福袋 / 预约
|
||||
self.high_value_fudai_enabled: bool = False
|
||||
self.high_value_fudai_threshold_yuan: float = 500.0
|
||||
self.high_value_fudai_join_ahead_seconds: int = 100
|
||||
self.high_value_fudai_max_swipe_back: int = 35
|
||||
self.high_value_fudai_max_reservations: int = 3
|
||||
self.high_value_fudai_after_action: str = "continue"
|
||||
self.high_value_fudai_after_stay_seconds: int = 120
|
||||
self.high_value_fudai_poll_before_seconds: float = 10.0
|
||||
|
||||
# 高价值直播间回访
|
||||
self.high_value_room_revisit_enabled: bool = False
|
||||
self.high_value_room_revisit_only_current_run: bool = False
|
||||
self.high_value_room_revisit_min_interval_seconds: int = 300
|
||||
self.high_value_room_revisit_max_per_run: int = 5
|
||||
self.high_value_room_revisit_min_prize_value: float = 0.0
|
||||
self.high_value_room_revisit_max_age_days: int = 30
|
||||
|
||||
# 粉丝团
|
||||
self.auto_join_fansclub: bool = False
|
||||
self.fansclub_fail_action: str = "stay"
|
||||
|
||||
# 预约回退
|
||||
self.reservation_back_verify_enabled: bool = True
|
||||
self.reservation_back_swipe_delay: float = 0.6
|
||||
|
||||
# 滑动次数重置
|
||||
self.reset_after_swipes_enabled: bool = False
|
||||
self.reset_after_swipes: int = 10
|
||||
|
||||
# 意外返回桌面自救
|
||||
self.desktop_icon_x: int = 153
|
||||
self.desktop_icon_y: int = 260
|
||||
self.yanghao_fallback_live_x: int = 540
|
||||
self.yanghao_fallback_live_y: int = 2000
|
||||
self.yanghao_fallback_enter_live_x: int = 540
|
||||
self.yanghao_fallback_enter_live_y: int = 1200
|
||||
|
||||
# 养号配置
|
||||
self.yanghao_enabled: bool = True
|
||||
self.yanghao_enable_actions: bool = True
|
||||
self.yanghao_step_screenshot: bool = False
|
||||
self.yanghao_recommend_duration_seconds: int = 60
|
||||
self.yanghao_recommend_interval_seconds: int = 0
|
||||
self.yanghao_like_prob: float = 0.15
|
||||
self.yanghao_fav_prob: float = 0.05
|
||||
self.yanghao_comment_prob: float = 0.0
|
||||
self.yanghao_dwell_on_action_min_seconds: float = 5.0
|
||||
self.yanghao_dwell_on_action_max_seconds: float = 30.0
|
||||
self.yanghao_icon_roi_size: int = 180
|
||||
self.yanghao_icon_match_threshold: float = 0.70
|
||||
self.yanghao_like_roi_scale: float = 1.5
|
||||
self.yanghao_fav_roi_scale: float = 1.5
|
||||
self.yanghao_like_icon_match_threshold: float | None = None
|
||||
self.yanghao_fav_icon_match_threshold: float | None = None
|
||||
self.yanghao_like_icon_x: int = 0
|
||||
self.yanghao_like_icon_y: int = 0
|
||||
self.yanghao_fav_icon_x: int = 0
|
||||
self.yanghao_fav_icon_y: int = 0
|
||||
self.yanghao_like_roi_offset_x: int = 0
|
||||
self.yanghao_like_roi_offset_y: int = 0
|
||||
self.yanghao_fav_roi_offset_x: int = 0
|
||||
self.yanghao_fav_roi_offset_y: int = 0
|
||||
self._last_yanghao_ts: float = 0.0
|
||||
|
||||
self.yanghao_comment_btn_x: int = 0
|
||||
self.yanghao_comment_btn_y: int = 0
|
||||
self.yanghao_comment_input_x: int = 0
|
||||
self.yanghao_comment_input_y: int = 0
|
||||
self.yanghao_comment_send_x: int = 0
|
||||
self.yanghao_comment_send_y: int = 0
|
||||
self.yanghao_comment_close_x: int = 0
|
||||
self.yanghao_comment_close_y: int = 0
|
||||
self.yanghao_comment_texts: list[str] = []
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,42 @@
|
||||
"""underlying_operations_pkg - underlying_operations 类的零 self 方法子包。
|
||||
|
||||
原 douyin/core/underlying_operations.py(3021 行)的 6 个零 self 方法搬出到本子包:
|
||||
|
||||
- adb_helpers _adb_path / _pick_adbkeyboard_ime
|
||||
- pic_path _find_pic_path
|
||||
- ocr_content extract_ocr_content (218 行)
|
||||
- countdown check_countdown (161 行)
|
||||
- bounds _parse_bounds
|
||||
|
||||
类 ``underlying_operations`` 留在原文件,方法保留为 1 行 @staticmethod
|
||||
forwarding(签名不变,外部调用 ``self.X()`` / ``cls.X()`` 全部兼容)。
|
||||
"""
|
||||
|
||||
from .adb_helpers import _adb_path, _pick_adbkeyboard_ime
|
||||
from .pic_path import _find_pic_path
|
||||
from .ocr_content import extract_ocr_content
|
||||
from .countdown import check_countdown
|
||||
from .bounds import _parse_bounds
|
||||
from .reward_pic import save_reward_pic
|
||||
from .swipe_sendevent import _swipe_with_sendevent_improved
|
||||
from .clipboard import set_clipboard_text
|
||||
from .device_select import select_device
|
||||
from .ocr_digits import analyse_pic_digits
|
||||
|
||||
from .adb_helpers import _adb_args
|
||||
|
||||
|
||||
__all__ = [
|
||||
"_adb_path",
|
||||
"_pick_adbkeyboard_ime",
|
||||
"_find_pic_path",
|
||||
"extract_ocr_content",
|
||||
"check_countdown",
|
||||
"_parse_bounds",
|
||||
"save_reward_pic",
|
||||
"_swipe_with_sendevent_improved",
|
||||
"set_clipboard_text",
|
||||
"_adb_args",
|
||||
"select_device",
|
||||
"analyse_pic_digits",
|
||||
]
|
||||
@@ -0,0 +1,38 @@
|
||||
"""underlying_operations_pkg.adb_helpers - ADB 辅助。
|
||||
|
||||
- _adb_path 返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)
|
||||
- _pick_adbkeyboard_ime 从 IME 列表里挑出 ADBKeyboard 的 ID
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import List
|
||||
|
||||
|
||||
def _adb_path() -> str:
|
||||
"""返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。"""
|
||||
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
|
||||
if adb.startswith('"') and adb.endswith('"'):
|
||||
adb = adb[1:-1]
|
||||
return adb
|
||||
|
||||
|
||||
|
||||
def _pick_adbkeyboard_ime(imes: list[str]) -> str:
|
||||
# 兼容不同包名/组件名写法,优先匹配常见的 AdbIME
|
||||
for cand in imes or []:
|
||||
s = str(cand).strip()
|
||||
ls = s.lower()
|
||||
if "adbkeyboard" in ls and "adbime" in ls:
|
||||
return s
|
||||
for cand in imes or []:
|
||||
s = str(cand).strip()
|
||||
ls = s.lower()
|
||||
if "adbkeyboard" in ls or "adbime" in ls:
|
||||
return s
|
||||
return ""
|
||||
|
||||
|
||||
def _adb_args(device_id: str, *args: object) -> list[str]:
|
||||
"""构造 ``adb -s <device> <args>`` 的命令行参数列表。"""
|
||||
return [_adb_path(), "-s", str(device_id), *[str(arg) for arg in args]]
|
||||
@@ -0,0 +1,17 @@
|
||||
"""underlying_operations_pkg.bounds - bounds 字符串解析。
|
||||
|
||||
_parse_bounds: 解析 UI dump 里的 ``[x1,y1][x2,y2]`` 格式。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Optional, Tuple
|
||||
|
||||
|
||||
def _parse_bounds(bounds: str):
|
||||
m = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", str(bounds or ""))
|
||||
if not m:
|
||||
return None
|
||||
x1, y1, x2, y2 = map(int, m.groups())
|
||||
return x1, y1, x2, y2
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""underlying_operations_pkg.clipboard - 设备剪贴板设置。
|
||||
|
||||
set_clipboard_text(device_id, text): 在设备上设置剪贴板内容(支持中文)。
|
||||
优先 ``cmd clipboard set``(Android 10+),失败回退到 Clipper broadcast。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
import subprocess
|
||||
|
||||
from .adb_helpers import _adb_args
|
||||
|
||||
|
||||
def set_clipboard_text(device_id: str, text: str) -> bool:
|
||||
"""设置设备剪贴板文本(尽量支持中文)。
|
||||
|
||||
优先:Android 10+ 的 `cmd clipboard set`。
|
||||
兜底:Clipper(若设备装了 clipper app)。
|
||||
"""
|
||||
t = str(text or "").strip()
|
||||
if not t:
|
||||
return False
|
||||
|
||||
# 使用 shlex.quote 转义文本,防止 shell 注入
|
||||
safe_t = shlex.quote(t)
|
||||
|
||||
# 1) cmd clipboard set
|
||||
try:
|
||||
if (
|
||||
subprocess.run(
|
||||
_adb_args(device_id, "shell", "cmd", "clipboard", "set", safe_t),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=3.0,
|
||||
check=False,
|
||||
).returncode
|
||||
== 0
|
||||
):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2) Clipper broadcast: am broadcast -a clipper.set -e text "..."
|
||||
try:
|
||||
if (
|
||||
subprocess.run(
|
||||
_adb_args(
|
||||
device_id,
|
||||
"shell",
|
||||
"am",
|
||||
"broadcast",
|
||||
"-a",
|
||||
"clipper.set",
|
||||
"-e",
|
||||
"text",
|
||||
safe_t,
|
||||
),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=3.0,
|
||||
check=False,
|
||||
).returncode
|
||||
== 0
|
||||
):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
"""underlying_operations_pkg.countdown - 倒计时文本解析。
|
||||
|
||||
check_countdown: 兼容多种 OCR 误识别的倒计时格式:
|
||||
- 11:37 / 11:37 / 11:37后开奖
|
||||
- 1分23秒 / 23秒
|
||||
- 1137 / 934 / 31
|
||||
- 字符混淆纠正:O→0, l/I→1, S→5 等
|
||||
|
||||
返回 (剩余秒数, 预计开奖时间戳)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Tuple
|
||||
|
||||
# 与原 underlying_operations._uo_log 同名 logger,避免改变历史日志检索
|
||||
_LOGGER = logging.getLogger("douyin.core.underlying_operations")
|
||||
|
||||
|
||||
def _uo_log(msg, level: str = "INFO") -> None:
|
||||
"""统一底层操作日志出口;本地实现避免对原文件的循环依赖。"""
|
||||
try:
|
||||
lv = str(level or "INFO").upper()
|
||||
text = str(msg)
|
||||
if lv == "ERROR":
|
||||
_LOGGER.error(text)
|
||||
elif lv == "WARNING":
|
||||
_LOGGER.warning(text)
|
||||
elif lv == "DEBUG":
|
||||
_LOGGER.debug(text)
|
||||
else:
|
||||
_LOGGER.info(text)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def check_countdown(last_time=""):
|
||||
"""对倒计时时间进行转化,返回 (剩余秒数, 预计开奖时间戳)。
|
||||
|
||||
兼容 OCR 常见格式与误识别:
|
||||
- 11:37 / 11:37 / 11:37后开奖
|
||||
- 1分23秒 / 23秒
|
||||
- 1137 / 934 / 31
|
||||
- 字符混淆:O->0, l/I->1, S->5 等
|
||||
"""
|
||||
|
||||
def _norm(s: str) -> str:
|
||||
t = str(s or "")
|
||||
t = re.sub(r"\s+", "", t)
|
||||
t = t.replace(":", ":")
|
||||
# 常见 OCR 混淆纠正
|
||||
trans = str.maketrans(
|
||||
{
|
||||
"O": "0",
|
||||
"o": "0",
|
||||
"Q": "0",
|
||||
"D": "0",
|
||||
"I": "1",
|
||||
"l": "1",
|
||||
"|": "1",
|
||||
"!": "1",
|
||||
"S": "5",
|
||||
"s": "5",
|
||||
"B": "8",
|
||||
"G": "6",
|
||||
"Z": "2",
|
||||
}
|
||||
)
|
||||
t = t.translate(trans)
|
||||
return t
|
||||
|
||||
def _parse_seconds(text: str) -> Optional[int]:
|
||||
t = _norm(text)
|
||||
if not t:
|
||||
return None
|
||||
|
||||
# 1) mm:ss(允许 ss 为 1 位)
|
||||
m = re.search(r"(\d{1,2})[:](\d{1,2})", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
# 若秒数 >= 60,优先尝试交换(OCR 容易把分秒顺序颠倒)
|
||||
if ss >= 60 and mm < 60:
|
||||
mm, ss = ss, mm
|
||||
# 兜底:仍不合法则做进位
|
||||
if ss >= 60:
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return max(0, mm * 60 + ss)
|
||||
|
||||
# 2) 中文:x分y秒 / y秒
|
||||
m = re.search(r"(\d{1,2})分(\d{1,2})秒", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
if ss >= 60:
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return max(0, mm * 60 + ss)
|
||||
m = re.search(r"(\d{1,3})秒", t)
|
||||
if m:
|
||||
return max(0, int(m.group(1)))
|
||||
|
||||
# 3) 纯数字:1137(=11:37) / 934(=9:34) / 31(=31秒)
|
||||
digits = "".join(ch for ch in t if ch.isdigit())
|
||||
if not digits:
|
||||
return None
|
||||
|
||||
if len(digits) == 4:
|
||||
a = int(digits[:2])
|
||||
b = int(digits[2:])
|
||||
# 两种解释:a:b 或 b:a。
|
||||
# 默认按“前两位=分、后两位=秒”,只有在明显异常(>15分钟)或秒不合法时才交换。
|
||||
if b < 60:
|
||||
total1 = a * 60 + b
|
||||
else:
|
||||
total1 = None
|
||||
if a < 60:
|
||||
total2 = b * 60 + a
|
||||
else:
|
||||
total2 = None
|
||||
|
||||
if total1 is not None and total1 <= 900:
|
||||
return total1
|
||||
if total2 is not None and total2 <= 900:
|
||||
return total2
|
||||
|
||||
# 若一个明显异常而另一个更合理(<=900),交换
|
||||
if total1 is not None and total2 is not None:
|
||||
if total1 > 900 and total2 <= 900:
|
||||
return total2
|
||||
if total2 > 900 and total1 <= 900:
|
||||
return total1
|
||||
|
||||
# 兜底:谁能解析就用谁;都不行则做进位
|
||||
if total1 is not None:
|
||||
return total1
|
||||
if total2 is not None:
|
||||
return total2
|
||||
|
||||
mm, ss = a, b
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return mm * 60 + ss
|
||||
|
||||
if len(digits) == 3:
|
||||
mm = int(digits[0])
|
||||
ss = int(digits[1:])
|
||||
if ss >= 60:
|
||||
# 例如 159 可能是 15:09(OCR 丢 0)
|
||||
mm2 = int(digits[:2])
|
||||
ss2 = int(digits[2])
|
||||
if ss2 < 60:
|
||||
return mm2 * 60 + ss2
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return mm * 60 + ss
|
||||
|
||||
if len(digits) == 2:
|
||||
return int(digits) # 直接当秒(更符合“临近开奖”场景)
|
||||
|
||||
if len(digits) == 1:
|
||||
return int(digits)
|
||||
|
||||
# 太长:取最后4位(OCR 常把别的数字也识别进来)
|
||||
tail = digits[-4:]
|
||||
a = int(tail[:2])
|
||||
b = int(tail[2:])
|
||||
if b >= 60 and a < 60:
|
||||
a, b = b, a
|
||||
if b >= 60:
|
||||
a += b // 60
|
||||
b = b % 60
|
||||
return a * 60 + b
|
||||
|
||||
try:
|
||||
total_seconds = _parse_seconds(last_time)
|
||||
if total_seconds is None:
|
||||
_uo_log("时间格式异常")
|
||||
return False
|
||||
_uo_log("剩余总秒数:", total_seconds)
|
||||
# 超过 15 分钟基本是误识别:按 14分50秒处理,避免卡死等待
|
||||
if total_seconds > 900:
|
||||
total_seconds = 890
|
||||
|
||||
now = datetime.now()
|
||||
_uo_log("当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
future_time = now + timedelta(seconds=int(total_seconds))
|
||||
future_timestamp = future_time.timestamp()
|
||||
future_datetime = datetime.fromtimestamp(future_timestamp)
|
||||
formatted_future_time = future_datetime.strftime("%Y-%m-%d %H:%M:%S")
|
||||
_uo_log("预计开奖时间:", formatted_future_time)
|
||||
return int(total_seconds), future_timestamp
|
||||
except Exception:
|
||||
_uo_log("输入的字符串不是有效的时间格式")
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""underlying_operations_pkg.device_select - 设备选择交互。
|
||||
|
||||
select_device(): 列出 adb devices,单设备直接返回,多设备时让用户选。
|
||||
保留交互 print(CLI 用户在 stdout 看提示),无设备返回 False。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from .adb_helpers import _adb_args, _adb_path
|
||||
|
||||
|
||||
def select_device():
|
||||
"""选择需要连接的设备"""
|
||||
result = subprocess.run(
|
||||
[_adb_path(), "devices", "-l"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
)
|
||||
totalstring = result.stdout or ""
|
||||
# print(totalstring)
|
||||
devicelist = []
|
||||
for line in totalstring.splitlines()[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) >= 2 and parts[1] == "device":
|
||||
devicelist.append(parts[0])
|
||||
# devicelist = re.compile(r'(\w*)\s*device\b').findall(totalstring)
|
||||
devicenum = len(devicelist)
|
||||
if devicenum == 0:
|
||||
print("当前无设备连接电脑,请检查设备连接情况!")
|
||||
return False
|
||||
elif devicenum == 1:
|
||||
print("当前有一台设备连接,编号:%s." % devicelist[0])
|
||||
return devicelist[0]
|
||||
else:
|
||||
print("当前存在多台设备连接! 输入数字选择对应设备:")
|
||||
dictdevice = {}
|
||||
for i in range(devicenum):
|
||||
prop = subprocess.run(
|
||||
_adb_args(devicelist[i], "shell", "getprop", "ro.product.device"),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
)
|
||||
modestring = (prop.stdout or "").strip()
|
||||
print("%s:%s---%s" % (i + 1, devicelist[i], modestring))
|
||||
dictdevice[i + 1] = devicelist[i]
|
||||
if not sys.stdin.isatty():
|
||||
print("检测到多台设备且当前不是交互式终端,请通过 --device-id 明确指定设备。")
|
||||
return False
|
||||
num = input()
|
||||
num = int(num)
|
||||
while not num in dictdevice.keys():
|
||||
print("输入不正确,请重新输入:")
|
||||
num = input()
|
||||
num = int(num)
|
||||
return dictdevice[num]
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
"""underlying_operations_pkg.ocr_content - OCR 文本拼接 + 置信度。
|
||||
|
||||
extract_ocr_content: 把 OCR 引擎返回的多行结果拼成一段文本,
|
||||
可选附带置信度统计(avg/min/max/count)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def extract_ocr_content(content=None, return_confidence=False):
|
||||
"""对OCR识别到的内容进行取值和拼接,变成完整的一段内容
|
||||
|
||||
参数:
|
||||
content: OCR识别结果
|
||||
return_confidence: 是否返回置信度信息(默认False,保持向后兼容)
|
||||
|
||||
返回:
|
||||
如果return_confidence=False: 返回文本字符串
|
||||
如果return_confidence=True: 返回(text, confidence_info)元组,其中confidence_info是置信度信息字典
|
||||
"""
|
||||
ocr_result = content or []
|
||||
|
||||
# 用于收集置信度信息
|
||||
confidence_scores = []
|
||||
confidence_info = {
|
||||
"avg_confidence": 0.0,
|
||||
"min_confidence": 1.0,
|
||||
"max_confidence": 0.0,
|
||||
"item_count": 0,
|
||||
}
|
||||
|
||||
def _extract_text_and_confidence_from_item(item):
|
||||
"""提取文本和置信度"""
|
||||
text = ""
|
||||
confidence = None
|
||||
|
||||
# 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence)
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||
# EasyOCR格式:item = (bbox, text, confidence),text在索引1,confidence在索引2
|
||||
if len(item) >= 3:
|
||||
confidence = item[2]
|
||||
if isinstance(item[1], str):
|
||||
text = item[1]
|
||||
return text, confidence
|
||||
|
||||
# 兼容旧格式:[box, (text, score)]
|
||||
second = item[1]
|
||||
if isinstance(second, (list, tuple)) and len(second) >= 1:
|
||||
if isinstance(second[0], str):
|
||||
return second[0]
|
||||
if isinstance(second, dict):
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = second.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
if isinstance(second, str):
|
||||
return second
|
||||
|
||||
# 兼容新格式:dict / 对象
|
||||
if isinstance(item, dict):
|
||||
# 常见:rec_texts 为字符串列表
|
||||
for list_key in ("rec_texts", "texts", "text_list"):
|
||||
vals = item.get(list_key)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = item.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
for attr in ("text", "rec_text", "transcription"):
|
||||
val = getattr(item, attr, None)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
# 对象属性里也可能是列表
|
||||
for list_attr in ("rec_texts", "texts", "text_list"):
|
||||
vals = getattr(item, list_attr, None)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
|
||||
return ""
|
||||
|
||||
# PaddleOCR 可能返回 [[...]] 或 [...]
|
||||
items = ocr_result
|
||||
if (
|
||||
isinstance(ocr_result, list)
|
||||
and len(ocr_result) == 1
|
||||
and isinstance(ocr_result[0], list)
|
||||
):
|
||||
items = ocr_result[0]
|
||||
|
||||
def _extract_xy_from_item(item):
|
||||
"""尽力从 OCR item 中提取用于排序的 (y, x)。无法提取则返回 None。"""
|
||||
try:
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 1:
|
||||
box = item[0]
|
||||
# EasyOCR格式:bbox = [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]
|
||||
# PaddleOCR格式:box 为 4 点坐标列表
|
||||
if isinstance(box, (list, tuple)) and box:
|
||||
xs = []
|
||||
ys = []
|
||||
for p in box:
|
||||
if isinstance(p, (list, tuple)) and len(p) >= 2:
|
||||
xs.append(float(p[0]))
|
||||
ys.append(float(p[1]))
|
||||
if xs and ys:
|
||||
return (min(ys), min(xs))
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
def _extract_text_from_item(item):
|
||||
"""提取文本(原始逻辑,保持向后兼容)"""
|
||||
# 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence)
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||
# EasyOCR格式:item = (bbox, text, confidence),text在索引1
|
||||
if isinstance(item[1], str):
|
||||
return item[1]
|
||||
|
||||
# 兼容旧格式:[box, (text, score)]
|
||||
second = item[1]
|
||||
if isinstance(second, (list, tuple)) and len(second) >= 1:
|
||||
if isinstance(second[0], str):
|
||||
return second[0]
|
||||
if isinstance(second, dict):
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = second.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
if isinstance(second, str):
|
||||
return second
|
||||
|
||||
# 兼容新格式:dict / 对象
|
||||
if isinstance(item, dict):
|
||||
# 常见:rec_texts 为字符串列表
|
||||
for list_key in ("rec_texts", "texts", "text_list"):
|
||||
vals = item.get(list_key)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = item.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
for attr in ("text", "rec_text", "transcription"):
|
||||
val = getattr(item, attr, None)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
# 对象属性里也可能是列表
|
||||
for list_attr in ("rec_texts", "texts", "text_list"):
|
||||
vals = getattr(item, list_attr, None)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
|
||||
return ""
|
||||
|
||||
extracted_items = []
|
||||
if isinstance(items, list):
|
||||
for idx, item in enumerate(items):
|
||||
text = _extract_text_from_item(item)
|
||||
if not text:
|
||||
continue
|
||||
xy = _extract_xy_from_item(item)
|
||||
if xy is None:
|
||||
# 无坐标信息:保持原相对顺序
|
||||
extracted_items.append((1e18, float(idx), text))
|
||||
else:
|
||||
y, x = xy
|
||||
extracted_items.append((float(y), float(x), text))
|
||||
|
||||
# 按从上到下、从左到右排序;解决同一行多个框的乱序拼接(例如倒计时两段数字)
|
||||
extracted_items.sort(key=lambda t: (t[0], t[1]))
|
||||
|
||||
# 如果不需要返回置信度,直接返回文本(保持向后兼容)
|
||||
if not return_confidence:
|
||||
return "".join([t[2] for t in extracted_items])
|
||||
|
||||
# 如果需要返回置信度,提取置信度信息
|
||||
if return_confidence:
|
||||
for item in items:
|
||||
confidence = None
|
||||
# EasyOCR格式:[(bbox, text, confidence), ...]
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 3:
|
||||
confidence = item[2]
|
||||
# PaddleOCR格式:[box, (text, score)]
|
||||
elif isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||
second = item[1]
|
||||
if isinstance(second, (list, tuple)) and len(second) >= 2:
|
||||
confidence = second[1]
|
||||
elif isinstance(second, dict):
|
||||
confidence = second.get("confidence") or second.get("score")
|
||||
|
||||
if confidence is not None:
|
||||
try:
|
||||
conf_float = float(confidence)
|
||||
confidence_scores.append(conf_float)
|
||||
confidence_info["min_confidence"] = min(
|
||||
confidence_info["min_confidence"], conf_float
|
||||
)
|
||||
confidence_info["max_confidence"] = max(
|
||||
confidence_info["max_confidence"], conf_float
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
if confidence_scores:
|
||||
confidence_info["avg_confidence"] = sum(confidence_scores) / len(
|
||||
confidence_scores
|
||||
)
|
||||
confidence_info["item_count"] = len(confidence_scores)
|
||||
else:
|
||||
confidence_info["min_confidence"] = 0.0
|
||||
|
||||
return "".join([t[2] for t in extracted_items]), confidence_info
|
||||
|
||||
return "".join([t[2] for t in extracted_items])
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""underlying_operations_pkg.ocr_digits - 数字 OCR 识别。
|
||||
|
||||
analyse_pic_digits(analyser, picname, change_color=1, pic_path=None):
|
||||
轻量数字 OCR 识别。复用 analyser.analyse_pic_word 的核心路径,
|
||||
拿到原始文本后做数字过滤与智能段提取(保留 . 用于小数)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
|
||||
def analyse_pic_digits(analyser, picname, change_color=1, pic_path=None):
|
||||
"""轻量数字OCR识别函数,专门用于识别数字(0-9)。
|
||||
|
||||
策略:
|
||||
1. 复用 analyse_pic_word 的核心路径(缓存 / 预处理 / OCR 调用 / 调试图保存)
|
||||
2. change_color=1/2 触发二值化(数字框背景简单时有效)
|
||||
3. 在拿到原始文本后做数字过滤与智能段提取(保留 . 用于小数)
|
||||
"""
|
||||
text = analyser.analyse_pic_word(
|
||||
picname, change_color=change_color, pic_path=pic_path
|
||||
)
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
# 规范化常见全角/中文标点 -> 英文点
|
||||
text_norm = (
|
||||
str(text).replace("。", ".").replace(",", ".").replace(".", ".")
|
||||
)
|
||||
digits_only = "".join(ch for ch in text_norm if ch.isdigit())
|
||||
digits = "".join(ch for ch in text_norm if ch.isdigit() or ch == ".")
|
||||
|
||||
# 智能过滤:识别出的数字过多通常意味着混入了非目标内容
|
||||
# (例如把文件名/坐标也识别进来),尝试提取合理段
|
||||
if len(digits_only) > 10:
|
||||
digit_segments = re.findall(r"\d+(?:\.\d+)?", text_norm)
|
||||
if digit_segments:
|
||||
# 价值类:1-6 位最合理;倒计时:1-2 位最合理
|
||||
reasonable_segments = [
|
||||
s for s in digit_segments if 1 <= len(s.replace(".", "")) <= 6
|
||||
]
|
||||
if reasonable_segments:
|
||||
return max(reasonable_segments, key=len)
|
||||
return min(digit_segments, key=len) if digit_segments else digits[:6]
|
||||
|
||||
return digits
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""underlying_operations_pkg.pic_path - 图片路径查找(含新旧位置兼容)。
|
||||
|
||||
_find_pic_path: 按图片名查找路径。运行时必需文件(screenshot/cut)放在
|
||||
``pic/`` 根;OCR 调试图片按 douyin_screenshot_manager 分类组织到子目录。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def _find_pic_path(picname: str, for_reading: bool = True) -> Optional[str]:
|
||||
"""查找图片路径,支持新旧位置(向后兼容),并按分类组织
|
||||
|
||||
Args:
|
||||
picname: 图片名称(不含扩展名),如 '直播广场', '福袋内容'
|
||||
for_reading: True=读取(支持新旧位置),False=写入(使用新位置+分类目录)
|
||||
|
||||
Returns:
|
||||
图片的完整路径,如果找不到且for_reading=True则返回None
|
||||
"""
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_base = path_config.get_pic_dir()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_base = path_config.get_pic_dir()
|
||||
|
||||
# 运行时必需文件始终在根目录(不需要移动)
|
||||
runtime_files = {"screenshot", "cut"}
|
||||
if picname in runtime_files:
|
||||
path = os.path.join(pic_base, f"{picname}.png")
|
||||
return path if (os.path.exists(path) or not for_reading) else None
|
||||
|
||||
# OCR图片文件:按分类组织到子目录
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
category = douyin_screenshot_manager.get_category_for_picname(picname)
|
||||
except Exception:
|
||||
category = "others"
|
||||
|
||||
if for_reading:
|
||||
# 读取:先查分类目录,再查旧位置(向后兼容)
|
||||
# 1. 新位置(分类目录)
|
||||
category_path = os.path.join(pic_base, "ocr", category, f"{picname}.png")
|
||||
if os.path.exists(category_path):
|
||||
return category_path
|
||||
# 2. 旧位置(ocr根目录)
|
||||
old_ocr_path = os.path.join(pic_base, "ocr", f"{picname}.png")
|
||||
if os.path.exists(old_ocr_path):
|
||||
return old_ocr_path
|
||||
# 3. 更旧的位置(pic根目录)
|
||||
old_root_path = os.path.join(pic_base, f"{picname}.png")
|
||||
if os.path.exists(old_root_path):
|
||||
return old_root_path
|
||||
return None
|
||||
else:
|
||||
# 写入:使用分类目录,确保目录存在
|
||||
category_dir = os.path.join(pic_base, "ocr", category)
|
||||
os.makedirs(category_dir, exist_ok=True)
|
||||
return os.path.join(category_dir, f"{picname}.png")
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""underlying_operations_pkg.reward_pic - 中奖截图保存。
|
||||
|
||||
save_reward_pic(device_id): 中奖时保存当前屏幕截图到 ``pic/<时间>.png``。
|
||||
优先 exec-out 模式(更快),失败回退到 shell screencap + pull。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from .adb_helpers import _adb_path
|
||||
|
||||
_LOGGER = logging.getLogger("douyin.core.underlying_operations")
|
||||
|
||||
|
||||
def _uo_log(msg, level: str = "INFO") -> None:
|
||||
try:
|
||||
lv = str(level or "INFO").upper()
|
||||
if lv == "ERROR":
|
||||
_LOGGER.error(str(msg))
|
||||
elif lv == "WARNING":
|
||||
_LOGGER.warning(str(msg))
|
||||
elif lv == "DEBUG":
|
||||
_LOGGER.debug(str(msg))
|
||||
else:
|
||||
_LOGGER.info(str(msg))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def save_reward_pic(device_id):
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
out_dir = path_config.get_pic_dir()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
out_dir = path_config.get_pic_dir()
|
||||
if not os.path.exists(out_dir):
|
||||
os.makedirs(out_dir)
|
||||
timepic = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
|
||||
out_file = os.path.join(out_dir, f"{timepic}.png")
|
||||
|
||||
adb = _adb_path()
|
||||
|
||||
# 同样优先使用 exec-out,减少手机端 I/O
|
||||
try:
|
||||
with open(out_file, "wb") as f:
|
||||
subprocess.run(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=f,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
_uo_log("中奖了,点击领奖,保存中奖图片{}.png".format(timepic))
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 回退:shell screencap + pull
|
||||
try:
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"screencap",
|
||||
"-p",
|
||||
"/sdcard/DCIM/screenshot.png",
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", out_file],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[adb, "-s", device_id, "shell", "rm", "/sdcard/DCIM/screenshot.png"],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=False,
|
||||
)
|
||||
_uo_log("中奖了,点击领奖,保存中奖图片{}.png".format(timepic))
|
||||
except Exception:
|
||||
# 保存失败不打断主流程
|
||||
_uo_log("保存中奖截图失败")
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""underlying_operations_pkg.swipe_sendevent - sendevent 滑动(占位实现)。
|
||||
|
||||
_swipe_with_sendevent_improved(...) 是更底层的触摸事件模拟方式,需要 root 权限
|
||||
且不同设备的事件格式可能不同。当前实现只做检测和异常抛出,主流程不依赖它。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
|
||||
from .adb_helpers import _adb_args
|
||||
|
||||
|
||||
def _swipe_with_sendevent_improved(device_id, x1, y1, x2, y2, steps=50):
|
||||
"""使用 sendevent 方法滑动(需要 root 权限)
|
||||
|
||||
这是更底层的触摸事件模拟方式,通过直接向 /dev/input/eventX 写入事件。
|
||||
优点:绕过部分权限检查
|
||||
缺点:需要 root 权限,实现复杂,不同设备的事件格式可能不同
|
||||
"""
|
||||
|
||||
# 获取触摸设备路径(通常是 /dev/input/eventX)
|
||||
result = subprocess.run(
|
||||
_adb_args(device_id, "shell", "getevent", "-p"),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=3.0,
|
||||
check=False,
|
||||
)
|
||||
|
||||
# 解析设备路径(简化版,实际需要更复杂的解析)
|
||||
# 这里只是示例,完整实现需要:
|
||||
# 1. 解析 getevent -p 输出找到触摸设备
|
||||
# 2. 计算触摸事件的坐标范围(ABS_MT_POSITION_X/Y 的 min/max)
|
||||
# 3. 将屏幕坐标转换为设备坐标
|
||||
# 4. 发送 DOWN -> MOVE -> UP 事件序列
|
||||
|
||||
if "ABS_MT" not in result.stdout or "event" not in result.stdout.lower():
|
||||
raise FileNotFoundError("无法找到触摸设备(需要 root 权限)")
|
||||
|
||||
# 注意:完整的 sendevent 实现非常复杂,需要:
|
||||
# - 设备特定的坐标转换
|
||||
# - 正确的事件序列(SYN_REPORT 等)
|
||||
# - 不同 Android 版本的事件格式可能不同
|
||||
|
||||
raise PermissionError("sendevent 需要 root 权限且实现复杂,暂不支持完整实现")
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""detection_pkg - 福袋检测子包。
|
||||
|
||||
原 douyin/detection/douyin_detection.py 拆成 3 个子模块:
|
||||
|
||||
- _common _ensure_detection_cache
|
||||
- detail check_detail_height / check_in_fudai_detail
|
||||
- finder check_have_fudai_with_ready_screenshot(最大头)
|
||||
|
||||
外部 import 路径不变:
|
||||
``from douyin.detection.douyin_detection import check_in_fudai_detail`` 仍可用
|
||||
(原文件改成 re-export shim)。
|
||||
"""
|
||||
|
||||
from ._common import _ensure_detection_cache
|
||||
from .detail import check_detail_height, check_in_fudai_detail
|
||||
from .finder import check_have_fudai_with_ready_screenshot
|
||||
|
||||
__all__ = [
|
||||
"_ensure_detection_cache",
|
||||
"check_detail_height",
|
||||
"check_have_fudai_with_ready_screenshot",
|
||||
"check_in_fudai_detail",
|
||||
]
|
||||
@@ -0,0 +1,14 @@
|
||||
"""detection_pkg._common - 共享:分析器检测缓存初始化。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _ensure_detection_cache(analyser: Any) -> None:
|
||||
"""Ensure analyser has a simple detection cache structure."""
|
||||
if not hasattr(analyser, "_detection_cache"):
|
||||
analyser._detection_cache = {}
|
||||
if not hasattr(analyser, "_detection_cache_ttl"):
|
||||
analyser._detection_cache_ttl = 2.0
|
||||
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
"""detection_pkg.detail - 福袋详情页相关检测。
|
||||
|
||||
- check_detail_height 识别详情页弹窗中"任务"数量(0/1/2/3)
|
||||
- check_in_fudai_detail 判断当前是否处于福袋详情页(综合多种特征)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# pylint: disable=no-member
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from ._common import _ensure_detection_cache
|
||||
|
||||
|
||||
def check_detail_height(analyser: Any) -> int:
|
||||
"""Detect how many tasks are required in the fudai detail popup.
|
||||
|
||||
Returns:
|
||||
0 / 1 / 2 / 3 (number of tasks).
|
||||
"""
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic1_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
from douyin.core import path_config
|
||||
|
||||
pic1_path = path_config.get_screenshot_path()
|
||||
|
||||
# 记录截图文件的时间戳(如果存在)
|
||||
screenshot_timestamp = None
|
||||
try:
|
||||
if os.path.exists(pic1_path):
|
||||
screenshot_timestamp = os.path.getmtime(pic1_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
pic = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
pic = Image.open(pic1_path)
|
||||
pic.load() # force load to catch truncated files early
|
||||
break
|
||||
except Exception:
|
||||
if attempt < 2:
|
||||
try:
|
||||
analyser.operation.get_screenshot(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
analyser.operation.delay(0.2)
|
||||
# 重新获取截图后,更新时间戳
|
||||
try:
|
||||
if os.path.exists(pic1_path):
|
||||
screenshot_timestamp = os.path.getmtime(pic1_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
pic = None
|
||||
if pic is None:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"检测",
|
||||
"读取截图失败,默认不需要任务",
|
||||
level="WARN",
|
||||
screenshot_timestamp=screenshot_timestamp,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
pic_new = pic.convert("RGBA")
|
||||
pix = pic_new.load()
|
||||
width, height = pic_new.size
|
||||
|
||||
# X of “参与” button
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
except Exception:
|
||||
rx = 1080
|
||||
try:
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
ry = 2400
|
||||
|
||||
x = 536 * rx // 1080
|
||||
if not (0 <= x < width):
|
||||
return 0
|
||||
|
||||
# (base_y, y_pianyi_offset, task_count)
|
||||
try:
|
||||
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
except Exception:
|
||||
y_pianyi_val = 0
|
||||
|
||||
check_points = [
|
||||
(983, 0, 2),
|
||||
(983, y_pianyi_val, 2),
|
||||
(983, -y_pianyi_val, 2),
|
||||
(883, 0, 3),
|
||||
(883, y_pianyi_val, 3),
|
||||
(883, -y_pianyi_val, 3),
|
||||
(1058, 0, 1),
|
||||
(1058, y_pianyi_val, 1),
|
||||
(1058, -y_pianyi_val, 1),
|
||||
]
|
||||
|
||||
def _check_pixel_color(y_coord: int) -> bool:
|
||||
if not (0 <= y_coord < height):
|
||||
return False
|
||||
try:
|
||||
p = pix[x, y_coord]
|
||||
if not (isinstance(p, tuple) and len(p) >= 3):
|
||||
return False
|
||||
r, g, b = int(p[0]), int(p[1]), int(p[2])
|
||||
return 28 <= r <= 40 and 32 <= g <= 42 and 76 <= b <= 86
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
detected_task_count = None
|
||||
detected_y = None
|
||||
try:
|
||||
for base_y, dy, task_count in check_points:
|
||||
y = base_y * ry // 2400 + dy
|
||||
if _check_pixel_color(y):
|
||||
detected_task_count = task_count
|
||||
detected_y = y
|
||||
try:
|
||||
import time
|
||||
|
||||
current_time = time.time()
|
||||
analyser._log_kv(
|
||||
"检测",
|
||||
f"识别到福袋任务数量:{task_count}个",
|
||||
task_count=task_count,
|
||||
detected_y=detected_y,
|
||||
screenshot_timestamp=screenshot_timestamp,
|
||||
current_time=current_time,
|
||||
time_diff=(
|
||||
round(current_time - screenshot_timestamp, 3)
|
||||
if screenshot_timestamp
|
||||
else None
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 保存调试图片:标注检测区域和检测点
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
# 计算检测区域(参与按钮附近的区域)
|
||||
check_region_x1 = max(0, x - 50)
|
||||
check_region_x2 = min(width, x + 50)
|
||||
check_region_y1 = max(0, (883 * ry // 2400) - 100) # 3个任务的Y坐标附近
|
||||
check_region_y2 = min(height, (1058 * ry // 2400) + 100) # 1个任务的Y坐标附近
|
||||
|
||||
# 标注检测点
|
||||
coords_list = []
|
||||
for base_y, dy, task_count_val in check_points:
|
||||
check_y = base_y * ry // 2400 + dy
|
||||
if 0 <= check_y < height:
|
||||
# 标注检测点(小矩形区域)
|
||||
coords_list.append(
|
||||
(
|
||||
max(0, x - 10),
|
||||
max(0, check_y - 5),
|
||||
min(width, x + 10),
|
||||
min(height, check_y + 5),
|
||||
)
|
||||
)
|
||||
|
||||
# 保存调试图片
|
||||
pic_rgb = pic.convert("RGB")
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb,
|
||||
operation_type="detection",
|
||||
picname="福袋任务数量",
|
||||
step="task_count_detection",
|
||||
coords=(check_region_x1, check_region_y1, check_region_x2, check_region_y2),
|
||||
extra_info={
|
||||
"task_count": (
|
||||
detected_task_count if detected_task_count is not None else 0
|
||||
),
|
||||
"detected_y": detected_y,
|
||||
"check_x": x,
|
||||
"check_points_count": len(check_points),
|
||||
"region": f"({check_region_x1},{check_region_y1})-({check_region_x2},{check_region_y2})",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋任务数量检测",
|
||||
path=debug_path,
|
||||
task_count=(
|
||||
detected_task_count if detected_task_count is not None else 0
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if detected_task_count is not None:
|
||||
return detected_task_count
|
||||
|
||||
# Optional robot-check path from original implementation
|
||||
try:
|
||||
if (
|
||||
hasattr(analyser, "check_have_robot_analyse")
|
||||
and analyser.check_have_robot_analyse()
|
||||
):
|
||||
analyser.deal_robot_analyse()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
import time
|
||||
|
||||
current_time = time.time()
|
||||
analyser._log_kv(
|
||||
"检测",
|
||||
"识别福袋任务数量:0个(不需要任务)",
|
||||
level="INFO",
|
||||
task_count=0,
|
||||
screenshot_timestamp=screenshot_timestamp,
|
||||
current_time=current_time,
|
||||
time_diff=(
|
||||
current_time - screenshot_timestamp if screenshot_timestamp else None
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
|
||||
def check_in_fudai_detail(analyser: Any) -> bool:
|
||||
"""Detect whether we are currently on the fudai detail page.
|
||||
|
||||
使用模板匹配检测,与 detect_fudai_detail_page 保持一致。
|
||||
"""
|
||||
_ensure_detection_cache(analyser)
|
||||
cache_key = "check_in_fudai_detail"
|
||||
now = time.time()
|
||||
cached = analyser._detection_cache.get(cache_key)
|
||||
if cached:
|
||||
cached_ts, cached_result = cached
|
||||
ttl = float(getattr(analyser, "_detection_cache_ttl", 2.0) or 2.0)
|
||||
if (now - cached_ts) < ttl:
|
||||
return bool(cached_result)
|
||||
|
||||
# 使用模板匹配检测,与 detect_fudai_detail_page 保持一致
|
||||
try:
|
||||
from douyin.detection import douyin_pixel
|
||||
from douyin.core import path_config
|
||||
|
||||
# 获取截图
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if not os.path.exists(pic_path):
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
except Exception:
|
||||
analyser._detection_cache[cache_key] = (now, False)
|
||||
return False
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if not os.path.exists(pic_path):
|
||||
analyser._detection_cache[cache_key] = (now, False)
|
||||
return False
|
||||
|
||||
pic = Image.open(pic_path)
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
|
||||
# 获取分辨率比例和Y偏移
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
|
||||
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
|
||||
template_threshold = float(
|
||||
getattr(analyser, "fudai_detail_template_threshold", None)
|
||||
or getattr(analyser, "fudai_template_match_threshold", 0.7)
|
||||
or 0.7
|
||||
)
|
||||
if template_threshold < 0.0:
|
||||
template_threshold = 0.0
|
||||
if template_threshold > 1.0:
|
||||
template_threshold = 1.0
|
||||
|
||||
# 使用任务数量检测
|
||||
result = douyin_pixel.detect_fudai_detail_page(
|
||||
pic_rgb,
|
||||
rx,
|
||||
ry,
|
||||
y_pianyi,
|
||||
template_threshold,
|
||||
return_info=False, # 不需要详细信息
|
||||
analyser=analyser,
|
||||
)
|
||||
|
||||
is_in_detail = bool(result)
|
||||
analyser._detection_cache[cache_key] = (now, is_in_detail)
|
||||
return is_in_detail
|
||||
except Exception:
|
||||
analyser._detection_cache[cache_key] = (now, False)
|
||||
return False
|
||||
|
||||
|
||||
# ========== 以下为旧的像素检测代码,已暂时禁用 ==========
|
||||
# 像素检测代码已删除,使用模板匹配替代
|
||||
# 如需恢复像素检测,请参考 git 历史记录
|
||||
@@ -0,0 +1,320 @@
|
||||
"""detection_pkg.finder - 找福袋图标主入口(1420 行)。
|
||||
|
||||
包含 check_have_fudai_with_ready_screenshot:在直播间内通过模板匹配
|
||||
定位福袋图标,并把找到的位置写到 analyser 上供后续点击使用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# pylint: disable=no-member
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from ._common import _ensure_detection_cache
|
||||
|
||||
|
||||
def check_have_fudai_with_ready_screenshot(
|
||||
analyser: Any, screenshot_ready: bool = False
|
||||
):
|
||||
"""判定直播页面福袋的小图标是否存在(优化版,优先使用模块化查找器)。
|
||||
|
||||
如果启用了优化查找器(fudai_finder_optimized_enabled=True),则使用新的模块化查找器。
|
||||
否则使用原版像素检测实现。
|
||||
"""
|
||||
# 检查是否启用优化查找器
|
||||
try:
|
||||
use_optimized = bool(getattr(analyser, "fudai_finder_optimized_enabled", False))
|
||||
except Exception:
|
||||
use_optimized = False
|
||||
|
||||
if use_optimized:
|
||||
try:
|
||||
from douyin.fudai.douyin_fudai_finder import (
|
||||
check_have_fudai_with_ready_screenshot_optimized,
|
||||
)
|
||||
|
||||
return check_have_fudai_with_ready_screenshot_optimized(
|
||||
analyser, screenshot_ready
|
||||
)
|
||||
except ImportError:
|
||||
# 优化版不可用,回退到原版
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标]", "优化查找器不可用,使用原版", error="ImportError"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 优化版异常,回退到原版
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标]",
|
||||
"优化查找器异常,使用原版",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 原版实现(像素检测版)
|
||||
func_start = time.time()
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic1_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
from douyin.core import path_config
|
||||
|
||||
pic1_path = path_config.get_screenshot_path()
|
||||
attempt_count = 0 # 仅用于日志记录,不影响循环控制
|
||||
|
||||
# ===== 像素检测版(优先使用),不依赖 OpenCV =====
|
||||
# 改为按时间控制循环,而不是按次数限制
|
||||
try:
|
||||
retry_delay_s = float(
|
||||
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
|
||||
)
|
||||
except Exception:
|
||||
retry_delay_s = 0.6
|
||||
try:
|
||||
max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0)
|
||||
except Exception:
|
||||
max_wait_s = 5.0
|
||||
if retry_delay_s < 0.1:
|
||||
retry_delay_s = 0.1 # 最小间隔改为0.1秒
|
||||
if max_wait_s < 0:
|
||||
max_wait_s = 0.0
|
||||
# 防止无限等待:最大等待时间限制为30秒
|
||||
if max_wait_s > 30.0:
|
||||
max_wait_s = 30.0
|
||||
|
||||
loop = 0
|
||||
max_loops = int(max_wait_s / retry_delay_s) + 10 # 额外的循环次数保护
|
||||
consecutive_failures = 0 # 连续失败计数
|
||||
max_consecutive_failures = 5 # 最大连续失败次数
|
||||
|
||||
# 额外的时间限制保护,防止死循环
|
||||
absolute_timeout = func_start + max(
|
||||
max_wait_s * 1.5, 15
|
||||
) # 最长15秒,但不超过 max_wait_s * 1.5
|
||||
|
||||
while (time.time() - func_start) < max_wait_s and time.time() < absolute_timeout:
|
||||
# 额外的循环次数保护:防止无限循环
|
||||
if loop >= max_loops:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 警告",
|
||||
"达到最大循环次数限制,提前退出",
|
||||
max_loops=max_loops,
|
||||
elapsed_s=round(time.time() - func_start, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
# 每次循环都重新截图(除了第一次如果已经提供了截图)
|
||||
from douyin.detection.detection_pkg.finder_screenshot import (
|
||||
capture_screenshot_for_loop,
|
||||
handle_screenshot_load_failure,
|
||||
load_screenshot_with_retry,
|
||||
)
|
||||
|
||||
capture_screenshot_for_loop(analyser, screenshot_ready, loop, pic1_path)
|
||||
|
||||
# 读取截图
|
||||
pic = load_screenshot_with_retry(analyser, pic1_path)
|
||||
|
||||
# 如果截图读取失败,等待后继续下一次循环
|
||||
if pic is None:
|
||||
loop += 1
|
||||
consecutive_failures += 1
|
||||
action = handle_screenshot_load_failure(
|
||||
analyser,
|
||||
consecutive_failures,
|
||||
max_consecutive_failures,
|
||||
func_start,
|
||||
max_wait_s,
|
||||
retry_delay_s,
|
||||
)
|
||||
if action == "break":
|
||||
break
|
||||
continue
|
||||
|
||||
pic_new = pic.convert("RGBA")
|
||||
width, height = pic_new.size
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
except Exception:
|
||||
rx = 1080
|
||||
try:
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
ry = 2400
|
||||
try:
|
||||
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
except Exception:
|
||||
y_pianyi_val = 0
|
||||
|
||||
detected = False
|
||||
detected_x = None
|
||||
# 初始化扫描范围变量(用于日志记录)
|
||||
scan_x_start = 41 * rx // 1080
|
||||
scan_x_end = min(410 * rx // 1080, width)
|
||||
scan_y = 403 * ry // 2400 + y_pianyi_val
|
||||
|
||||
# 获取最优搜索起始位置(使用历史记录或默认值)
|
||||
try:
|
||||
# 尝试获取上次找到的福袋位置(1080基准)
|
||||
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
|
||||
if last_fudai_x > 0 and scan_x_start <= last_fudai_x <= scan_x_end:
|
||||
optimal_x_scaled = last_fudai_x * rx // 1080
|
||||
else:
|
||||
# 使用默认最优位置:最热门区域中心(98-240的中心,约169)
|
||||
optimal_x_scaled = 169 * rx // 1080
|
||||
except Exception:
|
||||
# 使用默认最优位置
|
||||
optimal_x_scaled = 169 * rx // 1080
|
||||
|
||||
# 确保最优位置在搜索范围内
|
||||
optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1))
|
||||
|
||||
# 保存完整截图用于调试(检测前)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
pic_rgb_full = pic_new.convert("RGB")
|
||||
|
||||
# 保存完整截图
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="before_detect",
|
||||
coords=(
|
||||
(scan_x_start, scan_y - 3, scan_x_end, scan_y + 4)
|
||||
if scan_y >= 3
|
||||
else None
|
||||
),
|
||||
extra_info={
|
||||
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
|
||||
"resolution": f"{rx}x{ry}",
|
||||
"y_offset": y_pianyi_val,
|
||||
"loop": loop,
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]", "福袋图标检测前保存完整截图", path=debug_path
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 先尝试 numpy 加速扫描水平带(性能优化:批量处理)
|
||||
from douyin.detection.detection_pkg.finder_numpy_scan import (
|
||||
numpy_band_scan,
|
||||
)
|
||||
|
||||
detected, detected_x = numpy_band_scan(
|
||||
analyser, detected, detected_x, pic_new,
|
||||
width, height, rx, ry, y_pianyi_val, optimal_x_scaled,
|
||||
)
|
||||
# numpy 未命中/不可用时回退到原始逐像素检查
|
||||
from douyin.detection.detection_pkg.finder_pixel_scan import (
|
||||
pixel_scan_fallback,
|
||||
)
|
||||
|
||||
detected, detected_x = pixel_scan_fallback(
|
||||
analyser, detected, detected_x, pic_new, rx, ry, y_pianyi_val,
|
||||
)
|
||||
if detected:
|
||||
break # 找到后退出外层 while 循环
|
||||
|
||||
# 像素检测未命中时,使用模板匹配作为兜底
|
||||
from douyin.detection.detection_pkg.finder_template_match import (
|
||||
template_match_fallback,
|
||||
)
|
||||
|
||||
detected, detected_x = template_match_fallback(
|
||||
analyser, detected, detected_x, pic_new,
|
||||
width, height, rx, ry, y_pianyi_val, loop,
|
||||
)
|
||||
if detected and detected_x is not None:
|
||||
# 重置连续失败计数
|
||||
consecutive_failures = 0
|
||||
|
||||
# 记录"进入直播间→找到福袋"耗时统计 + 命中调试信息
|
||||
from douyin.detection.detection_pkg.finder_loop_logging import (
|
||||
log_fudai_found_and_metrics,
|
||||
)
|
||||
|
||||
log_fudai_found_and_metrics(
|
||||
analyser, detected_x, func_start, loop, ry, y_pianyi_val
|
||||
)
|
||||
return int(detected_x or 0)
|
||||
|
||||
loop += 1
|
||||
consecutive_failures += 1
|
||||
|
||||
# 如果连续失败太多次,提前退出(避免无效循环)
|
||||
if consecutive_failures >= max_consecutive_failures:
|
||||
try:
|
||||
elapsed_ms = int((time.time() - func_start) * 1000)
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 警告",
|
||||
"连续检测失败次数过多,提前退出",
|
||||
consecutive_failures=consecutive_failures,
|
||||
loop=loop,
|
||||
elapsed_ms=elapsed_ms,
|
||||
scan_y=scan_y,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
# 每轮记录一次轻量调试信息(每 3 次循环一次,减少日志量)
|
||||
from douyin.detection.detection_pkg.finder_loop_logging import (
|
||||
log_loop_progress,
|
||||
)
|
||||
|
||||
log_loop_progress(
|
||||
analyser, loop, func_start, pic_new, width, height,
|
||||
scan_x_start, scan_x_end, scan_y, consecutive_failures,
|
||||
)
|
||||
|
||||
# 检查是否还有剩余时间
|
||||
elapsed = time.time() - func_start
|
||||
if elapsed < max_wait_s:
|
||||
remaining_time = max_wait_s - elapsed
|
||||
sleep_time = min(retry_delay_s, remaining_time)
|
||||
if sleep_time > 0:
|
||||
try:
|
||||
analyser.operation.delay(sleep_time)
|
||||
except Exception:
|
||||
time.sleep(sleep_time)
|
||||
else:
|
||||
# 时间已到,退出循环
|
||||
break
|
||||
|
||||
# 像素检测未找到时,返回 False,并记录总耗时与循环次数
|
||||
from douyin.detection.detection_pkg.finder_loop_logging import (
|
||||
log_no_fudai_found,
|
||||
)
|
||||
|
||||
log_no_fudai_found(analyser, func_start, loop, max_wait_s, retry_delay_s)
|
||||
return False
|
||||
|
||||
|
||||
|
||||
# ========== 以下为旧的像素检测代码,已暂时禁用 ==========
|
||||
# 像素检测代码已删除,使用模板匹配替代
|
||||
# 如需恢复像素检测,请参考 git 历史记录
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""find_fudai 辅助:循环中的调试日志
|
||||
|
||||
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
|
||||
- log_fudai_found_and_metrics:命中福袋后记录"进入直播间→找到福袋"耗时统计 + 命中调试信息
|
||||
- log_loop_progress:每 3 次循环记录一次轻量调试信息
|
||||
- log_no_fudai_found:未找到时记录总耗时与循环次数
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
|
||||
def log_fudai_found_and_metrics(
|
||||
analyser: Any,
|
||||
detected_x,
|
||||
func_start: float,
|
||||
loop: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
) -> None:
|
||||
"""命中福袋后:记录"进入直播间→找到福袋"耗时统计 + 命中调试信息。"""
|
||||
# 统计:每次"进入直播间"后首次找到福袋图标耗时
|
||||
try:
|
||||
enter_ts = float(getattr(analyser, "_enter_live_ts", 0.0) or 0.0)
|
||||
except Exception:
|
||||
enter_ts = 0.0
|
||||
try:
|
||||
already = bool(getattr(analyser, "_enter_live_fudai_logged", False))
|
||||
except Exception:
|
||||
already = False
|
||||
if (enter_ts > 0) and (not already):
|
||||
try:
|
||||
dt = float(time.time() - enter_ts)
|
||||
except Exception:
|
||||
dt = -1.0
|
||||
if dt >= 0:
|
||||
try:
|
||||
reason = str(getattr(analyser, "_enter_live_reason", "") or "")
|
||||
except Exception:
|
||||
reason = ""
|
||||
try:
|
||||
analyser._enter_live_fudai_logged = True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"性能",
|
||||
"进入直播间后找到福袋耗时",
|
||||
seconds=round(dt, 2),
|
||||
enter_reason=reason,
|
||||
fudai_x=int(detected_x or 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 命中时记录调试信息
|
||||
try:
|
||||
elapsed_ms = int((time.time() - func_start) * 1000)
|
||||
scan_y_for_log = 403 * ry // 2400 + y_pianyi_val
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 命中",
|
||||
loop=loop,
|
||||
elapsed_ms=elapsed_ms,
|
||||
scan_y=scan_y_for_log,
|
||||
x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def log_loop_progress(
|
||||
analyser: Any,
|
||||
loop: int,
|
||||
func_start: float,
|
||||
pic_new,
|
||||
width: int,
|
||||
height: int,
|
||||
scan_x_start: int,
|
||||
scan_x_end: int,
|
||||
scan_y: int,
|
||||
consecutive_failures: int,
|
||||
) -> None:
|
||||
"""每 3 次循环记录一次轻量调试信息(帮助诊断为何未命中)。"""
|
||||
if loop % 3 != 0:
|
||||
return
|
||||
try:
|
||||
elapsed_ms = int((time.time() - func_start) * 1000)
|
||||
sample_color = None
|
||||
try:
|
||||
mid_x = (scan_x_start + scan_x_end) // 2
|
||||
if 0 <= scan_y < height and 0 <= mid_x < width:
|
||||
pix_sample = pic_new.load()
|
||||
sample_color = pix_sample[mid_x, scan_y]
|
||||
except Exception:
|
||||
sample_color = None
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 循环中",
|
||||
loop=loop,
|
||||
elapsed_ms=elapsed_ms,
|
||||
scan_y=scan_y,
|
||||
scan_x_start=scan_x_start,
|
||||
scan_x_end=scan_x_end,
|
||||
sample_color=(
|
||||
str(sample_color) if sample_color is not None else "None"
|
||||
),
|
||||
consecutive_failures=consecutive_failures,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def log_no_fudai_found(
|
||||
analyser: Any,
|
||||
func_start: float,
|
||||
loop: int,
|
||||
max_wait_s: float,
|
||||
retry_delay_s: float,
|
||||
) -> None:
|
||||
"""像素检测未找到时记录总耗时与循环次数。"""
|
||||
try:
|
||||
total_elapsed_ms = int((time.time() - func_start) * 1000)
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 未找到福袋图标",
|
||||
elapsed_ms=total_elapsed_ms,
|
||||
total_loops=loop,
|
||||
max_wait_s=max_wait_s,
|
||||
retry_delay_s=retry_delay_s,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,156 @@
|
||||
"""find_fudai 辅助:numpy 加速水平带扫描
|
||||
|
||||
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
|
||||
使用 numpy 批量处理,从最优位置向左右两侧交替搜索福袋图标的特征颜色。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Tuple
|
||||
|
||||
|
||||
def numpy_band_scan(
|
||||
analyser: Any,
|
||||
detected: bool,
|
||||
detected_x,
|
||||
pic_new,
|
||||
width: int,
|
||||
height: int,
|
||||
rx: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
optimal_x_scaled: int,
|
||||
) -> Tuple[bool, Any]:
|
||||
"""numpy 加速扫描水平带,查找福袋图标的特征颜色。
|
||||
|
||||
返回更新后的 (detected, detected_x)。
|
||||
"""
|
||||
try:
|
||||
import numpy as _np
|
||||
|
||||
# 计算检测区域,考虑分辨率缩放和偏移
|
||||
# 将像素检测的扫描带左上角改为图片坐标 x=157, y=354(右下不变)
|
||||
y0 = 354 * ry // 2400 + y_pianyi_val
|
||||
x1 = max(0, 157 * rx // 1080)
|
||||
x2 = min(width, 410 * rx // 1080)
|
||||
y_top = max(0, y0 - 3)
|
||||
y_bottom = min(height, y0 + 4)
|
||||
|
||||
# 边界检查
|
||||
if x1 < x2 and y_top < y_bottom:
|
||||
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
|
||||
|
||||
# 双截图记录:保存实时操作截图(像素检测区域)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
roi, operation_type="pixel_detect"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
arr = _np.array(roi)
|
||||
if arr.size > 0:
|
||||
r = arr[:, :, 0] # type: ignore[index]
|
||||
g = arr[:, :, 1] # type: ignore[index]
|
||||
b = arr[:, :, 2] # type: ignore[index]
|
||||
# 精度优化:扩大颜色范围,提高容错性(考虑不同屏幕色温和亮度)
|
||||
# 原来的范围:R[193-203], G[176-193], B[237-247]
|
||||
# 优化后:适度放宽范围,但保持中心值权重
|
||||
mask_center = (r >= 190) & (r <= 206) & (g >= 173) & (g <= 196) & (b >= 234) & (b <= 250) # type: ignore[operator]
|
||||
# 速度优化:使用更宽松的预筛选,减少计算量
|
||||
mask = mask_center
|
||||
# 检查每一列是否有足够多的匹配像素(提高准确性,避免单个噪点误判)
|
||||
cols = _np.sum(mask, axis=0)
|
||||
# 至少需要2个像素匹配(避免单个噪点误判)
|
||||
valid_cols = cols >= 2
|
||||
if valid_cols.any():
|
||||
# 优化:从最优位置开始向左右两侧搜索
|
||||
roi_width = x2 - x1
|
||||
optimal_col = optimal_x_scaled - x1 # 转换为ROI内的列索引
|
||||
optimal_col = max(0, min(optimal_col, roi_width - 1))
|
||||
|
||||
# 从最优位置开始,向左右两侧交替搜索
|
||||
found_col = None
|
||||
search_range = max(optimal_col, roi_width - optimal_col)
|
||||
|
||||
# 先检查最优位置本身
|
||||
if valid_cols[optimal_col]:
|
||||
found_col = optimal_col
|
||||
else:
|
||||
# 向左右两侧交替搜索
|
||||
for offset in range(1, search_range + 1):
|
||||
# 先检查右侧
|
||||
right_col = optimal_col + offset
|
||||
if right_col < roi_width and valid_cols[right_col]:
|
||||
found_col = right_col
|
||||
break
|
||||
# 再检查左侧
|
||||
left_col = optimal_col - offset
|
||||
if left_col >= 0 and valid_cols[left_col]:
|
||||
found_col = left_col
|
||||
break
|
||||
|
||||
# 如果没找到,回退到原来的方法(从左到右)
|
||||
if found_col is None:
|
||||
found_col = int(_np.argmax(valid_cols))
|
||||
|
||||
col_idx = found_col
|
||||
# 计算检测到的x坐标:转换为1080基准坐标,确保精度
|
||||
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
|
||||
detected = True
|
||||
|
||||
# 保存找到的位置作为下次的最优位置
|
||||
try:
|
||||
analyser.last_fudai_x = detected_x
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
roi, operation_type="pixel_detect"
|
||||
)
|
||||
|
||||
# 保存完整截图(检测成功)
|
||||
pic_rgb_full = pic_new.convert("RGB")
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=(x1, y_top, x2, y_bottom),
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"detected_x_scaled": x1 + col_idx,
|
||||
"scan_range": f"x:{x1}-{x2}, y:{y_top}-{y_bottom}",
|
||||
"resolution": f"{rx}x{ry}",
|
||||
"result": "success",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标检测成功保存完整截图",
|
||||
path=debug_path,
|
||||
detected_x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
except (ImportError, ValueError, IndexError, AttributeError):
|
||||
# numpy不可用或计算错误,回退到逐像素检测
|
||||
detected = False
|
||||
|
||||
|
||||
return detected, detected_x
|
||||
@@ -0,0 +1,207 @@
|
||||
"""find_fudai 辅助:逐像素扫描兜底
|
||||
|
||||
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
|
||||
当 numpy 加速扫描未命中或不可用时,回退到原始逐像素检查。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Tuple
|
||||
|
||||
|
||||
def pixel_scan_fallback(
|
||||
analyser: Any,
|
||||
detected: bool,
|
||||
detected_x,
|
||||
pic_new,
|
||||
rx: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
) -> Tuple[bool, Any]:
|
||||
"""numpy 未命中或不可用时的原始逐像素检查兜底。
|
||||
|
||||
返回更新后的 (detected, detected_x)。
|
||||
"""
|
||||
if not detected:
|
||||
try:
|
||||
pix = pic_new.load()
|
||||
pic_width, pic_height = pic_new.size
|
||||
# 计算实际扫描范围,防止越界
|
||||
scan_x_start = 41 * rx // 1080
|
||||
scan_x_end = min(410 * rx // 1080, pic_width)
|
||||
scan_y = 403 * ry // 2400 + y_pianyi_val
|
||||
|
||||
# 获取最优搜索起始位置(使用历史记录或默认值)
|
||||
try:
|
||||
# 尝试获取上次找到的福袋位置(1080基准)
|
||||
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
|
||||
if (
|
||||
last_fudai_x > 0
|
||||
and scan_x_start <= last_fudai_x * rx // 1080 <= scan_x_end
|
||||
):
|
||||
optimal_x_scaled = last_fudai_x * rx // 1080
|
||||
else:
|
||||
# 使用默认最优位置:最热门区域中心(98-240的中心,约169)
|
||||
optimal_x_scaled = 169 * rx // 1080
|
||||
except Exception:
|
||||
# 使用默认最优位置
|
||||
optimal_x_scaled = 169 * rx // 1080
|
||||
|
||||
# 确保最优位置在搜索范围内
|
||||
optimal_x_scaled = max(
|
||||
scan_x_start, min(optimal_x_scaled, scan_x_end - 1)
|
||||
)
|
||||
|
||||
# 确保y坐标在有效范围内
|
||||
if 0 <= scan_y < pic_height:
|
||||
# 精度优化:同时检查上下几行像素,提高检测准确性
|
||||
for offset_y in [0, -1, 1, -2, 2]: # 检查当前行及上下2行
|
||||
check_y = scan_y + offset_y
|
||||
if not (0 <= check_y < pic_height):
|
||||
continue
|
||||
|
||||
# 优化:从最优位置开始向左右两侧搜索
|
||||
found_x = None
|
||||
search_range = max(
|
||||
optimal_x_scaled - scan_x_start,
|
||||
scan_x_end - optimal_x_scaled,
|
||||
)
|
||||
|
||||
# 先检查最优位置本身
|
||||
try:
|
||||
px = pix[optimal_x_scaled, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = optimal_x_scaled
|
||||
except (IndexError, TypeError):
|
||||
pass
|
||||
|
||||
# 如果最优位置没找到,向左右两侧交替搜索
|
||||
if found_x is None:
|
||||
for offset in range(1, search_range + 1):
|
||||
# 先检查右侧
|
||||
right_x = optimal_x_scaled + offset
|
||||
if right_x < scan_x_end:
|
||||
try:
|
||||
px = pix[right_x, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = right_x
|
||||
break
|
||||
except (IndexError, TypeError):
|
||||
continue
|
||||
|
||||
# 再检查左侧
|
||||
left_x = optimal_x_scaled - offset
|
||||
if left_x >= scan_x_start:
|
||||
try:
|
||||
px = pix[left_x, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = left_x
|
||||
break
|
||||
except (IndexError, TypeError):
|
||||
continue
|
||||
|
||||
# 如果还是没找到,回退到原来的方法(从左到右)
|
||||
if found_x is None:
|
||||
for x_scaled in range(scan_x_start, scan_x_end):
|
||||
try:
|
||||
px = pix[x_scaled, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = x_scaled
|
||||
break
|
||||
except (IndexError, TypeError):
|
||||
continue
|
||||
|
||||
if found_x is not None:
|
||||
# 转换回1080基准坐标
|
||||
detected_x = int(found_x * 1080.0 / max(1, rx))
|
||||
detected = True
|
||||
|
||||
# 保存找到的位置作为下次的最优位置
|
||||
try:
|
||||
analyser.last_fudai_x = detected_x
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
detect_roi = pic_new.crop(
|
||||
(
|
||||
scan_x_start,
|
||||
max(0, scan_y - 3),
|
||||
scan_x_end,
|
||||
min(pic_height, scan_y + 4),
|
||||
)
|
||||
).convert("RGB")
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
detect_roi,
|
||||
operation_type="pixel_detect",
|
||||
)
|
||||
|
||||
# 保存完整截图(检测成功)
|
||||
pic_rgb_full = pic_new.convert("RGB")
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=(
|
||||
scan_x_start,
|
||||
max(0, scan_y - 3),
|
||||
scan_x_end,
|
||||
min(pic_height, scan_y + 4),
|
||||
),
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"detected_x_scaled": found_x,
|
||||
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
|
||||
"resolution": f"{rx}x{ry}",
|
||||
"result": "success",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标检测成功保存完整截图",
|
||||
path=debug_path,
|
||||
detected_x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
break # 找到后退出offset_y循环
|
||||
|
||||
except Exception:
|
||||
# 像素检测失败,记录但不影响主流程
|
||||
pass
|
||||
|
||||
|
||||
return detected, detected_x
|
||||
@@ -0,0 +1,111 @@
|
||||
"""find_fudai 辅助:截图获取 + 验证 + 重试
|
||||
|
||||
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
|
||||
def capture_screenshot_for_loop(analyser: Any, screenshot_ready: bool, loop: int, pic1_path: str) -> None:
|
||||
"""每次循环开始时获取截图(除了第一次如果已提供)。
|
||||
|
||||
流程:
|
||||
1. 调用 _shot_and_diagnose 截图(diagnose=False)
|
||||
2. 失败时调用 get_screenshot 并用 PIL 验证文件完整性
|
||||
3. 如验证失败再尝试一次截图作为最后回退
|
||||
"""
|
||||
if screenshot_ready and loop == 0:
|
||||
return
|
||||
|
||||
try:
|
||||
analyser._shot_and_diagnose(
|
||||
"找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False
|
||||
)
|
||||
except Exception:
|
||||
# 如果截图失败,尝试直接调用 get_screenshot 并验证文件可读性
|
||||
try:
|
||||
analyser.operation.get_screenshot(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
valid = False
|
||||
try:
|
||||
if (
|
||||
os.path.exists(pic1_path)
|
||||
and os.path.getsize(pic1_path) >= 1024
|
||||
):
|
||||
from PIL import Image as PILImage
|
||||
|
||||
with PILImage.open(pic1_path) as _im:
|
||||
_im.verify()
|
||||
valid = True
|
||||
except Exception:
|
||||
valid = False
|
||||
if not valid:
|
||||
# 再尝试一次直接截图作为最后回退
|
||||
try:
|
||||
analyser.operation.get_screenshot(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def load_screenshot_with_retry(analyser: Any, pic1_path: str):
|
||||
"""读取截图,失败时重新截图后重试。返回 PIL Image 或 None。"""
|
||||
from PIL import Image
|
||||
|
||||
pic = None
|
||||
try:
|
||||
pic = Image.open(pic1_path)
|
||||
pic.load()
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
|
||||
pic = Image.open(pic1_path)
|
||||
pic.load()
|
||||
except Exception:
|
||||
pass
|
||||
return pic
|
||||
|
||||
|
||||
def handle_screenshot_load_failure(
|
||||
analyser: Any,
|
||||
consecutive_failures: int,
|
||||
max_consecutive_failures: int,
|
||||
func_start: float,
|
||||
max_wait_s: float,
|
||||
retry_delay_s: float,
|
||||
) -> str:
|
||||
"""截图读取失败时的处理:
|
||||
|
||||
- 连续失败超过阈值 → 写警告日志,返回 "break"(外层 while 应 break)
|
||||
- 否则等待 retry_delay_s 秒后返回 "continue"(外层 while 应 continue)
|
||||
"""
|
||||
if consecutive_failures >= max_consecutive_failures:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 警告",
|
||||
"连续截图失败次数过多,提前退出",
|
||||
consecutive_failures=consecutive_failures,
|
||||
elapsed_s=round(time.time() - func_start, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return "break"
|
||||
|
||||
# 检查是否还有剩余时间
|
||||
elapsed = time.time() - func_start
|
||||
if elapsed < max_wait_s:
|
||||
remaining_time = max_wait_s - elapsed
|
||||
sleep_time = min(retry_delay_s, remaining_time)
|
||||
if sleep_time > 0:
|
||||
try:
|
||||
analyser.operation.delay(sleep_time)
|
||||
except Exception:
|
||||
time.sleep(sleep_time)
|
||||
return "continue"
|
||||
@@ -0,0 +1,257 @@
|
||||
"""find_fudai 辅助:模板匹配兜底(OpenCV)
|
||||
|
||||
从 douyin/detection/detection_pkg/finder.py:check_have_fudai_with_ready_screenshot 中提取。
|
||||
当像素检测未命中时,使用 cv2.matchTemplate 在指定区域查找福袋图标。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Tuple
|
||||
|
||||
|
||||
def template_match_fallback(
|
||||
analyser: Any,
|
||||
detected: bool,
|
||||
detected_x,
|
||||
pic_new,
|
||||
width: int,
|
||||
height: int,
|
||||
rx: int,
|
||||
ry: int,
|
||||
y_pianyi_val: int,
|
||||
loop: int,
|
||||
) -> Tuple[bool, Any]:
|
||||
"""像素检测未命中时的 OpenCV 模板匹配兜底。
|
||||
|
||||
返回更新后的 (detected, detected_x)。
|
||||
"""
|
||||
# 像素检测未命中时,使用模板匹配作为兜底
|
||||
if not detected or detected_x is None:
|
||||
try:
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# 获取模板路径
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
template_path = path_config.get_assets_dir() + "/fudai.png"
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
base_dir = os.path.dirname(__file__)
|
||||
template_path = os.path.join(base_dir, "assets", "fudai.png")
|
||||
|
||||
if os.path.exists(template_path):
|
||||
# 获取匹配阈值
|
||||
try:
|
||||
template_threshold = float(
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.7)
|
||||
or 0.7
|
||||
)
|
||||
except Exception:
|
||||
template_threshold = 0.7
|
||||
|
||||
# 读取模板
|
||||
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
|
||||
if template is not None:
|
||||
# 将PIL图片转换为OpenCV格式
|
||||
pic_rgb = pic_new.convert("RGB")
|
||||
screenshot_bgr = cv2.cvtColor(
|
||||
np.array(pic_rgb), cv2.COLOR_RGB2BGR
|
||||
)
|
||||
|
||||
# 定义搜索区域:X=156-269(1080基准),Y=351-451(2400基准)
|
||||
x1 = max(0, 156 * rx // 1080)
|
||||
x2 = min(width, 269 * rx // 1080)
|
||||
y_top = max(0, 351 * ry // 2400 + y_pianyi_val)
|
||||
y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val)
|
||||
|
||||
if x1 < x2 and y_top < y_bottom:
|
||||
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index]
|
||||
|
||||
if search_roi.size > 0:
|
||||
th, tw = template.shape[:2]
|
||||
rh, rw = search_roi.shape[:2]
|
||||
|
||||
# 保存搜索区域截图到 last_match.png
|
||||
try:
|
||||
base_dir = os.path.dirname(__file__)
|
||||
pic_base = os.path.join(base_dir, "pic")
|
||||
match_dir = os.path.join(pic_base, "template_match")
|
||||
os.makedirs(match_dir, exist_ok=True)
|
||||
last_match_path = os.path.join(
|
||||
match_dir, "last_match.png"
|
||||
)
|
||||
|
||||
# 保存截图并检查是否成功
|
||||
save_success = cv2.imwrite(
|
||||
last_match_path, search_roi
|
||||
)
|
||||
if save_success:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 已保存搜索区域截图",
|
||||
loop=loop,
|
||||
文件路径=last_match_path,
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 保存搜索区域截图失败",
|
||||
loop=loop,
|
||||
文件路径=last_match_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as save_err:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 保存搜索区域截图异常",
|
||||
loop=loop,
|
||||
错误类型=type(save_err).__name__,
|
||||
错误信息=str(save_err),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果模板太大,缩小模板
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
if scale > 0:
|
||||
template = cv2.resize(
|
||||
template,
|
||||
(
|
||||
max(1, int(tw * scale)),
|
||||
max(1, int(th * scale)),
|
||||
),
|
||||
)
|
||||
th, tw = template.shape[:2]
|
||||
|
||||
# 执行模板匹配
|
||||
if th <= rh and tw <= rw:
|
||||
res = cv2.matchTemplate(
|
||||
search_roi, template, cv2.TM_CCOEFF_NORMED
|
||||
)
|
||||
_min_val, max_val, _min_loc, max_loc = (
|
||||
cv2.minMaxLoc(res)
|
||||
)
|
||||
|
||||
# 双截图记录:保存实时操作截图(搜索区域)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
|
||||
)
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
search_roi_pil,
|
||||
operation_type="template_match",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配兜底",
|
||||
loop=loop,
|
||||
匹配分数=round(max_val, 4),
|
||||
阈值=template_threshold,
|
||||
是否通过=bool(
|
||||
max_val >= template_threshold
|
||||
),
|
||||
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
模板尺寸=f"{tw}x{th}",
|
||||
截图尺寸=f"{width}x{height}",
|
||||
分辨率=f"{rx}x{ry}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if max_val >= template_threshold:
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(
|
||||
search_roi, cv2.COLOR_BGR2RGB
|
||||
)
|
||||
)
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
search_roi_pil,
|
||||
operation_type="template_match",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 计算检测到的X坐标(1080基准)
|
||||
detected_x_in_roi = max_loc[0]
|
||||
detected_x = int(
|
||||
(x1 + detected_x_in_roi + tw // 2)
|
||||
* 1080.0
|
||||
/ max(1, rx)
|
||||
)
|
||||
detected = True
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 模板尺寸不匹配,记录调试信息
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-尺寸不匹配",
|
||||
loop=loop,
|
||||
模板尺寸=f"{tw}x{th}",
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 搜索区域为空,记录调试信息
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-搜索区域为空",
|
||||
loop=loop,
|
||||
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
截图尺寸=f"{width}x{height}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 搜索区域坐标无效,记录调试信息
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配失败-坐标无效",
|
||||
loop=loop,
|
||||
x1=x1,
|
||||
x2=x2,
|
||||
y_top=y_top,
|
||||
y_bottom=y_bottom,
|
||||
截图尺寸=f"{width}x{height}",
|
||||
分辨率=f"{rx}x{ry}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except (ImportError, Exception) as e:
|
||||
# OpenCV不可用或模板匹配失败,继续使用像素检测结果
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配异常",
|
||||
loop=loop,
|
||||
错误类型=type(e).__name__,
|
||||
错误信息=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
return detected, detected_x
|
||||
File diff suppressed because it is too large.
Load diff
+33
-1172
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
||||
"""pixel - 像素 / 模板匹配检测子包。
|
||||
|
||||
原 douyin/detection/douyin_pixel.py 拆成 4 个子模块:
|
||||
|
||||
- _common 共享:_safe_open_screenshot_rgb
|
||||
- popups 弹窗类检测:优惠券 / 红包 / 抽奖结果
|
||||
- buttons 按钮区域红色检测:参与按钮 / 粉丝团加入
|
||||
- stage 阶段诊断:直播间图标 / 福袋详情页 / 综合阶段状态读取
|
||||
|
||||
外部 import 路径不变:
|
||||
``from douyin.detection.douyin_pixel import detect_fudai_detail_page`` 仍可用。
|
||||
"""
|
||||
|
||||
from ._common import _safe_open_screenshot_rgb
|
||||
from .popups import (
|
||||
detect_coupon_popup_background,
|
||||
detect_redpacket_popup_background,
|
||||
detect_lucky_draw_result_popup,
|
||||
)
|
||||
from .buttons import (
|
||||
detect_attend_button_red_area,
|
||||
detect_fansclub_join_red_area,
|
||||
)
|
||||
from .stage import (
|
||||
detect_live_room_icons_by_pixel,
|
||||
detect_fudai_detail_page,
|
||||
read_pixel_stage_state_from_screenshot,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"_safe_open_screenshot_rgb",
|
||||
"detect_coupon_popup_background",
|
||||
"detect_redpacket_popup_background",
|
||||
"detect_lucky_draw_result_popup",
|
||||
"detect_attend_button_red_area",
|
||||
"detect_fansclub_join_red_area",
|
||||
"detect_live_room_icons_by_pixel",
|
||||
"detect_fudai_detail_page",
|
||||
"read_pixel_stage_state_from_screenshot",
|
||||
]
|
||||
@@ -0,0 +1,32 @@
|
||||
# pyright: reportGeneralTypeIssues=false
|
||||
# pyright: reportAttributeAccessIssue=false
|
||||
# pyright: reportMissingModuleSource=false
|
||||
# pyright: reportUnknownMemberType=false
|
||||
# pyright: reportUnknownVariableType=false
|
||||
# pylint: disable=no-member
|
||||
"""pixel._common - 共享工具函数。
|
||||
|
||||
只包含 _safe_open_screenshot_rgb:安全打开截图为 RGB Image,
|
||||
处理 truncated/损坏文件。被 popups / buttons / stage 子模块共用。
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Any, Optional
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def _safe_open_screenshot_rgb(pic_path: str) -> Optional[Image.Image]:
|
||||
try:
|
||||
if not pic_path or (not os.path.exists(pic_path)):
|
||||
return None
|
||||
pic = Image.open(pic_path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
return pic.convert("RGB")
|
||||
except (OSError, IOError, SyntaxError):
|
||||
# Handle truncated image files
|
||||
return None
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
return None
|
||||
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
# pyright: reportGeneralTypeIssues=false
|
||||
# pyright: reportAttributeAccessIssue=false
|
||||
# pyright: reportMissingModuleSource=false
|
||||
# pyright: reportUnknownMemberType=false
|
||||
# pyright: reportUnknownVariableType=false
|
||||
# pylint: disable=no-member
|
||||
"""pixel.buttons - 按钮区域的红色检测。
|
||||
|
||||
- detect_attend_button_red_area 福袋详情页"参与抽奖"按钮
|
||||
- detect_fansclub_join_red_area 粉丝团加入按钮
|
||||
"""
|
||||
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any, Optional
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from ._common import _safe_open_screenshot_rgb
|
||||
|
||||
|
||||
def detect_attend_button_red_area(
|
||||
pic_rgb: Image.Image,
|
||||
return_info: bool = False,
|
||||
red_ratio_threshold: float | None = None,
|
||||
analyser: Any = None,
|
||||
) -> bool | tuple[bool, dict]:
|
||||
"""检测参与按钮:大片红色区域。
|
||||
|
||||
参与按钮通常在屏幕底部,有大片红色背景。
|
||||
检测区域:(306,2030)-(780,2110) 基准1080x2400,但实际可能更宽
|
||||
扩展检测区域到更宽的范围以覆盖"一键参与评论"等按钮
|
||||
"""
|
||||
try:
|
||||
width, height = pic_rgb.size
|
||||
# 缩放坐标到实际尺寸
|
||||
scale_x = width / 1080.0
|
||||
scale_y = height / 2400.0
|
||||
|
||||
# 检测区域(基准1080x2400,扩展宽度以覆盖更宽的按钮)
|
||||
x1 = int(200 * scale_x) # 扩展左侧
|
||||
y1 = int(2000 * scale_y) # 稍微上移
|
||||
x2 = int(880 * scale_x) # 扩展右侧
|
||||
y2 = int(2120 * scale_y) # 稍微下移
|
||||
|
||||
# 确保坐标在范围内
|
||||
x1 = max(0, min(x1, width))
|
||||
y1 = max(0, min(y1, height))
|
||||
x2 = max(0, min(x2, width))
|
||||
y2 = max(0, min(y2, height))
|
||||
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
return False
|
||||
|
||||
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb, # 使用全屏截图
|
||||
operation_type="pixel_detect",
|
||||
picname="attend_button",
|
||||
step="before_detect",
|
||||
coords=(x1, y1, x2, y2), # 标注识别区域
|
||||
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.info("[调试图像] 参与按钮检测前保存: %s", debug_path)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
# 采样检测点:检测大片红色区域
|
||||
red_count = 0
|
||||
step_x = max(1, (x2 - x1) // 15)
|
||||
step_y = max(1, (y2 - y1) // 10)
|
||||
|
||||
for y in range(y1, y2, step_y):
|
||||
for x in range(x1, x2, step_x):
|
||||
try:
|
||||
r, g, b = pic_rgb.getpixel((x, y))
|
||||
# 检测红色:R值高,G和B相对较低
|
||||
if r > 200 and (r - g) > 50 and (r - b) > 50:
|
||||
red_count += 1
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
continue
|
||||
|
||||
# 如果红色像素占比足够高(至少25%),认为有大片红色背景
|
||||
total_samples = len(list(range(y1, y2, step_y))) * len(
|
||||
list(range(x1, x2, step_x))
|
||||
)
|
||||
if total_samples == 0:
|
||||
return False
|
||||
|
||||
red_ratio = red_count / total_samples if total_samples > 0 else 0
|
||||
# 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值
|
||||
if red_ratio_threshold is not None:
|
||||
threshold = float(red_ratio_threshold)
|
||||
elif analyser is not None:
|
||||
try:
|
||||
threshold = float(
|
||||
getattr(analyser, "attend_button_red_ratio_threshold", 0.25) or 0.25
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
threshold = 0.25
|
||||
else:
|
||||
threshold = 0.25
|
||||
result = red_ratio >= threshold
|
||||
|
||||
# 如果请求详细信息,返回包含red_ratio的字典
|
||||
if return_info:
|
||||
reason_value: Optional[str] = (
|
||||
None if result else "red_ratio_below_threshold"
|
||||
)
|
||||
return result, {
|
||||
"method": "pixel_detect",
|
||||
"red_ratio": red_ratio,
|
||||
"red_count": red_count,
|
||||
"total_samples": total_samples,
|
||||
"effective_threshold": threshold,
|
||||
"reason": reason_value,
|
||||
}
|
||||
|
||||
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
|
||||
# 无论成功失败都保存debug截图
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb, # 使用全屏截图
|
||||
operation_type="pixel_detect",
|
||||
picname="attend_button",
|
||||
step="detected" if result else "not_detected",
|
||||
coords=(x1, y1, x2, y2), # 标注识别区域
|
||||
extra_info={
|
||||
"red_ratio": round(red_ratio, 4),
|
||||
"red_count": red_count,
|
||||
"total_samples": total_samples,
|
||||
"threshold": threshold,
|
||||
"result": "success" if result else "failed",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.info(
|
||||
"[调试图像] 参与按钮检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
|
||||
debug_path,
|
||||
red_ratio,
|
||||
threshold,
|
||||
"success" if result else "failed",
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
return result
|
||||
except Exception:
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "pixel_detect",
|
||||
"red_ratio": None,
|
||||
"reason": "exception",
|
||||
}
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def detect_fansclub_join_red_area(
|
||||
pic_rgb: Image.Image,
|
||||
return_info: bool = False,
|
||||
red_ratio_threshold: float | None = None,
|
||||
analyser: Any = None,
|
||||
) -> bool | tuple[bool, dict]:
|
||||
"""检测粉丝团加入:大片红色区域。
|
||||
|
||||
粉丝团加入按钮通常在屏幕中下部,有大片红色背景。
|
||||
检测区域:(200,1940)-(880,2140) 基准1080x2400
|
||||
"""
|
||||
try:
|
||||
width, height = pic_rgb.size
|
||||
# 缩放坐标到实际尺寸
|
||||
scale_x = width / 1080.0
|
||||
scale_y = height / 2400.0
|
||||
|
||||
# 检测区域(基准1080x2400)
|
||||
x1 = int(200 * scale_x)
|
||||
y1 = int(1940 * scale_y)
|
||||
x2 = int(880 * scale_x)
|
||||
y2 = int(2140 * scale_y)
|
||||
|
||||
# 确保坐标在范围内
|
||||
x1 = max(0, min(x1, width))
|
||||
y1 = max(0, min(y1, height))
|
||||
x2 = max(0, min(x2, width))
|
||||
y2 = max(0, min(y2, height))
|
||||
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "pixel_detect",
|
||||
"red_ratio": None,
|
||||
"reason": "invalid_region",
|
||||
}
|
||||
return False
|
||||
|
||||
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb, # 使用全屏截图
|
||||
operation_type="pixel_detect",
|
||||
picname="fansclub_join",
|
||||
step="before_detect",
|
||||
coords=(x1, y1, x2, y2), # 标注识别区域
|
||||
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.info(
|
||||
"[调试图像] 粉丝团加入检测前保存: %s",
|
||||
debug_path,
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
# 采样检测点:检测大片红色区域
|
||||
red_count = 0
|
||||
step_x = max(1, (x2 - x1) // 15)
|
||||
step_y = max(1, (y2 - y1) // 10)
|
||||
|
||||
for y in range(y1, y2, step_y):
|
||||
for x in range(x1, x2, step_x):
|
||||
try:
|
||||
r, g, b = pic_rgb.getpixel((x, y))
|
||||
# 检测红色:R值高,G和B相对较低
|
||||
if r > 200 and (r - g) > 50 and (r - b) > 50:
|
||||
red_count += 1
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 如果红色像素占比足够高(至少25%),认为有大片红色背景
|
||||
total_samples = len(list(range(y1, y2, step_y))) * len(
|
||||
list(range(x1, x2, step_x))
|
||||
)
|
||||
if total_samples == 0:
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "pixel_detect",
|
||||
"red_ratio": None,
|
||||
"reason": "no_samples",
|
||||
}
|
||||
return False
|
||||
|
||||
red_ratio = red_count / total_samples if total_samples > 0 else 0
|
||||
# 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值
|
||||
if red_ratio_threshold is not None:
|
||||
threshold = float(red_ratio_threshold)
|
||||
elif analyser is not None:
|
||||
try:
|
||||
threshold = float(
|
||||
getattr(analyser, "fansclub_join_red_ratio_threshold", 0.25) or 0.25
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
threshold = 0.25
|
||||
else:
|
||||
threshold = 0.25
|
||||
result = red_ratio >= threshold
|
||||
|
||||
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
# 无论成功失败都保存debug截图
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb, # 使用全屏截图
|
||||
operation_type="pixel_detect",
|
||||
picname="fansclub_join",
|
||||
step="detected" if result else "not_detected",
|
||||
coords=(x1, y1, x2, y2), # 标注识别区域
|
||||
extra_info={
|
||||
"red_ratio": round(red_ratio, 4),
|
||||
"red_count": red_count,
|
||||
"total_samples": total_samples,
|
||||
"threshold": threshold,
|
||||
"result": "success" if result else "failed",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.info(
|
||||
"[调试图像] 粉丝团加入检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
|
||||
debug_path,
|
||||
red_ratio,
|
||||
threshold,
|
||||
"success" if result else "failed",
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
if return_info:
|
||||
reason_value: Optional[str] = (
|
||||
None if result else "red_ratio_below_threshold"
|
||||
)
|
||||
return result, {
|
||||
"method": "pixel_detect",
|
||||
"red_ratio": red_ratio,
|
||||
"red_count": red_count,
|
||||
"total_samples": total_samples,
|
||||
"effective_threshold": threshold,
|
||||
"reason": reason_value,
|
||||
}
|
||||
|
||||
return result
|
||||
except Exception:
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "pixel_detect",
|
||||
"red_ratio": None,
|
||||
"reason": "exception",
|
||||
}
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,444 @@
|
||||
# pyright: reportGeneralTypeIssues=false
|
||||
# pyright: reportAttributeAccessIssue=false
|
||||
# pyright: reportMissingModuleSource=false
|
||||
# pyright: reportUnknownMemberType=false
|
||||
# pyright: reportUnknownVariableType=false
|
||||
# pylint: disable=no-member
|
||||
"""pixel.popups - 弹窗类像素 / 模板检测。
|
||||
|
||||
- detect_coupon_popup_background 优惠券大弹窗
|
||||
- detect_redpacket_popup_background 购物红包大弹窗
|
||||
- detect_lucky_draw_result_popup 抽奖结果弹窗
|
||||
"""
|
||||
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any, Optional
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from ._common import _safe_open_screenshot_rgb
|
||||
|
||||
|
||||
def detect_coupon_popup_background(
|
||||
pic_rgb: Image.Image,
|
||||
return_info: bool = False,
|
||||
template_threshold: float | None = None,
|
||||
analyser: Any = None,
|
||||
) -> bool | tuple[bool, dict]:
|
||||
"""检测底部优惠券大弹窗(仅模板匹配)。
|
||||
|
||||
模板匹配区域(基于1080x2400基准):
|
||||
- 左上: (9, 1173)
|
||||
- 右下: (1079, 2255)
|
||||
使用 `assets/coupon.png` 作为模板。
|
||||
|
||||
参数:
|
||||
pic_rgb: RGB格式的整屏截图
|
||||
return_info: 是否返回详细信息(包含检测分数)
|
||||
template_threshold: 模板匹配阈值(默认0.75,如果提供则使用,否则从analyser读取)
|
||||
analyser: analyser对象,用于读取配置阈值
|
||||
|
||||
返回:
|
||||
bool: 是否检测到优惠券背景(return_info=False时)
|
||||
tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时)
|
||||
"""
|
||||
try:
|
||||
try:
|
||||
import cv2 # type: ignore[import-untyped]
|
||||
import numpy as np # type: ignore[import-untyped]
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "template_match",
|
||||
"template_score": None,
|
||||
"reason": "opencv_unavailable",
|
||||
}
|
||||
return False
|
||||
|
||||
width, height = pic_rgb.size
|
||||
scale_x = width / 1080.0
|
||||
scale_y = height / 2400.0
|
||||
|
||||
x1 = int(9 * scale_x)
|
||||
y1 = int(1173 * scale_y)
|
||||
x2 = int(1079 * scale_x)
|
||||
y2 = int(2255 * scale_y)
|
||||
|
||||
x1 = max(0, min(x1, width))
|
||||
y1 = max(0, min(y1, height))
|
||||
x2 = max(0, min(x2, width))
|
||||
y2 = max(0, min(y2, height))
|
||||
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "template_match",
|
||||
"template_score": None,
|
||||
"reason": "invalid_region",
|
||||
}
|
||||
return False
|
||||
|
||||
bgr = cv2.cvtColor( # type: ignore[attr-defined]
|
||||
np.asarray(pic_rgb), cv2.COLOR_RGB2BGR # type: ignore[attr-defined]
|
||||
)
|
||||
roi = bgr[y1:y2, x1:x2] # type: ignore[index]
|
||||
if roi.size == 0:
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "template_match",
|
||||
"template_score": None,
|
||||
"reason": "empty_roi",
|
||||
}
|
||||
return False
|
||||
|
||||
# 使用统一的模板路径配置
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
template_path = path_config.get_assets_dir() + "/coupon.png"
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
base_dir = os.path.dirname(__file__)
|
||||
template_path = os.path.join(base_dir, "assets", "coupon.png")
|
||||
if not os.path.exists(template_path):
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "template_match",
|
||||
"template_score": None,
|
||||
"reason": "template_not_found",
|
||||
}
|
||||
return False
|
||||
|
||||
template = cv2.imread( # type: ignore[attr-defined,assignment]
|
||||
template_path, cv2.IMREAD_COLOR # type: ignore[attr-defined]
|
||||
)
|
||||
if template is None:
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "template_match",
|
||||
"template_score": None,
|
||||
"reason": "template_load_failed",
|
||||
}
|
||||
return False
|
||||
if roi.shape[0] < template.shape[0] or roi.shape[1] < template.shape[1]:
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "template_match",
|
||||
"template_score": None,
|
||||
"reason": "template_too_large",
|
||||
}
|
||||
return False
|
||||
|
||||
res = cv2.matchTemplate( # type: ignore[attr-defined]
|
||||
roi, template, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined]
|
||||
)
|
||||
_, max_val, _, _ = cv2.minMaxLoc(res) # type: ignore[attr-defined]
|
||||
# 获取阈值:优先使用传入参数,其次从analyser读取,最后使用默认值
|
||||
if template_threshold is not None:
|
||||
threshold = float(template_threshold)
|
||||
elif analyser is not None:
|
||||
try:
|
||||
threshold = float(
|
||||
getattr(analyser, "coupon_template_match_threshold", 0.75) or 0.75
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
threshold = 0.75
|
||||
else:
|
||||
threshold = 0.75
|
||||
result = max_val >= threshold
|
||||
|
||||
if return_info:
|
||||
reason_value: Optional[str] = None if result else "score_below_threshold"
|
||||
return result, {
|
||||
"method": "template_match",
|
||||
"template_score": float(max_val),
|
||||
"effective_threshold": threshold,
|
||||
"reason": reason_value,
|
||||
}
|
||||
return result
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "template_match",
|
||||
"template_score": None,
|
||||
"reason": f"exception: {str(e)}",
|
||||
}
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def detect_redpacket_popup_background(
|
||||
pic_rgb: Image.Image,
|
||||
return_info: bool = False,
|
||||
red_ratio_threshold: float | None = None,
|
||||
analyser: Any = None,
|
||||
) -> bool | tuple[bool, dict]:
|
||||
"""中央购物红包弹窗检测:检测中央大红包区域的红色占比。
|
||||
|
||||
购物红包特征:
|
||||
- 中央大型红色弹窗
|
||||
- 包含黄色圆形"抢"按钮
|
||||
- 主要颜色为红色(RGB约 255, 100-150, 100-150)
|
||||
|
||||
检测区域(基准1080x2400):大约中央区域
|
||||
- 左上:(300, 400)
|
||||
- 右下:(780, 1200)
|
||||
|
||||
参数:
|
||||
pic_rgb: RGB格式的整屏截图
|
||||
return_info: 是否返回详细信息(包含红色比例)
|
||||
red_ratio_threshold: 红色占比阈值(默认0.15,若提供则使用)
|
||||
analyser: analyser对象,用于读取配置阈值
|
||||
|
||||
返回:
|
||||
bool: 是否检测到购物红包背景(return_info=False时)
|
||||
tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时)
|
||||
"""
|
||||
try:
|
||||
import numpy as np # type: ignore[import-untyped]
|
||||
|
||||
width, height = pic_rgb.size
|
||||
scale_x = width / 1080.0
|
||||
scale_y = height / 2400.0
|
||||
|
||||
# 购物红包通常出现在屏幕中央
|
||||
# 基准坐标(1080x2400)
|
||||
x1 = int(200 * scale_x)
|
||||
y1 = int(300 * scale_y)
|
||||
x2 = int(880 * scale_x)
|
||||
y2 = int(1400 * scale_y)
|
||||
|
||||
# 边界检查
|
||||
x1 = max(0, min(x1, width))
|
||||
x2 = max(0, min(x2, width))
|
||||
y1 = max(0, min(y1, height))
|
||||
y2 = max(0, min(y2, height))
|
||||
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "pixel_detection",
|
||||
"red_ratio": 0.0,
|
||||
"reason": "invalid_region",
|
||||
}
|
||||
return False
|
||||
|
||||
# 裁剪感兴趣区域
|
||||
roi = pic_rgb.crop((x1, y1, x2, y2))
|
||||
arr = np.asarray(roi)
|
||||
|
||||
if arr.size == 0:
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "pixel_detection",
|
||||
"red_ratio": 0.0,
|
||||
"reason": "empty_roi",
|
||||
}
|
||||
return False
|
||||
|
||||
# 提取RGB通道
|
||||
r = arr[:, :, 0] # type: ignore[index]
|
||||
g = arr[:, :, 1] # type: ignore[index]
|
||||
b = arr[:, :, 2] # type: ignore[index]
|
||||
|
||||
# 红色特征:R > 200, G < 180, B < 180
|
||||
# 购物红包的红色通常很纯,R值很高
|
||||
mask = (r >= 220) & (g <= 160) & (b <= 160)
|
||||
|
||||
# 计算红色像素占比
|
||||
total_pixels = mask.size
|
||||
red_pixels = np.sum(mask) # type: ignore[call-overload]
|
||||
red_ratio = red_pixels / total_pixels if total_pixels > 0 else 0
|
||||
|
||||
# 阈值:至少15%的像素满足红色特征
|
||||
if red_ratio_threshold is not None:
|
||||
threshold = float(red_ratio_threshold)
|
||||
elif analyser is not None:
|
||||
try:
|
||||
threshold = float(
|
||||
getattr(analyser, "shopping_redpacket_red_ratio_threshold", 0.15)
|
||||
or 0.15
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
threshold = 0.15
|
||||
else:
|
||||
threshold = 0.15
|
||||
result = bool(red_ratio > threshold)
|
||||
|
||||
if return_info:
|
||||
reason_value: Optional[str] = (
|
||||
None if result else "red_ratio_below_threshold"
|
||||
)
|
||||
return result, {
|
||||
"method": "pixel_detection",
|
||||
"red_ratio": float(red_ratio),
|
||||
"effective_threshold": threshold,
|
||||
"reason": reason_value,
|
||||
}
|
||||
return result
|
||||
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "pixel_detection",
|
||||
"red_ratio": 0.0,
|
||||
"reason": f"exception: {str(e)}",
|
||||
}
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def detect_lucky_draw_result_popup(
|
||||
pic_rgb: Image.Image, red_ratio_threshold: float = 0.8, return_info: bool = False
|
||||
) -> bool | tuple[bool, dict]:
|
||||
"""检测抽奖结果弹窗:检测指定区域的红色占比("我知道了"按钮区域)。
|
||||
|
||||
使用基准 1080x2400 坐标的检测区域:
|
||||
- 左上: (181, 1261)
|
||||
- 右下: (890, 1389)
|
||||
"""
|
||||
try:
|
||||
width, height = pic_rgb.size
|
||||
scale_x = width / 1080.0
|
||||
scale_y = height / 2400.0
|
||||
|
||||
x1 = int(181 * scale_x)
|
||||
y1 = int(1261 * scale_y)
|
||||
x2 = int(890 * scale_x)
|
||||
y2 = int(1389 * scale_y)
|
||||
|
||||
# 边界与顺序
|
||||
x1, x2 = max(0, min(x1, width)), max(0, min(x2, width))
|
||||
y1, y2 = max(0, min(y1, height)), max(0, min(y2, height))
|
||||
if x1 > x2:
|
||||
x1, x2 = x2, x1
|
||||
if y1 > y2:
|
||||
y1, y2 = y2, y1
|
||||
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
return False
|
||||
|
||||
# 双截图记录:保存实时操作截图(像素检测区域)
|
||||
detect_roi = None
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
detect_roi, operation_type="pixel_detect"
|
||||
)
|
||||
|
||||
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb, # 使用全屏截图
|
||||
operation_type="pixel_detect",
|
||||
picname="lucky_draw_result",
|
||||
step="before_detect",
|
||||
coords=(x1, y1, x2, y2), # 标注识别区域
|
||||
extra_info={
|
||||
"threshold": red_ratio_threshold,
|
||||
"region_size": f"{x2-x1}x{y2-y1}",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.info(
|
||||
"[调试图像] 像素检测前保存: %s, threshold=%s",
|
||||
debug_path,
|
||||
red_ratio_threshold,
|
||||
)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
red_count = 0
|
||||
total_samples = 0
|
||||
step_x = max(1, (x2 - x1) // 10)
|
||||
step_y = max(1, (y2 - y1) // 10)
|
||||
|
||||
for y in range(y1, y2, step_y):
|
||||
for x in range(x1, x2, step_x):
|
||||
try:
|
||||
r, g, b = pic_rgb.getpixel((x, y))
|
||||
total_samples += 1
|
||||
# 根据实际检测结果:R: 245-255, G: 44-255, B: 85-255
|
||||
# 红色按钮检测:R >= 245 且 R 明显大于 G 和 B
|
||||
if r >= 245 and r <= 255 and (r - g) >= 50 and (r - b) >= 50:
|
||||
red_count += 1
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
continue
|
||||
|
||||
if total_samples == 0:
|
||||
return False
|
||||
|
||||
red_ratio = red_count / total_samples
|
||||
result = red_ratio >= red_ratio_threshold
|
||||
|
||||
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
if result:
|
||||
# 检测成功
|
||||
if detect_roi is None:
|
||||
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
detect_roi, operation_type="pixel_detect"
|
||||
)
|
||||
|
||||
# 无论成功失败都保存debug截图
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb, # 使用全屏截图
|
||||
operation_type="pixel_detect",
|
||||
picname="lucky_draw_result",
|
||||
step="detected" if result else "not_detected",
|
||||
coords=(x1, y1, x2, y2), # 标注识别区域
|
||||
extra_info={
|
||||
"red_ratio": round(red_ratio, 4),
|
||||
"red_count": red_count,
|
||||
"total_samples": total_samples,
|
||||
"threshold": red_ratio_threshold,
|
||||
"result": "success" if result else "failed",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.info(
|
||||
"[调试图像] 抽奖结果检测保存: %s, red_ratio=%.4f, threshold=%s, score=%.4f",
|
||||
debug_path,
|
||||
red_ratio,
|
||||
red_ratio_threshold,
|
||||
red_ratio,
|
||||
)
|
||||
except Exception: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果请求详细信息,返回包含red_ratio的字典
|
||||
if return_info:
|
||||
reason_value: Optional[str] = (
|
||||
None if result else "red_ratio_below_threshold"
|
||||
)
|
||||
return result, {
|
||||
"method": "pixel_detect",
|
||||
"red_ratio": red_ratio,
|
||||
"red_count": red_count,
|
||||
"total_samples": total_samples,
|
||||
"effective_threshold": red_ratio_threshold,
|
||||
"reason": reason_value,
|
||||
}
|
||||
|
||||
return result
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
# pyright: reportGeneralTypeIssues=false
|
||||
# pyright: reportAttributeAccessIssue=false
|
||||
# pyright: reportMissingModuleSource=false
|
||||
# pyright: reportUnknownMemberType=false
|
||||
# pyright: reportUnknownVariableType=false
|
||||
# pylint: disable=no-member
|
||||
"""pixel.stage - 阶段诊断相关像素检测。
|
||||
|
||||
- detect_live_room_icons_by_pixel 直播间图标检测
|
||||
- detect_fudai_detail_page 福袋详情页识别
|
||||
- read_pixel_stage_state_from_screenshot 综合多种检测,返回阶段状态
|
||||
"""
|
||||
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any, Optional
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from ._common import _safe_open_screenshot_rgb
|
||||
|
||||
|
||||
def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
|
||||
"""通过像素检测多边形区域内的白色像素,判断是否在直播间。
|
||||
|
||||
检测指定多边形区域内的白色像素比例,基于1080x2400分辨率:
|
||||
- 多边形顶点坐标(12个点):
|
||||
(1002,172), (999,174), (1011,186), (999,199), (1002,202), (1013,190),
|
||||
(1025,201), (1028,198), (1017,187), (1028,174), (1025,172), (1014,184)
|
||||
- 白色像素比例 >= 0.8 则认为在直播间内
|
||||
|
||||
返回:
|
||||
(detected, confidence) 其中 confidence 为白色像素比例(0.0~1.0)
|
||||
"""
|
||||
try:
|
||||
from PIL import ImageDraw
|
||||
import numpy as np
|
||||
|
||||
width, height = pic_rgb.size
|
||||
# 缩放坐标到实际尺寸(基于1080x2400)
|
||||
scale_x = width / 1080.0
|
||||
scale_y = height / 2400.0
|
||||
|
||||
# 多边形顶点坐标(基于1080x2400基准分辨率)
|
||||
polygon_base_points = [
|
||||
(1002, 172),
|
||||
(999, 174),
|
||||
(1011, 186),
|
||||
(999, 199),
|
||||
(1002, 202),
|
||||
(1013, 190),
|
||||
(1025, 201),
|
||||
(1028, 198),
|
||||
(1017, 187),
|
||||
(1028, 174),
|
||||
(1025, 172),
|
||||
(1014, 184),
|
||||
]
|
||||
|
||||
# 缩放多边形坐标到实际截图尺寸
|
||||
polygon_points = [
|
||||
(int(x * scale_x), int(y * scale_y)) for x, y in polygon_base_points
|
||||
]
|
||||
|
||||
# 创建多边形mask
|
||||
mask = Image.new("L", (width, height), 0)
|
||||
draw = ImageDraw.Draw(mask)
|
||||
|
||||
# 绘制多边形(填充为白色)
|
||||
draw.polygon(polygon_points, fill=255)
|
||||
|
||||
# 将mask转换为numpy数组
|
||||
mask_array = np.asarray(mask)
|
||||
|
||||
# 获取原始图像的像素数据
|
||||
img_array = np.asarray(pic_rgb)
|
||||
|
||||
# 计算多边形内部的总像素数
|
||||
total_pixels = np.sum(mask_array > 0)
|
||||
|
||||
if total_pixels == 0:
|
||||
return False, 0.0
|
||||
|
||||
# 计算多边形内部的白色像素(RGB值都>=240)——使用 numpy 向量化计算以加速
|
||||
# mask_array 为 uint8,mask_bool 为布尔数组
|
||||
mask_bool = mask_array > 0
|
||||
# 将 img_array 转为 numpy 数组并选择掩膜区域内的像素,shape -> (N, 3)
|
||||
masked_pixels = img_array[mask_bool]
|
||||
if masked_pixels.size == 0:
|
||||
white_count = 0
|
||||
else:
|
||||
# 检查 RGB 三通道是否都 >= 240
|
||||
white_flags = (
|
||||
(masked_pixels[:, 0] >= 240)
|
||||
& (masked_pixels[:, 1] >= 240)
|
||||
& (masked_pixels[:, 2] >= 240)
|
||||
)
|
||||
white_count = int(np.count_nonzero(white_flags))
|
||||
|
||||
white_ratio = white_count / total_pixels if total_pixels > 0 else 0.0
|
||||
|
||||
# 白色像素比例 >= 0.8 则认为在直播间内
|
||||
detected = white_ratio >= 0.8
|
||||
confidence = white_ratio # 置信度就是白色比例
|
||||
|
||||
# 计算多边形边界框(用于调试图像)
|
||||
if polygon_points:
|
||||
x_coords = [p[0] for p in polygon_points]
|
||||
y_coords = [p[1] for p in polygon_points]
|
||||
x1 = max(0, min(x_coords))
|
||||
y1 = max(0, min(y_coords))
|
||||
x2 = min(width, max(x_coords))
|
||||
y2 = min(height, max(y_coords))
|
||||
else:
|
||||
x1, y1, x2, y2 = 0, 0, 0, 0
|
||||
|
||||
# 保存调试图像(检测结果)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb, # 使用全屏截图
|
||||
operation_type="pixel_detect",
|
||||
picname="live_room_icons",
|
||||
step="detected" if detected else "not_detected",
|
||||
coords=(x1, y1, x2, y2), # 标注识别区域边界框
|
||||
extra_info={
|
||||
"white_ratio": round(white_ratio, 4),
|
||||
"white_count": white_count,
|
||||
"total_pixels": total_pixels,
|
||||
"confidence": round(confidence, 4),
|
||||
"threshold": 0.8,
|
||||
"result": "success" if detected else "failed",
|
||||
"polygon_points": len(polygon_points),
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.info(
|
||||
"[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, white_count=%d, total_pixels=%d, confidence=%.4f, result=%s",
|
||||
debug_path,
|
||||
white_ratio,
|
||||
white_count,
|
||||
total_pixels,
|
||||
confidence,
|
||||
"success" if detected else "failed",
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
return bool(detected), float(confidence)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
return False, 0.0
|
||||
|
||||
|
||||
|
||||
|
||||
def detect_fudai_detail_page(
|
||||
_pic_rgb: Image.Image,
|
||||
_resolution_ratio_x: int = 1080,
|
||||
_resolution_ratio_y: int = 2400,
|
||||
_y_pianyi: int = 0,
|
||||
_template_threshold: float = 0.7,
|
||||
return_info: bool = False,
|
||||
analyser: Any = None,
|
||||
) -> bool | tuple[bool, dict]:
|
||||
"""检测是否处于福袋详情页。
|
||||
|
||||
检测策略:任务数量检测
|
||||
1. 通过检测任务数量来判断是否在福袋详情页
|
||||
2. 如果任务数量 <= 0,则认为不在福袋详情页
|
||||
3. 如果任务数量 >= 1,则认为在福袋详情页,并返回任务数量
|
||||
|
||||
参数:
|
||||
pic_rgb: RGB格式的整屏截图(保留用于兼容性,实际不使用)
|
||||
resolution_ratio_x: 分辨率X比例(默认1080,保留用于兼容性)
|
||||
resolution_ratio_y: 分辨率Y比例(默认2400,保留用于兼容性)
|
||||
y_pianyi: Y轴偏移(默认0,保留用于兼容性)
|
||||
template_threshold: 模板匹配阈值(保留用于兼容性,不再使用)
|
||||
return_info: 是否返回详细信息(包含任务数量)
|
||||
analyser: 分析器对象(必需,用于任务数量检测)
|
||||
|
||||
返回:
|
||||
bool: 是否检测到福袋详情页(return_info=False时)
|
||||
tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时)
|
||||
详细信息包含:
|
||||
- method: 检测方法("task_count")
|
||||
- task_count: 任务数量(0/1/2/3)
|
||||
"""
|
||||
# ---------- 任务数量检测 ----------
|
||||
if analyser is None:
|
||||
# analyser 参数必需
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "task_count",
|
||||
"task_count": 0,
|
||||
"reason": "analyser_required",
|
||||
}
|
||||
return False
|
||||
|
||||
try:
|
||||
from .douyin_detection import check_detail_height
|
||||
|
||||
# 执行任务数量检测
|
||||
task_count = int(check_detail_height(analyser) or 0)
|
||||
|
||||
# 判断是否在福袋详情页
|
||||
# 如果任务数量 <= 0,则认为不在福袋详情页
|
||||
# 如果任务数量 >= 1,则认为在福袋详情页
|
||||
is_in_detail = task_count >= 1
|
||||
|
||||
if return_info:
|
||||
return is_in_detail, {
|
||||
"method": "task_count",
|
||||
"task_count": task_count,
|
||||
}
|
||||
return is_in_detail
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
# 检测异常
|
||||
if return_info:
|
||||
return False, {
|
||||
"method": "task_count",
|
||||
"task_count": 0,
|
||||
"reason": f"detection_exception: {str(e)}",
|
||||
}
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def read_pixel_stage_state_from_screenshot(
|
||||
pic_path: str,
|
||||
resolution_ratio_x: int = 1080,
|
||||
resolution_ratio_y: int = 2400,
|
||||
y_pianyi: int = 0,
|
||||
lucky_draw_red_ratio_threshold: float = 0.8,
|
||||
fudai_template_threshold: float = 0.7,
|
||||
return_details: bool = False,
|
||||
analyser: Any = None,
|
||||
) -> dict[str, bool] | tuple[dict[str, bool], dict[str, dict]]:
|
||||
"""从 screenshot.png 读取"阶段诊断"需要的多区域像素特征(不调用 OCR)。
|
||||
|
||||
使用多线程并行执行所有检测函数以提高性能。
|
||||
|
||||
参数:
|
||||
pic_path: 截图路径
|
||||
resolution_ratio_x: 分辨率X比例(默认1080)
|
||||
resolution_ratio_y: 分辨率Y比例(默认2400)
|
||||
y_pianyi: Y轴偏移(默认0)
|
||||
lucky_draw_red_ratio_threshold: 抽奖结果红色比例阈值(默认0.8)
|
||||
fudai_template_threshold: 福袋详情模板匹配阈值(默认0.7)
|
||||
return_details: 是否返回每个检测步骤的详细信息(包括分数)
|
||||
|
||||
返回:
|
||||
dict[str, bool]: 检测结果(return_details=False时)
|
||||
tuple[dict[str, bool], dict[str, dict]]: (检测结果, 详细信息)(return_details=True时)
|
||||
"""
|
||||
state: dict[str, bool] = {
|
||||
"has_coupon_bg": False,
|
||||
"has_redpacket_bg": False,
|
||||
"has_lucky_draw_result": False,
|
||||
"has_attend_button_red": False,
|
||||
"has_fansclub_join_red": False,
|
||||
"has_fudai_detail": False,
|
||||
"has_live_room_pixel": False, # 直播间图标像素检测(多边形区域白色像素检测)
|
||||
}
|
||||
details: dict[str, dict] = {}
|
||||
|
||||
pic_rgb = _safe_open_screenshot_rgb(pic_path)
|
||||
if pic_rgb is None:
|
||||
if return_details:
|
||||
return state, details
|
||||
return state
|
||||
|
||||
# 并行执行所有检测函数
|
||||
# 注意:优惠券检测需要额外参数,使用lambda包装
|
||||
# 注意:福袋详情检测使用任务数量检测,需要analyser参数
|
||||
# 从analyser读取阈值(如果可用)
|
||||
coupon_threshold = None
|
||||
attend_button_threshold = None
|
||||
fansclub_threshold = None
|
||||
redpacket_threshold = None
|
||||
live_room_pixel_threshold = None
|
||||
if analyser is not None:
|
||||
try:
|
||||
coupon_threshold = float(
|
||||
getattr(analyser, "coupon_template_match_threshold", None) or 0.75
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
try:
|
||||
attend_button_threshold = float(
|
||||
getattr(analyser, "attend_button_red_ratio_threshold", None) or 0.25
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
try:
|
||||
fansclub_threshold = float(
|
||||
getattr(analyser, "fansclub_join_red_ratio_threshold", None) or 0.25
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
try:
|
||||
redpacket_threshold = float(
|
||||
getattr(analyser, "shopping_redpacket_red_ratio_threshold", None)
|
||||
or 0.15
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
try:
|
||||
live_room_pixel_threshold = float(
|
||||
getattr(analyser, "live_room_match_threshold", None) or 0.8
|
||||
)
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
pass
|
||||
|
||||
# 定义直播间图标像素检测包装函数
|
||||
def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]:
|
||||
"""直播间图标像素检测包装函数,返回 (bool, dict) 格式"""
|
||||
try:
|
||||
detected, confidence = detect_live_room_icons_by_pixel(pic)
|
||||
threshold = live_room_pixel_threshold or 0.8
|
||||
is_detected = detected and confidence >= threshold
|
||||
return is_detected, {
|
||||
"method": "pixel_detection",
|
||||
"confidence": confidence,
|
||||
"effective_threshold": threshold,
|
||||
}
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
return False, {"method": "pixel_detection", "error": str(e)}
|
||||
|
||||
# 模板匹配已删除,只使用像素检测
|
||||
|
||||
detection_tasks = {
|
||||
"has_coupon_bg": lambda pic: detect_coupon_popup_background(
|
||||
pic,
|
||||
return_info=True,
|
||||
template_threshold=coupon_threshold,
|
||||
analyser=analyser,
|
||||
),
|
||||
"has_redpacket_bg": lambda pic: detect_redpacket_popup_background(
|
||||
pic,
|
||||
return_info=True,
|
||||
red_ratio_threshold=redpacket_threshold,
|
||||
analyser=analyser,
|
||||
),
|
||||
"has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup(
|
||||
pic, lucky_draw_red_ratio_threshold, return_info=True
|
||||
),
|
||||
"has_attend_button_red": lambda pic: detect_attend_button_red_area(
|
||||
pic,
|
||||
return_info=True,
|
||||
red_ratio_threshold=attend_button_threshold,
|
||||
analyser=analyser,
|
||||
),
|
||||
"has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area(
|
||||
pic,
|
||||
return_info=True,
|
||||
red_ratio_threshold=fansclub_threshold,
|
||||
analyser=analyser,
|
||||
),
|
||||
"has_fudai_detail": lambda pic: detect_fudai_detail_page(
|
||||
pic,
|
||||
resolution_ratio_x,
|
||||
resolution_ratio_y,
|
||||
y_pianyi,
|
||||
fudai_template_threshold,
|
||||
return_info=True,
|
||||
analyser=analyser,
|
||||
),
|
||||
"has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测(多边形区域白色像素检测)
|
||||
}
|
||||
|
||||
# 使用线程池并行执行检测(增加线程数以支持直播间图标检测)
|
||||
with ThreadPoolExecutor(max_workers=8) as executor:
|
||||
# 提交所有任务,并记录开始时间
|
||||
import time
|
||||
|
||||
future_to_key = {}
|
||||
for key, detect_func in detection_tasks.items():
|
||||
start_time = time.time()
|
||||
future = executor.submit(detect_func, pic_rgb)
|
||||
future_to_key[future] = (key, start_time)
|
||||
|
||||
# 收集结果
|
||||
for future in as_completed(future_to_key):
|
||||
key, start_time = future_to_key[future]
|
||||
elapsed_ms = (time.time() - start_time) * 1000
|
||||
try:
|
||||
result = future.result()
|
||||
|
||||
# 处理结果
|
||||
if isinstance(result, tuple):
|
||||
# 检测函数返回 (bool, dict) 格式
|
||||
is_detected, info = result
|
||||
state[key] = bool(is_detected)
|
||||
if return_details:
|
||||
details[key] = {
|
||||
"detected": bool(is_detected),
|
||||
"method": info.get("method", "unknown"),
|
||||
"template_score": info.get("template_score"),
|
||||
"confidence": info.get(
|
||||
"confidence"
|
||||
), # 添加confidence支持(用于像素检测)
|
||||
"task_count": info.get("task_count"), # 添加task_count支持
|
||||
"red_ratio": info.get("red_ratio"), # 添加red_ratio支持
|
||||
"effective_threshold": info.get("effective_threshold"),
|
||||
"reason": info.get("reason"),
|
||||
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
|
||||
}
|
||||
else:
|
||||
# 其他检测返回 bool(不应该发生,因为所有检测都支持return_info)
|
||||
state[key] = bool(result)
|
||||
if return_details:
|
||||
details[key] = {
|
||||
"detected": bool(result),
|
||||
"method": "unknown",
|
||||
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
|
||||
}
|
||||
except Exception as e: # type: ignore[general-exception]
|
||||
# 如果某个检测失败,保持默认值 False
|
||||
state[key] = False
|
||||
if return_details:
|
||||
details[key] = {
|
||||
"detected": False,
|
||||
"error": str(e),
|
||||
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
|
||||
}
|
||||
|
||||
if return_details:
|
||||
return state, details
|
||||
return state
|
||||
+53
-1548
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,496 @@
|
||||
"""attend_choujiang 分支辅助函数
|
||||
|
||||
从 douyin/fudai/core/fudai_attend.py:attend_choujiang 中提取的相对独立的早返回分支。
|
||||
每个 helper 处理一个 button_text 命中情况,返回 True/False(与原代码 return 值一致)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def resolve_attend_button_text(analyser):
|
||||
"""从 analyser 缓存解析"参与按钮文本"。
|
||||
|
||||
优先级:
|
||||
1. 已有的 _fudai_button_text + _fudai_button_status(并行 OCR 设置)
|
||||
2. 缺失则从 button_text_raw / 映射表中查找候选并推断状态
|
||||
3. 检查 OCR 时间戳:5 秒内有效 → 直接使用;超时但同房间 → 复用
|
||||
|
||||
返回 attend_button_text(若不可用则返回空字符串)。
|
||||
"""
|
||||
button_status = getattr(analyser, "_fudai_button_status", None)
|
||||
button_text = getattr(analyser, "_fudai_button_text", "")
|
||||
|
||||
try:
|
||||
current_room_pos = int(getattr(analyser, "room_pos", 0) or 0)
|
||||
except Exception:
|
||||
current_room_pos = 0
|
||||
try:
|
||||
cached_room_pos = int(getattr(analyser, "_fudai_button_room_pos", 0) or 0)
|
||||
except Exception:
|
||||
cached_room_pos = 0
|
||||
|
||||
# 如果并行 OCR 属性缺失或不完整,尝试从其它缓存字段复用识别结果
|
||||
if not button_text or not button_status:
|
||||
try:
|
||||
candidate = getattr(analyser, "button_text_raw", None)
|
||||
if not candidate:
|
||||
try:
|
||||
room_pos = int(getattr(analyser, "room_pos", 0) or 0)
|
||||
room_map = getattr(analyser, "_room_pos_to_title_map", {}) or {}
|
||||
if room_map and room_pos in room_map:
|
||||
info = room_map.get(room_pos) or {}
|
||||
if isinstance(info, dict):
|
||||
fudai_detail = info.get("fudai_detail") or {}
|
||||
candidate = (
|
||||
fudai_detail.get("button_text")
|
||||
or fudai_detail.get("button_text_raw")
|
||||
or None
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if candidate:
|
||||
bt = str(candidate or "").strip()
|
||||
if bt:
|
||||
# 推断按钮状态(与并行 OCR 的判断逻辑保持一致)
|
||||
if "参与成功" in bt or "等待开奖" in bt:
|
||||
bs = "已参与"
|
||||
elif "加入粉丝团" in bt or "粉丝团" in bt:
|
||||
bs = "需要加入粉丝团"
|
||||
elif "评论" in bt or "发表评论" in bt or "一键发表评论" in bt:
|
||||
bs = "需要评论"
|
||||
elif "还需看播" in bt or "开始观看" in bt:
|
||||
bs = "需要观看"
|
||||
elif "未达成" in bt:
|
||||
bs = "未达成要求"
|
||||
elif "参与抽奖" in bt or "参与" in bt:
|
||||
bs = "可以参与"
|
||||
else:
|
||||
bs = "未知状态"
|
||||
|
||||
try:
|
||||
analyser._fudai_button_status = bs
|
||||
analyser._fudai_button_text = bt
|
||||
analyser._fudai_button_ocr_time = time.time()
|
||||
try:
|
||||
analyser._fudai_button_room_pos = int(
|
||||
getattr(analyser, "room_pos", 0) or 0
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"复用缓存的并行OCR文本作为按钮状态",
|
||||
button_text=(bt[:100] if bt else ""),
|
||||
button_status=bs,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
button_text = bt
|
||||
button_status = bs
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 使用并行 OCR 识别的按钮状态(如果可用且在有效期内)
|
||||
attend_button_text = ""
|
||||
try:
|
||||
button_ocr_time = getattr(analyser, "_fudai_button_ocr_time", 0)
|
||||
current_time = time.time()
|
||||
if button_text and button_status and current_time - button_ocr_time < 5.0:
|
||||
attend_button_text = button_text
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"使用并行OCR识别的按钮状态",
|
||||
button_text=(
|
||||
attend_button_text[:100] if attend_button_text else ""
|
||||
),
|
||||
button_status=button_status,
|
||||
)
|
||||
elif button_text and button_status:
|
||||
same_room = (
|
||||
not current_room_pos
|
||||
or not cached_room_pos
|
||||
or current_room_pos == cached_room_pos
|
||||
)
|
||||
if same_room:
|
||||
attend_button_text = button_text
|
||||
try:
|
||||
age_ms = int(
|
||||
max(0.0, current_time - float(button_ocr_time)) * 1000
|
||||
)
|
||||
except Exception:
|
||||
age_ms = None
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"使用并行OCR缓存的按钮状态(超时复用)",
|
||||
button_text=(
|
||||
attend_button_text[:100] if attend_button_text else ""
|
||||
),
|
||||
button_status=button_status,
|
||||
age_ms=age_ms,
|
||||
room_pos=current_room_pos,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return attend_button_text
|
||||
|
||||
|
||||
def handle_simple_click(analyser, action_label: str, log_message: str) -> bool:
|
||||
"""通用"点击 543,2070 + 简单日志"分支模板,覆盖"开始观看"/"参与"等无额外副作用的点击。
|
||||
|
||||
流程:click(543, 2070) → 记录日志 → 返回 True。
|
||||
"""
|
||||
analyser.click(543, 2070)
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
log_message,
|
||||
action=action_label,
|
||||
base_x=543,
|
||||
base_y=2070,
|
||||
region="(306,2030)-(780,2110)",
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def handle_attend_already_success(analyser, attend_button_text: str) -> bool:
|
||||
"""处理"参与成功/已参与"分支:记录、设置等待开奖标志、关闭详情。返回 True。"""
|
||||
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
|
||||
|
||||
future_ts = 0.0
|
||||
try:
|
||||
future_ts = float(getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0)
|
||||
except Exception:
|
||||
future_ts = 0.0
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="success",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
future_ts=int(future_ts) if future_ts else None,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._last_successful_attend_ts = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
future_ts = 0.0
|
||||
try:
|
||||
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
|
||||
if not future_ts:
|
||||
try:
|
||||
from douyin.fudai import douyin_fudai_core
|
||||
|
||||
content, time_text, participants, copies, prize_value_yuan = (
|
||||
douyin_fudai_core.get_fudai_contain(analyser, renwu=1)
|
||||
)
|
||||
try:
|
||||
res = analyser.operation.check_countdown(time_text)
|
||||
if isinstance(res, tuple) and len(res) == 2:
|
||||
_, parsed_future = res
|
||||
future_ts = float(parsed_future or 0.0)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
if future_ts > 0:
|
||||
participated_fudai_ts = getattr(
|
||||
analyser, "_participated_fudai_future_ts", set()
|
||||
)
|
||||
if not isinstance(participated_fudai_ts, set):
|
||||
participated_fudai_ts = set()
|
||||
participated_fudai_ts.add(future_ts)
|
||||
analyser._participated_fudai_future_ts = participated_fudai_ts
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"记录已参与福袋",
|
||||
future_ts=future_ts,
|
||||
total_participated=len(participated_fudai_ts),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if future_ts > 0:
|
||||
try:
|
||||
current_time = time.time()
|
||||
remain_seconds = max(0, future_ts - current_time)
|
||||
if remain_seconds > 0:
|
||||
analyser._waiting_for_lottery_result = True
|
||||
analyser._lottery_result_expected_ts = future_ts
|
||||
analyser._lottery_wait_start_ts = current_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"参与成功,设置等待开奖标志",
|
||||
remain_seconds=int(remain_seconds),
|
||||
future_ts=int(future_ts),
|
||||
lottery_result_expected_ts=int(
|
||||
analyser._lottery_result_expected_ts
|
||||
),
|
||||
)
|
||||
else:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"参与成功,但倒计时已过期,不设置等待标志",
|
||||
future_ts=int(future_ts),
|
||||
remain_seconds=int(remain_seconds),
|
||||
)
|
||||
except Exception as e:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"设置开奖等待状态时出错",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
|
||||
try:
|
||||
analyser._detail_closed_by_attend = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser.click(500, 470)
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return True
|
||||
|
||||
|
||||
def handle_activity_ended(analyser) -> bool:
|
||||
"""处理"活动已结束/福袋超时"分支:按返回键退出详情。返回 False。"""
|
||||
analyser.last_attend_fail_reason = "activity_ended"
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"活动已结束/福袋超时:按返回键退出详情",
|
||||
result="activity_ended",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="fail",
|
||||
reason="activity_ended",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.click(500, 470)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def handle_no_parallel_ocr(analyser) -> bool:
|
||||
"""处理"并行OCR结果不可用"分支:放弃参与并关闭详情。返回 False。"""
|
||||
analyser.last_attend_fail_reason = "no_parallel_ocr_result"
|
||||
analyser._log_kv("参与", "并行OCR结果不可用,放弃参与", result="不参与")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="fail",
|
||||
reason="no_parallel_ocr_result",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.click(500, 470)
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return False
|
||||
|
||||
|
||||
def handle_condition_not_met(analyser) -> bool:
|
||||
"""处理"不满足参与条件"分支:放弃参与并关闭详情。返回 False。"""
|
||||
analyser.last_attend_fail_reason = "condition_not_met"
|
||||
analyser._log_kv("参与", "不满足参与条件,直接放弃", result="不满足条件")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="fail",
|
||||
reason="condition_not_met",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.click(500, 470)
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return False
|
||||
|
||||
|
||||
def handle_simple_fail(
|
||||
analyser, log_message: str, log_result: str, fail_reason: str
|
||||
) -> bool:
|
||||
"""通用"简单失败 + 关闭详情"模板,覆盖 watch_required / cannot_participate / watch_duration_insufficient 等。
|
||||
|
||||
流程:
|
||||
1. 设置 last_attend_fail_reason = fail_reason
|
||||
2. 记录"参与"日志(log_message + result=log_result)
|
||||
3. 记录 metric: fudai_attend / fail / reason=fail_reason
|
||||
4. click(500, 470) 关闭详情
|
||||
5. 返回 False
|
||||
"""
|
||||
try:
|
||||
analyser.last_attend_fail_reason = fail_reason
|
||||
except Exception:
|
||||
pass
|
||||
analyser._log_kv("参与", log_message, result=log_result)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="fail",
|
||||
reason=fail_reason,
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.click(500, 470)
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return False
|
||||
|
||||
|
||||
def handle_attend_click(analyser, mode: str) -> bool:
|
||||
"""处理"评论"或"参与抽奖"分支:点击参与按钮、记录 metric。返回 True。
|
||||
|
||||
"参与抽奖"模式下还会:
|
||||
- 设置 _skip_stage_diagnosis_and_find_fudai 标志
|
||||
- 写 debug log(开始设置等待开奖标志)
|
||||
- 设置 _waiting_for_lottery_result / _lottery_result_expected_ts
|
||||
- 写 debug log(成功设置等待开奖标志)
|
||||
"""
|
||||
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
|
||||
# 区域中心 X = 543, Y = 2070
|
||||
analyser.click(543, 2070)
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与抽奖(基于截图优化坐标)",
|
||||
action="点击参与",
|
||||
mode=mode,
|
||||
base_x=543,
|
||||
base_y=2070,
|
||||
region="(306,2030)-(780,2110)",
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="attempt",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
mode=mode,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if mode != "普通":
|
||||
# 评论分支:直接返回,不设置等待开奖标志
|
||||
return True
|
||||
|
||||
# 参与抽奖分支:设置标志 + 等待开奖
|
||||
try:
|
||||
analyser._skip_stage_diagnosis_and_find_fudai = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
import json as _json
|
||||
import time as _time
|
||||
from douyin.core.path_config import get_debug_log_path
|
||||
|
||||
current_ts_debug = int(_time.time() * 1000)
|
||||
try:
|
||||
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
|
||||
f.write(
|
||||
_json.dumps(
|
||||
{
|
||||
"id": f"log_{current_ts_debug}_set_countdown_start",
|
||||
"timestamp": current_ts_debug,
|
||||
"location": "fudai_attend_branches.py:handle_attend_click",
|
||||
"message": "开始设置等待开奖标志",
|
||||
"data": {
|
||||
"future_ts": getattr(
|
||||
analyser, "_current_fudai_future_ts", 0.0
|
||||
)
|
||||
},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "countdown_debug_run1",
|
||||
"hypothesisId": "countdown_hyp2",
|
||||
}
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
|
||||
if future_ts > 0:
|
||||
current_time = _time.time()
|
||||
remain_seconds = int(future_ts - current_time)
|
||||
if remain_seconds > 0:
|
||||
analyser._waiting_for_lottery_result = True
|
||||
analyser._lottery_result_expected_ts = future_ts
|
||||
analyser._lottery_wait_start_ts = current_time
|
||||
|
||||
try:
|
||||
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
|
||||
f.write(
|
||||
_json.dumps(
|
||||
{
|
||||
"id": f"log_{current_ts_debug}_countdown_set",
|
||||
"timestamp": current_ts_debug,
|
||||
"location": "fudai_attend_branches.py:handle_attend_click",
|
||||
"message": "成功设置等待开奖标志",
|
||||
"data": {
|
||||
"waiting_for_lottery_result": analyser._waiting_for_lottery_result,
|
||||
"lottery_result_expected_ts": analyser._lottery_result_expected_ts,
|
||||
"future_ts": future_ts,
|
||||
"current_time": current_time,
|
||||
"remain_seconds": remain_seconds,
|
||||
},
|
||||
"sessionId": "debug-session",
|
||||
"runId": "countdown_debug_run1",
|
||||
"hypothesisId": "countdown_hyp2",
|
||||
}
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与抽奖后,设置等待开奖标志",
|
||||
future_ts=int(future_ts),
|
||||
remain_seconds=remain_seconds,
|
||||
expected_result_ts=int(analyser._lottery_result_expected_ts),
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与抽奖后,设置等待开奖标志时出错",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测",
|
||||
)
|
||||
return True
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,19 @@
|
||||
"""fudai_detail_orchestrator_pkg - 福袋详情读取子包。
|
||||
|
||||
原 douyin/fudai/core/fudai_detail_orchestrator.py 拆成 2 个子模块:
|
||||
|
||||
- read_once read_fudai_detail_once(单次识别)
|
||||
- read_with_retries read_fudai_detail_with_retries(带重试)
|
||||
|
||||
外部 import 路径不变:
|
||||
``from douyin.fudai.core.fudai_detail_orchestrator import read_fudai_detail_with_retries``
|
||||
仍可用(原文件改成 re-export shim)。
|
||||
"""
|
||||
|
||||
from .read_once import read_fudai_detail_once
|
||||
from .read_with_retries import read_fudai_detail_with_retries
|
||||
|
||||
__all__ = [
|
||||
"read_fudai_detail_once",
|
||||
"read_fudai_detail_with_retries",
|
||||
]
|
||||
@@ -0,0 +1,546 @@
|
||||
"""fudai_detail_orchestrator_pkg.read_once - 单次福袋详情识别。
|
||||
|
||||
read_fudai_detail_once:执行一次完整的 OCR 识别(任务数 / 内容 / 时间 / 价值 / 参与人数)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from douyin.fudai.douyin_fudai_core import get_fudai_contain
|
||||
from douyin.fudai.core.fudai_detail_validator import validate_fudai_detail
|
||||
|
||||
|
||||
def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
"""执行一次福袋详情识别(本地完整版实现)。
|
||||
|
||||
流程:
|
||||
1. 获取截图(任务数量检测和弹窗检测已在阶段检测中完成,不再重复检测);
|
||||
2. 从阶段检测结果中获取任务数量(_fudai_detail_task_count_from_stage);
|
||||
3. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值;
|
||||
4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。
|
||||
"""
|
||||
start_time = time.time()
|
||||
# 性能标记变量
|
||||
screenshot_reused = False
|
||||
screenshot_start = None
|
||||
screenshot_end = None
|
||||
ocr_start = None
|
||||
ocr_end = None
|
||||
wait_file_ms: Optional[float] = None
|
||||
image_load_ms: Optional[float] = None
|
||||
service_stop_ms: Optional[float] = None
|
||||
countdown_parse_ms: Optional[float] = None
|
||||
|
||||
def _log_perf(tag: str) -> None:
|
||||
try:
|
||||
total_ms = round((time.time() - start_time) * 1000, 1)
|
||||
screenshot_ms = None
|
||||
if screenshot_start is not None and screenshot_end is not None:
|
||||
screenshot_ms = round((screenshot_end - screenshot_start) * 1000, 1)
|
||||
ocr_ms = None
|
||||
if ocr_start is not None and ocr_end is not None:
|
||||
ocr_ms = round((ocr_end - ocr_start) * 1000, 1)
|
||||
analyser._log_kv(
|
||||
"性能",
|
||||
"福袋详情关键耗时(ms)",
|
||||
log_type="PERF",
|
||||
total_ms=total_ms,
|
||||
screenshot_ms=screenshot_ms,
|
||||
ocr_ms=ocr_ms,
|
||||
wait_file_ms=wait_file_ms,
|
||||
image_load_ms=image_load_ms,
|
||||
service_stop_ms=service_stop_ms,
|
||||
countdown_parse_ms=countdown_parse_ms,
|
||||
screenshot_reused=bool(screenshot_reused),
|
||||
tag=tag,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 步骤1:从阶段检测结果中获取任务数量(不需要截图,直接从阶段检测结果读取)
|
||||
# 任务数量已在阶段检测中检测并保存到 analyser._fudai_detail_task_count_from_stage
|
||||
task_count = 0
|
||||
try:
|
||||
task_count_from_stage = getattr(
|
||||
analyser, "_fudai_detail_task_count_from_stage", None
|
||||
)
|
||||
if task_count_from_stage is not None:
|
||||
task_count = int(task_count_from_stage or 0)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:从阶段检测获取任务数量(无需截图)",
|
||||
log_type="OP",
|
||||
task_count=task_count,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 如果阶段检测未保存任务数量,记录警告日志
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:警告:阶段检测未保存任务数量,使用默认值0",
|
||||
log_type="WARNING",
|
||||
可能原因="点击验证阶段检测未执行或像素检测失败",
|
||||
建议="检查阶段检测日志,确认触发原因和检测结果",
|
||||
task_count_from_stage=task_count_from_stage,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
pass
|
||||
# 使用默认值
|
||||
task_count = 0
|
||||
|
||||
# 注意:任务数量标志不由 read_fudai_detail_once 清除
|
||||
# 应该由调用方在完成所有相关处理后清除,避免影响后续逻辑
|
||||
# 保留此代码块以便将来需要时恢复
|
||||
# try:
|
||||
# analyser._fudai_detail_task_count_from_stage = None
|
||||
# try:
|
||||
# analyser._log_kv(
|
||||
# "福袋详情",
|
||||
# "read_fudai_detail_once:清除任务数量标志",
|
||||
# log_type="DEBUG",
|
||||
# )
|
||||
# except Exception:
|
||||
# pass
|
||||
# except Exception:
|
||||
# # 忽略异常,继续处理
|
||||
# pass
|
||||
|
||||
# 如果任务数量为0,说明不在福袋详情页(阶段检测应该已经过滤掉了,这里作为兜底)
|
||||
# 在获取截图之前就返回错误,避免不必要的截图
|
||||
if task_count <= 0:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:任务数量为0,不在福袋详情页,跳过截图和OCR",
|
||||
task_count=task_count,
|
||||
)
|
||||
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),
|
||||
log_type="OP",
|
||||
)
|
||||
_log_perf("taskcount_zero")
|
||||
return (
|
||||
"error",
|
||||
tup_err,
|
||||
{"reason": "not_in_fudai_detail", "task_count": task_count},
|
||||
)
|
||||
|
||||
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理
|
||||
if task_count not in (1, 2, 3):
|
||||
task_count = 2
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:获取任务数量异常,使用默认值",
|
||||
log_type="ERR",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 异常时使用默认值
|
||||
task_count = 2
|
||||
|
||||
# 步骤2:获取截图(仅用于后续OCR识别内容/倒计时/价值,不是为了获取任务数量)
|
||||
# 注意:此时后台截图服务已被停止,直接调用底层截图避免递归
|
||||
|
||||
# 检查是否可以复用阶段诊断时的截图
|
||||
screenshot_reused = False
|
||||
try:
|
||||
if getattr(analyser, "_screenshot_ready_for_ocr", False):
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
pic_path = os.path.join(
|
||||
os.path.dirname(__file__), "pic", "screenshot.png"
|
||||
)
|
||||
|
||||
if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024:
|
||||
analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用
|
||||
screenshot_reused = True
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:复用阶段诊断截图",
|
||||
log_type="SCREENSHOT",
|
||||
reason="stage_diagnosed_task_count_gt_zero",
|
||||
path=pic_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:无法复用阶段诊断截图(文件不可用)",
|
||||
log_type="SCREENSHOT",
|
||||
path=pic_path,
|
||||
size=(
|
||||
os.path.getsize(pic_path) if os.path.exists(pic_path) else 0
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 只有在不能复用截图时才进行新的截图
|
||||
if not screenshot_reused:
|
||||
try:
|
||||
screenshot_start = time.time()
|
||||
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
|
||||
|
||||
# 等待截图文件确实存在(最多等待3秒)
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
pic_path = os.path.join(
|
||||
os.path.dirname(__file__), "pic", "screenshot.png"
|
||||
)
|
||||
|
||||
wait_start = time.time()
|
||||
while time.time() - wait_start < 3.0:
|
||||
if os.path.exists(pic_path):
|
||||
file_size = os.path.getsize(pic_path)
|
||||
if file_size >= 1024: # 至少1KB
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
screenshot_end = time.time()
|
||||
wait_file_ms = round((screenshot_end - wait_start) * 1000, 1)
|
||||
|
||||
_log_perf("after_screenshot") # 移除:避免过多性能日志
|
||||
|
||||
except Exception:
|
||||
screenshot_end = time.time() if screenshot_start is not None else None
|
||||
pass
|
||||
|
||||
# 使用统一的截图路径配置
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
pic_rgb = None
|
||||
try:
|
||||
if os.path.exists(pic_path):
|
||||
_img0 = time.time()
|
||||
pic = Image.open(pic_path)
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
image_load_ms = round((time.time() - _img0) * 1000, 1)
|
||||
_log_perf("after_image_load") # 移除:避免过多性能日志
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if pic_rgb is None:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情", "read_fudai_detail_once:无法读取截图,跳过识别"
|
||||
)
|
||||
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完成(截图失败)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
_log_perf("screenshot_failed")
|
||||
return "error", tup_err, {"reason": "screenshot_failed"}
|
||||
|
||||
# 如果任务数不在(1,2,3)范围内,默认按2个任务处理
|
||||
if task_count not in (1, 2, 3):
|
||||
task_count = 2
|
||||
|
||||
# 识别福袋内容 / 倒计时 / 价值
|
||||
# 在OCR密集操作期间临时禁用截图服务,避免后台截图干扰
|
||||
_ocr_screenshot_service_disabled = False
|
||||
try:
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
|
||||
service = ScreenshotService.get_instance()
|
||||
if service.is_running():
|
||||
_svc0 = time.time()
|
||||
# 临时停止后台截图服务,避免在OCR过程中继续截图
|
||||
service.stop()
|
||||
_ocr_screenshot_service_disabled = True
|
||||
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()
|
||||
_log_perf("after_get_fudai_contain") # 移除:避免过多性能日志
|
||||
except Exception as e: # pyright: ignore[reportTooBroadExceptionType]
|
||||
# 出现异常时,记录详细错误和 traceback 并返回占位结果,便于排查
|
||||
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,
|
||||
)
|
||||
except Exception: # pyright: ignore[reportTooBroadExceptionType]
|
||||
# fallback: 将 traceback 写入统一错误日志
|
||||
try:
|
||||
from douyin.core 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
|
||||
except Exception: # pyright: ignore[reportTooBroadExceptionType]
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once 异常(无法格式化 traceback)",
|
||||
error=str(e),
|
||||
) # pyright: ignore[reportPrivateUsage]
|
||||
except Exception: # pyright: ignore[reportTooBroadExceptionType]
|
||||
pass
|
||||
now = time.time()
|
||||
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]
|
||||
except Exception: # pyright: ignore[reportTooBroadExceptionType]
|
||||
pass
|
||||
_log_perf("exception_in_get_fudai_contain")
|
||||
return "error", tup_err, {}
|
||||
# 由于已全局禁用流式截图,不再重新启动服务
|
||||
|
||||
# 检查是否检测到观看任务(通过 _is_watch_task_detected 标志)
|
||||
is_watch_task = False
|
||||
try:
|
||||
is_watch_task = bool(getattr(analyser, "_is_watch_task_detected", False))
|
||||
# 清除标志,避免影响后续调用
|
||||
if is_watch_task:
|
||||
try:
|
||||
analyser._is_watch_task_detected = (
|
||||
False # pyright: ignore[reportPrivateUsage]
|
||||
)
|
||||
except Exception: # pyright: ignore[reportTooBroadExceptionType]
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果检测到观看任务,返回 watch_task 状态
|
||||
if is_watch_task:
|
||||
try:
|
||||
analyser._log_kv( # pyright: ignore[reportPrivateUsage]
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:检测到'观看X分钟'任务,直接跳过",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
now = time.time()
|
||||
tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once完成(观看任务)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
) # pyright: ignore[reportPrivateUsage]
|
||||
return (
|
||||
"watch_task",
|
||||
tup_watch,
|
||||
{"reason": "watch_task_detected", "task_count": task_count},
|
||||
)
|
||||
|
||||
# 解析倒计时 -> (剩余秒数, 未来时间戳)
|
||||
countdown_start = time.time()
|
||||
countdown_end = countdown_start + 60.0
|
||||
total_seconds_from_ocr = None # 保存OCR识别到的原始秒数
|
||||
try:
|
||||
_cd0 = time.time()
|
||||
if time_text:
|
||||
res = analyser.operation.check_countdown(time_text)
|
||||
if isinstance(res, tuple) and len(res) == 2:
|
||||
total_seconds, future_ts = res
|
||||
try:
|
||||
total_seconds = int(total_seconds)
|
||||
total_seconds_from_ocr = total_seconds # 保存原始秒数
|
||||
except Exception:
|
||||
total_seconds = int(float(total_seconds or 0))
|
||||
total_seconds_from_ocr = total_seconds
|
||||
if total_seconds >= 0 and isinstance(future_ts, (int, float)):
|
||||
countdown_start = float(countdown_start)
|
||||
countdown_end = float(future_ts)
|
||||
countdown_parse_ms = round((time.time() - _cd0) * 1000, 1)
|
||||
# _log_perf("after_countdown_parse") # 移除:避免过多性能日志
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
detail_tuple = (
|
||||
content or "",
|
||||
time_text or "",
|
||||
int(participants or 0),
|
||||
int(copies or 0),
|
||||
float(prize_value_yuan or 0.0),
|
||||
(countdown_start, countdown_end, total_seconds_from_ocr), # 添加原始秒数
|
||||
)
|
||||
extra: Dict[str, Any] = {
|
||||
"task_count": task_count,
|
||||
}
|
||||
|
||||
# 获取直播间名字
|
||||
room_title = ""
|
||||
room_title_raw = ""
|
||||
try:
|
||||
room_title = str(getattr(analyser, "current_room_title", "") or "").strip()
|
||||
room_title_raw = str(
|
||||
getattr(analyser, "current_room_title_raw", "") or ""
|
||||
).strip()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 输出所有识别到的内容到运行日志和行为日志
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
# 格式化时间戳为可读格式
|
||||
countdown_start_str = ""
|
||||
countdown_end_str = ""
|
||||
if countdown_start and countdown_end:
|
||||
try:
|
||||
if countdown_start > 0:
|
||||
countdown_start_str = datetime.fromtimestamp(
|
||||
countdown_start
|
||||
).strftime("%Y-%m-%d %H:%M:%S")
|
||||
if countdown_end > 0:
|
||||
countdown_end_str = datetime.fromtimestamp(countdown_end).strftime(
|
||||
"%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 计算剩余秒数 - 优先使用OCR识别到的原始秒数,避免时间差导致的误差
|
||||
remain_seconds = 0
|
||||
if total_seconds_from_ocr is not None:
|
||||
# 使用OCR识别到的原始秒数,这更准确地反映了识别时刻的倒计时
|
||||
remain_seconds = max(0, total_seconds_from_ocr)
|
||||
elif countdown_end > countdown_start:
|
||||
# 兜底:使用时间戳计算(可能有误差)
|
||||
remain_seconds = int(max(0, countdown_end - time.time()))
|
||||
|
||||
# 输出完整的识别结果到运行日志
|
||||
content_preview = (content or "")[:60] if content else "未识别到"
|
||||
content_full = content or ""
|
||||
# 添加明确的"福袋内容:"格式输出,确保GUI能正确解析(即使内容为空也输出)
|
||||
analyser._log_kv(
|
||||
"福袋",
|
||||
f"福袋内容:{content_full[:200] if content_full else '未识别到'}", # 使用明确的"福袋内容:"格式,确保GUI能解析
|
||||
level="DEBUG",
|
||||
)
|
||||
except Exception as e:
|
||||
# 如果详细日志输出失败,至少输出基本信息
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once 结果(简化)",
|
||||
status="ok",
|
||||
content=content or "",
|
||||
time_text=time_text or "",
|
||||
participants=int(participants or 0),
|
||||
copies=int(copies or 0),
|
||||
prize_value_yuan=float(prize_value_yuan or 0.0),
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
# 计算各阶段耗时(可能为 None)
|
||||
screenshot_ms = (
|
||||
round((screenshot_end - screenshot_start) * 1000, 1)
|
||||
if screenshot_start is not None and screenshot_end is not None
|
||||
else None
|
||||
)
|
||||
ocr_ms = (
|
||||
round((ocr_end - ocr_start) * 1000, 1)
|
||||
if ocr_start is not None and ocr_end is not None
|
||||
else None
|
||||
)
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once完成(成功)",
|
||||
log_type="OP",
|
||||
level="INFO",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
screenshot_ms=screenshot_ms,
|
||||
ocr_ms=ocr_ms,
|
||||
wait_file_ms=wait_file_ms,
|
||||
image_load_ms=image_load_ms,
|
||||
service_stop_ms=service_stop_ms,
|
||||
countdown_parse_ms=countdown_parse_ms,
|
||||
screenshot_reused=bool(getattr(analyser, "_screenshot_ready_for_ocr", False)),
|
||||
content_preview=(content or "")[:60],
|
||||
prize_value_yuan=float(prize_value_yuan or 0.0),
|
||||
time_text=time_text or "",
|
||||
participants=int(participants or 0),
|
||||
copies=int(copies or 0),
|
||||
task_count=task_count,
|
||||
)
|
||||
_log_perf("success") # 只在最终成功时输出性能日志
|
||||
return "ok", detail_tuple, extra
|
||||
|
||||
|
||||
@@ -0,0 +1,513 @@
|
||||
"""fudai_detail_orchestrator_pkg.read_with_retries - 带重试的福袋详情识别。
|
||||
|
||||
read_fudai_detail_with_retries:包装 read_fudai_detail_once,按配置做多轮重试,
|
||||
解决 OCR 偶发误识别 / 内容尚未渲染完整的情况。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from douyin.fudai.douyin_fudai_core import get_fudai_contain
|
||||
from douyin.fudai.core.fudai_detail_validator import validate_fudai_detail
|
||||
|
||||
from .read_once import read_fudai_detail_once
|
||||
|
||||
|
||||
def read_fudai_detail_with_retries(
|
||||
analyser: Any,
|
||||
fudai_x: int,
|
||||
read_once_callback,
|
||||
close_detail_callback,
|
||||
ensure_open_callback,
|
||||
) -> Tuple:
|
||||
"""多次重试读取福袋详情,返回 6 字段 detail tuple。
|
||||
|
||||
与原版保持兼容:总是返回
|
||||
(content, time_text, participants, copies, prize_value_yuan, countdown_tuple)
|
||||
"""
|
||||
start_time = time.time()
|
||||
# 首次识别前等待,确保详情页完全加载
|
||||
# 如果优化查找器已经验证过详情页,可以减少等待时间
|
||||
already_verified = bool(getattr(analyser, "_fudai_detail_verified", False) or False)
|
||||
# 为了兼容之前对未使用参数的本地检测,我们在本地使用带下划线的别名
|
||||
_read_once_callback = read_once_callback
|
||||
_close_detail_callback = close_detail_callback
|
||||
_ensure_open_callback = ensure_open_callback
|
||||
if already_verified:
|
||||
# 已经验证过,只需要短暂等待确保界面稳定
|
||||
# 使用配置项,默认0.2秒(比之前的0.3秒更快)
|
||||
initial_wait = float(
|
||||
getattr(analyser, "fudai_detail_verified_wait_seconds", 0.2) or 0.2
|
||||
)
|
||||
if initial_wait < 0.1:
|
||||
initial_wait = 0.1 # 最小0.1秒
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:优化查找器已验证详情页,缩短等待时间",
|
||||
initial_wait=initial_wait,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 清除标志,避免影响后续调用
|
||||
try:
|
||||
analyser._fudai_detail_verified = False
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 未验证情况,使用配置项,默认0.5秒(优化:从0.8秒降低到0.5秒)
|
||||
initial_wait = float(
|
||||
getattr(analyser, "fudai_detail_initial_wait_seconds", 0.5) or 0.5
|
||||
)
|
||||
if initial_wait < 0.3:
|
||||
initial_wait = 0.3 # 最小0.3秒
|
||||
try:
|
||||
analyser.operation.delay(initial_wait)
|
||||
except Exception:
|
||||
time.sleep(initial_wait)
|
||||
|
||||
max_attempts = 2
|
||||
try:
|
||||
max_attempts = int(getattr(analyser, "fudai_detail_max_attempts", 2) or 2)
|
||||
except Exception:
|
||||
max_attempts = 2
|
||||
if max_attempts < 1:
|
||||
max_attempts = 1
|
||||
# 使用配置项,默认0.3秒(优化:从0.5秒降低到0.3秒)
|
||||
retry_delay = 0.3
|
||||
try:
|
||||
retry_delay = float(
|
||||
getattr(analyser, "fudai_detail_retry_delay_seconds", 0.3) or 0.3
|
||||
)
|
||||
except Exception:
|
||||
retry_delay = 0.3
|
||||
if retry_delay < 0.2:
|
||||
retry_delay = 0.2 # 最小0.2秒
|
||||
|
||||
last_tuple: Optional[Tuple] = None
|
||||
last_status: str = "error"
|
||||
first_countdown_seconds: Optional[float] = None
|
||||
first_tuple: Optional[Tuple] = None
|
||||
first_attempt_time: float = 0.0
|
||||
extra: dict = {} # 初始化 extra,避免未绑定错误
|
||||
|
||||
for attempt in range(max_attempts):
|
||||
attempt_start_time = time.time()
|
||||
status, tup, extra = read_fudai_detail_once(analyser)
|
||||
last_status = status
|
||||
if isinstance(tup, tuple) and len(tup) >= 6:
|
||||
current_tuple = tup[:6]
|
||||
# 计算当前倒计时秒数
|
||||
current_countdown_seconds = None
|
||||
try:
|
||||
cd = current_tuple[5]
|
||||
if isinstance(cd, (tuple, list)) and len(cd) >= 2:
|
||||
cd_start = float(cd[0] or 0.0)
|
||||
cd_end = float(cd[1] or 0.0)
|
||||
if cd_start > 0 and cd_end > cd_start:
|
||||
current_countdown_seconds = cd_end - cd_start
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录第一次成功读取的结果(作为基准)
|
||||
if (
|
||||
first_countdown_seconds is None
|
||||
and current_countdown_seconds is not None
|
||||
and status == "ok"
|
||||
):
|
||||
first_countdown_seconds = current_countdown_seconds
|
||||
first_tuple = current_tuple
|
||||
first_attempt_time = attempt_start_time
|
||||
last_tuple = current_tuple
|
||||
|
||||
# 优化:如果第一次识别成功且数据合理,直接返回,不进行第二次重试
|
||||
# 检查数据是否合理(有内容、有价值、倒计时合理)
|
||||
content = current_tuple[0] if len(current_tuple) > 0 else ""
|
||||
prize_value = current_tuple[4] if len(current_tuple) > 4 else 0.0
|
||||
time_text = current_tuple[1] if len(current_tuple) > 1 else ""
|
||||
|
||||
# 如果数据看起来合理(有内容或价值>0,倒计时合理),直接返回
|
||||
is_data_reasonable = (
|
||||
(content and len(content.strip()) > 0)
|
||||
or (prize_value and float(prize_value) > 0)
|
||||
or (time_text and len(time_text.strip()) > 0)
|
||||
)
|
||||
|
||||
if is_data_reasonable and current_countdown_seconds > 0:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:第一次识别成功且数据合理,跳过重试",
|
||||
attempt=attempt + 1,
|
||||
content_preview=content[:30] if content else "",
|
||||
prize_value=prize_value,
|
||||
countdown_seconds=int(current_countdown_seconds),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 直接返回,不进行第二次重试
|
||||
break
|
||||
|
||||
# 倒计时一致性检查:如果后续读取的倒计时与第一次差异过大,判定为识别错误
|
||||
elif (
|
||||
first_countdown_seconds is not None
|
||||
and current_countdown_seconds is not None
|
||||
):
|
||||
# 计算时间流逝(从第一次读取到现在的时间差)
|
||||
time_elapsed = attempt_start_time - first_attempt_time
|
||||
if time_elapsed < 0:
|
||||
time_elapsed = 0.5 # 默认假设间隔0.5秒
|
||||
|
||||
# 预期倒计时 = 第一次倒计时 - 时间流逝(允许一定误差)
|
||||
expected_countdown = first_countdown_seconds - time_elapsed
|
||||
|
||||
# 计算实际差异(与第一次相比)
|
||||
diff_ratio = abs(
|
||||
current_countdown_seconds - first_countdown_seconds
|
||||
) / max(first_countdown_seconds, 1.0)
|
||||
# 计算与预期的差异(考虑时间流逝)
|
||||
expected_diff_ratio = (
|
||||
abs(current_countdown_seconds - expected_countdown)
|
||||
/ max(expected_countdown, 1.0)
|
||||
if expected_countdown > 0
|
||||
else 1.0
|
||||
)
|
||||
|
||||
# 如果差异过大(超过30%)或与预期差异过大(超过20%),判定为识别错误
|
||||
# 注意:如果当前倒计时明显大于第一次(时间应该减少),肯定是识别错误
|
||||
is_inconsistent = (
|
||||
diff_ratio > 0.3
|
||||
or expected_diff_ratio > 0.2
|
||||
or current_countdown_seconds
|
||||
> first_countdown_seconds + 10 # 倒计时不应该增加
|
||||
)
|
||||
|
||||
if is_inconsistent:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"倒计时识别不一致,判定为识别错误(拒绝本次结果,保留第一次结果)",
|
||||
attempt=attempt + 1,
|
||||
first_countdown_seconds=int(first_countdown_seconds),
|
||||
current_countdown_seconds=int(current_countdown_seconds),
|
||||
expected_countdown=int(expected_countdown),
|
||||
time_elapsed=round(time_elapsed, 2),
|
||||
diff_ratio=round(diff_ratio, 3),
|
||||
expected_diff_ratio=round(expected_diff_ratio, 3),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 拒绝本次结果,继续使用第一次的结果
|
||||
current_tuple = first_tuple
|
||||
# 如果还有重试机会,继续重试
|
||||
if attempt < max_attempts - 1:
|
||||
try:
|
||||
analyser.operation.delay(retry_delay)
|
||||
except Exception:
|
||||
time.sleep(retry_delay)
|
||||
continue
|
||||
else:
|
||||
# 倒计时合理,更新为当前结果
|
||||
last_tuple = current_tuple
|
||||
|
||||
# 如果没有第一次结果,直接使用当前结果
|
||||
elif first_countdown_seconds is None:
|
||||
last_tuple = current_tuple
|
||||
|
||||
# 如果成功读取,或者检测到优惠券弹窗(已处理完毕),或者检测到观看任务,都停止重试
|
||||
if status == "ok" or status == "coupon_popup" or status == "watch_task":
|
||||
break
|
||||
|
||||
# 如果任务数量为0,说明没有正确打开福袋详情页,尝试重新打开
|
||||
if (
|
||||
status == "error"
|
||||
and isinstance(extra, dict)
|
||||
and extra.get("reason") == "task_count_zero"
|
||||
):
|
||||
if attempt < max_attempts - 1:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:任务数量为0,尝试重新打开福袋详情页",
|
||||
attempt=attempt + 1,
|
||||
max_attempts=max_attempts,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 调用回调函数重新打开福袋详情页
|
||||
try:
|
||||
if _ensure_open_callback:
|
||||
_ensure_open_callback(analyser, fudai_x)
|
||||
# 重新打开后等待一段时间,确保页面加载完成
|
||||
try:
|
||||
analyser.operation.delay(retry_delay + 0.5)
|
||||
except Exception:
|
||||
time.sleep(retry_delay + 0.5)
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:重新打开福袋详情页失败",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if attempt < max_attempts - 1:
|
||||
try:
|
||||
analyser.operation.delay(retry_delay)
|
||||
except Exception:
|
||||
time.sleep(retry_delay)
|
||||
|
||||
if last_tuple is None:
|
||||
now = time.time()
|
||||
last_tuple = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
|
||||
content, time_text, participants, copies, prize_value_yuan, cd = last_tuple
|
||||
cd_start, cd_end = None, None
|
||||
if isinstance(cd, (tuple, list)) and len(cd) >= 2:
|
||||
cd_start, cd_end = cd[0], cd[1]
|
||||
|
||||
# 如果是优惠券弹窗,记录日志并明确标记
|
||||
is_coupon_popup = last_status == "coupon_popup"
|
||||
is_watch_task = last_status == "watch_task"
|
||||
|
||||
# 获取直播间名字(所有情况都需要,用于日志输出)
|
||||
room_title = ""
|
||||
room_title_raw = ""
|
||||
try:
|
||||
room_title = str(getattr(analyser, "current_room_title", "") or "").strip()
|
||||
room_title_raw = str(
|
||||
getattr(analyser, "current_room_title_raw", "") or ""
|
||||
).strip()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 格式化时间信息(所有情况都需要,用于日志输出)
|
||||
cd_end_str = ""
|
||||
remain_seconds = 0
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
if cd_end and isinstance(cd_end, (int, float)) and cd_end > 0:
|
||||
cd_end_str = datetime.fromtimestamp(cd_end).strftime("%Y-%m-%d %H:%M:%S")
|
||||
remain_seconds = int(cd_end - time.time()) if cd_end > time.time() else 0
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if is_coupon_popup:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries 最终结果:优惠券弹窗,已关闭,跳过后续处理",
|
||||
status=last_status,
|
||||
fudai_x=fudai_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 输出到行为日志
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"行为",
|
||||
"识别福袋详情完成(最终结果)",
|
||||
action="识别福袋详情",
|
||||
result="优惠券弹窗",
|
||||
detail={
|
||||
"直播间": room_title if room_title else room_title_raw,
|
||||
"直播间原始": room_title_raw,
|
||||
"福袋内容": content or "",
|
||||
"倒计时文本": time_text or "",
|
||||
"参与人数": int(participants or 0),
|
||||
"福袋份数": int(copies or 0),
|
||||
"奖品价值": float(prize_value_yuan or 0.0),
|
||||
"倒计时开始时间": str(cd_start) if cd_start else "",
|
||||
"倒计时结束时间": (
|
||||
cd_end_str if cd_end_str else str(cd_end) if cd_end else ""
|
||||
),
|
||||
"剩余秒数": remain_seconds,
|
||||
"状态": last_status,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elif is_watch_task:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries 最终结果:观看X分钟任务,已跳过,关闭详情",
|
||||
status=last_status,
|
||||
fudai_x=fudai_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 输出到行为日志
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"行为",
|
||||
"识别福袋详情完成(最终结果)",
|
||||
action="识别福袋详情",
|
||||
result="观看任务",
|
||||
detail={
|
||||
"直播间": room_title if room_title else room_title_raw,
|
||||
"直播间原始": room_title_raw,
|
||||
"福袋内容": content or "",
|
||||
"倒计时文本": time_text or "",
|
||||
"参与人数": int(participants or 0),
|
||||
"福袋份数": int(copies or 0),
|
||||
"奖品价值": float(prize_value_yuan or 0.0),
|
||||
"倒计时开始时间": str(cd_start) if cd_start else "",
|
||||
"倒计时结束时间": (
|
||||
cd_end_str if cd_end_str else str(cd_end) if cd_end else ""
|
||||
),
|
||||
"剩余秒数": remain_seconds,
|
||||
"状态": last_status,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 关闭详情页
|
||||
try:
|
||||
_close_detail_callback(analyser)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
# 切换直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if needswitch:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"检测到观看任务后切换直播间",
|
||||
)
|
||||
# 优先使用封装好的上滑切房方法
|
||||
if hasattr(analyser, "swipe_up_to_next_live"):
|
||||
analyser.swipe_up_to_next_live()
|
||||
else:
|
||||
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1200 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 600 * ry // 2400
|
||||
analyser.operation.swipe(
|
||||
analyser.device_id, start_x, start_y, end_x, end_y, 300
|
||||
)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 正常情况(成功或错误):输出到运行日志和行为日志
|
||||
try:
|
||||
# 运行日志:完整的福袋详情
|
||||
content_preview = (content or "")[:60] if content else "未识别到"
|
||||
content_full = content or ""
|
||||
# 移除重复的福袋内容输出,避免与read_fudai_detail_once重复
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
f"read_fudai_detail_with_retries 最终结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
|
||||
status=last_status,
|
||||
room_title=room_title,
|
||||
room_title_raw=room_title_raw,
|
||||
content=content_full,
|
||||
time_text=time_text,
|
||||
participants=participants,
|
||||
copies=copies,
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
countdown_start=cd_start,
|
||||
countdown_end=cd_end,
|
||||
countdown_end_str=cd_end_str if cd_end_str else "",
|
||||
remain_seconds=remain_seconds,
|
||||
fudai_x=fudai_x,
|
||||
)
|
||||
|
||||
# 行为日志:完整的福袋详情
|
||||
analyser._log_kv(
|
||||
"行为",
|
||||
f"识别福袋详情完成(最终结果):内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
|
||||
action="识别福袋详情",
|
||||
result="成功" if last_status == "ok" else last_status,
|
||||
detail={
|
||||
"直播间": room_title if room_title else room_title_raw,
|
||||
"直播间原始": room_title_raw,
|
||||
"福袋内容": content or "",
|
||||
"倒计时文本": time_text or "",
|
||||
"参与人数": int(participants or 0),
|
||||
"福袋份数": int(copies or 0),
|
||||
"奖品价值": float(prize_value_yuan or 0.0),
|
||||
"倒计时开始时间": str(cd_start) if cd_start else "",
|
||||
"倒计时结束时间": (
|
||||
cd_end_str if cd_end_str else str(cd_end) if cd_end else ""
|
||||
),
|
||||
"剩余秒数": remain_seconds,
|
||||
"状态": last_status,
|
||||
},
|
||||
)
|
||||
except Exception as e:
|
||||
# 如果日志输出失败,至少尝试输出简化版本
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries 最终结果(简化)",
|
||||
status=last_status,
|
||||
content=content or "",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 将状态信息存储在 analyser 中,供调用方检查
|
||||
try:
|
||||
analyser._last_fudai_detail_status = last_status # type: ignore[attr-defined]
|
||||
# 同时保存 extra 信息,用于检查错误原因
|
||||
if isinstance(extra, dict):
|
||||
analyser._last_fudai_detail_extra = extra # type: ignore[attr-defined]
|
||||
else:
|
||||
analyser._last_fudai_detail_extra = {} # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 验证福袋详情数据的合理性(仅在成功读取时验证)
|
||||
if last_status == "ok":
|
||||
is_valid, reason = validate_fudai_detail(last_tuple, analyser)
|
||||
if not is_valid:
|
||||
# 先标记状态,避免日志异常导致未标记
|
||||
try:
|
||||
analyser._last_fudai_detail_status = "validation_failed" # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
# 同步本地状态用于后续日志输出
|
||||
last_status = "validation_failed"
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries:数据验证失败,识别可能出错",
|
||||
validation_reason=reason,
|
||||
content=content[:50] if content else "",
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
participants=participants,
|
||||
copies=copies,
|
||||
time_text=time_text[:30] if time_text else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_with_retries完成",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
status=last_status,
|
||||
attempts=max_attempts,
|
||||
)
|
||||
return last_tuple
|
||||
+21
-1087
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,27 @@
|
||||
"""fudai_filter_pkg - 福袋筛选决策子包。
|
||||
|
||||
原 douyin/fudai/core/fudai_filter.py 拆成 3 个子模块:
|
||||
|
||||
- helpers 小工具:倒计时短文本 / 黑名单 / 观看任务识别
|
||||
- should_skip should_skip_fudai_by_config 配置筛选总决策
|
||||
- join_decision basic_join_decision 最终参与决策
|
||||
|
||||
外部 import 路径不变:``from douyin.fudai.core.fudai_filter import basic_join_decision``
|
||||
仍可用(原文件改成 re-export shim)。
|
||||
"""
|
||||
|
||||
from .helpers import (
|
||||
_is_short_countdown_text,
|
||||
check_contain,
|
||||
is_watch_task_fudai,
|
||||
)
|
||||
from .should_skip import should_skip_fudai_by_config
|
||||
from .join_decision import basic_join_decision
|
||||
|
||||
__all__ = [
|
||||
"_is_short_countdown_text",
|
||||
"check_contain",
|
||||
"is_watch_task_fudai",
|
||||
"should_skip_fudai_by_config",
|
||||
"basic_join_decision",
|
||||
]
|
||||
@@ -0,0 +1,126 @@
|
||||
"""fudai_filter_pkg.helpers - 小型工具函数。
|
||||
|
||||
- _is_short_countdown_text 判断倒计时文本是否表示 "剩余 ≤2 秒" 应跳过
|
||||
- check_contain 黑名单关键词检查(contains_not_want)
|
||||
- is_watch_task_fudai 识别 "观看 X 分钟" 类观看任务福袋
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
|
||||
def _is_short_countdown_text(time_text: str) -> bool:
|
||||
"""检查倒计时文本是否表示剩余时间很短(应跳过)"""
|
||||
if not time_text:
|
||||
return False
|
||||
|
||||
time_text = time_text.strip()
|
||||
|
||||
# 匹配 00:00, 00:01, 00:02 等,表示剩余时间 <= 2秒
|
||||
if re.match(r"^00:0[0-2]$", time_text):
|
||||
return True
|
||||
|
||||
# 匹配 0:00, 0:01, 0:02 等(有时没有前导零)
|
||||
if re.match(r"^0:0[0-2]$", time_text):
|
||||
return True
|
||||
|
||||
# 匹配 "00秒", "01秒", "02秒" 等
|
||||
if re.match(r"^0[0-2]秒$", time_text):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def check_contain(analyser, contains: str = "") -> bool:
|
||||
"""检查福袋内容是否命中"黑名单"关键词(只保留黑名单逻辑,不再使用白名单)。
|
||||
|
||||
返回值语义(调整后):
|
||||
- True : "建议丢弃"(内容命中黑名单 contains_not_want)
|
||||
- False : "可以保留"(未命中黑名单)
|
||||
"""
|
||||
try:
|
||||
for contain in getattr(analyser, "contains_not_want", []) or []:
|
||||
if contain and contain in (contains or ""):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"福袋内容命中黑名单,将丢弃",
|
||||
keyword=contain,
|
||||
contains=contains[:80] if contains else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"福袋内容未命中黑名单,保留",
|
||||
contains=contains[:80] if contains else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except Exception:
|
||||
# 容错:异常时不过滤
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"check_contain 异常,默认保留",
|
||||
contains=contains[:80] if contains else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def is_watch_task_fudai(content: str) -> bool:
|
||||
"""检测是否为"观看X分钟"类任务福袋。
|
||||
|
||||
参数:
|
||||
content: 福袋内容文本
|
||||
|
||||
返回:
|
||||
True 表示是"观看X分钟"类任务,应放弃
|
||||
False 表示不是此类任务
|
||||
"""
|
||||
if not content:
|
||||
return False
|
||||
|
||||
try:
|
||||
import re
|
||||
|
||||
# 将内容转换为字符串并去除空白
|
||||
content_str = re.sub(r"\s+", "", str(content))
|
||||
|
||||
# 中文数字字符
|
||||
chinese_num_chars = "零一二三四五六七八九十百千两"
|
||||
|
||||
# 匹配模式1:观看/看 + (可选"直播") + 数字或中文数字 + 分钟
|
||||
patt1 = rf"(?:观看|看)(?:直播)?(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟"
|
||||
|
||||
# 匹配模式2:需要观看/需要看 + 数字或中文数字 + 分钟
|
||||
patt2 = rf"需要(?:观看|看)(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟"
|
||||
|
||||
# 匹配模式3:观看时长 + 数字或中文数字 + 分钟
|
||||
patt3 = rf"观看时长(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟"
|
||||
|
||||
# 匹配模式4:看播 + 数字或中文数字 + 分钟
|
||||
patt4 = rf"看播(?:.*?)?(?:\d+|[{chinese_num_chars}]+)\s*分钟"
|
||||
|
||||
# 检查是否匹配任一模式
|
||||
patterns = [patt1, patt2, patt3, patt4]
|
||||
for patt in patterns:
|
||||
if re.search(patt, content_str):
|
||||
return True
|
||||
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,524 @@
|
||||
"""fudai_filter_pkg.join_decision - basic_join_decision 主决策。
|
||||
|
||||
包含 basic_join_decision:在 should_skip_fudai_by_config 通过后,
|
||||
做最终的 "是否真的点击参与按钮" 决策(含运行时校验、按钮文本识别等)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from typing import Any, Tuple
|
||||
|
||||
from .helpers import _is_short_countdown_text
|
||||
from .should_skip import should_skip_fudai_by_config
|
||||
|
||||
|
||||
def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
"""基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。
|
||||
|
||||
返回:
|
||||
True 表示已经参与或已处理完成;
|
||||
False 表示未参与(例如被配置筛掉或参与失败)。
|
||||
"""
|
||||
# time 模块在文件开头已导入
|
||||
start_time = time.time()
|
||||
# 解析 detail 字段:先提取价值信息,用于判断是否达到高价值阈值
|
||||
content = ""
|
||||
prize_value_yuan = 0.0
|
||||
countdown_tuple = None
|
||||
try:
|
||||
if isinstance(detail, tuple) and len(detail) >= 6:
|
||||
content = str(detail[0] or "")
|
||||
prize_value_yuan = float(detail[4] or 0.0)
|
||||
countdown_tuple = detail[5]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理
|
||||
try:
|
||||
last_status = getattr(analyser, "_last_fudai_detail_status", "")
|
||||
if last_status == "coupon_popup":
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(优惠券弹窗)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
elif last_status == "validation_failed":
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(验证失败)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 强制参与标志已移除:始终进行正常验证流程
|
||||
force_attend = False
|
||||
# 继续走后续验证分支
|
||||
# 额外验证:使用验证函数检查数据合理性
|
||||
try:
|
||||
# 在函数开头导入,避免作用域问题
|
||||
from douyin.fudai import douyin_fudai_detail as dfd_module
|
||||
|
||||
is_valid, reason = dfd_module.validate_fudai_detail(detail, analyser)
|
||||
if not is_valid:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:福袋详情数据验证失败,识别出错",
|
||||
validation_reason=reason,
|
||||
content=content[:50] if content else "",
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(验证失败)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误
|
||||
if not content and prize_value_yuan == 0.0:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理",
|
||||
content=content,
|
||||
prize_value_yuan=prize_value_yuan,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(无效详情)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
|
||||
# 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if not needswitch:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:单间模式,忽略阈值与预约逻辑,直接参与当前福袋",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 这里需要导入 attend_choujiang 函数
|
||||
from .fudai_attend import attend_choujiang
|
||||
|
||||
result = attend_choujiang(analyser)
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(单间模式参与)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
result=result,
|
||||
)
|
||||
return result
|
||||
|
||||
# 检查是否启用高价值预约,以及价值是否达到阈值
|
||||
try:
|
||||
high_value_enabled = bool(getattr(analyser, "high_value_fudai_enabled", False))
|
||||
except Exception:
|
||||
high_value_enabled = False
|
||||
|
||||
try:
|
||||
high_value_threshold = float(
|
||||
getattr(analyser, "high_value_fudai_threshold_yuan", 500.0) or 500.0
|
||||
)
|
||||
except Exception:
|
||||
high_value_threshold = 500.0
|
||||
|
||||
# 计算 future_timestamp(预计开奖时间戳)
|
||||
future_ts = 0.0
|
||||
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
|
||||
try:
|
||||
future_ts = float(countdown_tuple[1] or 0.0)
|
||||
except Exception:
|
||||
future_ts = 0.0
|
||||
|
||||
# 检查是否已经参与过这个福袋(通过 future_ts 匹配,避免重复参与)
|
||||
if future_ts > 0:
|
||||
try:
|
||||
participated_fudai_ts = getattr(
|
||||
analyser, "_participated_fudai_future_ts", set()
|
||||
)
|
||||
if not isinstance(participated_fudai_ts, set):
|
||||
participated_fudai_ts = set()
|
||||
|
||||
# 检查是否已经参与过(允许5秒误差,因为倒计时可能略有变化)
|
||||
for participated_ts in participated_fudai_ts:
|
||||
if abs(future_ts - participated_ts) < 5.0:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:已参与过此福袋,跳过重复参与",
|
||||
future_ts=future_ts,
|
||||
participated_ts=participated_ts,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 已参与过,直接返回 True(表示已处理完成)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检查价值是否达到高价值阈值
|
||||
is_high_value = (
|
||||
high_value_enabled
|
||||
and prize_value_yuan > 0
|
||||
and prize_value_yuan >= high_value_threshold
|
||||
and future_ts > 0.0
|
||||
)
|
||||
|
||||
# 执行筛选检查
|
||||
skip, reason = should_skip_fudai_by_config(analyser, detail)
|
||||
|
||||
# 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值
|
||||
# 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约
|
||||
# 注意:如果是观看任务,不应该进入这个特殊处理逻辑(should_skip_fudai_by_config 已经返回 watch_task_detected)
|
||||
if skip and reason.startswith("countdown_gt_") and is_high_value:
|
||||
# 再次检查是否是观看任务(双重保险)
|
||||
is_watch_task = False
|
||||
try:
|
||||
is_watch_task = is_watch_task_fudai(content)
|
||||
if is_watch_task:
|
||||
# 是观看任务,不记录预约,直接关闭详情页并返回
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[预约]",
|
||||
"特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃",
|
||||
content=content[:80] if content else "",
|
||||
value_yuan=prize_value_yuan,
|
||||
threshold=high_value_threshold,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 关闭详情页
|
||||
try:
|
||||
analyser.click(500, 470)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:已关闭详情(观看任务)",
|
||||
action="close_detail",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 如果允许切换直播间,切换直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if needswitch:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:观看任务后切换直播间",
|
||||
reason="watch_task",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
# 优先使用封装好的上滑切房方法
|
||||
if hasattr(analyser, "swipe_up_to_next_live"):
|
||||
analyser.swipe_up_to_next_live()
|
||||
else:
|
||||
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
|
||||
try:
|
||||
rx = int(
|
||||
getattr(analyser, "resolution_ratio_x", 1080)
|
||||
or 1080
|
||||
)
|
||||
ry = int(
|
||||
getattr(analyser, "resolution_ratio_y", 2400)
|
||||
or 2400
|
||||
)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1200 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 600 * ry // 2400
|
||||
analyser.operation.swipe(
|
||||
analyser.device_id,
|
||||
start_x,
|
||||
start_y,
|
||||
end_x,
|
||||
end_y,
|
||||
300,
|
||||
)
|
||||
except Exception:
|
||||
# 切房失败不影响主流程,直接返回
|
||||
pass
|
||||
# 直接返回 False,不参与抽奖
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(观看任务,已丢弃)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
# 如果检查观看任务时出错,记录日志但继续后续处理(容错处理)
|
||||
pass
|
||||
|
||||
# 计算剩余秒数
|
||||
remain_seconds = None
|
||||
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
|
||||
try:
|
||||
now = time.time()
|
||||
cd_start = float(countdown_tuple[0] or 0.0)
|
||||
cd_end = float(countdown_tuple[1] or 0.0)
|
||||
if cd_start > 0 and cd_end > cd_start:
|
||||
remain_seconds = float(cd_end - now)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 获取"预约参与阈值"配置
|
||||
try:
|
||||
join_ahead_seconds = int(
|
||||
getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120
|
||||
)
|
||||
except Exception:
|
||||
join_ahead_seconds = 120
|
||||
|
||||
# 检查是否是回退后强制参与
|
||||
# 如果剩余秒数在"预约参与阈值"内,立即参与而不是预约
|
||||
if remain_seconds is not None and remain_seconds <= join_ahead_seconds:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:倒计时大于阈值,但剩余秒数在预约参与阈值内或回退后强制参与,立即参与",
|
||||
reason=reason,
|
||||
value_yuan=prize_value_yuan,
|
||||
threshold=high_value_threshold,
|
||||
remain_seconds=(
|
||||
int(remain_seconds) if remain_seconds is not None else None
|
||||
),
|
||||
join_ahead_threshold=join_ahead_seconds,
|
||||
force_attend=force_attend,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 不关闭详情,继续走立即参与逻辑
|
||||
skip = False
|
||||
reason = (
|
||||
"high_value_immediate_join"
|
||||
if not force_attend
|
||||
else "reservation_back_force_attend"
|
||||
)
|
||||
# 如果是强制参与,设置 is_high_value = False,跳过后续的高价值处理逻辑(避免再次记录预约)
|
||||
# 注意:强制参与标志会在参与成功后清除(在 attend_choujiang 返回后),避免影响后续福袋
|
||||
# no-op: 强制参与标志已删除
|
||||
else:
|
||||
# 剩余秒数大于"预约参与阈值",但在记录预约之前再次检查是否是观看任务
|
||||
is_watch_task_check = False
|
||||
try:
|
||||
is_watch_task_check = is_watch_task_fudai(content)
|
||||
if is_watch_task_check:
|
||||
# 是观看任务,不记录预约,直接关闭详情页并返回
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[预约]",
|
||||
"特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃",
|
||||
content=content[:80] if content else "",
|
||||
value_yuan=prize_value_yuan,
|
||||
threshold=high_value_threshold,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 关闭详情页
|
||||
try:
|
||||
analyser.click(500, 470)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:已关闭详情(观看任务)",
|
||||
action="close_detail",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 如果允许切换直播间,切换直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if needswitch:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:观看任务后切换直播间",
|
||||
reason="watch_task",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
# 优先使用封装好的上滑切房方法
|
||||
if hasattr(analyser, "swipe_up_to_next_live"):
|
||||
analyser.swipe_up_to_next_live()
|
||||
else:
|
||||
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
|
||||
try:
|
||||
rx = int(
|
||||
getattr(analyser, "resolution_ratio_x", 1080)
|
||||
or 1080
|
||||
)
|
||||
ry = int(
|
||||
getattr(analyser, "resolution_ratio_y", 2400)
|
||||
or 2400
|
||||
)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1200 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 600 * ry // 2400
|
||||
analyser.operation.swipe(
|
||||
analyser.device_id,
|
||||
start_x,
|
||||
start_y,
|
||||
end_x,
|
||||
end_y,
|
||||
300,
|
||||
)
|
||||
except Exception:
|
||||
# 切房失败不影响主流程,直接返回
|
||||
pass
|
||||
# 直接返回 False,不参与抽奖
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(观看任务,已丢弃)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
# 如果检查观看任务时出错,记录日志但继续后续处理(容错处理)
|
||||
pass
|
||||
|
||||
# 剩余秒数大于"预约参与阈值",记录预约
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:倒计时大于阈值,但价值达到高价值阈值,记录预约",
|
||||
reason=reason,
|
||||
value_yuan=prize_value_yuan,
|
||||
threshold=high_value_threshold,
|
||||
remain_seconds=(
|
||||
int(remain_seconds) if remain_seconds is not None else None
|
||||
),
|
||||
join_ahead_threshold=join_ahead_seconds,
|
||||
level="DEBUG",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 这里需要实现预约逻辑,由于代码太长,这里暂时简化
|
||||
# 不关闭详情,继续走预约逻辑
|
||||
skip = False
|
||||
reason = "high_value_reservation"
|
||||
|
||||
if skip:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:按配置丢弃福袋",
|
||||
reason=reason,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 丢弃时,尽量关闭详情,避免停留在详情页
|
||||
try:
|
||||
analyser.click(500, 470)
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与", "basic_join_decision:已关闭详情", action="close_detail"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果允许切换直播间,筛选不通过直接切换直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if needswitch:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与", "basic_join_decision:丢弃后切换直播间", reason=reason
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 这里需要实现切换直播间的逻辑,由于代码太长,这里暂时简化
|
||||
pass
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(丢弃)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
result=False,
|
||||
)
|
||||
return False
|
||||
|
||||
# 参与抽奖
|
||||
try:
|
||||
analyser._log_kv("参与", "basic_join_decision:开始参与抽奖")
|
||||
except Exception:
|
||||
pass
|
||||
from .fudai_attend import attend_choujiang
|
||||
|
||||
result = attend_choujiang(analyser)
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision完成(参与抽奖)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
result=result,
|
||||
)
|
||||
return result
|
||||
@@ -0,0 +1,483 @@
|
||||
"""fudai_filter_pkg.should_skip - 福袋是否应跳过的总决策。
|
||||
|
||||
包含 should_skip_fudai_by_config:基于 config.json 中的价值/参与人数/
|
||||
观看任务/黑白名单等多维度配置,决定是否跳过当前福袋。
|
||||
|
||||
返回 (skip, reason):
|
||||
- skip=True 应跳过,reason 说明原因(low_value / blacklist / ...)
|
||||
- skip=False 应继续参与,reason="ok"
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from typing import Any, Tuple
|
||||
|
||||
from .helpers import (
|
||||
_is_short_countdown_text,
|
||||
check_contain,
|
||||
is_watch_task_fudai,
|
||||
)
|
||||
|
||||
|
||||
def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str]:
|
||||
"""根据 config.json 中的阈值与关键词,判断是否应丢弃当前福袋。
|
||||
|
||||
返回:
|
||||
(skip, reason) 其中 reason 为简单文字原因,便于日志查看。
|
||||
"""
|
||||
start_time = time.time()
|
||||
# 单间模式(needswitch=False):忽略所有福袋阈值配置,永远不因为配置而跳过
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if not needswitch:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"单间模式:忽略所有福袋阈值配置,直接参与",
|
||||
needswitch=0,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, "single_room_mode"
|
||||
|
||||
if not isinstance(detail, tuple) or len(detail) < 6:
|
||||
return False, "detail_tuple_invalid"
|
||||
|
||||
content = str(detail[0] or "")
|
||||
|
||||
# 优先检查是否为"观看X分钟"类任务:若是,直接放弃
|
||||
if is_watch_task_fudai(content):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"检测到'观看X分钟'类任务,自动放弃",
|
||||
content=content[:80] if content else "",
|
||||
reason="watch_task_detected",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"should_skip_fudai_by_config完成(观看任务)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return True, "watch_task_detected"
|
||||
|
||||
time_text = str(detail[1] or "")
|
||||
try:
|
||||
participants = int(detail[2] or 0)
|
||||
except Exception:
|
||||
participants = 0
|
||||
try:
|
||||
copies = int(detail[3] or 0)
|
||||
except Exception:
|
||||
copies = 0
|
||||
try:
|
||||
prize_value_yuan = float(detail[4] or 0.0)
|
||||
except Exception:
|
||||
prize_value_yuan = 0.0
|
||||
|
||||
cd_start, cd_end = None, None
|
||||
if isinstance(detail[5], (tuple, list)) and len(detail[5]) >= 2:
|
||||
cd_start, cd_end = detail[5][0], detail[5][1]
|
||||
now = time.time()
|
||||
remain_seconds = None
|
||||
try:
|
||||
if isinstance(cd_end, (int, float)) and cd_end > now:
|
||||
remain_seconds = float(cd_end - now)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"倒计时计算成功",
|
||||
cd_end=cd_end,
|
||||
now=now,
|
||||
剩余秒数=remain_seconds,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"倒计时计算失败或已过期",
|
||||
cd_end=cd_end,
|
||||
now=now,
|
||||
cd_end类型=type(cd_end).__name__,
|
||||
cd_end大于now=(
|
||||
bool(isinstance(cd_end, (int, float)) and cd_end > now)
|
||||
if isinstance(cd_end, (int, float))
|
||||
else False
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
remain_seconds = None
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"倒计时计算异常",
|
||||
异常=str(e),
|
||||
异常类型=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 读取配置阈值
|
||||
try:
|
||||
min_value = float(getattr(analyser, "min_prize_value_yuan", 0.0) or 0.0)
|
||||
except Exception:
|
||||
min_value = 0.0
|
||||
try:
|
||||
min_participants = int(getattr(analyser, "min_participants", 0) or 0)
|
||||
except Exception:
|
||||
min_participants = 0
|
||||
try:
|
||||
max_participants = int(getattr(analyser, "max_participants", 0) or 0)
|
||||
except Exception:
|
||||
max_participants = 0
|
||||
skip_if_gt = 0 # Initialize before try block
|
||||
try:
|
||||
skip_if_gt = int(getattr(analyser, "skip_if_countdown_gt_seconds", 0) or 0)
|
||||
except Exception:
|
||||
skip_if_gt = 0
|
||||
skip_if_lt = 0 # Initialize before try block
|
||||
try:
|
||||
skip_if_lt = int(getattr(analyser, "skip_if_countdown_lt_seconds", 0) or 0)
|
||||
except Exception:
|
||||
skip_if_lt = 0
|
||||
|
||||
# 获取按钮文本,用于记录
|
||||
button_text = str(getattr(analyser, "button_text_raw", "") or "").strip()
|
||||
|
||||
# 记录所有配置值和实际值,便于调试
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"should_skip_fudai_by_config 开始检查",
|
||||
配置_最小价值=min_value,
|
||||
配置_最小参与人数=min_participants,
|
||||
配置_最大参与人数=max_participants,
|
||||
配置_倒计时大于秒数=skip_if_gt,
|
||||
配置_倒计时小于秒数=skip_if_lt,
|
||||
实际_价值=prize_value_yuan,
|
||||
实际_参与人数=participants,
|
||||
实际_份数=copies,
|
||||
实际_剩余秒数=int(remain_seconds) if remain_seconds is not None else None,
|
||||
实际_内容=content[:60] if content else "",
|
||||
按钮文本=button_text if button_text else "未识别",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 并行检查所有筛选条件,收集所有不符合的原因
|
||||
skip_reasons = []
|
||||
|
||||
# 1) 价值过滤
|
||||
if min_value > 0:
|
||||
if prize_value_yuan > 0:
|
||||
if prize_value_yuan < min_value:
|
||||
skip_reasons.append(f"value_lt_{min_value}")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"价值过滤:不符合(价值过低)",
|
||||
实际价值=prize_value_yuan,
|
||||
配置最小价值=min_value,
|
||||
判断条件=f"{prize_value_yuan} < {min_value} = True",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"价值过滤:通过",
|
||||
实际价值=prize_value_yuan,
|
||||
配置最小价值=min_value,
|
||||
判断条件=f"{prize_value_yuan} >= {min_value} = True",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"价值过滤:跳过(未识别到价值)",
|
||||
实际价值=prize_value_yuan,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2) 参与人数过滤
|
||||
if min_participants > 0:
|
||||
if participants > 0:
|
||||
if participants < min_participants:
|
||||
skip_reasons.append(f"participants_lt_{min_participants}")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"参与人数过滤:不符合(小于最小值)",
|
||||
实际参与人数=participants,
|
||||
配置最小参与人数=min_participants,
|
||||
判断条件=f"{participants} < {min_participants} = True",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"参与人数过滤:通过(最小值检查)",
|
||||
实际参与人数=participants,
|
||||
配置最小参与人数=min_participants,
|
||||
判断条件=f"{participants} >= {min_participants} = True",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"参与人数过滤:跳过(未识别到参与人数)",
|
||||
实际参与人数=participants,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if max_participants > 0:
|
||||
if participants > 0:
|
||||
if participants > max_participants:
|
||||
skip_reasons.append(f"participants_gt_{max_participants}")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"参与人数过滤:不符合(大于最大值)",
|
||||
实际参与人数=participants,
|
||||
配置最大参与人数=max_participants,
|
||||
判断条件=f"{participants} > {max_participants} = True",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"参与人数过滤:通过(最大值检查)",
|
||||
实际参与人数=participants,
|
||||
配置最大参与人数=max_participants,
|
||||
判断条件=f"{participants} <= {max_participants} = True",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 3) 倒计时过滤
|
||||
# 3.1) 倒计时小于阈值:直接丢弃(不参与)
|
||||
if skip_if_lt > 0:
|
||||
if remain_seconds is not None:
|
||||
if remain_seconds < skip_if_lt:
|
||||
skip_reasons.append(f"countdown_lt_{skip_if_lt}")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"倒计时过滤:不符合(剩余秒数小于阈值)",
|
||||
实际剩余秒数=int(remain_seconds),
|
||||
配置阈值秒数=skip_if_lt,
|
||||
判断条件=f"{remain_seconds} < {skip_if_lt} = True",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 3.2) 倒计时大于阈值:不参与(但如果价值达到高价值阈值,可以预约)
|
||||
if skip_if_gt > 0:
|
||||
if remain_seconds is not None:
|
||||
if remain_seconds > skip_if_gt:
|
||||
skip_reasons.append(f"countdown_gt_{skip_if_gt}")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"倒计时过滤:不符合(剩余秒数大于阈值)",
|
||||
实际剩余秒数=int(remain_seconds),
|
||||
配置阈值秒数=skip_if_gt,
|
||||
判断条件=f"{remain_seconds} > {skip_if_gt} = True",
|
||||
说明="如果价值达到高价值阈值,basic_join_decision 会记录预约",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"倒计时过滤:通过",
|
||||
实际剩余秒数=int(remain_seconds),
|
||||
配置阈值秒数=skip_if_gt,
|
||||
判断条件=f"{remain_seconds} <= {skip_if_gt} = True",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"倒计时过滤:跳过(未识别到倒计时或倒计时已过期)",
|
||||
剩余秒数=remain_seconds,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"倒计时过滤:跳过(配置阈值为0,不启用倒计时过滤)",
|
||||
配置阈值秒数=skip_if_gt,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 4) 内容关键词过滤(复用 check_contain 逻辑)
|
||||
content_check_result = check_contain(analyser, content)
|
||||
if content_check_result:
|
||||
skip_reasons.append("content_not_wanted")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"内容关键词过滤:不符合",
|
||||
内容=content[:60] if content else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"内容关键词过滤:通过",
|
||||
内容=content[:60] if content else "",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 5) 按钮文本过滤:检查按钮是否显示无法参与、还需看播等状态
|
||||
try:
|
||||
if button_text:
|
||||
# 检查是否包含无法参与的关键词
|
||||
unable_to_participate_keywords = [
|
||||
"无法参与",
|
||||
"不能参与",
|
||||
"不可参与",
|
||||
"还没到时间",
|
||||
"活动已结束",
|
||||
"活动结束",
|
||||
"已结束",
|
||||
"已过期",
|
||||
"已截止",
|
||||
"时长不足",
|
||||
]
|
||||
watch_required_keywords = [
|
||||
"还需看播",
|
||||
"观看",
|
||||
"看播",
|
||||
"观看时长",
|
||||
"观看分钟",
|
||||
]
|
||||
|
||||
# 检查无法参与关键词
|
||||
for keyword in unable_to_participate_keywords:
|
||||
if keyword in button_text:
|
||||
skip_reasons.append("button_unable_to_participate")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"按钮文本过滤:不符合(无法参与)",
|
||||
按钮文本=button_text,
|
||||
匹配关键词=keyword,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
# 检查观看要求关键词
|
||||
for keyword in watch_required_keywords:
|
||||
if keyword in button_text:
|
||||
skip_reasons.append("button_watch_required")
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"按钮文本过滤:不符合(观看任务)",
|
||||
按钮文本=button_text,
|
||||
匹配关键词=keyword,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
if not any(reason.startswith("button_") for reason in skip_reasons):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"按钮文本过滤:通过",
|
||||
按钮文本=button_text,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"按钮文本过滤:跳过(未识别到按钮文本)",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"按钮文本过滤:异常",
|
||||
异常=str(e),
|
||||
异常类型=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果有任何不符合的条件,就跳过
|
||||
if skip_reasons:
|
||||
elapsed = time.time() - start_time
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"should_skip_fudai_by_config完成(不符合条件,跳过)",
|
||||
不符合原因=skip_reasons,
|
||||
总原因数=len(skip_reasons),
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 返回第一个原因作为主要原因
|
||||
return True, skip_reasons[0]
|
||||
|
||||
# 所有条件都通过
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"should_skip_fudai_by_config 通过(所有检查项均通过)",
|
||||
content=content[:60] if content else "",
|
||||
participants=participants,
|
||||
copies=copies,
|
||||
value_yuan=prize_value_yuan,
|
||||
remain_seconds=int(remain_seconds) if remain_seconds is not None else None,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"should_skip_fudai_by_config完成(通过)",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
return False, "ok"
|
||||
|
||||
|
||||
@@ -26,6 +26,23 @@ from douyin.fudai.core.fudai_debug_utils import (
|
||||
_save_full_screenshot_with_ocr_region,
|
||||
)
|
||||
|
||||
|
||||
# 从子包 re-export(保持兼容):薄壳 forwarding + OCR 线程池
|
||||
from douyin.fudai.douyin_fudai_core_pkg import (
|
||||
_FudaiOcrExecutorState,
|
||||
_fudai_ocr_executor_state,
|
||||
_get_fudai_ocr_executor,
|
||||
attend_choujiang,
|
||||
basic_join_decision,
|
||||
check_have_reward_notice_confirm,
|
||||
check_in_order_confirm_page,
|
||||
check_lucky_draw_result,
|
||||
get_reward,
|
||||
is_watch_task_fudai,
|
||||
should_skip_fudai_by_config,
|
||||
_is_short_countdown_text,
|
||||
)
|
||||
|
||||
try:
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
except Exception: # pyright: ignore
|
||||
@@ -41,33 +58,6 @@ except Exception: # pyright: ignore
|
||||
# 模块级线程池状态,用于复用 OCR 并行执行,避免频繁创建/销毁
|
||||
|
||||
|
||||
class _FudaiOcrExecutorState:
|
||||
def __init__(self) -> None:
|
||||
self.executor: Optional[ThreadPoolExecutor] = None
|
||||
self.workers: int = 0
|
||||
self.lock = threading.Lock()
|
||||
|
||||
|
||||
_fudai_ocr_executor_state = _FudaiOcrExecutorState()
|
||||
|
||||
|
||||
def _get_fudai_ocr_executor(optimal_workers: int) -> ThreadPoolExecutor:
|
||||
"""获取复用的 OCR 线程池;如线程数变化则重建。"""
|
||||
state = _fudai_ocr_executor_state
|
||||
with state.lock:
|
||||
if state.executor and state.workers == optimal_workers:
|
||||
return state.executor
|
||||
# 若线程数变化,安全关闭旧池
|
||||
if state.executor:
|
||||
try:
|
||||
state.executor.shutdown(wait=False, cancel_futures=True)
|
||||
except RuntimeError:
|
||||
pass
|
||||
state.executor = None
|
||||
executor = ThreadPoolExecutor(max_workers=optimal_workers)
|
||||
state.executor = executor
|
||||
state.workers = optimal_workers
|
||||
return executor
|
||||
|
||||
|
||||
def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]:
|
||||
@@ -2132,74 +2122,3 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
# 此处保留模块级名称以兼容历史 from douyin_fudai_core import check_contain。
|
||||
|
||||
|
||||
def attend_choujiang(analyser) -> bool: # noqa: F811 — 兼容性 re-export
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_attend。"""
|
||||
from douyin.fudai.core.fudai_attend import attend_choujiang as _impl
|
||||
|
||||
return _impl(analyser)
|
||||
|
||||
|
||||
def check_lucky_draw_result(analyser): # noqa: F811 — 兼容性 re-export
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
|
||||
from douyin.fudai.core.fudai_result_checker import (
|
||||
check_lucky_draw_result as _impl,
|
||||
)
|
||||
|
||||
return _impl(analyser)
|
||||
|
||||
|
||||
def check_have_reward_notice_confirm(analyser) -> bool: # noqa: F811
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
|
||||
from douyin.fudai.core.fudai_result_checker import (
|
||||
check_have_reward_notice_confirm as _impl,
|
||||
)
|
||||
|
||||
return _impl(analyser)
|
||||
|
||||
|
||||
def check_in_order_confirm_page(analyser) -> bool: # noqa: F811
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
|
||||
from douyin.fudai.core.fudai_result_checker import (
|
||||
check_in_order_confirm_page as _impl,
|
||||
)
|
||||
|
||||
return _impl(analyser)
|
||||
|
||||
|
||||
def get_reward(analyser, reward_y: int = 0) -> None: # noqa: F811
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
|
||||
from douyin.fudai.core.fudai_result_checker import get_reward as _impl
|
||||
|
||||
return _impl(analyser, reward_y=reward_y)
|
||||
|
||||
|
||||
def is_watch_task_fudai(content: str) -> bool: # noqa: F811 — 兼容性 re-export
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
|
||||
from douyin.fudai.core.fudai_filter import is_watch_task_fudai as _impl
|
||||
|
||||
return _impl(content)
|
||||
|
||||
|
||||
def _is_short_countdown_text(time_text: str) -> bool: # noqa: F811
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
|
||||
from douyin.fudai.core.fudai_filter import (
|
||||
_is_short_countdown_text as _impl,
|
||||
)
|
||||
|
||||
return _impl(time_text)
|
||||
|
||||
|
||||
def should_skip_fudai_by_config(analyser, detail): # noqa: F811 — 兼容性 re-export
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
|
||||
from douyin.fudai.core.fudai_filter import (
|
||||
should_skip_fudai_by_config as _impl,
|
||||
)
|
||||
|
||||
return _impl(analyser, detail)
|
||||
|
||||
|
||||
def basic_join_decision(analyser, detail): # noqa: F811 — 兼容性 re-export
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
|
||||
from douyin.fudai.core.fudai_filter import basic_join_decision as _impl
|
||||
|
||||
return _impl(analyser, detail)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""douyin_fudai_core_pkg - 福袋核心薄壳子包。
|
||||
|
||||
原 douyin/fudai/douyin_fudai_core.py 的工具/兼容部分搬到本子包:
|
||||
|
||||
- ocr_executor _FudaiOcrExecutorState / _get_fudai_ocr_executor / _fudai_ocr_executor_state
|
||||
- thin_wrappers 11 个 [兼容] 薄壳 forwarding 函数
|
||||
|
||||
巨型 get_fudai_contain (2062 行) 留在原文件 douyin_fudai_core.py 不变。
|
||||
外部 ``from douyin.fudai.douyin_fudai_core import attend_choujiang`` 等
|
||||
完全兼容(原文件 from 子包 import 后自动暴露)。
|
||||
"""
|
||||
|
||||
from .ocr_executor import (
|
||||
_FudaiOcrExecutorState,
|
||||
_fudai_ocr_executor_state,
|
||||
_get_fudai_ocr_executor,
|
||||
)
|
||||
from .thin_wrappers import (
|
||||
attend_choujiang,
|
||||
basic_join_decision,
|
||||
check_have_reward_notice_confirm,
|
||||
check_in_order_confirm_page,
|
||||
check_lucky_draw_result,
|
||||
get_reward,
|
||||
is_watch_task_fudai,
|
||||
should_skip_fudai_by_config,
|
||||
_is_short_countdown_text,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"_FudaiOcrExecutorState",
|
||||
"_fudai_ocr_executor_state",
|
||||
"_get_fudai_ocr_executor",
|
||||
"attend_choujiang",
|
||||
"check_lucky_draw_result",
|
||||
"check_have_reward_notice_confirm",
|
||||
"check_in_order_confirm_page",
|
||||
"get_reward",
|
||||
"is_watch_task_fudai",
|
||||
"_is_short_countdown_text",
|
||||
"should_skip_fudai_by_config",
|
||||
"basic_join_decision",
|
||||
]
|
||||
@@ -0,0 +1,46 @@
|
||||
"""douyin_fudai_core_pkg.ocr_executor - OCR 线程池复用。
|
||||
|
||||
避免每次 OCR 都创建/销毁 ThreadPoolExecutor 的开销。
|
||||
线程数变化时安全销毁旧池并新建。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class _FudaiOcrExecutorState:
|
||||
def __init__(self) -> None:
|
||||
self.executor: Optional[ThreadPoolExecutor] = None
|
||||
self.workers: int = 0
|
||||
self.lock = threading.Lock()
|
||||
|
||||
|
||||
_fudai_ocr_executor_state = _FudaiOcrExecutorState()
|
||||
|
||||
|
||||
|
||||
|
||||
_fudai_ocr_executor_state = _FudaiOcrExecutorState()
|
||||
|
||||
|
||||
def _get_fudai_ocr_executor(optimal_workers: int) -> ThreadPoolExecutor:
|
||||
"""获取复用的 OCR 线程池;如线程数变化则重建。"""
|
||||
state = _fudai_ocr_executor_state
|
||||
with state.lock:
|
||||
if state.executor and state.workers == optimal_workers:
|
||||
return state.executor
|
||||
# 若线程数变化,安全关闭旧池
|
||||
if state.executor:
|
||||
try:
|
||||
state.executor.shutdown(wait=False, cancel_futures=True)
|
||||
except RuntimeError:
|
||||
pass
|
||||
state.executor = None
|
||||
executor = ThreadPoolExecutor(max_workers=optimal_workers)
|
||||
state.executor = executor
|
||||
state.workers = optimal_workers
|
||||
return executor
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""douyin_fudai_core_pkg.thin_wrappers - 11 个兼容性薄壳。
|
||||
|
||||
原 douyin/fudai/douyin_fudai_core.py 末尾 11 个 forwarding 函数全是
|
||||
``[兼容] 已迁移到 douyin.fudai.core.X`` 风格。本子模块集中存放,
|
||||
保持外部 ``from douyin.fudai.douyin_fudai_core import attend_choujiang``
|
||||
等仍然可用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def attend_choujiang(analyser) -> bool: # noqa: F811 — 兼容性 re-export
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_attend。"""
|
||||
from douyin.fudai.core.fudai_attend import attend_choujiang as _impl
|
||||
|
||||
return _impl(analyser)
|
||||
def check_lucky_draw_result(analyser): # noqa: F811 — 兼容性 re-export
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
|
||||
from douyin.fudai.core.fudai_result_checker import (
|
||||
check_lucky_draw_result as _impl,
|
||||
)
|
||||
|
||||
return _impl(analyser)
|
||||
def check_have_reward_notice_confirm(analyser) -> bool: # noqa: F811
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
|
||||
from douyin.fudai.core.fudai_result_checker import (
|
||||
check_have_reward_notice_confirm as _impl,
|
||||
)
|
||||
|
||||
return _impl(analyser)
|
||||
def check_in_order_confirm_page(analyser) -> bool: # noqa: F811
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
|
||||
from douyin.fudai.core.fudai_result_checker import (
|
||||
check_in_order_confirm_page as _impl,
|
||||
)
|
||||
|
||||
return _impl(analyser)
|
||||
def get_reward(analyser, reward_y: int = 0) -> None: # noqa: F811
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_result_checker。"""
|
||||
from douyin.fudai.core.fudai_result_checker import get_reward as _impl
|
||||
|
||||
return _impl(analyser, reward_y=reward_y)
|
||||
def is_watch_task_fudai(content: str) -> bool: # noqa: F811 — 兼容性 re-export
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
|
||||
from douyin.fudai.core.fudai_filter import is_watch_task_fudai as _impl
|
||||
|
||||
return _impl(content)
|
||||
def _is_short_countdown_text(time_text: str) -> bool: # noqa: F811
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
|
||||
from douyin.fudai.core.fudai_filter import (
|
||||
_is_short_countdown_text as _impl,
|
||||
)
|
||||
|
||||
return _impl(time_text)
|
||||
def should_skip_fudai_by_config(analyser, detail): # noqa: F811 — 兼容性 re-export
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
|
||||
from douyin.fudai.core.fudai_filter import (
|
||||
should_skip_fudai_by_config as _impl,
|
||||
)
|
||||
|
||||
return _impl(analyser, detail)
|
||||
def basic_join_decision(analyser, detail): # noqa: F811 — 兼容性 re-export
|
||||
"""[兼容] 已迁移到 douyin.fudai.core.fudai_filter。"""
|
||||
from douyin.fudai.core.fudai_filter import basic_join_decision as _impl
|
||||
|
||||
return _impl(analyser, detail)
|
||||
+26
-1813
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,31 @@
|
||||
"""douyin_fudai_finder_pkg - 福袋查找器子包。
|
||||
|
||||
原 douyin/fudai/douyin_fudai_finder.py 拆成 6 个子模块:
|
||||
|
||||
- image_acquirer FudaiImageAcquirer(图像获取与预处理)
|
||||
- detector FudaiDetector(多算法识别,最大头 930 行)
|
||||
- click_executor FudaiClickExecutor(点击执行)
|
||||
- detail_verifier FudaiDetailVerifier(详情页打开验证)
|
||||
- finder FudaiFinder(4 个组件的组合入口)
|
||||
- optimized_entry check_have_fudai_with_ready_screenshot_optimized(顶层函数)
|
||||
|
||||
外部 import 路径不变:
|
||||
``from douyin.fudai.douyin_fudai_finder import FudaiFinder`` 仍可用
|
||||
(原文件改成 re-export shim)。
|
||||
"""
|
||||
|
||||
from .image_acquirer import FudaiImageAcquirer
|
||||
from .detector import FudaiDetector
|
||||
from .click_executor import FudaiClickExecutor
|
||||
from .detail_verifier import FudaiDetailVerifier
|
||||
from .finder import FudaiFinder
|
||||
from .optimized_entry import check_have_fudai_with_ready_screenshot_optimized
|
||||
|
||||
__all__ = [
|
||||
"FudaiImageAcquirer",
|
||||
"FudaiDetector",
|
||||
"FudaiClickExecutor",
|
||||
"FudaiDetailVerifier",
|
||||
"FudaiFinder",
|
||||
"check_have_fudai_with_ready_screenshot_optimized",
|
||||
]
|
||||
@@ -0,0 +1,220 @@
|
||||
"""douyin_fudai_finder_pkg.click_executor - 点击执行器。
|
||||
|
||||
FudaiClickExecutor:根据 detector 给出的坐标执行点击,
|
||||
带 Y 偏移、防抖、重试等业务策略。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# pylint: disable=E1101
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
# OCR 预处理接口
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
# 调试图像管理器(用于保存调试截图)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
except ImportError:
|
||||
douyin_screenshot_manager = None
|
||||
|
||||
|
||||
class FudaiClickExecutor:
|
||||
"""福袋点击执行器:负责点击福袋图标"""
|
||||
|
||||
def __init__(self, analyser: Any):
|
||||
self.analyser = analyser
|
||||
self._init_resolution()
|
||||
|
||||
def _init_resolution(self):
|
||||
"""初始化分辨率信息"""
|
||||
try:
|
||||
self.rx = int(getattr(self.analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
self.ry = int(getattr(self.analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
self.rx, self.ry = 1080, 2400
|
||||
|
||||
def click(self, fudai_x: int) -> bool:
|
||||
"""点击福袋图标(点击前会检查是否是红包,避免误点)
|
||||
|
||||
参数:
|
||||
fudai_x: 福袋图标的X坐标(1080基准)
|
||||
|
||||
返回:
|
||||
是否点击成功
|
||||
"""
|
||||
start_time = time.time()
|
||||
|
||||
# 计算点击坐标
|
||||
base_y = 403 # 与检测时使用的同一水平线
|
||||
click_x = int(fudai_x * self.rx / 1080)
|
||||
click_y = int(base_y * self.ry / 2400)
|
||||
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 点击",
|
||||
"开始",
|
||||
fudai_x=fudai_x,
|
||||
click_x=click_x,
|
||||
click_y=click_y,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 点击前检查:避免误点红包
|
||||
try:
|
||||
# 检查是否有红包弹窗
|
||||
from douyin.other import douyin_popups
|
||||
|
||||
has_redpacket = douyin_popups.check_shopping_redpacket_popup(self.analyser)
|
||||
if has_redpacket:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 点击",
|
||||
"跳过(检测到红包弹窗)",
|
||||
fudai_x=fudai_x,
|
||||
note="检测到红包弹窗,避免误点红包",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
# 快速检查点击位置附近是否有红包特征(通过OCR)
|
||||
# 检查点击位置上方和下方的区域,看是否有红包关键词
|
||||
try:
|
||||
# 截图点击位置附近的区域(扩大范围以包含可能的红包文字)
|
||||
check_x1 = max(0, click_x - 150)
|
||||
check_x2 = min(self.rx, click_x + 150)
|
||||
check_y1 = max(0, click_y - 200)
|
||||
check_y2 = min(self.ry, click_y + 200)
|
||||
|
||||
# 转换为1080基准坐标
|
||||
check_x1_base = int(check_x1 * 1080 / self.rx)
|
||||
check_y1_base = int(check_y1 * 2400 / self.ry)
|
||||
check_x2_base = int(check_x2 * 1080 / self.rx)
|
||||
check_y2_base = int(check_y2 * 2400 / self.ry)
|
||||
|
||||
# 截图检查区域
|
||||
self.analyser.cut_pic(
|
||||
check_x1_base,
|
||||
check_y1_base,
|
||||
check_x2_base,
|
||||
check_y2_base,
|
||||
"",
|
||||
"檢查紅包特徵",
|
||||
)
|
||||
|
||||
# OCR识别
|
||||
name_chk = preprocess_for_ocr(self.analyser, "檢查紅包特徵")
|
||||
check_text = str(
|
||||
self.analyser.operation.analyse_pic_word(name_chk, 0) or ""
|
||||
).strip()
|
||||
|
||||
# 检查是否包含红包关键词
|
||||
redpacket_keywords = (
|
||||
"最高金额",
|
||||
"开抢",
|
||||
"邀你抢",
|
||||
"抢红包",
|
||||
"购物红包",
|
||||
"手气红包",
|
||||
)
|
||||
if check_text and any(kw in check_text for kw in redpacket_keywords):
|
||||
matched_keywords = [
|
||||
kw for kw in redpacket_keywords if kw in check_text
|
||||
]
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 点击",
|
||||
"跳过(检测到红包特征)",
|
||||
fudai_x=fudai_x,
|
||||
matched_keywords=matched_keywords,
|
||||
check_text_preview=check_text[:50],
|
||||
note="点击位置附近检测到红包特征文字,避免误点红包",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except Exception as e:
|
||||
# OCR检查失败不影响点击,继续执行
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 点击",
|
||||
"红包特征检查异常,继续点击",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 红包检查失败不影响点击,继续执行
|
||||
pass
|
||||
|
||||
# 执行点击
|
||||
try:
|
||||
device_id = getattr(self.analyser, "device_id", "")
|
||||
self.analyser.operation.click(device_id, click_x, click_y)
|
||||
|
||||
# 点击后等待足够时间让详情页加载(避免连续点击导致详情页被关闭)
|
||||
# 默认等待1.0秒,可通过 GUI 配置
|
||||
click_wait_time = float(
|
||||
getattr(self.analyser, "fudai_click_wait_seconds", 1.0) or 1.0
|
||||
)
|
||||
if click_wait_time < 1.0:
|
||||
click_wait_time = 1.0 # 最小1.0秒
|
||||
self.analyser.operation.delay(click_wait_time)
|
||||
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 点击",
|
||||
"成功",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
wait_seconds=click_wait_time,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
except Exception:
|
||||
# 回退到analyser.click
|
||||
try:
|
||||
self.analyser.click(fudai_x, base_y)
|
||||
# 回退模式也需要等待
|
||||
click_wait_time = float(
|
||||
getattr(self.analyser, "fudai_click_wait_seconds", 1.0) or 1.0
|
||||
)
|
||||
if click_wait_time < 1.0:
|
||||
click_wait_time = 1.0
|
||||
self.analyser.operation.delay(click_wait_time)
|
||||
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 点击",
|
||||
"成功(回退模式)",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
wait_seconds=click_wait_time,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
except Exception:
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 点击",
|
||||
"失败",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
error="点击异常",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
"""douyin_fudai_finder_pkg.detail_verifier - 详情页打开验证。
|
||||
|
||||
FudaiDetailVerifier:点击后验证是否成功进入福袋详情页,
|
||||
失败时反馈给上层重试或换策略。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# pylint: disable=E1101
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
# OCR 预处理接口
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
# 调试图像管理器(用于保存调试截图)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
except ImportError:
|
||||
douyin_screenshot_manager = None
|
||||
|
||||
|
||||
class FudaiDetailVerifier:
|
||||
"""福袋详情页验证器:验证是否成功打开详情页"""
|
||||
|
||||
def __init__(self, analyser: Any):
|
||||
self.analyser = analyser
|
||||
|
||||
def verify(self, max_wait_seconds: float = 2.0) -> bool:
|
||||
"""验证是否成功打开福袋详情页
|
||||
|
||||
参数:
|
||||
max_wait_seconds: 最大等待时间(秒)
|
||||
|
||||
返回:
|
||||
是否成功打开详情页
|
||||
"""
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
# 等待界面加载(增加等待时间,确保详情页完全加载)
|
||||
# 点击后已经等待了2.5秒,这里再等待0.8秒,总共约3.3秒
|
||||
verify_initial_wait = float(
|
||||
getattr(self.analyser, "fudai_verify_initial_wait_seconds", 0.8) or 0.8
|
||||
)
|
||||
if verify_initial_wait < 0.5:
|
||||
verify_initial_wait = 0.5 # 最小0.5秒
|
||||
self.analyser.operation.delay(verify_initial_wait)
|
||||
|
||||
# 多次检查,直到超时或检测到详情页
|
||||
check_interval = 0.3
|
||||
checks = 0
|
||||
max_checks = int(max_wait_seconds / check_interval) + 1
|
||||
|
||||
while checks < max_checks:
|
||||
# 刷新截图
|
||||
try:
|
||||
self.analyser.operation.get_screenshot(
|
||||
self.analyser.device_id, use_service=False
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检查是否在详情页(已移除任务数量检测,仅使用OCR检测)
|
||||
# 额外检测:在指定区域检测"邀你抢红包"文字
|
||||
# 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400)
|
||||
try:
|
||||
y_pianyi = int(getattr(self.analyser, "y_pianyi", 0) or 0)
|
||||
|
||||
# 保存完整截图并标注OCR区域
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(pic_path):
|
||||
pic = Image.open(pic_path)
|
||||
pic.load()
|
||||
pic_rgb = pic.convert("RGB")
|
||||
|
||||
width, height = pic_rgb.size
|
||||
rx = int(
|
||||
getattr(self.analyser, "resolution_ratio_x", 1080)
|
||||
or 1080
|
||||
)
|
||||
ry = int(
|
||||
getattr(self.analyser, "resolution_ratio_y", 2400)
|
||||
or 2400
|
||||
)
|
||||
|
||||
x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545
|
||||
x1 = int(x1_base * width / rx)
|
||||
y1 = int((y1_base + y_pianyi) * height / ry)
|
||||
x2 = int(x2_base * width / rx)
|
||||
y2 = int((y2_base + y_pianyi) * height / ry)
|
||||
|
||||
x1 = max(0, min(x1, width - 1))
|
||||
y1 = max(0, min(y1, height - 1))
|
||||
x2 = max(0, min(x2, width - 1))
|
||||
y2 = max(0, min(y2, height - 1))
|
||||
|
||||
if x1 < x2 and y1 < y2:
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb,
|
||||
operation_type="ocr",
|
||||
picname="验证邀你抢红包区域",
|
||||
step="before_ocr",
|
||||
coords=(x1, y1, x2, y2),
|
||||
extra_info={
|
||||
"region": f"({x1_base},{y1_base})-({x2_base},{y2_base})",
|
||||
"size": f"{x2_base-x1_base}x{y2_base-y1_base}",
|
||||
"y_offset": y_pianyi,
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"OCR识别前保存完整截图(验证邀你抢红包区域)",
|
||||
path=debug_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# cut_pic 方法内部会根据分辨率自动缩放,所以直接传入基准坐标
|
||||
self.analyser.cut_pic(
|
||||
238, 454, 847, 545, "", "验证邀你抢红包区域", y_pianyi
|
||||
)
|
||||
name_invite = preprocess_for_ocr(
|
||||
self.analyser, "验证邀你抢红包区域"
|
||||
)
|
||||
ocr_text = str(
|
||||
self.analyser.operation.analyse_pic_word(name_invite, 0) or ""
|
||||
)
|
||||
|
||||
# 如果模式0未识别到,尝试模式1
|
||||
enable_ocr_mode1 = bool(
|
||||
getattr(self.analyser, "enable_ocr_mode1", False)
|
||||
)
|
||||
if enable_ocr_mode1 and (
|
||||
not ocr_text
|
||||
or not any(
|
||||
kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气")
|
||||
)
|
||||
):
|
||||
name_invite1 = preprocess_for_ocr(
|
||||
self.analyser, "验证邀你抢红包区域"
|
||||
)
|
||||
ocr_text = str(
|
||||
self.analyser.operation.analyse_pic_word(name_invite1, 1)
|
||||
or ""
|
||||
)
|
||||
|
||||
# 检测是否包含"邀你抢红包"相关关键词(支持变体)
|
||||
# 关键词包括:"邀你抢红包"、"邀你抢手气红包"、"邀你抢"等
|
||||
redpacket_keywords = (
|
||||
"邀你抢红包",
|
||||
"邀你抢手气红包",
|
||||
"邀你抢",
|
||||
"抢红包",
|
||||
"抢手气",
|
||||
)
|
||||
if ocr_text and any(kw in ocr_text for kw in redpacket_keywords):
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 验证",
|
||||
"成功打开详情页(检测到邀你抢红包)",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
checks=checks + 1,
|
||||
ocr_text=ocr_text[:50],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 额外等待,确保参与按钮加载完成
|
||||
# 验证时只检测了详情页是否打开,但参与按钮可能需要额外时间加载
|
||||
button_wait_time = float(
|
||||
getattr(
|
||||
self.analyser, "fudai_button_load_wait_seconds", 0.5
|
||||
)
|
||||
or 0.5
|
||||
)
|
||||
if button_wait_time > 0:
|
||||
try:
|
||||
self.analyser.operation.delay(button_wait_time)
|
||||
except Exception:
|
||||
time.sleep(button_wait_time)
|
||||
|
||||
# 设置标志,表示详情页已经验证过,后续读取详情时可以缩短等待时间
|
||||
# 同时设置重试标志,如果任务数为0可以重试一次
|
||||
try:
|
||||
self.analyser._fudai_detail_verified = True
|
||||
self.analyser._fudai_detail_verified_retry = True
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
except Exception:
|
||||
# OCR检测失败不影响其他检测方式
|
||||
pass
|
||||
|
||||
checks += 1
|
||||
if checks < max_checks:
|
||||
self.analyser.operation.delay(check_interval)
|
||||
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 验证",
|
||||
"未检测到详情页",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
checks=checks,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except Exception as e:
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 验证",
|
||||
"异常",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
"""douyin_fudai_finder_pkg.detect_by_template - 模板匹配检测福袋图标。
|
||||
|
||||
从 FudaiDetector 类拆出,纯函数形式接受 (analyser, rx, pic, region)。
|
||||
类内保留 1 行 forwarding 调用本函数。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# pylint: disable=E1101
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def detect_by_template(analyser, rx: int, pic: Image.Image, region: Dict) -> Optional[int]:
|
||||
"""使用模板匹配在指定区域查找福袋图标(优化版:多方法+预处理)
|
||||
|
||||
参数:
|
||||
pic: PIL Image对象
|
||||
region: 搜索区域配置
|
||||
|
||||
返回:
|
||||
检测到的X坐标(1080基准),未找到返回None
|
||||
"""
|
||||
# pyright: ignore[reportUnknownMemberType, reportAttributeAccessIssue]
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
import cv2 # type: ignore[import-untyped]
|
||||
import numpy as np
|
||||
except ImportError:
|
||||
return None
|
||||
|
||||
# 获取模板路径
|
||||
try:
|
||||
# path_config 已在文件顶部导入,直接使用
|
||||
template_path = path_config.get_assets_dir() + "/fudai.png"
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
base_dir = os.path.dirname(__file__)
|
||||
template_path = os.path.join(base_dir, "assets", "fudai.png")
|
||||
if not os.path.exists(template_path):
|
||||
return None
|
||||
|
||||
# 获取匹配阈值
|
||||
try:
|
||||
threshold = float(
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.6) or 0.6
|
||||
)
|
||||
except Exception:
|
||||
threshold = 0.6 # 降低默认阈值,因为添加了多种匹配方法
|
||||
|
||||
# 读取模板(彩色和灰度)
|
||||
template_color = cv2.imread(template_path, cv2.IMREAD_COLOR) # type: ignore[attr-defined, misc]
|
||||
template_gray = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE) # type: ignore[attr-defined, misc]
|
||||
if template_color is None or template_gray is None:
|
||||
return None
|
||||
|
||||
width, height = pic.size
|
||||
pic_rgb = pic.convert("RGB")
|
||||
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR) # type: ignore[attr-defined, misc]
|
||||
|
||||
# 提取搜索区域(扩大Y范围用于模板匹配,提高成功率)
|
||||
if "y_top" in region:
|
||||
# 中间区域(矩形)
|
||||
x1 = max(0, min(region.get("x1", 0), width))
|
||||
x2 = max(0, min(region.get("x2", width), width))
|
||||
y_top = max(0, min(region.get("y_top", 0), height))
|
||||
y_bottom = max(0, min(region.get("y_bottom", height), height))
|
||||
else:
|
||||
# 水平带区域:扩大Y范围用于模板匹配(从7像素扩大到30像素)
|
||||
x1 = max(0, min(region.get("x1", 0), width))
|
||||
x2 = max(0, min(region.get("x2", width), width))
|
||||
scan_y = region.get("y", 0)
|
||||
y_range = region.get("y_range", 7)
|
||||
# 模板匹配需要更大的Y范围
|
||||
template_match_y_range = max(30, y_range * 4) # 至少30像素
|
||||
y_top = max(0, scan_y - template_match_y_range // 2)
|
||||
y_bottom = min(height, scan_y + template_match_y_range // 2 + 1)
|
||||
|
||||
if x1 >= x2 or y_top >= y_bottom:
|
||||
return None
|
||||
|
||||
search_roi_bgr = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index]
|
||||
if search_roi_bgr.size == 0:
|
||||
return None
|
||||
|
||||
# 转换为灰度图(用于灰度匹配)
|
||||
search_roi_gray = cv2.cvtColor(search_roi_bgr, cv2.COLOR_BGR2GRAY) # type: ignore[attr-defined, misc]
|
||||
|
||||
# 图像预处理:增强对比度和去噪
|
||||
try:
|
||||
# 直方图均衡化(增强对比度)
|
||||
search_roi_gray_enhanced = cv2.equalizeHist(search_roi_gray) # type: ignore[attr-defined, misc]
|
||||
template_gray_enhanced = cv2.equalizeHist(template_gray) # type: ignore[attr-defined, misc]
|
||||
except Exception:
|
||||
search_roi_gray_enhanced = search_roi_gray
|
||||
template_gray_enhanced = template_gray
|
||||
|
||||
th, tw = template_color.shape[:2]
|
||||
rh, rw = search_roi_bgr.shape[:2]
|
||||
|
||||
# 多尺度+多方法模板匹配
|
||||
best_score = -1.0
|
||||
best_x = None
|
||||
best_scale = 1.0
|
||||
best_method = ""
|
||||
|
||||
# 缩放比例范围:0.7 到 1.3(扩大范围)
|
||||
scales = [1.0, 0.9, 1.1, 0.8, 1.2, 0.7, 1.3]
|
||||
|
||||
# 多种匹配方法(按优先级排序)
|
||||
match_methods = [
|
||||
(cv2.TM_CCOEFF_NORMED, "CCOEFF_NORMED"), # type: ignore[attr-defined, misc] # 归一化相关系数(最常用)
|
||||
(cv2.TM_CCORR_NORMED, "CCORR_NORMED"), # type: ignore[attr-defined, misc] # 归一化相关匹配
|
||||
(cv2.TM_SQDIFF_NORMED, "SQDIFF_NORMED"), # type: ignore[attr-defined, misc] # 归一化平方差(值越小越好)
|
||||
]
|
||||
|
||||
for scale in scales:
|
||||
scaled_tw = max(1, int(tw * scale))
|
||||
scaled_th = max(1, int(th * scale))
|
||||
|
||||
# 如果缩放后的模板太大,跳过
|
||||
if scaled_th > rh or scaled_tw > rw:
|
||||
continue
|
||||
|
||||
# 缩放模板(彩色和灰度)
|
||||
scaled_template_color = cv2.resize(template_color, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
|
||||
scaled_template_gray = cv2.resize(template_gray, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
|
||||
scaled_template_gray_enhanced = cv2.resize(template_gray_enhanced, (scaled_tw, scaled_th)) # type: ignore[attr-defined, misc]
|
||||
|
||||
# 尝试多种匹配方法
|
||||
for method, method_name in match_methods:
|
||||
try:
|
||||
# 方法1:彩色匹配
|
||||
res_color = cv2.matchTemplate( # type: ignore[attr-defined, misc]
|
||||
search_roi_bgr, scaled_template_color, method
|
||||
)
|
||||
if method == cv2.TM_SQDIFF_NORMED:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) # type: ignore[attr-defined, misc]
|
||||
score = 1.0 - max_val # SQDIFF值越小越好,转换为越大越好
|
||||
else:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_color) # type: ignore[attr-defined, misc]
|
||||
score = max_val
|
||||
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_x = max_loc[0]
|
||||
best_scale = scale
|
||||
best_method = f"{method_name}_color"
|
||||
|
||||
# 方法2:灰度匹配(更稳定,不受光照影响)
|
||||
res_gray = cv2.matchTemplate( # type: ignore[attr-defined, misc]
|
||||
search_roi_gray, scaled_template_gray, method
|
||||
)
|
||||
if method == cv2.TM_SQDIFF_NORMED:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) # type: ignore[attr-defined, misc]
|
||||
score = 1.0 - max_val
|
||||
else:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res_gray) # type: ignore[attr-defined, misc]
|
||||
score = max_val
|
||||
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_x = max_loc[0]
|
||||
best_scale = scale
|
||||
best_method = f"{method_name}_gray"
|
||||
|
||||
# 方法3:增强对比度后的灰度匹配
|
||||
res_gray_enhanced = cv2.matchTemplate( # type: ignore[attr-defined, misc]
|
||||
search_roi_gray_enhanced, scaled_template_gray_enhanced, method
|
||||
)
|
||||
if method == cv2.TM_SQDIFF_NORMED:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined, misc]
|
||||
res_gray_enhanced
|
||||
)
|
||||
score = 1.0 - max_val
|
||||
else:
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined, misc]
|
||||
res_gray_enhanced
|
||||
)
|
||||
score = max_val
|
||||
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_x = max_loc[0]
|
||||
best_scale = scale
|
||||
best_method = f"{method_name}_gray_enhanced"
|
||||
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 如果所有方法都失败,回退到单尺度单方法匹配
|
||||
if best_score < 0:
|
||||
# 如果模板太大,缩小模板
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
if scale > 0:
|
||||
template_color = cv2.resize( # type: ignore[attr-defined, misc]
|
||||
template_color,
|
||||
(max(1, int(tw * scale)), max(1, int(th * scale))),
|
||||
)
|
||||
template_gray = cv2.resize( # type: ignore[attr-defined, misc]
|
||||
template_gray,
|
||||
(max(1, int(tw * scale)), max(1, int(th * scale))),
|
||||
)
|
||||
th, tw = template_color.shape[:2]
|
||||
|
||||
if th <= rh and tw <= rw:
|
||||
try:
|
||||
res = cv2.matchTemplate( # type: ignore[attr-defined, misc]
|
||||
search_roi_bgr, template_color, cv2.TM_CCOEFF_NORMED
|
||||
)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res) # type: ignore[attr-defined, misc]
|
||||
best_score = max_val
|
||||
best_x = max_loc[0]
|
||||
best_scale = 1.0
|
||||
best_method = "CCOEFF_NORMED_color_fallback"
|
||||
except Exception:
|
||||
best_score = -1.0
|
||||
best_x = None
|
||||
best_scale = 1.0
|
||||
best_method = ""
|
||||
else:
|
||||
best_score = -1.0
|
||||
best_x = None
|
||||
best_scale = 1.0
|
||||
best_method = ""
|
||||
|
||||
max_val = best_score
|
||||
max_loc = (best_x, 0) if best_x is not None else (0, 0)
|
||||
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[福袋查找] 模板匹配",
|
||||
f"{region['name']}",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
score=round(max_val, 4),
|
||||
threshold=threshold,
|
||||
passed=bool(max_val >= threshold),
|
||||
best_scale=round(best_scale, 2) if best_score >= 0 else None,
|
||||
best_method=best_method if best_method else None,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 保存模板匹配的调试图像(无论成功与否)- 使用完整截图
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
# Image 已在文件顶部导入
|
||||
|
||||
# 使用完整截图而不是搜索区域ROI
|
||||
pic_rgb = pic.convert("RGB")
|
||||
|
||||
# 计算匹配位置在完整截图中的坐标(如果匹配成功)
|
||||
match_coords = None
|
||||
if max_val >= threshold and best_x is not None:
|
||||
try:
|
||||
best_tw = int(tw * best_scale) if best_score >= 0 else tw
|
||||
best_th = int(th * best_scale) if best_score >= 0 else th
|
||||
# 匹配位置在ROI内的坐标
|
||||
match_x1_in_roi = best_x
|
||||
match_y1_in_roi = 0
|
||||
match_x2_in_roi = best_x + best_tw
|
||||
match_y2_in_roi = best_th
|
||||
# 转换为完整截图坐标
|
||||
match_x1 = x1 + match_x1_in_roi
|
||||
match_y1 = y_top + match_y1_in_roi
|
||||
match_x2 = x1 + match_x2_in_roi
|
||||
match_y2 = y_top + match_y2_in_roi
|
||||
match_coords = (match_x1, match_y1, match_x2, match_y2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 使用搜索区域坐标作为主要标注,匹配位置作为额外信息
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb,
|
||||
operation_type="template_match",
|
||||
picname="fudai_icon",
|
||||
step="matched" if max_val >= threshold else "failed",
|
||||
coords=(x1, y_top, x2, y_bottom), # 搜索区域坐标
|
||||
extra_info={
|
||||
"region": region.get("name", "unknown"),
|
||||
"score": round(max_val, 4),
|
||||
"threshold": threshold,
|
||||
"passed": bool(max_val >= threshold),
|
||||
"best_scale": round(best_scale, 2) if best_score >= 0 else None,
|
||||
"template_size": f"{tw}x{th}",
|
||||
"search_size": f"{rw}x{rh}",
|
||||
"match_coords": match_coords, # 匹配位置坐标(如果匹配成功)
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
f"模板匹配{'成功' if max_val >= threshold else '失败'}",
|
||||
path=debug_path,
|
||||
region=region.get("name", "unknown"),
|
||||
score=round(max_val, 4),
|
||||
threshold=threshold,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if max_val >= threshold:
|
||||
detected_x_in_roi = max_loc[0]
|
||||
# 使用最佳匹配时的模板宽度计算中心点
|
||||
best_tw = int(tw * best_scale) if best_score >= 0 else tw
|
||||
detected_x = int(
|
||||
(x1 + detected_x_in_roi + best_tw // 2) * 1080.0 / max(1, rx)
|
||||
)
|
||||
return detected_x
|
||||
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,655 @@
|
||||
"""douyin_fudai_finder_pkg.detector - 福袋图标识别器(最大头)。
|
||||
|
||||
FudaiDetector:组合模板匹配、OCR、特征点匹配等多种方式定位福袋图标,
|
||||
返回点击坐标与置信度。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# pylint: disable=E1101
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from .detect_by_template import detect_by_template as _impl_detect_by_template
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
# OCR 预处理接口
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
# 调试图像管理器(用于保存调试截图)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
except ImportError:
|
||||
douyin_screenshot_manager = None
|
||||
|
||||
|
||||
class FudaiDetector:
|
||||
"""福袋识别器:负责检测福袋图标位置"""
|
||||
|
||||
def __init__(self, analyser: Any):
|
||||
self.analyser = analyser
|
||||
self._init_resolution()
|
||||
self._init_search_regions()
|
||||
|
||||
def _init_resolution(self):
|
||||
"""初始化分辨率信息"""
|
||||
try:
|
||||
self.rx = int(getattr(self.analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
self.ry = int(getattr(self.analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
self.y_pianyi = int(getattr(self.analyser, "y_pianyi", 0) or 0)
|
||||
except Exception:
|
||||
self.rx, self.ry, self.y_pianyi = 1080, 2400, 0
|
||||
|
||||
# 记录调试图像管理器状态
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 初始化",
|
||||
f"调试图像管理器状态: {'可用' if douyin_screenshot_manager else '不可用'}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _init_search_regions(self):
|
||||
"""初始化搜索区域
|
||||
|
||||
实际福袋出现区域:(153, 348) 到 (561, 451) [基于1080x2400基准]
|
||||
只在此区域内搜索,不扩大搜索范围
|
||||
"""
|
||||
# 实际福袋区域(X=153-561, Y=348-451)
|
||||
# 这是用户确认的福袋实际出现区域,只在此区域内搜索
|
||||
self.search_regions = [
|
||||
{
|
||||
"name": "实际福袋区域",
|
||||
"priority": 1,
|
||||
"x1": 153 * self.rx // 1080,
|
||||
"x2": 561 * self.rx // 1080,
|
||||
"y_top": 348 * self.ry // 2400 + self.y_pianyi,
|
||||
"y_bottom": 451 * self.ry // 2400 + self.y_pianyi,
|
||||
"y": (348 + 451) // 2 * self.ry // 2400 + self.y_pianyi, # 中心Y坐标
|
||||
"y_range": (451 - 348) // 2 + 1, # 覆盖整个Y范围
|
||||
},
|
||||
]
|
||||
|
||||
def detect_by_pixel(self, pic: Image.Image, region: Dict) -> Optional[int]:
|
||||
"""使用像素检测在指定区域查找福袋图标
|
||||
|
||||
参数:
|
||||
pic: PIL Image对象
|
||||
region: 搜索区域配置
|
||||
|
||||
返回:
|
||||
检测到的X坐标(1080基准),未找到返回None
|
||||
"""
|
||||
start_time = time.time()
|
||||
width, height = pic.size
|
||||
|
||||
# 提取区域参数
|
||||
x1 = max(0, min(region.get("x1", 0), width))
|
||||
x2 = max(0, min(region.get("x2", width), width))
|
||||
|
||||
# 支持两种区域配置方式:
|
||||
# 1. 使用 y_top 和 y_bottom(精确范围)
|
||||
# 2. 使用 y 和 y_range(中心点+范围)
|
||||
# 初始化变量,避免未绑定错误
|
||||
scan_y: int = 0
|
||||
y_range: int = 7
|
||||
if "y_top" in region and "y_bottom" in region:
|
||||
y_top = max(0, min(int(region.get("y_top", 0)), height))
|
||||
y_bottom = max(0, min(int(region.get("y_bottom", height)), height))
|
||||
else:
|
||||
scan_y = region.get("y", 0)
|
||||
y_range = region.get("y_range", 7)
|
||||
if not (0 <= scan_y < height):
|
||||
# 记录无效区域配置
|
||||
try:
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 像素检测",
|
||||
f"{region['name']}区域无效(Y坐标超出范围)",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
region=region["name"],
|
||||
scan_y=scan_y,
|
||||
height=height,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
y_top = max(0, scan_y - y_range // 2)
|
||||
y_bottom = min(height, scan_y + y_range // 2 + 1)
|
||||
|
||||
if x1 >= x2 or y_top >= y_bottom:
|
||||
# 记录无效区域配置
|
||||
try:
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 像素检测",
|
||||
f"{region['name']}区域无效(坐标范围错误)",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
region=region["name"],
|
||||
x1=x1,
|
||||
x2=x2,
|
||||
y_top=y_top,
|
||||
y_bottom=y_bottom,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
|
||||
# 使用numpy加速
|
||||
roi = pic.crop((x1, y_top, x2, y_bottom)).convert("RGB")
|
||||
arr = np.array(roi)
|
||||
|
||||
if arr.size == 0:
|
||||
return None
|
||||
|
||||
r = arr[:, :, 0] # type: ignore[index]
|
||||
g = arr[:, :, 1] # type: ignore[index]
|
||||
b = arr[:, :, 2] # type: ignore[index]
|
||||
|
||||
# 福袋图标颜色范围(优化后的范围)
|
||||
mask = (
|
||||
(r >= 190) # type: ignore[operator]
|
||||
& (r <= 206) # type: ignore[operator]
|
||||
& (g >= 173) # type: ignore[operator]
|
||||
& (g <= 196) # type: ignore[operator]
|
||||
& (b >= 234) # type: ignore[operator]
|
||||
& (b <= 250) # type: ignore[operator]
|
||||
)
|
||||
|
||||
# 检查每一列是否有足够多的匹配像素
|
||||
cols = np.sum(mask, axis=0)
|
||||
valid_cols = cols >= 2 # 至少2个像素匹配
|
||||
|
||||
if valid_cols.any():
|
||||
# 优化:从最优位置开始向左右两侧搜索
|
||||
roi_width = x2 - x1
|
||||
|
||||
# 获取最优搜索起始位置(使用历史记录或默认值)
|
||||
try:
|
||||
# 尝试获取上次找到的福袋位置(1080基准)
|
||||
last_fudai_x = int(getattr(self.analyser, "last_fudai_x", 0) or 0)
|
||||
if last_fudai_x > 0:
|
||||
optimal_x_scaled = last_fudai_x * self.rx // 1080
|
||||
optimal_col = optimal_x_scaled - x1
|
||||
if optimal_col < 0 or optimal_col >= roi_width:
|
||||
# 如果历史位置不在当前区域内,使用区域中心
|
||||
optimal_col = roi_width // 2
|
||||
else:
|
||||
# 使用区域中心作为最优位置
|
||||
optimal_col = roi_width // 2
|
||||
except Exception:
|
||||
# 使用区域中心作为最优位置
|
||||
optimal_col = roi_width // 2
|
||||
|
||||
optimal_col = max(0, min(optimal_col, roi_width - 1))
|
||||
|
||||
# 从最优位置开始,向左右两侧交替搜索
|
||||
found_col = None
|
||||
search_range = max(optimal_col, roi_width - optimal_col)
|
||||
|
||||
# 先检查最优位置本身
|
||||
if valid_cols[optimal_col]:
|
||||
found_col = optimal_col
|
||||
else:
|
||||
# 向左右两侧交替搜索
|
||||
for offset in range(1, search_range + 1):
|
||||
# 先检查右侧
|
||||
right_col = optimal_col + offset
|
||||
if right_col < roi_width and valid_cols[right_col]:
|
||||
found_col = right_col
|
||||
break
|
||||
# 再检查左侧
|
||||
left_col = optimal_col - offset
|
||||
if left_col >= 0 and valid_cols[left_col]:
|
||||
found_col = left_col
|
||||
break
|
||||
|
||||
# 如果没找到,回退到原来的方法(从右往左)
|
||||
if found_col is None:
|
||||
valid_cols_reversed = valid_cols[::-1]
|
||||
col_idx_reversed = int(np.argmax(valid_cols_reversed))
|
||||
found_col = len(valid_cols) - 1 - col_idx_reversed
|
||||
|
||||
detected_x = int((x1 + found_col) * 1080.0 / max(1, self.rx))
|
||||
|
||||
# 保存找到的位置作为下次的最优位置
|
||||
try:
|
||||
self.analyser.last_fudai_x = detected_x
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 保存调试图像(标注检测区域)
|
||||
try:
|
||||
if douyin_screenshot_manager:
|
||||
debug_coords = (x1, y_top, x2, y_bottom)
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic,
|
||||
operation_type="detection",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=debug_coords,
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"detected_x_scaled": x1 + found_col,
|
||||
"region": region["name"],
|
||||
"color_range": "R:190-206,G:173-196,B:234-250",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标像素检测命中保存",
|
||||
path=debug_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[调试图像]", "福袋图标像素检测命中但截图管理器不可用"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[调试图像]", "福袋图标像素检测命中保存失败", error=str(e)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 像素检测",
|
||||
f"{region['name']}命中",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
x=detected_x,
|
||||
region=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
optimal_col=optimal_col,
|
||||
found_col=found_col,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return detected_x
|
||||
except ImportError:
|
||||
# numpy不可用,回退到逐像素检测
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 回退到逐像素检测(从最优位置开始向左右两侧搜索)
|
||||
try:
|
||||
pix = pic.load()
|
||||
y_range_int = int(y_range) if y_range is not None else 7
|
||||
|
||||
# 获取最优搜索起始位置(使用历史记录或默认值)
|
||||
try:
|
||||
# 尝试获取上次找到的福袋位置(1080基准)
|
||||
last_fudai_x = int(getattr(self.analyser, "last_fudai_x", 0) or 0)
|
||||
if last_fudai_x > 0:
|
||||
optimal_x_scaled = last_fudai_x * self.rx // 1080
|
||||
if optimal_x_scaled < x1 or optimal_x_scaled >= x2:
|
||||
# 如果历史位置不在当前区域内,使用区域中心
|
||||
optimal_x_scaled = (x1 + x2) // 2
|
||||
else:
|
||||
# 使用区域中心作为最优位置
|
||||
optimal_x_scaled = (x1 + x2) // 2
|
||||
except Exception:
|
||||
# 使用区域中心作为最优位置
|
||||
optimal_x_scaled = (x1 + x2) // 2
|
||||
|
||||
optimal_x_scaled = max(x1, min(optimal_x_scaled, x2 - 1))
|
||||
|
||||
for offset_y in range(-y_range_int // 2, y_range_int // 2 + 1):
|
||||
check_y = scan_y + offset_y
|
||||
if not (0 <= check_y < height):
|
||||
continue
|
||||
|
||||
# 优化:从最优位置开始向左右两侧搜索
|
||||
found_x = None
|
||||
search_range = max(optimal_x_scaled - x1, x2 - optimal_x_scaled)
|
||||
|
||||
# 先检查最优位置本身
|
||||
try:
|
||||
px = pix[optimal_x_scaled, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = optimal_x_scaled
|
||||
except (IndexError, TypeError):
|
||||
pass
|
||||
|
||||
# 如果最优位置没找到,向左右两侧交替搜索
|
||||
if found_x is None:
|
||||
for offset in range(1, search_range + 1):
|
||||
# 先检查右侧
|
||||
right_x = optimal_x_scaled + offset
|
||||
if right_x < x2:
|
||||
try:
|
||||
px = pix[right_x, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = right_x
|
||||
break
|
||||
except (IndexError, TypeError):
|
||||
continue
|
||||
|
||||
# 再检查左侧
|
||||
left_x = optimal_x_scaled - offset
|
||||
if left_x >= x1:
|
||||
try:
|
||||
px = pix[left_x, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = left_x
|
||||
break
|
||||
except (IndexError, TypeError):
|
||||
continue
|
||||
|
||||
# 如果还是没找到,回退到原来的方法(从右往左)
|
||||
if found_x is None:
|
||||
for x_scaled in range(x2 - 1, x1 - 1, -1):
|
||||
try:
|
||||
px = pix[x_scaled, check_y]
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
found_x = x_scaled
|
||||
break
|
||||
except (IndexError, TypeError):
|
||||
continue
|
||||
|
||||
if found_x is not None:
|
||||
detected_x = int(found_x * 1080.0 / max(1, self.rx))
|
||||
|
||||
# 保存找到的位置作为下次的最优位置
|
||||
try:
|
||||
self.analyser.last_fudai_x = detected_x
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 保存调试图像(标注检测区域)
|
||||
try:
|
||||
if douyin_screenshot_manager:
|
||||
debug_coords = (x1, y_top, x2, y_bottom)
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic,
|
||||
operation_type="detection",
|
||||
picname="fudai_icon",
|
||||
step="detected_fallback",
|
||||
coords=debug_coords,
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"detected_x_scaled": found_x,
|
||||
"region": region["name"],
|
||||
"color_range": "R:190-206,G:173-196,B:234-250",
|
||||
"mode": "fallback_pixel_search",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标逐像素检测命中保存",
|
||||
path=debug_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标逐像素检测命中但截图管理器不可用",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标逐像素检测命中保存失败",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
pass # 调试图像保存失败不影响主流程
|
||||
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 像素检测",
|
||||
f"{region['name']}命中(回退模式,从最优位置搜索)",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return detected_x
|
||||
if found_x is not None:
|
||||
break # 找到后退出offset_y循环
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
def detect_by_template(self, pic: Image.Image, region: Dict) -> Optional[int]:
|
||||
return _impl_detect_by_template(self.analyser, self.rx, pic, region)
|
||||
def detect(self, pic: Image.Image) -> Tuple[Optional[int], str]:
|
||||
"""检测福袋图标位置(按优先级搜索,像素检测后需模板匹配确认)
|
||||
|
||||
参数:
|
||||
pic: PIL Image对象
|
||||
|
||||
返回:
|
||||
(检测到的X坐标(1080基准),检测方法) 或 (None, "")
|
||||
检测方法: "pixel" 或 "template"
|
||||
"""
|
||||
overall_start = time.time()
|
||||
|
||||
# 检查是否启用模板匹配
|
||||
try:
|
||||
template_match_enabled = bool(
|
||||
getattr(self.analyser, "fudai_template_match_enabled", False)
|
||||
)
|
||||
except Exception:
|
||||
template_match_enabled = False # 默认关闭模板匹配
|
||||
|
||||
# 按优先级搜索
|
||||
regions_checked = []
|
||||
for region in self.search_regions:
|
||||
regions_checked.append(region["name"])
|
||||
# 优先使用像素检测(更快)
|
||||
detected_x = self.detect_by_pixel(pic, region)
|
||||
if detected_x is not None:
|
||||
# 如果模板匹配已关闭,直接返回像素检测结果
|
||||
if not template_match_enabled:
|
||||
overall_elapsed = (time.time() - overall_start) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 检测完成",
|
||||
"像素检测命中(模板匹配已关闭)",
|
||||
total_elapsed_ms=round(overall_elapsed, 2),
|
||||
region=region["name"],
|
||||
x=detected_x,
|
||||
method="pixel",
|
||||
note="模板匹配已禁用,直接使用像素检测结果",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return detected_x, "pixel"
|
||||
|
||||
# 像素检测命中后,使用模板匹配确认
|
||||
# 在整个检测区域内进行模板匹配,而不是只在检测位置附近
|
||||
# 这样可以处理像素检测位置偏差的情况
|
||||
try:
|
||||
width, height = pic.size
|
||||
|
||||
# 确定Y范围(与检测区域相同)
|
||||
if "y_top" in region and "y_bottom" in region:
|
||||
confirm_y_top = max(0, min(int(region.get("y_top", 0)), height))
|
||||
confirm_y_bottom = max(
|
||||
0, min(int(region.get("y_bottom", height)), height)
|
||||
)
|
||||
else:
|
||||
scan_y = region.get("y", 0)
|
||||
y_range = region.get("y_range", 7)
|
||||
confirm_y_top = max(0, scan_y - y_range // 2)
|
||||
confirm_y_bottom = min(height, scan_y + y_range // 2 + 1)
|
||||
|
||||
# 使用整个检测区域进行模板匹配确认(而不是只在检测位置附近)
|
||||
# 这样可以处理像素检测位置偏差的情况
|
||||
confirm_region = {
|
||||
"name": f"{region['name']}-模板确认",
|
||||
"x1": max(0, min(region.get("x1", 0), width)),
|
||||
"x2": max(0, min(region.get("x2", width), width)),
|
||||
"y_top": confirm_y_top,
|
||||
"y_bottom": confirm_y_bottom,
|
||||
}
|
||||
|
||||
# 进行模板匹配确认(在整个检测区域内搜索)
|
||||
template_confirmed_x = self.detect_by_template(pic, confirm_region)
|
||||
|
||||
if template_confirmed_x is not None:
|
||||
# 模板匹配确认成功
|
||||
overall_elapsed = (time.time() - overall_start) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 检测完成",
|
||||
"像素检测+模板确认命中",
|
||||
total_elapsed_ms=round(overall_elapsed, 2),
|
||||
region=region["name"],
|
||||
pixel_x=detected_x,
|
||||
template_x=template_confirmed_x,
|
||||
method="pixel+template",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 使用模板匹配确认的X坐标(更准确)
|
||||
return template_confirmed_x, "pixel+template"
|
||||
else:
|
||||
# 模板匹配未确认,检查是否应该信任像素检测结果
|
||||
# 检查配置:是否允许在模板匹配失败时信任像素检测
|
||||
try:
|
||||
trust_pixel_when_template_fails = bool(
|
||||
getattr(
|
||||
self.analyser,
|
||||
"fudai_trust_pixel_when_template_fails",
|
||||
True,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
trust_pixel_when_template_fails = True # 默认信任
|
||||
|
||||
# 如果配置允许,且像素检测在可信区域命中,信任像素检测
|
||||
if trust_pixel_when_template_fails:
|
||||
if region.get("name") == "实际福袋区域":
|
||||
# 信任像素检测结果
|
||||
overall_elapsed = (time.time() - overall_start) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 检测完成",
|
||||
"像素检测命中(模板确认失败但信任像素检测)",
|
||||
total_elapsed_ms=round(overall_elapsed, 2),
|
||||
region=region["name"],
|
||||
x=detected_x,
|
||||
method="pixel",
|
||||
note="模板匹配失败但像素检测在可信区域命中,信任像素检测结果",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return detected_x, "pixel"
|
||||
|
||||
# 不信任,返回未找到(不再扩大搜索范围)
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 像素检测命中但模板确认失败",
|
||||
f"{region['name']}",
|
||||
pixel_x=detected_x,
|
||||
confirm_region=f"({confirm_region['x1']},{confirm_y_top})-({confirm_region['x2']},{confirm_y_bottom})",
|
||||
说明="在整个检测区域内未找到模板匹配,不再扩大搜索范围",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 不再继续搜索,直接返回未找到
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
# 模板确认过程异常,信任像素检测结果
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 模板确认异常",
|
||||
f"{region['name']}",
|
||||
pixel_x=detected_x,
|
||||
error=str(e),
|
||||
说明="信任像素检测结果",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
overall_elapsed = (time.time() - overall_start) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 检测完成",
|
||||
"像素检测命中(模板确认异常)",
|
||||
total_elapsed_ms=round(overall_elapsed, 2),
|
||||
region=region["name"],
|
||||
x=detected_x,
|
||||
method="pixel",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return detected_x, "pixel"
|
||||
|
||||
# 像素检测未命中,记录日志
|
||||
try:
|
||||
pixel_elapsed = (time.time() - overall_start) * 1000
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 像素检测",
|
||||
f"{region['name']}未命中",
|
||||
elapsed_ms=round(pixel_elapsed, 2),
|
||||
region=region["name"],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
overall_elapsed = (time.time() - overall_start) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 检测完成",
|
||||
"未找到",
|
||||
total_elapsed_ms=round(overall_elapsed, 2),
|
||||
checked_regions=", ".join(regions_checked),
|
||||
total_regions=len(regions_checked),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return None, ""
|
||||
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
"""douyin_fudai_finder_pkg.finder - 福袋查找主流程。
|
||||
|
||||
FudaiFinder:组合 ImageAcquirer / Detector / ClickExecutor / DetailVerifier,
|
||||
对外提供"找到福袋并打开详情页"的高级入口。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# pylint: disable=E1101
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
# OCR 预处理接口
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
# 调试图像管理器(用于保存调试截图)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
except ImportError:
|
||||
douyin_screenshot_manager = None
|
||||
|
||||
|
||||
from .click_executor import FudaiClickExecutor
|
||||
from .detail_verifier import FudaiDetailVerifier
|
||||
from .detector import FudaiDetector
|
||||
from .image_acquirer import FudaiImageAcquirer
|
||||
|
||||
|
||||
class FudaiFinder:
|
||||
"""福袋查找器:统一管理查找流程"""
|
||||
|
||||
def __init__(self, analyser: Any):
|
||||
self.analyser = analyser
|
||||
self.acquirer = FudaiImageAcquirer(analyser)
|
||||
self.detector = FudaiDetector(analyser)
|
||||
self.executor = FudaiClickExecutor(analyser)
|
||||
self.verifier = FudaiDetailVerifier(analyser)
|
||||
|
||||
# 配置参数
|
||||
self._init_config()
|
||||
|
||||
def _init_config(self):
|
||||
"""初始化配置参数"""
|
||||
try:
|
||||
self.retry_delay_s = float(
|
||||
getattr(self.analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
|
||||
)
|
||||
except Exception:
|
||||
self.retry_delay_s = 0.6
|
||||
|
||||
try:
|
||||
self.max_wait_s = float(
|
||||
getattr(self.analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0
|
||||
)
|
||||
except Exception:
|
||||
self.max_wait_s = 5.0
|
||||
|
||||
try:
|
||||
self.verify_enabled = bool(
|
||||
getattr(self.analyser, "fudai_click_verify_enabled", True)
|
||||
)
|
||||
except Exception:
|
||||
self.verify_enabled = True
|
||||
|
||||
try:
|
||||
self.max_retries = int(
|
||||
getattr(self.analyser, "fudai_find_max_retries", 3) or 3
|
||||
)
|
||||
except Exception:
|
||||
self.max_retries = 3
|
||||
|
||||
# 确保参数合理
|
||||
if self.retry_delay_s < 0.1:
|
||||
self.retry_delay_s = 0.1
|
||||
if self.max_wait_s < 0:
|
||||
self.max_wait_s = 0.0
|
||||
# 防止无限等待:最大等待时间限制为30秒
|
||||
if self.max_wait_s > 30.0:
|
||||
self.max_wait_s = 30.0
|
||||
|
||||
def find_and_open(
|
||||
self,
|
||||
screenshot_ready: bool = False,
|
||||
verify_after_click: bool = True, # noqa: ARG002
|
||||
) -> Tuple[bool, Optional[int]]:
|
||||
"""查找并打开福袋详情页
|
||||
|
||||
参数:
|
||||
screenshot_ready: 是否已有可用截图
|
||||
verify_after_click: 点击后是否验证
|
||||
|
||||
返回:
|
||||
(是否成功, 福袋X坐标)
|
||||
"""
|
||||
overall_start = time.time()
|
||||
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 开始",
|
||||
"查找福袋图标",
|
||||
max_wait_s=self.max_wait_s,
|
||||
retry_delay_s=self.retry_delay_s,
|
||||
screenshot_ready=screenshot_ready,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 主循环:按时间限制重试
|
||||
loop = 0
|
||||
max_loops = int(self.max_wait_s / self.retry_delay_s) + 10 # 额外的循环次数保护
|
||||
consecutive_failures = 0 # 连续失败计数
|
||||
max_consecutive_failures = 5 # 最大连续失败次数
|
||||
|
||||
# 额外的时间限制保护,防止死循环(最长等待时间限制)
|
||||
absolute_timeout = overall_start + max(self.max_wait_s * 1.5, 180) # 最长3分钟
|
||||
|
||||
while (
|
||||
time.time() - overall_start
|
||||
) < self.max_wait_s and time.time() < absolute_timeout:
|
||||
# 额外的循环次数保护:防止无限循环
|
||||
if loop >= max_loops:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 警告",
|
||||
"达到最大循环次数限制,提前退出",
|
||||
max_loops=max_loops,
|
||||
elapsed_s=round(time.time() - overall_start, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
# 1. 获取截图
|
||||
pic = self.acquirer.acquire_screenshot(
|
||||
force_refresh=not (screenshot_ready and loop == 0)
|
||||
)
|
||||
|
||||
if pic is None:
|
||||
loop += 1
|
||||
consecutive_failures += 1
|
||||
# 如果连续失败太多次,提前退出
|
||||
if consecutive_failures >= max_consecutive_failures:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 警告",
|
||||
"连续截图失败次数过多,提前退出",
|
||||
consecutive_failures=consecutive_failures,
|
||||
elapsed_s=round(time.time() - overall_start, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
elapsed = time.time() - overall_start
|
||||
if elapsed < self.max_wait_s:
|
||||
remaining_time = self.max_wait_s - elapsed
|
||||
sleep_time = min(self.retry_delay_s, remaining_time)
|
||||
if sleep_time > 0:
|
||||
self.analyser.operation.delay(sleep_time)
|
||||
continue
|
||||
|
||||
# 保存完整截图用于调试(检测前)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
pic_rgb_full = pic.convert("RGB")
|
||||
|
||||
# 获取检测区域信息用于标注
|
||||
try:
|
||||
first_region = (
|
||||
self.detector.search_regions[0]
|
||||
if self.detector.search_regions
|
||||
else None
|
||||
)
|
||||
if first_region:
|
||||
if "y_top" in first_region:
|
||||
coords = (
|
||||
first_region.get("x1", 0),
|
||||
first_region.get("y_top", 0),
|
||||
first_region.get("x2", 0),
|
||||
first_region.get("y_bottom", 0),
|
||||
)
|
||||
else:
|
||||
scan_y = first_region.get("y", 0)
|
||||
y_range = first_region.get("y_range", 7)
|
||||
coords = (
|
||||
first_region.get("x1", 0),
|
||||
max(0, scan_y - y_range // 2),
|
||||
first_region.get("x2", 0),
|
||||
scan_y + y_range // 2 + 1,
|
||||
)
|
||||
else:
|
||||
coords = None
|
||||
except Exception:
|
||||
coords = None
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="before_detect",
|
||||
coords=coords,
|
||||
extra_info={
|
||||
"loop": loop,
|
||||
"method": "optimized_finder",
|
||||
"resolution": f"{self.detector.rx}x{self.detector.ry}",
|
||||
"y_offset": self.detector.y_pianyi,
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标检测前保存完整截图(优化查找器)",
|
||||
path=debug_path,
|
||||
loop=loop,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2. 检测福袋图标
|
||||
detected_x, detect_method = self.detector.detect(pic)
|
||||
|
||||
if detected_x is not None:
|
||||
# 重置连续失败计数
|
||||
consecutive_failures = 0
|
||||
# 保存完整截图(检测成功)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
pic_rgb_full = pic.convert("RGB")
|
||||
|
||||
# 获取检测区域信息用于标注
|
||||
try:
|
||||
# 找到检测成功的区域
|
||||
detected_region = None
|
||||
for region in self.detector.search_regions:
|
||||
if "y_top" in region:
|
||||
x1 = region.get("x1", 0)
|
||||
x2 = region.get("x2", 0)
|
||||
y_top = region.get("y_top", 0)
|
||||
y_bottom = region.get("y_bottom", 0)
|
||||
else:
|
||||
scan_y = region.get("y", 0)
|
||||
y_range = region.get("y_range", 7)
|
||||
x1 = region.get("x1", 0)
|
||||
x2 = region.get("x2", 0)
|
||||
y_top = max(0, scan_y - y_range // 2)
|
||||
y_bottom = scan_y + y_range // 2 + 1
|
||||
|
||||
# 检查detected_x是否在这个区域内
|
||||
detected_x_scaled = detected_x * self.detector.rx // 1080
|
||||
if x1 <= detected_x_scaled <= x2:
|
||||
detected_region = (x1, y_top, x2, y_bottom)
|
||||
break
|
||||
|
||||
coords = detected_region
|
||||
except Exception:
|
||||
coords = None
|
||||
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=coords,
|
||||
extra_info={
|
||||
"detected_x": detected_x,
|
||||
"method": detect_method,
|
||||
"loop": loop,
|
||||
"resolution": f"{self.detector.rx}x{self.detector.ry}",
|
||||
"result": "success",
|
||||
},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"福袋图标检测成功保存完整截图(优化查找器)",
|
||||
path=debug_path,
|
||||
detected_x=detected_x,
|
||||
method=detect_method,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 3. 点击福袋图标
|
||||
click_success = self.executor.click(detected_x)
|
||||
|
||||
if click_success:
|
||||
# 点击成功后直接返回,不进行验证
|
||||
# 让主循环进行阶段检测,判断是否成功打开详情页
|
||||
overall_elapsed = (time.time() - overall_start) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 完成",
|
||||
"成功(已点击,等待阶段检测)",
|
||||
total_elapsed_ms=round(overall_elapsed, 2),
|
||||
loops=loop + 1,
|
||||
x=detected_x,
|
||||
method=detect_method,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录首次找到福袋的时间
|
||||
self._record_find_fudai_time(detected_x)
|
||||
return True, detected_x
|
||||
|
||||
loop += 1
|
||||
consecutive_failures += 1
|
||||
|
||||
# 如果连续失败太多次,提前退出(避免无效循环)
|
||||
if consecutive_failures >= max_consecutive_failures:
|
||||
try:
|
||||
overall_elapsed = (time.time() - overall_start) * 1000
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 警告",
|
||||
"连续检测失败次数过多,提前退出",
|
||||
consecutive_failures=consecutive_failures,
|
||||
loop=loop,
|
||||
total_elapsed_ms=round(overall_elapsed, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
# 检查是否还有剩余时间
|
||||
elapsed = time.time() - overall_start
|
||||
if elapsed < self.max_wait_s:
|
||||
remaining_time = self.max_wait_s - elapsed
|
||||
sleep_time = min(self.retry_delay_s, remaining_time)
|
||||
if sleep_time > 0:
|
||||
self.analyser.operation.delay(sleep_time)
|
||||
else:
|
||||
# 时间已到,退出循环
|
||||
break
|
||||
|
||||
# 未找到
|
||||
overall_elapsed = (time.time() - overall_start) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 完成",
|
||||
"未找到",
|
||||
total_elapsed_ms=round(overall_elapsed, 2),
|
||||
loops=loop,
|
||||
max_wait_s=self.max_wait_s,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return False, None
|
||||
|
||||
def _record_find_fudai_time(self, detected_x: int):
|
||||
"""记录首次找到福袋的时间"""
|
||||
try:
|
||||
enter_ts = float(getattr(self.analyser, "_enter_live_ts", 0.0) or 0.0)
|
||||
if enter_ts > 0:
|
||||
dt = time.time() - enter_ts
|
||||
if not getattr(self.analyser, "_enter_live_fudai_logged", False):
|
||||
try:
|
||||
self.analyser._enter_live_fudai_logged = True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
reason = str(
|
||||
getattr(self.analyser, "_enter_live_reason", "") or ""
|
||||
)
|
||||
except Exception:
|
||||
reason = ""
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"性能",
|
||||
"进入直播间后找到福袋耗时",
|
||||
seconds=round(dt, 2),
|
||||
enter_reason=reason,
|
||||
fudai_x=detected_x,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""douyin_fudai_finder_pkg.image_acquirer - 截图获取与预处理。
|
||||
|
||||
FudaiImageAcquirer:负责拍取设备截图、做必要的预处理,
|
||||
为后续的模板匹配 / OCR 识别提供 PIL Image。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# pylint: disable=E1101
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
# OCR 预处理接口
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
# 调试图像管理器(用于保存调试截图)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
except ImportError:
|
||||
douyin_screenshot_manager = None
|
||||
|
||||
|
||||
class FudaiImageAcquirer:
|
||||
"""图像获取器:负责截图和图像预处理"""
|
||||
|
||||
def __init__(self, analyser: Any):
|
||||
self.analyser = analyser
|
||||
self.screenshot_path = path_config.get_screenshot_path()
|
||||
|
||||
def acquire_screenshot(self, force_refresh: bool = False) -> Optional[Image.Image]:
|
||||
"""获取截图
|
||||
|
||||
参数:
|
||||
force_refresh: 是否强制刷新截图
|
||||
|
||||
返回:
|
||||
PIL Image对象,失败返回None
|
||||
"""
|
||||
start_time = time.time()
|
||||
try:
|
||||
if force_refresh or not os.path.exists(self.screenshot_path):
|
||||
try:
|
||||
self.analyser._shot_and_diagnose(
|
||||
"找福袋图标",
|
||||
"获取截图",
|
||||
self.analyser.device_id,
|
||||
diagnose=False,
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
self.analyser.operation.get_screenshot(
|
||||
self.analyser.device_id, use_service=False
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
# 读取截图
|
||||
try:
|
||||
pic = Image.open(self.screenshot_path)
|
||||
pic.load()
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 图像获取",
|
||||
"成功",
|
||||
elapsed_ms=round(elapsed, 2),
|
||||
size=f"{pic.size[0]}x{pic.size[1]}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return pic.convert("RGBA")
|
||||
except Exception:
|
||||
return None
|
||||
except Exception as e:
|
||||
try:
|
||||
self.analyser._log_kv(
|
||||
"[福袋查找] 图像获取",
|
||||
"失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""douyin_fudai_finder_pkg.optimized_entry - 顶层"快速找福袋"入口。
|
||||
|
||||
check_have_fudai_with_ready_screenshot_optimized:直接拼装 Acquirer + Detector,
|
||||
跳过 FudaiFinder 重试逻辑的轻量入口。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# pylint: disable=E1101
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
# OCR 预处理接口
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore
|
||||
|
||||
# 调试图像管理器(用于保存调试截图)
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
except ImportError:
|
||||
douyin_screenshot_manager = None
|
||||
|
||||
|
||||
from .detector import FudaiDetector
|
||||
from .image_acquirer import FudaiImageAcquirer
|
||||
|
||||
|
||||
def check_have_fudai_with_ready_screenshot_optimized(
|
||||
analyser: Any, screenshot_ready: bool = False
|
||||
) -> int:
|
||||
"""优化的福袋查找函数(兼容原接口,仅检测不点击)
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
screenshot_ready: 是否已有可用截图
|
||||
|
||||
返回:
|
||||
福袋X坐标(1080基准),未找到返回False
|
||||
"""
|
||||
# 只检测,不点击(避免与 find_and_open_fudai_detail 重复点击)
|
||||
try:
|
||||
acquirer = FudaiImageAcquirer(analyser)
|
||||
pic = acquirer.acquire_screenshot(force_refresh=not screenshot_ready)
|
||||
|
||||
if pic is None:
|
||||
return False
|
||||
|
||||
detector = FudaiDetector(analyser)
|
||||
detected_x, _detect_method = detector.detect(pic)
|
||||
|
||||
if detected_x is not None:
|
||||
return int(detected_x)
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,84 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""screenshot_manager - 截图管理子包(双截图记录 + 异步调试保存)。
|
||||
|
||||
原 douyin/handlers/douyin_screenshot_manager.py 拆成 6 个子模块:
|
||||
|
||||
- _common 共享 logger / 全局状态 / 异步计数器
|
||||
- paths OCR 目录、调试存档目录、各类路径计算
|
||||
- save_files save_latest_attempt / save_last_success / save_*_from_file / cleanup_ocr_dir
|
||||
- async_save _debug_save_loop + 工作线程启停
|
||||
- cleanup debug_captures 目录的清理与轮转
|
||||
- save_image save_debug_image 主入口
|
||||
|
||||
外部 import 路径不变:from douyin.handlers.douyin_screenshot_manager import save_debug_image
|
||||
仍能工作(原文件改为 re-export shell)。
|
||||
"""
|
||||
|
||||
from ._common import (
|
||||
_LOGGER,
|
||||
_mgr_log,
|
||||
_debug_save_queue,
|
||||
_debug_save_worker_lock,
|
||||
_debug_save_shutdown_event,
|
||||
_async_save_counters_lock,
|
||||
_SKIP_DEBUG_SAVE_IN_HOTLOOPS,
|
||||
get_async_save_counters,
|
||||
reset_async_save_counters,
|
||||
)
|
||||
from .paths import (
|
||||
get_ocr_dir,
|
||||
get_category_for_picname,
|
||||
get_latest_attempt_path,
|
||||
get_last_success_path,
|
||||
ensure_ocr_dir,
|
||||
get_debug_captures_dir,
|
||||
ensure_debug_captures_dir,
|
||||
get_debug_captures_base_dir,
|
||||
)
|
||||
from .save_files import (
|
||||
cleanup_ocr_dir,
|
||||
save_latest_attempt,
|
||||
save_last_success,
|
||||
save_attempt_from_file,
|
||||
save_success_from_file,
|
||||
)
|
||||
from .async_save import (
|
||||
_debug_save_loop,
|
||||
_ensure_debug_save_worker_started,
|
||||
shutdown_debug_save_worker,
|
||||
)
|
||||
from .cleanup import (
|
||||
count_debug_captures_files,
|
||||
cleanup_debug_captures,
|
||||
init_debug_captures_cleanup,
|
||||
)
|
||||
from .save_image import (
|
||||
_sanitize_filename_part,
|
||||
save_debug_image,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"_LOGGER",
|
||||
"_mgr_log",
|
||||
"get_async_save_counters",
|
||||
"reset_async_save_counters",
|
||||
"get_ocr_dir",
|
||||
"get_category_for_picname",
|
||||
"get_latest_attempt_path",
|
||||
"get_last_success_path",
|
||||
"ensure_ocr_dir",
|
||||
"get_debug_captures_dir",
|
||||
"ensure_debug_captures_dir",
|
||||
"get_debug_captures_base_dir",
|
||||
"cleanup_ocr_dir",
|
||||
"save_latest_attempt",
|
||||
"save_last_success",
|
||||
"save_attempt_from_file",
|
||||
"save_success_from_file",
|
||||
"shutdown_debug_save_worker",
|
||||
"count_debug_captures_files",
|
||||
"cleanup_debug_captures",
|
||||
"init_debug_captures_cleanup",
|
||||
"save_debug_image",
|
||||
]
|
||||
@@ -0,0 +1,79 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""screenshot_manager._common - 共享 logger + 全局状态 + 异步保存计数器。
|
||||
|
||||
被本子包的 async_save / save_files / cleanup / save_image 共享:
|
||||
- _LOGGER / _mgr_log:统一日志出口
|
||||
- _debug_save_queue / _debug_save_worker_started / _debug_save_worker_lock
|
||||
/ _debug_save_shutdown_event:异步保存的工作线程状态
|
||||
- _async_save_*_count / _async_save_counters_lock:异步计数器
|
||||
- _SKIP_DEBUG_SAVE_IN_HOTLOOPS:高频路径跳过开关
|
||||
"""
|
||||
|
||||
import os
|
||||
import threading
|
||||
from queue import Queue
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import logging as _logging
|
||||
from PIL import Image
|
||||
|
||||
# 模块级 logger:原代码用 print 输出截图管理 / 调试图像清理日志,统一走 logging。
|
||||
# 保留消息中已有的 "[截图管理]"/"[调试图像清理]" 前缀,避免改变历史搜索习惯。
|
||||
_LOGGER = _logging.getLogger("douyin.handlers.douyin_screenshot_manager")
|
||||
|
||||
|
||||
def _mgr_log(msg: str, level: str = "INFO") -> None:
|
||||
"""统一截图管理日志出口;失败兜底 stdout。"""
|
||||
try:
|
||||
lv = str(level or "INFO").upper()
|
||||
if lv == "ERROR":
|
||||
_LOGGER.error(str(msg))
|
||||
elif lv == "WARNING":
|
||||
_LOGGER.warning(str(msg))
|
||||
elif lv == "DEBUG":
|
||||
_LOGGER.debug(str(msg))
|
||||
else:
|
||||
_LOGGER.info(str(msg))
|
||||
except Exception:
|
||||
try:
|
||||
print(str(msg))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 背景保存队列与工作线程(用于异步保存调试图像,避免阻塞主流程)
|
||||
_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
|
||||
_debug_save_worker_lock = threading.Lock() # 保护 worker 启动的双检查锁
|
||||
_debug_save_shutdown_event = threading.Event() # 用于优雅关闭
|
||||
|
||||
# 异步保存计数(用于 GUI 显示)
|
||||
_async_save_success_count = 0
|
||||
_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"
|
||||
)
|
||||
|
||||
|
||||
def get_async_save_counters() -> tuple[int, int]:
|
||||
"""返回 (success_count, failure_count)"""
|
||||
try:
|
||||
with _async_save_counters_lock:
|
||||
return int(_async_save_success_count), int(_async_save_failure_count)
|
||||
except Exception:
|
||||
return 0, 0
|
||||
|
||||
|
||||
def reset_async_save_counters() -> None:
|
||||
"""重置计数器(GUI 可调用)"""
|
||||
try:
|
||||
with _async_save_counters_lock:
|
||||
global _async_save_success_count, _async_save_failure_count
|
||||
_async_save_success_count = 0
|
||||
_async_save_failure_count = 0
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,360 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""screenshot_manager.async_save - 异步调试图像保存工作线程。
|
||||
|
||||
定义:
|
||||
- _debug_save_loop:消费 _debug_save_queue 的后台线程入口
|
||||
- shutdown_debug_save_worker:优雅关闭(atexit 注册一次)
|
||||
- _ensure_debug_save_worker_started:启动 worker(双检查锁)
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from queue import Empty
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import logging
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from ._common import (
|
||||
_async_save_counters_lock,
|
||||
_debug_save_queue,
|
||||
_debug_save_shutdown_event,
|
||||
_debug_save_worker_lock,
|
||||
_LOGGER,
|
||||
_mgr_log,
|
||||
)
|
||||
from . import _common as _state
|
||||
from .paths import ensure_debug_captures_dir
|
||||
|
||||
|
||||
def _debug_save_loop() -> None:
|
||||
"""后台线程循环,消费调试图像保存任务并执行同步保存。"""
|
||||
while not _debug_save_shutdown_event.is_set():
|
||||
try:
|
||||
task = _debug_save_queue.get(timeout=1.0)
|
||||
if task is None:
|
||||
_debug_save_queue.task_done()
|
||||
break
|
||||
(
|
||||
img,
|
||||
file_path,
|
||||
annotate,
|
||||
coords,
|
||||
extra_info,
|
||||
operation_type,
|
||||
picname,
|
||||
step,
|
||||
) = task
|
||||
# 在函数中修改全局计数器时需要声明 global,避免静态分析/运行时错误
|
||||
try:
|
||||
# 执行同步保存(重复之前 save_debug_image 中的标注与保存逻辑)
|
||||
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:
|
||||
img_to_save.save(path, "PNG")
|
||||
return True
|
||||
except FileNotFoundError as e:
|
||||
last_error = e
|
||||
if attempt < max_retries - 1:
|
||||
try:
|
||||
ensure_debug_captures_dir()
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
raise
|
||||
except PermissionError:
|
||||
raise
|
||||
except OSError:
|
||||
raise
|
||||
if last_error:
|
||||
raise last_error
|
||||
return False
|
||||
|
||||
# 标注并保存
|
||||
if annotate and (coords or extra_info):
|
||||
try:
|
||||
from PIL import ImageDraw, ImageFont
|
||||
|
||||
annotated_image = img.copy()
|
||||
draw = ImageDraw.Draw(annotated_image)
|
||||
try:
|
||||
font = ImageFont.truetype("arial.ttf", 12)
|
||||
except Exception:
|
||||
try:
|
||||
font = ImageFont.load_default()
|
||||
except Exception:
|
||||
font = None
|
||||
|
||||
if coords:
|
||||
x1, y1, x2, y2 = coords
|
||||
img_w, img_h = annotated_image.size
|
||||
x1 = max(0, min(x1, img_w - 1))
|
||||
y1 = max(0, min(y1, img_h - 1))
|
||||
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),
|
||||
)
|
||||
draw.rectangle(rect_coords, outline="red", width=2)
|
||||
|
||||
if extra_info:
|
||||
text_lines = [f"{k}: {v}" for k, v in extra_info.items()]
|
||||
if text_lines:
|
||||
text = "\n".join(text_lines)
|
||||
try:
|
||||
draw.text((5, 5), text, fill="yellow", font=font)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
_save_image_with_retry(annotated_image, file_path)
|
||||
# 计数并写入 actions.log
|
||||
try:
|
||||
with _async_save_counters_lock:
|
||||
_state._async_save_success_count += 1
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
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)
|
||||
)
|
||||
if log_on_complete:
|
||||
logging.info(
|
||||
"[调试图像] 异步保存完成: %s", file_path
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
try:
|
||||
_save_image_with_retry(img, file_path)
|
||||
try:
|
||||
with _async_save_counters_lock:
|
||||
_state._async_save_success_count += 1
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
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
|
||||
)
|
||||
)
|
||||
if log_on_complete:
|
||||
logging.info(
|
||||
"[调试图像] 异步保存完成: %s", file_path
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 保存失败:写入异步错误日志、计数并写入 actions.log
|
||||
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"
|
||||
)
|
||||
ef.write(traceback.format_exc())
|
||||
ef.write("\n\n")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
with _async_save_counters_lock:
|
||||
_state._async_save_failure_count += 1
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.getLogger("action_logger").info(
|
||||
"[调试图像] 异步保存失败: %s", file_path
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 捕获标注过程中的任何异常,避免线程退出
|
||||
except Exception:
|
||||
pass
|
||||
# end if annotate block
|
||||
else:
|
||||
try:
|
||||
_save_image_with_retry(img, file_path)
|
||||
try:
|
||||
with _async_save_counters_lock:
|
||||
_state._async_save_success_count += 1
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
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)
|
||||
)
|
||||
if log_on_complete:
|
||||
logging.info("[调试图像] 异步保存完成: %s", file_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 保存失败:写入异步错误日志以便追踪,同时记录到 actions.log
|
||||
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"
|
||||
)
|
||||
ef.write(traceback.format_exc())
|
||||
ef.write("\n\n")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
with _async_save_counters_lock:
|
||||
_state._async_save_failure_count += 1
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
import logging
|
||||
|
||||
logging.getLogger("action_logger").info(
|
||||
"[调试图像] 异步保存失败: %s", file_path
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
_debug_save_queue.task_done()
|
||||
except Empty:
|
||||
continue
|
||||
except Exception:
|
||||
# 防止线程因异常退出
|
||||
try:
|
||||
import time
|
||||
|
||||
time.sleep(0.1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
def shutdown_debug_save_worker(timeout: float = 5.0) -> None:
|
||||
"""优雅关闭调试保存工作线程"""
|
||||
if not _state._debug_save_worker_started:
|
||||
return
|
||||
_debug_save_shutdown_event.set()
|
||||
_debug_save_queue.put(None) # 毒丸信号
|
||||
try:
|
||||
_debug_save_queue.join()
|
||||
except Exception:
|
||||
pass
|
||||
_state._debug_save_worker_started = False
|
||||
|
||||
|
||||
# 注册 atexit 清理函数
|
||||
import atexit
|
||||
atexit.register(shutdown_debug_save_worker)
|
||||
|
||||
|
||||
|
||||
|
||||
def _ensure_debug_save_worker_started() -> None:
|
||||
if _state._debug_save_worker_started:
|
||||
return
|
||||
with _debug_save_worker_lock:
|
||||
if _state._debug_save_worker_started:
|
||||
return
|
||||
t = threading.Thread(target=_debug_save_loop, name="debug-save-worker", daemon=True)
|
||||
t.start()
|
||||
_state._debug_save_worker_started = True
|
||||
|
||||
|
||||
# 注册 atexit 清理函数(仅注册一次)
|
||||
import atexit
|
||||
atexit.register(shutdown_debug_save_worker)
|
||||
@@ -0,0 +1,293 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""screenshot_manager.cleanup - 调试图像存档目录的轮转 / 清理。"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from ._common import _mgr_log
|
||||
from .paths import get_debug_captures_base_dir
|
||||
|
||||
|
||||
def count_debug_captures_files() -> int:
|
||||
"""统计所有调试图像文件的总数量
|
||||
|
||||
返回:
|
||||
文件总数
|
||||
"""
|
||||
try:
|
||||
debug_base_dir = get_debug_captures_base_dir()
|
||||
if not os.path.exists(debug_base_dir):
|
||||
return 0
|
||||
|
||||
total_count = 0
|
||||
# 遍历所有日期目录
|
||||
for item in os.listdir(debug_base_dir):
|
||||
# 跳过隐藏文件和标记文件
|
||||
if item.startswith("."):
|
||||
continue
|
||||
|
||||
item_path = os.path.join(debug_base_dir, item)
|
||||
if not os.path.isdir(item_path):
|
||||
continue
|
||||
|
||||
# 统计该目录下的所有PNG文件
|
||||
try:
|
||||
for _root, _dirs, files in os.walk(item_path):
|
||||
for f in files:
|
||||
if f.lower().endswith(".png"):
|
||||
total_count += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return total_count
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
|
||||
def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int:
|
||||
"""清理旧的调试图像存档目录
|
||||
|
||||
参数:
|
||||
keep_days: 保留天数,默认7天,超过此天数的目录将被删除
|
||||
max_files: 最大文件数量,默认2000,超过此数量时删除最旧的目录
|
||||
|
||||
返回:
|
||||
清理的目录数量
|
||||
"""
|
||||
try:
|
||||
debug_base_dir = get_debug_captures_base_dir()
|
||||
if not os.path.exists(debug_base_dir):
|
||||
return 0
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# 计算截止日期
|
||||
cutoff_date = datetime.now() - timedelta(days=keep_days)
|
||||
|
||||
deleted_count = 0
|
||||
deleted_dirs = []
|
||||
total_size_freed = 0
|
||||
|
||||
# 收集所有日期目录及其信息
|
||||
dirs_info = []
|
||||
for item in os.listdir(debug_base_dir):
|
||||
# 跳过隐藏文件和标记文件
|
||||
if item.startswith("."):
|
||||
continue
|
||||
|
||||
item_path = os.path.join(debug_base_dir, item)
|
||||
if not os.path.isdir(item_path):
|
||||
continue
|
||||
|
||||
# 尝试解析目录名为日期(格式:YYYY-MM-DD)
|
||||
try:
|
||||
dir_date = datetime.strptime(item, "%Y-%m-%d")
|
||||
|
||||
# 统计该目录下的文件数量和大小
|
||||
file_count = 0
|
||||
dir_size = 0
|
||||
try:
|
||||
for root, _dirs, files in os.walk(item_path):
|
||||
for f in files:
|
||||
if f.lower().endswith(".png"):
|
||||
file_count += 1
|
||||
file_path = os.path.join(root, f)
|
||||
try:
|
||||
dir_size += os.path.getsize(file_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
dirs_info.append(
|
||||
{
|
||||
"name": item,
|
||||
"path": item_path,
|
||||
"date": dir_date,
|
||||
"file_count": file_count,
|
||||
"size": dir_size,
|
||||
}
|
||||
)
|
||||
except ValueError:
|
||||
# 如果目录名不是日期格式,跳过
|
||||
continue
|
||||
|
||||
# 按日期排序(最旧的在前)
|
||||
dirs_info.sort(key=lambda x: x["date"])
|
||||
|
||||
# 先按天数清理:删除超过保留天数的目录
|
||||
for dir_info in dirs_info[:]:
|
||||
if dir_info["date"] < cutoff_date:
|
||||
try:
|
||||
shutil.rmtree(dir_info["path"])
|
||||
deleted_count += 1
|
||||
deleted_dirs.append(dir_info["name"])
|
||||
total_size_freed += dir_info["size"]
|
||||
dirs_info.remove(dir_info)
|
||||
except Exception as e:
|
||||
try:
|
||||
_mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 再按文件数量清理:如果文件总数超过max_files,删除最旧的目录
|
||||
total_files = sum(d["file_count"] for d in dirs_info)
|
||||
if total_files > max_files:
|
||||
# 计算需要删除的文件数量
|
||||
need_delete_count = total_files - max_files
|
||||
|
||||
# 从最旧的目录开始删除,直到文件数量降到max_files以下
|
||||
deleted_files_count = 0
|
||||
for dir_info in dirs_info[:]:
|
||||
if deleted_files_count >= need_delete_count:
|
||||
break
|
||||
|
||||
try:
|
||||
shutil.rmtree(dir_info["path"])
|
||||
deleted_count += 1
|
||||
deleted_dirs.append(dir_info["name"])
|
||||
total_size_freed += dir_info["size"]
|
||||
deleted_files_count += dir_info["file_count"]
|
||||
dirs_info.remove(dir_info)
|
||||
except Exception as e:
|
||||
try:
|
||||
_mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if deleted_count > 0:
|
||||
try:
|
||||
size_mb = total_size_freed / (1024 * 1024)
|
||||
reason_parts = []
|
||||
if total_files > max_files:
|
||||
reason_parts.append(f"文件数量超过{max_files}")
|
||||
if any(
|
||||
d["date"] < cutoff_date
|
||||
for d in dirs_info
|
||||
if d not in [{"name": name} for name in deleted_dirs]
|
||||
):
|
||||
reason_parts.append(f"超过{keep_days}天")
|
||||
reason = ",".join(reason_parts) if reason_parts else "自动清理"
|
||||
|
||||
_mgr_log(
|
||||
f"[调试图像清理] 已删除 {deleted_count} 个调试图像目录: {', '.join(deleted_dirs)}"
|
||||
)
|
||||
_mgr_log(f"[调试图像清理] 清理原因: {reason}")
|
||||
if size_mb > 0.1: # 只显示大于0.1MB的清理
|
||||
_mgr_log(f"[调试图像清理] 释放空间: {size_mb:.2f} MB")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return deleted_count
|
||||
except Exception as e:
|
||||
# 清理失败不应影响程序运行
|
||||
try:
|
||||
_mgr_log(f"[调试图像清理] 清理旧调试图像时出错: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
|
||||
def init_debug_captures_cleanup() -> None:
|
||||
"""初始化调试图像清理(在程序启动时调用)
|
||||
|
||||
从 config.json 读取配置并执行清理
|
||||
"""
|
||||
try:
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
if not os.path.exists(config_path):
|
||||
return
|
||||
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
|
||||
# 检查是否启用自动清理
|
||||
auto_cleanup = True
|
||||
keep_days = 7
|
||||
max_files = 2000
|
||||
|
||||
if "debug_captures" in config and isinstance(config["debug_captures"], dict):
|
||||
auto_cleanup = config["debug_captures"].get("auto_cleanup", True)
|
||||
keep_days = int(config["debug_captures"].get("keep_days", 7))
|
||||
max_files = int(config["debug_captures"].get("max_files", 2000))
|
||||
|
||||
if auto_cleanup:
|
||||
cleanup_debug_captures(keep_days=keep_days, max_files=max_files)
|
||||
except Exception:
|
||||
# 初始化失败不影响程序运行
|
||||
pass
|
||||
|
||||
|
||||
# 操作类型和步骤的中文映射
|
||||
_OPERATION_TYPE_CN = {
|
||||
"cut_pic": "裁剪图片",
|
||||
"ocr": "ocr", # 保持ocr不变
|
||||
"pixel_detect": "像素检测",
|
||||
"template_match": "模板匹配",
|
||||
}
|
||||
|
||||
_STEP_CN = {
|
||||
"before_ocr": "识别前",
|
||||
"preprocessed": "预处理后",
|
||||
"after_ocr": "识别后",
|
||||
"before_detect": "检测前",
|
||||
"detected": "检测成功",
|
||||
"not_detected": "未检测到",
|
||||
"matched": "匹配成功",
|
||||
"failed": "匹配失败",
|
||||
}
|
||||
|
||||
# picname 的中文映射
|
||||
_PICNAME_CN = {
|
||||
"live_room_title_mid": "直播间标题", # 现在只使用一个区域,简化为"直播间标题"
|
||||
"live_room_title_large": "直播间标题_大", # 保留以兼容旧代码
|
||||
"live_room_title_small": "直播间标题_小", # 保留以兼容旧代码
|
||||
"live_room_title_mid_tmp": "直播间标题_临时", # 保留以兼容旧代码
|
||||
"live_room_title_large_tmp": "直播间标题_大_临时", # 保留以兼容旧代码
|
||||
"fudai_icon": "福袋图标",
|
||||
"lucky_draw_result": "抽奖结果",
|
||||
"attend_button": "参与按钮",
|
||||
"live_room_icons": "直播间图标",
|
||||
"fudai_content": "福袋内容",
|
||||
"fudai_countdown": "福袋倒计时",
|
||||
"fudai_value": "福袋价值",
|
||||
"fudai_task_list": "福袋任务列表",
|
||||
"fudai_coupon": "优惠券",
|
||||
"shopping_redpacket": "购物红包",
|
||||
}
|
||||
|
||||
# extra_info 键名的中文映射
|
||||
_EXTRA_INFO_KEY_CN = {
|
||||
"mode": "模式",
|
||||
"size": "尺寸",
|
||||
"used_img2": "使用图片2",
|
||||
"avg_confidence": "平均置信度",
|
||||
"min_confidence": "最小置信度",
|
||||
"max_confidence": "最大置信度",
|
||||
"confidence_items": "置信度项数",
|
||||
"text_preview": "文本预览",
|
||||
"text_len": "文本长度",
|
||||
"source": "来源",
|
||||
"has_full_screenshot": "有完整截图",
|
||||
"has_coords": "有坐标",
|
||||
"digits": "数字",
|
||||
"type": "类型",
|
||||
"region": "区域",
|
||||
"y_offset": "Y偏移",
|
||||
"region_size": "区域尺寸",
|
||||
"content": "内容",
|
||||
"threshold": "阈值",
|
||||
"score": "分数",
|
||||
"loc": "位置",
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""screenshot_manager.paths - 路径计算与目录确保。
|
||||
|
||||
包含:OCR 目录、调试存档目录、最新尝试 / 上次成功的路径,
|
||||
以及按图片名称分类到子目录的辅助函数。
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
|
||||
def get_ocr_dir() -> str:
|
||||
"""获取OCR目录路径"""
|
||||
return os.path.join(path_config.get_pic_dir(), "ocr")
|
||||
|
||||
|
||||
|
||||
|
||||
def get_category_for_picname(picname: str) -> str:
|
||||
"""根据图片名称判断应该保存到哪个分类目录
|
||||
|
||||
参数:
|
||||
picname: 图片名称(不含扩展名)
|
||||
|
||||
返回:
|
||||
分类目录名称,如 "fudai", "live_room", "popups", "buttons", "stage_diag", "others"
|
||||
"""
|
||||
picname_lower = picname.lower()
|
||||
|
||||
# 福袋相关
|
||||
if any(keyword in picname_lower for keyword in ["福袋", "fudai"]):
|
||||
return "fudai"
|
||||
|
||||
# 直播间相关
|
||||
if any(
|
||||
keyword in picname_lower
|
||||
for keyword in [
|
||||
"live_room",
|
||||
"直播间",
|
||||
"直播列表",
|
||||
"直播广场",
|
||||
"直播状态",
|
||||
"直播验证",
|
||||
]
|
||||
):
|
||||
return "live_room"
|
||||
|
||||
# 弹窗相关
|
||||
if any(
|
||||
keyword in picname_lower
|
||||
for keyword in [
|
||||
"抽奖结果",
|
||||
"无奖励",
|
||||
"优惠券",
|
||||
"购物红包",
|
||||
"奖励通知",
|
||||
"订单确认",
|
||||
"lucky_draw",
|
||||
"coupon",
|
||||
"redpacket",
|
||||
"reward",
|
||||
"order",
|
||||
]
|
||||
):
|
||||
return "popups"
|
||||
|
||||
# 按钮相关
|
||||
if any(
|
||||
keyword in picname_lower
|
||||
for keyword in ["参与按钮", "粉丝团", "attend_button", "fans_club"]
|
||||
):
|
||||
return "buttons"
|
||||
|
||||
# 阶段诊断相关
|
||||
if any(
|
||||
keyword in picname_lower
|
||||
for keyword in [
|
||||
"推荐页",
|
||||
"关注列表",
|
||||
"直播列表标签",
|
||||
"recommend",
|
||||
"follow",
|
||||
"live_list",
|
||||
]
|
||||
):
|
||||
return "stage_diag"
|
||||
|
||||
# 其他
|
||||
return "others"
|
||||
|
||||
|
||||
|
||||
|
||||
def get_latest_attempt_path(operation_type: str = "general") -> str:
|
||||
"""获取实时操作截图路径
|
||||
|
||||
参数:
|
||||
operation_type: 操作类型,可选值:
|
||||
- "pixel" 或 "pixel_detect": 像素检测
|
||||
- "ocr": OCR识别
|
||||
- "template" 或 "template_match": 模板匹配
|
||||
- 其他: 通用操作
|
||||
"""
|
||||
# 规范化操作类型
|
||||
if operation_type.startswith("pixel"):
|
||||
type_key = "pixel"
|
||||
elif operation_type.startswith("ocr") or operation_type.startswith("cut_pic"):
|
||||
type_key = "ocr"
|
||||
elif operation_type.startswith("template"):
|
||||
type_key = "template"
|
||||
else:
|
||||
type_key = "general"
|
||||
|
||||
return os.path.join(get_ocr_dir(), f"latest_attempt_{type_key}.png")
|
||||
|
||||
|
||||
|
||||
|
||||
def get_last_success_path(operation_type: str = "general") -> str:
|
||||
"""获取成功识别存档截图路径
|
||||
|
||||
参数:
|
||||
operation_type: 操作类型,可选值:
|
||||
- "pixel" 或 "pixel_detect": 像素检测
|
||||
- "ocr": OCR识别
|
||||
- "template" 或 "template_match": 模板匹配
|
||||
- 其他: 通用操作
|
||||
"""
|
||||
# 规范化操作类型
|
||||
if operation_type.startswith("pixel"):
|
||||
type_key = "pixel"
|
||||
elif operation_type.startswith("ocr") or operation_type.startswith("cut_pic"):
|
||||
type_key = "ocr"
|
||||
elif operation_type.startswith("template"):
|
||||
type_key = "template"
|
||||
else:
|
||||
type_key = "general"
|
||||
|
||||
return os.path.join(get_ocr_dir(), f"last_success_{type_key}.png")
|
||||
|
||||
|
||||
|
||||
|
||||
def ensure_ocr_dir() -> None:
|
||||
"""确保OCR目录存在"""
|
||||
ocr_dir = get_ocr_dir()
|
||||
os.makedirs(ocr_dir, exist_ok=True)
|
||||
|
||||
|
||||
|
||||
|
||||
def get_debug_captures_dir() -> str:
|
||||
"""获取调试图像存档目录路径"""
|
||||
pic_dir = path_config.get_pic_dir()
|
||||
debug_dir = os.path.join(pic_dir, "debug_captures")
|
||||
# 按日期分类:YYYY-MM-DD
|
||||
from datetime import datetime
|
||||
|
||||
date_str = datetime.now().strftime("%Y-%m-%d")
|
||||
return os.path.join(debug_dir, date_str)
|
||||
|
||||
|
||||
|
||||
|
||||
def ensure_debug_captures_dir() -> None:
|
||||
"""确保调试图像存档目录存在"""
|
||||
try:
|
||||
debug_dir = get_debug_captures_dir()
|
||||
# 确保父目录也存在
|
||||
parent_dir = os.path.dirname(debug_dir)
|
||||
if parent_dir and not os.path.exists(parent_dir):
|
||||
try:
|
||||
os.makedirs(parent_dir, exist_ok=True)
|
||||
except PermissionError as e:
|
||||
raise PermissionError(f"无权限创建调试图像目录: {parent_dir}") from e
|
||||
except OSError as e:
|
||||
raise OSError(f"创建调试图像目录失败: {parent_dir}") from e
|
||||
try:
|
||||
os.makedirs(debug_dir, exist_ok=True)
|
||||
except PermissionError as e:
|
||||
raise PermissionError(f"无权限创建调试图像目录: {debug_dir}") from e
|
||||
except OSError as e:
|
||||
raise OSError(f"创建调试图像目录失败: {debug_dir}") from e
|
||||
except (PermissionError, OSError):
|
||||
# 权限或系统错误,重新抛出
|
||||
raise
|
||||
except Exception as e:
|
||||
# 其他未知错误
|
||||
error_type = type(e).__name__
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 创建调试图像目录失败({error_type}): {e}")
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
|
||||
|
||||
def get_debug_captures_base_dir() -> str:
|
||||
"""获取调试图像存档根目录路径(不包含日期)"""
|
||||
pic_dir = path_config.get_pic_dir()
|
||||
return os.path.join(pic_dir, "debug_captures")
|
||||
@@ -0,0 +1,173 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""screenshot_manager.save_files - 双截图记录的保存接口。
|
||||
|
||||
实时操作截图(latest_attempt_<type>.png)每次都覆盖;
|
||||
成功识别存档截图(last_success_<type>.png)仅在成功时保存。
|
||||
"""
|
||||
|
||||
import os
|
||||
from PIL import Image
|
||||
|
||||
from ._common import _mgr_log
|
||||
from .paths import (
|
||||
ensure_ocr_dir,
|
||||
get_latest_attempt_path,
|
||||
get_last_success_path,
|
||||
get_ocr_dir,
|
||||
)
|
||||
|
||||
|
||||
def cleanup_ocr_dir(
|
||||
keep_latest_attempt: bool = True,
|
||||
keep_last_success: bool = True,
|
||||
keep_success_files: bool = True,
|
||||
max_files: int = 50,
|
||||
) -> int:
|
||||
"""清理OCR目录中的旧文件
|
||||
|
||||
参数:
|
||||
keep_latest_attempt: 是否保留所有 latest_attempt_*.png 文件
|
||||
keep_last_success: 是否保留所有 last_success_*.png 文件
|
||||
keep_success_files: 是否保留所有 _success.png 文件
|
||||
max_files: 最多保留的文件数(不包括特殊文件)
|
||||
|
||||
返回:
|
||||
清理的文件数量
|
||||
"""
|
||||
try:
|
||||
ocr_dir = get_ocr_dir()
|
||||
if not os.path.exists(ocr_dir):
|
||||
return 0
|
||||
|
||||
files = []
|
||||
for f in os.listdir(ocr_dir):
|
||||
file_path = os.path.join(ocr_dir, f)
|
||||
if os.path.isfile(file_path) and f.lower().endswith(".png"):
|
||||
# 检查是否为特殊文件
|
||||
is_special = False
|
||||
if f.startswith("latest_attempt_") and keep_latest_attempt:
|
||||
is_special = True
|
||||
elif f.startswith("last_success_") and keep_last_success:
|
||||
is_special = True
|
||||
elif f.endswith("_success.png") and keep_success_files:
|
||||
is_special = True
|
||||
|
||||
if not is_special:
|
||||
files.append((file_path, os.path.getmtime(file_path)))
|
||||
|
||||
# 按修改时间排序,保留最新的
|
||||
files.sort(key=lambda x: x[1], reverse=True)
|
||||
|
||||
# 删除超出限制的文件
|
||||
deleted_count = 0
|
||||
for file_path, _ in files[max_files:]:
|
||||
try:
|
||||
os.remove(file_path)
|
||||
deleted_count += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return deleted_count
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
|
||||
def save_latest_attempt(image: Image.Image, operation_type: str = "") -> bool:
|
||||
"""保存实时操作截图(覆盖保存)
|
||||
|
||||
参数:
|
||||
image: PIL Image 对象
|
||||
operation_type: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic")
|
||||
|
||||
返回:
|
||||
是否保存成功
|
||||
"""
|
||||
try:
|
||||
ensure_ocr_dir()
|
||||
path = get_latest_attempt_path(operation_type)
|
||||
image.save(path, "PNG")
|
||||
return True
|
||||
except Exception as e:
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 保存 latest_attempt_{operation_type}.png 失败: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def save_last_success(image: Image.Image, operation_type: str = "") -> bool:
|
||||
"""保存成功识别存档截图(不覆盖,仅成功时保存)
|
||||
|
||||
参数:
|
||||
image: PIL Image 对象
|
||||
operation_type: 操作类型(用于分类,如 "template_match", "pixel_detect", "ocr", "cut_pic")
|
||||
|
||||
返回:
|
||||
是否保存成功
|
||||
"""
|
||||
try:
|
||||
ensure_ocr_dir()
|
||||
path = get_last_success_path(operation_type)
|
||||
image.save(path, "PNG")
|
||||
return True
|
||||
except Exception as e:
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 保存 last_success_{operation_type}.png 失败: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool:
|
||||
"""从文件保存实时操作截图
|
||||
|
||||
参数:
|
||||
source_path: 源图片文件路径
|
||||
operation_type: 操作类型
|
||||
|
||||
返回:
|
||||
是否保存成功
|
||||
"""
|
||||
try:
|
||||
if not os.path.exists(source_path):
|
||||
return False
|
||||
image = Image.open(source_path)
|
||||
return save_latest_attempt(image, operation_type)
|
||||
except Exception as e:
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 从文件保存 latest_attempt.png 失败: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def save_success_from_file(source_path: str, operation_type: str = "") -> bool:
|
||||
"""从文件保存成功识别存档截图
|
||||
|
||||
参数:
|
||||
source_path: 源图片文件路径
|
||||
operation_type: 操作类型
|
||||
|
||||
返回:
|
||||
是否保存成功
|
||||
"""
|
||||
try:
|
||||
if not os.path.exists(source_path):
|
||||
return False
|
||||
image = Image.open(source_path)
|
||||
return save_last_success(image, operation_type)
|
||||
except Exception as e:
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 从文件保存 last_success.png 失败: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
@@ -0,0 +1,731 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""screenshot_manager.save_image - save_debug_image 主入口。
|
||||
|
||||
包含 _sanitize_filename_part(文件名规范化)与 save_debug_image
|
||||
(按 picname/operation_type/category 写入调试图像,支持异步队列)。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
import logging
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from ._common import (
|
||||
_async_save_counters_lock,
|
||||
_debug_save_queue,
|
||||
_LOGGER,
|
||||
_mgr_log,
|
||||
_SKIP_DEBUG_SAVE_IN_HOTLOOPS,
|
||||
)
|
||||
from . import _common as _state
|
||||
from .paths import (
|
||||
ensure_debug_captures_dir,
|
||||
get_category_for_picname,
|
||||
get_debug_captures_dir,
|
||||
)
|
||||
from .async_save import _ensure_debug_save_worker_started
|
||||
|
||||
|
||||
def _sanitize_filename_part(text: str) -> str:
|
||||
"""清理文件名部分,移除Windows不允许的字符
|
||||
|
||||
参数:
|
||||
text: 要清理的文本
|
||||
|
||||
返回:
|
||||
清理后的文本
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
# Windows文件名不允许的字符: < > : " / \ | ? *
|
||||
# 同时移除路径分隔符和空格(用下划线替换)
|
||||
invalid_chars = '<>:"/\\|?*'
|
||||
sanitized = str(text)
|
||||
|
||||
# 如果是路径,只保留文件名部分
|
||||
if os.sep in sanitized or "/" in sanitized:
|
||||
sanitized = os.path.basename(sanitized)
|
||||
|
||||
# 移除所有无效字符
|
||||
for char in invalid_chars:
|
||||
sanitized = sanitized.replace(char, "_")
|
||||
|
||||
# 移除连续的下划线,替换为单个下划线
|
||||
while "__" in sanitized:
|
||||
sanitized = sanitized.replace("__", "_")
|
||||
|
||||
# 移除首尾的下划线和空格
|
||||
sanitized = sanitized.strip("_").strip()
|
||||
|
||||
# 如果清理后为空,返回默认值
|
||||
if not sanitized:
|
||||
sanitized = "unknown"
|
||||
|
||||
return sanitized
|
||||
|
||||
|
||||
|
||||
|
||||
def save_debug_image( # type: ignore
|
||||
image: Image.Image,
|
||||
operation_type: str = "",
|
||||
picname: str = "",
|
||||
step: str = "",
|
||||
coords: Optional[Tuple[int, int, int, int]] = None,
|
||||
extra_info: Optional[dict] = None,
|
||||
session_id: Optional[str] = None, # noqa: ARG001
|
||||
annotate: bool = True,
|
||||
auto_cleanup: bool = True,
|
||||
background: Optional[bool] = None,
|
||||
) -> Optional[str]:
|
||||
"""保存调试图像到存档目录
|
||||
|
||||
参数:
|
||||
image: PIL Image 对象
|
||||
operation_type: 操作类型("pixel_detect", "ocr", "template_match", "cut_pic")
|
||||
picname: 图片名称(可选)
|
||||
step: 步骤描述(可选,如 "before_detect", "detected")
|
||||
coords: 坐标信息 (x1, y1, x2, y2)(可选)
|
||||
extra_info: 额外信息字典(可选)
|
||||
session_id: 会话ID(可选,默认使用当前日期,保留用于未来扩展)
|
||||
annotate: 是否在图像上添加标注信息(默认True)
|
||||
auto_cleanup: 是否自动清理旧目录(默认True)
|
||||
|
||||
返回:
|
||||
保存的文件路径,失败返回None
|
||||
"""
|
||||
try:
|
||||
# 从配置读取是否启用调试图像保存;默认关闭
|
||||
try:
|
||||
import json
|
||||
|
||||
enabled = False
|
||||
config_path = path_config.get_config_path()
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
dbg_cfg = config.get("debug_captures")
|
||||
if isinstance(dbg_cfg, dict):
|
||||
enabled = bool(dbg_cfg.get("enabled", False))
|
||||
if not enabled:
|
||||
return None
|
||||
except Exception:
|
||||
# 配置读取异常时,为安全起见直接跳过保存调试图像
|
||||
return None
|
||||
|
||||
# 自动清理旧目录(仅在每天第一次保存时执行)
|
||||
if auto_cleanup:
|
||||
try:
|
||||
# 检查今天是否已经清理过(使用简单的标记文件)
|
||||
debug_base_dir = get_debug_captures_base_dir()
|
||||
cleanup_marker = os.path.join(debug_base_dir, ".cleanup_marker")
|
||||
from datetime import datetime
|
||||
|
||||
today_str = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# 读取标记文件,检查今天是否已清理
|
||||
need_cleanup = True
|
||||
if os.path.exists(cleanup_marker):
|
||||
try:
|
||||
with open(cleanup_marker, "r", encoding="utf-8") as f:
|
||||
last_cleanup_date = f.read().strip()
|
||||
if last_cleanup_date == today_str:
|
||||
need_cleanup = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if need_cleanup:
|
||||
# 从配置读取保留天数、最大文件数和自动清理设置
|
||||
keep_days = 7 # 默认7天
|
||||
max_files = 2000 # 默认2000个文件
|
||||
cleanup_enabled = True
|
||||
try:
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
if "debug_captures" in config and isinstance(
|
||||
config["debug_captures"], dict
|
||||
):
|
||||
cleanup_enabled = config["debug_captures"].get(
|
||||
"auto_cleanup", True
|
||||
)
|
||||
keep_days = int(
|
||||
config["debug_captures"].get("keep_days", 7)
|
||||
)
|
||||
max_files = int(
|
||||
config["debug_captures"].get("max_files", 2000)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果启用自动清理,执行清理
|
||||
if cleanup_enabled:
|
||||
cleanup_debug_captures(keep_days=keep_days, max_files=max_files)
|
||||
|
||||
# 更新标记文件(仅在执行清理后更新)
|
||||
try:
|
||||
with open(cleanup_marker, "w", encoding="utf-8") as f:
|
||||
f.write(today_str)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 即使今天已经清理过,也要检查文件数量是否超过限制
|
||||
# 如果超过,立即清理(不更新标记文件,避免频繁清理)
|
||||
try:
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
max_files = 2000
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
if "debug_captures" in config and isinstance(
|
||||
config["debug_captures"], dict
|
||||
):
|
||||
max_files = int(
|
||||
config["debug_captures"].get("max_files", 2000)
|
||||
)
|
||||
|
||||
# 检查当前文件数量
|
||||
current_count = count_debug_captures_files()
|
||||
if current_count > max_files:
|
||||
# 文件数量超过限制,立即清理
|
||||
try:
|
||||
_mgr_log(
|
||||
f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
cleanup_debug_captures(
|
||||
keep_days=999, max_files=max_files
|
||||
) # keep_days设为999表示只按文件数量清理
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 清理失败不影响保存操作
|
||||
pass
|
||||
|
||||
ensure_debug_captures_dir()
|
||||
debug_dir = get_debug_captures_dir()
|
||||
|
||||
# 生成文件名
|
||||
from datetime import datetime
|
||||
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
|
||||
parts = []
|
||||
if operation_type:
|
||||
# 转换为中文
|
||||
operation_type_cn = _OPERATION_TYPE_CN.get(operation_type, operation_type)
|
||||
parts.append(_sanitize_filename_part(operation_type_cn))
|
||||
if picname:
|
||||
# 转换为中文
|
||||
picname_cn = _PICNAME_CN.get(picname, picname)
|
||||
parts.append(_sanitize_filename_part(picname_cn))
|
||||
if step:
|
||||
# 转换为中文
|
||||
step_cn = _STEP_CN.get(step, step)
|
||||
parts.append(_sanitize_filename_part(step_cn))
|
||||
if coords:
|
||||
parts.append(f"({coords[0]},{coords[1]})-({coords[2]},{coords[3]})")
|
||||
if extra_info:
|
||||
for key, value in extra_info.items():
|
||||
# 将键名转换为中文
|
||||
key_cn = _EXTRA_INFO_KEY_CN.get(key, key)
|
||||
# 清理键名和值
|
||||
clean_key = _sanitize_filename_part(str(key_cn))
|
||||
# 处理值的转换(布尔值转为中文)
|
||||
if isinstance(value, bool):
|
||||
clean_value = "是" if value else "否"
|
||||
else:
|
||||
clean_value = _sanitize_filename_part(str(value))
|
||||
# 限制值的长度,避免文件名过长
|
||||
# 对于 text_preview 等长文本,限制更短(20字符)
|
||||
if key == "text_preview" or key == "content":
|
||||
if len(clean_value) > 20:
|
||||
clean_value = clean_value[:20]
|
||||
else:
|
||||
if len(clean_value) > 30:
|
||||
clean_value = clean_value[:30]
|
||||
parts.append(f"{clean_key}_{clean_value}")
|
||||
|
||||
filename_parts = [timestamp] + parts
|
||||
filename = "_".join(str(p) for p in filename_parts if p) + ".png"
|
||||
|
||||
# Windows文件名长度限制(260字符),自动截断
|
||||
# 考虑完整路径长度,文件名部分限制更严格
|
||||
max_len = 180 # 留更多余量,考虑目录路径长度
|
||||
if len(filename) > max_len:
|
||||
# 保留时间戳和关键信息,截断其他部分
|
||||
# 优先保留:时间戳、操作类型、图片名、步骤
|
||||
base_parts = [timestamp]
|
||||
if operation_type:
|
||||
# 转换为中文
|
||||
operation_type_cn = _OPERATION_TYPE_CN.get(
|
||||
operation_type, operation_type
|
||||
)
|
||||
base_parts.append(_sanitize_filename_part(operation_type_cn))
|
||||
if picname:
|
||||
# 转换为中文
|
||||
picname_cn = _PICNAME_CN.get(picname, picname)
|
||||
base_parts.append(_sanitize_filename_part(picname_cn))
|
||||
if step:
|
||||
# 转换为中文
|
||||
step_cn = _STEP_CN.get(step, step)
|
||||
base_parts.append(_sanitize_filename_part(step_cn))
|
||||
|
||||
base = "_".join(base_parts)
|
||||
|
||||
# 如果还有空间,添加最重要的额外信息(排除长文本)
|
||||
remaining = max_len - len(base) - 10 # 留10字符余量
|
||||
if remaining > 20 and extra_info:
|
||||
important_keys = ["mode", "size", "used_img2", "avg_confidence"]
|
||||
for key in important_keys:
|
||||
if key in extra_info and remaining > 0:
|
||||
# 将键名转换为中文
|
||||
key_cn = _EXTRA_INFO_KEY_CN.get(key, key)
|
||||
clean_key = _sanitize_filename_part(str(key_cn))
|
||||
# 处理值的转换(布尔值转为中文)
|
||||
value = extra_info[key]
|
||||
if isinstance(value, bool):
|
||||
clean_value = "是" if value else "否"
|
||||
else:
|
||||
clean_value = _sanitize_filename_part(str(value))
|
||||
if len(clean_value) > 15:
|
||||
clean_value = clean_value[:15]
|
||||
part = f"{clean_key}_{clean_value}"
|
||||
if len(part) <= remaining:
|
||||
base += f"_{part}"
|
||||
remaining -= len(part) + 1
|
||||
|
||||
filename = base[:max_len] + ".png"
|
||||
|
||||
file_path = os.path.join(debug_dir, filename)
|
||||
|
||||
# 在保存文件前,再次确保目录存在(防止并发访问或权限问题导致目录不存在)
|
||||
try:
|
||||
ensure_debug_captures_dir()
|
||||
except Exception:
|
||||
pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理
|
||||
|
||||
# 根据配置决定是否后台保存(优先使用函数参数,参数为 None 时读取 config)
|
||||
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 {}
|
||||
)
|
||||
background = bool(dbg_cfg.get("async_save", True))
|
||||
else:
|
||||
background = True
|
||||
except Exception:
|
||||
background = True
|
||||
|
||||
# 保存图像的辅助函数,带重试机制
|
||||
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:
|
||||
img_to_save.save(path, "PNG")
|
||||
return True
|
||||
except FileNotFoundError as e:
|
||||
# 目录不存在,尝试创建后重试
|
||||
last_error = e
|
||||
if attempt < max_retries - 1:
|
||||
try:
|
||||
ensure_debug_captures_dir()
|
||||
except Exception as dir_error:
|
||||
# 记录目录创建失败
|
||||
try:
|
||||
_mgr_log(
|
||||
f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 最后一次尝试失败,抛出异常
|
||||
raise
|
||||
except PermissionError as e:
|
||||
# 权限错误,不重试
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
except OSError as e:
|
||||
# 系统级错误(磁盘空间不足等),不重试
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
except Exception as e:
|
||||
# 其他异常直接抛出
|
||||
last_error = e
|
||||
raise
|
||||
# 所有重试都失败
|
||||
if last_error:
|
||||
raise last_error
|
||||
return False
|
||||
|
||||
# 如果选择后台保存,入队并返回 None(不阻塞主线程)
|
||||
if background:
|
||||
try:
|
||||
# 如果在高频路径中要求跳过调试保存(通过环境变量控制),则直接跳过以免阻塞或占用IO
|
||||
if _SKIP_DEBUG_SAVE_IN_HOTLOOPS and operation_type in (
|
||||
"pixel_detect",
|
||||
"cut_pic",
|
||||
"pixel",
|
||||
):
|
||||
try:
|
||||
logging.debug(
|
||||
"[截图管理] 跳过热路径调试保存: %s %s",
|
||||
operation_type,
|
||||
picname,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
_ensure_debug_save_worker_started()
|
||||
# 放入队列(复制 image 避免被外部修改)
|
||||
try:
|
||||
img_copy = image.copy()
|
||||
except Exception:
|
||||
img_copy = image
|
||||
t0 = time.time()
|
||||
_debug_save_queue.put(
|
||||
(
|
||||
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,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
except Exception:
|
||||
# 如果队列机制失败,回退到同步保存
|
||||
pass
|
||||
|
||||
# 如果需要标注,在图像上添加信息
|
||||
if annotate and (coords or extra_info):
|
||||
try:
|
||||
from PIL import ImageDraw, ImageFont
|
||||
|
||||
annotated_image = image.copy()
|
||||
draw = ImageDraw.Draw(annotated_image)
|
||||
|
||||
# 尝试使用默认字体
|
||||
try:
|
||||
font = ImageFont.truetype("arial.ttf", 12)
|
||||
except Exception:
|
||||
try:
|
||||
font = ImageFont.load_default()
|
||||
except Exception:
|
||||
font = None
|
||||
|
||||
# 绘制坐标框
|
||||
if coords:
|
||||
x1, y1, x2, y2 = coords
|
||||
# 确保坐标在图像范围内
|
||||
img_w, img_h = annotated_image.size
|
||||
x1 = max(0, min(x1, img_w - 1))
|
||||
y1 = max(0, min(y1, img_h - 1))
|
||||
x2 = max(0, min(x2, img_w - 1))
|
||||
y2 = max(0, min(y2, img_h - 1))
|
||||
|
||||
if x1 < x2 and y1 < y2:
|
||||
# 使用元组格式 (x1, y1, x2, y2)
|
||||
rect_coords: Tuple[float, float, float, float] = (
|
||||
float(x1),
|
||||
float(y1),
|
||||
float(x2),
|
||||
float(y2),
|
||||
)
|
||||
draw.rectangle(rect_coords, outline="red", width=2)
|
||||
|
||||
# 添加文本信息:统一使用底部半透明信息栏,风格与 OCR 调试图一致
|
||||
try:
|
||||
info_lines = []
|
||||
# 基础信息行:图片名 / 步骤
|
||||
if picname:
|
||||
info_lines.append(str(_PICNAME_CN.get(picname, picname)))
|
||||
if step:
|
||||
info_lines.append(str(_STEP_CN.get(step, step)))
|
||||
|
||||
# 坐标与额外信息优先展示重要字段
|
||||
if coords:
|
||||
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",
|
||||
]
|
||||
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)}"
|
||||
)
|
||||
# 将其余的键也加入(但限制长度)
|
||||
for k, v in extra_info.items():
|
||||
if k in important_keys:
|
||||
continue
|
||||
# 限制文本长度,避免溢出
|
||||
s = str(v)
|
||||
if len(s) > 30:
|
||||
s = s[:30] + "..."
|
||||
info_lines.append(f"{_EXTRA_INFO_KEY_CN.get(k, k)}: {s}")
|
||||
|
||||
# 如果没有任何信息,则不绘制信息栏
|
||||
if info_lines:
|
||||
# 准备RGBA图层以绘制半透明底栏
|
||||
if annotated_image.mode != "RGBA":
|
||||
annotated_image = annotated_image.convert("RGBA")
|
||||
overlay = Image.new("RGBA", annotated_image.size, (0, 0, 0, 0))
|
||||
odraw = ImageDraw.Draw(overlay)
|
||||
|
||||
# 计算文字区域高度
|
||||
padding_v = 6
|
||||
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:
|
||||
# Preferred: ImageDraw.textbbox -> returns (left, top, right, bottom)
|
||||
if hasattr(odraw, "textbbox"):
|
||||
l, t, r, b = odraw.textbbox((0, 0), text, font=font)
|
||||
return (r - l, b - t)
|
||||
# Fallbacks using ImageFont methods compatible with different Pillow versions
|
||||
if font is not None:
|
||||
# Prefer font.getbbox if available
|
||||
if hasattr(font, "getbbox"):
|
||||
try:
|
||||
l, t, r, b = font.getbbox(text)
|
||||
return (r - l, b - t)
|
||||
except Exception:
|
||||
pass
|
||||
# Fallback: use font.getmask to get rendered size
|
||||
try:
|
||||
mask = font.getmask(text)
|
||||
return (mask.size[0], mask.size[1])
|
||||
except Exception:
|
||||
pass
|
||||
# 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)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
# Conservative fallback estimate
|
||||
return (len(text) * 7, 14)
|
||||
|
||||
for line in info_lines:
|
||||
# 简单换行:如果太长,切断
|
||||
w, h = _measure_text(line)
|
||||
if w > max_width:
|
||||
# 估算每行能容纳的字符数并切断
|
||||
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)
|
||||
|
||||
# Compute line height using safe measurement
|
||||
try:
|
||||
line_height = _measure_text("Ay")[1]
|
||||
except Exception:
|
||||
line_height = 14
|
||||
bar_height = padding_v * 2 + line_height * len(lines_to_draw)
|
||||
img_w, img_h = annotated_image.size
|
||||
bar_y1 = img_h - bar_height
|
||||
bar_y2 = img_h
|
||||
|
||||
# 绘制半透明白色底栏
|
||||
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,
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
odraw.text(
|
||||
(text_x, text_y), line, fill=(10, 10, 10, 255)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
text_y += line_height
|
||||
|
||||
# 如果 extra_info 中包含匹配坐标(match_coords)或检测像素坐标(detected_x_scaled),绘制点/框以便快速定位
|
||||
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
|
||||
):
|
||||
mx1, my1, mx2, my2 = extra_info["match_coords"]
|
||||
# 在 overlay 上画红框
|
||||
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),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 合并 overlay 到原图并保存
|
||||
try:
|
||||
annotated_image = Image.alpha_composite(
|
||||
annotated_image, overlay
|
||||
)
|
||||
# 转回 RGB 保存为PNG,以减少兼容问题
|
||||
annotated_image = annotated_image.convert("RGB")
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 标注失败,回退到原有行为(什么也不画)
|
||||
pass
|
||||
|
||||
save_image_with_retry(annotated_image, file_path)
|
||||
except (PermissionError, OSError) as e:
|
||||
# 权限或系统错误,尝试保存原图
|
||||
try:
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
save_image_with_retry(image, file_path)
|
||||
except Exception:
|
||||
# 如果保存原图也失败,抛出异常让外层处理
|
||||
raise
|
||||
except Exception as e:
|
||||
# 其他标注错误,尝试保存原图
|
||||
try:
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 图像标注失败,尝试保存原图: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
save_image_with_retry(image, file_path)
|
||||
except Exception:
|
||||
# 如果保存原图也失败,抛出异常让外层处理
|
||||
raise
|
||||
else:
|
||||
save_image_with_retry(image, file_path)
|
||||
|
||||
return file_path
|
||||
except FileNotFoundError as e:
|
||||
# 文件或目录不存在
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 保存调试图像失败(文件/目录不存在): {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
except PermissionError as e:
|
||||
# 权限错误
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 保存调试图像失败(权限错误): {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
except OSError as e:
|
||||
# 系统级错误(磁盘空间不足、路径过长等)
|
||||
try:
|
||||
_mgr_log(f"[截图管理] 保存调试图像失败(系统错误): {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
except Exception as e:
|
||||
# 其他未知错误
|
||||
try:
|
||||
error_type = type(e).__name__
|
||||
_mgr_log(f"[截图管理] 保存调试图像失败({error_type}): {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
# 结束 save_debug_image 的主逻辑,返回 None 表示保存失败
|
||||
return None
|
||||
+43
-1409
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,56 @@
|
||||
"""douyin_logging_pkg - 日志系统子包。
|
||||
|
||||
原 douyin/logging/douyin_logging.py 拆成 5 个子模块:
|
||||
|
||||
- _common 共享全局状态:_logging_configured / _logger_cache / _log_monitor
|
||||
- handlers 自定义 handler:RotatingDatedFileHandler / DatedFileHandler
|
||||
- cleanup 压缩与清理:compress_log_file / cleanup_old_logs
|
||||
- monitor 监控线程:LogRotationMonitor / start_log_monitor / stop_log_monitor / get_log_stats
|
||||
- config 主配置入口:get_logger / configure_logging / log_function_call / LogContext
|
||||
|
||||
外部 import 路径不变:
|
||||
``from douyin.logging.douyin_logging import configure_logging`` 仍可用
|
||||
(原文件改成 re-export shim)。
|
||||
"""
|
||||
|
||||
from .handlers import (
|
||||
DatedFileHandler,
|
||||
RotatingDatedFileHandler,
|
||||
)
|
||||
from .cleanup import (
|
||||
_load_logging_cleanup_policy_from_config,
|
||||
cleanup_old_logs,
|
||||
compress_log_file,
|
||||
)
|
||||
from .monitor import (
|
||||
LogRotationMonitor,
|
||||
get_log_stats,
|
||||
start_log_monitor,
|
||||
stop_log_monitor,
|
||||
)
|
||||
from .config import (
|
||||
LogContext,
|
||||
configure_logging,
|
||||
format_exception_info,
|
||||
get_caller_info,
|
||||
get_logger,
|
||||
log_function_call,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"RotatingDatedFileHandler",
|
||||
"DatedFileHandler",
|
||||
"compress_log_file",
|
||||
"cleanup_old_logs",
|
||||
"_load_logging_cleanup_policy_from_config",
|
||||
"get_logger",
|
||||
"configure_logging",
|
||||
"log_function_call",
|
||||
"LogContext",
|
||||
"get_caller_info",
|
||||
"format_exception_info",
|
||||
"LogRotationMonitor",
|
||||
"start_log_monitor",
|
||||
"stop_log_monitor",
|
||||
"get_log_stats",
|
||||
]
|
||||
@@ -0,0 +1,21 @@
|
||||
"""douyin_logging_pkg._common - 共享全局状态。
|
||||
|
||||
被 handlers / cleanup / config / monitor 子模块共用:
|
||||
- _logging_configured:configure_logging 是否已调用过
|
||||
- _logger_cache:get_logger 缓存
|
||||
- _log_monitor:LogRotationMonitor 实例(懒初始化)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Dict, Optional, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .monitor import LogRotationMonitor
|
||||
|
||||
# 全局日志配置
|
||||
_logging_configured = False
|
||||
_logger_cache: Dict[str, logging.Logger] = {}
|
||||
|
||||
# 日志监控器实例(懒启动 / 在 start_log_monitor 内创建)
|
||||
_log_monitor: "Optional[LogRotationMonitor]" = None
|
||||
@@ -0,0 +1,282 @@
|
||||
"""douyin_logging_pkg.cleanup - 日志压缩与清理策略。
|
||||
|
||||
- compress_log_file 压缩单个日志文件为 .gz
|
||||
- cleanup_old_logs 按大小 / 数量 / 天数三重清理
|
||||
- _load_logging_cleanup_policy_from_config 从 config.json 读取清理策略
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import gzip
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
def compress_log_file(log_file: str) -> bool:
|
||||
"""压缩单个日志文件
|
||||
|
||||
参数:
|
||||
log_file: 日志文件路径
|
||||
|
||||
返回:
|
||||
是否压缩成功
|
||||
"""
|
||||
try:
|
||||
if not os.path.exists(log_file):
|
||||
return False
|
||||
|
||||
# 检查文件大小,只有较大文件才压缩
|
||||
file_size = os.path.getsize(log_file)
|
||||
if file_size < 1024 * 1024: # 小于1MB不压缩
|
||||
return False
|
||||
|
||||
compressed_file = log_file + ".gz"
|
||||
|
||||
# 如果压缩文件已存在,跳过
|
||||
if os.path.exists(compressed_file):
|
||||
return False
|
||||
|
||||
# 压缩文件
|
||||
with open(log_file, "rb") as f_in:
|
||||
with gzip.open(compressed_file, "wb", compresslevel=9) as f_out:
|
||||
shutil.copyfileobj(f_in, f_out)
|
||||
|
||||
# 验证压缩文件
|
||||
if os.path.exists(compressed_file):
|
||||
compressed_size = os.path.getsize(compressed_file)
|
||||
if compressed_size > 0:
|
||||
# 删除原文件
|
||||
os.remove(log_file)
|
||||
try:
|
||||
print(
|
||||
f"[日志压缩] 压缩完成: {os.path.basename(log_file)} "
|
||||
f"({file_size/1024:.1f}KB -> {compressed_size/1024:.1f}KB, "
|
||||
f"压缩率: {compressed_size/file_size*100:.1f}%)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
return False
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[日志压缩] 压缩失败 {log_file}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def cleanup_old_logs(
|
||||
logs_dir: str,
|
||||
base_name: str,
|
||||
keep_days: int = 30,
|
||||
max_total_size_gb: float = 10.0, # 最大总大小(GB)
|
||||
compress_after_days: int = 7, # 几天后压缩
|
||||
compress: bool = True,
|
||||
) -> Dict[str, int]:
|
||||
"""智能清理旧日志文件:支持时间、大小、压缩三重策略
|
||||
|
||||
参数:
|
||||
logs_dir: 日志目录路径
|
||||
base_name: 日志文件基础名称(不含日期和扩展名),如 "unified"
|
||||
keep_days: 保留天数,默认30天
|
||||
max_total_size_gb: 最大总大小(GB),默认10GB
|
||||
compress_after_days: 几天后压缩,默认7天
|
||||
compress: 是否启用压缩,默认True
|
||||
|
||||
返回:
|
||||
清理统计信息
|
||||
"""
|
||||
stats = {
|
||||
"deleted": 0,
|
||||
"compressed": 0,
|
||||
"total_size_mb": 0.0,
|
||||
"freed_space_mb": 0.0,
|
||||
}
|
||||
|
||||
def _safe_get_mtime(path: str) -> float:
|
||||
try:
|
||||
return os.path.getmtime(path)
|
||||
except Exception:
|
||||
return 0.0
|
||||
|
||||
def _safe_get_size(path: str) -> int:
|
||||
try:
|
||||
return os.path.getsize(path)
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
try:
|
||||
if not os.path.exists(logs_dir):
|
||||
return stats
|
||||
|
||||
# 收集所有相关日志文件(包括压缩文件)
|
||||
patterns = [
|
||||
os.path.join(logs_dir, f"{base_name}_*.log"),
|
||||
os.path.join(logs_dir, f"{base_name}_*.log.gz"),
|
||||
]
|
||||
|
||||
all_files: list[str] = []
|
||||
for pattern in patterns:
|
||||
for p in glob.glob(pattern):
|
||||
# 并发轮转/删除时避免后续排序抛 FileNotFoundError
|
||||
if os.path.exists(p):
|
||||
all_files.append(p)
|
||||
|
||||
if not all_files:
|
||||
return stats
|
||||
|
||||
# 按修改时间排序(最新的在前)
|
||||
all_files.sort(key=_safe_get_mtime, reverse=True)
|
||||
|
||||
# 计算总大小
|
||||
total_size = sum(_safe_get_size(f) for f in all_files if os.path.exists(f))
|
||||
stats["total_size_mb"] = total_size / 1024 / 1024
|
||||
|
||||
# 如果总大小超过限制,先删除最旧的文件
|
||||
max_total_size_bytes = max_total_size_gb * 1024 * 1024 * 1024
|
||||
if total_size > max_total_size_bytes:
|
||||
# 按时间排序,删除最旧的
|
||||
sorted_files = sorted(
|
||||
[f for f in all_files if os.path.exists(f)],
|
||||
key=_safe_get_mtime,
|
||||
)
|
||||
|
||||
for log_file in sorted_files:
|
||||
if total_size <= max_total_size_bytes:
|
||||
break
|
||||
|
||||
try:
|
||||
file_size = _safe_get_size(log_file)
|
||||
os.remove(log_file)
|
||||
total_size -= file_size
|
||||
stats["deleted"] += 1
|
||||
stats["freed_space_mb"] += file_size / 1024 / 1024
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[日志清理] 删除文件失败 {log_file}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 处理每个文件:压缩或删除
|
||||
cutoff_date = datetime.now() - timedelta(days=keep_days)
|
||||
compress_date = datetime.now() - timedelta(days=compress_after_days)
|
||||
|
||||
for log_file in all_files:
|
||||
try:
|
||||
if not os.path.exists(log_file):
|
||||
continue
|
||||
|
||||
# 从文件名提取日期
|
||||
filename = os.path.basename(log_file)
|
||||
# 处理压缩文件扩展名
|
||||
if filename.endswith(".gz"):
|
||||
filename = filename[:-3]
|
||||
|
||||
# 提取日期部分
|
||||
date_part = filename.replace(f"{base_name}_", "").split(".")[0]
|
||||
|
||||
try:
|
||||
file_date = datetime.strptime(date_part, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
# 如果超过保留天数,删除
|
||||
if file_date < cutoff_date:
|
||||
file_size = os.path.getsize(log_file)
|
||||
os.remove(log_file)
|
||||
stats["deleted"] += 1
|
||||
stats["freed_space_mb"] += file_size / 1024 / 1024
|
||||
|
||||
# 如果超过压缩天数且未压缩,压缩
|
||||
elif (
|
||||
compress
|
||||
and file_date < compress_date
|
||||
and not log_file.endswith(".gz")
|
||||
):
|
||||
if compress_log_file(log_file):
|
||||
stats["compressed"] += 1
|
||||
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[日志清理] 处理文件失败 {log_file}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 输出统计信息
|
||||
if stats["deleted"] > 0 or stats["compressed"] > 0:
|
||||
try:
|
||||
print(
|
||||
f"[日志清理] 完成 - 删除:{stats['deleted']}, 压缩:{stats['compressed']}, "
|
||||
f"释放:{stats['freed_space_mb']:.1f}MB"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[日志清理] 清理过程出错: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
|
||||
|
||||
def _load_logging_cleanup_policy_from_config() -> tuple[int, float, int, bool]:
|
||||
"""从 config/config.json 读取日志清理策略。
|
||||
|
||||
返回:
|
||||
(keep_days, max_total_size_gb, compress_after_days, compress)
|
||||
|
||||
说明:
|
||||
- 只负责读取与容错;不做“阈值联动”的业务决策。
|
||||
- 读取失败时回退到模块默认值。
|
||||
"""
|
||||
keep_days = 30
|
||||
max_total_size_gb = 10.0
|
||||
compress_after_days = 7
|
||||
compress = True
|
||||
|
||||
try:
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
if not os.path.exists(config_path):
|
||||
return keep_days, max_total_size_gb, compress_after_days, compress
|
||||
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
|
||||
log_cfg = cfg.get("logging", {})
|
||||
if isinstance(log_cfg, dict):
|
||||
keep_days = int(log_cfg.get("keep_days", keep_days))
|
||||
max_total_size_gb = float(
|
||||
log_cfg.get("max_total_size_gb", max_total_size_gb)
|
||||
)
|
||||
compress_after_days = int(
|
||||
log_cfg.get("compress_after_days", compress_after_days)
|
||||
)
|
||||
compress = bool(log_cfg.get("compress_logs", compress))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 基础兜底,避免异常配置导致“全部删光/不清理”
|
||||
if keep_days < 0:
|
||||
keep_days = 0
|
||||
if compress_after_days < 0:
|
||||
compress_after_days = 0
|
||||
if max_total_size_gb <= 0:
|
||||
# 若用户配置为 0/负数,视为禁用“按总量限制”,回退到默认
|
||||
max_total_size_gb = 10.0
|
||||
|
||||
return keep_days, max_total_size_gb, compress_after_days, compress
|
||||
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
"""douyin_logging_pkg.config - 日志配置与工具。
|
||||
|
||||
- get_logger 带缓存的 logger 获取
|
||||
- configure_logging 主配置入口(应用 handlers + cleanup + monitor)
|
||||
- log_function_call 性能装饰器:记录函数调用耗时与异常
|
||||
- LogContext 上下文管理器:记录代码块执行时间
|
||||
- get_caller_info 栈帧信息抓取
|
||||
- format_exception_info 异常堆栈格式化
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from functools import wraps
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from . import _common as _state
|
||||
from .handlers import DatedFileHandler, RotatingDatedFileHandler
|
||||
from .cleanup import (
|
||||
_load_logging_cleanup_policy_from_config,
|
||||
cleanup_old_logs,
|
||||
compress_log_file,
|
||||
)
|
||||
from .monitor import start_log_monitor
|
||||
|
||||
|
||||
def get_logger(name: Optional[str] = None) -> logging.Logger:
|
||||
"""获取指定名称的 logger,如果未配置则自动配置"""
|
||||
if not _state._logging_configured:
|
||||
configure_logging()
|
||||
|
||||
# Ensure name is never None
|
||||
if name is None:
|
||||
# 自动获取调用者模块名
|
||||
frame = None
|
||||
try:
|
||||
frame = inspect.currentframe()
|
||||
if frame and frame.f_back:
|
||||
caller_frame = frame.f_back
|
||||
name = caller_frame.f_globals.get("__name__", "root")
|
||||
else:
|
||||
name = "root"
|
||||
except Exception:
|
||||
name = "root"
|
||||
finally:
|
||||
if frame is not None:
|
||||
try:
|
||||
del frame
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Final fallback to ensure name is a string
|
||||
logger_name: str = name if name is not None else "root"
|
||||
if logger_name not in _state._logger_cache:
|
||||
_state._logger_cache[logger_name] = logging.getLogger(logger_name)
|
||||
|
||||
return _state._logger_cache[logger_name]
|
||||
|
||||
|
||||
|
||||
|
||||
def configure_logging(
|
||||
log_level: Optional[str] = None,
|
||||
log_file: Optional[str] = None,
|
||||
max_bytes: int = 10 * 1024 * 1024, # 10MB
|
||||
backup_count: int = 5, # 同一日期内保留的文件数
|
||||
enable_console: bool = True,
|
||||
enable_file: bool = True,
|
||||
keep_days: Optional[int] = None, # 保留日志天数
|
||||
use_dated_logs: Optional[bool] = None, # 是否使用按日期分割的日志
|
||||
compress_logs: Optional[bool] = None, # 是否压缩旧日志
|
||||
max_total_size_gb: float = 10.0, # 最大总日志大小(GB)
|
||||
compress_after_days: int = 7, # 几天后压缩
|
||||
enable_monitor: Optional[bool] = None, # 是否启用日志监控(仅启动阶段检查;运行时监控需显式开启)
|
||||
monitor_warning_mb: Optional[float] = None, # 监控警告大小(MB)
|
||||
monitor_critical_mb: Optional[float] = None, # 监控严重大小(MB)
|
||||
) -> None:
|
||||
"""配置日志系统
|
||||
|
||||
参数:
|
||||
log_level: 日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL),默认从 config.json 读取
|
||||
log_file: 日志文件基础路径,默认使用 logs/unified.log(会被转换为 logs/unified)
|
||||
max_bytes: 单个日志文件最大大小(字节),超过后轮转,默认100MB
|
||||
backup_count: 保留的备份文件数量,默认10
|
||||
enable_console: 是否输出到控制台
|
||||
enable_file: 是否输出到文件
|
||||
keep_days: 保留日志的天数,超过此天数的日志将被自动删除,默认30天
|
||||
use_dated_logs: 是否使用按日期分割的日志,默认True
|
||||
compress_logs: 是否压缩旧日志,默认True
|
||||
max_total_size_gb: 最大总日志大小(GB),超过后删除最旧文件,默认10GB
|
||||
compress_after_days: 几天后压缩日志,默认7天
|
||||
enable_monitor: 是否启用日志监控(默认从 config.json 读取;仅影响启动阶段检查)
|
||||
monitor_warning_mb: 监控警告大小阈值(MB),默认500MB
|
||||
monitor_critical_mb: 监控严重大小阈值(MB),默认2000MB
|
||||
"""
|
||||
|
||||
# rotation 相关默认值(函数级),确保在所有分支可用,避免可能的未赋值使用
|
||||
rotation_enabled = False
|
||||
rotation_when = None
|
||||
rotation_interval = 1
|
||||
|
||||
# 从 config.json 读取配置
|
||||
if (
|
||||
log_level is None
|
||||
or log_file is None
|
||||
or keep_days is None
|
||||
or use_dated_logs 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:
|
||||
config = json.load(f)
|
||||
if log_level is None:
|
||||
log_level = config.get("log_level", "INFO")
|
||||
if log_file is None:
|
||||
# 优先读取 log_unified_path,其次读取 logging.file_path
|
||||
log_file = config.get("log_unified_path") or config.get(
|
||||
"logging", {}
|
||||
).get("file_path", "logs/unified.log")
|
||||
log_config = config.get("logging", {})
|
||||
if keep_days is None:
|
||||
keep_days = log_config.get("keep_days", 30)
|
||||
if use_dated_logs is None:
|
||||
use_dated_logs = log_config.get("use_dated_logs", True)
|
||||
if compress_logs is None:
|
||||
compress_logs = log_config.get("compress_logs", True)
|
||||
if max_total_size_gb == 10.0: # 如果是默认值,从配置读取
|
||||
max_total_size_gb = log_config.get("max_total_size_gb", 10.0)
|
||||
if compress_after_days == 7: # 如果是默认值,从配置读取
|
||||
compress_after_days = log_config.get("compress_after_days", 7)
|
||||
|
||||
# 读取 monitor 配置
|
||||
if enable_monitor is None:
|
||||
enable_monitor = bool(log_config.get("enable_monitor", False))
|
||||
if monitor_warning_mb is None:
|
||||
try:
|
||||
monitor_warning_mb = float(log_config.get("monitor_warning_mb", 500.0))
|
||||
except Exception:
|
||||
monitor_warning_mb = 500.0
|
||||
if monitor_critical_mb is None:
|
||||
try:
|
||||
monitor_critical_mb = float(log_config.get("monitor_critical_mb", 2000.0))
|
||||
except Exception:
|
||||
monitor_critical_mb = 2000.0
|
||||
|
||||
# 读取 rotation 配置(优先级高于函数默认参数)
|
||||
rotation_cfg = (
|
||||
log_config.get("rotation", {})
|
||||
if isinstance(log_config, dict)
|
||||
else {}
|
||||
)
|
||||
rotation_enabled = rotation_cfg.get("enabled", True)
|
||||
if rotation_cfg:
|
||||
# 支持按大小与按时间的配置
|
||||
max_bytes = rotation_cfg.get("max_bytes", max_bytes)
|
||||
backup_count = rotation_cfg.get("backup_count", backup_count)
|
||||
rotation_when = rotation_cfg.get("when")
|
||||
rotation_interval = rotation_cfg.get("interval", 1)
|
||||
else:
|
||||
rotation_when = None
|
||||
rotation_interval = 1
|
||||
except Exception:
|
||||
if log_level is None:
|
||||
log_level = "INFO"
|
||||
if log_file is None:
|
||||
log_file = "logs/unified.log"
|
||||
if keep_days is None:
|
||||
keep_days = 30
|
||||
if use_dated_logs is None:
|
||||
use_dated_logs = True
|
||||
if compress_logs is None:
|
||||
compress_logs = True
|
||||
|
||||
if enable_monitor is None:
|
||||
enable_monitor = False
|
||||
if monitor_warning_mb is None:
|
||||
monitor_warning_mb = 500.0
|
||||
if monitor_critical_mb is None:
|
||||
monitor_critical_mb = 2000.0
|
||||
|
||||
# rotation 默认值(当读取 config 出错时)
|
||||
rotation_when = None
|
||||
rotation_interval = 1
|
||||
rotation_enabled = False
|
||||
|
||||
# 规范化 monitor 默认值
|
||||
if enable_monitor is None:
|
||||
enable_monitor = False
|
||||
if monitor_warning_mb is None:
|
||||
monitor_warning_mb = 500.0
|
||||
if monitor_critical_mb is None:
|
||||
monitor_critical_mb = 2000.0
|
||||
|
||||
# 规范化日志级别
|
||||
if log_level is None:
|
||||
log_level = "INFO"
|
||||
numeric_level = getattr(logging, log_level.upper(), logging.INFO)
|
||||
|
||||
# 配置根 logger
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(numeric_level)
|
||||
|
||||
# 清除已有的 handlers(避免重复配置)
|
||||
root_logger.handlers.clear()
|
||||
|
||||
# 简化的日志格式:时间戳 - [级别] - [模块] - 消息
|
||||
# 去掉了冗余的线程名、函数名、行号、traceId等信息,使日志更简洁
|
||||
detailed_format = "%(asctime)s - [%(levelname)s] - [%(name)s] - %(message)s"
|
||||
simple_format = "%(asctime)s - [%(levelname)s] - %(message)s"
|
||||
|
||||
# 控制台输出
|
||||
if enable_console:
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(numeric_level)
|
||||
console_formatter = logging.Formatter(
|
||||
simple_format, datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
console_handler.setFormatter(console_formatter)
|
||||
|
||||
class ConsoleSuppressFilter(logging.Filter):
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
return not getattr(record, "suppress_console_output", False)
|
||||
|
||||
console_handler.addFilter(ConsoleSuppressFilter())
|
||||
root_logger.addHandler(console_handler)
|
||||
|
||||
# 文件输出(按日期分割或传统轮转)
|
||||
if enable_file:
|
||||
try:
|
||||
# 确保日志目录存在
|
||||
if log_file is None:
|
||||
log_file = "logs/unified.log" # 默认值
|
||||
if not os.path.isabs(log_file):
|
||||
log_file = os.path.join(path_config.PROJECT_ROOT, log_file)
|
||||
|
||||
# 如果是使用日期日志,提取基础文件名(移除扩展名)
|
||||
if use_dated_logs:
|
||||
# 从完整路径提取基础名称,例如: logs/unified.log -> logs/unified
|
||||
if log_file:
|
||||
base_filename = log_file.replace(".log", "")
|
||||
else:
|
||||
base_filename = "logs/unified"
|
||||
log_dir = os.path.dirname(base_filename)
|
||||
|
||||
# 确保目录存在
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# 使用增强的轮转Handler
|
||||
# 支持每次运行生成独立文件(per_run):在 base_filename 后追加运行时间戳,并在 handler 中关闭日期轮转
|
||||
per_run = False
|
||||
try:
|
||||
per_run = (
|
||||
bool(log_config.get("per_run", True))
|
||||
if isinstance(log_config, dict)
|
||||
else True
|
||||
)
|
||||
except Exception:
|
||||
per_run = True
|
||||
|
||||
# base_filename_base: 不带运行时间戳/扩展名的基础名,用于清理和监控
|
||||
base_filename_base = base_filename
|
||||
if per_run:
|
||||
run_ts = datetime.now().strftime("%Y-%m-%d_%H%M%S")
|
||||
base_filename = f"{base_filename_base}_{run_ts}"
|
||||
|
||||
file_handler = RotatingDatedFileHandler(
|
||||
base_filename,
|
||||
date_format="%Y-%m-%d",
|
||||
max_bytes=max_bytes,
|
||||
backup_count=backup_count,
|
||||
encoding="utf-8-sig",
|
||||
mode="a",
|
||||
errors="replace",
|
||||
compress_old=compress_logs if compress_logs is not None else True,
|
||||
per_run=per_run,
|
||||
)
|
||||
|
||||
# 启动时检查总日志大小:若超过警告阈值则同步清理一次(仅在启动执行)
|
||||
if keep_days is not None:
|
||||
try:
|
||||
# 计算当前日志总大小(MB)
|
||||
pattern = os.path.join(
|
||||
log_dir or path_config.get_logs_dir(),
|
||||
f"{os.path.basename(base_filename_base)}_*.log*",
|
||||
)
|
||||
total_size = 0
|
||||
for p in glob.glob(pattern):
|
||||
try:
|
||||
if os.path.exists(p):
|
||||
total_size += os.path.getsize(p)
|
||||
except Exception:
|
||||
pass
|
||||
total_size_mb = total_size / 1024.0 / 1024.0
|
||||
except Exception:
|
||||
total_size_mb = 0.0
|
||||
|
||||
try:
|
||||
if total_size_mb >= float(monitor_warning_mb or 500.0):
|
||||
# 同步清理一次(仅在启动阶段)
|
||||
cleanup_old_logs(
|
||||
log_dir or path_config.get_logs_dir(),
|
||||
os.path.basename(base_filename_base),
|
||||
keep_days=keep_days,
|
||||
max_total_size_gb=max_total_size_gb,
|
||||
compress_after_days=compress_after_days,
|
||||
compress=(
|
||||
compress_logs if compress_logs is not None else True
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 注意:按用户反馈,默认不在运行过程中做日志目录体积检查。
|
||||
# 仅当显式开启运行时监控时才启动后台线程(避免主流程中途 I/O 干扰与刷屏)。
|
||||
runtime_monitor_enabled = False
|
||||
try:
|
||||
runtime_monitor_enabled = bool(
|
||||
(log_config.get("enable_runtime_monitor", False) if isinstance(log_config, dict) else False)
|
||||
)
|
||||
except Exception:
|
||||
runtime_monitor_enabled = False
|
||||
|
||||
# 环境变量可强制开启(便于临时诊断)
|
||||
if os.environ.get("ENABLE_RUNTIME_LOG_MONITOR") == "1":
|
||||
runtime_monitor_enabled = True
|
||||
|
||||
if runtime_monitor_enabled:
|
||||
try:
|
||||
monitor_check_interval = 300
|
||||
try:
|
||||
if isinstance(log_config, dict):
|
||||
monitor_check_interval = int(
|
||||
log_config.get("monitor_check_interval", 300)
|
||||
)
|
||||
except Exception:
|
||||
monitor_check_interval = 300
|
||||
|
||||
start_log_monitor(
|
||||
logs_dir=log_dir or path_config.get_logs_dir(),
|
||||
base_name=os.path.basename(base_filename_base),
|
||||
warning_size_mb=float(monitor_warning_mb),
|
||||
critical_size_mb=float(monitor_critical_mb),
|
||||
check_interval=monitor_check_interval,
|
||||
enable_runtime_cleanup=bool(
|
||||
(log_config.get("enable_runtime_cleanup", False) if isinstance(log_config, dict) else False)
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[日志配置] 启动运行时监控器失败: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 使用传统的RotatingFileHandler
|
||||
if log_file is None:
|
||||
log_file = "logs/unified.log" # 默认值
|
||||
log_dir = os.path.dirname(log_file)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# 如果配置了按时间轮转(when),使用 TimedRotatingFileHandler
|
||||
try:
|
||||
if rotation_enabled and rotation_when:
|
||||
file_handler = logging.handlers.TimedRotatingFileHandler(
|
||||
log_file,
|
||||
when=rotation_when,
|
||||
interval=rotation_interval,
|
||||
backupCount=backup_count,
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
)
|
||||
else:
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_file, # type: ignore[arg-type]
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
)
|
||||
except Exception:
|
||||
# 回退到大小轮转
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_file, # type: ignore[arg-type]
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
)
|
||||
|
||||
file_handler.setLevel(numeric_level)
|
||||
# 使用自定义Formatter以支持traceId
|
||||
try:
|
||||
from douyin.logging.unified_logger import UnifiedFormatter
|
||||
|
||||
file_formatter = UnifiedFormatter(
|
||||
detailed_format, datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
except ImportError:
|
||||
# 如果unified_logger不可用,使用标准Formatter
|
||||
file_formatter = logging.Formatter(
|
||||
detailed_format, datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
|
||||
# 添加traceId占位符处理
|
||||
class TraceIdFormatter(logging.Formatter):
|
||||
def format(self, record):
|
||||
if not hasattr(record, "traceId"):
|
||||
record.traceId = "N/A"
|
||||
return super().format(record)
|
||||
|
||||
file_formatter = TraceIdFormatter(
|
||||
detailed_format, datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
file_formatter.default_msec_format = "%s.%03d" # 毫秒精度
|
||||
file_handler.setFormatter(file_formatter)
|
||||
|
||||
class FileSuppressFilter(logging.Filter):
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
return not getattr(record, "suppress_file_output", False)
|
||||
|
||||
file_handler.addFilter(FileSuppressFilter())
|
||||
root_logger.addHandler(file_handler)
|
||||
except Exception as e:
|
||||
# 文件 handler 创建失败,只输出到控制台
|
||||
try:
|
||||
print(f"[日志配置] 警告:无法创建日志文件 {log_file}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_state._logging_configured = True
|
||||
|
||||
|
||||
|
||||
|
||||
def log_function_call(
|
||||
logger: Optional[logging.Logger] = None,
|
||||
log_args: bool = True,
|
||||
log_result: bool = False,
|
||||
log_time: bool = True,
|
||||
min_duration: float = 0.0, # 只记录超过此耗时的调用
|
||||
):
|
||||
"""装饰器:记录函数调用信息(参数、返回值、耗时)
|
||||
|
||||
参数:
|
||||
logger: 使用的 logger,默认自动获取
|
||||
log_args: 是否记录函数参数
|
||||
log_result: 是否记录返回值
|
||||
log_time: 是否记录执行时间
|
||||
min_duration: 最小耗时阈值(秒),低于此值不记录耗时
|
||||
"""
|
||||
|
||||
def decorator(func: Callable) -> Callable:
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
if logger is None:
|
||||
_logger = get_logger()
|
||||
else:
|
||||
_logger = logger
|
||||
|
||||
func_name = func.__name__
|
||||
start_time = time.time()
|
||||
|
||||
# 记录函数调用
|
||||
if log_args:
|
||||
args_str = ", ".join(
|
||||
[str(arg)[:100] for arg in args[:3]]
|
||||
) # 只记录前3个参数,避免过长
|
||||
kwargs_str = ", ".join(
|
||||
[f"{k}={str(v)[:50]}" for k, v in list(kwargs.items())[:3]]
|
||||
)
|
||||
call_info = (
|
||||
f"{func_name}({args_str}{', ' + kwargs_str if kwargs_str else ''})"
|
||||
)
|
||||
if len(args) > 3 or len(kwargs) > 3:
|
||||
call_info += "..."
|
||||
_logger.debug(f"调用函数: {call_info}")
|
||||
|
||||
# 执行函数
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
elapsed = time.time() - start_time
|
||||
|
||||
# 记录执行结果
|
||||
if log_time and elapsed >= min_duration:
|
||||
_logger.debug(f"函数 {func_name} 执行完成,耗时: {elapsed:.3f}秒")
|
||||
|
||||
if log_result:
|
||||
result_str = str(result)[:200] # 限制长度
|
||||
_logger.debug(f"函数 {func_name} 返回值: {result_str}")
|
||||
|
||||
return result
|
||||
except Exception as e:
|
||||
elapsed = time.time() - start_time
|
||||
_logger.exception(
|
||||
f"函数 {func_name} 执行异常,耗时: {elapsed:.3f}秒", exc_info=True
|
||||
)
|
||||
raise
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
|
||||
|
||||
class LogContext:
|
||||
"""上下文管理器:记录代码块执行时间"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
logger: Optional[logging.Logger] = None,
|
||||
level: str = "DEBUG",
|
||||
log_on_exit: bool = True,
|
||||
):
|
||||
self.message = message
|
||||
self.logger = logger or get_logger()
|
||||
self.level = getattr(logging, level.upper(), logging.DEBUG)
|
||||
self.log_on_exit = log_on_exit
|
||||
self.start_time: Optional[float] = None
|
||||
|
||||
def __enter__(self):
|
||||
self.start_time = time.time()
|
||||
self.logger.log(self.level, f"{self.message} [开始]")
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
if not self.log_on_exit:
|
||||
return False
|
||||
|
||||
if self.start_time is None:
|
||||
elapsed = 0.0
|
||||
else:
|
||||
elapsed = time.time() - self.start_time
|
||||
|
||||
if exc_type is None:
|
||||
self.logger.log(self.level, f"{self.message} [完成] 耗时: {elapsed:.3f}秒")
|
||||
else:
|
||||
self.logger.log(
|
||||
logging.ERROR,
|
||||
f"{self.message} [异常] 耗时: {elapsed:.3f}秒",
|
||||
exc_info=(exc_type, exc_val, exc_tb),
|
||||
)
|
||||
|
||||
return False # 不抑制异常
|
||||
|
||||
|
||||
|
||||
|
||||
def get_caller_info(skip_frames: int = 0) -> Dict[str, Any]:
|
||||
"""获取调用者信息(模块名、函数名、行号)
|
||||
|
||||
参数:
|
||||
skip_frames: 跳过的栈帧数(用于在装饰器中获取真正的调用者)
|
||||
|
||||
返回:
|
||||
包含 module, function, line, file 的字典
|
||||
"""
|
||||
frame = None
|
||||
try:
|
||||
frame = inspect.currentframe()
|
||||
if frame:
|
||||
# 跳过当前函数和装饰器
|
||||
for _ in range(skip_frames + 2):
|
||||
if frame.f_back:
|
||||
frame = frame.f_back
|
||||
else:
|
||||
break
|
||||
|
||||
if frame:
|
||||
return {
|
||||
"module": os.path.basename(frame.f_code.co_filename),
|
||||
"function": frame.f_code.co_name,
|
||||
"line": frame.f_lineno,
|
||||
"file": frame.f_code.co_filename,
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if frame is not None:
|
||||
try:
|
||||
del frame
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"module": "unknown",
|
||||
"function": "unknown",
|
||||
"line": 0,
|
||||
"file": "unknown",
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
def format_exception_info(exc_info=None) -> str:
|
||||
"""格式化异常信息为字符串
|
||||
|
||||
参数:
|
||||
exc_info: 异常信息元组 (type, value, traceback),默认使用 sys.exc_info()
|
||||
|
||||
返回:
|
||||
格式化的异常堆栈字符串
|
||||
"""
|
||||
if exc_info is None:
|
||||
exc_info = sys.exc_info()
|
||||
|
||||
if exc_info[0] is None:
|
||||
return ""
|
||||
|
||||
try:
|
||||
# exc_info 应该是 (type, value, traceback) 元组
|
||||
if isinstance(exc_info, tuple) and len(exc_info) >= 3:
|
||||
exc_type, exc_value, exc_tb = exc_info[0], exc_info[1], exc_info[2]
|
||||
# 确保类型正确
|
||||
if isinstance(exc_value, BaseException):
|
||||
return "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
|
||||
else:
|
||||
# 如果不是异常实例,创建一个包装
|
||||
return "".join(
|
||||
traceback.format_exception(
|
||||
exc_type,
|
||||
(
|
||||
BaseException(str(exc_value))
|
||||
if exc_value
|
||||
else BaseException("Unknown error")
|
||||
),
|
||||
exc_tb,
|
||||
)
|
||||
)
|
||||
else:
|
||||
return "".join(traceback.format_exception(*exc_info))
|
||||
except Exception:
|
||||
return (
|
||||
f"异常: {exc_info[1] if len(exc_info) > 1 and exc_info[1] else 'Unknown'}"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
"""douyin_logging_pkg.handlers - 自定义日志 handler。
|
||||
|
||||
- RotatingDatedFileHandler 按日期 + 大小双轮转、自动压缩
|
||||
- DatedFileHandler 按日期分割(兼容包装)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class RotatingDatedFileHandler(logging.FileHandler):
|
||||
"""增强的日志处理器:支持日期+大小轮转和压缩
|
||||
|
||||
特性:
|
||||
1. 按日期分割日志文件(每天一个新文件)
|
||||
2. 当文件超过大小限制时,在日期内创建序号文件(如 unified_2024-01-15.1.log)
|
||||
3. 自动压缩超过保留天数的旧日志文件
|
||||
4. 智能清理策略:按时间、大小、数量三重限制
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_filename: str,
|
||||
date_format: str = "%Y-%m-%d",
|
||||
max_bytes: int = 10 * 1024 * 1024, # 10MB
|
||||
backup_count: int = 5, # 同一日期内最多保留的文件数
|
||||
per_run: bool = False, # 是否为每次运行生成独立文件(包含运行时间戳)
|
||||
encoding: str = "utf-8-sig",
|
||||
mode: str = "a",
|
||||
errors: str = "replace",
|
||||
compress_old: bool = True, # 是否压缩旧日志
|
||||
):
|
||||
"""
|
||||
参数:
|
||||
base_filename: 基础文件名(不含日期和扩展名),如 "logs/unified"
|
||||
date_format: 日期格式,默认 "%Y-%m-%d"
|
||||
max_bytes: 单个日志文件最大大小(字节),默认100MB
|
||||
backup_count: 同一日期内保留的备份文件数量,默认10
|
||||
encoding: 文件编码,默认 "utf-8-sig"
|
||||
mode: 打开模式,默认 "a"
|
||||
errors: 错误处理,默认 "replace"
|
||||
compress_old: 是否压缩旧日志,默认True
|
||||
"""
|
||||
self.base_filename = base_filename
|
||||
self.date_format = date_format
|
||||
self.max_bytes = max_bytes
|
||||
self.backup_count = backup_count
|
||||
self.compress_old = compress_old
|
||||
self.per_run = per_run
|
||||
|
||||
self.current_date = datetime.now().strftime(date_format)
|
||||
self.current_filename = self._get_filename_for_date(self.current_date)
|
||||
self.current_sequence = 0 # 当前文件序号
|
||||
self.per_run = per_run
|
||||
|
||||
# 确保目录存在
|
||||
log_dir = os.path.dirname(self.current_filename)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
super().__init__(
|
||||
self.current_filename,
|
||||
mode=mode,
|
||||
encoding=encoding,
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
# 优化:缓存日期检查
|
||||
self._date_check_counter = 0
|
||||
self._last_date_check_time = datetime.now()
|
||||
|
||||
def _get_filename_for_date(self, date_str: str, sequence: int = 0) -> str:
|
||||
"""根据日期和序号生成文件名"""
|
||||
if self.per_run:
|
||||
# 每次运行的文件名不再包含额外的日期字段(base_filename 已带运行时间戳)
|
||||
if sequence == 0:
|
||||
return f"{self.base_filename}.log"
|
||||
else:
|
||||
return f"{self.base_filename}.{sequence}.log"
|
||||
else:
|
||||
if sequence == 0:
|
||||
return f"{self.base_filename}_{date_str}.log"
|
||||
else:
|
||||
return f"{self.base_filename}_{date_str}.{sequence}.log"
|
||||
|
||||
def _get_next_filename(self, date_str: str) -> str:
|
||||
"""获取下一个可用的文件名"""
|
||||
# 首先检查序号0的文件
|
||||
filename = self._get_filename_for_date(date_str, 0)
|
||||
if not os.path.exists(filename) or os.path.getsize(filename) < self.max_bytes:
|
||||
return filename
|
||||
|
||||
# 如果序号0的文件已满,查找可用的序号
|
||||
for sequence in range(1, self.backup_count + 1):
|
||||
filename = self._get_filename_for_date(date_str, sequence)
|
||||
if (
|
||||
not os.path.exists(filename)
|
||||
or os.path.getsize(filename) < self.max_bytes
|
||||
):
|
||||
return filename
|
||||
|
||||
# 如果所有序号都满了,返回最后一个(会触发覆盖最旧的)
|
||||
return self._get_filename_for_date(date_str, self.backup_count)
|
||||
|
||||
def _rotate_file(self, date_str: str) -> None:
|
||||
"""轮转到新文件"""
|
||||
self.close()
|
||||
|
||||
# 获取新的文件名
|
||||
new_filename = self._get_next_filename(date_str)
|
||||
|
||||
# 如果文件已存在且已满,删除最旧的文件
|
||||
if (
|
||||
os.path.exists(new_filename)
|
||||
and os.path.getsize(new_filename) >= self.max_bytes
|
||||
):
|
||||
try:
|
||||
os.remove(new_filename)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.current_filename = new_filename
|
||||
|
||||
# 重新初始化文件流
|
||||
self.baseFilename = self.current_filename
|
||||
self.stream = self._open()
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
"""发送日志记录,支持日期和大小轮转"""
|
||||
# 检查是否需要日期轮转
|
||||
self._check_date_rotation()
|
||||
|
||||
# 检查是否需要大小轮转
|
||||
if self.stream and hasattr(self.stream, "tell"):
|
||||
try:
|
||||
current_size = self.stream.tell()
|
||||
if current_size >= self.max_bytes:
|
||||
self._rotate_file(self.current_date)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
super().emit(record)
|
||||
|
||||
def _check_date_rotation(self) -> None:
|
||||
"""检查日期轮转(优化版本)"""
|
||||
# 每100条记录或每1秒检查一次日期
|
||||
self._date_check_counter += 1
|
||||
should_check_date = (
|
||||
self._date_check_counter >= 100
|
||||
or (datetime.now() - self._last_date_check_time).total_seconds() >= 1.0
|
||||
)
|
||||
|
||||
if should_check_date:
|
||||
today = datetime.now().strftime(self.date_format)
|
||||
self._last_date_check_time = datetime.now()
|
||||
|
||||
if not self.per_run and today != self.current_date:
|
||||
# 日期变化,轮转到新日期(per_run 模式下不按日期轮转)
|
||||
self.close()
|
||||
self.current_date = today
|
||||
self.current_filename = self._get_filename_for_date(self.current_date)
|
||||
|
||||
# 确保目录存在
|
||||
log_dir = os.path.dirname(self.current_filename)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# 重新初始化文件流
|
||||
self.baseFilename = self.current_filename
|
||||
self.stream = self._open()
|
||||
|
||||
# 重置计数器
|
||||
self._date_check_counter = 0
|
||||
|
||||
|
||||
|
||||
|
||||
class DatedFileHandler(RotatingDatedFileHandler):
|
||||
"""兼容性类:保留原DatedFileHandler接口"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_filename: str,
|
||||
date_format: str = "%Y-%m-%d",
|
||||
encoding: str = "utf-8-sig",
|
||||
mode: str = "a",
|
||||
errors: str = "replace",
|
||||
):
|
||||
# 为了兼容,设置较大的max_bytes(1GB)以基本只按日期分割
|
||||
super().__init__(
|
||||
base_filename=base_filename,
|
||||
date_format=date_format,
|
||||
max_bytes=1024 * 1024 * 1024, # 1GB
|
||||
backup_count=1,
|
||||
encoding=encoding,
|
||||
mode=mode,
|
||||
errors=errors,
|
||||
compress_old=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
"""douyin_logging_pkg.monitor - 日志轮转 / 大小监控。
|
||||
|
||||
- LogRotationMonitor 轮转监控线程(按间隔检查日志大小并触发清理)
|
||||
- start_log_monitor 启动监控(懒创建实例)
|
||||
- stop_log_monitor 停止监控
|
||||
- get_log_stats 汇总日志统计信息
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from . import _common as _state
|
||||
|
||||
|
||||
class LogRotationMonitor:
|
||||
"""日志轮转监控器:监控日志大小、轮转频率并发出告警"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
logs_dir: str,
|
||||
base_name: str,
|
||||
warning_size_mb: float = 500.0, # 警告大小(MB)
|
||||
critical_size_mb: float = 2000.0, # 严重大小(MB)
|
||||
check_interval: int = 300, # 检查间隔(秒)
|
||||
rotation_threshold: int = 10, # 轮转频率阈值(每天)
|
||||
alert_callback: Optional[Callable[[str, str], None]] = None,
|
||||
enable_runtime_cleanup: bool = False,
|
||||
):
|
||||
"""
|
||||
参数:
|
||||
logs_dir: 日志目录
|
||||
base_name: 日志文件基础名称
|
||||
warning_size_mb: 警告大小阈值(MB)
|
||||
critical_size_mb: 严重大小阈值(MB)
|
||||
check_interval: 检查间隔(秒)
|
||||
rotation_threshold: 轮转频率阈值(每天)
|
||||
alert_callback: 告警回调函数,参数:(level, message)
|
||||
"""
|
||||
self.logs_dir = logs_dir
|
||||
self.base_name = base_name
|
||||
self.warning_size_mb = warning_size_mb
|
||||
self.critical_size_mb = critical_size_mb
|
||||
self.check_interval = check_interval
|
||||
self.rotation_threshold = rotation_threshold
|
||||
self.alert_callback = alert_callback
|
||||
|
||||
self._running = False
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._last_rotation_count = 0
|
||||
self._last_check_time = datetime.now()
|
||||
# 清理状态,避免并发触发大量清理操作
|
||||
self._cleanup_lock = threading.Lock()
|
||||
self._cleanup_running = False
|
||||
# 是否允许在运行过程中触发自动清理(默认不允许)
|
||||
self.enable_runtime_cleanup = bool(enable_runtime_cleanup)
|
||||
|
||||
# 告警输出限流:避免在运行时开启监控时刷屏
|
||||
self._last_warning_print_ts = 0.0
|
||||
self._last_critical_print_ts = 0.0
|
||||
self._min_alert_print_interval_sec = 3600.0
|
||||
|
||||
def start(self) -> None:
|
||||
"""启动监控器"""
|
||||
if self._running:
|
||||
return
|
||||
|
||||
self._running = True
|
||||
self._thread = threading.Thread(target=self._monitor_loop, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self) -> None:
|
||||
"""停止监控器"""
|
||||
self._running = False
|
||||
if self._thread and self._thread.is_alive():
|
||||
self._thread.join(timeout=5)
|
||||
|
||||
def _monitor_loop(self) -> None:
|
||||
"""监控循环"""
|
||||
while self._running:
|
||||
try:
|
||||
self._check_logs()
|
||||
time.sleep(self.check_interval)
|
||||
except Exception as e:
|
||||
if self.alert_callback:
|
||||
self.alert_callback("ERROR", f"日志监控器异常: {e}")
|
||||
|
||||
def _check_logs(self) -> None:
|
||||
"""检查日志状态"""
|
||||
try:
|
||||
# 收集所有日志文件
|
||||
pattern = os.path.join(self.logs_dir, f"{self.base_name}_*.log*")
|
||||
log_files = glob.glob(pattern)
|
||||
|
||||
if not log_files:
|
||||
return
|
||||
|
||||
# 计算总大小
|
||||
total_size = sum(os.path.getsize(f) for f in log_files if os.path.exists(f))
|
||||
total_size_mb = total_size / 1024 / 1024
|
||||
|
||||
# 检查大小告警
|
||||
if total_size_mb >= self.critical_size_mb:
|
||||
message = f"日志总大小严重超限: {total_size_mb:.1f}MB >= {self.critical_size_mb}MB"
|
||||
if self.alert_callback:
|
||||
self.alert_callback("CRITICAL", message)
|
||||
else:
|
||||
now_ts = time.time()
|
||||
if (
|
||||
now_ts - self._last_critical_print_ts
|
||||
>= self._min_alert_print_interval_sec
|
||||
):
|
||||
print(f"[日志监控] CRITICAL: {message}")
|
||||
self._last_critical_print_ts = now_ts
|
||||
|
||||
elif total_size_mb >= self.warning_size_mb:
|
||||
message = (
|
||||
f"日志总大小警告: {total_size_mb:.1f}MB >= {self.warning_size_mb}MB"
|
||||
)
|
||||
if self.alert_callback:
|
||||
self.alert_callback("WARNING", message)
|
||||
else:
|
||||
now_ts = time.time()
|
||||
if (
|
||||
now_ts - self._last_warning_print_ts
|
||||
>= self._min_alert_print_interval_sec
|
||||
):
|
||||
print(f"[日志监控] WARNING: {message}")
|
||||
self._last_warning_print_ts = now_ts
|
||||
# 运行时不再自动触发清理,清理仅在启动阶段执行以避免中途 I/O 干扰
|
||||
# 检查轮转频率
|
||||
current_time = datetime.now()
|
||||
if (
|
||||
current_time - self._last_check_time
|
||||
).total_seconds() >= 86400: # 24小时
|
||||
# 计算今天的文件数量
|
||||
today_str = current_time.strftime("%Y-%m-%d")
|
||||
today_files = [f for f in log_files if today_str in f]
|
||||
|
||||
if len(today_files) >= self.rotation_threshold:
|
||||
message = f"日志轮转频率过高: 今天已轮转 {len(today_files)} 次 (>= {self.rotation_threshold})"
|
||||
if self.alert_callback:
|
||||
self.alert_callback("WARNING", message)
|
||||
else:
|
||||
print(f"[日志监控] WARNING: {message}")
|
||||
|
||||
self._last_check_time = current_time
|
||||
|
||||
except Exception as e:
|
||||
if self.alert_callback:
|
||||
self.alert_callback("ERROR", f"日志检查失败: {e}")
|
||||
|
||||
def _schedule_cleanup_async(self) -> None:
|
||||
"""如果没有正在运行的清理任务,则在后台线程中启动一次清理。"""
|
||||
# 如果未开启运行时清理功能,直接返回(清理仅限启动阶段)
|
||||
if not getattr(self, "enable_runtime_cleanup", False):
|
||||
return
|
||||
|
||||
# 用锁做“唯一运行”判定,避免竞态导致并发启动多个清理线程
|
||||
with self._cleanup_lock:
|
||||
if self._cleanup_running:
|
||||
return
|
||||
self._cleanup_running = True
|
||||
|
||||
keep_days, cfg_max_total_size_gb, compress_after_days, compress = (
|
||||
_load_logging_cleanup_policy_from_config()
|
||||
)
|
||||
|
||||
# 监控告警阈值与清理联动:当触发 WARNING 时,把总量上限压到 warning 阈值附近
|
||||
# 这样“>=500MB 报警”能实际驱动清理生效(而不是仍按 10GB 上限导致无动作)。
|
||||
try:
|
||||
warning_target_gb = max(0.05, float(self.warning_size_mb) / 1024.0)
|
||||
except Exception:
|
||||
warning_target_gb = 0.5
|
||||
|
||||
effective_max_total_size_gb = min(cfg_max_total_size_gb, warning_target_gb)
|
||||
|
||||
def _worker():
|
||||
try:
|
||||
# 使用模块内的 cleanup_old_logs 执行清理,采用默认策略(保留30天、10GB上限)
|
||||
try:
|
||||
cleanup_old_logs(
|
||||
logs_dir=self.logs_dir,
|
||||
base_name=self.base_name,
|
||||
keep_days=keep_days,
|
||||
max_total_size_gb=effective_max_total_size_gb,
|
||||
compress_after_days=compress_after_days,
|
||||
compress=compress,
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
if self.alert_callback:
|
||||
self.alert_callback("ERROR", f"日志自动清理失败: {e}")
|
||||
else:
|
||||
print(f"[日志监控] 日志自动清理失败: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
with self._cleanup_lock:
|
||||
self._cleanup_running = False
|
||||
except Exception:
|
||||
self._cleanup_running = False
|
||||
|
||||
t = threading.Thread(target=_worker, daemon=True)
|
||||
t.start()
|
||||
|
||||
|
||||
|
||||
|
||||
def start_log_monitor(
|
||||
logs_dir: str,
|
||||
base_name: str,
|
||||
warning_size_mb: float = 500.0,
|
||||
critical_size_mb: float = 2000.0,
|
||||
check_interval: int = 300,
|
||||
alert_callback: Optional[Callable[[str, str], None]] = None,
|
||||
enable_runtime_cleanup: bool = False,
|
||||
) -> None:
|
||||
"""启动日志轮转监控器
|
||||
|
||||
参数:
|
||||
logs_dir: 日志目录
|
||||
base_name: 日志文件基础名称
|
||||
warning_size_mb: 警告大小阈值(MB)
|
||||
critical_size_mb: 严重大小阈值(MB)
|
||||
check_interval: 检查间隔(秒)
|
||||
alert_callback: 告警回调函数
|
||||
"""
|
||||
|
||||
if _state._log_monitor:
|
||||
_state._log_monitor.stop()
|
||||
|
||||
_state._log_monitor = LogRotationMonitor(
|
||||
logs_dir=logs_dir,
|
||||
base_name=base_name,
|
||||
warning_size_mb=warning_size_mb,
|
||||
critical_size_mb=critical_size_mb,
|
||||
check_interval=check_interval,
|
||||
alert_callback=alert_callback,
|
||||
enable_runtime_cleanup=enable_runtime_cleanup,
|
||||
)
|
||||
_state._log_monitor.start()
|
||||
|
||||
|
||||
|
||||
|
||||
def stop_log_monitor() -> None:
|
||||
"""停止日志轮转监控器"""
|
||||
|
||||
if _state._log_monitor:
|
||||
_state._log_monitor.stop()
|
||||
_log_monitor = None
|
||||
|
||||
|
||||
|
||||
|
||||
def get_log_stats(logs_dir: str, base_name: str) -> Dict[str, Any]:
|
||||
"""获取日志统计信息
|
||||
|
||||
返回:
|
||||
包含文件数量、总大小、压缩率等信息的字典
|
||||
"""
|
||||
stats = {
|
||||
"total_files": 0,
|
||||
"total_size_mb": 0.0,
|
||||
"compressed_files": 0,
|
||||
"compressed_size_mb": 0.0,
|
||||
"compression_ratio": 0.0,
|
||||
"oldest_file": None,
|
||||
"newest_file": None,
|
||||
}
|
||||
|
||||
try:
|
||||
pattern = os.path.join(logs_dir, f"{base_name}_*.log*")
|
||||
log_files = glob.glob(pattern)
|
||||
|
||||
if not log_files:
|
||||
return stats
|
||||
|
||||
stats["total_files"] = len(log_files)
|
||||
|
||||
# 计算大小统计
|
||||
uncompressed_size = 0
|
||||
compressed_size = 0
|
||||
|
||||
file_times = []
|
||||
for log_file in log_files:
|
||||
if os.path.exists(log_file):
|
||||
size = os.path.getsize(log_file)
|
||||
stats["total_size_mb"] += size / 1024 / 1024
|
||||
|
||||
if log_file.endswith(".gz"):
|
||||
stats["compressed_files"] += 1
|
||||
compressed_size += size
|
||||
else:
|
||||
uncompressed_size += size
|
||||
|
||||
# 记录文件时间
|
||||
try:
|
||||
mtime = os.path.getmtime(log_file)
|
||||
file_times.append((mtime, log_file))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 计算压缩率
|
||||
if uncompressed_size > 0 and compressed_size > 0:
|
||||
# 压缩率 = 压缩后大小 / 原始大小
|
||||
stats["compression_ratio"] = compressed_size / (
|
||||
uncompressed_size + compressed_size
|
||||
)
|
||||
|
||||
# 找出最老和最新的文件
|
||||
if file_times:
|
||||
file_times.sort()
|
||||
stats["oldest_file"] = os.path.basename(file_times[0][1])
|
||||
stats["newest_file"] = os.path.basename(file_times[-1][1])
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
# 自动配置日志(在模块导入时)
|
||||
if not _state._logging_configured:
|
||||
# 延迟配置,避免在导入时读取 config.json 失败
|
||||
try:
|
||||
configure_logging()
|
||||
except Exception:
|
||||
pass
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,66 @@
|
||||
"""douyin_logging_wrapper_pkg - 日志包装器子包。
|
||||
|
||||
原 douyin/logging/douyin_logging_wrapper.py 拆成 6 个子模块:
|
||||
|
||||
- _common 共享:colorama / 占位类 / 模块实例
|
||||
- enhanced enhanced_log_kv 主入口
|
||||
- simple _enhanced_log_kv_simple 简化版
|
||||
- detailed _enhanced_log_kv_detailed 详细版(最大头)
|
||||
- misc 5 个小型日志辅助方法
|
||||
- wrapper LoggingWrapper 类(薄壳)
|
||||
|
||||
外部 import 路径不变:
|
||||
``from douyin.logging.douyin_logging_wrapper import LoggingWrapper`` 仍可用
|
||||
(原文件改成 re-export shim)。
|
||||
"""
|
||||
|
||||
from ._common import (
|
||||
COLORAMA_AVAILABLE,
|
||||
Fore,
|
||||
LOGGING_MODULES_AVAILABLE,
|
||||
Style,
|
||||
ActionLogger,
|
||||
DebugLogger,
|
||||
ErrorLogger,
|
||||
PerformanceTracker,
|
||||
_action_logger,
|
||||
_debug_logger,
|
||||
_error_logger,
|
||||
_performance_tracker,
|
||||
)
|
||||
from .enhanced import enhanced_log_kv
|
||||
from .simple import _enhanced_log_kv_simple
|
||||
from .detailed import _enhanced_log_kv_detailed
|
||||
from .misc import (
|
||||
get_performance_stats,
|
||||
log_debug_info,
|
||||
log_error_with_context,
|
||||
log_performance_step,
|
||||
log_step_time,
|
||||
)
|
||||
from .wrapper import LoggingWrapper
|
||||
|
||||
__all__ = [
|
||||
"LoggingWrapper",
|
||||
"enhanced_log_kv",
|
||||
"_enhanced_log_kv_simple",
|
||||
"_enhanced_log_kv_detailed",
|
||||
"log_step_time",
|
||||
"log_error_with_context",
|
||||
"log_performance_step",
|
||||
"log_debug_info",
|
||||
"get_performance_stats",
|
||||
# 共享对象(兼容原文件 module-level 暴露)
|
||||
"COLORAMA_AVAILABLE",
|
||||
"LOGGING_MODULES_AVAILABLE",
|
||||
"Fore",
|
||||
"Style",
|
||||
"ErrorLogger",
|
||||
"DebugLogger",
|
||||
"ActionLogger",
|
||||
"PerformanceTracker",
|
||||
"_error_logger",
|
||||
"_debug_logger",
|
||||
"_action_logger",
|
||||
"_performance_tracker",
|
||||
]
|
||||
@@ -0,0 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""douyin_logging_wrapper_pkg._common - 共享:colorama / 占位类 / 模块实例。
|
||||
|
||||
被本子包的所有方法子模块共用。
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
# 导入 colorama 用于颜色支持
|
||||
try:
|
||||
from colorama import Fore, Style, init
|
||||
|
||||
init(autoreset=True)
|
||||
COLORAMA_AVAILABLE = True
|
||||
except ImportError:
|
||||
# 如果没有 colorama,使用 ANSI 转义序列
|
||||
class Fore:
|
||||
RED = "\033[31m"
|
||||
GREEN = "\033[32m"
|
||||
YELLOW = "\033[33m"
|
||||
BLUE = "\033[34m"
|
||||
MAGENTA = "\033[35m"
|
||||
CYAN = "\033[36m"
|
||||
WHITE = "\033[37m"
|
||||
LIGHTRED_EX = "\033[91m"
|
||||
LIGHTGREEN_EX = "\033[92m"
|
||||
LIGHTYELLOW_EX = "\033[93m"
|
||||
LIGHTBLUE_EX = "\033[94m"
|
||||
LIGHTMAGENTA_EX = "\033[95m"
|
||||
LIGHTCYAN_EX = "\033[96m"
|
||||
LIGHTWHITE_EX = "\033[97m"
|
||||
|
||||
class Style:
|
||||
RESET_ALL = "\033[0m"
|
||||
BRIGHT = "\033[1m"
|
||||
|
||||
COLORAMA_AVAILABLE = False
|
||||
|
||||
|
||||
# 导入所有日志模块
|
||||
try:
|
||||
from douyin.logging.internal_loggers import ErrorLogger, DebugLogger # type: ignore[assignment]
|
||||
from douyin.logging.action_logger import ActionLogger # type: ignore[assignment]
|
||||
from douyin.logging.performance_tracker import PerformanceTracker # type: ignore[assignment]
|
||||
|
||||
LOGGING_MODULES_AVAILABLE = True
|
||||
except ImportError:
|
||||
# 如果导入失败,提供占位符类
|
||||
class ErrorLogger:
|
||||
def log_exception(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
class DebugLogger:
|
||||
def log_variable(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
class ActionLogger:
|
||||
def log_step(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
class PerformanceTracker:
|
||||
def end_timer(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def get_statistics(self, *args, **kwargs):
|
||||
return {}
|
||||
|
||||
LOGGING_MODULES_AVAILABLE = False
|
||||
|
||||
|
||||
# 初始化日志模块实例
|
||||
_error_logger = ErrorLogger()
|
||||
_debug_logger = DebugLogger()
|
||||
_action_logger = ActionLogger()
|
||||
_performance_tracker = PerformanceTracker()
|
||||
@@ -0,0 +1,356 @@
|
||||
"""douyin_logging_wrapper_pkg.detailed - _enhanced_log_kv_detailed 详细版日志记录。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from ._common import (
|
||||
COLORAMA_AVAILABLE,
|
||||
Fore,
|
||||
LOGGING_MODULES_AVAILABLE,
|
||||
Style,
|
||||
_action_logger,
|
||||
_debug_logger,
|
||||
_error_logger,
|
||||
_performance_tracker,
|
||||
)
|
||||
|
||||
|
||||
def _enhanced_log_kv_detailed(
|
||||
analyser: Any,
|
||||
tag: str,
|
||||
msg: str,
|
||||
log_level: str,
|
||||
log_type: str,
|
||||
log_parts: list[str],
|
||||
timestamp: str,
|
||||
caller_info: str,
|
||||
fields: Dict[str, Any],
|
||||
need_separator: bool,
|
||||
separator_reason: str,
|
||||
color: Optional[str] = None,
|
||||
) -> None:
|
||||
"""详细模式的日志记录(保留之前的复杂格式用于debug)"""
|
||||
# 字段映射(中文 key)- 在详细模式中重新定义
|
||||
key_map: Dict[str, str] = {
|
||||
"rid": "运行",
|
||||
"seq": "序号",
|
||||
"msg": "说明",
|
||||
"stage": "阶段",
|
||||
"seen": "识别",
|
||||
"ok": "成功",
|
||||
"text": "文本",
|
||||
"action": "动作",
|
||||
"result": "结果",
|
||||
"mode": "模式",
|
||||
"reason": "原因",
|
||||
"wait_seconds": "等待秒",
|
||||
"value_yuan": "价值元",
|
||||
"future": "开奖时间",
|
||||
"pos_seen": "发现位置",
|
||||
"qsize": "队列数量",
|
||||
"room_pos": "当前位置",
|
||||
"content": "内容",
|
||||
"countdown": "倒计时",
|
||||
"participants": "参与人数",
|
||||
"copies": "份数",
|
||||
"seconds": "耗时秒",
|
||||
"error": "错误",
|
||||
"error_type": "错误类型",
|
||||
"fudai_x": "福袋X坐标",
|
||||
"attempt": "尝试次数",
|
||||
"room_title": "直播间名",
|
||||
"back_times": "需回退次数",
|
||||
}
|
||||
# 输出分隔符(如果需要)- 详细模式使用更明显的分隔符
|
||||
if need_separator:
|
||||
try:
|
||||
separator = "=" * 50
|
||||
separator_line = f"{separator} {separator_reason} {separator}"
|
||||
print(separator_line, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 更新上一个日志标签
|
||||
analyser._last_log_tag = tag
|
||||
|
||||
# 构建详细的日志行(包含更多信息)
|
||||
detailed_log_parts = log_parts.copy()
|
||||
|
||||
# 在详细模式下添加更多字段信息
|
||||
important_fields = []
|
||||
for k, v in fields.items():
|
||||
if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"):
|
||||
continue
|
||||
if v is None:
|
||||
continue
|
||||
# 详细模式显示更多字段
|
||||
key_cn = key_map.get(str(k), k)
|
||||
if isinstance(v, float):
|
||||
if "seconds" in k or "elapsed" in k:
|
||||
v_str = f"{v:.2f}s"
|
||||
elif "yuan" in k:
|
||||
v_str = f"{v:.0f}元"
|
||||
else:
|
||||
v_str = f"{v:.2f}"
|
||||
else:
|
||||
v_str = str(v)[:30] # 详细模式允许稍长
|
||||
important_fields.append(f"{key_cn}={v_str}")
|
||||
|
||||
if important_fields:
|
||||
detailed_log_parts.append(" ".join(important_fields))
|
||||
|
||||
# 添加调用者信息(详细模式)
|
||||
if caller_info:
|
||||
detailed_log_parts.append(f"[调用:{caller_info}]")
|
||||
|
||||
log_line = " ".join(detailed_log_parts)
|
||||
|
||||
# 应用颜色(如果指定了颜色)
|
||||
if color:
|
||||
try:
|
||||
if hasattr(Fore, color.upper()):
|
||||
color_code = getattr(Fore, color.upper())
|
||||
log_line = f"{color_code}{log_line}{Style.RESET_ALL}"
|
||||
elif color.startswith("\033["): # ANSI 转义序列
|
||||
log_line = f"{color}{log_line}{Style.RESET_ALL}"
|
||||
except Exception:
|
||||
pass # 如果颜色应用失败,使用原始日志行
|
||||
|
||||
# 始终输出到 stdout(供 GUI 捕获)
|
||||
try:
|
||||
print(log_line, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 详细的行为日志记录(保留之前的复杂逻辑)
|
||||
try:
|
||||
# 记录所有操作到行为日志(详细模式)
|
||||
should_log = True
|
||||
|
||||
# 过滤一些不需要记录的日志(避免噪音)
|
||||
if tag:
|
||||
skip_tags = ["[调试图像]", "[步骤耗时]"]
|
||||
for skip_tag in skip_tags:
|
||||
if tag.startswith(skip_tag):
|
||||
should_log = False
|
||||
break
|
||||
|
||||
if should_log:
|
||||
# 提取关键信息:做了什么、耗时、分数
|
||||
def _shorten(value: Any, max_len: int = 60) -> str:
|
||||
s = str(value).strip()
|
||||
if len(s) > max_len:
|
||||
return s[: max_len - 3] + "..."
|
||||
return s
|
||||
|
||||
if msg:
|
||||
action_desc = _shorten(str(msg), max_len=120)
|
||||
# 移除函数名:匹配 "函数名:" 或 "函数名 " 格式
|
||||
action_desc = re.sub(
|
||||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s*[::]\s*", "", action_desc
|
||||
)
|
||||
action_desc = re.sub(
|
||||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s+(?=[^a-zA-Z_])", "", action_desc
|
||||
)
|
||||
if not action_desc.strip():
|
||||
action_desc = _shorten(str(msg), max_len=120)
|
||||
else:
|
||||
if tag:
|
||||
tag_clean = tag.strip("[]").strip()
|
||||
if tag_clean:
|
||||
action_desc = tag_clean
|
||||
else:
|
||||
action_desc = "操作"
|
||||
else:
|
||||
action_desc = "操作"
|
||||
|
||||
# 提取耗时
|
||||
elapsed_str = ""
|
||||
fields_clean: Dict[str, Any] = {}
|
||||
for k, v in fields.items():
|
||||
kk = str(k)
|
||||
if kk.startswith("字段_"):
|
||||
kk = kk[len("字段_") :]
|
||||
fields_clean[kk] = v
|
||||
|
||||
if "elapsed_ms" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("elapsed_ms", 0)) / 1000.0
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "total_ms" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("total_ms", 0)) / 1000.0
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "seconds" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("seconds", 0))
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "elapsed_seconds" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("elapsed_seconds", 0))
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
|
||||
# 提取分数
|
||||
score_str = ""
|
||||
if "score" in fields_clean and fields_clean.get("score") is not None:
|
||||
try:
|
||||
score_val = float(fields_clean.get("score", 0))
|
||||
score_str = f"分数:{score_val:.3f}"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# 构建详细的行为日志行
|
||||
action_parts = [timestamp, "-", "[GUI]", "-"]
|
||||
if tag:
|
||||
action_parts.append(tag)
|
||||
else:
|
||||
action_parts.append("[日志]")
|
||||
|
||||
if log_type:
|
||||
action_parts.append(f"[{log_type}]")
|
||||
|
||||
action_parts.append(action_desc)
|
||||
|
||||
if elapsed_str:
|
||||
action_parts.append(elapsed_str)
|
||||
|
||||
if score_str:
|
||||
action_parts.append(score_str)
|
||||
|
||||
action_log_line = " ".join(action_parts)
|
||||
|
||||
# 写入 actions.log 文件
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
actions_log_path = path_config.get_actions_log_path()
|
||||
log_dir = path_config.get_logs_dir()
|
||||
except Exception:
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(__file__), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# 检测标签变化
|
||||
if not hasattr(analyser, "_last_action_tag"):
|
||||
analyser._last_action_tag = None
|
||||
|
||||
current_tag = tag or "[日志]"
|
||||
try:
|
||||
import logging
|
||||
|
||||
action_logger = logging.getLogger("action_logger")
|
||||
if (
|
||||
analyser._last_action_tag is not None
|
||||
and analyser._last_action_tag != current_tag
|
||||
):
|
||||
action_logger.info("=" * 80)
|
||||
action_logger.info(action_log_line)
|
||||
analyser._last_action_tag = current_tag
|
||||
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
|
||||
|
||||
# 详细模式:保留标准logging输出(用于debug)
|
||||
try:
|
||||
import logging
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
if not root_logger.handlers:
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
|
||||
douyin_logging.configure_logging()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not hasattr(analyser, "_std_logger") or analyser._std_logger is None:
|
||||
try:
|
||||
from douyin.logging.unified_logger import get_unified_logger
|
||||
|
||||
analyser._std_logger = get_unified_logger("douyin.fudai")
|
||||
except ImportError:
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
|
||||
analyser._std_logger = douyin_logging.get_logger("douyin")
|
||||
except Exception:
|
||||
analyser._std_logger = logging.getLogger("douyin.fudai")
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
if root_logger.handlers:
|
||||
std_msg_parts = [f"[{tag}]"]
|
||||
if caller_info:
|
||||
std_msg_parts.append(f"[调用:{caller_info}]")
|
||||
if msg:
|
||||
try:
|
||||
from douyin.logging.unified_logger import SensitiveDataMasker
|
||||
|
||||
masked_msg = SensitiveDataMasker.mask_all(str(msg))
|
||||
std_msg_parts.append(masked_msg)
|
||||
except ImportError:
|
||||
std_msg_parts.append(str(msg))
|
||||
|
||||
masked_fields: Dict[str, Any] = {}
|
||||
try:
|
||||
from douyin.logging.unified_logger import SensitiveDataMasker
|
||||
|
||||
masked_fields = SensitiveDataMasker.mask_dict(fields)
|
||||
except ImportError:
|
||||
masked_fields = fields
|
||||
|
||||
for k, v in masked_fields.items():
|
||||
if k in (
|
||||
"tag",
|
||||
"msg",
|
||||
"level",
|
||||
"exc_info",
|
||||
"_show_caller",
|
||||
"_caller",
|
||||
):
|
||||
continue
|
||||
if v is not None:
|
||||
std_msg_parts.append(f"{k}={v}")
|
||||
|
||||
log_message = " ".join(std_msg_parts)
|
||||
|
||||
exc_info = fields.get("exc_info")
|
||||
if exc_info is None:
|
||||
if sys.exc_info()[0] is not None:
|
||||
exc_info = sys.exc_info()
|
||||
|
||||
level = getattr(logging, log_level, logging.INFO)
|
||||
extra_data = {
|
||||
"caller": caller_info,
|
||||
"suppress_console_output": True,
|
||||
"suppress_file_output": True,
|
||||
}
|
||||
if exc_info:
|
||||
root_logger.log(
|
||||
level, log_message, exc_info=exc_info, extra=extra_data
|
||||
)
|
||||
else:
|
||||
root_logger.log(level, log_message, extra=extra_data)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,380 @@
|
||||
"""douyin_logging_wrapper_pkg.enhanced - enhanced_log_kv 主入口。
|
||||
|
||||
按 verbose 配置决定走 simple / detailed 实现。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from ._common import (
|
||||
COLORAMA_AVAILABLE,
|
||||
Fore,
|
||||
LOGGING_MODULES_AVAILABLE,
|
||||
Style,
|
||||
_action_logger,
|
||||
_debug_logger,
|
||||
_error_logger,
|
||||
_performance_tracker,
|
||||
)
|
||||
|
||||
|
||||
from .simple import _enhanced_log_kv_simple
|
||||
from .detailed import _enhanced_log_kv_detailed
|
||||
|
||||
|
||||
def enhanced_log_kv(analyser: Any, *args: Any, **fields: Any) -> None:
|
||||
"""增强的日志记录方法:始终输出到 stdout(供 GUI 捕获),同时可选输出到标准 logging
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
*args: 位置参数,第一个是tag,第二个是msg
|
||||
**fields: 关键字参数字典
|
||||
"""
|
||||
# 解析参数:优先使用位置参数,避免与关键字参数冲突
|
||||
if len(args) >= 1:
|
||||
tag = args[0]
|
||||
# 如果位置参数提供了 tag,从 fields 中移除 tag 避免冲突
|
||||
fields.pop("tag", None)
|
||||
else:
|
||||
tag = fields.get("tag", "日志")
|
||||
|
||||
if len(args) >= 2:
|
||||
msg = args[1]
|
||||
# 如果位置参数提供了 msg,从 fields 中移除 msg 避免冲突
|
||||
fields.pop("msg", None)
|
||||
else:
|
||||
msg = fields.get("msg", "")
|
||||
|
||||
# 获取日志级别
|
||||
log_level = fields.get("level", "INFO").upper()
|
||||
if log_level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
|
||||
log_level = "INFO"
|
||||
|
||||
# 获取颜色设置
|
||||
color = fields.get("color", None)
|
||||
if color:
|
||||
fields.pop("color", None) # 从 fields 中移除,避免在日志中显示
|
||||
|
||||
# 支持可选的 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
|
||||
except Exception:
|
||||
analyser._log_seq = 1
|
||||
|
||||
# 获取时间戳(使用系统时间)
|
||||
try:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
except Exception:
|
||||
# 如果无法导入 datetime(极少见),回退为 time.strftime
|
||||
try:
|
||||
timestamp = time.strftime("%H:%M:%S")
|
||||
except Exception:
|
||||
timestamp = ""
|
||||
|
||||
# 获取调用者信息(模块名:函数名:行号)
|
||||
caller_info = ""
|
||||
try:
|
||||
# 获取调用栈:跳过 _enhanced_log_kv 本身,找到真正的调用者
|
||||
frame = inspect.currentframe()
|
||||
if frame:
|
||||
# frame.f_back 是调用 _enhanced_log_kv 的帧(可能是 _log_kv 或其他)
|
||||
# 需要再往上找一层,找到实际调用 _log_kv 的代码
|
||||
caller_frame = frame.f_back
|
||||
if caller_frame:
|
||||
# 检查是否是 _log_kv 的调用(属性赋值的情况)
|
||||
if (
|
||||
caller_frame.f_code.co_name == "_log_kv"
|
||||
or "log_kv" in caller_frame.f_code.co_name
|
||||
):
|
||||
caller_frame = caller_frame.f_back
|
||||
# 如果找到了调用者,提取信息
|
||||
if caller_frame:
|
||||
filename = caller_frame.f_code.co_filename
|
||||
funcname = caller_frame.f_code.co_name
|
||||
lineno = caller_frame.f_lineno
|
||||
# 只取文件名,不包含路径
|
||||
filename = os.path.basename(filename)
|
||||
# 如果文件名是 <string> 或类似,说明是测试代码,跳过
|
||||
if filename and filename not in ("<string>", "<stdin>"):
|
||||
caller_info = f"{filename}:{funcname}:{lineno}"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 字段映射(中文 key)
|
||||
key_map: Dict[str, str] = {
|
||||
"rid": "运行",
|
||||
"seq": "序号",
|
||||
"msg": "说明",
|
||||
"stage": "阶段",
|
||||
"seen": "识别",
|
||||
"ok": "成功",
|
||||
"text": "文本",
|
||||
"action": "动作",
|
||||
"result": "结果",
|
||||
"mode": "模式",
|
||||
"reason": "原因",
|
||||
"wait_seconds": "等待秒",
|
||||
"value_yuan": "价值元",
|
||||
"future": "开奖时间",
|
||||
"pos_seen": "发现位置",
|
||||
"qsize": "队列数量",
|
||||
"room_pos": "当前位置",
|
||||
"content": "内容",
|
||||
"countdown": "倒计时",
|
||||
"participants": "参与人数",
|
||||
"copies": "份数",
|
||||
"seconds": "耗时秒",
|
||||
"error": "错误",
|
||||
"error_type": "错误类型",
|
||||
"fudai_x": "福袋X坐标",
|
||||
"attempt": "尝试次数",
|
||||
"room_title": "直播间名",
|
||||
"back_times": "需回退次数",
|
||||
"elapsed_ms": "耗时",
|
||||
"分数": "分数",
|
||||
"置信度": "置信度",
|
||||
"阈值": "阈值",
|
||||
"红色比例": "红色比例",
|
||||
"匹配分数": "匹配分数",
|
||||
"模板匹配分数": "模板匹配分数",
|
||||
"平均分": "平均分",
|
||||
"检测结果": "检测结果",
|
||||
"检测方法": "检测方法",
|
||||
"耗时(ms)": "耗时",
|
||||
# 筛选相关字段映射
|
||||
"配置_最小价值": "最小价值",
|
||||
"配置_最小参与人数": "最小参与人数",
|
||||
"配置_最大参与人数": "最大参与人数",
|
||||
"配置_倒计时大于秒数": "倒计时大于阈值",
|
||||
"配置_倒计时小于秒数": "倒计时小于阈值",
|
||||
"实际_价值": "实际价值",
|
||||
"实际_参与人数": "实际参与人数",
|
||||
"实际_份数": "实际份数",
|
||||
"实际_剩余秒数": "剩余秒数",
|
||||
"实际_内容": "福袋内容",
|
||||
"配置阈值秒数": "阈值秒数",
|
||||
"实际剩余秒数": "剩余秒数",
|
||||
"判断条件": "判断条件",
|
||||
"说明": "说明",
|
||||
"是否有倒计时数据": "有倒计时数据",
|
||||
"按钮文本": "按钮文本",
|
||||
}
|
||||
|
||||
# 构建简洁的日志行:时间 [级别] [标签] 消息 关键字段
|
||||
log_parts: list[str] = []
|
||||
if timestamp:
|
||||
log_parts.append(f"[{timestamp}]")
|
||||
log_parts.append(f"[{log_level}]")
|
||||
if tag and tag != "日志":
|
||||
log_parts.append(f"[{tag}]")
|
||||
|
||||
if msg:
|
||||
m = str(msg).replace("\r", " ").replace("\n", " ").strip()
|
||||
if len(m) > 150:
|
||||
m = m[:150] + "..."
|
||||
log_parts.append(m)
|
||||
|
||||
# 只添加最重要的字段,避免日志过长
|
||||
important_fields = []
|
||||
for k, v in fields.items():
|
||||
if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"):
|
||||
continue
|
||||
if v is None:
|
||||
continue
|
||||
# 只显示关键字段:耗时、价值、错误等
|
||||
if k in (
|
||||
"elapsed_seconds",
|
||||
"value_yuan",
|
||||
"error",
|
||||
"room_pos",
|
||||
"future_ts",
|
||||
"elapsed_ms",
|
||||
"分数",
|
||||
"置信度",
|
||||
"阈值",
|
||||
"红色比例",
|
||||
"匹配分数",
|
||||
"模板匹配分数",
|
||||
"平均分",
|
||||
"检测结果",
|
||||
"检测方法",
|
||||
"耗时(ms)",
|
||||
"福袋内容",
|
||||
"任务列表",
|
||||
"倒计时分钟",
|
||||
"倒计时秒",
|
||||
"奖品价值",
|
||||
"按钮文本",
|
||||
"直播间标题",
|
||||
"fudai_content_raw",
|
||||
"task_list_raw",
|
||||
"countdown_mm_raw",
|
||||
"countdown_ss_raw",
|
||||
"value_raw",
|
||||
"button_text_raw",
|
||||
"live_room_title_raw",
|
||||
# 筛选相关字段
|
||||
"配置_最小价值",
|
||||
"配置_最小参与人数",
|
||||
"配置_最大参与人数",
|
||||
"配置_倒计时大于秒数",
|
||||
"配置_倒计时小于秒数",
|
||||
"实际_价值",
|
||||
"实际_参与人数",
|
||||
"实际_份数",
|
||||
"实际_剩余秒数",
|
||||
"实际_内容",
|
||||
"配置阈值秒数",
|
||||
"实际剩余秒数",
|
||||
"判断条件",
|
||||
"说明",
|
||||
"原因",
|
||||
"是否有倒计时数据",
|
||||
"按钮文本",
|
||||
):
|
||||
key_cn = key_map.get(str(k), k)
|
||||
if isinstance(v, float):
|
||||
# 优先检测毫秒字段(例如 elapsed_ms、total_elapsed_ms),避免被 "elapsed" 关键字误判为秒
|
||||
if "ms" in k:
|
||||
v_str = f"{v:.0f}ms"
|
||||
elif "seconds" in k or "elapsed" in k:
|
||||
v_str = f"{v:.1f}s"
|
||||
elif "yuan" in k:
|
||||
v_str = f"{v:.0f}元"
|
||||
elif "分数" in k or "置信度" in k or "比例" in k or "阈值" in k:
|
||||
v_str = f"{v:.3f}"
|
||||
else:
|
||||
v_str = f"{v:.1f}"
|
||||
else:
|
||||
v_str = str(v)[:20] # 限制字段值长度
|
||||
important_fields.append(f"{key_cn}={v_str}")
|
||||
|
||||
if important_fields:
|
||||
log_parts.append(" ".join(important_fields))
|
||||
|
||||
# 构建完整日志行
|
||||
log_line = " ".join(log_parts)
|
||||
|
||||
# 简化分隔符逻辑,只在真正重要的阶段变化时添加,且使用更简洁的分隔符
|
||||
need_separator = False
|
||||
separator_reason = ""
|
||||
last_tag = getattr(analyser, "_last_log_tag", None)
|
||||
tag_changed = bool(tag) and tag != last_tag
|
||||
|
||||
# 只在错误或非常重要的阶段变化时添加分隔符,避免日志过于冗余
|
||||
if log_level in ("ERROR", "CRITICAL"):
|
||||
need_separator = True
|
||||
separator_reason = f"错误: {tag or '系统'}"
|
||||
elif tag_changed and tag in ("运行", "启动", "完成"):
|
||||
need_separator = True
|
||||
separator_reason = tag
|
||||
|
||||
# 输出分隔符(如果需要)- 使用更简洁的分隔符
|
||||
if need_separator:
|
||||
try:
|
||||
separator = f"=== {separator_reason} ==="
|
||||
print(separator, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 更新上一个日志标签
|
||||
analyser._last_log_tag = tag
|
||||
|
||||
# 获取日志格式模式配置(simple 或 detailed)
|
||||
log_format_mode = "simple" # 默认简洁模式
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
log_format_mode = config.get("logging", {}).get(
|
||||
"log_format_mode", "simple"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 根据模式决定日志格式
|
||||
if log_format_mode == "detailed":
|
||||
# 详细模式:保留之前的复杂格式
|
||||
return _enhanced_log_kv_detailed(
|
||||
analyser,
|
||||
tag,
|
||||
msg,
|
||||
log_level,
|
||||
log_type,
|
||||
log_parts,
|
||||
timestamp,
|
||||
caller_info,
|
||||
fields,
|
||||
need_separator,
|
||||
separator_reason,
|
||||
color,
|
||||
)
|
||||
else:
|
||||
# 简洁模式:使用优化后的格式
|
||||
return _enhanced_log_kv_simple(
|
||||
analyser,
|
||||
tag,
|
||||
msg,
|
||||
log_level,
|
||||
log_parts,
|
||||
timestamp,
|
||||
fields,
|
||||
need_separator,
|
||||
separator_reason,
|
||||
color,
|
||||
)
|
||||
@@ -0,0 +1,151 @@
|
||||
"""douyin_logging_wrapper_pkg.misc - 5 个小型日志辅助方法。
|
||||
|
||||
- log_step_time 记录步骤耗时
|
||||
- log_error_with_context 记录带上下文的错误
|
||||
- log_performance_step 记录性能步骤
|
||||
- log_debug_info 记录调试信息
|
||||
- get_performance_stats 获取性能统计快照
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from ._common import (
|
||||
COLORAMA_AVAILABLE,
|
||||
Fore,
|
||||
LOGGING_MODULES_AVAILABLE,
|
||||
Style,
|
||||
_action_logger,
|
||||
_debug_logger,
|
||||
_error_logger,
|
||||
_performance_tracker,
|
||||
)
|
||||
|
||||
|
||||
from .enhanced import enhanced_log_kv as _enhanced_log_kv
|
||||
|
||||
|
||||
def log_step_time(
|
||||
analyser: Any,
|
||||
step_name: str,
|
||||
start_time: float,
|
||||
extra_info: Optional[Dict[str, Any]] = None,
|
||||
) -> None:
|
||||
"""记录某个子步骤的耗时(供检测模块调用,减少日志噪音)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
step_name: 步骤名称
|
||||
start_time: 开始时间(时间戳)
|
||||
extra_info: 额外信息字典
|
||||
"""
|
||||
try:
|
||||
elapsed = time.time() - float(start_time or 0.0)
|
||||
except Exception:
|
||||
elapsed = 0.0
|
||||
fields: Dict[str, Any] = {"seconds": elapsed}
|
||||
if extra_info:
|
||||
for k, v in extra_info.items():
|
||||
fields[str(k)] = v
|
||||
try:
|
||||
analyser._log_kv("步骤耗时", step_name, **fields) # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
|
||||
|
||||
def log_error_with_context(
|
||||
analyser: Any,
|
||||
exc: BaseException,
|
||||
context: Optional[Dict[str, Any]] = None,
|
||||
level: str = "ERROR",
|
||||
) -> None:
|
||||
"""使用错误日志模块记录异常及上下文信息"""
|
||||
if LOGGING_MODULES_AVAILABLE and _error_logger:
|
||||
try:
|
||||
_error_logger.log_exception(exc, context=context, level=level)
|
||||
except Exception:
|
||||
pass # 错误日志记录失败不应该影响主流程
|
||||
|
||||
# 同时记录到标准日志
|
||||
_enhanced_log_kv(
|
||||
analyser,
|
||||
"错误",
|
||||
f"{type(exc).__name__}: {exc}",
|
||||
level=level,
|
||||
exception_type=type(exc).__name__,
|
||||
exception_message=str(exc),
|
||||
context=context or {},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
|
||||
def log_performance_step(
|
||||
analyser: Any,
|
||||
step_name: str,
|
||||
elapsed_seconds: float,
|
||||
details: Optional[Dict[str, Any]] = None,
|
||||
) -> None:
|
||||
"""记录性能步骤信息"""
|
||||
if LOGGING_MODULES_AVAILABLE and _performance_tracker:
|
||||
try:
|
||||
# 记录到性能追踪器
|
||||
_performance_tracker.end_timer(f"{step_name}-{int(time.time()*1000)}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录到行为日志
|
||||
if LOGGING_MODULES_AVAILABLE and _action_logger:
|
||||
try:
|
||||
_action_logger.log_step(step_name, elapsed=elapsed_seconds)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录到标准日志
|
||||
fields = {"elapsed_seconds": elapsed_seconds}
|
||||
if details:
|
||||
fields.update(details)
|
||||
|
||||
_enhanced_log_kv(
|
||||
analyser, "性能", f"步骤完成: {step_name}", **fields
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
|
||||
def log_debug_info(analyser: Any, message: str, **context: Any) -> None:
|
||||
"""记录调试信息"""
|
||||
if LOGGING_MODULES_AVAILABLE and _debug_logger:
|
||||
try:
|
||||
# 这里可以扩展为更详细的调试信息记录
|
||||
_debug_logger.log_variable("debug_message", message)
|
||||
for key, value in context.items():
|
||||
_debug_logger.log_variable(key, value)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录到标准日志
|
||||
_enhanced_log_kv(
|
||||
analyser, "调试", message, level="DEBUG", **context
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
|
||||
def get_performance_stats() -> Dict[str, Any]:
|
||||
"""获取性能统计信息"""
|
||||
if LOGGING_MODULES_AVAILABLE and _performance_tracker:
|
||||
try:
|
||||
return _performance_tracker.get_statistics()
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
@@ -0,0 +1,216 @@
|
||||
"""douyin_logging_wrapper_pkg.simple - _enhanced_log_kv_simple 简化版日志记录。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from ._common import (
|
||||
COLORAMA_AVAILABLE,
|
||||
Fore,
|
||||
LOGGING_MODULES_AVAILABLE,
|
||||
Style,
|
||||
_action_logger,
|
||||
_debug_logger,
|
||||
_error_logger,
|
||||
_performance_tracker,
|
||||
)
|
||||
|
||||
|
||||
def _enhanced_log_kv_simple(
|
||||
analyser: Any,
|
||||
tag: str,
|
||||
msg: str,
|
||||
log_level: str,
|
||||
log_parts: list[str],
|
||||
timestamp: str,
|
||||
fields: Dict[str, Any],
|
||||
need_separator: bool,
|
||||
separator_reason: str,
|
||||
color: Optional[str] = None,
|
||||
) -> None:
|
||||
"""简洁模式的日志记录"""
|
||||
# 输出分隔符(如果需要)- 使用更简洁的分隔符
|
||||
if need_separator:
|
||||
try:
|
||||
separator = f"=== {separator_reason} ==="
|
||||
print(separator, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 更新上一个日志标签
|
||||
analyser._last_log_tag = tag
|
||||
|
||||
# 构建简洁的日志行
|
||||
log_line = " ".join(log_parts)
|
||||
|
||||
# 应用颜色(如果指定了颜色)
|
||||
if color:
|
||||
try:
|
||||
if hasattr(Fore, color.upper()):
|
||||
color_code = getattr(Fore, color.upper())
|
||||
log_line = f"{color_code}{log_line}{Style.RESET_ALL}"
|
||||
elif color.startswith("\033["): # ANSI 转义序列
|
||||
log_line = f"{color}{log_line}{Style.RESET_ALL}"
|
||||
except Exception:
|
||||
pass # 如果颜色应用失败,使用原始日志行
|
||||
|
||||
# 始终输出到 stdout(供 GUI 捕获)- 这是最重要的!
|
||||
try:
|
||||
print(log_line, flush=True) # flush=True 确保立即输出,不缓冲
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 简化行为日志记录,避免重复输出
|
||||
try:
|
||||
# 只在重要事件时写入行为日志
|
||||
should_log_action = False
|
||||
if tag and any(
|
||||
keyword in str(tag)
|
||||
for keyword in ["参与", "中奖", "完成", "失败", "运行"]
|
||||
):
|
||||
should_log_action = True
|
||||
|
||||
if should_log_action:
|
||||
# 获取时间戳
|
||||
if not timestamp:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
|
||||
# 构建简洁的行为日志
|
||||
action_parts = [f"[{timestamp}]"]
|
||||
if tag:
|
||||
action_parts.append(f"[{tag}]")
|
||||
if msg:
|
||||
action_parts.append(msg[:100]) # 限制长度
|
||||
action_log_line = " ".join(action_parts)
|
||||
|
||||
# 写入 actions.log 文件
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
actions_log_path = path_config.get_actions_log_path()
|
||||
log_dir = path_config.get_logs_dir()
|
||||
except Exception:
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(__file__), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
with open(
|
||||
actions_log_path,
|
||||
"a",
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
) as f:
|
||||
f.write(action_log_line + "\n")
|
||||
f.flush()
|
||||
# 同步调用行为日志模块以获得结构化记录
|
||||
try:
|
||||
if LOGGING_MODULES_AVAILABLE and _action_logger:
|
||||
# 提取耗时(统一为秒传入 ActionLogger)
|
||||
elapsed_seconds = None
|
||||
try:
|
||||
if "elapsed_ms" in fields:
|
||||
elapsed_seconds = (
|
||||
float(fields.get("elapsed_ms", 0)) / 1000.0
|
||||
)
|
||||
elif "total_ms" in fields:
|
||||
elapsed_seconds = (
|
||||
float(fields.get("total_ms", 0)) / 1000.0
|
||||
)
|
||||
elif "elapsed_seconds" in fields:
|
||||
elapsed_seconds = float(
|
||||
fields.get("elapsed_seconds", 0)
|
||||
)
|
||||
elif "seconds" in fields:
|
||||
elapsed_seconds = float(fields.get("seconds", 0))
|
||||
except Exception:
|
||||
elapsed_seconds = None
|
||||
|
||||
# 构建额外字段(保留分数、价值、位置信息)
|
||||
extra = {}
|
||||
for k in ("score", "value_yuan", "room_pos", "fudai_x", "rid"):
|
||||
if k in fields:
|
||||
extra[k] = fields.get(k)
|
||||
|
||||
try:
|
||||
op_name = tag if tag else "操作"
|
||||
details = msg if msg else None
|
||||
if elapsed_seconds is not None:
|
||||
_action_logger.log_operation(
|
||||
op_name,
|
||||
details or "",
|
||||
elapsed=elapsed_seconds,
|
||||
**extra,
|
||||
)
|
||||
else:
|
||||
_action_logger.log_operation(
|
||||
op_name, details or "", **extra
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 移除标准 logging 输出,避免与 stdout 重复
|
||||
# 现在只通过 print 输出到控制台,行为日志只记录重要事件
|
||||
|
||||
# 如果有异常堆栈,也输出到 stdout
|
||||
exc_info = fields.get("exc_info")
|
||||
if exc_info is None:
|
||||
if sys.exc_info()[0] is not None:
|
||||
exc_info = sys.exc_info()
|
||||
|
||||
if exc_info:
|
||||
try:
|
||||
# exc_info 应该是 (type, value, traceback) 元组
|
||||
if isinstance(exc_info, tuple) and len(exc_info) == 3:
|
||||
exc_type, exc_value, exc_traceback = exc_info
|
||||
# 确保 exc_value 是 BaseException 实例
|
||||
if isinstance(exc_value, BaseException):
|
||||
tb_str = traceback.format_exception(
|
||||
exc_type, exc_value, exc_traceback
|
||||
)
|
||||
else:
|
||||
# 如果不是异常实例,创建一个包装异常
|
||||
try:
|
||||
# 尝试使用原始值
|
||||
tb_str = traceback.format_exception(
|
||||
exc_type,
|
||||
(
|
||||
BaseException(str(exc_value))
|
||||
if exc_value
|
||||
else BaseException("Unknown error")
|
||||
),
|
||||
exc_traceback,
|
||||
)
|
||||
except Exception:
|
||||
# 如果还是失败,只输出异常信息
|
||||
print(
|
||||
f" 异常类型: {exc_type}, 异常值: {exc_value}",
|
||||
flush=True,
|
||||
)
|
||||
tb_str = []
|
||||
for line in tb_str:
|
||||
print(f" {line.rstrip()}", flush=True)
|
||||
else:
|
||||
# 如果不是标准格式,尝试直接格式化
|
||||
try:
|
||||
tb_str = traceback.format_exception(*exc_info)
|
||||
for line in tb_str:
|
||||
print(f" {line.rstrip()}", flush=True)
|
||||
except Exception:
|
||||
# 如果格式化失败,只输出异常信息
|
||||
print(f" 异常信息: {exc_info}", flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,55 @@
|
||||
"""douyin_logging_wrapper_pkg.wrapper - LoggingWrapper 类(薄壳)。
|
||||
|
||||
每个方法都是 @staticmethod 的 1 行 forwarding。
|
||||
外部 LoggingWrapper.method(...) 的代码完全不需要改。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from .enhanced import enhanced_log_kv as _enhanced_log_kv
|
||||
from .simple import _enhanced_log_kv_simple as __simple
|
||||
from .detailed import _enhanced_log_kv_detailed as __detailed
|
||||
from .misc import (
|
||||
log_step_time as _log_step_time,
|
||||
log_error_with_context as _log_error_with_context,
|
||||
log_performance_step as _log_performance_step,
|
||||
log_debug_info as _log_debug_info,
|
||||
get_performance_stats as _get_performance_stats,
|
||||
)
|
||||
|
||||
|
||||
class LoggingWrapper:
|
||||
"""日志包装器:统一管理日志功能(薄壳,转发到 module-level 函数)。"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def enhanced_log_kv(*args, **kwargs) -> None:
|
||||
return _enhanced_log_kv(*args, **kwargs)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _enhanced_log_kv_simple(*args, **kwargs) -> None:
|
||||
return __simple(*args, **kwargs)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _enhanced_log_kv_detailed(*args, **kwargs) -> None:
|
||||
return __detailed(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def log_step_time(*args, **kwargs) -> None:
|
||||
return _log_step_time(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def log_error_with_context(*args, **kwargs) -> None:
|
||||
return _log_error_with_context(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def log_performance_step(*args, **kwargs) -> None:
|
||||
return _log_performance_step(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def log_debug_info(*args, **kwargs) -> None:
|
||||
return _log_debug_info(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def get_performance_stats() -> Dict[str, Any]:
|
||||
return _get_performance_stats()
|
||||
+13
-147
@@ -11,100 +11,25 @@ cv2: Any = _cv2
|
||||
import numpy as np
|
||||
|
||||
|
||||
# 从子包 re-export(保持兼容;yanghao_idle 仍在本文件,需要这些 helper)
|
||||
from douyin.other.douyin_yanghao_pkg import (
|
||||
_LOGGER,
|
||||
_yanghao_log,
|
||||
_scaled_click,
|
||||
_do_comment,
|
||||
yanghao_recommend_flow,
|
||||
yanghao_wait,
|
||||
yanghao_get_recommend_seconds,
|
||||
)
|
||||
|
||||
|
||||
|
||||
# 模块级日志:优先走 analyser._log_kv,回退到 logging(避免裸 print 散落到 stdout)
|
||||
import logging as _logging
|
||||
|
||||
_LOGGER = _logging.getLogger("douyin.other.douyin_yanghao")
|
||||
|
||||
|
||||
def _yanghao_log(analyser, msg: str, level: str = "INFO") -> None:
|
||||
"""统一养号日志出口。
|
||||
|
||||
- 当 analyser 提供 `_log_kv` 时,优先用它(与项目统一日志体系一致)。
|
||||
- 否则回退到模块 logger;最后兜底到 stdout 以避免静默丢日志。
|
||||
"""
|
||||
try:
|
||||
log_kv = getattr(analyser, "_log_kv", None)
|
||||
if callable(log_kv):
|
||||
log_kv("养号", str(msg), level=str(level or "INFO"))
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if str(level).upper() == "ERROR":
|
||||
_LOGGER.error(str(msg))
|
||||
elif str(level).upper() == "WARNING":
|
||||
_LOGGER.warning(str(msg))
|
||||
else:
|
||||
_LOGGER.info(str(msg))
|
||||
except Exception:
|
||||
try:
|
||||
_yanghao_log(analyser, str(msg))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
def _scaled_click(analyser, base_x: int, base_y: int) -> None:
|
||||
"""模块级点击封装:根据基准坐标缩放并点击(兼容原嵌套实现)。"""
|
||||
sx, sy = analyser._scale_from_base(int(base_x), int(base_y))
|
||||
# 使用底层 click 时不打印底层日志,以避免养号动作产生多余的聚焦/日志噪音
|
||||
try:
|
||||
analyser.operation.click(analyser.device_id, sx, sy, log=False)
|
||||
except TypeError:
|
||||
# 向后兼容:如果底层 click 还没有 log 参数,回退到旧调用
|
||||
analyser.operation.click(analyser.device_id, sx, sy)
|
||||
|
||||
|
||||
def _do_comment(analyser) -> None:
|
||||
"""模块级评论操作:点击评论按钮 -> 输入框 -> 输入文本 -> 发送 -> 关闭"""
|
||||
try:
|
||||
# 步骤1: 点击评论按钮
|
||||
btn_x = int(getattr(analyser, "yanghao_comment_btn_x", 540) or 540)
|
||||
btn_y = int(getattr(analyser, "yanghao_comment_btn_y", 2000) or 2000)
|
||||
_yanghao_log(analyser, f"[养号][评论] Step1: 点击评论按钮 coord=({btn_x},{btn_y})")
|
||||
_scaled_click(analyser, btn_x, btn_y)
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 步骤2: 点击输入框
|
||||
input_x = int(getattr(analyser, "yanghao_comment_input_x", 144) or 144)
|
||||
input_y = int(getattr(analyser, "yanghao_comment_input_y", 2179) or 2179)
|
||||
_yanghao_log(analyser, f"[养号][评论] Step2: 点击输入框 coord=({input_x},{input_y})")
|
||||
_scaled_click(analyser, input_x, input_y)
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 步骤3: 输入评论文本
|
||||
comment_texts = getattr(analyser, "yanghao_comment_texts", []) or []
|
||||
if not comment_texts:
|
||||
comment_texts = ["加油", "不错", "很好看"]
|
||||
selected_text = random.choice(comment_texts)
|
||||
_yanghao_log(analyser, f"[养号][评论] Step3: 选择文本 -> {selected_text}")
|
||||
|
||||
ix, iy = analyser._scale_from_base(input_x, input_y)
|
||||
ok_input = bool(
|
||||
analyser.operation.paste_text_at(
|
||||
analyser.device_id, ix, iy, selected_text, ensure_focus=False
|
||||
)
|
||||
)
|
||||
_yanghao_log(analyser, f"[养号][评论] paste_text_at -> ok={ok_input} scaled_coord=({ix},{iy})")
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 步骤4: 发送评论
|
||||
ok_send = bool(analyser.operation.confirm_from_keyboard(analyser.device_id))
|
||||
_yanghao_log(analyser, f"[养号][评论] Step4: 发送评论 -> ok={ok_send}")
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 步骤5: 关闭评论窗口
|
||||
close_x = int(getattr(analyser, "yanghao_comment_close_x", 900) or 900)
|
||||
close_y = int(getattr(analyser, "yanghao_comment_close_y", 300) or 300)
|
||||
_yanghao_log(analyser, f"[养号][评论] Step5: 关闭评论窗口 coord=({close_x},{close_y})")
|
||||
_scaled_click(analyser, close_x, close_y)
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
except Exception as e:
|
||||
_yanghao_log(analyser, f"[养号] 评论操作失败: {e}")
|
||||
|
||||
|
||||
def yanghao_idle(analyser, total_seconds: int) -> None:
|
||||
"""养号等待。
|
||||
|
||||
@@ -861,62 +786,3 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
|
||||
return True, 1.0
|
||||
|
||||
|
||||
def yanghao_recommend_flow(analyser, total_seconds: int) -> None:
|
||||
"""执行推荐页养号流程:退出直播间 -> 进入推荐页 -> 养号。
|
||||
|
||||
每一步操作间隔1秒,确保界面稳定。
|
||||
"""
|
||||
try:
|
||||
# 输出设备分辨率与调试行(兼容原始日志格式)
|
||||
try:
|
||||
resx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
resy = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
resx, resy = 1080, 2400
|
||||
_yanghao_log(analyser, f"设备分辨率为:{resx}*{resy}")
|
||||
_yanghao_log(analyser, f"[YANGHAO-ONLY] device_id={analyser.device_id} res={resx}x{resy}")
|
||||
_yanghao_log(analyser, "[养号] 开始推荐页养号流程")
|
||||
|
||||
# 步骤1: 发送系统返回键退出当前直播间
|
||||
_yanghao_log(analyser, "[养号] 步骤1: 发送系统返回键退出直播间")
|
||||
analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4
|
||||
analyser.operation.delay(3.0)
|
||||
|
||||
# 步骤2: 再次发送返回键确保退出
|
||||
_yanghao_log(analyser, "[养号] 步骤2: 再次发送返回键")
|
||||
analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4
|
||||
analyser.operation.delay(3.0)
|
||||
|
||||
# 步骤3: 在推荐页执行养号
|
||||
_yanghao_log(analyser, f"[养号] 步骤3: 在推荐页养号 {total_seconds} 秒")
|
||||
analyser.operation.delay(3.0)
|
||||
yanghao_idle(analyser, total_seconds)
|
||||
|
||||
_yanghao_log(analyser, "[养号] 推荐页养号流程完成")
|
||||
|
||||
except Exception as e:
|
||||
_yanghao_log(analyser, f"[养号] 推荐页养号流程失败: {e}")
|
||||
# 失败时退化为普通养号
|
||||
yanghao_idle(analyser, total_seconds)
|
||||
|
||||
|
||||
def yanghao_wait(analyser, total_seconds: int) -> None:
|
||||
"""养号等待函数(兼容接口)。"""
|
||||
if total_seconds <= 0:
|
||||
return
|
||||
|
||||
# 检查是否启用养号
|
||||
if not bool(getattr(analyser, "yanghao_enabled", True)):
|
||||
_yanghao_log(analyser, "[养号] yanghao_enabled=0,跳过推荐页养号(快速继续)")
|
||||
return
|
||||
|
||||
# 执行推荐页养号流程
|
||||
yanghao_recommend_flow(analyser, total_seconds)
|
||||
|
||||
|
||||
def yanghao_get_recommend_seconds(analyser) -> int:
|
||||
"""返回推荐页养号的默认时长(兼容接口)。"""
|
||||
try:
|
||||
return int(getattr(analyser, "yanghao_recommend_duration_seconds", 60) or 60)
|
||||
except Exception:
|
||||
return 60
|
||||
@@ -0,0 +1,32 @@
|
||||
"""douyin_yanghao_pkg - 推荐页养号子包。
|
||||
|
||||
原 douyin/other/douyin_yanghao.py 拆出 6 个独立函数:
|
||||
|
||||
- logger _yanghao_log
|
||||
- click_helpers _scaled_click / _do_comment
|
||||
- entrypoints yanghao_recommend_flow / yanghao_wait / yanghao_get_recommend_seconds
|
||||
|
||||
巨型函数 yanghao_idle (756 行) 留在原文件,从子包 import _yanghao_log /
|
||||
_scaled_click / _do_comment 即可正常工作。
|
||||
|
||||
外部 import 路径不变:
|
||||
``from douyin.other.douyin_yanghao import yanghao_recommend_flow`` 仍可用。
|
||||
"""
|
||||
|
||||
from .logger import _LOGGER, _yanghao_log
|
||||
from .click_helpers import _do_comment, _scaled_click
|
||||
from .entrypoints import (
|
||||
yanghao_get_recommend_seconds,
|
||||
yanghao_recommend_flow,
|
||||
yanghao_wait,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"_LOGGER",
|
||||
"_yanghao_log",
|
||||
"_scaled_click",
|
||||
"_do_comment",
|
||||
"yanghao_recommend_flow",
|
||||
"yanghao_wait",
|
||||
"yanghao_get_recommend_seconds",
|
||||
]
|
||||
@@ -0,0 +1,75 @@
|
||||
"""douyin_yanghao_pkg.click_helpers - 点击 / 评论操作辅助。
|
||||
|
||||
- _scaled_click: 模块级点击封装,自动按分辨率缩放坐标。
|
||||
- _do_comment: 模块级评论操作(点击评论按钮 → 输入框 → 输入 → 发送 → 关闭)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
from .logger import _yanghao_log
|
||||
|
||||
|
||||
def _scaled_click(analyser, base_x: int, base_y: int) -> None:
|
||||
"""模块级点击封装:根据基准坐标缩放并点击(兼容原嵌套实现)。"""
|
||||
sx, sy = analyser._scale_from_base(int(base_x), int(base_y))
|
||||
# 使用底层 click 时不打印底层日志,以避免养号动作产生多余的聚焦/日志噪音
|
||||
try:
|
||||
analyser.operation.click(analyser.device_id, sx, sy, log=False)
|
||||
except TypeError:
|
||||
# 向后兼容:如果底层 click 还没有 log 参数,回退到旧调用
|
||||
analyser.operation.click(analyser.device_id, sx, sy)
|
||||
|
||||
|
||||
|
||||
|
||||
def _do_comment(analyser) -> None:
|
||||
"""模块级评论操作:点击评论按钮 -> 输入框 -> 输入文本 -> 发送 -> 关闭"""
|
||||
try:
|
||||
# 步骤1: 点击评论按钮
|
||||
btn_x = int(getattr(analyser, "yanghao_comment_btn_x", 540) or 540)
|
||||
btn_y = int(getattr(analyser, "yanghao_comment_btn_y", 2000) or 2000)
|
||||
_yanghao_log(analyser, f"[养号][评论] Step1: 点击评论按钮 coord=({btn_x},{btn_y})")
|
||||
_scaled_click(analyser, btn_x, btn_y)
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 步骤2: 点击输入框
|
||||
input_x = int(getattr(analyser, "yanghao_comment_input_x", 144) or 144)
|
||||
input_y = int(getattr(analyser, "yanghao_comment_input_y", 2179) or 2179)
|
||||
_yanghao_log(analyser, f"[养号][评论] Step2: 点击输入框 coord=({input_x},{input_y})")
|
||||
_scaled_click(analyser, input_x, input_y)
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 步骤3: 输入评论文本
|
||||
comment_texts = getattr(analyser, "yanghao_comment_texts", []) or []
|
||||
if not comment_texts:
|
||||
comment_texts = ["加油", "不错", "很好看"]
|
||||
selected_text = random.choice(comment_texts)
|
||||
_yanghao_log(analyser, f"[养号][评论] Step3: 选择文本 -> {selected_text}")
|
||||
|
||||
ix, iy = analyser._scale_from_base(input_x, input_y)
|
||||
ok_input = bool(
|
||||
analyser.operation.paste_text_at(
|
||||
analyser.device_id, ix, iy, selected_text, ensure_focus=False
|
||||
)
|
||||
)
|
||||
_yanghao_log(analyser, f"[养号][评论] paste_text_at -> ok={ok_input} scaled_coord=({ix},{iy})")
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 步骤4: 发送评论
|
||||
ok_send = bool(analyser.operation.confirm_from_keyboard(analyser.device_id))
|
||||
_yanghao_log(analyser, f"[养号][评论] Step4: 发送评论 -> ok={ok_send}")
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 步骤5: 关闭评论窗口
|
||||
close_x = int(getattr(analyser, "yanghao_comment_close_x", 900) or 900)
|
||||
close_y = int(getattr(analyser, "yanghao_comment_close_y", 300) or 300)
|
||||
_yanghao_log(analyser, f"[养号][评论] Step5: 关闭评论窗口 coord=({close_x},{close_y})")
|
||||
_scaled_click(analyser, close_x, close_y)
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
except Exception as e:
|
||||
_yanghao_log(analyser, f"[养号] 评论操作失败: {e}")
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""douyin_yanghao_pkg.entrypoints - 养号入口函数。
|
||||
|
||||
- yanghao_recommend_flow: 推荐页养号流程(退出直播间 → 进推荐页 → 养号)
|
||||
- yanghao_wait: 养号等待函数(兼容接口)
|
||||
- yanghao_get_recommend_seconds: 推荐页养号默认时长读取
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .logger import _yanghao_log
|
||||
|
||||
|
||||
def _yanghao_idle_from_main(analyser, total_seconds: int) -> None:
|
||||
"""懒加载 yanghao_idle(避免循环依赖:yanghao_idle 仍在原文件)。"""
|
||||
from douyin.other.douyin_yanghao import yanghao_idle as _impl
|
||||
_impl(analyser, total_seconds)
|
||||
|
||||
|
||||
def yanghao_recommend_flow(analyser, total_seconds: int) -> None:
|
||||
"""执行推荐页养号流程:退出直播间 -> 进入推荐页 -> 养号。
|
||||
|
||||
每一步操作间隔1秒,确保界面稳定。
|
||||
"""
|
||||
try:
|
||||
# 输出设备分辨率与调试行(兼容原始日志格式)
|
||||
try:
|
||||
resx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
resy = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
resx, resy = 1080, 2400
|
||||
_yanghao_log(analyser, f"设备分辨率为:{resx}*{resy}")
|
||||
_yanghao_log(analyser, f"[YANGHAO-ONLY] device_id={analyser.device_id} res={resx}x{resy}")
|
||||
_yanghao_log(analyser, "[养号] 开始推荐页养号流程")
|
||||
|
||||
# 步骤1: 发送系统返回键退出当前直播间
|
||||
_yanghao_log(analyser, "[养号] 步骤1: 发送系统返回键退出直播间")
|
||||
analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4
|
||||
analyser.operation.delay(3.0)
|
||||
|
||||
# 步骤2: 再次发送返回键确保退出
|
||||
_yanghao_log(analyser, "[养号] 步骤2: 再次发送返回键")
|
||||
analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4
|
||||
analyser.operation.delay(3.0)
|
||||
|
||||
# 步骤3: 在推荐页执行养号
|
||||
_yanghao_log(analyser, f"[养号] 步骤3: 在推荐页养号 {total_seconds} 秒")
|
||||
analyser.operation.delay(3.0)
|
||||
_yanghao_idle_from_main(analyser, total_seconds)
|
||||
|
||||
_yanghao_log(analyser, "[养号] 推荐页养号流程完成")
|
||||
|
||||
except Exception as e:
|
||||
_yanghao_log(analyser, f"[养号] 推荐页养号流程失败: {e}")
|
||||
# 失败时退化为普通养号
|
||||
_yanghao_idle_from_main(analyser, total_seconds)
|
||||
|
||||
|
||||
|
||||
|
||||
def yanghao_wait(analyser, total_seconds: int) -> None:
|
||||
"""养号等待函数(兼容接口)。"""
|
||||
if total_seconds <= 0:
|
||||
return
|
||||
|
||||
# 检查是否启用养号
|
||||
if not bool(getattr(analyser, "yanghao_enabled", True)):
|
||||
_yanghao_log(analyser, "[养号] yanghao_enabled=0,跳过推荐页养号(快速继续)")
|
||||
return
|
||||
|
||||
# 执行推荐页养号流程
|
||||
yanghao_recommend_flow(analyser, total_seconds)
|
||||
|
||||
|
||||
|
||||
|
||||
def yanghao_get_recommend_seconds(analyser) -> int:
|
||||
"""返回推荐页养号的默认时长(兼容接口)。"""
|
||||
try:
|
||||
return int(getattr(analyser, "yanghao_recommend_duration_seconds", 60) or 60)
|
||||
except Exception:
|
||||
return 60
|
||||
@@ -0,0 +1,40 @@
|
||||
"""douyin_yanghao_pkg.logger - 模块级日志输出。
|
||||
|
||||
_yanghao_log: 优先走 analyser._log_kv(项目统一日志体系),
|
||||
失败兜底到 logging logger,再失败兜底 stdout。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging as _logging
|
||||
|
||||
_LOGGER = _logging.getLogger("douyin.other.douyin_yanghao")
|
||||
|
||||
|
||||
def _yanghao_log(analyser, msg: str, level: str = "INFO") -> None:
|
||||
"""统一养号日志出口。
|
||||
|
||||
- 当 analyser 提供 `_log_kv` 时,优先用它(与项目统一日志体系一致)。
|
||||
- 否则回退到模块 logger;最后兜底到 stdout 以避免静默丢日志。
|
||||
"""
|
||||
try:
|
||||
log_kv = getattr(analyser, "_log_kv", None)
|
||||
if callable(log_kv):
|
||||
log_kv("养号", str(msg), level=str(level or "INFO"))
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if str(level).upper() == "ERROR":
|
||||
_LOGGER.error(str(msg))
|
||||
elif str(level).upper() == "WARNING":
|
||||
_LOGGER.warning(str(msg))
|
||||
else:
|
||||
_LOGGER.info(str(msg))
|
||||
except Exception:
|
||||
try:
|
||||
_yanghao_log(analyser, str(msg))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user