feat: Refactor coverage management and enhance logging functionality
- Removed the `.coverage` file from the repository to streamline coverage management. - Updated `.gitignore` to exclude coverage-related files and directories, ensuring a cleaner project structure. - Introduced new scripts for checking GPU availability and detecting GUI parameter conflicts, enhancing the overall functionality of the application. - Improved logging mechanisms across various modules to support better debugging and monitoring. - Added comprehensive documentation for new features and updated existing markdown files for clarity.
This commit is contained in:
1 parent
539e580147
commit
e68f1dd3de
70 files changed
+62590
-10791
No files matched your search
@@ -15,6 +15,13 @@ pyright_report.txt
|
||||
*.report
|
||||
*.lint
|
||||
|
||||
# Test coverage
|
||||
.coverage
|
||||
.coverage.*
|
||||
htmlcov/
|
||||
.tox/
|
||||
.pytest_cache/
|
||||
|
||||
# VS Code
|
||||
.vscode/
|
||||
|
||||
|
||||
+13046
-9755
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- vscode Session 8c9f5341-af85-4918-b056-0c29446bc029 (2025-12-22 13:45Z) -->
|
||||
|
||||
# 完善我的readme (2025-12-22 13:45Z)
|
||||
|
||||
_**User (2025-12-22 13:45Z)**_
|
||||
|
||||
完善我的readme
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model copilot/gpt-5-mini)**_
|
||||
|
||||
**Improving the README**
|
||||
|
||||
The user asked to improve their README. First, I need to use the manage_todo_list tool to plan and track progress. I'll start with a short preamble to explain what I'll be doing. After that, I'll write the plan and then proceed to update README.md using apply_patch. Before that, I should read the current content of README.md with functions.read_file to ensure I maintain or enhance it. Then, I will describe my next steps!**Processing README Updates**
|
||||
|
||||
I noticed that the tool preamble suggests avoiding trivial preambles, but I still need one before tool calls. First, I’ll send a brief preamble and then call functions.read_file to read the first 400 lines of README.md. After reading, I’ll prepare a patch and create new README content in Chinese. I have to ensure the format is concise yet comprehensive, using headers and bullet points for clarity. Additionally, I’ll wrap filenames in backticks and follow the appropriate linkification rules.**Navigating README Instructions**
|
||||
|
||||
I see there are some conflicting instructions regarding wrapping filenames in backticks. It's clear that I can mention `README.md` in backticks, but earlier notes say not to use backticks for file links. Since I’m not including links, that works just fine! My steps are to first review the current README, then draft an improved version covering various sections like project overview, features, and contributions. After applying the patch, I might consider a quick lint or test. I’ll start by calling manage_todo_list to track these steps.**Planning README Improvements**
|
||||
|
||||
The instructions are clear: I need to start with the todo list tool
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- vscode Session 2be00521-0236-4d09-b90c-7fd3019c096c (2025-12-22 13:51Z) -->
|
||||
|
||||
# 为什么我的vscode隔一会会卡一下 (2025-12-22 13:51Z)
|
||||
|
||||
_**User (2025-12-22 13:52Z)**_
|
||||
|
||||
为什么我的vscode隔一会会卡一下
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model copilot/gpt-5-mini)**_
|
||||
|
||||
**Diagnosing VSCode issues**
|
||||
|
||||
User asked why their VSCode freezes intermittently. I need to utilize the manage_todo_list tool to plan and track my steps since this task involves multiple actions. I’ll start by gathering environment details, which I know includes Windows OS. Then I'll check CPU/memory usage, extensions, and logs. I can suggest quick fixes, and I might run checks if the user wants that. I'll also check the extensions list but without direct access to the VSCode API.**Identifying VSCode performance issues**
|
||||
|
||||
I need to use the todo list tool to organize my steps for diagnosing VSCode's freezing. I'll consider possible causes like CPU-intensive extensions, Git or TypeScript servers, large workspaces, and various background processes. I can provide PowerShell commands, such as "code --status" to check CPU usage. Also, I should suggest running VSCode with `--disable-extensions` to test extensions' impact and consider enabling or disabling hardware acceleration through the relevant settings carefully. Staying precise is key!**Recommending VSCode troubleshooting steps**
|
||||
|
||||
I want to suggest launching VSCode with `code --disable-gpu` and `code --disable-features=RendererCodeIntegrity` for testing. Checking extensions is essential—I'll recommend running `code --list-extensions` and using `code --disable-extensions` to help identify the issue. The steps I'll outline include testing in extensions-disabled mode, monitoring with `code --status` or Task Manager, and inspecting console errors through the Developer Tools. I should also advise updating VSCode, disabling Git auto-fetch, and excluding unnecessary files from watchers to streamline performance. Plus, mentioning antivirus exclusions for project folders could help!**Planning diagnostic steps**
|
||||
|
||||
I need to gather information from the user about their symptoms and how frequently they occur. Then, I'll run some quick checks, like disabling extensions and using `code --status`. Next, checking the logs through the Developer Tools is important. For fixes, I’ll suggest excluding certain folders, updating, and disabling the GPU. I’ll use the manage_todo_list tool to write a detailed plan with status updates. After calling the tool, I’ll provide a progress update and ask the user for specifics about their Windows and VSCode versions, along with any other relevant information.**Creating a diagnostic TODO list in Chinese**
|
||||
|
||||
I'll start by crafting a preamble before my tool call: "我将创建一个诊断与修复步骤的 TODO 列表,用于跟踪检查进度。" Then, I’ll call the manage_todo_list tool with a list that includes gathering user details, testing with extensions disabled, collecting VSCode status, inspecting Developer Tools logs, and applying fixes. After creating the list, I will provide a progress update saying: "已创建诊断 TODO;接下来列出常见原因和快速排查命令。" I'll include specific commands for the user to run, along with settings changes and suggestions for troubleshooting.我将创建一个用于诊断和修复 VSCode 卡顿的 TODO 列表以便跟踪进度。
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- cursor Session 4e3c1b7d-0998-4cd8-8d9d-8d29cefe38d6 (2025-12-22 14:31Z) -->
|
||||
|
||||
# Participation button click issue (2025-12-22 14:31Z)
|
||||
|
||||
_**User (2025-12-22 13:37Z)**_
|
||||
|
||||
@pic/debug_captures/2025-12-22/20251222_212122_ocr_参与按钮_preprocessed_mode_0_size_680x200_source_参与按钮.png.png 参与按钮识别到了,但是没点击到
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model default, mode Agent)**_
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- cursor Session b1c57c9b-0408-4ad6-ad54-cc48c7eecabb (2025-12-22 14:32Z) -->
|
||||
|
||||
# 福袋详情识别与回退失败 (2025-12-22 14:32Z)
|
||||
|
||||
_**User (2025-12-22 14:45Z)**_
|
||||
|
||||
把这里的没识别到福袋详情的返回换成点击520,505;另外,这里为什么回退失败了:[2025-12-22 21:50:29.814] [INFO] [阶段诊断] [douyin_stage.py:_log_summary:35] 阶段诊断完成(在直播间) 字段_阶段=IN_LIVE_ROOM 字段_原因=识别到在直播间(像素检测),其他阶段未识别 字段_检测方法=像素检测 字段_分数=0.857 字段_总耗时毫秒=938
|
||||
[2025-12-22 21:50:29.814] [INFO] [截图] [douyin_fudai.py:run_once_basic:1684] 截图+阶段诊断 阶段=IN_LIVE_ROOM 识别=识别到在直播间(像素检测),其他阶段未识别
|
||||
[21:50:30] [截图] ✓ 获取屏幕截图成功
|
||||
[21:50:34] [截图] ✓ 获取屏幕截图成功
|
||||
[2025-12-22 21:50:36.089] [INFO] [找福袋图标] [douyin_fudai.py:_shot_and_diagnose:2062] 获取截图
|
||||
[2025-12-22 21:50:36.174] [INFO] [[福袋查找] 图像获取] [douyin_fudai_finder.py:acquire_screenshot:60] 成功 字段_elapsed_ms=2018 字段_size=1080x2400
|
||||
[2025-12-22 21:50:36.177] [INFO] [[福袋查找] 像素检测] [douyin_fudai_finder.py:detect_by_pixel:326] 实际福袋区域命中 字段_elapsed_ms=0.000 字段_x=509 字段_region=(34,363)-(608,451) 字段_optimal_col=176 字段_found_col=475
|
||||
[2025-12-22 21:50:36.177] [INFO] [[福袋查找] 检测完成] [douyin_fudai_finder.py:detect:788] 像素检测命中(模板匹配已关闭) 字段_total_elapsed_ms=0.000 字段_region=实际福袋区域 字段_x=509 字段_method=pixel 字段_note=模板匹配已禁用,直接使用像素检测结果
|
||||
[2025-12-22 21:50:36.178] [INFO] [流程] [douyin_flow_control.py:find_and_open_fudai_detail:134] find_and_open_fudai_detail:检测到福袋图标 字段_x=509 字段_elapsed_seconds=2.02
|
||||
[2025-12-22 21:50:36.178] [INFO] [流程] [douyin_flow_control.py:find_and_open_fudai_detail:193] find_and_open_fudai_detail:检测到福袋图标并点击 福袋X坐标=509 字段_click_x=509 字段_click_y=403
|
||||
[21:50:37] [截图] ✓ 获取屏幕截图成功
|
||||
[2025-12-22 21:50:40.501] [INFO] [流程] [douyin_flow_control.py:find_and_open_fudai_detail:262] find_and_open_fudai_detail:点击后未检测到福袋详情页,可能误点击 字段_detected_x=509 字段_click_x=509 字段_click_y=403
|
||||
点击返回键
|
||||
[2025-12-22 21:50:41.747] [INFO] [流程] [douyin_flow_control.py:handle_no_fudai_situation:321] handle_no_fudai_situation 字段_x=0 字段_swipe_times=0 当前位置=0 字段_reservations=0
|
||||
[2025-12-22 21:50:42.748] [INFO] [滑动] [douyin_swipe_ops.py:swipe_up_switch_live:34] swipe_up_switch_live:上滑切换直播间 字段_start_x=540 字段_start_y=1700 字段_end_x=540 字段_end_y=700
|
||||
[停止] 正在终止进程...
|
||||
[进程结束] exit_code=1
|
||||
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model default, mode Agent)**_
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- cursor Session f1d2eaa4-088c-4fb6-b719-fab2eb9af4b6 (2025-12-22 14:49Z) -->
|
||||
|
||||
# 福袋详情识别与回退失败 (2025-12-22 14:49Z)
|
||||
|
||||
_**User (2025-12-22 14:45Z)**_
|
||||
|
||||
把这里的没识别到福袋详情的返回换成点击520,505;另外,这里为什么回退失败了:[2025-12-22 21:50:29.814] [INFO] [阶段诊断] [douyin_stage.py:_log_summary:35] 阶段诊断完成(在直播间) 字段_阶段=IN_LIVE_ROOM 字段_原因=识别到在直播间(像素检测),其他阶段未识别 字段_检测方法=像素检测 字段_分数=0.857 字段_总耗时毫秒=938
|
||||
[2025-12-22 21:50:29.814] [INFO] [截图] [douyin_fudai.py:run_once_basic:1684] 截图+阶段诊断 阶段=IN_LIVE_ROOM 识别=识别到在直播间(像素检测),其他阶段未识别
|
||||
[21:50:30] [截图] ✓ 获取屏幕截图成功
|
||||
[21:50:34] [截图] ✓ 获取屏幕截图成功
|
||||
[2025-12-22 21:50:36.089] [INFO] [找福袋图标] [douyin_fudai.py:_shot_and_diagnose:2062] 获取截图
|
||||
[2025-12-22 21:50:36.174] [INFO] [[福袋查找] 图像获取] [douyin_fudai_finder.py:acquire_screenshot:60] 成功 字段_elapsed_ms=2018 字段_size=1080x2400
|
||||
[2025-12-22 21:50:36.177] [INFO] [[福袋查找] 像素检测] [douyin_fudai_finder.py:detect_by_pixel:326] 实际福袋区域命中 字段_elapsed_ms=0.000 字段_x=509 字段_region=(34,363)-(608,451) 字段_optimal_col=176 字段_found_col=475
|
||||
[2025-12-22 21:50:36.177] [INFO] [[福袋查找] 检测完成] [douyin_fudai_finder.py:detect:788] 像素检测命中(模板匹配已关闭) 字段_total_elapsed_ms=0.000 字段_region=实际福袋区域 字段_x=509 字段_method=pixel 字段_note=模板匹配已禁用,直接使用像素检测结果
|
||||
[2025-12-22 21:50:36.178] [INFO] [流程] [douyin_flow_control.py:find_and_open_fudai_detail:134] find_and_open_fudai_detail:检测到福袋图标 字段_x=509 字段_elapsed_seconds=2.02
|
||||
[2025-12-22 21:50:36.178] [INFO] [流程] [douyin_flow_control.py:find_and_open_fudai_detail:193] find_and_open_fudai_detail:检测到福袋图标并点击 福袋X坐标=509 字段_click_x=509 字段_click_y=403
|
||||
[21:50:37] [截图] ✓ 获取屏幕截图成功
|
||||
[2025-12-22 21:50:40.501] [INFO] [流程] [douyin_flow_control.py:find_and_open_fudai_detail:262] find_and_open_fudai_detail:点击后未检测到福袋详情页,可能误点击 字段_detected_x=509 字段_click_x=509 字段_click_y=403
|
||||
点击返回键
|
||||
[2025-12-22 21:50:41.747] [INFO] [流程] [douyin_flow_control.py:handle_no_fudai_situation:321] handle_no_fudai_situation 字段_x=0 字段_swipe_times=0 当前位置=0 字段_reservations=0
|
||||
[2025-12-22 21:50:42.748] [INFO] [滑动] [douyin_swipe_ops.py:swipe_up_switch_live:34] swipe_up_switch_live:上滑切换直播间 字段_start_x=540 字段_start_y=1700 字段_end_x=540 字段_end_y=700
|
||||
[停止] 正在终止进程...
|
||||
[进程结束] exit_code=1
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model default, mode Agent)**_
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
_**User (2025-12-22 14:45Z)**_
|
||||
|
||||
把这里的没识别到福袋详情的返回换成点击520,505;另外,这里为什么回退失败了:[2025-12-22 21:50:29.814] [INFO] [阶段诊断] [douyin_stage.py:_log_summary:35] 阶段诊断完成(在直播间) 字段_阶段=IN_LIVE_ROOM 字段_原因=识别到在直播间(像素检测),其他阶段未识别 字段_检测方法=像素检测 字段_分数=0.857 字段_总耗时毫秒=938
|
||||
[2025-12-22 21:50:29.814] [INFO] [截图] [douyin_fudai.py:run_once_basic:1684] 截图+阶段诊断 阶段=IN_LIVE_ROOM 识别=识别到在直播间(像素检测),其他阶段未识别
|
||||
[21:50:30] [截图] ✓ 获取屏幕截图成功
|
||||
[21:50:34] [截图] ✓ 获取屏幕截图成功
|
||||
[2025-12-22 21:50:36.089] [INFO] [找福袋图标] [douyin_fudai.py:_shot_and_diagnose:2062] 获取截图
|
||||
[2025-12-22 21:50:36.174] [INFO] [[福袋查找] 图像获取] [douyin_fudai_finder.py:acquire_screenshot:60] 成功 字段_elapsed_ms=2018 字段_size=1080x2400
|
||||
[2025-12-22 21:50:36.177] [INFO] [[福袋查找] 像素检测] [douyin_fudai_finder.py:detect_by_pixel:326] 实际福袋区域命中 字段_elapsed_ms=0.000 字段_x=509 字段_region=(34,363)-(608,451) 字段_optimal_col=176 字段_found_col=475
|
||||
[2025-12-22 21:50:36.177] [INFO] [[福袋查找] 检测完成] [douyin_fudai_finder.py:detect:788] 像素检测命中(模板匹配已关闭) 字段_total_elapsed_ms=0.000 字段_region=实际福袋区域 字段_x=509 字段_method=pixel 字段_note=模板匹配已禁用,直接使用像素检测结果
|
||||
[2025-12-22 21:50:36.178] [INFO] [流程] [douyin_flow_control.py:find_and_open_fudai_detail:134] find_and_open_fudai_detail:检测到福袋图标 字段_x=509 字段_elapsed_seconds=2.02
|
||||
[2025-12-22 21:50:36.178] [INFO] [流程] [douyin_flow_control.py:find_and_open_fudai_detail:193] find_and_open_fudai_detail:检测到福袋图标并点击 福袋X坐标=509 字段_click_x=509 字段_click_y=403
|
||||
[21:50:37] [截图] ✓ 获取屏幕截图成功
|
||||
[2025-12-22 21:50:40.501] [INFO] [流程] [douyin_flow_control.py:find_and_open_fudai_detail:262] find_and_open_fudai_detail:点击后未检测到福袋详情页,可能误点击 字段_detected_x=509 字段_click_x=509 字段_click_y=403
|
||||
点击返回键
|
||||
[2025-12-22 21:50:41.747] [INFO] [流程] [douyin_flow_control.py:handle_no_fudai_situation:321] handle_no_fudai_situation 字段_x=0 字段_swipe_times=0 当前位置=0 字段_reservations=0
|
||||
[2025-12-22 21:50:42.748] [INFO] [滑动] [douyin_swipe_ops.py:swipe_up_switch_live:34] swipe_up_switch_live:上滑切换直播间 字段_start_x=540 字段_start_y=1700 字段_end_x=540 字段_end_y=700
|
||||
[停止] 正在终止进程...
|
||||
[进程结束] exit_code=1
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model default, mode Agent)**_
|
||||
|
||||
<think><details><summary>Thought Process</summary>
|
||||
**Modifying code behavior**
|
||||
|
||||
I need to make some code changes in the repository. There are two specific requests: First, I should replace the logic for "点击后未检测到福袋详情页" so that instead of using the "back key," it clicks specific coordinates (520, 505). I have to locate where that log and code reside. Second, I need to explain why the back functionality failed, possibly due to the stage being stuck in IN_LIVE_ROOM. I’ll inspect code involving handle_no_fudai_situation and swipe_up_switch_live.</details></think>
|
||||
|
||||
---
|
||||
|
||||
我先在项目里找到 `find_and_open_fudai_detail` 和 “点击后未检测到福袋详情页” 这段代码,把原来的“点击返回键”逻辑改成点击坐标 (520, 505),然后顺便看下为什么当前回退逻辑没生效。改完我会简单说明:改了哪一处以及回退失败的原因。
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="search" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "find_and_open_fudai_detail" in "." • 15 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
| File | Content | Line |
|
||||
|------|------|------|
|
||||
| `.\douyin_fudai.py` | `# 如果没有保存的福袋X坐标,使用find_and_open_fudai_detail` | L2486 |
|
||||
| `.\douyin_fudai.py` | `douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)` | L2489 |
|
||||
| `.\douyin_fudai.py` | `opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)` | L2897 |
|
||||
| `.\douyin_fudai_finder.py` | `# 只检测,不点击(避免与 find_and_open_fudai_detail 重复点击)` | L1724 |
|
||||
| `.\douyin_flow_control.py` | `- find_and_open_fudai_detail:通过像素检测福袋图标并点击打开详情` | L9 |
|
||||
| `.\douyin_flow_control.py` | `def find_and_open_fudai_detail(` | L45 |
|
||||
| `.\douyin_flow_control.py` | `"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情",` | L56 |
|
||||
| `.\douyin_flow_control.py` | `"find_and_open_fudai_detail:已在福袋详情页,跳过查找和点击",` | L97 |
|
||||
| `.\douyin_flow_control.py` | `"find_and_open_fudai_detail:已在福袋详情页(通过check_in_fudai_detail),跳过查找和点击",` | L111 |
|
||||
| `.\douyin_flow_control.py` | `"find_and_open_fudai_detail:检测到福袋图标",` | L136 |
|
||||
| `.\douyin_flow_control.py` | `"find_and_open_fudai_detail:未检测到福袋图标,等待后重试",` | L155 |
|
||||
| `.\douyin_flow_control.py` | `"find_and_open_fudai_detail:等待超时,未检测到福袋图标",` | L172 |
|
||||
| `.\douyin_flow_control.py` | `"find_and_open_fudai_detail:检测到福袋图标并点击",` | L195 |
|
||||
| `.\douyin_flow_control.py` | `"find_and_open_fudai_detail:误点击到嘉年华页面,返回",` | L228 |
|
||||
| `.\douyin_flow_control.py` | `"find_and_open_fudai_detail:点击后未检测到福袋详情页,可能误点击",` | L264 |
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="search" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "未检测到福袋详情页" in "." • 2 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
| File | Content | Line |
|
||||
|------|------|------|
|
||||
| `.\douyin_stage.py` | `说明="未检测到福袋详情页,返回直播间",` | L1122 |
|
||||
| `.\douyin_flow_control.py` | `"find_and_open_fudai_detail:点击后未检测到福袋详情页,可能误点击",` | L264 |
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="search" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "handle_no_fudai_situation" in "." • 4 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
| File | Content | Line |
|
||||
|------|------|------|
|
||||
| `.\douyin_fudai.py` | `douyin_flow_control.handle_no_fudai_situation(` | L2910 |
|
||||
| `.\douyin_flow_control.py` | `- handle_no_fudai_situation:在没有福袋时做简单的等待/上滑切换` | L10 |
|
||||
| `.\douyin_flow_control.py` | `def handle_no_fudai_situation(` | L293 |
|
||||
| `.\douyin_flow_control.py` | `"handle_no_fudai_situation",` | L323 |
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="search" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "点击返回键" in "." • 17 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
| File | Content | Line |
|
||||
|------|------|------|
|
||||
| `.\douyin_fudai.py` | `# 识别到"立即领取奖品",保存全屏截图到单独文件夹,点击返回键,切换下一个直播间` | L1978 |
|
||||
| `.\douyin_fudai.py` | `# 点击返回键` | L2005 |
|
||||
| `.\douyin_fudai.py` | `self._log_kv("开奖结果", "点击返回键关闭开奖结果")` | L2007 |
|
||||
| `.\douyin_fudai.py` | `通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。` | L2097 |
|
||||
| `.\douyin_fudai.py` | `# 多次点击返回键,直到到达推荐页面` | L2101 |
|
||||
| `.\douyin_fudai.py` | `# 即使截图失败,也尝试点击返回键` | L2109 |
|
||||
| `.\douyin_fudai.py` | `# 点击返回键` | L2122 |
|
||||
| `.\douyin_fudai.py` | `# 继续尝试点击返回键` | L2139 |
|
||||
| `.\douyin_fudai.py` | `"点击返回键失败但继续",` | L2148 |
|
||||
| `.\douyin_fudai.py` | `# 若子模块未实现,则退化为点击返回键` | L2247 |
|
||||
| `.\douyin_fudai.py` | `# 设置标志:已经关闭了详情,避免后续再次点击返回键` | L2555 |
|
||||
| `.\douyin_fudai.py` | `# 检查 attend_choujiang 是否已经关闭了详情,如果已关闭就不应该再点击返回键` | L2812 |
|
||||
| `.\douyin_fudai_core.py` | `# 设置标志:已经关闭了详情,避免后续再次点击返回键` | L744 |
|
||||
| `.\douyin_fudai_core.py` | `# 实际上可能还在加入成功的页面,需要点击返回键` | L977 |
|
||||
| `.\douyin_fudai_core.py` | `"点击加入粉丝团后显示在直播间(可能误判),尝试点击返回键",` | L980 |
|
||||
| `.\Underlying_Operations.py` | `"""点击返回键"""` | L706 |
|
||||
| `.\Underlying_Operations.py` | `print("点击返回键")` | L708 |
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: douyin_flow_control.py</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: Underlying_Operations.py</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<think><details><summary>Thought Process</summary>
|
||||
**Explaining modifications**
|
||||
|
||||
I need to adjust the code to use fixed coordinates for clicking instead of relying on the back key in the Android system. Updating the coordinates is crucial, but I also need to be mindful of the order in the operations to avoid crashes if anything is missing.
|
||||
|
||||
The back function is failing, but it’s not really a failure; it’s just executing an undesired action by closing the live room. I should clearly explain this in the notes and remember to apply the patch.</details></think>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="unknown" data-tool-name="apply_patch">
|
||||
<details>
|
||||
<summary>Tool use: **apply_patch**</summary>
|
||||
|
||||
|
||||
Parameters:
|
||||
|
||||
```json
|
||||
{
|
||||
"relativeWorkspacePath": "douyin_flow_control.py"
|
||||
}
|
||||
```
|
||||
Additional data:
|
||||
|
||||
```json
|
||||
{
|
||||
"codeblockId": "e6f120eb-5adb-4e1e-94aa-73924256154a"
|
||||
}
|
||||
```
|
||||
Result:
|
||||
|
||||
```json
|
||||
{
|
||||
"diff": {
|
||||
"chunks": [
|
||||
{
|
||||
"diffString": " \n if not is_in_detail:\n- # 如果不在福袋详情页,可能是误点击,返回\n+ # 如果不在福袋详情页,可能是误点击,通过点击固定坐标返回直播间\n try:\n analyser._log_kv(",
|
||||
"oldStart": 258,
|
||||
"newStart": 258,
|
||||
"oldLines": 5,
|
||||
"newLines": 5,
|
||||
"linesRemoved": 1,
|
||||
"linesAdded": 1
|
||||
},
|
||||
{
|
||||
"diffString": " except Exception:\n pass\n- # 返回直播间\n- analyser.operation.click_back(device_id)\n- analyser.operation.delay(1.0)\n+ \n+ # 使用固定坐标 (520, 505) 进行点击,而不是系统返回键\n+ # 根据当前分辨率进行等比例换算(基准分辨率 1080x2400)\n+ try:\n+ back_click_x = int(520 * rx / 1080)\n+ back_click_y = int(505 * ry / 2400)\n+ except Exception:\n+ back_click_x, back_click_y = 520, 505\n+ \n+ try:\n+ analyser.operation.click(device_id, back_click_x, back_click_y)\n+ except Exception:\n+ # 兜底:直接用 analyser.click\n+ try:\n+ analyser.click(back_click_x, back_click_y)\n+ except Exception:\n+ pass\n+ \n+ try:\n+ analyser.operation.delay(1.0)\n+ except Exception:\n+ time.sleep(1.0)\n+ \n # 清除历史位置,避免下次继续误点击\n try:",
|
||||
"oldStart": 269,
|
||||
"newStart": 269,
|
||||
"oldLines": 7,
|
||||
"newLines": 27,
|
||||
"linesRemoved": 3,
|
||||
"linesAdded": 23
|
||||
}
|
||||
],
|
||||
"editor": "EDITOR_AI"
|
||||
},
|
||||
"shouldAutoFixLints": true,
|
||||
"resultForModel": "Success. Updated the following files:\nM douyin_flow_control.py",
|
||||
"contentsAfterEdit": "from __future__ import annotations\n\n\"\"\"\nFlow control main helpers (本地模块化实现,基础版)\n================================================\n\n当前只实现与你\"基础抢福袋、不启用预约\"相关的核心流程:\n- handle_stage_after_diagnosis:记录阶段信息(暂不做复杂跳转)\n- find_and_open_fudai_detail:通过像素检测福袋图标并点击打开详情\n- handle_no_fudai_situation:在没有福袋时做简单的等待/上滑切换\n- filter_fudai_detail:根据 config.json 对福袋进行基础筛选\n\"\"\"\n\nfrom typing import Any, List, Tuple\nimport time\nimport os\n\nfrom douyin_detection import check_have_fudai_with_ready_screenshot\nfrom douyin_fudai_core import should_skip_fudai_by_config\nimport douyin_reservation_logic\nimport path_config\nfrom PIL import Image\n\n\ndef handle_stage_after_diagnosis(\n analyser: Any,\n stage: str,\n seen: str,\n loop_count: int,\n) -> bool:\n \"\"\"记录阶段诊断结果,当前不改变主流程走向。\"\"\"\n try:\n analyser._log_kv(\n \"流程\",\n \"handle_stage_after_diagnosis\",\n stage=stage,\n seen=seen,\n loop_count=loop_count,\n )\n except Exception:\n pass\n return False\n\n\ndef find_and_open_fudai_detail(\n analyser: Any,\n room_pos_ref: List[int],\n) -> bool:\n \"\"\"在当前直播间查找福袋图标并尝试点击打开详情(基础版,不做预约)。\"\"\"\n # 如果正在等待开奖,不应该再次打开福袋详情\n try:\n if getattr(analyser, \"_waiting_for_lottery_result\", False):\n try:\n analyser._log_kv(\n \"流程\",\n \"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情\",\n )\n except Exception:\n pass\n return False\n except Exception:\n pass\n \n device_id = getattr(analyser, \"device_id\", \"\")\n \n # 0. 先检查是否已经在福袋详情页,如果是则直接返回True,避免重复点击\n try:\n import douyin_pixel\n import douyin_detection\n \n # 先刷新截图,确保检测准确\n try:\n analyser.operation.get_screenshot(device_id)\n except Exception:\n pass\n \n # 使用像素检测检查是否在详情页\n try:\n pic_path = path_config.get_screenshot_path()\n if os.path.exists(pic_path):\n pic = Image.open(pic_path)\n pic.load()\n pic_rgb = pic.convert(\"RGB\")\n \n rx = int(getattr(analyser, \"resolution_ratio_x\", 1080) or 1080)\n ry = int(getattr(analyser, \"resolution_ratio_y\", 2400) or 2400)\n y_pianyi = int(getattr(analyser, \"y_pianyi\", 0) or 0)\n \n is_in_detail = douyin_pixel.detect_fudai_detail_page(\n pic_rgb, rx, ry, y_pianyi\n )\n \n if is_in_detail:\n try:\n analyser._log_kv(\n \"流程\",\n \"find_and_open_fudai_detail:已在福袋详情页,跳过查找和点击\",\n )\n except Exception:\n pass\n return True\n except Exception:\n pass\n \n # 使用 check_in_fudai_detail 作为补充检查\n try:\n if douyin_detection.check_in_fudai_detail(analyser):\n try:\n analyser._log_kv(\n \"流程\",\n \"find_and_open_fudai_detail:已在福袋详情页(通过check_in_fudai_detail),跳过查找和点击\",\n )\n except Exception:\n pass\n return True\n except Exception:\n pass\n except Exception:\n pass\n \n # 1. 利用像素检测福袋图标的 X 坐标(1080 基准)\n # 在配置的最大等待时间内重复检测福袋图标\n max_wait_seconds = float(getattr(analyser, \"fudai_icon_max_wait_seconds\", 5.0) or 5.0)\n retry_delay_seconds = float(getattr(analyser, \"fudai_icon_retry_delay_seconds\", 0.6) or 0.6)\n \n start_time = time.time()\n x = False\n \n while (time.time() - start_time) < max_wait_seconds:\n x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False)\n if x:\n # 找到福袋图标,跳出循环\n try:\n analyser._log_kv(\n \"流程\",\n \"find_and_open_fudai_detail:检测到福袋图标\",\n x=int(x or 0),\n elapsedLine truncated
|
||||
}
|
||||
```
|
||||
User decision: **accepted**
|
||||
|
||||
Status: **completed**
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
已把“点击后未检测到福袋详情页”的处理从按返回键改成点击坐标 (520,505),并加了分辨率自适应和兜底逻辑。接下来简单解释一下原来你看到的那次“回退失败”的原因。### 1. 已按你说的改动逻辑
|
||||
|
||||
现在在 `douyin_flow_control.py` 里,这段逻辑:
|
||||
|
||||
- **原来**:
|
||||
当 `find_and_open_fudai_detail` 点击福袋后,检测到“**点击后未检测到福袋详情页,可能误点击**”时,会执行:
|
||||
|
||||
```python
|
||||
analyser.operation.click_back(device_id)
|
||||
analyser.operation.delay(1.0)
|
||||
```
|
||||
|
||||
- **现在**(已改好):
|
||||
改成不再按系统返回键,而是点击坐标 **(520, 505)**(并做了分辨率适配):
|
||||
|
||||
```python
|
||||
# 基准分辨率 1080x2400 下的 (520, 505),按当前分辨率等比换算
|
||||
back_click_x = int(520 * rx / 1080)
|
||||
back_click_y = int(505 * ry / 2400)
|
||||
|
||||
analyser.operation.click(device_id, back_click_x, back_click_y)
|
||||
# 失败的话兜底用 analyser.click(...)
|
||||
```
|
||||
|
||||
也就是说:**“点击后未检测到福袋详情页,可能误点击” 的情况下,现在会去点 (520,505),而不是再发 keyevent 4。**
|
||||
|
||||
---
|
||||
|
||||
### 2. 为啥你那次“回退失败”
|
||||
|
||||
从你给的日志看:
|
||||
|
||||
1. 检测到福袋图标并点击:
|
||||
`click_x=509, click_y=403`
|
||||
2. 点击后检测:
|
||||
`find_and_open_fudai_detail:点击后未检测到福袋详情页,可能误点击`
|
||||
3. 然后内部调用了 `analyser.operation.click_back(device_id)`,这是在 `Underlying_Operations.click_back` 里直接发 `adb shell input keyevent 4` 的系统返回键。
|
||||
4. 接着马上进入了 `handle_no_fudai_situation`,`x=0`,然后执行了 `swipe_up_switch_live:上滑切换直播间`。
|
||||
|
||||
结合这一串:
|
||||
|
||||
- **系统返回键确实发出去了**(所以日志里能看到“点击返回键”)。
|
||||
- 但在抖音里,**系统返回键很可能把你当前直播间直接退掉/切换页面**,而不是仅仅把“误点的那个浮层”关掉。
|
||||
- 回到主流程时,阶段诊断 + 福袋检测的结果是:**当前画面被认为“没有福袋”**(`x=0`),于是 `handle_no_fudai_situation` 就按“无福袋”策略,**上滑切换下一个直播间**。
|
||||
|
||||
所以你感觉是“回退失败了”,本质上是:
|
||||
|
||||
> **回退键起作用了,但它把你带离了原本的直播福袋场景,导致后续逻辑认为当前没有福袋 → 触发上滑换间。**
|
||||
|
||||
因此改成你现在要求的 **点击 (520,505)**,就是避免再用系统返回键,改为点击你实际观察到的能“正确回到直播间位置”的 UI 区域,更贴合抖音的真实交互。
|
||||
|
||||
---
|
||||
|
||||
@@ -118,3 +118,23 @@ python cleanup_unused_files.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -133,3 +133,19 @@ except Exception as e:
|
||||
**修复完成时间**: 2025-12-22
|
||||
**代码质量评分**: 7.5/10 → 8.5/10 ⬆️
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -336,3 +336,19 @@ self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标
|
||||
**报告生成时间**: 2025-12-22
|
||||
**检查工具版本**: pylint 4.0.4, Python 3.12.4
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -216,3 +216,23 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -181,6 +181,26 @@ python check_dependencies.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -160,6 +160,26 @@ douyin_guaji
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -101,6 +101,26 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -319,3 +319,23 @@ douyin_fudai_finder.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# GUI参数冲突分析报告
|
||||
|
||||
## 当前配置参数
|
||||
|
||||
根据 `config.json` 文件:
|
||||
|
||||
### 倒计时相关参数
|
||||
- `skip_if_countdown_gt_seconds`: **600秒** - 倒计时大于此值时不参与
|
||||
- `skip_if_countdown_lt_seconds`: **5秒** - 倒计时小于此值时不参与
|
||||
- `high_value_fudai_join_ahead_seconds`: **90秒** - 预约参与阈值(剩余秒数在此值内立即参与)
|
||||
|
||||
### 价值相关参数
|
||||
- `min_prize_value_yuan`: **200元** - 最小价值阈值
|
||||
- `high_value_fudai_threshold_yuan`: **500元** - 高价值阈值
|
||||
|
||||
### 高价值预约相关
|
||||
- `high_value_fudai_enabled`: **true** - 已启用高价值预约
|
||||
- `high_value_fudai_max_reservations`: **3** - 最多记录3个预约
|
||||
|
||||
## 参数逻辑关系分析
|
||||
|
||||
### ✅ 正常情况
|
||||
1. **倒计时范围**: 5秒 < 90秒 < 600秒 ✓
|
||||
- 剩余秒数 ≤ 5秒:被过滤(太短)
|
||||
- 剩余秒数 5-90秒:如果价值≥500元,立即参与
|
||||
- 剩余秒数 90-600秒:如果价值≥500元,记录预约
|
||||
- 剩余秒数 > 600秒:被过滤(太长)
|
||||
|
||||
2. **价值阈值**: 200元 < 500元 ✓
|
||||
- 价值 < 200元:被过滤
|
||||
- 价值 200-500元:普通参与(如果倒计时在范围内)
|
||||
- 价值 ≥ 500元:高价值处理(立即参与或预约)
|
||||
|
||||
### ⚠️ 潜在问题
|
||||
|
||||
#### 问题1:倒计时过滤优先级过高
|
||||
**场景**: 剩余秒数 = 660秒,价值 = 5999元
|
||||
|
||||
**当前行为**:
|
||||
1. `should_skip_fudai_by_config` 检查:660秒 > 600秒 → 返回 `skip=True, reason="countdown_gt_600"`
|
||||
2. `basic_join_decision` 特殊处理:价值5999元 ≥ 500元 → 检查剩余秒数
|
||||
3. 剩余秒数660秒 > 90秒 → 记录预约
|
||||
|
||||
**问题**: 虽然最终会记录预约,但逻辑上应该先检查是否在预约参与阈值内,而不是先被倒计时过滤筛掉。
|
||||
|
||||
**建议**: 在 `should_skip_fudai_by_config` 中,如果价值达到高价值阈值,应该使用 `high_value_fudai_join_ahead_seconds` 而不是 `skip_if_countdown_gt_seconds` 来判断。
|
||||
|
||||
#### 问题2:预约参与阈值与倒计时过滤的关系不明确
|
||||
**场景**: 剩余秒数 = 100秒,价值 = 600元
|
||||
|
||||
**当前行为**:
|
||||
1. `should_skip_fudai_by_config` 检查:100秒 < 600秒 → 通过过滤
|
||||
2. `basic_join_decision` 检查:价值600元 ≥ 500元 → 高价值处理
|
||||
3. 剩余秒数100秒 > 90秒 → 记录预约
|
||||
|
||||
**问题**: 剩余秒数100秒在600秒阈值内,应该可以参与,但因为大于90秒而被记录为预约。这个逻辑是正确的,但可能不符合用户期望。
|
||||
|
||||
**建议**: 如果用户希望剩余秒数在某个范围内(如90-600秒)时,高价值福袋也应该立即参与,需要调整 `high_value_fudai_join_ahead_seconds` 的值。
|
||||
|
||||
## 建议的修复方案
|
||||
|
||||
### 方案1:调整 `should_skip_fudai_by_config` 逻辑
|
||||
在倒计时过滤时,如果价值达到高价值阈值,应该:
|
||||
- 使用 `high_value_fudai_join_ahead_seconds` 来判断是否过滤
|
||||
- 而不是使用 `skip_if_countdown_gt_seconds`
|
||||
|
||||
### 方案2:调整参数值
|
||||
如果用户希望高价值福袋在剩余秒数 ≤ 600秒时都立即参与,可以:
|
||||
- 将 `high_value_fudai_join_ahead_seconds` 设置为 600秒
|
||||
- 或者将 `skip_if_countdown_gt_seconds` 设置为更大的值(如900秒)
|
||||
|
||||
### 方案3:明确参数说明
|
||||
在GUI中添加更清晰的参数说明:
|
||||
- `skip_if_countdown_gt_seconds`: 普通福袋的倒计时上限(超过此值不参与)
|
||||
- `high_value_fudai_join_ahead_seconds`: 高价值福袋的预约参与阈值(剩余秒数在此值内立即参与,超过此值记录预约)
|
||||
|
||||
## 当前配置的合理性
|
||||
|
||||
✅ **当前配置是合理的**,但需要注意:
|
||||
1. 高价值福袋(≥500元)在剩余秒数 ≤ 90秒时会立即参与
|
||||
2. 高价值福袋在剩余秒数 90-600秒之间会记录预约
|
||||
3. 高价值福袋在剩余秒数 > 600秒时会被过滤(但代码中有特殊处理,会记录预约)
|
||||
|
||||
## 用户遇到的问题
|
||||
|
||||
根据日志,剩余秒数 = 660秒,价值 = 5999元:
|
||||
- 660秒 > 600秒 → 被倒计时过滤
|
||||
- 但价值5999元 ≥ 500元 → 触发特殊处理
|
||||
- 660秒 > 90秒 → 记录预约
|
||||
|
||||
**这是符合当前逻辑的**,但如果用户希望剩余秒数在90秒内时立即参与,那么当前660秒的情况应该记录预约,这是正确的。
|
||||
|
||||
**如果用户希望剩余秒数在600秒内时都立即参与**,需要将 `high_value_fudai_join_ahead_seconds` 设置为 600秒。
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
# GUI日志功能修复总结
|
||||
|
||||
## 修复内容
|
||||
|
||||
### 1. 添加线程安全的日志文件写入功能
|
||||
|
||||
在 `gui_app.py` 中添加了 `ThreadSafeLogWriter` 类,实现以下功能:
|
||||
|
||||
- **线程安全**:使用 `threading.Lock()` 确保多线程环境下日志写入的安全性
|
||||
- **自动文件管理**:支持按日期分割日志文件(如 `unified_2025-12-22.log`)
|
||||
- **配置读取**:从 `config.json` 读取日志配置(路径、启用状态等)
|
||||
- **异常处理**:完善的异常处理机制,避免日志写入失败导致应用崩溃
|
||||
- **缓冲区刷新**:每次写入后立即调用 `flush()`,确保日志及时写入磁盘
|
||||
|
||||
### 2. 日志格式
|
||||
|
||||
- **自动时间戳**:如果日志行不包含时间戳,自动添加格式化的时间戳
|
||||
- **格式规范**:`YYYY-MM-DD HH:MM:SS.mmm - [GUI] - 日志内容`
|
||||
- **编码支持**:使用 `utf-8-sig` 编码(带BOM),避免Windows下中文乱码
|
||||
|
||||
### 3. 集成到GUI应用
|
||||
|
||||
- 在 `on_line()` 函数中集成日志写入功能
|
||||
- 日志同时显示在GUI界面和写入文件
|
||||
- 文件写入失败不影响GUI显示
|
||||
|
||||
## 代码位置
|
||||
|
||||
**文件**:`gui_app.py`
|
||||
|
||||
**关键代码**:
|
||||
- 第52-149行:`ThreadSafeLogWriter` 类定义
|
||||
- 第152行:创建日志写入器实例
|
||||
- 第154-161行:`on_line()` 函数集成日志写入
|
||||
|
||||
## 测试验证
|
||||
|
||||
运行 `test_gui_logging.py` 进行测试:
|
||||
|
||||
```bash
|
||||
python test_gui_logging.py
|
||||
```
|
||||
|
||||
测试包括:
|
||||
1. **基本功能测试**:验证日志文件创建和写入
|
||||
2. **线程安全测试**:5个线程同时写入,验证无冲突
|
||||
3. **文件完整性测试**:验证日志文件格式和内容
|
||||
|
||||
所有测试均通过 ✓
|
||||
|
||||
## 日志文件位置
|
||||
|
||||
默认位置:`logs/unified_YYYY-MM-DD.log`
|
||||
|
||||
可通过 `config.json` 中的 `log_unified_path` 配置自定义路径。
|
||||
|
||||
## 配置选项
|
||||
|
||||
在 `config.json` 中可以配置:
|
||||
|
||||
```json
|
||||
{
|
||||
"log_unified_enabled": true,
|
||||
"log_unified_path": "logs/unified.log",
|
||||
"logging": {
|
||||
"use_dated_logs": true,
|
||||
"keep_days": 30
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 使用说明
|
||||
|
||||
1. **启动GUI应用**:日志会自动写入文件
|
||||
2. **查看日志**:日志文件位于 `logs/` 目录下
|
||||
3. **日志格式**:每条日志包含时间戳、级别和内容
|
||||
4. **线程安全**:多线程环境下日志写入安全可靠
|
||||
|
||||
## 注意事项
|
||||
|
||||
- 日志文件使用追加模式(`a`),不会覆盖已有内容
|
||||
- 每次写入后立即刷新缓冲区,确保日志及时持久化
|
||||
- 如果日志文件写入失败,会在控制台输出警告,但不会影响GUI运行
|
||||
- 日志目录不存在时会自动创建
|
||||
|
||||
## 真机测试建议
|
||||
|
||||
1. 启动GUI应用
|
||||
2. 运行核心功能至少30秒
|
||||
3. 检查 `logs/unified_YYYY-MM-DD.log` 文件
|
||||
4. 验证日志内容包含时间戳和正确的格式
|
||||
5. 使用 `adb logcat` 监控系统日志,确认无相关错误
|
||||
|
||||
## 修复完成时间
|
||||
|
||||
2025-12-22
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
# OCR性能分析报告
|
||||
|
||||
## 问题描述
|
||||
|
||||
根据日志分析,福袋详情的OCR识别耗时较长,通常在3-4秒左右。
|
||||
|
||||
## OCR耗时统计(从日志中提取)
|
||||
|
||||
### 阶段诊断中的OCR(检测"邀你抢红包")
|
||||
- 13:14:40.299: **3270ms** (3.27秒)
|
||||
- 13:16:24.091: **3596ms** (3.6秒)
|
||||
- 13:16:37.278: **1116ms** (1.1秒) - 较快
|
||||
- 13:16:55.976: **3163ms** (3.16秒)
|
||||
- 13:19:44.197: **3457ms** (3.46秒)
|
||||
- 13:20:10.957: **1176ms** (1.18秒) - 较快
|
||||
- 13:20:49.675: **3073ms** (3.07秒)
|
||||
- 13:25:10.525: **3804ms** (3.8秒)
|
||||
- 13:25:35.351: **3258ms** (3.26秒)
|
||||
- 13:26:01.553: **3185ms** (3.19秒)
|
||||
- 13:26:46.555: **3115ms** (3.12秒)
|
||||
- 13:27:56.150: **3090ms** (3.09秒)
|
||||
- 13:28:18.987: **742ms** (0.74秒) - 最快
|
||||
|
||||
**平均耗时**: 约 **2.8-3.5秒**
|
||||
|
||||
### 福袋详情读取中的OCR
|
||||
|
||||
从代码分析,`get_fudai_contain`函数中会执行以下OCR操作:
|
||||
|
||||
1. **任务列表OCR**(第230行):识别任务列表区域,检测"观看X分钟"任务
|
||||
2. **并行OCR**(第308-318行):
|
||||
- 福袋内容OCR
|
||||
- 福袋倒计时OCR
|
||||
- 福袋价值OCR
|
||||
- 任务数量检测(像素检测,非OCR)
|
||||
|
||||
3. **倒计时分割OCR**(第117-121行):如果倒计时识别失败,会分割成分钟和秒分别OCR
|
||||
|
||||
**总OCR调用次数**: 最多4次(任务列表 + 内容 + 倒计时 + 价值)
|
||||
|
||||
## 耗时原因分析
|
||||
|
||||
### 1. OCR引擎本身较慢
|
||||
- 使用EasyOCR或PaddleOCR,CPU模式
|
||||
- 没有GPU加速(`gpu=False`)
|
||||
- OCR模型加载和推理需要时间
|
||||
|
||||
### 2. 图像预处理
|
||||
- 每次OCR前需要裁剪图像(`cut_pic`)
|
||||
- 图像保存和读取可能耗时
|
||||
|
||||
### 3. 多次OCR调用
|
||||
- 福袋详情读取需要4次OCR调用
|
||||
- 虽然使用了并行执行(`ThreadPoolExecutor`),但每次OCR本身耗时较长
|
||||
|
||||
### 4. OCR初始化延迟
|
||||
- 首次OCR调用可能需要初始化模型
|
||||
- 如果OCR未初始化,会触发延迟初始化
|
||||
|
||||
## 优化建议
|
||||
|
||||
### 1. 启用GPU加速(如果可用)
|
||||
```python
|
||||
# 在 Underlying_Operations.py 中
|
||||
self.ocr = easyocr.Reader(
|
||||
["ch_sim", "en"],
|
||||
gpu=True, # 如果GPU可用
|
||||
verbose=False
|
||||
)
|
||||
```
|
||||
|
||||
### 2. 减少OCR调用次数
|
||||
- 如果任务列表OCR检测到"观看X分钟"任务,可以提前返回,避免后续OCR
|
||||
- 优化倒计时识别,减少分割OCR的使用
|
||||
|
||||
### 3. 优化图像预处理
|
||||
- 缓存裁剪后的图像,避免重复裁剪
|
||||
- 优化图像保存路径,使用内存缓存
|
||||
|
||||
### 4. 使用更快的OCR引擎
|
||||
- 考虑使用Tesseract OCR(如果可用)
|
||||
- 或者使用在线OCR API(如果网络条件允许)
|
||||
|
||||
### 5. 并行优化
|
||||
- 当前已经使用了并行执行,但可以考虑:
|
||||
- 减少OCR区域大小
|
||||
- 使用更快的OCR模式(如果支持)
|
||||
|
||||
### 6. 缓存OCR结果
|
||||
- 对于相同的图像区域,可以缓存OCR结果
|
||||
- 避免重复识别相同内容
|
||||
|
||||
## 当前性能
|
||||
|
||||
根据日志分析:
|
||||
- **单次OCR耗时**: 约3-4秒(CPU模式)
|
||||
- **福袋详情总OCR耗时**: 约3-4秒(并行执行)
|
||||
- **阶段诊断OCR耗时**: 约3-4秒
|
||||
|
||||
## 预期优化效果
|
||||
|
||||
如果启用GPU加速:
|
||||
- **单次OCR耗时**: 可能降至0.5-1秒
|
||||
- **总耗时**: 可能降至1-2秒
|
||||
|
||||
如果优化OCR调用次数:
|
||||
- **减少1次OCR调用**: 节省约3-4秒
|
||||
- **提前返回**: 可以节省后续OCR调用
|
||||
|
||||
## 建议的优化优先级
|
||||
|
||||
1. **高优先级**:
|
||||
- 检查是否有GPU可用,启用GPU加速
|
||||
- 优化任务列表OCR,提前返回避免后续OCR
|
||||
|
||||
2. **中优先级**:
|
||||
- 减少OCR区域大小
|
||||
- 优化图像预处理流程
|
||||
|
||||
3. **低优先级**:
|
||||
- 缓存OCR结果
|
||||
- 使用更快的OCR引擎
|
||||
|
||||
## 代码位置
|
||||
|
||||
- OCR实现:`Underlying_Operations.py` - `analyse_pic_word`方法
|
||||
- OCR初始化:`Underlying_Operations.py` - `__init__`和`_ensure_ocr`方法
|
||||
- 福袋详情OCR调用:`douyin_fudai_core.py` - `get_fudai_contain`函数
|
||||
- 阶段诊断OCR调用:`douyin_stage.py` - 阶段诊断流程
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
基于 ADB + OCR + 像素检测 + 模板匹配技术
|
||||
|
||||
[](version.py)
|
||||
[](version.py)
|
||||
[](https://www.python.org/)
|
||||
[](https://www.microsoft.com/windows)
|
||||
|
||||
@@ -27,74 +27,145 @@
|
||||
- [代码结构](#代码结构)
|
||||
- [故障排查](#故障排查)
|
||||
- [开发指南](#开发指南)
|
||||
- [常见问题 FAQ](#常见问题-faq)
|
||||
- [版本历史](#版本历史)
|
||||
- [免责声明](#免责声明)
|
||||
### V3.2.0
|
||||
|
||||
- ✨ 新增:高价值福袋预约功能
|
||||
- ✨ 新增:高价值直播间回访功能
|
||||
- 🔧 优化:推荐页养号逻辑优化
|
||||
|
||||
### V3.1.0
|
||||
|
||||
- ✨ 新增:推荐页养号功能
|
||||
- 🔧 优化:OCR 识别准确率提升
|
||||
|
||||
### V3.0.0
|
||||
|
||||
- 🔄 重大更新:引入 PaddleOCR 替换 pytesseract
|
||||
- ✨ 新增:自动分辨率适配
|
||||
- 🐛 修复:修复大量已知问题
|
||||
|
||||
### V2.x
|
||||
|
||||
- 多分辨率支持
|
||||
- 稳定性提升
|
||||
- 各种 bug 修复
|
||||
|
||||
### V1.x
|
||||
|
||||
- 基础功能实现
|
||||
- 福袋检测和参与
|
||||
- 自动领奖
|
||||
|
||||
---
|
||||
|
||||
## 📖 项目简介
|
||||
## ⚠️ 免责声明
|
||||
|
||||
**抖音福袋挂机脚本(douyin_guaji)** 是一个专为抖音直播间设计的自动化工具,通过 ADB(Android Debug Bridge)连接安卓设备,结合 OCR(光学字符识别)、像素检测和模板匹配技术,实现全自动的福袋寻找、筛选、参与和领奖流程。
|
||||
1. **本工具仅供学习交流使用**,请勿用于商业用途。
|
||||
|
||||
### 主要特点
|
||||
2. **使用本工具产生的任何后果由使用者自行承担**,包括但不限于:
|
||||
- 账号被封禁或限制
|
||||
- 数据丢失或泄露
|
||||
- 设备损坏
|
||||
- 其他法律风险
|
||||
|
||||
- ✅ **全自动化**:无需人工干预,24小时持续运行
|
||||
- ✅ **智能筛选**:根据价值、参与人数、关键词等多维度条件筛选福袋
|
||||
- ✅ **高价值预约**:自动预约高价值福袋,提前参与抽奖
|
||||
- ✅ **风控优化**:支持推荐页养号行为,降低账号风险
|
||||
- ✅ **多界面支持**:提供桌面 GUI、Web GUI 和命令行三种使用方式
|
||||
- ✅ **模块化设计**:代码结构清晰,易于维护和扩展
|
||||
- ✅ **详细日志**:完整的运行日志记录,便于问题排查
|
||||
- ✅ **性能优化**:并行OCR执行,识别速度提升约50%
|
||||
- ✅ **代码质量**:通过 Pylance 类型检查,代码健壮性高
|
||||
3. **请遵守抖音平台相关规则**,不要使用本工具进行违法违规操作。
|
||||
|
||||
### 适用场景
|
||||
4. **作者不对使用本工具造成的任何损失负责**。
|
||||
|
||||
- 需要长时间挂机抢福袋的用户
|
||||
- 希望自动筛选高价值福袋的用户
|
||||
- 需要批量管理多个账号的用户
|
||||
- 希望降低人工操作频率的用户
|
||||
5. **使用本工具即表示您已阅读并同意本免责声明**。
|
||||
|
||||
---
|
||||
|
||||
## ✨ 核心功能
|
||||
## 📞 支持与反馈
|
||||
|
||||
### 1. 自动寻找福袋
|
||||
如有问题或建议,请优先在仓库中提交 Issue,或按照下列步骤提供反馈:
|
||||
|
||||
- 在直播间内自动检测福袋图标
|
||||
- 支持多种分辨率设备(自动适配)
|
||||
- 可配置检测重试次数和等待时间
|
||||
- 智能处理福袋图标加载延迟
|
||||
- **标题(必填)**:一句话概述问题或建议
|
||||
- **环境信息(必填)**:操作系统、Python 版本、ADB 版本、设备型号
|
||||
- **复现步骤(必填)**:最小复现步骤(命令、点击顺序等)
|
||||
- **日志与截图(可选)**:运行日志(logs/ 下相关文件)、截图或录屏
|
||||
- **期望行为与实际行为(可选)**:描述期望结果与实际观察到的结果
|
||||
|
||||
### 2. 智能筛选系统
|
||||
如果你愿意,可以在 Issue 中附上 `--verbose` 模式输出或 `logs/` 中最新的日志文件,这有助于定位问题。
|
||||
|
||||
**价值筛选**
|
||||
- 设置最低奖品价值阈值
|
||||
- 自动跳过低价值福袋
|
||||
---
|
||||
|
||||
**参与人数筛选**
|
||||
- 设置参与人数范围(最小/最大)
|
||||
- 避免竞争过于激烈的福袋
|
||||
## 🤝 贡献(Contributing)
|
||||
|
||||
**关键词筛选**
|
||||
- 支持"想要"关键词列表(白名单)
|
||||
- 支持"不想要"关键词列表(黑名单)
|
||||
- 自动匹配福袋内容描述
|
||||
欢迎 PR、Issue、或参与讨论。贡献流程建议:
|
||||
|
||||
**倒计时筛选**
|
||||
- 跳过倒计时过短的福袋(避免来不及参与)
|
||||
- 跳过倒计时过长的福袋(切换到其他直播间)
|
||||
1. Fork 本仓库并在本地新建分支:`git checkout -b fix/your-change`
|
||||
2. 在分支上实现改动,并尽量保持风格一致
|
||||
3. 运行现有测试(如适用)并确保无新错误
|
||||
4. 提交 PR,标题使用“类型:简短描述”(例如 `fix: 修复 OCR 识别问题`)
|
||||
5. 在 PR 描述中说明变更细节、测试方法和影响范围
|
||||
|
||||
### 3. 自动参与抽奖
|
||||
代码风格与规范:保持现有代码风格,使用清晰的函数和变量名,避免大面积重构而不提前沟通。
|
||||
|
||||
- 自动点击参与按钮
|
||||
- 处理"参与成功"、"还需看播"等提示
|
||||
- 自动处理粉丝团门槛(可选)
|
||||
- 处理各种弹窗和异常情况
|
||||
---
|
||||
|
||||
### 4. 自动领奖系统
|
||||
## 🐞 报告问题模板(建议)
|
||||
|
||||
Issue 模板参考:
|
||||
|
||||
```
|
||||
标题:简短描述
|
||||
|
||||
环境:
|
||||
- 操作系统:Windows 10/11
|
||||
- Python:3.10
|
||||
- ADB:platform-tools 版本
|
||||
- 设备型号:例如 Mi 10
|
||||
|
||||
复现步骤:
|
||||
1. 启动脚本:`python run_cli.py --...`
|
||||
2. 执行到 XX 步骤
|
||||
3. 观察到异常
|
||||
|
||||
日志:请粘贴相关 logs/ 下的日志片段或上传文件
|
||||
|
||||
截图/录屏:如有请附上
|
||||
|
||||
期望:期望看到的行为
|
||||
实际:实际看到的行为
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ 测试
|
||||
|
||||
本仓库包含若干测试文件(`tests/` 目录),可使用以下方式运行:
|
||||
|
||||
```bash
|
||||
# 运行所有测试
|
||||
pytest -q
|
||||
|
||||
# 运行单个测试文件
|
||||
pytest tests/unit/test_example.py::test_some_behavior -q
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📜 许可(License)
|
||||
|
||||
本仓库当前未在根目录添加明确的开源许可文件(LICENSE)。如果你希望对外发布或在项目中使用本代码,请先在 Issue 中联系作者或为仓库添加合适的许可证(例如 MIT / Apache-2.0 / GPL-3.0)。
|
||||
|
||||
---
|
||||
|
||||
## 联系方式
|
||||
|
||||
- 提交 Issue:仓库 Issues 页面
|
||||
- Pull Request:提交 PR 以贡献代码
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**感谢使用抖音福袋挂机脚本!**
|
||||
|
||||
如果这个项目对你有帮助,欢迎 Star ⭐ 并提出你的建议或贡献代码。
|
||||
|
||||
</div>
|
||||
- 自动识别开奖结果(中奖/未中奖)
|
||||
- 中奖后自动领取奖品
|
||||
- 处理订单确认页面
|
||||
@@ -140,22 +211,9 @@
|
||||
|
||||
- 支持上划切换直播间
|
||||
- 可配置切换策略(倒计时阈值)
|
||||
- 支持切换N次后回到第一个直播间(循环模式,向上回退)
|
||||
- 支持切换N次后回到第一个直播间(循环模式)
|
||||
- 智能处理直播结束、网络异常等情况
|
||||
|
||||
### 11. 手动操作功能
|
||||
|
||||
- **手动发送返回键**:在GUI界面提供"发送返回键"按钮,可随时手动发送返回键到设备
|
||||
- 适用于需要手动干预的场景
|
||||
- 支持自动设备选择或手动指定设备
|
||||
|
||||
### 12. 智能超时保护
|
||||
|
||||
- **30分钟超时机制**:如果30分钟没有成功参与福袋,自动返回推荐页面并重新进入直播间
|
||||
- 防止长时间卡在某个直播间无法参与福袋
|
||||
- 自动重置运行状态,确保脚本持续有效运行
|
||||
- 记录最后一次成功参与的时间,智能判断是否需要重置
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 技术架构
|
||||
@@ -185,13 +243,11 @@
|
||||
- 使用 PaddleOCR 识别文字内容
|
||||
- 用于识别福袋内容、倒计时、价值等
|
||||
- 支持中英文识别
|
||||
- **并行执行优化**:多个 OCR 操作并行执行,显著提升识别速度
|
||||
|
||||
4. **阶段诊断**
|
||||
- 综合使用像素检测、模板匹配和OCR
|
||||
- 判断当前页面状态(直播间、推荐页、详情页等)
|
||||
- 支持并行检测,提高效率
|
||||
- **并行OCR优化**:倒计时分割识别、模式0+模式1并行执行等
|
||||
|
||||
### 架构设计
|
||||
|
||||
@@ -358,11 +414,7 @@ adb devices
|
||||
- 在右侧日志窗口查看运行状态
|
||||
- 点击"截图"按钮可查看实时截图
|
||||
|
||||
4. **手动操作**
|
||||
- 点击"发送返回键"按钮可手动发送返回键到设备
|
||||
- 适用于需要手动干预的场景
|
||||
|
||||
5. **停止运行**
|
||||
4. **停止运行**
|
||||
- 点击"停止"按钮
|
||||
- 或点击"强制停止"按钮(如果普通停止无效)
|
||||
|
||||
@@ -435,14 +487,13 @@ python run_cli.py \
|
||||
| `wait_minutes` | integer | `5` | 倒计时超过该分钟数时切换直播间(仅在 needswitch=true 时生效) |
|
||||
| `skip_if_countdown_lt_seconds` | integer | `5` | 倒计时小于该秒数时不参与(高价值福袋可预约) |
|
||||
| `reset_after_swipes_enabled` | boolean | `true` | 是否启用"切换N次后回到第一个直播间"功能 |
|
||||
| `reset_after_swipes` | integer | `30` | 切换直播间达到该次数后,向上回退到第一个直播间 |
|
||||
| `reset_after_swipes` | integer | `30` | 切换直播间达到该次数后,下滑回退到第一个直播间 |
|
||||
| `fudai_find_max_attempts` | integer | `10` | 找福袋图标的最大尝试次数 |
|
||||
| `fudai_icon_retry_delay_seconds` | float | `0.6` | 找福袋图标的重试间隔(秒) |
|
||||
| `fudai_icon_max_wait_seconds` | float | `5.0` | 找福袋图标的最大等待时间(秒),实际识别常见 4-6 秒 |
|
||||
| `live_room_match_threshold` | float | `0.8` | 直播间检测阈值(0.0~1.0),值越高越严格,建议≥0.8 |
|
||||
| `stage_diag_max_time` | float | `15.0` | 阶段诊断的最大耗时(秒) |
|
||||
| `stage_diag_max_step_time` | float | `4.0` | 阶段诊断单步的最大耗时(秒) |
|
||||
| `no_attend_timeout_minutes` | float | `30.0` | 超时时间(分钟),如果该时间内没有成功参与福袋,则返回推荐页面重新进入直播间 |
|
||||
|
||||
### 福袋筛选设置
|
||||
|
||||
@@ -591,11 +642,6 @@ python run_cli.py \
|
||||
- 关注是否出现人机验证
|
||||
- 如频繁出现验证,降低运行频率或启用养号
|
||||
|
||||
5. **利用超时保护功能**
|
||||
- 30分钟超时功能会自动重置运行状态
|
||||
- 如果发现长时间没有参与福袋,脚本会自动返回推荐页面
|
||||
- 无需手动干预,脚本会自动恢复运行
|
||||
|
||||
### 高级使用技巧
|
||||
|
||||
1. **多账号管理**
|
||||
@@ -612,10 +658,6 @@ python run_cli.py \
|
||||
- 配置端口转发,实现外网访问
|
||||
|
||||
4. **性能优化**
|
||||
- **并行OCR执行**(V3.3.2+):多个OCR操作并行执行,识别速度提升约50%
|
||||
- 福袋内容、倒计时、价值识别并行执行
|
||||
- 倒计时分割识别(分钟+秒)并行执行
|
||||
- OCR模式0+模式1并行执行(启用时)
|
||||
- 调整阶段诊断时间参数,平衡速度和准确性
|
||||
- 优化 OCR 缓存设置,减少重复识别
|
||||
- 根据设备性能调整截图频率
|
||||
@@ -694,12 +736,10 @@ python run_cli.py \
|
||||
- 处理各种弹窗干扰
|
||||
|
||||
3. **信息提取**
|
||||
- **并行OCR识别**:内容、倒计时、价值、任务数量检测并行执行
|
||||
- OCR 识别福袋内容区域
|
||||
- OCR 识别倒计时区域(支持分割识别)
|
||||
- OCR 识别倒计时区域
|
||||
- OCR 识别价值区域
|
||||
- OCR 识别参与人数区域
|
||||
- 任务数量检测(像素检测)
|
||||
|
||||
4. **信息解析**
|
||||
- 解析倒计时文本(支持多种格式)
|
||||
@@ -973,11 +1013,10 @@ python run_cli.py \
|
||||
**问题**:OCR 识别速度慢
|
||||
|
||||
**解决方案**:
|
||||
1. **已优化**:V3.3.2+ 版本已实现并行OCR,识别速度显著提升
|
||||
2. 减少 OCR 识别频率
|
||||
3. 启用 OCR 缓存(如果支持)
|
||||
4. 优化识别区域大小
|
||||
5. 使用 GPU 版本的 PaddleOCR(如果有 GPU)
|
||||
1. 减少 OCR 识别频率
|
||||
2. 启用 OCR 缓存(如果支持)
|
||||
3. 优化识别区域大小
|
||||
4. 使用 GPU 版本的 PaddleOCR(如果有 GPU)
|
||||
|
||||
### 运行异常问题
|
||||
|
||||
@@ -1206,51 +1245,14 @@ python run_cli.py \
|
||||
|
||||
**A**: 目前不支持 iOS 设备,因为 iOS 需要越狱才能使用类似 ADB 的工具。
|
||||
|
||||
### Q13: 30分钟超时功能如何工作?
|
||||
|
||||
**A**:
|
||||
1. 脚本会记录最后一次成功参与福袋的时间
|
||||
2. 如果30分钟内没有成功参与福袋,会自动返回推荐页面
|
||||
3. 然后重新进入直播间,重置运行状态
|
||||
4. 这样可以防止长时间卡在某个直播间无法参与福袋
|
||||
|
||||
### Q14: 如何使用手动发送返回键功能?
|
||||
|
||||
**A**:
|
||||
1. 在GUI界面找到"发送返回键"按钮(位于"测试评论"按钮旁边)
|
||||
2. 点击按钮即可发送返回键到当前设备
|
||||
3. 如果没有指定设备,会自动选择第一个可用设备
|
||||
4. 适用于需要手动干预的场景
|
||||
|
||||
---
|
||||
|
||||
## 📜 版本历史
|
||||
|
||||
### V3.3.3 (2025-12-XX)
|
||||
### V3.3.1 (2025-12-14)
|
||||
|
||||
**当前版本**
|
||||
|
||||
- ✨ **新增功能**:
|
||||
- 手动发送返回键按钮:在GUI界面添加"发送返回键"按钮,支持随时手动发送返回键
|
||||
- 30分钟超时保护:如果30分钟没有成功参与福袋,自动返回推荐页面并重新进入直播间
|
||||
- 智能超时检测:记录最后一次成功参与的时间,智能判断是否需要重置
|
||||
- 🐛 修复:修复代码中的缩进错误和残留代码块
|
||||
- 🔧 优化:完善错误处理和日志记录
|
||||
- 📝 更新:完善文档和 README
|
||||
|
||||
### V3.3.2 (2025-12-22)
|
||||
|
||||
- 🚀 **性能优化**:所有串行OCR改为并行执行,显著提升识别速度
|
||||
- 福袋内容、倒计时、价值识别并行执行
|
||||
- 倒计时分割识别(分钟+秒)并行执行
|
||||
- OCR模式0+模式1并行执行(启用时)
|
||||
- 异常回退流程也使用并行执行
|
||||
- 🐛 修复:修复"切换N次后回到第一个"的回退方向(改为向上回退)
|
||||
- 🔧 优化:代码质量改进,通过 Pylance 类型检查
|
||||
- 📝 更新:完善文档和 README
|
||||
|
||||
### V3.3.1 (2025-12-14)
|
||||
|
||||
- ✨ 新增:直播间检测阈值可配置(`live_room_match_threshold`)
|
||||
- ✨ 新增:福袋图标检测等待时间可配置
|
||||
- 🐛 修复:修复直播间检测模板文件路径警告
|
||||
|
||||
@@ -208,6 +208,10 @@ class underlying_operations:
|
||||
# 支持延迟初始化(测试流程/只做点击时不需要 OCR)。
|
||||
self.ocr: Any = None
|
||||
self.ocr_type = None # 'easyocr' 或 'paddleocr'
|
||||
|
||||
# 检测GPU是否可用(自动检测)
|
||||
self._gpu_available = self._detect_gpu_available()
|
||||
|
||||
if not str(os.environ.get("SKIP_OCR_INIT", "")).strip():
|
||||
# 优先使用EasyOCR(更快),如果失败则回退到PaddleOCR
|
||||
# 首先尝试EasyOCR
|
||||
@@ -220,11 +224,13 @@ class underlying_operations:
|
||||
import easyocr # type: ignore[import-untyped]
|
||||
|
||||
# 只加载中文和英文,加快初始化速度
|
||||
# 自动检测GPU可用性,如果可用则启用GPU加速
|
||||
self.ocr = easyocr.Reader(
|
||||
["ch_sim", "en"], gpu=False, verbose=False
|
||||
["ch_sim", "en"], gpu=self._gpu_available, verbose=False
|
||||
)
|
||||
self.ocr_type = "easyocr"
|
||||
print("[OCR] 使用 EasyOCR(快速模式)")
|
||||
gpu_status = "GPU加速" if self._gpu_available else "CPU模式"
|
||||
print(f"[OCR] 使用 EasyOCR({gpu_status})")
|
||||
except Exception:
|
||||
# EasyOCR初始化失败,回退到PaddleOCR
|
||||
try:
|
||||
@@ -242,15 +248,27 @@ class underlying_operations:
|
||||
), contextlib.redirect_stderr(devnull):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# PaddleOCR的GPU支持需要paddlepaddle-gpu版本
|
||||
use_gpu = False
|
||||
try:
|
||||
import paddle
|
||||
if paddle.device.is_compiled_with_cuda() and paddle.device.get_device():
|
||||
use_gpu = self._gpu_available
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_angle_cls=False,
|
||||
use_gpu=use_gpu,
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
print("[OCR] EasyOCR不可用,使用 PaddleOCR(备选方案)")
|
||||
gpu_status = "GPU加速" if use_gpu else "CPU模式"
|
||||
print(f"[OCR] EasyOCR不可用,使用 PaddleOCR({gpu_status})")
|
||||
print(
|
||||
f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr"
|
||||
)
|
||||
@@ -291,9 +309,45 @@ class underlying_operations:
|
||||
adb = adb[1:-1]
|
||||
return adb
|
||||
|
||||
def _detect_gpu_available(self) -> bool:
|
||||
"""检测GPU是否可用
|
||||
|
||||
默认返回False(CPU模式),除非通过环境变量明确启用GPU
|
||||
|
||||
返回:
|
||||
True: GPU可用且已启用
|
||||
False: 使用CPU模式(默认)
|
||||
"""
|
||||
# 默认使用CPU模式,除非环境变量明确要求使用GPU
|
||||
# 检查环境变量是否强制启用GPU
|
||||
if str(os.environ.get("FORCE_GPU_OCR", "")).strip().lower() in ("1", "true", "yes"):
|
||||
# 强制启用时,验证GPU是否真的可用
|
||||
try:
|
||||
import torch # type: ignore[import-untyped]
|
||||
if torch.cuda.is_available():
|
||||
gpu_name = torch.cuda.get_device_name(0)
|
||||
print(f"[OCR] 环境变量强制启用GPU: {gpu_name},将使用GPU加速")
|
||||
return True
|
||||
else:
|
||||
print("[OCR] 环境变量要求启用GPU,但GPU不可用,使用CPU模式")
|
||||
return False
|
||||
except ImportError:
|
||||
print("[OCR] 环境变量要求启用GPU,但PyTorch未安装,使用CPU模式")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"[OCR] GPU检测失败: {e},使用CPU模式")
|
||||
return False
|
||||
|
||||
# 默认使用CPU模式
|
||||
return False
|
||||
|
||||
def _ensure_ocr(self):
|
||||
if self.ocr is not None:
|
||||
return
|
||||
|
||||
# 重新检测GPU(延迟初始化时)
|
||||
self._gpu_available = self._detect_gpu_available()
|
||||
|
||||
# 优先尝试EasyOCR
|
||||
devnull = None
|
||||
try:
|
||||
@@ -303,9 +357,10 @@ class underlying_operations:
|
||||
):
|
||||
import easyocr # type: ignore[import-untyped]
|
||||
|
||||
self.ocr = easyocr.Reader(["ch_sim", "en"], gpu=False, verbose=False)
|
||||
self.ocr = easyocr.Reader(["ch_sim", "en"], gpu=self._gpu_available, verbose=False)
|
||||
self.ocr_type = "easyocr"
|
||||
print("[OCR] 延迟初始化:使用 EasyOCR(快速模式)")
|
||||
gpu_status = "GPU加速" if self._gpu_available else "CPU模式"
|
||||
print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})")
|
||||
except Exception:
|
||||
# EasyOCR失败,回退到PaddleOCR
|
||||
try:
|
||||
@@ -323,15 +378,27 @@ class underlying_operations:
|
||||
):
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
# PaddleOCR的GPU支持需要paddlepaddle-gpu版本
|
||||
use_gpu = False
|
||||
try:
|
||||
import paddle
|
||||
if paddle.device.is_compiled_with_cuda() and paddle.device.get_device():
|
||||
use_gpu = self._gpu_available
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_angle_cls=False,
|
||||
use_gpu=use_gpu,
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = "paddleocr"
|
||||
print("[OCR] 延迟初始化:使用 PaddleOCR(备选方案)")
|
||||
gpu_status = "GPU加速" if use_gpu else "CPU模式"
|
||||
print(f"[OCR] 延迟初始化:使用 PaddleOCR({gpu_status})")
|
||||
except Exception:
|
||||
try:
|
||||
if devnull is not None:
|
||||
|
||||
+20
@@ -77,3 +77,23 @@ python 生成WPS流程图.py
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -85,6 +85,26 @@ else:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
检查GPU是否可用的脚本
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
# 修复Windows控制台编码问题
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def check_torch_cuda():
|
||||
"""检查PyTorch是否支持CUDA"""
|
||||
try:
|
||||
import torch
|
||||
|
||||
if torch.cuda.is_available():
|
||||
print(f"[GPU检测] PyTorch CUDA可用")
|
||||
print(f" CUDA版本: {torch.version.cuda}")
|
||||
print(f" GPU数量: {torch.cuda.device_count()}")
|
||||
for i in range(torch.cuda.device_count()):
|
||||
print(f" GPU {i}: {torch.cuda.get_device_name(i)}")
|
||||
return True
|
||||
else:
|
||||
print("[GPU检测] PyTorch CUDA不可用")
|
||||
return False
|
||||
except ImportError:
|
||||
print("[GPU检测] PyTorch未安装")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"[GPU检测] PyTorch CUDA检测失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_easyocr_gpu():
|
||||
"""检查EasyOCR是否可以使用GPU"""
|
||||
try:
|
||||
import easyocr
|
||||
|
||||
print("[GPU检测] EasyOCR已安装")
|
||||
# EasyOCR使用PyTorch,所以需要PyTorch支持CUDA
|
||||
try:
|
||||
import torch
|
||||
|
||||
if torch.cuda.is_available():
|
||||
print("[GPU检测] EasyOCR可以使用GPU(通过PyTorch CUDA)")
|
||||
return True
|
||||
else:
|
||||
print("[GPU检测] EasyOCR无法使用GPU(PyTorch CUDA不可用)")
|
||||
return False
|
||||
except ImportError:
|
||||
print("[GPU检测] EasyOCR需要PyTorch才能使用GPU")
|
||||
return False
|
||||
except ImportError:
|
||||
print("[GPU检测] EasyOCR未安装")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"[GPU检测] EasyOCR GPU检测失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_paddleocr_gpu():
|
||||
"""检查PaddleOCR是否可以使用GPU"""
|
||||
try:
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
print("[GPU检测] PaddleOCR已安装")
|
||||
# PaddleOCR需要paddlepaddle-gpu版本
|
||||
try:
|
||||
import paddle
|
||||
|
||||
if paddle.device.is_compiled_with_cuda():
|
||||
print("[GPU检测] PaddleOCR可以使用GPU(paddlepaddle-gpu已安装)")
|
||||
if paddle.device.get_device():
|
||||
print(f" Paddle设备: {paddle.device.get_device()}")
|
||||
return True
|
||||
else:
|
||||
print("[GPU检测] PaddleOCR无法使用GPU(需要安装paddlepaddle-gpu)")
|
||||
return False
|
||||
except ImportError:
|
||||
print("[GPU检测] PaddleOCR需要paddlepaddle才能使用GPU")
|
||||
return False
|
||||
except ImportError:
|
||||
print("[GPU检测] PaddleOCR未安装")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"[GPU检测] PaddleOCR GPU检测失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_integrated_graphics():
|
||||
"""检查是否是集成显卡(核显)"""
|
||||
try:
|
||||
import torch
|
||||
|
||||
if torch.cuda.is_available():
|
||||
for i in range(torch.cuda.device_count()):
|
||||
gpu_name = torch.cuda.get_device_name(i).lower()
|
||||
# 常见的核显标识
|
||||
integrated_keywords = [
|
||||
"intel",
|
||||
"iris",
|
||||
"uhd",
|
||||
"hd graphics",
|
||||
"amd",
|
||||
"radeon vega",
|
||||
"radeon graphics",
|
||||
]
|
||||
is_integrated = any(
|
||||
keyword in gpu_name for keyword in integrated_keywords
|
||||
)
|
||||
if is_integrated:
|
||||
print(
|
||||
f"[GPU检测] 检测到可能是集成显卡: {torch.cuda.get_device_name(i)}"
|
||||
)
|
||||
print("[GPU检测] 警告:集成显卡的GPU加速效果可能不明显")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("=" * 60)
|
||||
print("GPU可用性检测")
|
||||
print("=" * 60)
|
||||
print()
|
||||
|
||||
# 检查PyTorch CUDA
|
||||
print("[1] 检查PyTorch CUDA支持")
|
||||
torch_cuda_available = check_torch_cuda()
|
||||
print()
|
||||
|
||||
# 检查是否是核显
|
||||
if torch_cuda_available:
|
||||
print("[2] 检查显卡类型")
|
||||
is_integrated = check_integrated_graphics()
|
||||
print()
|
||||
|
||||
# 检查EasyOCR GPU支持
|
||||
print("[3] 检查EasyOCR GPU支持")
|
||||
easyocr_gpu_available = check_easyocr_gpu()
|
||||
print()
|
||||
|
||||
# 检查PaddleOCR GPU支持
|
||||
print("[4] 检查PaddleOCR GPU支持")
|
||||
paddleocr_gpu_available = check_paddleocr_gpu()
|
||||
print()
|
||||
|
||||
# 总结
|
||||
print("=" * 60)
|
||||
print("检测结果总结")
|
||||
print("=" * 60)
|
||||
|
||||
if torch_cuda_available:
|
||||
print("[OK] PyTorch CUDA可用")
|
||||
if is_integrated:
|
||||
print("[WARN] 检测到集成显卡,GPU加速效果可能有限")
|
||||
else:
|
||||
print("[OK] 检测到独立显卡,GPU加速效果较好")
|
||||
else:
|
||||
print("[NO] PyTorch CUDA不可用(将使用CPU模式)")
|
||||
|
||||
if easyocr_gpu_available:
|
||||
print("[OK] EasyOCR可以使用GPU")
|
||||
else:
|
||||
print("[NO] EasyOCR无法使用GPU(将使用CPU模式)")
|
||||
|
||||
if paddleocr_gpu_available:
|
||||
print("[OK] PaddleOCR可以使用GPU")
|
||||
else:
|
||||
print("[NO] PaddleOCR无法使用GPU(将使用CPU模式)")
|
||||
|
||||
print()
|
||||
print("建议:")
|
||||
if not torch_cuda_available:
|
||||
print(" - 如果使用NVIDIA独立显卡,请安装CUDA和PyTorch GPU版本")
|
||||
print(" - 如果使用集成显卡,GPU加速效果可能不明显,建议继续使用CPU模式")
|
||||
elif is_integrated:
|
||||
print(" - 集成显卡的GPU加速效果可能不明显")
|
||||
print(" - 可以尝试启用GPU,但性能提升可能有限")
|
||||
print(" - 如果遇到问题,建议继续使用CPU模式")
|
||||
else:
|
||||
print(" - 可以启用GPU加速以提升OCR性能")
|
||||
print(" - 修改 Underlying_Operations.py 中的 gpu=False 为 gpu=True")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
检查GUI参数设置冲突的脚本
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
# 修复Windows控制台编码问题
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8') # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.json")
|
||||
|
||||
|
||||
def check_conflicts(cfg: dict) -> list:
|
||||
"""检查配置参数冲突,返回冲突列表"""
|
||||
conflicts = []
|
||||
|
||||
# 1. 检查倒计时参数冲突
|
||||
skip_gt = int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)
|
||||
skip_lt = int(cfg.get("skip_if_countdown_lt_seconds", 5) or 5)
|
||||
join_ahead = int(cfg.get("high_value_fudai_join_ahead_seconds", 120) or 120)
|
||||
|
||||
if skip_lt >= skip_gt:
|
||||
conflicts.append({
|
||||
"type": "倒计时阈值冲突",
|
||||
"message": f"倒计时小于阈值({skip_lt}秒) >= 倒计时大于阈值({skip_gt}秒),这会导致所有福袋都被过滤",
|
||||
"params": {
|
||||
"skip_if_countdown_lt_seconds": skip_lt,
|
||||
"skip_if_countdown_gt_seconds": skip_gt,
|
||||
}
|
||||
})
|
||||
|
||||
if join_ahead > skip_gt:
|
||||
conflicts.append({
|
||||
"type": "预约参与阈值冲突",
|
||||
"message": f"预约参与阈值({join_ahead}秒) > 倒计时大于阈值({skip_gt}秒),高价值福袋即使剩余时间在预约阈值内也会被过滤",
|
||||
"params": {
|
||||
"high_value_fudai_join_ahead_seconds": join_ahead,
|
||||
"skip_if_countdown_gt_seconds": skip_gt,
|
||||
}
|
||||
})
|
||||
|
||||
if join_ahead < skip_lt:
|
||||
conflicts.append({
|
||||
"type": "预约参与阈值冲突",
|
||||
"message": f"预约参与阈值({join_ahead}秒) < 倒计时小于阈值({skip_lt}秒),可能导致高价值福袋在预约阈值内也被过滤",
|
||||
"params": {
|
||||
"high_value_fudai_join_ahead_seconds": join_ahead,
|
||||
"skip_if_countdown_lt_seconds": skip_lt,
|
||||
}
|
||||
})
|
||||
|
||||
# 2. 检查参与人数参数冲突
|
||||
min_participants = int(cfg.get("min_participants", 0) or 0)
|
||||
max_participants = int(cfg.get("max_participants", 0) or 0)
|
||||
|
||||
if max_participants > 0 and min_participants > max_participants:
|
||||
conflicts.append({
|
||||
"type": "参与人数阈值冲突",
|
||||
"message": f"最小参与人数({min_participants}) > 最大参与人数({max_participants}),这会导致所有福袋都被过滤",
|
||||
"params": {
|
||||
"min_participants": min_participants,
|
||||
"max_participants": max_participants,
|
||||
}
|
||||
})
|
||||
|
||||
# 3. 检查价值参数冲突
|
||||
min_value = float(cfg.get("min_prize_value_yuan", 0) or 0)
|
||||
high_value_threshold = float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000)
|
||||
|
||||
if high_value_threshold < min_value:
|
||||
conflicts.append({
|
||||
"type": "价值阈值冲突",
|
||||
"message": f"高价值阈值({high_value_threshold}元) < 最小价值({min_value}元),高价值福袋可能被最小价值过滤掉",
|
||||
"params": {
|
||||
"high_value_fudai_threshold_yuan": high_value_threshold,
|
||||
"min_prize_value_yuan": min_value,
|
||||
}
|
||||
})
|
||||
|
||||
# 4. 检查高价值预约相关参数
|
||||
high_value_enabled = bool(cfg.get("high_value_fudai_enabled", False))
|
||||
|
||||
if high_value_enabled and high_value_threshold <= 0:
|
||||
conflicts.append({
|
||||
"type": "高价值预约配置错误",
|
||||
"message": f"已启用高价值预约,但高价值阈值({high_value_threshold}元) <= 0,预约功能无法正常工作",
|
||||
"params": {
|
||||
"high_value_fudai_enabled": high_value_enabled,
|
||||
"high_value_fudai_threshold_yuan": high_value_threshold,
|
||||
}
|
||||
})
|
||||
|
||||
# 5. 检查预约相关参数合理性
|
||||
if high_value_enabled:
|
||||
max_reservations = int(cfg.get("high_value_fudai_max_reservations", 5) or 5)
|
||||
if max_reservations <= 0:
|
||||
conflicts.append({
|
||||
"type": "预约数量配置错误",
|
||||
"message": f"最多记录数量({max_reservations}) <= 0,预约功能无法正常工作",
|
||||
"params": {
|
||||
"high_value_fudai_max_reservations": max_reservations,
|
||||
}
|
||||
})
|
||||
|
||||
# 6. 检查福袋查找相关参数
|
||||
fudai_icon_max_wait = float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0)
|
||||
fudai_icon_retry_delay = float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
|
||||
|
||||
if fudai_icon_max_wait < fudai_icon_retry_delay:
|
||||
conflicts.append({
|
||||
"type": "福袋查找参数不合理",
|
||||
"message": f"最大等待时间({fudai_icon_max_wait}秒) < 重试延迟({fudai_icon_retry_delay}秒),可能导致只检测一次就放弃",
|
||||
"params": {
|
||||
"fudai_icon_max_wait_seconds": fudai_icon_max_wait,
|
||||
"fudai_icon_retry_delay_seconds": fudai_icon_retry_delay,
|
||||
}
|
||||
})
|
||||
|
||||
return conflicts
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
if not os.path.exists(CONFIG_PATH):
|
||||
print(f"配置文件不存在: {CONFIG_PATH}")
|
||||
return
|
||||
|
||||
try:
|
||||
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
except Exception as e:
|
||||
print(f"读取配置文件失败: {e}")
|
||||
return
|
||||
|
||||
conflicts = check_conflicts(cfg)
|
||||
|
||||
if not conflicts:
|
||||
print("[OK] 未发现参数冲突")
|
||||
return
|
||||
|
||||
print(f"发现 {len(conflicts)} 个参数冲突:\n")
|
||||
for i, conflict in enumerate(conflicts, 1):
|
||||
print(f"{i}. 【{conflict['type']}】")
|
||||
print(f" {conflict['message']}")
|
||||
print(f" 相关参数: {conflict['params']}")
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
+5
-5
@@ -2,10 +2,10 @@
|
||||
"needswitch": true,
|
||||
"infinite_loop_enabled": true,
|
||||
"wait_minutes": 5,
|
||||
"min_prize_value_yuan": 1.0,
|
||||
"min_prize_value_yuan": 200.0,
|
||||
"min_participants": 0,
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 600,
|
||||
"skip_if_countdown_gt_seconds": 180,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 50,
|
||||
"auto_join_fansclub": true,
|
||||
@@ -18,7 +18,7 @@
|
||||
"high_value_fudai_after_action": "continue",
|
||||
"high_value_room_revisit_enabled": true,
|
||||
"high_value_room_revisit_only_current_run": true,
|
||||
"reservation_back_verify_enabled": true,
|
||||
"reservation_back_verify_enabled": false,
|
||||
"reservation_back_swipe_delay": 0.6,
|
||||
"reservation_preempt_min_value": 0.0,
|
||||
"desktop_icon_x": 153,
|
||||
@@ -29,7 +29,7 @@
|
||||
"yanghao_fallback_enter_live_y": 1200,
|
||||
"fudai_find_max_attempts": 99999,
|
||||
"fudai_icon_retry_delay_seconds": 0.7,
|
||||
"fudai_icon_max_wait_seconds": 15.0,
|
||||
"fudai_icon_max_wait_seconds": 10.0,
|
||||
"yanghao_recommend_duration_seconds": 206,
|
||||
"yanghao_recommend_interval_seconds": 570,
|
||||
"yanghao_like_prob": 1.0,
|
||||
@@ -92,7 +92,7 @@
|
||||
}
|
||||
},
|
||||
"debug_captures": {
|
||||
"keep_days": 7,
|
||||
"keep_days": 3,
|
||||
"max_files": 2000,
|
||||
"auto_cleanup": true
|
||||
}
|
||||
|
||||
@@ -1637,111 +1637,3 @@ def check_in_fudai_detail(analyser: Any) -> bool:
|
||||
# ========== 以下为旧的像素检测代码,已暂时禁用 ==========
|
||||
# 像素检测代码已删除,使用模板匹配替代
|
||||
# 如需恢复像素检测,请参考 git 历史记录
|
||||
|
||||
|
||||
def check_in_fudai_detail(analyser: Any) -> bool:
|
||||
"""Detect whether we are currently on the 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)
|
||||
|
||||
path = os.path.join(os.path.dirname(__file__), "pic")
|
||||
pic1_path = os.path.join(path, "screenshot.png")
|
||||
try:
|
||||
try:
|
||||
pic0 = Image.open(pic1_path)
|
||||
pic0.load()
|
||||
pic = pic0.convert("RGBA")
|
||||
except Exception:
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
pic0 = Image.open(pic1_path)
|
||||
pic0.load()
|
||||
pic = pic0.convert("RGBA")
|
||||
except Exception:
|
||||
analyser._detection_cache[cache_key] = (now, False)
|
||||
return False
|
||||
|
||||
pix = pic.load()
|
||||
width, height = pic.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
|
||||
|
||||
x = 536 * rx // 1080
|
||||
if not (0 <= x < width):
|
||||
analyser._detection_cache[cache_key] = (now, False)
|
||||
return False
|
||||
|
||||
base_ys = (883, 983, 1058)
|
||||
offsets = (0, y_pianyi_val, -y_pianyi_val)
|
||||
|
||||
for base_y in base_ys:
|
||||
y0 = base_y * ry // 2400
|
||||
for dy in offsets:
|
||||
y = y0 + dy
|
||||
if not (0 <= y < height):
|
||||
continue
|
||||
try:
|
||||
p = pix[x, y]
|
||||
if not (isinstance(p, tuple) and len(p) >= 3):
|
||||
continue
|
||||
r, g, b = int(p[0]), int(p[1]), int(p[2])
|
||||
if 30 <= r <= 38 and 34 <= g <= 40 and 78 <= b <= 84:
|
||||
analyser._detection_cache[cache_key] = (now, True)
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# OCR fallback (lighter version of original implementation)
|
||||
try:
|
||||
try:
|
||||
min_interval = float(
|
||||
getattr(analyser, "detail_ocr_check_min_interval_seconds", 8.0) or 0.0
|
||||
)
|
||||
except Exception:
|
||||
min_interval = 8.0
|
||||
last = float(getattr(analyser, "_last_detail_ocr_check_ts", 0.0) or 0.0)
|
||||
if min_interval > 0 and (now - last) < min_interval:
|
||||
analyser._detection_cache[cache_key] = (now, False)
|
||||
return False
|
||||
analyser._last_detail_ocr_check_ts = now
|
||||
|
||||
analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮")
|
||||
t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
|
||||
keywords = (
|
||||
"参与",
|
||||
"评论",
|
||||
"还需看播",
|
||||
"无法参与",
|
||||
"时长不足",
|
||||
"粉丝团",
|
||||
"开始观看",
|
||||
)
|
||||
if not t_btn or not any(k in t_btn for k in keywords):
|
||||
t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "")
|
||||
if any(k in t_btn for k in keywords):
|
||||
analyser._detection_cache[cache_key] = (now, True)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser._detection_cache[cache_key] = (now, False)
|
||||
return False
|
||||
+91
-72
@@ -47,6 +47,20 @@ def find_and_open_fudai_detail(
|
||||
room_pos_ref: List[int],
|
||||
) -> bool:
|
||||
"""在当前直播间查找福袋图标并尝试点击打开详情(基础版,不做预约)。"""
|
||||
# 如果正在等待开奖,不应该再次打开福袋详情
|
||||
try:
|
||||
if getattr(analyser, "_waiting_for_lottery_result", False):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
device_id = getattr(analyser, "device_id", "")
|
||||
|
||||
# 0. 先检查是否已经在福袋详情页,如果是则直接返回True,避免重复点击
|
||||
@@ -105,10 +119,61 @@ def find_and_open_fudai_detail(
|
||||
pass
|
||||
|
||||
# 1. 利用像素检测福袋图标的 X 坐标(1080 基准)
|
||||
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False)
|
||||
# 在配置的最大等待时间内重复检测福袋图标
|
||||
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:
|
||||
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
|
||||
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:
|
||||
analyser._log_kv("流程", "find_and_open_fudai_detail:未检测到福袋图标", x=int(x or 0))
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:等待超时,未检测到福袋图标",
|
||||
x=int(x or 0),
|
||||
max_wait_seconds=max_wait_seconds,
|
||||
total_elapsed_seconds=round(time.time() - start_time, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
@@ -192,7 +257,7 @@ def find_and_open_fudai_detail(
|
||||
)
|
||||
|
||||
if not is_in_detail:
|
||||
# 如果不在福袋详情页,可能是误点击,返回
|
||||
# 如果不在福袋详情页,可能是误点击,通过点击固定坐标返回直播间
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
@@ -203,9 +268,29 @@ def find_and_open_fudai_detail(
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 返回直播间
|
||||
analyser.operation.click_back(device_id)
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 使用固定坐标 (520, 505) 进行点击,而不是系统返回键
|
||||
# 根据当前分辨率进行等比例换算(基准分辨率 1080x2400)
|
||||
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:
|
||||
# 兜底:直接用 analyser.click
|
||||
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
|
||||
@@ -336,72 +421,6 @@ def handle_no_fudai_situation(
|
||||
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 对福袋进行基础筛选。"""
|
||||
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:
|
||||
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
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
# 简单策略:轻微等待 + 上滑切换
|
||||
try:
|
||||
analyser.operation.delay(1.0)
|
||||
except Exception:
|
||||
time.sleep(1.0)
|
||||
|
||||
if needswitch and swipe_up_switch_callback:
|
||||
swipe_up_switch_callback()
|
||||
try:
|
||||
analyser.operation.delay(post_switch_delay_s or 1.2)
|
||||
except Exception:
|
||||
time.sleep(post_switch_delay_s or 1.2)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def filter_fudai_detail(
|
||||
analyser: Any,
|
||||
detail: Tuple,
|
||||
|
||||
+767
-94
File diff suppressed because it is too large.
Load diff
+478
-137
@@ -101,30 +101,105 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
return ""
|
||||
|
||||
def _read_countdown_split(box: tuple[int, int, int, int]) -> str:
|
||||
"""将倒计时区域按三等分切成"分钟段/秒段/后开奖段",分别OCR分钟与秒,组合为 mm:ss。"""
|
||||
"""将倒计时区域分割成"分钟段"和"秒段",分别OCR识别,然后组合为 mm:ss。
|
||||
|
||||
优化:更精确的分割方式,避免识别顺序错误。
|
||||
倒计时格式通常是:XX:XX后开奖,其中前两位是分钟,中间两位是秒。
|
||||
"""
|
||||
try:
|
||||
x1, y1, x2, y2 = box
|
||||
w = max(1, int(x2 - x1))
|
||||
seg = max(1, w // 3)
|
||||
# 前 1/3:分钟;中 1/3:秒(第三段通常包含"后开奖")
|
||||
h = max(1, int(y2 - y1))
|
||||
|
||||
# 优化:根据实际布局,倒计时通常是:分钟(2位数字框) + 冒号 + 秒(2位数字框) + 后开奖
|
||||
# 更精确的分割:前30%为分钟数字框,中间30%为秒数字框(剩余40%包含冒号和"后开奖")
|
||||
# 这样可以更精确地定位到数字区域,避免识别到冒号或"后开奖"文字
|
||||
seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框
|
||||
seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框
|
||||
|
||||
# 保存调试截图
|
||||
try:
|
||||
_save_full_screenshot_with_ocr_region(
|
||||
analyser, "福袋倒计时_分钟", (x1, y1, x1 + seg1, y2), analyser.y_pianyi
|
||||
)
|
||||
_save_full_screenshot_with_ocr_region(
|
||||
analyser, "福袋倒计时_秒", (x1 + seg1, y1, x1 + seg1 + seg2, y2), analyser.y_pianyi
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 切割分钟区域(左侧)
|
||||
analyser.cut_pic(
|
||||
x1, y1, x1 + seg, y2, "", "福袋倒计时_分钟", analyser.y_pianyi
|
||||
x1, y1, x1 + seg1, y2, "", "福袋倒计时_分钟", analyser.y_pianyi
|
||||
)
|
||||
# 切割秒区域(中间,跳过冒号)
|
||||
analyser.cut_pic(
|
||||
x1 + seg, y1, x1 + 2 * seg, y2, "", "福袋倒计时_秒", analyser.y_pianyi
|
||||
x1 + seg1, y1, x1 + seg1 + seg2, y2, "", "福袋倒计时_秒", analyser.y_pianyi
|
||||
)
|
||||
|
||||
# 并行执行两个OCR识别
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_mm = executor.submit(analyser.operation.analyse_pic_word, "福袋倒计时_分钟", 0)
|
||||
future_ss = executor.submit(analyser.operation.analyse_pic_word, "福袋倒计时_秒", 0)
|
||||
mm_raw = future_mm.result()
|
||||
ss_raw = future_ss.result()
|
||||
mm = _extract_2digits(mm_raw)
|
||||
ss = _extract_2digits(ss_raw)
|
||||
|
||||
# 提取数字:分钟和秒都应该是1-2位数字
|
||||
def _extract_digits(text: str, max_digits: int = 2) -> str:
|
||||
"""提取数字,最多max_digits位"""
|
||||
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
|
||||
if len(digits) > max_digits:
|
||||
return digits[:max_digits]
|
||||
if len(digits) == 1:
|
||||
return "0" + digits
|
||||
return digits
|
||||
|
||||
mm = _extract_digits(mm_raw, max_digits=2)
|
||||
ss = _extract_digits(ss_raw, max_digits=2)
|
||||
|
||||
# 分割识别已经分别识别了分钟和秒,顺序是正确的,不需要交换纠正
|
||||
# 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果)
|
||||
try:
|
||||
mm_int = int(mm) if mm else 0
|
||||
ss_int = int(ss) if ss else 0
|
||||
if ss_int >= 60:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋倒计时",
|
||||
"分割识别:检测到秒数>=60(可能是识别错误)",
|
||||
mm=mm_int,
|
||||
ss=ss_int,
|
||||
mm_raw=mm_raw,
|
||||
ss_raw=ss_raw,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if mm and ss:
|
||||
return f"{mm}:{ss}"
|
||||
except Exception:
|
||||
return ""
|
||||
result = f"{mm}:{ss}"
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋倒计时",
|
||||
"分割识别成功",
|
||||
mm_raw=mm_raw,
|
||||
ss_raw=ss_raw,
|
||||
result=result,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return result
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋倒计时",
|
||||
"分割识别失败",
|
||||
error=str(e),
|
||||
error_type=type(e).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
|
||||
def _extract_participants_and_clean(text: str):
|
||||
@@ -328,59 +403,10 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 检测到任务数量后,点击一次返回,然后切换到下一个直播间,并直接返回
|
||||
# 注意:任务数量为0时说明没有正确打开福袋,不执行返回和切换操作
|
||||
if detected_task_count is not None and detected_task_count > 0:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"并行OCR检测到任务数量",
|
||||
task_count=detected_task_count,
|
||||
)
|
||||
# 点击一次返回
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
analyser._log_kv("福袋详情", "检测到任务数量后点击返回")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 切换到下一个直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
if needswitch:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"检测到任务数量后切换直播间",
|
||||
task_count=detected_task_count,
|
||||
)
|
||||
# 优先使用封装好的上滑切房方法
|
||||
if hasattr(analyser, "swipe_up_to_next_live"):
|
||||
analyser.swipe_up_to_next_live()
|
||||
else:
|
||||
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1700 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 700 * ry // 2400
|
||||
analyser.operation.swipe(
|
||||
analyser.device_id, start_x, start_y, end_x, end_y, 300
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 检测到任务数量后直接返回,不继续后续处理
|
||||
return "", "", 0, 0, 0.0
|
||||
except Exception:
|
||||
pass
|
||||
elif detected_task_count == 0:
|
||||
# 检测到任务数量后的处理逻辑
|
||||
# 修改:只有任务数量为0时才跳过(认为未正确打开福袋详情页)
|
||||
# 任务数量 >= 1 时,应该参与,继续后续处理
|
||||
if detected_task_count == 0:
|
||||
# 任务数量为0,说明没有正确打开福袋详情页,记录日志但不执行返回操作
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -440,38 +466,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
detected_task_count = future_task_count.result()
|
||||
|
||||
# 检测任务数量后的处理逻辑
|
||||
if detected_task_count is not None and detected_task_count > 0:
|
||||
# 点击返回并切换直播间,然后直接返回
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"备用并行模式检测到任务数量",
|
||||
task_count=detected_task_count,
|
||||
)
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
if needswitch:
|
||||
if hasattr(analyser, "swipe_up_to_next_live"):
|
||||
analyser.swipe_up_to_next_live()
|
||||
else:
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
start_x = 540 * rx // 1080
|
||||
start_y = 1700 * ry // 2400
|
||||
end_x = 540 * rx // 1080
|
||||
end_y = 700 * ry // 2400
|
||||
analyser.operation.swipe(
|
||||
analyser.device_id, start_x, start_y, end_x, end_y, 300
|
||||
)
|
||||
# 检测到任务数量后直接返回,不继续后续处理
|
||||
return "", "", 0, 0, 0.0
|
||||
except Exception:
|
||||
pass
|
||||
elif detected_task_count == 0:
|
||||
# 修改:只有任务数量为0时才跳过(认为未正确打开福袋详情页)
|
||||
# 任务数量 >= 1 时,应该参与,继续后续处理
|
||||
if detected_task_count == 0:
|
||||
# 任务数量为0,说明没有正确打开福袋详情页,记录日志但不执行返回操作
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -584,17 +581,45 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 倒计时:优先用完整OCR(更快,只需1次),失败再用分割OCR
|
||||
time_text = normalize_countdown_text(time_raw)
|
||||
if not time_text or not _parse_mm_ss(time_text):
|
||||
# 倒计时:优先使用分割OCR(更准确,避免识别顺序错误),失败再用完整OCR
|
||||
time_text = None
|
||||
try:
|
||||
if countdown_box:
|
||||
split_raw = _read_countdown_split(countdown_box)
|
||||
# 分割识别的结果已经是 mm:ss 格式,不需要再进行 normalize_countdown_text 处理
|
||||
# 因为分割识别已经分别识别了分钟和秒,顺序是正确的
|
||||
if split_raw and _parse_mm_ss(split_raw):
|
||||
time_text = split_raw
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋倒计时",
|
||||
"使用分割识别结果(无需纠正)",
|
||||
split_text=split_raw,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
if countdown_box:
|
||||
split_raw = _read_countdown_split(countdown_box)
|
||||
split_text = normalize_countdown_text(split_raw)
|
||||
if _parse_mm_ss(split_text):
|
||||
time_text = split_text
|
||||
analyser._log_kv(
|
||||
"福袋倒计时",
|
||||
"分割识别异常,回退到完整OCR",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果分割识别失败,回退到完整OCR(完整OCR仍需要 normalize_countdown_text 处理)
|
||||
if not time_text:
|
||||
time_text = normalize_countdown_text(time_raw)
|
||||
if time_text:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋倒计时",
|
||||
"使用完整OCR结果",
|
||||
time_text=time_text,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser._log_kv(
|
||||
"福袋", "识别倒计时", countdown=time_text if time_text else "未识别到"
|
||||
)
|
||||
@@ -696,6 +721,32 @@ def attend_choujiang(analyser) -> bool:
|
||||
analyser._last_successful_attend_ts = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录已参与的福袋(通过 future_ts 标识),避免重复参与
|
||||
try:
|
||||
# 从 detail 中获取 future_ts(如果可用)
|
||||
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
|
||||
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
|
||||
|
||||
# 设置标志:已经关闭了详情,避免后续再次点击返回键
|
||||
try:
|
||||
analyser._detail_closed_by_attend = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser.click(500, 470) # 点击刚才打开福袋的旁边位置
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return True
|
||||
@@ -736,18 +787,55 @@ def attend_choujiang(analyser) -> bool:
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return False
|
||||
elif "评论" in attend_button_text:
|
||||
analyser.click(500, 2060)
|
||||
analyser._log_kv("参与", "点击参与抽奖", action="点击参与", mode="评论")
|
||||
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
|
||||
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
|
||||
analyser.click(543, 2070)
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与抽奖(基于截图优化坐标)",
|
||||
action="点击参与",
|
||||
mode="评论",
|
||||
base_x=543,
|
||||
base_y=2070,
|
||||
region="(306,2030)-(780,2110)",
|
||||
)
|
||||
return True
|
||||
elif "参与抽奖" in attend_button_text:
|
||||
analyser.click(500, 2060)
|
||||
analyser._log_kv("参与", "点击参与抽奖", action="点击参与", mode="普通")
|
||||
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
|
||||
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
|
||||
analyser.click(543, 2070)
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击参与抽奖(基于截图优化坐标)",
|
||||
action="点击参与",
|
||||
mode="普通",
|
||||
base_x=543,
|
||||
base_y=2070,
|
||||
region="(306,2030)-(780,2110)",
|
||||
)
|
||||
|
||||
# 设置标志:需要重新点击福袋位置进入详情来验证是否参与成功
|
||||
# 注意:点击参与按钮后会自动关闭详情页,所以不需要手动关闭
|
||||
try:
|
||||
analyser._need_reopen_detail_to_verify_attend = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser._log_kv("参与", "点击参与按钮完成,详情页将自动关闭,准备重新点击福袋位置验证参与状态")
|
||||
return True
|
||||
elif "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text:
|
||||
# 需要粉丝团门槛:先点击尝试进入加入/点亮流程
|
||||
analyser.last_attend_fail_reason = "fansclub_required"
|
||||
analyser.click(500, 2060)
|
||||
analyser._log_kv("参与", "粉丝团门槛:已点击加入按钮", result="需要粉丝团")
|
||||
# 基于截图优化坐标:OCR区域(200,1940)-(880,2140),红色区域中心Y=2006
|
||||
# 点击红色文字区域中心(540, 2006)而不是按钮中心(500, 2060)
|
||||
analyser.click(540, 2006)
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"粉丝团门槛:已点击加入按钮(优化坐标)",
|
||||
result="需要粉丝团",
|
||||
base_x=540,
|
||||
base_y=2000,
|
||||
)
|
||||
analyser.operation.delay(2)
|
||||
|
||||
if not analyser.auto_join_fansclub:
|
||||
@@ -776,7 +864,7 @@ def attend_choujiang(analyser) -> bool:
|
||||
return True
|
||||
|
||||
if st == "FANSCLUB_JOIN":
|
||||
# 在加入页点击底部“加入粉丝团”按钮(与详情页按钮同位置)
|
||||
# 在加入页点击底部"加入粉丝团"按钮(与详情页按钮同位置)
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"粉丝团加入页:点击加入粉丝团",
|
||||
@@ -785,16 +873,155 @@ def attend_choujiang(analyser) -> bool:
|
||||
attempt=i + 1,
|
||||
)
|
||||
try:
|
||||
analyser.click(500, 2060)
|
||||
# 点击加入粉丝团按钮
|
||||
# 基于实际截图分析:OCR区域 (200, 1940, 880, 2140),尺寸680x200
|
||||
# 按钮上部66%是红色区域(文字"加入粉丝团"所在),高度约132像素
|
||||
# 红色区域Y范围:1940 到 2072,中心Y = 1940 + 132/2 = 2006
|
||||
# 使用区域中心X = (200+880)/2 = 540,Y = 2006(红色区域中心)
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
# 点击红色文字区域的中心(基于截图分析优化)
|
||||
click_x = int(540 * rx // 1080) # 区域中心X
|
||||
click_y = int(2006 * ry // 2400) # 红色区域中心Y(基于截图:1940+132/2=2006)
|
||||
analyser.operation.click(analyser.device_id, click_x, click_y)
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击加入粉丝团按钮(基于截图优化坐标)",
|
||||
x=click_x,
|
||||
y=click_y,
|
||||
base_x=540,
|
||||
base_y=2006,
|
||||
region="(200,1940)-(880,2140)",
|
||||
red_area_center_y=2006,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.operation.delay(2)
|
||||
# 尝试返回到详情
|
||||
# 如果新坐标失败,回退到优化后的坐标(粉丝团加入按钮)
|
||||
try:
|
||||
analyser.click(540, 2006) # 粉丝团加入按钮优化坐标
|
||||
except Exception:
|
||||
# 最后回退到旧坐标
|
||||
try:
|
||||
analyser.click(500, 2060)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 等待加入流程完成(根据是否启用自动加入决定等待时间)
|
||||
auto_join_enabled = getattr(analyser, "auto_join_fansclub", False)
|
||||
if auto_join_enabled:
|
||||
# 启用自动加入:等待更长时间,让加入流程完成
|
||||
analyser.operation.delay(5.0)
|
||||
analyser._log_kv("参与", "已启用自动加入粉丝团,等待加入流程完成", wait_seconds=5.0)
|
||||
else:
|
||||
# 未启用自动加入:等待较短时间后返回
|
||||
analyser.operation.delay(3.0)
|
||||
analyser._log_kv("参与", "未启用自动加入粉丝团,等待后返回", wait_seconds=3.0)
|
||||
|
||||
# 重新诊断阶段,确认是否还在粉丝团加入页
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(1)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
st_after, seen_after = analyser._diagnose_stage_from_current_screen()
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击加入粉丝团后重新诊断阶段",
|
||||
stage_before=st,
|
||||
stage_after=st_after,
|
||||
seen_after=seen_after,
|
||||
)
|
||||
|
||||
if st_after == "FANSCLUB_JOIN":
|
||||
# 仍在粉丝团加入页,说明可能需要再次点击或等待更长时间
|
||||
if auto_join_enabled:
|
||||
# 如果启用了自动加入,尝试再次点击
|
||||
analyser._log_kv("参与", "仍在粉丝团加入页,尝试再次点击")
|
||||
try:
|
||||
# 基于截图优化坐标:红色区域中心Y=2006
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
click_x = int(540 * rx // 1080)
|
||||
click_y = int(2006 * ry // 2400) # 红色区域中心Y=2006
|
||||
analyser.operation.click(analyser.device_id, click_x, click_y)
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"再次点击加入粉丝团按钮(基于截图优化坐标)",
|
||||
x=click_x,
|
||||
y=click_y,
|
||||
base_y=2006,
|
||||
)
|
||||
analyser.operation.delay(3.0)
|
||||
except Exception:
|
||||
# 回退到优化后的坐标(粉丝团加入按钮)
|
||||
try:
|
||||
analyser.click(540, 2006) # 粉丝团加入按钮优化坐标
|
||||
analyser.operation.delay(3.0)
|
||||
except Exception:
|
||||
# 最后回退到旧坐标
|
||||
try:
|
||||
analyser.click(500, 2060)
|
||||
analyser.operation.delay(3.0)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 未启用自动加入,直接返回
|
||||
analyser._log_kv("参与", "仍在粉丝团加入页,未启用自动加入,返回")
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(1)
|
||||
except Exception:
|
||||
pass
|
||||
elif st_after == "FUDai_DETAIL":
|
||||
# 已经回到福袋详情页,说明加入成功
|
||||
analyser._log_kv("参与", "已回到福袋详情页,加入流程可能已完成")
|
||||
return True
|
||||
elif st_after in ("IN_LIVE_ROOM", "FOLLOW_LIST", "LIVE_LIST"):
|
||||
# 如果之前是在粉丝团加入页,现在显示在直播间,可能是误判
|
||||
# 实际上可能还在加入成功的页面,需要点击返回键
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击加入粉丝团后显示在直播间(可能误判),尝试点击返回键",
|
||||
stage_before="FANSCLUB_JOIN",
|
||||
stage_after=st_after,
|
||||
)
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(1.0)
|
||||
# 点击返回后再次诊断,看是否回到福袋详情页
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
st_after_back, seen_after_back = analyser._diagnose_stage_from_current_screen()
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"点击返回后重新诊断阶段",
|
||||
stage_after_back=st_after_back,
|
||||
seen_after_back=seen_after_back,
|
||||
)
|
||||
if st_after_back == "FUDai_DETAIL":
|
||||
analyser._log_kv("参与", "点击返回后已回到福袋详情页")
|
||||
return True
|
||||
elif st_after_back in ("IN_LIVE_ROOM", "FOLLOW_LIST", "LIVE_LIST"):
|
||||
analyser._log_kv("参与", "点击返回后确实回到直播间,停止继续返回", stage=st_after_back)
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
else:
|
||||
# 其他阶段,尝试返回
|
||||
analyser._log_kv("参与", "点击后进入其他阶段,尝试返回", stage=st_after)
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(1)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 诊断失败,保守处理:如果启用了自动加入,不返回;否则返回
|
||||
analyser._log_kv("参与", "重新诊断阶段失败", error=str(e))
|
||||
if not auto_join_enabled:
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(1)
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
|
||||
# 已经回到直播间/列表时:不要继续按返回键,避免退出直播
|
||||
@@ -1187,6 +1414,22 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
|
||||
返回:
|
||||
(skip, reason) 其中 reason 为简单文字原因,便于日志查看。
|
||||
"""
|
||||
# 单间模式(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"
|
||||
|
||||
@@ -1601,6 +1844,21 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
pass
|
||||
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
|
||||
return attend_choujiang(analyser)
|
||||
|
||||
# 检查是否启用高价值预约,以及价值是否达到阈值
|
||||
try:
|
||||
high_value_enabled = bool(getattr(analyser, "high_value_fudai_enabled", False))
|
||||
@@ -1622,6 +1880,30 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
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
|
||||
@@ -1633,21 +1915,64 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
# 执行筛选检查
|
||||
skip, reason = should_skip_fudai_by_config(analyser, detail)
|
||||
|
||||
# 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值,则记录预约而不是丢弃
|
||||
# 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值
|
||||
# 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约
|
||||
if skip and reason.startswith("countdown_gt_") and is_high_value:
|
||||
# 计算剩余秒数
|
||||
remain_seconds = None
|
||||
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
|
||||
try:
|
||||
import time
|
||||
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:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:倒计时大于阈值,但价值达到高价值阈值,记录预约",
|
||||
reason=reason,
|
||||
value_yuan=prize_value_yuan,
|
||||
threshold=high_value_threshold,
|
||||
join_ahead_seconds = int(
|
||||
getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 不关闭详情,继续走预约逻辑
|
||||
skip = False
|
||||
reason = "high_value_reservation"
|
||||
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),
|
||||
join_ahead_threshold=join_ahead_seconds,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 不关闭详情,继续走立即参与逻辑
|
||||
skip = False
|
||||
reason = "high_value_immediate_join"
|
||||
else:
|
||||
# 剩余秒数大于"预约参与阈值",记录预约
|
||||
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,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 不关闭详情,继续走预约逻辑
|
||||
skip = False
|
||||
reason = "high_value_reservation"
|
||||
|
||||
if skip:
|
||||
try:
|
||||
@@ -1717,7 +2042,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
# 注意:content, prize_value_yuan, countdown_tuple, future_ts, high_value_enabled, high_value_threshold, is_high_value 已在前面提取
|
||||
# 仅当启用高价值预约、识别到价值且未来时间合理时,才考虑记入预约队列
|
||||
if is_high_value:
|
||||
# 价值达到高价值阈值:检查剩余秒数,如果在阈值内则立即参与,否则记录预约
|
||||
# 价值达到高价值阈值:检查剩余秒数,如果在"预约参与阈值"内则立即参与,否则记录预约
|
||||
# 计算剩余秒数
|
||||
remain_seconds = None
|
||||
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
|
||||
@@ -1731,27 +2056,43 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 获取倒计时阈值配置
|
||||
# 获取"预约参与阈值"配置(high_value_fudai_join_ahead_seconds)
|
||||
# 如果剩余秒数 <= 这个阈值,立即参与;否则记录预约
|
||||
try:
|
||||
skip_if_gt = int(getattr(analyser, "skip_if_countdown_gt_seconds", 0) or 0)
|
||||
join_ahead_seconds = int(
|
||||
getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120
|
||||
)
|
||||
except Exception:
|
||||
skip_if_gt = 0
|
||||
join_ahead_seconds = 120
|
||||
|
||||
# 如果剩余秒数在阈值内(<= 阈值),立即参与而不是记录预约
|
||||
if remain_seconds is not None and skip_if_gt > 0 and remain_seconds <= skip_if_gt:
|
||||
# 如果剩余秒数在"预约参与阈值"内(<= 阈值),立即参与而不是记录预约
|
||||
if remain_seconds is not None and remain_seconds <= join_ahead_seconds:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:价值达到高价值阈值,但剩余秒数在阈值内,立即参与",
|
||||
"basic_join_decision:价值达到高价值阈值,剩余秒数在预约参与阈值内,立即参与",
|
||||
value_yuan=prize_value_yuan,
|
||||
threshold=high_value_threshold,
|
||||
remain_seconds=int(remain_seconds),
|
||||
countdown_threshold=skip_if_gt,
|
||||
join_ahead_threshold=join_ahead_seconds,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 不记录预约,继续执行后续的立即参与逻辑
|
||||
is_high_value = False
|
||||
else:
|
||||
# 剩余秒数大于"预约参与阈值",记录预约
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"basic_join_decision:价值达到高价值阈值,但剩余秒数大于预约参与阈值,记录预约",
|
||||
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,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if is_high_value:
|
||||
# 价值达到高价值阈值且剩余秒数大于阈值:记录预约而不是立即参与
|
||||
|
||||
@@ -455,10 +455,10 @@ def read_live_room_title_core(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# small ROI:最后兜底(历史区域)
|
||||
# small ROI:最后兜底(历史区域),使用优化后的坐标
|
||||
if not cands or max(len(x[0] or "") for x in cands) <= 1:
|
||||
try:
|
||||
analyser.cut_pic(138, 144, 335, 185, '', 'live_room_title_small', y_pianyi)
|
||||
analyser.cut_pic(147, 147, 320, 188, '', 'live_room_title_small', y_pianyi)
|
||||
t4, r4 = _ocr_try_room_title(analyser, 'live_room_title_small', 0)
|
||||
cands.append((t4, r4, 'small_cc0'))
|
||||
except Exception:
|
||||
|
||||
@@ -542,10 +542,6 @@ class FudaiDetector:
|
||||
# 直方图均衡化(增强对比度)
|
||||
search_roi_gray_enhanced = cv2.equalizeHist(search_roi_gray)
|
||||
template_gray_enhanced = cv2.equalizeHist(template_gray)
|
||||
|
||||
# 轻微高斯模糊去噪(可选)
|
||||
# search_roi_gray = cv2.GaussianBlur(search_roi_gray, (3, 3), 0)
|
||||
# template_gray = cv2.GaussianBlur(template_gray, (3, 3), 0)
|
||||
except Exception:
|
||||
search_roi_gray_enhanced = search_roi_gray
|
||||
template_gray_enhanced = template_gray
|
||||
|
||||
+33
-14
@@ -69,22 +69,41 @@ class DatedFileHandler(logging.FileHandler):
|
||||
)
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
"""发送日志记录,如果日期变化则切换到新文件"""
|
||||
today = datetime.now().strftime(self.date_format)
|
||||
if today != self.current_date:
|
||||
# 日期变化,关闭旧文件,打开新文件
|
||||
self.close()
|
||||
self.current_date = today
|
||||
self.current_filename = f"{self.base_filename}_{self.current_date}.log"
|
||||
"""发送日志记录,如果日期变化则切换到新文件(性能优化版本)"""
|
||||
# 优化:缓存日期检查,避免每次调用都执行 datetime.now().strftime()
|
||||
# 使用记录计数器和时间戳来减少日期检查频率
|
||||
if not hasattr(self, '_date_check_counter'):
|
||||
self._date_check_counter = 0
|
||||
self._last_date_check_time = datetime.now()
|
||||
|
||||
# 每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 today != self.current_date:
|
||||
# 日期变化,关闭旧文件,打开新文件
|
||||
self.close()
|
||||
self.current_date = today
|
||||
self.current_filename = f"{self.base_filename}_{self.current_date}.log"
|
||||
|
||||
# 确保目录存在
|
||||
log_dir = os.path.dirname(self.current_filename)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
# 确保目录存在
|
||||
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.baseFilename = self.current_filename
|
||||
self.stream = self._open()
|
||||
|
||||
# 重置计数器
|
||||
self._date_check_counter = 0
|
||||
|
||||
super().emit(record)
|
||||
|
||||
|
||||
@@ -357,3 +357,45 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
OCR耗時秒=f"{ocr_total:.3f}",
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def handle_lottery_result_popup(analyser) -> None:
|
||||
"""处理抽奖结果弹窗:点击"我知道了"或"领取并使用"按钮。
|
||||
|
||||
根据阶段诊断,已经确认是 FUDai_RESULT 阶段,这里只需要点击按钮关闭弹窗。
|
||||
按钮位置通常在屏幕中下部,坐标约 (540, 1400) 基于1080x2400。
|
||||
"""
|
||||
try:
|
||||
analyser._log_kv("开奖结果", "开始处理抽奖结果弹窗")
|
||||
|
||||
# 点击"我知道了"或"领取并使用"按钮(坐标基于1080x2400:540, 1400)
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
btn_x = int(540 * rx // 1080)
|
||||
btn_y = int(1400 * ry // 2400)
|
||||
|
||||
analyser.operation.click(analyser.device_id, btn_x, btn_y)
|
||||
analyser._log_kv("开奖结果", "已点击结果按钮", x=btn_x, y=btn_y)
|
||||
analyser.operation.delay(1.0)
|
||||
|
||||
# 如果还有弹窗,尝试再次点击或按返回键
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
import douyin_stage
|
||||
stage, _ = douyin_stage.diagnose_stage_from_current_screen(analyser)
|
||||
if stage == "FUDai_RESULT":
|
||||
# 仍在结果页,尝试按返回键
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
analyser._log_kv("开奖结果", "处理完成")
|
||||
except Exception as e:
|
||||
analyser._log_kv("开奖结果", "处理失败", error=str(e))
|
||||
# 失败时尝试按返回键
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
+144
-26
@@ -14,19 +14,49 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
"""
|
||||
import time
|
||||
|
||||
# 是否输出详细阶段诊断日志:
|
||||
# - False:只保留最终结果等精简日志
|
||||
# - True:输出完整步骤级诊断日志(便于排查问题)
|
||||
verbose: bool = bool(getattr(self, "stage_diag_verbose", False))
|
||||
|
||||
def _log(msg: str, **fields):
|
||||
"""阶段诊断统一日志入口,使用 self._log_kv 输出。"""
|
||||
"""阶段诊断详细日志入口:仅在 verbose=True 时输出。"""
|
||||
if not verbose:
|
||||
return
|
||||
try:
|
||||
self._log_kv("阶段诊断", msg, **fields)
|
||||
except Exception:
|
||||
# 兜底:避免任何日志异常影响主流程
|
||||
pass
|
||||
|
||||
def _log_summary(msg: str, **fields):
|
||||
"""阶段诊断精简日志入口:始终输出,用于记录最终结果等关键信息。"""
|
||||
try:
|
||||
self._log_kv("阶段诊断", msg, **fields)
|
||||
except Exception:
|
||||
# 兜底:避免任何日志异常影响主流程
|
||||
pass
|
||||
|
||||
def _log_separator(title: str = "", char: str = "="):
|
||||
"""输出简洁分隔符(仅在 verbose=True 时启用),方便阅读详细日志。"""
|
||||
if not verbose:
|
||||
return
|
||||
try:
|
||||
if title:
|
||||
msg = f"\n{char * 3} {title} {char * 3}\n"
|
||||
else:
|
||||
msg = f"\n{char * 10}\n"
|
||||
self._log_kv("阶段诊断", msg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
diag_start = time.time()
|
||||
max_diag_time = getattr(self, "stage_diag_max_time", 10.0) # 最大诊断时间(可配置,默认10秒)
|
||||
max_step_time = getattr(self, "stage_diag_max_step_time", 2.0) # 每个步骤最大耗时(可配置,默认2秒)
|
||||
enable_ocr_mode1 = bool(getattr(self, "enable_ocr_mode1", False)) # OCR模式1开关(二值化)
|
||||
|
||||
# 仅在详细模式下输出开始分隔符与起始信息
|
||||
_log_separator("开始阶段诊断")
|
||||
_log("开始阶段诊断", 最大诊断时间秒=max_diag_time, 单步最大耗时秒=max_step_time)
|
||||
|
||||
# ========== 步骤0:首先检测是否在直播间(最优先)==========
|
||||
@@ -151,7 +181,13 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=seen_text,
|
||||
)
|
||||
_log("阶段诊断完成", 阶段="RECOMMEND_PAGE", 原因=f"标题='{t_recommend}'")
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="RECOMMEND_PAGE",
|
||||
原因=f"标题='{t_recommend}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:RECOMMEND_PAGE(推荐页)")
|
||||
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
|
||||
|
||||
# 如果识别到"关注"但没有"推荐",可能是关注列表
|
||||
@@ -204,7 +240,13 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
self._last_follow_list_title_text = str(t_follow or "").strip()
|
||||
except Exception:
|
||||
self._last_follow_list_title_text = ""
|
||||
_log("阶段诊断完成", 阶段="FOLLOW_LIST", 原因=f"标题='{t_follow}'")
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="FOLLOW_LIST",
|
||||
原因=f"标题='{t_follow}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:FOLLOW_LIST(关注列表)")
|
||||
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
|
||||
|
||||
# 如果识别到"正在直播"标签,判定为直播列表
|
||||
@@ -253,7 +295,13 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=list_text,
|
||||
)
|
||||
_log("阶段诊断完成", 阶段="LIVE_LIST", 原因=f"标题='{t_list}'")
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="LIVE_LIST",
|
||||
原因=f"标题='{t_list}'",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:LIVE_LIST(直播列表)")
|
||||
return "LIVE_LIST", "标题='{}'".format(t_list)
|
||||
|
||||
# 记录诊断时看到的"关注页标题"
|
||||
@@ -284,11 +332,17 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
|
||||
# 如果不在直播间且OCR也未识别到特定页面,返回未知状态
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
_log("不在直播间且OCR未识别到特定页面", 总耗时毫秒=total_elapsed)
|
||||
_log("阶段诊断完成", 阶段="UNKNOWN", 原因="不在直播间且未识别到特定页面")
|
||||
_log_summary(
|
||||
"阶段诊断完成",
|
||||
阶段="UNKNOWN",
|
||||
原因="不在直播间且未识别到特定页面",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:UNKNOWN(未知状态)")
|
||||
return "UNKNOWN", "不在直播间且未识别到特定页面"
|
||||
|
||||
# ========== 在直播间:继续执行像素检测 ==========
|
||||
_log_separator("在直播间,继续执行像素检测")
|
||||
_log("在直播间,继续执行像素检测")
|
||||
|
||||
# ========== 第一步:基于同一张截图并行采集所有像素特征 ==========
|
||||
@@ -319,6 +373,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
|
||||
# 优先级1:抽奖结果弹窗(大片红色+我知道了)
|
||||
if pixel_state.get("has_lucky_draw_result", False):
|
||||
_log_separator("步骤1:检测抽奖结果弹窗")
|
||||
# 像素检测到抽奖结果弹窗,使用OCR兜底确认
|
||||
step_result_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
@@ -391,17 +446,19 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
if result_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
result_elapsed = (time.time() - step_result_start) * 1000
|
||||
_log(
|
||||
_log_summary(
|
||||
"阶段诊断完成(抽奖结果弹窗)",
|
||||
阶段="FUDai_RESULT",
|
||||
原因="像素检测+OCR确认(抽奖结果弹窗)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
结果检测耗时毫秒=result_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:FUDai_RESULT(抽奖结果弹窗)")
|
||||
return "FUDai_RESULT", "像素检测+OCR确认(抽奖结果弹窗)"
|
||||
|
||||
# 优先级1.5:购物红包弹窗检测(保持现有检测方式)
|
||||
if pixel_state.get("has_redpacket_bg", False):
|
||||
_log_separator("步骤1.5:检测购物红包弹窗")
|
||||
step_redpacket_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
_log("步骤1.5[检测购物红包弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到购物红包背景")
|
||||
@@ -441,7 +498,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
if redpacket_detected:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
|
||||
_log(
|
||||
_log_summary(
|
||||
"阶段诊断完成(购物红包弹窗)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="检测到购物红包弹窗",
|
||||
@@ -511,18 +568,20 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
if coupon_text and "开心收下" in coupon_text:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
coupon_elapsed = (time.time() - step_coupon_start) * 1000
|
||||
_log(
|
||||
_log_summary(
|
||||
"阶段诊断完成(优惠券弹窗)",
|
||||
阶段="COUPON_POPUP",
|
||||
原因="检测到开心收下(优惠券弹窗)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
优惠券检测耗时毫秒=coupon_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:COUPON_POPUP(优惠券弹窗)")
|
||||
return "COUPON_POPUP", "OCR确认(开心收下)"
|
||||
|
||||
# 优先级3:参与按钮/粉丝团加入区域(大片红色,需要OCR区分)
|
||||
# 注意:这两个检测区域重叠,检测到红色区域后需要用OCR区分是"加入粉丝团"还是"一键发表评论"
|
||||
if has_red_button_area:
|
||||
_log_separator("步骤2:OCR区分按钮类型(参与/粉丝团)")
|
||||
step_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
_log("步骤2[OCR区分按钮类型]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到红色按钮区域,需OCR区分类型")
|
||||
@@ -577,7 +636,13 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=t_button[:50] if t_button else "",
|
||||
)
|
||||
_log("阶段诊断完成(像素+OCR)", 阶段="FANSCLUB_JOIN", 原因=f"OCR识别:{t_button[:30]}")
|
||||
_log_summary(
|
||||
"阶段诊断完成(像素+OCR)",
|
||||
阶段="FANSCLUB_JOIN",
|
||||
原因=f"OCR识别:{t_button[:30]}",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:FANSCLUB_JOIN(粉丝团加入)")
|
||||
return "FANSCLUB_JOIN", f"像素检测+OCR确认(加入粉丝团)"
|
||||
elif "一键" in t_button or "发表" in t_button or "评论" in t_button or "参与" in t_button:
|
||||
_log(
|
||||
@@ -586,7 +651,13 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
总耗时毫秒=total_elapsed,
|
||||
识别文本=t_button[:50] if t_button else "",
|
||||
)
|
||||
_log("阶段诊断完成(像素+OCR)", 阶段="FUDai_DETAIL", 原因=f"OCR识别:{t_button[:30]}")
|
||||
_log_summary(
|
||||
"阶段诊断完成(像素+OCR)",
|
||||
阶段="FUDai_DETAIL",
|
||||
原因=f"OCR识别:{t_button[:30]}",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:FUDai_DETAIL(福袋详情页)")
|
||||
return "FUDai_DETAIL", f"像素检测+OCR确认(参与按钮)"
|
||||
else:
|
||||
# OCR未识别到明确文字,不判定为任何阶段(以OCR为准)
|
||||
@@ -604,7 +675,12 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
if detail_detected:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
_log("步骤1[像素检测福袋详情]-命中(并行检测)", 总耗时毫秒=total_elapsed)
|
||||
_log("阶段诊断完成(像素检测)", 阶段="FUDai_DETAIL", 原因="福袋详情页像素检测(并行)")
|
||||
_log_summary(
|
||||
"阶段诊断完成(像素检测)",
|
||||
阶段="FUDai_DETAIL",
|
||||
原因="福袋详情页像素检测(并行)",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
return "FUDai_DETAIL", "像素检测确认(福袋详情页,并行检测)"
|
||||
|
||||
# 如果并行检测未命中,使用"超级福袋"模板匹配作为补充(不再使用 OCR 兜底)
|
||||
@@ -653,10 +729,14 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
if threshold > 1.0:
|
||||
threshold = 1.0
|
||||
|
||||
# 保存模板匹配分数,用于后续判断是否跳过OCR检测
|
||||
template_match_score = float(max_val or 0.0)
|
||||
setattr(self, "_last_template_match_score", template_match_score)
|
||||
|
||||
elapsed = (time.time() - step_start) * 1000
|
||||
_log(
|
||||
"步骤1[福袋详情模板匹配]-结果",
|
||||
分数=round(float(max_val or 0.0), 4),
|
||||
分数=round(template_match_score, 4),
|
||||
阈值=threshold,
|
||||
耗时毫秒=elapsed,
|
||||
)
|
||||
@@ -666,14 +746,16 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
_log(
|
||||
"步骤1[福袋详情模板匹配]-命中",
|
||||
分数=round(float(max_val or 0.0), 4),
|
||||
分数=round(template_match_score, 4),
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log(
|
||||
_log_summary(
|
||||
"阶段诊断完成(模板匹配)",
|
||||
阶段="FUDai_DETAIL",
|
||||
原因="超级福袋模板匹配命中",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:FUDai_DETAIL(福袋详情页-模板匹配)")
|
||||
return "FUDai_DETAIL", "模板匹配确认(超级福袋)"
|
||||
else:
|
||||
elapsed = (time.time() - step_start) * 1000
|
||||
@@ -691,6 +773,9 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
模板存在=os.path.exists(tpl_path),
|
||||
耗时毫秒=elapsed,
|
||||
)
|
||||
# 文件不存在时设置默认值
|
||||
if not hasattr(self, "_last_template_match_score"):
|
||||
setattr(self, "_last_template_match_score", 0.0)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
elapsed = (time.time() - step_start) * 1000
|
||||
@@ -701,23 +786,47 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
异常信息=str(e),
|
||||
堆栈=traceback.format_exc(),
|
||||
)
|
||||
# 异常时设置默认值
|
||||
setattr(self, "_last_template_match_score", 0.0)
|
||||
|
||||
if detail_detected:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
_log("步骤1[像素检测福袋详情]-最终命中", 总耗时毫秒=total_elapsed)
|
||||
_log("阶段诊断完成(像素检测+OCR兜底)", 阶段="FUDai_DETAIL", 原因="福袋详情页检测")
|
||||
_log_summary(
|
||||
"阶段诊断完成(像素检测+OCR兜底)",
|
||||
阶段="FUDai_DETAIL",
|
||||
原因="福袋详情页检测",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
return "FUDai_DETAIL", "像素检测+OCR兜底确认(福袋详情页)"
|
||||
|
||||
# 额外检测:在指定区域检测"邀你抢红包"文字(用于检测红包/福袋详情页)
|
||||
# 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400)
|
||||
if not detail_detected:
|
||||
# 优化:当模板匹配分数很低(<0.4)时,说明明显不在福袋详情页,跳过OCR检测以节省时间
|
||||
enable_invite_redpacket_ocr = bool(getattr(self, "enable_invite_redpacket_ocr", True))
|
||||
template_match_score_threshold = float(getattr(self, "invite_redpacket_ocr_template_threshold", 0.4) or 0.4)
|
||||
# 获取模板匹配分数(如果存在),用于判断是否跳过OCR
|
||||
template_match_score = float(getattr(self, "_last_template_match_score", 0.0) or 0.0)
|
||||
should_skip_redpacket_ocr = (not detail_detected and template_match_score > 0 and template_match_score < template_match_score_threshold)
|
||||
|
||||
if should_skip_redpacket_ocr:
|
||||
_log(
|
||||
"步骤1.5[OCR检测邀你抢红包]-跳过(模板匹配分数过低)",
|
||||
模板匹配分数=template_match_score,
|
||||
阈值=template_match_score_threshold,
|
||||
说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间"
|
||||
)
|
||||
|
||||
if not detail_detected and enable_invite_redpacket_ocr and not should_skip_redpacket_ocr:
|
||||
step_ocr_redpacket_start = time.time()
|
||||
remaining_time_before = max_diag_time - (time.time() - diag_start)
|
||||
if remaining_time_before > max_step_time:
|
||||
# 为OCR检测设置更小的超时时间(默认1秒),避免长时间等待
|
||||
ocr_max_step_time = float(getattr(self, "invite_redpacket_ocr_max_step_time", 1.0) or 1.0)
|
||||
if remaining_time_before > ocr_max_step_time:
|
||||
try:
|
||||
_log("步骤1.5[OCR检测邀你抢红包]-开始", 剩余时间秒=remaining_time_before, 说明="在指定区域检测邀你抢红包文字")
|
||||
|
||||
if time.time() - step_ocr_redpacket_start < max_step_time:
|
||||
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
|
||||
cut_start = time.time()
|
||||
y_pianyi = int(getattr(self, "y_pianyi", 0) or 0)
|
||||
# 保存完整截图并标注OCR区域
|
||||
@@ -773,7 +882,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
cut_elapsed = (time.time() - cut_start) * 1000
|
||||
_log("步骤1.5[OCR检测邀你抢红包]-截图完成", 耗时毫秒=cut_elapsed)
|
||||
|
||||
if time.time() - step_ocr_redpacket_start < max_step_time:
|
||||
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
|
||||
ocr_start = time.time()
|
||||
ocr_text = str(self.operation.analyse_pic_word("阶段诊断邀你抢红包区域", 0) or "")
|
||||
ocr_elapsed = (time.time() - ocr_start) * 1000
|
||||
@@ -787,7 +896,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
# 如果模式0未识别到,尝试模式1
|
||||
enable_ocr_mode1 = bool(getattr(self, "enable_ocr_mode1", False))
|
||||
if enable_ocr_mode1 and (not ocr_text or not any(kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气"))):
|
||||
if time.time() - step_ocr_redpacket_start < max_step_time:
|
||||
if time.time() - step_ocr_redpacket_start < ocr_max_step_time:
|
||||
ocr_text = str(self.operation.analyse_pic_word("阶段诊断邀你抢红包区域", 1) or "")
|
||||
_log(
|
||||
"步骤1.5[OCR检测邀你抢红包]-OCR模式1",
|
||||
@@ -806,11 +915,12 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
总耗时毫秒=total_elapsed,
|
||||
OCR文本=ocr_text[:50],
|
||||
)
|
||||
_log(
|
||||
_log_summary(
|
||||
"阶段诊断完成(OCR检测邀你抢红包)",
|
||||
阶段="FUDai_DETAIL",
|
||||
原因="检测到邀你抢红包文字",
|
||||
OCR文本=ocr_text[:50],
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
return "FUDai_DETAIL", "OCR检测确认(邀你抢红包)"
|
||||
else:
|
||||
@@ -888,7 +998,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
if coupon_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log(
|
||||
_log_summary(
|
||||
"阶段诊断完成(优惠券弹窗-OCR确认)",
|
||||
阶段="COUPON_POPUP",
|
||||
原因="像素检测到背景+OCR确认(开心收下)",
|
||||
@@ -928,7 +1038,7 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
if redpacket_verified:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
|
||||
_log(
|
||||
_log_summary(
|
||||
"阶段诊断完成(购物红包弹窗-OCR确认)",
|
||||
阶段="SHOPPING_REDPACKET_POPUP",
|
||||
原因="像素检测到背景+OCR确认(购物红包)",
|
||||
@@ -1048,18 +1158,26 @@ def diagnose_stage_from_current_screen(self): # type: ignore[misc] # noqa: C90
|
||||
if in_live_room:
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
_log("所有阶段检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed)
|
||||
_log(
|
||||
_log_summary(
|
||||
"阶段诊断完成(在直播间)",
|
||||
阶段="IN_LIVE_ROOM",
|
||||
原因=f"识别到在直播间({detection_method}),其他阶段未识别",
|
||||
检测方法=detection_method,
|
||||
分数=live_room_score,
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:IN_LIVE_ROOM(在直播间)")
|
||||
return "IN_LIVE_ROOM", f"识别到在直播间({detection_method}),其他阶段未识别"
|
||||
|
||||
# 如果不在直播间,默认返回:在直播间内(IN_LIVE_ROOM)
|
||||
# 这种情况可能是检测失败,但为了流程继续,默认返回在直播间
|
||||
total_elapsed = (time.time() - diag_start) * 1000
|
||||
_log("所有像素检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed)
|
||||
_log("阶段诊断完成(像素检测)", 阶段="IN_LIVE_ROOM", 原因="像素检测未命中,默认直播间")
|
||||
_log_summary(
|
||||
"阶段诊断完成(像素检测)",
|
||||
阶段="IN_LIVE_ROOM",
|
||||
原因="像素检测未命中,默认直播间",
|
||||
总耗时毫秒=total_elapsed,
|
||||
)
|
||||
_log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)")
|
||||
return "IN_LIVE_ROOM", "像素检测未命中,默认直播间"
|
||||
+9
-7
@@ -54,10 +54,11 @@ def swipe_up_switch_live(analyser: Any) -> None:
|
||||
|
||||
|
||||
def swipe_down_back_live(analyser: Any) -> None:
|
||||
"""上划回退到上一个直播间(基础版封装)。
|
||||
"""下滑回退到上一个直播间(基础版封装)。
|
||||
|
||||
在直播间内,向上滑动可以回退到上一个直播间。
|
||||
采用 1080x2400 基准坐标,在屏幕中下部向上滑一段距离。
|
||||
在直播间内,向下滑动(从上往下)可以回退到上一个直播间。
|
||||
采用 1080x2400 基准坐标,在屏幕中上部向下滑一段距离。
|
||||
注意:这是与 swipe_up_switch_live 相反的方向。
|
||||
"""
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
@@ -70,11 +71,12 @@ def swipe_down_back_live(analyser: Any) -> None:
|
||||
|
||||
device_id = getattr(analyser, "device_id", "")
|
||||
|
||||
# 基准坐标(1080x2400):从中下部往上滑(与上滑切换相同方向)
|
||||
# 基准坐标(1080x2400):从上方往下滑(与上滑切换相反方向)
|
||||
# 回退操作:从上往下滑动(start_y < end_y)
|
||||
start_x_base = 540
|
||||
start_y_base = 1700
|
||||
start_y_base = 800 # 上方起始位置
|
||||
end_x_base = 540
|
||||
end_y_base = 700
|
||||
end_y_base = 1600 # 下方结束位置
|
||||
|
||||
start_x = start_x_base * rx // 1080
|
||||
end_x = end_x_base * rx // 1080
|
||||
@@ -84,7 +86,7 @@ def swipe_down_back_live(analyser: Any) -> None:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"滑动",
|
||||
"swipe_down_back_live:上划回退到上一个直播间",
|
||||
"swipe_down_back_live:下滑回退到上一个直播间",
|
||||
start_x=start_x_base,
|
||||
start_y=start_y_base,
|
||||
end_x=end_x_base,
|
||||
|
||||
@@ -95,3 +95,19 @@ def extract_participants_count(text: Optional[str]) -> int:
|
||||
return max(nums)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+332
-280
File diff suppressed because it is too large.
Load diff
@@ -42,6 +42,26 @@ paddlepaddle>=2.5.0,<3.0.0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -29,3 +29,19 @@ coverage>=7.3.0
|
||||
mypy>=1.5.0
|
||||
types-requests>=2.31.0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -58,6 +58,26 @@ ttkbootstrap>=1.10.0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -105,3 +105,19 @@ def main():
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+10
-10
@@ -1,19 +1,19 @@
|
||||
{
|
||||
"updated_ts": 1766338568.2483091,
|
||||
"updated_ts": 1766415324.1937325,
|
||||
"reason": "record_reservation",
|
||||
"room_pos": 3,
|
||||
"current_room_title": "云南名茶",
|
||||
"current_room_title_raw": "云南名茶。",
|
||||
"current_room_title": "小肉包",
|
||||
"current_room_title_raw": "小肉包",
|
||||
"reservations": [
|
||||
{
|
||||
"prize_value_yuan": 888.0,
|
||||
"content": "(福袋]云南名茶收藏馆专属盖碗+茶针",
|
||||
"future_ts": 1766338996.825995,
|
||||
"future_str": "2025-12-22 01:43:16",
|
||||
"prize_value_yuan": 1999.0,
|
||||
"content": "03|后开奖07(蓝牙耳机』五代蓝牙耳机pr0蓝牙耳机颜值蓝牙耳机755人巳参与",
|
||||
"future_ts": 1766415744.449139,
|
||||
"future_str": "2025-12-22 23:02:24",
|
||||
"pos_seen": 3,
|
||||
"room_title": "云南名茶",
|
||||
"room_title_raw": "云南名茶。",
|
||||
"created_ts": 1766338568.247795
|
||||
"room_title": "小肉包",
|
||||
"room_title_raw": "小肉包",
|
||||
"created_ts": 1766415324.1925805
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
"""
|
||||
GUI日志写入功能测试脚本
|
||||
用于验证GUI应用的日志文件写入功能是否正常工作
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import threading
|
||||
from datetime import datetime
|
||||
|
||||
# 确保在项目根目录
|
||||
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# 添加项目路径
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from path_config import get_logs_dir, PROJECT_ROOT
|
||||
from gui_core import read_config
|
||||
|
||||
def test_log_writer():
|
||||
"""测试日志写入器的基本功能"""
|
||||
print("=" * 60)
|
||||
print("测试1: 日志写入器基本功能")
|
||||
print("=" * 60)
|
||||
|
||||
# 导入GUI应用中的日志写入器类
|
||||
# 由于日志写入器是在main函数内部定义的,我们需要模拟它
|
||||
import threading
|
||||
import queue
|
||||
|
||||
class ThreadSafeLogWriter:
|
||||
"""线程安全的日志文件写入器"""
|
||||
|
||||
def __init__(self, log_dir: str | None = None):
|
||||
self._lock = threading.Lock()
|
||||
self._log_dir = log_dir or get_logs_dir()
|
||||
self._log_file_path: str = ""
|
||||
self._log_file_enabled: bool = True
|
||||
self._init_log_file()
|
||||
self._write_error_warned = False
|
||||
|
||||
def _init_log_file(self) -> None:
|
||||
"""初始化日志文件路径(按日期)"""
|
||||
try:
|
||||
os.makedirs(self._log_dir, exist_ok=True)
|
||||
cfg = read_config()
|
||||
self._log_file_enabled = bool(cfg.get("log_unified_enabled", True))
|
||||
log_path = cfg.get("log_unified_path") or "logs/unified.log"
|
||||
if not os.path.isabs(log_path):
|
||||
log_path = os.path.join(PROJECT_ROOT, log_path)
|
||||
use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True)
|
||||
if use_dated_logs:
|
||||
base_name = os.path.splitext(log_path)[0]
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
self._log_file_path = f"{base_name}_{today}.log"
|
||||
else:
|
||||
self._log_file_path = log_path
|
||||
except Exception as e:
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
self._log_file_path = os.path.join(self._log_dir, f"unified_{today}.log")
|
||||
print(f"[测试] 配置读取失败,使用默认路径: {e}")
|
||||
|
||||
def write(self, line: str) -> None:
|
||||
"""线程安全地写入日志行到文件"""
|
||||
if not self._log_file_enabled:
|
||||
return
|
||||
if not line or not line.strip():
|
||||
return
|
||||
with self._lock:
|
||||
try:
|
||||
cfg = read_config()
|
||||
use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True)
|
||||
if use_dated_logs:
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
current_base = os.path.splitext(self._log_file_path)[0]
|
||||
if not current_base.endswith(today):
|
||||
base_name = current_base.rsplit("_", 1)[0] if "_" in os.path.basename(current_base) else current_base
|
||||
self._log_file_path = f"{base_name}_{today}.log"
|
||||
log_dir = os.path.dirname(self._log_file_path)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
with open(
|
||||
self._log_file_path,
|
||||
"a",
|
||||
encoding="utf-8-sig",
|
||||
errors="replace"
|
||||
) as f:
|
||||
if line.strip() and not (line[0].isdigit() and " - [" in line):
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
formatted_line = f"{timestamp} - [GUI] - {line}\n"
|
||||
else:
|
||||
formatted_line = f"{line}\n"
|
||||
f.write(formatted_line)
|
||||
f.flush()
|
||||
except Exception as e:
|
||||
if not self._write_error_warned:
|
||||
print(f"[测试] 写入日志文件失败: {e}")
|
||||
self._write_error_warned = True
|
||||
|
||||
# 创建日志写入器
|
||||
writer = ThreadSafeLogWriter()
|
||||
print(f"[测试] 日志文件路径: {writer._log_file_path}")
|
||||
print(f"[测试] 日志目录: {writer._log_dir}")
|
||||
print(f"[测试] 日志启用状态: {writer._log_file_enabled}")
|
||||
|
||||
# 测试写入
|
||||
test_lines = [
|
||||
"这是一条测试日志",
|
||||
"2025-12-22 12:00:00.000 - [INFO] - 这是带时间戳的日志",
|
||||
"测试中文日志:你好世界",
|
||||
"测试特殊字符:!@#$%^&*()",
|
||||
]
|
||||
|
||||
print("\n[测试] 开始写入测试日志...")
|
||||
for line in test_lines:
|
||||
writer.write(line)
|
||||
print(f"[测试] 已写入: {line}")
|
||||
|
||||
# 验证文件是否存在
|
||||
if os.path.exists(writer._log_file_path):
|
||||
print(f"\n[测试] [OK] 日志文件已创建: {writer._log_file_path}")
|
||||
file_size = os.path.getsize(writer._log_file_path)
|
||||
print(f"[测试] [OK] 文件大小: {file_size} bytes")
|
||||
|
||||
# 读取文件内容验证
|
||||
with open(writer._log_file_path, "r", encoding="utf-8-sig") as f:
|
||||
content = f.read()
|
||||
lines = content.strip().split("\n")
|
||||
print(f"[测试] [OK] 文件包含 {len(lines)} 行")
|
||||
print("\n[测试] 文件内容预览(最后5行):")
|
||||
for line in lines[-5:]:
|
||||
print(f" {line}")
|
||||
else:
|
||||
print(f"\n[测试] [FAIL] 日志文件未创建: {writer._log_file_path}")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def test_thread_safety():
|
||||
"""测试多线程环境下的日志写入安全性"""
|
||||
print("\n" + "=" * 60)
|
||||
print("测试2: 多线程安全性")
|
||||
print("=" * 60)
|
||||
|
||||
# 使用与上面相同的日志写入器类
|
||||
import threading
|
||||
|
||||
class ThreadSafeLogWriter:
|
||||
def __init__(self, log_dir: str | None = None):
|
||||
self._lock = threading.Lock()
|
||||
self._log_dir = log_dir or get_logs_dir()
|
||||
self._log_file_path: str = ""
|
||||
self._log_file_enabled: bool = True
|
||||
self._init_log_file()
|
||||
self._write_error_warned = False
|
||||
|
||||
def _init_log_file(self) -> None:
|
||||
try:
|
||||
os.makedirs(self._log_dir, exist_ok=True)
|
||||
cfg = read_config()
|
||||
self._log_file_enabled = bool(cfg.get("log_unified_enabled", True))
|
||||
log_path = cfg.get("log_unified_path") or "logs/unified.log"
|
||||
if not os.path.isabs(log_path):
|
||||
log_path = os.path.join(PROJECT_ROOT, log_path)
|
||||
use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True)
|
||||
if use_dated_logs:
|
||||
base_name = os.path.splitext(log_path)[0]
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
self._log_file_path = f"{base_name}_{today}.log"
|
||||
else:
|
||||
self._log_file_path = log_path
|
||||
except Exception:
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
self._log_file_path = os.path.join(self._log_dir, f"unified_{today}.log")
|
||||
|
||||
def write(self, line: str) -> None:
|
||||
if not self._log_file_enabled or not line or not line.strip():
|
||||
return
|
||||
with self._lock:
|
||||
try:
|
||||
log_dir = os.path.dirname(self._log_file_path)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
with open(self._log_file_path, "a", encoding="utf-8-sig", errors="replace") as f:
|
||||
if line.strip() and not (line[0].isdigit() and " - [" in line):
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
formatted_line = f"{timestamp} - [GUI] - {line}\n"
|
||||
else:
|
||||
formatted_line = f"{line}\n"
|
||||
f.write(formatted_line)
|
||||
f.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
writer = ThreadSafeLogWriter()
|
||||
|
||||
# 创建多个线程同时写入
|
||||
def write_thread(thread_id: int, count: int):
|
||||
for i in range(count):
|
||||
writer.write(f"[线程{thread_id}] 日志消息 {i+1}")
|
||||
time.sleep(0.001) # 短暂延迟模拟真实场景
|
||||
|
||||
num_threads = 5
|
||||
messages_per_thread = 20
|
||||
|
||||
print(f"[测试] 启动 {num_threads} 个线程,每个线程写入 {messages_per_thread} 条消息...")
|
||||
|
||||
threads = []
|
||||
for i in range(num_threads):
|
||||
t = threading.Thread(target=write_thread, args=(i+1, messages_per_thread))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
|
||||
# 等待所有线程完成
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
print("[测试] 所有线程已完成写入")
|
||||
|
||||
# 验证文件完整性
|
||||
if os.path.exists(writer._log_file_path):
|
||||
with open(writer._log_file_path, "r", encoding="utf-8-sig") as f:
|
||||
content = f.read()
|
||||
lines = [l for l in content.strip().split("\n") if l.strip()]
|
||||
expected_lines = num_threads * messages_per_thread
|
||||
print(f"[测试] [OK] 文件包含 {len(lines)} 行(预期约 {expected_lines} 行)")
|
||||
|
||||
# 检查是否有重复或丢失
|
||||
thread_counts = {}
|
||||
for line in lines:
|
||||
if "[线程" in line:
|
||||
thread_id = line.split("[线程")[1].split("]")[0]
|
||||
thread_counts[thread_id] = thread_counts.get(thread_id, 0) + 1
|
||||
|
||||
print(f"[测试] [OK] 各线程写入统计:")
|
||||
for thread_id in sorted(thread_counts.keys()):
|
||||
print(f" 线程{thread_id}: {thread_counts[thread_id]} 条")
|
||||
|
||||
return True
|
||||
else:
|
||||
print("[测试] [FAIL] 日志文件未创建")
|
||||
return False
|
||||
|
||||
|
||||
def test_log_file_integrity():
|
||||
"""测试日志文件完整性"""
|
||||
print("\n" + "=" * 60)
|
||||
print("测试3: 日志文件完整性检查")
|
||||
print("=" * 60)
|
||||
|
||||
log_dir = get_logs_dir()
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# 查找今天的日志文件
|
||||
log_files = []
|
||||
if os.path.exists(log_dir):
|
||||
for fname in os.listdir(log_dir):
|
||||
if fname.endswith(f"_{today}.log") or fname == "unified.log":
|
||||
log_files.append(os.path.join(log_dir, fname))
|
||||
|
||||
if not log_files:
|
||||
print("[测试] [FAIL] 未找到日志文件")
|
||||
return False
|
||||
|
||||
print(f"[测试] 找到 {len(log_files)} 个日志文件:")
|
||||
for log_file in log_files:
|
||||
print(f" - {log_file}")
|
||||
|
||||
if os.path.exists(log_file):
|
||||
file_size = os.path.getsize(log_file)
|
||||
print(f" 大小: {file_size} bytes")
|
||||
|
||||
# 读取文件检查格式
|
||||
try:
|
||||
with open(log_file, "r", encoding="utf-8-sig") as f:
|
||||
lines = f.readlines()
|
||||
print(f" 行数: {len(lines)}")
|
||||
|
||||
# 检查最后几行的格式
|
||||
if lines:
|
||||
print(" 最后3行示例:")
|
||||
for line in lines[-3:]:
|
||||
line = line.strip()
|
||||
if line:
|
||||
print(f" {line[:80]}...")
|
||||
except Exception as e:
|
||||
print(f" [FAIL] 读取文件失败: {e}")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("GUI日志写入功能测试")
|
||||
print("=" * 60)
|
||||
|
||||
results = []
|
||||
|
||||
# 运行测试
|
||||
try:
|
||||
results.append(("基本功能", test_log_writer()))
|
||||
results.append(("线程安全", test_thread_safety()))
|
||||
results.append(("文件完整性", test_log_file_integrity()))
|
||||
except Exception as e:
|
||||
print(f"\n[错误] 测试过程中发生异常: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
|
||||
# 汇总结果
|
||||
print("\n" + "=" * 60)
|
||||
print("测试结果汇总")
|
||||
print("=" * 60)
|
||||
all_passed = True
|
||||
for test_name, passed in results:
|
||||
status = "[PASS] 通过" if passed else "[FAIL] 失败"
|
||||
print(f"{test_name}: {status}")
|
||||
if not passed:
|
||||
all_passed = False
|
||||
|
||||
if all_passed:
|
||||
print("\n[总结] 所有测试通过!日志写入功能正常。")
|
||||
sys.exit(0)
|
||||
else:
|
||||
print("\n[总结] 部分测试失败,请检查日志写入功能。")
|
||||
sys.exit(1)
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
"""
|
||||
GUI日志实时测试脚本
|
||||
通过运行run_cli.py来测试日志写入功能
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
|
||||
# 确保在项目根目录
|
||||
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from path_config import get_logs_dir, PROJECT_ROOT
|
||||
|
||||
def get_log_file_path():
|
||||
"""获取今天的日志文件路径"""
|
||||
log_dir = get_logs_dir()
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# 读取配置
|
||||
try:
|
||||
import json
|
||||
config_path = os.path.join(PROJECT_ROOT, "config.json")
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
log_path = config.get("log_unified_path") or "logs/unified.log"
|
||||
if not os.path.isabs(log_path):
|
||||
log_path = os.path.join(PROJECT_ROOT, log_path)
|
||||
use_dated_logs = config.get("logging", {}).get("use_dated_logs", True)
|
||||
if use_dated_logs:
|
||||
base_name = os.path.splitext(log_path)[0]
|
||||
return f"{base_name}_{today}.log"
|
||||
return log_path
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 默认路径
|
||||
return os.path.join(log_dir, f"unified_{today}.log")
|
||||
|
||||
|
||||
def check_log_file(log_file_path: str, duration: int = 30):
|
||||
"""检查日志文件在指定时间内的写入情况"""
|
||||
print("=" * 60)
|
||||
print("GUI日志实时测试")
|
||||
print("=" * 60)
|
||||
print(f"日志文件路径: {log_file_path}")
|
||||
print(f"测试时长: {duration} 秒")
|
||||
print()
|
||||
|
||||
# 检查日志文件是否存在
|
||||
if not os.path.exists(log_file_path):
|
||||
print(f"[警告] 日志文件不存在: {log_file_path}")
|
||||
print("[信息] 等待日志文件创建...")
|
||||
wait_time = 0
|
||||
while not os.path.exists(log_file_path) and wait_time < 10:
|
||||
time.sleep(1)
|
||||
wait_time += 1
|
||||
if not os.path.exists(log_file_path):
|
||||
print("[错误] 日志文件未创建,测试失败")
|
||||
return False
|
||||
|
||||
# 记录初始状态
|
||||
initial_size = os.path.getsize(log_file_path)
|
||||
print(f"[初始] 日志文件大小: {initial_size} bytes")
|
||||
|
||||
# 读取初始行数
|
||||
with open(log_file_path, "r", encoding="utf-8-sig") as f:
|
||||
initial_lines = len(f.readlines())
|
||||
print(f"[初始] 日志文件行数: {initial_lines}")
|
||||
|
||||
# 记录最后几行
|
||||
with open(log_file_path, "r", encoding="utf-8-sig") as f:
|
||||
lines = f.readlines()
|
||||
if lines:
|
||||
print("\n[初始] 最后3行日志:")
|
||||
for line in lines[-3:]:
|
||||
print(f" {line.rstrip()}")
|
||||
|
||||
print(f"\n[测试] 开始监控日志文件 {duration} 秒...")
|
||||
print("[测试] 请确保GUI应用正在运行并执行核心功能")
|
||||
|
||||
# 监控日志文件变化
|
||||
check_interval = 5 # 每5秒检查一次
|
||||
checks = duration // check_interval
|
||||
last_size = initial_size
|
||||
last_line_count = initial_lines
|
||||
|
||||
for i in range(checks):
|
||||
time.sleep(check_interval)
|
||||
|
||||
if not os.path.exists(log_file_path):
|
||||
print(f"[错误] 日志文件在检查 {i+1} 时消失")
|
||||
return False
|
||||
|
||||
current_size = os.path.getsize(log_file_path)
|
||||
with open(log_file_path, "r", encoding="utf-8-sig") as f:
|
||||
current_lines = len(f.readlines())
|
||||
|
||||
size_diff = current_size - last_size
|
||||
line_diff = current_lines - last_line_count
|
||||
|
||||
elapsed = (i + 1) * check_interval
|
||||
print(f"[{elapsed:3d}s] 大小: {current_size:6d} bytes (+{size_diff:5d}) | "
|
||||
f"行数: {current_lines:4d} (+{line_diff:3d})")
|
||||
|
||||
last_size = current_size
|
||||
last_line_count = current_lines
|
||||
|
||||
# 最终检查
|
||||
print("\n" + "=" * 60)
|
||||
print("测试结果")
|
||||
print("=" * 60)
|
||||
|
||||
final_size = os.path.getsize(log_file_path)
|
||||
with open(log_file_path, "r", encoding="utf-8-sig") as f:
|
||||
final_lines = len(f.readlines())
|
||||
|
||||
total_size_diff = final_size - initial_size
|
||||
total_line_diff = final_lines - initial_lines
|
||||
|
||||
print(f"初始大小: {initial_size} bytes")
|
||||
print(f"最终大小: {final_size} bytes")
|
||||
print(f"增加大小: {total_size_diff} bytes")
|
||||
print(f"初始行数: {initial_lines}")
|
||||
print(f"最终行数: {final_lines}")
|
||||
print(f"增加行数: {total_line_diff}")
|
||||
|
||||
# 检查日志格式
|
||||
print("\n[验证] 检查日志格式...")
|
||||
with open(log_file_path, "r", encoding="utf-8-sig") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
format_ok = True
|
||||
timestamp_ok = True
|
||||
|
||||
# 检查最后10行的格式
|
||||
check_lines = lines[-10:] if len(lines) >= 10 else lines
|
||||
for line in check_lines:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
# 检查时间戳格式
|
||||
if not (line[0].isdigit() and " - [" in line):
|
||||
# 如果没有时间戳,检查是否是GUI添加的
|
||||
if "[GUI] -" not in line:
|
||||
format_ok = False
|
||||
print(f" [警告] 格式异常: {line[:80]}")
|
||||
|
||||
# 检查时间戳格式(YYYY-MM-DD HH:MM:SS)
|
||||
if line[0].isdigit():
|
||||
try:
|
||||
date_part = line.split(" - ")[0]
|
||||
datetime.strptime(date_part[:19], "%Y-%m-%d %H:%M:%S")
|
||||
except Exception:
|
||||
timestamp_ok = False
|
||||
print(f" [警告] 时间戳格式异常: {line[:80]}")
|
||||
|
||||
print(f"\n[结果] 日志文件写入: {'正常' if total_line_diff > 0 else '异常'}")
|
||||
print(f"[结果] 日志格式检查: {'通过' if format_ok else '失败'}")
|
||||
print(f"[结果] 时间戳格式检查: {'通过' if timestamp_ok else '失败'}")
|
||||
|
||||
# 显示最后5行
|
||||
print("\n[最终] 最后5行日志:")
|
||||
for line in lines[-5:]:
|
||||
print(f" {line.rstrip()}")
|
||||
|
||||
# 判断测试是否通过
|
||||
if total_line_diff > 0 and format_ok and timestamp_ok:
|
||||
print("\n[总结] 测试通过!日志写入功能正常。")
|
||||
return True
|
||||
else:
|
||||
print("\n[总结] 测试失败,请检查日志写入功能。")
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
log_file = get_log_file_path()
|
||||
success = check_log_file(log_file, duration=30)
|
||||
sys.exit(0 if success else 1)
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""调试日志写入问题"""
|
||||
import douyin_logging
|
||||
douyin_logging.configure_logging()
|
||||
|
||||
import logging
|
||||
root = logging.getLogger()
|
||||
print(f"Root logger handlers: {len(root.handlers)}")
|
||||
for i, h in enumerate(root.handlers):
|
||||
print(f" Handler {i+1}: {type(h).__name__}, level: {h.level}")
|
||||
|
||||
print(f"Root logger level: {root.level}")
|
||||
print(f"Root logger effective level: {root.getEffectiveLevel()}")
|
||||
|
||||
# 测试直接写入根 logger
|
||||
root.info("直接写入根 logger 的测试日志")
|
||||
import time
|
||||
time.sleep(0.5)
|
||||
|
||||
# 测试 fudai_analyse
|
||||
from douyin_fudai import fudai_analyse
|
||||
a = fudai_analyse()
|
||||
|
||||
# 检查 _std_logger
|
||||
if hasattr(a, '_std_logger') and a._std_logger is not None:
|
||||
print(f"_std_logger: {a._std_logger}")
|
||||
print(f"_std_logger handlers: {len(a._std_logger.handlers)}")
|
||||
print(f"_std_logger propagate: {a._std_logger.propagate}")
|
||||
|
||||
# 写入日志
|
||||
a._log_kv("调试", "这是调试日志", debug_field="debug_value")
|
||||
time.sleep(0.5)
|
||||
|
||||
# 检查日志文件
|
||||
from datetime import datetime
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
log_file = f"logs/unified_{today}.log"
|
||||
|
||||
import os
|
||||
if os.path.exists(log_file):
|
||||
with open(log_file, 'r', encoding='utf-8') as f:
|
||||
lines = f.readlines()
|
||||
print(f"\nLog file lines: {len(lines)}")
|
||||
print("Last 5 lines:")
|
||||
for line in lines[-5:]:
|
||||
print(f" {line.rstrip()}")
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""最终测试日志写入"""
|
||||
import douyin_logging
|
||||
douyin_logging.configure_logging()
|
||||
|
||||
from douyin_fudai import fudai_analyse
|
||||
import logging
|
||||
import time
|
||||
|
||||
root = logging.getLogger()
|
||||
print(f"Root logger handlers: {len(root.handlers)}")
|
||||
|
||||
a = fudai_analyse()
|
||||
a._log_kv("GUI测试", "这是来自GUI的测试日志", test_field="test_value")
|
||||
|
||||
time.sleep(0.5)
|
||||
|
||||
# 读取日志文件
|
||||
from datetime import datetime
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
log_file = f"logs/unified_{today}.log"
|
||||
|
||||
import os
|
||||
if os.path.exists(log_file):
|
||||
with open(log_file, 'r', encoding='utf-8') as f:
|
||||
lines = f.readlines()
|
||||
print(f"Log file lines: {len(lines)}")
|
||||
print("Last 3 lines:")
|
||||
for line in lines[-3:]:
|
||||
print(f" {line.rstrip()}")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""最终检查日志写入"""
|
||||
import douyin_logging
|
||||
douyin_logging.configure_logging()
|
||||
|
||||
import logging
|
||||
root = logging.getLogger()
|
||||
print(f"Root logger handlers: {len(root.handlers)}")
|
||||
|
||||
from douyin_fudai import fudai_analyse
|
||||
a = fudai_analyse()
|
||||
|
||||
# 测试 _log_kv
|
||||
print("Calling _log_kv...")
|
||||
a._log_kv("最终测试", "这是最终测试日志", test_field="test_value")
|
||||
print("_log_kv called")
|
||||
|
||||
import time
|
||||
time.sleep(1)
|
||||
|
||||
# 检查日志文件
|
||||
from datetime import datetime
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
log_file = f"logs/unified_{today}.log"
|
||||
|
||||
import os
|
||||
if os.path.exists(log_file):
|
||||
with open(log_file, 'r', encoding='utf-8') as f:
|
||||
lines = f.readlines()
|
||||
print(f"\nLog file total lines: {len(lines)}")
|
||||
print("Last 3 lines:")
|
||||
for line in lines[-3:]:
|
||||
print(f" {line.rstrip()}")
|
||||
|
||||
# 检查是否有"最终测试"相关的日志
|
||||
found = False
|
||||
for line in lines:
|
||||
if "最终测试" in line or "test_value" in line:
|
||||
print(f"\nFound log entry: {line.rstrip()}")
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
print("\n[WARNING] Log entry not found in file!")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""
|
||||
测试 GUI 启动时的日志写入
|
||||
模拟 GUI 启动 run_cli.py 的过程
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
# 确保在项目根目录
|
||||
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# 首先配置日志系统
|
||||
print("=" * 60)
|
||||
print("步骤1: 配置日志系统")
|
||||
print("=" * 60)
|
||||
try:
|
||||
import douyin_logging
|
||||
douyin_logging.configure_logging()
|
||||
print("[OK] 日志系统配置成功")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 日志系统配置失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
# 检查日志文件
|
||||
print("\n" + "=" * 60)
|
||||
print("步骤2: 检查日志文件")
|
||||
print("=" * 60)
|
||||
import path_config
|
||||
log_dir = path_config.get_logs_dir()
|
||||
print(f"日志目录: {log_dir}")
|
||||
print(f"日志目录存在: {os.path.exists(log_dir)}")
|
||||
|
||||
# 查找今天的日志文件
|
||||
from datetime import datetime
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
log_file = os.path.join(log_dir, f"unified_{today}.log")
|
||||
print(f"今天的日志文件: {log_file}")
|
||||
print(f"日志文件存在: {os.path.exists(log_file)}")
|
||||
if os.path.exists(log_file):
|
||||
size_before = os.path.getsize(log_file)
|
||||
print(f"日志文件大小(测试前): {size_before} bytes")
|
||||
# 读取最后几行
|
||||
with open(log_file, 'r', encoding='utf-8') as f:
|
||||
lines = f.readlines()
|
||||
print(f"日志文件行数: {len(lines)}")
|
||||
if lines:
|
||||
print("最后3行:")
|
||||
for line in lines[-3:]:
|
||||
print(f" {line.rstrip()}")
|
||||
|
||||
# 测试日志写入
|
||||
print("\n" + "=" * 60)
|
||||
print("步骤3: 测试日志写入")
|
||||
print("=" * 60)
|
||||
try:
|
||||
import logging
|
||||
logger = logging.getLogger("test.gui")
|
||||
logger.info("这是一条测试日志 - GUI 启动测试")
|
||||
logger.warning("这是一条警告日志 - GUI 启动测试")
|
||||
print("[OK] 日志写入测试完成")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 日志写入测试失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
# 检查日志文件是否更新
|
||||
if os.path.exists(log_file):
|
||||
time.sleep(0.5) # 等待文件写入
|
||||
size_after = os.path.getsize(log_file)
|
||||
print(f"\n日志文件大小(测试后): {size_after} bytes")
|
||||
print(f"大小变化: {size_after - size_before} bytes")
|
||||
|
||||
# 读取新内容
|
||||
with open(log_file, 'r', encoding='utf-8') as f:
|
||||
lines = f.readlines()
|
||||
print(f"日志文件行数(测试后): {len(lines)}")
|
||||
if len(lines) > len(lines) if 'lines' in locals() else 0:
|
||||
print("新增的最后3行:")
|
||||
for line in lines[-3:]:
|
||||
print(f" {line.rstrip()}")
|
||||
|
||||
# 测试 fudai_analyse 实例化
|
||||
print("\n" + "=" * 60)
|
||||
print("步骤4: 测试 fudai_analyse 实例化")
|
||||
print("=" * 60)
|
||||
try:
|
||||
from douyin_fudai import fudai_analyse
|
||||
analyser = fudai_analyse()
|
||||
print("[OK] fudai_analyse 实例化成功")
|
||||
|
||||
# 测试日志写入
|
||||
analyser._log_kv("测试", "这是一条来自 fudai_analyse 的测试日志")
|
||||
print("[OK] _log_kv 调用成功")
|
||||
|
||||
# 检查 _std_logger
|
||||
if hasattr(analyser, '_std_logger') and analyser._std_logger:
|
||||
print(f"[OK] _std_logger 已初始化: {analyser._std_logger}")
|
||||
print(f" Logger 名称: {analyser._std_logger.name}")
|
||||
print(f" Logger 级别: {analyser._std_logger.level}")
|
||||
print(f" Handlers 数量: {len(analyser._std_logger.handlers)}")
|
||||
for i, handler in enumerate(analyser._std_logger.handlers):
|
||||
print(f" Handler {i+1}: {type(handler).__name__}")
|
||||
else:
|
||||
print("[ERROR] _std_logger 未初始化")
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ERROR] fudai_analyse 实例化失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
# 再次检查日志文件
|
||||
if os.path.exists(log_file):
|
||||
time.sleep(0.5) # 等待文件写入
|
||||
size_final = os.path.getsize(log_file)
|
||||
print(f"\n日志文件大小(最终): {size_final} bytes")
|
||||
|
||||
# 读取最新内容
|
||||
with open(log_file, 'r', encoding='utf-8') as f:
|
||||
lines = f.readlines()
|
||||
print(f"日志文件行数(最终): {len(lines)}")
|
||||
if lines:
|
||||
print("最新的5行:")
|
||||
for line in lines[-5:]:
|
||||
print(f" {line.rstrip()}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("测试完成")
|
||||
print("=" * 60)
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"""真机测试:验证GUI日志写入功能"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
|
||||
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from path_config import get_logs_dir, PROJECT_ROOT
|
||||
|
||||
def get_log_file():
|
||||
"""获取今天的日志文件路径"""
|
||||
log_dir = get_logs_dir()
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
import json
|
||||
config_path = os.path.join(PROJECT_ROOT, "config.json")
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
log_path = config.get("log_unified_path") or "logs/unified.log"
|
||||
if not os.path.isabs(log_path):
|
||||
log_path = os.path.join(PROJECT_ROOT, log_path)
|
||||
use_dated_logs = config.get("logging", {}).get("use_dated_logs", True)
|
||||
if use_dated_logs:
|
||||
base_name = os.path.splitext(log_path)[0]
|
||||
return f"{base_name}_{today}.log"
|
||||
return log_path
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return os.path.join(log_dir, f"unified_{today}.log")
|
||||
|
||||
|
||||
def main():
|
||||
print("=" * 60)
|
||||
print("GUI日志真机测试")
|
||||
print("=" * 60)
|
||||
|
||||
log_file = get_log_file()
|
||||
print(f"日志文件: {log_file}")
|
||||
|
||||
# 检查初始状态
|
||||
if os.path.exists(log_file):
|
||||
initial_size = os.path.getsize(log_file)
|
||||
with open(log_file, "r", encoding="utf-8-sig") as f:
|
||||
initial_lines = len(f.readlines())
|
||||
print(f"初始大小: {initial_size} bytes")
|
||||
print(f"初始行数: {initial_lines}")
|
||||
else:
|
||||
initial_size = 0
|
||||
initial_lines = 0
|
||||
print("日志文件不存在,等待创建...")
|
||||
|
||||
# 启动run_cli.py进行测试
|
||||
print("\n[测试] 启动run_cli.py进行30秒测试...")
|
||||
print("[测试] 设备ID: MB75DEFQZHZTGMLJ")
|
||||
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "run_cli.py", "--wait-minutes", "0", "--device-id", "MB75DEFQZHZTGMLJ"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
cwd=os.path.dirname(__file__)
|
||||
)
|
||||
|
||||
print("[测试] 进程已启动,等待30秒...")
|
||||
|
||||
# 每5秒检查一次日志文件
|
||||
for i in range(6):
|
||||
time.sleep(5)
|
||||
elapsed = (i + 1) * 5
|
||||
if os.path.exists(log_file):
|
||||
current_size = os.path.getsize(log_file)
|
||||
with open(log_file, "r", encoding="utf-8-sig") as f:
|
||||
current_lines = len(f.readlines())
|
||||
print(f"[{elapsed:2d}s] 大小: {current_size:6d} bytes | 行数: {current_lines:4d}")
|
||||
else:
|
||||
print(f"[{elapsed:2d}s] 日志文件尚未创建")
|
||||
|
||||
print("\n[测试] 30秒已过,终止进程...")
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
|
||||
print("[测试] 进程已终止")
|
||||
|
||||
except Exception as e:
|
||||
print(f"[错误] 启动测试失败: {e}")
|
||||
return False
|
||||
|
||||
# 最终检查
|
||||
print("\n" + "=" * 60)
|
||||
print("测试结果")
|
||||
print("=" * 60)
|
||||
|
||||
if not os.path.exists(log_file):
|
||||
print("[失败] 日志文件未创建")
|
||||
return False
|
||||
|
||||
final_size = os.path.getsize(log_file)
|
||||
with open(log_file, "r", encoding="utf-8-sig") as f:
|
||||
final_lines = len(f.readlines())
|
||||
|
||||
size_diff = final_size - initial_size
|
||||
line_diff = final_lines - initial_lines
|
||||
|
||||
print(f"初始大小: {initial_size} bytes")
|
||||
print(f"最终大小: {final_size} bytes")
|
||||
print(f"增加大小: {size_diff} bytes")
|
||||
print(f"初始行数: {initial_lines}")
|
||||
print(f"最终行数: {final_lines}")
|
||||
print(f"增加行数: {line_diff}")
|
||||
|
||||
# 检查日志格式
|
||||
print("\n[验证] 检查日志格式...")
|
||||
with open(log_file, "r", encoding="utf-8-sig") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
# 检查最后10行
|
||||
check_lines = lines[-10:] if len(lines) >= 10 else lines
|
||||
format_ok = True
|
||||
|
||||
print("\n最后10行日志:")
|
||||
for i, line in enumerate(check_lines, 1):
|
||||
line = line.strip()
|
||||
if line:
|
||||
print(f" {i:2d}. {line[:100]}")
|
||||
# 检查格式
|
||||
if not (line[0].isdigit() and " - [" in line):
|
||||
if "[GUI] -" not in line:
|
||||
format_ok = False
|
||||
|
||||
# 判断结果
|
||||
print("\n" + "=" * 60)
|
||||
if size_diff > 0 and line_diff > 0 and format_ok:
|
||||
print("[结果] 测试通过!日志写入功能正常。")
|
||||
return True
|
||||
else:
|
||||
print("[结果] 测试失败。")
|
||||
if size_diff <= 0:
|
||||
print(" - 日志文件大小未增加")
|
||||
if line_diff <= 0:
|
||||
print(" - 日志文件行数未增加")
|
||||
if not format_ok:
|
||||
print(" - 日志格式异常")
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = main()
|
||||
sys.exit(0 if success else 1)
|
||||
|
||||
@@ -174,3 +174,19 @@ pytest --pdb --pdbcls=IPython.terminal.debugger:Pdb
|
||||
- [pytest-cov文档](https://pytest-cov.readthedocs.io/)
|
||||
- [unittest.mock文档](https://docs.python.org/3/library/unittest.mock.html)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -11,3 +11,19 @@
|
||||
|
||||
__version__ = "1.0.0"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -201,3 +201,19 @@ def mock_time(monkeypatch):
|
||||
# 标记:需要真实设备的测试
|
||||
pytest_plugins = []
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,2 +1,18 @@
|
||||
"""集成测试模块"""
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -58,3 +58,19 @@ class TestConfigLoading:
|
||||
|
||||
assert analyser._no_attend_timeout_minutes == 60.0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -43,3 +43,19 @@ class TestFudaiAnalyseInit:
|
||||
assert hasattr(analyser.__class__, "BACK_KEY_CLICK_DELAY")
|
||||
assert analyser.__class__.BACK_KEY_CLICK_DELAY == 1.0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,2 +1,18 @@
|
||||
"""单元测试模块"""
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ douyin_fudai_core模块测试
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import time
|
||||
from unittest.mock import Mock, patch
|
||||
from douyin_fudai_core import (
|
||||
should_skip_fudai_by_config,
|
||||
@@ -10,6 +11,31 @@ from douyin_fudai_core import (
|
||||
)
|
||||
|
||||
|
||||
def _create_detail_tuple(
|
||||
content: str = "测试福袋",
|
||||
time_text: str = "01:00",
|
||||
participants: int = 100,
|
||||
copies: int = 1,
|
||||
prize_value_yuan: float = 10.0,
|
||||
countdown_seconds: float = 60.0,
|
||||
) -> tuple:
|
||||
"""创建测试用的 detail 元组
|
||||
|
||||
detail 格式: (content, time_text, participants, copies, prize_value_yuan, (countdown_start, countdown_end))
|
||||
"""
|
||||
now = time.time()
|
||||
countdown_start = now
|
||||
countdown_end = now + countdown_seconds
|
||||
return (
|
||||
content,
|
||||
time_text,
|
||||
participants,
|
||||
copies,
|
||||
prize_value_yuan,
|
||||
(countdown_start, countdown_end),
|
||||
)
|
||||
|
||||
|
||||
class TestShouldSkipFudaiByConfig:
|
||||
"""福袋筛选配置测试"""
|
||||
|
||||
@@ -17,68 +43,44 @@ class TestShouldSkipFudaiByConfig:
|
||||
"""测试按最小价值筛选"""
|
||||
mock_analyser.min_prize_value_yuan = 10.0
|
||||
# 价值低于最小值,应该跳过
|
||||
result = should_skip_fudai_by_config(
|
||||
mock_analyser,
|
||||
prize_value_yuan=5.0,
|
||||
participants=100,
|
||||
countdown_seconds=60
|
||||
)
|
||||
assert result is True
|
||||
detail = _create_detail_tuple(prize_value_yuan=5.0, participants=100, countdown_seconds=60)
|
||||
skip, reason = should_skip_fudai_by_config(mock_analyser, detail)
|
||||
assert skip is True
|
||||
|
||||
def test_not_skip_by_value(self, mock_analyser):
|
||||
"""测试价值满足要求,不跳过"""
|
||||
mock_analyser.min_prize_value_yuan = 10.0
|
||||
result = should_skip_fudai_by_config(
|
||||
mock_analyser,
|
||||
prize_value_yuan=20.0,
|
||||
participants=100,
|
||||
countdown_seconds=60
|
||||
)
|
||||
assert result is False
|
||||
detail = _create_detail_tuple(prize_value_yuan=20.0, participants=100, countdown_seconds=60)
|
||||
skip, reason = should_skip_fudai_by_config(mock_analyser, detail)
|
||||
assert skip is False
|
||||
|
||||
def test_skip_by_min_participants(self, mock_analyser):
|
||||
"""测试按最小参与人数筛选"""
|
||||
mock_analyser.min_participants = 1000
|
||||
result = should_skip_fudai_by_config(
|
||||
mock_analyser,
|
||||
prize_value_yuan=10.0,
|
||||
participants=500,
|
||||
countdown_seconds=60
|
||||
)
|
||||
assert result is True
|
||||
detail = _create_detail_tuple(prize_value_yuan=10.0, participants=500, countdown_seconds=60)
|
||||
skip, reason = should_skip_fudai_by_config(mock_analyser, detail)
|
||||
assert skip is True
|
||||
|
||||
def test_skip_by_max_participants(self, mock_analyser):
|
||||
"""测试按最大参与人数筛选"""
|
||||
mock_analyser.max_participants = 100
|
||||
result = should_skip_fudai_by_config(
|
||||
mock_analyser,
|
||||
prize_value_yuan=10.0,
|
||||
participants=200,
|
||||
countdown_seconds=60
|
||||
)
|
||||
assert result is True
|
||||
detail = _create_detail_tuple(prize_value_yuan=10.0, participants=200, countdown_seconds=60)
|
||||
skip, reason = should_skip_fudai_by_config(mock_analyser, detail)
|
||||
assert skip is True
|
||||
|
||||
def test_skip_by_countdown_gt(self, mock_analyser):
|
||||
"""测试按倒计时大于阈值筛选"""
|
||||
mock_analyser.skip_if_countdown_gt_seconds = 60
|
||||
result = should_skip_fudai_by_config(
|
||||
mock_analyser,
|
||||
prize_value_yuan=10.0,
|
||||
participants=100,
|
||||
countdown_seconds=120
|
||||
)
|
||||
assert result is True
|
||||
detail = _create_detail_tuple(prize_value_yuan=10.0, participants=100, countdown_seconds=120)
|
||||
skip, reason = should_skip_fudai_by_config(mock_analyser, detail)
|
||||
assert skip is True
|
||||
|
||||
def test_skip_by_countdown_lt(self, mock_analyser):
|
||||
"""测试按倒计时小于阈值筛选"""
|
||||
mock_analyser.skip_if_countdown_lt_seconds = 10
|
||||
result = should_skip_fudai_by_config(
|
||||
mock_analyser,
|
||||
prize_value_yuan=10.0,
|
||||
participants=100,
|
||||
countdown_seconds=5
|
||||
)
|
||||
assert result is True
|
||||
detail = _create_detail_tuple(prize_value_yuan=10.0, participants=100, countdown_seconds=5)
|
||||
skip, reason = should_skip_fudai_by_config(mock_analyser, detail)
|
||||
assert skip is True
|
||||
|
||||
|
||||
class TestBasicJoinDecision:
|
||||
@@ -90,23 +92,20 @@ class TestBasicJoinDecision:
|
||||
mock_analyser.min_participants = 0
|
||||
mock_analyser.max_participants = 0
|
||||
|
||||
with patch('douyin_fudai_core.should_skip_fudai_by_config', return_value=False):
|
||||
result = basic_join_decision(
|
||||
mock_analyser,
|
||||
prize_value_yuan=10.0,
|
||||
participants=100,
|
||||
countdown_seconds=60
|
||||
)
|
||||
assert result is True
|
||||
detail = _create_detail_tuple(prize_value_yuan=10.0, participants=100, countdown_seconds=60)
|
||||
with patch('douyin_fudai_core.should_skip_fudai_by_config', return_value=(False, "ok")):
|
||||
with patch('douyin_fudai_core.attend_choujiang', return_value=True):
|
||||
result = basic_join_decision(mock_analyser, detail)
|
||||
assert result is True
|
||||
|
||||
def test_join_decision_negative(self, mock_analyser):
|
||||
"""测试决定不参与"""
|
||||
with patch('douyin_fudai_core.should_skip_fudai_by_config', return_value=True):
|
||||
result = basic_join_decision(
|
||||
mock_analyser,
|
||||
prize_value_yuan=10.0,
|
||||
participants=100,
|
||||
countdown_seconds=60
|
||||
)
|
||||
detail = _create_detail_tuple(prize_value_yuan=10.0, participants=100, countdown_seconds=60)
|
||||
with patch('douyin_fudai_core.should_skip_fudai_by_config', return_value=(True, "test_reason")):
|
||||
result = basic_join_decision(mock_analyser, detail)
|
||||
assert result is False
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -97,3 +97,19 @@ class TestExtractParticipantsCount:
|
||||
assert extract_participants_count("") == 0
|
||||
assert extract_participants_count(None) == 0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -68,3 +68,19 @@ class TestParseCountdownSeconds:
|
||||
except (ValueError, AttributeError):
|
||||
pass # 如果抛出异常也是可以接受的
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -27,64 +27,23 @@ class TestRunParams:
|
||||
y_pianyi=0,
|
||||
needswitch=False,
|
||||
wait_minutes=5,
|
||||
min_prize_value_yuan=1.0,
|
||||
min_participants=0,
|
||||
max_participants=0,
|
||||
skip_if_countdown_gt_seconds=600,
|
||||
reset_after_swipes_enabled=False,
|
||||
reset_after_swipes=10,
|
||||
min_prize_value_yuan=1.0,
|
||||
min_participants=0,
|
||||
max_participants=0,
|
||||
auto_join_fansclub=False,
|
||||
fansclub_fail_action="stay",
|
||||
high_value_fudai_enabled=False,
|
||||
high_value_fudai_threshold_yuan=1000.0,
|
||||
high_value_fudai_join_ahead_seconds=120,
|
||||
high_value_fudai_max_swipe_back=60,
|
||||
high_value_fudai_max_reservations=5,
|
||||
high_value_fudai_after_action="continue",
|
||||
high_value_room_revisit_enabled=True,
|
||||
high_value_room_revisit_only_current_run=False,
|
||||
reservation_back_verify_enabled=True,
|
||||
reservation_back_swipe_delay=0.6,
|
||||
reservation_preempt_min_value=0.0,
|
||||
fudai_find_max_attempts=5,
|
||||
fudai_icon_retry_delay_seconds=0.6,
|
||||
fudai_icon_max_wait_seconds=5.0,
|
||||
yanghao_enabled=False,
|
||||
yanghao_enable_actions=False,
|
||||
yanghao_recommend_duration_seconds=60,
|
||||
yanghao_recommend_interval_seconds=0,
|
||||
yanghao_like_prob=0.15,
|
||||
yanghao_fav_prob=0.05,
|
||||
yanghao_comment_prob=0.0,
|
||||
yanghao_icon_roi_size=180,
|
||||
yanghao_icon_match_threshold=0.72,
|
||||
yanghao_like_template_path="assets/like.png",
|
||||
yanghao_fav_template_path="assets/fav.png",
|
||||
yanghao_after_dwell_swipe_direction="up",
|
||||
yanghao_after_dwell_swipe_distance_px=900,
|
||||
yanghao_like_icon_x=0,
|
||||
yanghao_like_icon_y=-1,
|
||||
yanghao_fav_icon_x=-1,
|
||||
yanghao_fav_icon_y=0,
|
||||
yanghao_comment_btn_x=0,
|
||||
yanghao_comment_btn_y=-1,
|
||||
yanghao_comment_input_x=0,
|
||||
yanghao_comment_input_y=0,
|
||||
yanghao_comment_send_x=0,
|
||||
yanghao_comment_send_y=-1,
|
||||
yanghao_comment_close_x=0,
|
||||
yanghao_comment_close_y=0,
|
||||
yanghao_comment_texts=[],
|
||||
yanghao_like_keywords=[],
|
||||
yanghao_fav_keywords=[],
|
||||
stage_diag_max_time=15.0,
|
||||
stage_diag_max_step_time=4.0,
|
||||
live_room_match_threshold=0.7,
|
||||
enable_ocr_mode1=False,
|
||||
fudai_template_match_enabled=False,
|
||||
fudai_template_match_threshold=0.7,
|
||||
lucky_draw_red_ratio_threshold=0.8,
|
||||
skip_if_countdown_lt_seconds=5,
|
||||
)
|
||||
|
||||
assert params.device_id == "test_device"
|
||||
@@ -136,3 +95,7 @@ class TestRunner:
|
||||
# 简化处理
|
||||
assert True # 占位测试
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -31,3 +31,19 @@ class TestPathConfig:
|
||||
# 实际测试中可能需要mock文件系统操作
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -43,3 +43,19 @@ class TestVersion:
|
||||
assert VERSION in captured.out
|
||||
assert RELEASE_DATE in captured.out
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+100
-37
@@ -155,15 +155,24 @@ class SensitiveDataMasker:
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def mask_all(text: str) -> str:
|
||||
"""对所有敏感信息进行脱敏"""
|
||||
"""对所有敏感信息进行脱敏(性能优化版本)"""
|
||||
if not isinstance(text, str):
|
||||
text = str(text)
|
||||
|
||||
text = SensitiveDataMasker.mask_password(text)
|
||||
text = SensitiveDataMasker.mask_phone(text)
|
||||
text = SensitiveDataMasker.mask_id_card(text)
|
||||
text = SensitiveDataMasker.mask_email(text)
|
||||
text = SensitiveDataMasker.mask_bank_card(text)
|
||||
# 优化:快速检查,如果文本很短或明显不包含敏感信息,跳过部分脱敏
|
||||
text_lower = text.lower()
|
||||
has_sensitive_keywords = any(
|
||||
keyword in text_lower
|
||||
for keyword in ['password', 'pwd', 'phone', 'mobile', 'id', 'card', '@']
|
||||
)
|
||||
|
||||
# 只在可能包含敏感信息时才执行脱敏
|
||||
if has_sensitive_keywords:
|
||||
text = SensitiveDataMasker.mask_password(text)
|
||||
text = SensitiveDataMasker.mask_phone(text)
|
||||
text = SensitiveDataMasker.mask_id_card(text)
|
||||
text = SensitiveDataMasker.mask_email(text)
|
||||
text = SensitiveDataMasker.mask_bank_card(text)
|
||||
|
||||
return text
|
||||
|
||||
@@ -201,10 +210,15 @@ class UnifiedFormatter(logging.Formatter):
|
||||
"%(asctime)s.%(msecs)03d - [%(levelname)s] - [%(threadName)s] - "
|
||||
"[%(name)s:%(funcName)s:%(lineno)d] - [traceId:%(traceId)s] - %(message)s"
|
||||
)
|
||||
# 缓存:避免重复检查MDC
|
||||
self._last_mdc_check_time = 0.0
|
||||
self._last_mdc_data = {}
|
||||
self._mdc_cache_ttl = 0.1 # 100ms缓存,减少MDC查询频率(在高频日志场景下提升性能)
|
||||
self._mdc_check_counter = 0 # 计数器,用于进一步优化
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
"""格式化日志记录,添加traceId"""
|
||||
# 获取traceId
|
||||
"""格式化日志记录,添加traceId(性能优化版本)"""
|
||||
# 获取traceId(快速路径,直接访问thread-local,无需调用get_all)
|
||||
trace_id = MDC.get_trace_id()
|
||||
if trace_id is None:
|
||||
trace_id = 'N/A'
|
||||
@@ -212,46 +226,95 @@ class UnifiedFormatter(logging.Formatter):
|
||||
# 将traceId添加到record中
|
||||
record.traceId = trace_id # type: ignore[attr-defined]
|
||||
|
||||
# 获取MDC中的所有上下文信息
|
||||
mdc_data = MDC.get_all()
|
||||
if mdc_data:
|
||||
# 将MDC信息添加到消息中
|
||||
mdc_str = ', '.join([f'{k}={v}' for k, v in mdc_data.items() if k != 'traceId'])
|
||||
if mdc_str:
|
||||
record.msg = f"{record.msg} | MDC: {mdc_str}"
|
||||
# 优化:使用计数器和时间戳双重检查,减少MDC查询频率
|
||||
self._mdc_check_counter += 1
|
||||
current_time = time.time()
|
||||
should_check_mdc = (
|
||||
(current_time - self._last_mdc_check_time) > self._mdc_cache_ttl or
|
||||
self._mdc_check_counter >= 50 # 每50条记录强制检查一次
|
||||
)
|
||||
|
||||
# 对消息进行敏感信息脱敏
|
||||
if should_check_mdc:
|
||||
self._last_mdc_data = MDC.get_all()
|
||||
self._last_mdc_check_time = current_time
|
||||
self._mdc_check_counter = 0
|
||||
|
||||
mdc_data = self._last_mdc_data
|
||||
if mdc_data:
|
||||
# 将MDC信息添加到消息中(排除traceId,避免重复)
|
||||
mdc_items = [(k, v) for k, v in mdc_data.items() if k != 'traceId']
|
||||
if mdc_items:
|
||||
# 优化:使用列表推导式,避免多次字符串拼接
|
||||
mdc_str = ', '.join(f'{k}={v}' for k, v in mdc_items)
|
||||
if mdc_str:
|
||||
record.msg = f"{record.msg} | MDC: {mdc_str}"
|
||||
|
||||
# 优化:只在消息较长或可能包含敏感信息时才进行脱敏
|
||||
# 进一步优化:缓存敏感关键词检查结果(对于相同消息)
|
||||
if isinstance(record.msg, str):
|
||||
record.msg = SensitiveDataMasker.mask_all(record.msg)
|
||||
msg = record.msg
|
||||
# 快速检查:如果消息很短(<30字符),直接跳过脱敏(提高阈值以减少检查)
|
||||
if len(msg) > 30:
|
||||
# 使用更高效的检查:先检查长度,再检查关键词
|
||||
msg_lower = msg.lower()
|
||||
if any(keyword in msg_lower for keyword in
|
||||
['password', 'pwd', 'phone', 'mobile', 'id', 'card', 'email', '@']):
|
||||
record.msg = SensitiveDataMasker.mask_all(msg)
|
||||
|
||||
# 格式化
|
||||
return super().format(record)
|
||||
|
||||
|
||||
# 缓存logger实例,避免重复创建和检查
|
||||
_logger_cache: Dict[str, logging.Logger] = {}
|
||||
_logger_cache_lock = threading.Lock()
|
||||
|
||||
def get_unified_logger(name: Optional[str] = None) -> logging.Logger:
|
||||
"""获取统一配置的logger实例"""
|
||||
"""获取统一配置的logger实例(性能优化版本)"""
|
||||
# 确保name不为None
|
||||
if name is None:
|
||||
# 自动获取调用者模块名
|
||||
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"
|
||||
# 优化:避免使用inspect.currentframe(),直接使用调用栈
|
||||
# 如果调用者没有提供name,使用默认值
|
||||
name = "root"
|
||||
try:
|
||||
# 尝试从调用栈获取模块名(最多向上查找3层)
|
||||
frame = inspect.currentframe()
|
||||
if frame:
|
||||
for _ in range(3): # 最多向上查找3层
|
||||
frame = frame.f_back
|
||||
if frame is None:
|
||||
break
|
||||
module_name = frame.f_globals.get("__name__")
|
||||
if module_name and module_name != __name__:
|
||||
name = module_name
|
||||
break
|
||||
except Exception:
|
||||
# 如果获取失败,使用默认值
|
||||
pass
|
||||
|
||||
logger = douyin_logging.get_logger(name)
|
||||
# 确保name是str类型(类型检查)
|
||||
logger_name: str = name if isinstance(name, str) else "root"
|
||||
|
||||
# 如果logger还没有自定义formatter,添加统一formatter
|
||||
if logger.handlers:
|
||||
for handler in logger.handlers:
|
||||
if isinstance(handler.formatter, logging.Formatter) and \
|
||||
not isinstance(handler.formatter, UnifiedFormatter):
|
||||
handler.setFormatter(UnifiedFormatter(
|
||||
fmt=handler.formatter._fmt if hasattr(handler.formatter, '_fmt') else None,
|
||||
datefmt="%Y-%m-%d %H:%M:%S"
|
||||
))
|
||||
|
||||
return logger
|
||||
# 使用缓存避免重复创建和检查
|
||||
with _logger_cache_lock:
|
||||
if logger_name in _logger_cache:
|
||||
return _logger_cache[logger_name]
|
||||
|
||||
logger = douyin_logging.get_logger(logger_name)
|
||||
|
||||
# 如果logger还没有自定义formatter,添加统一formatter
|
||||
# 优化:只检查一次,避免每次调用都检查
|
||||
if logger.handlers:
|
||||
for handler in logger.handlers:
|
||||
if isinstance(handler.formatter, logging.Formatter) and \
|
||||
not isinstance(handler.formatter, UnifiedFormatter):
|
||||
handler.setFormatter(UnifiedFormatter(
|
||||
fmt=handler.formatter._fmt if hasattr(handler.formatter, '_fmt') else None,
|
||||
datefmt="%Y-%m-%d %H:%M:%S"
|
||||
))
|
||||
|
||||
_logger_cache[logger_name] = logger
|
||||
return logger
|
||||
|
||||
|
||||
@contextmanager
|
||||
|
||||
+2
-8
@@ -679,12 +679,8 @@ class ProcRunner:
|
||||
}
|
||||
|
||||
# 获取当前traceId和MDC上下文
|
||||
current_trace_id = getattr(self, '_current_trace_id', None)
|
||||
mdc_context = dict(getattr(self, '_mdc_context', {}))
|
||||
|
||||
# 获取当前traceId和MDC上下文
|
||||
current_trace_id = getattr(self, '_current_trace_id', None)
|
||||
mdc_context = dict(getattr(self, '_mdc_context', {}))
|
||||
current_trace_id = getattr(self, "_current_trace_id", None)
|
||||
mdc_context = dict(getattr(self, "_mdc_context", {}))
|
||||
|
||||
payload = {
|
||||
"running": bool(running),
|
||||
@@ -704,8 +700,6 @@ class ProcRunner:
|
||||
# 统一日志系统信息
|
||||
"trace_id": current_trace_id,
|
||||
"mdc_context": mdc_context,
|
||||
"trace_id": current_trace_id,
|
||||
"mdc_context": mdc_context,
|
||||
}
|
||||
|
||||
if include_events:
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
# 核显GPU加速说明
|
||||
|
||||
## 关于核显(集成显卡)的GPU加速
|
||||
|
||||
### 核显的限制
|
||||
|
||||
1. **CUDA支持**
|
||||
- **NVIDIA核显**:不支持CUDA(CUDA是NVIDIA专有技术)
|
||||
- **Intel核显**:不支持CUDA,但部分型号支持OpenCL或Intel的深度学习加速工具
|
||||
- **AMD核显**:不支持CUDA,但可能支持OpenCL或ROCm
|
||||
|
||||
2. **性能限制**
|
||||
- 核显的计算能力通常远低于独立显卡
|
||||
- 即使支持GPU加速,性能提升可能不明显(可能只有10-30%的提升)
|
||||
- 核显的显存通常很小,可能无法处理较大的OCR任务
|
||||
|
||||
3. **兼容性问题**
|
||||
- EasyOCR和PaddleOCR主要针对NVIDIA CUDA优化
|
||||
- 核显可能需要特殊的驱动和库支持
|
||||
|
||||
### 当前代码的GPU检测逻辑
|
||||
|
||||
代码已添加自动GPU检测功能:
|
||||
|
||||
1. **自动检测GPU可用性**
|
||||
- 检测PyTorch CUDA支持(EasyOCR使用)
|
||||
- 检测PaddleOCR GPU支持(需要paddlepaddle-gpu)
|
||||
|
||||
2. **核显处理策略**
|
||||
- **默认**:检测到核显时,**不使用GPU加速**(因为效果不明显)
|
||||
- **可选**:通过环境变量 `USE_INTEGRATED_GPU=1` 强制使用核显GPU
|
||||
|
||||
3. **独立显卡**
|
||||
- 检测到独立显卡时,**自动启用GPU加速**
|
||||
|
||||
### 如何使用核显GPU加速(不推荐)
|
||||
|
||||
如果确实想尝试使用核显GPU加速:
|
||||
|
||||
#### 方法1:设置环境变量(Windows PowerShell)
|
||||
```powershell
|
||||
$env:USE_INTEGRATED_GPU = "1"
|
||||
python gui_app.py
|
||||
```
|
||||
|
||||
#### 方法2:设置环境变量(Windows CMD)
|
||||
```cmd
|
||||
set USE_INTEGRATED_GPU=1
|
||||
python gui_app.py
|
||||
```
|
||||
|
||||
#### 方法3:在代码中修改
|
||||
修改 `Underlying_Operations.py` 中的 `_detect_gpu_available` 方法,将核显检测部分改为:
|
||||
```python
|
||||
if is_integrated:
|
||||
# 核显:尝试使用GPU加速
|
||||
return True # 改为返回True
|
||||
```
|
||||
|
||||
### 预期效果
|
||||
|
||||
- **独立显卡(NVIDIA)**:GPU加速后,OCR耗时可能从3-4秒降至0.5-1秒
|
||||
- **核显(Intel/AMD)**:GPU加速后,OCR耗时可能从3-4秒降至2-3秒(提升有限)
|
||||
|
||||
### 建议
|
||||
|
||||
1. **如果有独立显卡**:启用GPU加速,性能提升明显
|
||||
2. **如果只有核显**:
|
||||
- **推荐**:继续使用CPU模式(当前默认行为)
|
||||
- **可选**:尝试启用核显GPU,但不要期望明显的性能提升
|
||||
3. **如果遇到问题**:
|
||||
- 核显GPU加速可能导致程序崩溃或性能下降
|
||||
- 可以通过环境变量 `FORCE_CPU_OCR=1` 强制使用CPU模式
|
||||
|
||||
### 环境变量控制
|
||||
|
||||
- `FORCE_CPU_OCR=1`:强制使用CPU模式(忽略GPU检测)
|
||||
- `FORCE_GPU_OCR=1`:强制使用GPU模式(如果GPU可用)
|
||||
- `USE_INTEGRATED_GPU=1`:允许使用核显GPU加速(默认禁用)
|
||||
|
||||
### 检测GPU状态
|
||||
|
||||
运行以下命令检测GPU状态:
|
||||
```bash
|
||||
python check_gpu_available.py
|
||||
```
|
||||
|
||||
### 总结
|
||||
|
||||
**核显可以使用GPU加速,但不推荐**,原因:
|
||||
1. 性能提升有限(可能只有10-30%)
|
||||
2. 兼容性问题(可能需要特殊驱动)
|
||||
3. 可能导致程序不稳定
|
||||
|
||||
**建议**:
|
||||
- 如果有独立显卡,启用GPU加速
|
||||
- 如果只有核显,继续使用CPU模式(当前默认行为)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -92,3 +92,23 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+20
@@ -164,3 +164,23 @@ if __name__ == "__main__":
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user