fix: Adjust configuration settings and improve error handling
- Updated `config.json` to modify `yanghao_recommend_interval_seconds` for better timing control. - Refactored logging in `douyin_detection.py` to enhance readability and error handling. - Improved pixel loading and error management in image processing functions across multiple modules. - Enhanced GUI elements in `gui_app.py` to support new configuration options and improve user experience.
This commit is contained in:
1 parent
47e6b016c5
commit
2cd81c05a3
35 files changed
+12043
-1711
No files matched your search
@@ -0,0 +1,4 @@
|
||||
# SpecStory explanation file
|
||||
/.what-is-this.md
|
||||
# SpecStory project identity file
|
||||
/.project.json
|
||||
+23
-19
@@ -1,45 +1,50 @@
|
||||
|
||||
# SpecStory Artifacts Directory
|
||||
|
||||
This directory is automatically created and maintained by the SpecStory extension to preserve your Cursor composer and chat history.
|
||||
This directory is automatically created and maintained by the SpecStory extension to preserve your AI chat history.
|
||||
|
||||
## What's Here?
|
||||
|
||||
- `.specstory/history`: Contains markdown files of your AI coding sessions
|
||||
- Each file represents a separate chat or composer session
|
||||
- Files are automatically updated as you work
|
||||
- `.specstory/cursor_rules_backups`: Contains backups of the `.cursor/rules/derived-cursor-rules.mdc` file
|
||||
- Backups are automatically created each time the `.cursor/rules/derived-cursor-rules.mdc` file is updated
|
||||
- You can enable/disable the Cursor Rules feature in the SpecStory settings, it is disabled by default
|
||||
- `.specstory/history`: Contains auto-saved markdown files of your AI coding sessions
|
||||
- Each file represents a separate AI chat session
|
||||
- If you enable auto-save, files are automatically updated as you work
|
||||
- You can enable/disable the auto-save feature in the SpecStory settings, it is disabled by default
|
||||
- `.specstory/.project.json`: Contains the persistent project identity for the current workspace
|
||||
- This file is only present if you enable AI rules derivation
|
||||
- This is used to provide consistent project identity of your project, even as the workspace is moved or renamed
|
||||
- `.specstory/ai_rules_backups`: Contains backups of the `.cursor/rules/derived-cursor-rules.mdc` or the `.github/copilot-instructions.md` file
|
||||
- Backups are automatically created each time the `.cursor/rules/derived-cursor-rules.mdc` or the `.github/copilot-instructions.md` file is updated
|
||||
- You can enable/disable the AI Rules derivation feature in the SpecStory settings, it is disabled by default
|
||||
- `.specstory/.gitignore`: Contains directives to exclude non-essential contents of the `.specstory` directory from version control
|
||||
- Add `/history` to exclude the auto-saved chat history from version control
|
||||
|
||||
## Valuable Uses
|
||||
|
||||
- Capture: Keep your context window up-to-date when starting new Chat/Composer sessions via @ references
|
||||
- Search: For previous prompts and code snippets
|
||||
- Learn: Meta-analyze your patterns and learn from your past experiences
|
||||
- Derive: Keep Cursor on course with your past decisions by automatically deriving Cursor rules from your AI interactions
|
||||
- Derive: Keep the AI on course with your past decisions by automatically deriving rules from your AI interactions
|
||||
|
||||
## Version Control
|
||||
|
||||
We recommend keeping this directory under version control to maintain a history of your AI interactions. However, if you prefer not to version these files, you can exclude them by adding this to your `.gitignore`:
|
||||
|
||||
```
|
||||
.specstory
|
||||
.specstory/**
|
||||
```
|
||||
|
||||
We recommend not keeping the `.specstory/cursor_rules_backups` directory under version control if you are already using git to version the `.cursor/rules` directory, and committing regularly. You can exclude it by adding this to your `.gitignore`:
|
||||
We recommend __not__ keeping the `.specstory/ai_rules_backups` directory under version control if you are already using git to version your AI rules, and committing regularly. You can exclude it by adding this to your `.gitignore`:
|
||||
|
||||
```
|
||||
.specstory/cursor_rules_backups
|
||||
.specstory/ai_rules_backups
|
||||
```
|
||||
|
||||
## Searching Your Codebase
|
||||
|
||||
When searching your codebase in Cursor, search results may include your previous AI coding interactions. To focus solely on your actual code files, you can exclude the AI interaction history from search results.
|
||||
When searching your codebase, search results may include your previous AI coding interactions. To focus solely on your actual code files, you can exclude the AI interaction history from search results.
|
||||
|
||||
To exclude AI interaction history:
|
||||
|
||||
1. Open the "Find in Files" search in Cursor (Cmd/Ctrl + Shift + F)
|
||||
1. Open the "Find in Files" search in Cursor or VSCode (Cmd/Ctrl + Shift + F)
|
||||
2. Navigate to the "files to exclude" section
|
||||
3. Add the following pattern:
|
||||
|
||||
@@ -51,15 +56,14 @@ This will ensure your searches only return results from your working codebase fi
|
||||
|
||||
## Notes
|
||||
|
||||
- Auto-save only works when Cursor/sqlite flushes data to disk. This results in a small delay after the AI response is complete before SpecStory can save the history.
|
||||
- Auto-save does not yet work on remote WSL workspaces.
|
||||
- Auto-save only works when Cursor or VSCode flushes sqlite database data to disk. This results in a small delay after the AI response is complete before SpecStory can save the history.
|
||||
|
||||
## Settings
|
||||
|
||||
You can control auto-saving behavior in Cursor:
|
||||
You can control auto-saving behavior in Cursor or VSCode:
|
||||
|
||||
1. Open Cursor → Settings → VS Code Settings (Cmd/Ctrl + ,)
|
||||
1. Open Cursor/Code → Settings → VS Code Settings (Cmd/Ctrl + ,)
|
||||
2. Search for "SpecStory"
|
||||
3. Find "Auto Save" setting to enable/disable
|
||||
|
||||
Auto-save occurs when changes are detected in Cursor's sqlite database, or every 2 minutes as a safety net.
|
||||
Auto-save occurs when changes are detected in the sqlite database, or every 2 minutes as a safety net.
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- vscode Session 99933567-6b61-4fe8-96fe-5eb236f157a5 (2025-12-21 02:16Z) -->
|
||||
|
||||
# Extension host terminated unexpectedly 3 times within the last 5 minutes. (2025-12-21 02:16Z)
|
||||
|
||||
_**User (2025-12-21 02:17Z)**_
|
||||
|
||||
Extension host terminated unexpectedly 3 times within the last 5 minutes.
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model copilot/gpt-5-mini)**_
|
||||
|
||||
<tool-use data-tool-type="task" data-tool-name="manage_todo_list">
|
||||
<details>
|
||||
<summary>Tool use: **manage_todo_list** • 正在使用 "管理和跟踪待办事项以进行任务规划"</summary>
|
||||
|
||||
**已创建 6 个待办事项**
|
||||
|
||||
- [ ] 收集扩展主机崩溃日志
|
||||
> 查看 VS Code 日志目录(%APPDATA%\Code\logs)并捕获最近崩溃条目;打开开发者工具(Console)截取错误堆栈。
|
||||
- [ ] 以禁用扩展模式启动 VS Code
|
||||
> 用 `code --disable-extensions` 启动 VS Code 以确认是否为扩展导致崩溃。
|
||||
- [ ] 逐个禁用/启用扩展定位问题
|
||||
> 如果第2步通过,启用扩展分批次(或二分法)以找出导致崩溃的扩展。
|
||||
- [ ] 检查与恢复扩展主机相关设置
|
||||
> 检查 `argv.json`、用户设置、以及是否安装了原生模块或本机依赖导致崩溃;尝试清空扩展缓存。
|
||||
- [ ] 更新或重装 VS Code / 扩展
|
||||
> 将 VS Code 更新到最新版或重装;重装或回退导致问题的扩展。
|
||||
- [ ] 收集并上报问题
|
||||
> 如果定位不到原因,整理日志与重现步骤,准备提交到 GitHub 的 `microsoft/vscode` issue 或扩展仓库。
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
**Troubleshooting VS Code issues**
|
||||
|
||||
It looks like the user is experiencing some problems with the VS Code extension host crashing unexpectedly. I need to help them diagnose and fix this, so I'll create a plan using the todo list tool, making sure to track our progress throughout. I should gather logs and provide specific troubleshooting steps, like checking the Developer Tools console, disabling extensions, and checking logs in their %APPDATA%\Code\logs directory. I can guide them on how to open the Developer Tools and run the code command with `--disable-extensions`.**Planning VS Code Help**
|
||||
|
||||
I see that I have the run_in_terminal tool to execute terminal commands. I'll need to start VS Code with disabled extensions, which means I should include a brief preamble each time I make a tool call. It’s crucial that I manage a todo list for this task, so I’ll write down the steps: 1) Collect logs, 2) Start Code with `--disable-extensions`, 3) Open Developer Tools, 4) Disable any suspect extensions, 5) Reinstall or update VS Code, and 6) Offer further assistance. Let's go ahead and create that plan!**Updating the task list**
|
||||
|
||||
I need to provide a progress update and confirm whether I should run the commands. So, I’ll start by using the manage_todo_list tool. I’ll create a concise preamble that says, "我将创建诊断与修复的任务清单". After I write the todo items, I’ll outline the next steps, which include running VS Code with `--disable-extensions` and checking logs. Following that, I’ll give a progress update and ensure everything is formatted correctly in Chinese, wrapping file names in backticks. Now, let's call manage_todo_list!我要先建立一个可追踪的诊断与修复任务清单,然后提供下一步命令与建议。已创建诊断与修复任务清单(6 步)。下一步我建议先以禁用扩展启动 VS Code 并查看开发者工具与日志;我会给出命令和后续操作指引。
|
||||
|
||||
- 若你希望我在本地执行命令,请确认我可以在你的机器上运行命令;否则按下面步骤手动执行。
|
||||
- 先运行:以禁用扩展启动 VS Code 并打开开发者工具查看 Console。复制并粘贴看到的错误或堆栈。
|
||||
|
||||
命令(在 PowerShell 中运行):
|
||||
```powershell
|
||||
# 以禁用扩展启动 VS Code
|
||||
code --disable-extensions
|
||||
|
||||
# 启动后打开开发者工具(菜单:帮助 → 切换开发者工具),在 Console 中查看错误日志
|
||||
```
|
||||
|
||||
另外,请检查并提供(或在此粘贴)以下信息以便我继续诊断:
|
||||
- 在 VS Code 弹出的“扩展主机已意外终止”的完整错误消息或时间戳。
|
||||
- `%APPDATA%\Code\logs` 目录下最新的日志文件(压缩或粘贴关键片段)。
|
||||
- 你最近安装或更新过哪些扩展(如有)。
|
||||
|
||||
要我现在在你的环境运行 `code --disable-extensions` 并抓取日志,我可以继续执行(需要你的确认)。
|
||||
|
||||
---
|
||||
|
||||
_**User (2025-12-21 02:21Z)**_
|
||||
|
||||
你直接帮我运行
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model copilot/gpt-5-mini)**_
|
||||
|
||||
<tool-use data-tool-type="unknown" data-tool-name="run_in_terminal">
|
||||
<details>
|
||||
<summary>Tool use: **run_in_terminal**</summary>
|
||||
|
||||
|
||||
Parameters:
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": "terminal",
|
||||
"terminalCommandId": "tool-29213d6a-ead5-45e4-a1a4-7a3cb447a718",
|
||||
"commandLine": {
|
||||
"original": "code --disable-extensions"
|
||||
},
|
||||
"language": "pwsh",
|
||||
"autoApproveInfo": {
|
||||
"value": "此会话的所有命令将得到自动批准 ([禁用](command:workbench.action.terminal.chat.disableSessionAutoApproval?%255B%252299933567-6b61-4fe8-96fe-5eb236f157a5%2522%255D))",
|
||||
"isTrusted": {
|
||||
"enabledCommands": [
|
||||
"workbench.action.terminal.chat.disableSessionAutoApproval"
|
||||
]
|
||||
},
|
||||
"supportThemeIcons": false,
|
||||
"supportHtml": false,
|
||||
"supportAlertSyntax": false
|
||||
},
|
||||
"terminalCommandState": {
|
||||
"timestamp": 1766283768991
|
||||
},
|
||||
"terminalTheme": {
|
||||
"background": "#282a36",
|
||||
"foreground": "#f8f8f2"
|
||||
}
|
||||
}
|
||||
```
|
||||
Additional data:
|
||||
|
||||
```json
|
||||
{
|
||||
"vscodeToolId": "run_in_terminal",
|
||||
"isHidden": false
|
||||
}
|
||||
```
|
||||
Result:
|
||||
|
||||
```json
|
||||
{
|
||||
"invocationMessage": "正在使用 \"在终端中运行\"",
|
||||
"isConfirmed": {
|
||||
"type": 4
|
||||
},
|
||||
"content": "",
|
||||
"textEditContent": "",
|
||||
"toolCallResult": null
|
||||
}
|
||||
```
|
||||
Status: **completed**
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
**Managing progress updates**
|
||||
|
||||
I’m planning to make two calls and need to follow the progress update rules. After every 3-5 tool calls or when editing several files, I should provide a concise update. Plus, I really need to call the manage_todo_list tool to keep track of statuses. Hmm, I’ve already started, but I wonder if it’s necessary to call it right now. I’ll update the todo list to mark step 2 as completed!**Preparing tool calls**
|
||||
|
||||
Before making any tool calls, I need to remember the requirement for a preamble message. My sequence goes like this: first, send a commentary explaining the batch process; second, call run_in_terminal to start VS Code with disabled extensions; third, run another command to fetch the latest log file and tail the last 200 lines; finally, update the statuses using manage_todo_list. I need to craft the PowerShell command correctly for the second run_in_terminal call and ensure I have everything set up before executing.**Presenting progress updates**
|
||||
|
||||
After receiving the tool responses, I need to provide a progress update and outline what’s next. It’s important that the final answer is in Chinese. So, I’ll make sure to prepare for that as I call the necessary tools. Being clear about our progress helps keep everything organized and ensures the user knows what's happening. Let’s move forward and get these tools called!我将以禁用扩展启动 VS Code,并抓取 `%APPDATA%\Code\logs` 下最近的日志尾部内容以便诊断。
|
||||
|
||||
---
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- vscode Session 897b9d4c-f1e1-4e94-8ab4-fb83ac85ce83 (2025-12-21 06:02Z) -->
|
||||
|
||||
# 帮我安装vs code的 Enable shell integration to improve command detection (2025-12-21 06:02Z)
|
||||
|
||||
_**User (2025-12-21 06:03Z)**_
|
||||
|
||||
帮我安装vs code的 Enable shell integration to improve command detection
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model copilot/gpt-5-mini)**_
|
||||
|
||||
<tool-use data-tool-type="task" data-tool-name="manage_todo_list">
|
||||
<details>
|
||||
<summary>Tool use: **manage_todo_list** • 正在使用 "管理和跟踪待办事项以进行任务规划"</summary>
|
||||
|
||||
**已创建 2 个待办事项**
|
||||
|
||||
- [-] Add workspace setting
|
||||
> Create .vscode/settings.json and set terminal.integrated.enableShellIntegration to true
|
||||
- [ ] Reload VS Code
|
||||
> Reload window to apply setting and verify command detection
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
**Exploring VS Code Shell Integration**
|
||||
|
||||
The user is asking how to enable shell integration in VS Code for improved command detection. This involves installing the "Shell Command: Install 'code' command in PATH" or enabling the "Enable shell integration" feature in Git Bash. The setting I'll focus on is "Terminal › Integrated: Enable Shell Integration," which is available in VS Code 1.79+. The user is on Windows using PowerShell, and enabling might require adjustments to their profile.**Using a Todo List for Planning**
|
||||
|
||||
I need to remember that the instruction requires me to use the todo list tool for multi-step tasks. This is simple, but since the developer insists on using manage_todo_list, I must apply that here. This task seems to involve multiple steps: adding a setting to settings.json and then restarting VS Code. So yes, I must call manage_todo_list with a plan. First, I’ll provide a brief introduction before calling the tool, and then I can edit the appropriate settings afterward.**Setting Shell Integration in VS Code**
|
||||
|
||||
I need to instruct the user on enabling or modifying the .vscode/settings.json file to set "terminal.integrated.enableShellIntegration": true. I'll create or update the settings.json file. The developer has specified that I must use apply_patch for file edits, and this should be done in the workspace root. After making the changes, I'll provide short instructions on how to reload VS Code and verify. I also need to remember to include preamble sentences before making any tool calls for manage_todo_list or apply_patch.**Updating Progress and File Details**
|
||||
|
||||
After gathering context, I need to give a progress update. I’m planning to make two tool calls: manage_todo_list and apply_patch. Even though I’m only making two tool calls here, I should still provide a concise update on progress and what's next. After applying the patch, I’ll format my final message succinctly, including a link to the [.vscode/settings.json](.vscode/settings.json#L1-L10) file without using backticks. I'll be sure to wrap any filenames in backticks when I refer to them.**Updating the Todo List**
|
||||
|
||||
I need to update the todo list by marking step 1 as completed. For step 2, I think I’ll leave it as not started for now. So, I'll call manage_todo_list again with the operation to write these updates. I need to remember to include short preamble messages before each tool call to keep everything clear. With that in mind, let's execute these updates and keep everything organized!我先把简短计划写入待办列表,然后在工作区添加设置文件以启用 shell integration。
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- vscode Session 43a8d043-4709-4025-89bd-01b03a6f4044 (2025-12-21 10:17Z) -->
|
||||
|
||||
# 核心指令:␍ (2025-12-21 10:17Z)
|
||||
|
||||
_**User (2025-12-21 10:17Z)**_
|
||||
|
||||
核心指令:
|
||||
|
||||
系统性地识别并修复项目中存在的所有问题,通过“识别-修复-验证”的闭环流程,持续迭代直至问题清零,确保项目达到稳定、可用的状态。
|
||||
|
||||
执行流程:
|
||||
|
||||
1. 问题识别与分类:
|
||||
|
||||
◦ 运行代码,全面收集运行时错误、警告及异常行为。
|
||||
|
||||
◦ 使用代码分析工具(如pylint、flake8)进行静态检查,识别潜在的代码质量问题(如语法错误、未定义变量、重复定义、不符合编码规范等)。
|
||||
|
||||
◦ 审查项目结构、配置文件和依赖关系,排查环境与配置问题。
|
||||
|
||||
◦ 将所有发现的问题进行分类、记录,并按严重性和影响范围确定修复优先级。
|
||||
|
||||
2. 迭代修复:
|
||||
|
||||
◦ 按照优先级,逐个解决已识别的问题。每次修复后,运行相关代码或测试脚本,验证修复是否有效,并确保未引入新的问题。
|
||||
|
||||
◦ 对于复杂问题,可采用分步修复策略,并记录中间步骤和决策。
|
||||
|
||||
3. 验证与回归测试:
|
||||
|
||||
◦ 在所有问题修复完成后,进行全面的功能测试和回归测试,确保核心功能正常,且已修复的问题没有复发。
|
||||
|
||||
◦ 运行完整的测试套件(如有),确认所有测试用例通过。
|
||||
|
||||
结束条件:
|
||||
|
||||
项目代码能够稳定运行,无错误和警告;通过代码静态检查,符合基本规范;并通过所有预定的功能测试。
|
||||
|
||||
请提供具体的项目代码或相关上下文,以便我们开始具体的问题识别与修复工作。
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model copilot/gpt-5-mini)**_
|
||||
|
||||
<tool-use data-tool-type="task" data-tool-name="manage_todo_list">
|
||||
<details>
|
||||
<summary>Tool use: **manage_todo_list** • 正在使用 "管理和跟踪待办事项以进行任务规划"</summary>
|
||||
|
||||
**已创建 8 个待办事项**
|
||||
|
||||
- [ ] 收集运行时错误与静态检查报告
|
||||
> 在虚拟环境中运行项目及所含脚本 (`run_cli.py`/`web_gui.py` 等),并执行 `pylint` 或 `pyright` 来收集运行时异常、导入错误和静态警告。保存输出以便后续定位。
|
||||
- [ ] 修复阻塞性运行时错误
|
||||
> 优先修复运行时报错和未定义变量(例如 `Underlying_Operations.py` 中的 undefined/used-before-assignment 错误、`douyin_fudai.py` 中的 access-member-before-definition)。每次修复后运行相关脚本验证。
|
||||
- [ ] 修复静态分析高优先级问题
|
||||
> 修复 `E`/`F` 类错误(未导入、不可用成员、语法错误),并处理 `W` 类中影响正确性的警告(used-before-assignment、attribute-defined-outside-init 等)。
|
||||
- [ ] 替换或限制 broad Exception 捕获
|
||||
> 在代码中逐步将广泛的 `except Exception:` 改为更具体的异常或添加注释并记录上下文,避免吞噬错误信息。优先处理频繁出现的模块:`gui_app.py`、`Underlying_Operations.py`、`run_cli.py`、`douyin_fudai.py`。
|
||||
- [ ] 修复第三方库兼容问题
|
||||
> 修复 PIL/OpenCV API 兼容性(如 `Image.LANCZOS`/`Image.BICUBIC` 的正确引用或 `Image.Resampling.LANCZOS`),并在需要时添加依赖到 `requirements.txt`。
|
||||
- [ ] 添加编码与安全检查
|
||||
> 在文件读写中加上显式 `encoding='utf-8'`,修复危险默认参数、subprocess 调用缺少 `check` 等潜在问题。
|
||||
- [ ] 回归测试与验证
|
||||
> 修复完成后运行核心功能脚本与可用测试(`tools/webgui_smoketest.py` 等),确保主要功能正常且静态检查通过。
|
||||
- [ ] 整理变更并提交建议
|
||||
> 生成变更清单,列出所有已修复问题和剩余可选改进,建议提交或打包发布步骤。
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
**Preparing a fix plan**
|
||||
|
||||
I need to fix attribute definitions that are outside of the `__init__` method and address anything used before it's defined. I want to replace broad Exception catches with more specific ones where possible. I should also check how I'm using the PIL attributes, particularly with Image.LANCZOS and BICUBIC versus Image.Resampling. Adding encoding when opening files is important too. I’m thinking about whether to include the requirements file. Then I’ll write a concise to-do list.我将先建立一个分步 TODO 计划,按优先级跟踪识别、修复和验证工作。
|
||||
|
||||
---
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,44 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- cursor Session 47893616-68e0-4044-a6f9-72116800ba79 (2025-12-21 13:46Z) -->
|
||||
|
||||
# back_times 未初始化 — 在某个代码路径中使用了未初始化的 back_times (2025-12-21 13:46Z)
|
||||
|
||||
_**User (2025-12-21 13:46Z)**_
|
||||
|
||||
back_times 未初始化 — 在某个代码路径中使用了未初始化的 back_times
|
||||
AttributeError: 'NoneType' object has no attribute 'span' — 正则匹配结果未检查 None
|
||||
IndentationError — 多处缩进错误
|
||||
OSError: image file is truncated — 图片文件处理需要异常处理
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model default, mode Agent)**_
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
_**User (2025-12-21 13:46Z)**_
|
||||
|
||||
back_times 未初始化 — 在某个代码路径中使用了未初始化的 back_times
|
||||
AttributeError: 'NoneType' object has no attribute 'span' — 正则匹配结果未检查 None
|
||||
IndentationError — 多处缩进错误
|
||||
OSError: image file is truncated — 图片文件处理需要异常处理
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model default, mode Agent)**_
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,819 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- cursor Session 03342924-05aa-45b2-a9ba-0ddc9d01a18a (2025-12-21 13:46Z) -->
|
||||
|
||||
# 代码错误与异常处理 (2025-12-21 13:46Z)
|
||||
|
||||
_**User (2025-12-21 13:49Z)**_
|
||||
|
||||
back_times 未初始化 — 在某个代码路径中使用了未初始化的 back_times
|
||||
AttributeError: 'NoneType' object has no attribute 'span' — 正则匹配结果未检查 None
|
||||
IndentationError — 多处缩进错误
|
||||
OSError: image file is truncated — 图片文件处理需要异常处理
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model default, mode Agent)**_
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
检查代码库结构,定位这些错误:
|
||||
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="generic" data-tool-name="list_dir">
|
||||
<details>
|
||||
<summary>Tool use: **list_dir** • Listed directory, 0 results</summary>
|
||||
|
||||
No results found
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="search" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "back_times" • 24 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
| File | Content | Line |
|
||||
|------|------|------|
|
||||
| `.\douyin_fudai.py` | `"back_times": "需回退次数",` | L958 |
|
||||
| `.\douyin_fudai.py` | `back_times = abs(current_pos)` | L1257 |
|
||||
| `.\douyin_fudai.py` | `if back_times > 0:` | L1258 |
|
||||
| `.\douyin_fudai.py` | `for i in range(back_times):` | L1259 |
|
||||
| `.\douyin_fudai.py` | `back_times=back_times,` | L1269 |
|
||||
| `.\douyin_fudai.py` | `back_times = int(swipe_times)` | L1529 |
|
||||
| `.\douyin_fudai.py` | `if back_times <= 0:` | L1530 |
|
||||
| `.\douyin_fudai.py` | `for i in range(back_times):` | L1540 |
|
||||
| `.\douyin_fudai.py` | `self._log_kv("流程", "回退直播间 \{}/\{}".format(i + 1, back_times))` | L1551 |
|
||||
| `.\douyin_fudai.py` | `back_times = max(0, cur_pos - target_pos)` | L1583 |
|
||||
| `.\douyin_fudai.py` | `if max_back > 0 and back_times > max_back:` | L1588 |
|
||||
| `.\douyin_fudai.py` | `back_times = max_back` | L1589 |
|
||||
| `.\douyin_fudai.py` | `back_times=back_times,` | L1597 |
|
||||
| `.\douyin_fudai.py` | `if back_times <= 0:` | L1602 |
|
||||
| `.\douyin_fudai.py` | `for _ in range(back_times):` | L1607 |
|
||||
| `.\douyin_reservation_logic.py` | `est_back_times = 0` | L398 |
|
||||
| `.\douyin_reservation_logic.py` | `est_back_times = max(0, int(room_pos) - target_pos)` | L401 |
|
||||
| `.\douyin_reservation_logic.py` | `est_back_times = min(est_back_times, max_back)` | L407 |
|
||||
| `.\douyin_reservation_logic.py` | `dynamic_ahead = int(max(join_ahead, est_back_times * reservation_back_swipe_delay_s_val + 18))` | L410 |
|
||||
| `.\douyin_reservation_logic.py` | `est_back_times=int(est_back_times),` | L433 |
|
||||
| `.\douyin_yanghao.py` | `back_times = int(swipe_times)` | L516 |
|
||||
| `.\douyin_yanghao.py` | `if back_times <= 0:` | L517 |
|
||||
| `.\douyin_yanghao.py` | `for i in range(back_times):` | L521 |
|
||||
| `.\douyin_yanghao.py` | `print("回退直播间 \{}/\{}".format(i + 1, back_times))` | L523 |
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="search" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "\.span" • 0 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
_No matches found_
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="search" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "re\.(search|match|findall)" • 53 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
| File | Content | Line |
|
||||
|------|------|------|
|
||||
| `.\fix_indentation.py` | `if re.match(r'^\s\{4,\}except\s+', line):` | L35 |
|
||||
| `.\fix_indentation.py` | `if re.match(r'^(\s*)try\s*:', lines[j]):` | L42 |
|
||||
| `.\fix_indentation.py` | `match_obj = re.match(r'^(\s*)', lines[j])` | L43 |
|
||||
| `.\fix_indentation.py` | `if re.match(r'^\s\{4,\}else\s*:', line):` | L71 |
|
||||
| `.\fix_indentation.py` | `if re.match(r'^(\s*)(if\|for\|while\|try\|elif)\s+.*:', prev_line):` | L78 |
|
||||
| `.\fix_indentation.py` | `match_obj = re.match(r'^(\s*)', prev_line)` | L79 |
|
||||
| `.\Underlying_Operations.py` | `devicelist = re.findall(pattern, totalstring)` | L363 |
|
||||
| `.\Underlying_Operations.py` | `match = re.search(r"Physical size: (\d+)x(\d+)", resolution_info_string)` | L655 |
|
||||
| `.\Underlying_Operations.py` | `m = re.search(r"(\d\{1,2\})[:](\d\{1,2\})", t)` | L1203 |
|
||||
| `.\Underlying_Operations.py` | `m = re.search(r"(\d\{1,2\})分(\d\{1,2\})秒", t)` | L1217 |
|
||||
| `.\Underlying_Operations.py` | `m = re.search(r"(\d\{1,3\})秒", t)` | L1225 |
|
||||
| `.\Underlying_Operations.py` | `m = re.search(r"([A-Za-z0-9_\.]+)\/", ln)` | L1413 |
|
||||
| `.\Underlying_Operations.py` | `m = re.search(r"([A-Za-z0-9_\.]+)\/", ln)` | L1423 |
|
||||
| `.\Underlying_Operations.py` | `m = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", str(bounds or ""))` | L1759 |
|
||||
| `.\douyin_fudai_core.py` | `m = re.search(r"(\d\{1,2\})[::](\d\{2\})", str(text or ""))` | L15 |
|
||||
| `.\douyin_fudai_core.py` | `m = re.search(r"共(\d+)份", compact)` | L57 |
|
||||
| `.\douyin_fudai_core.py` | `m = re.search(r"(\d+)人已参与", compact)` | L60 |
|
||||
| `.\douyin_reservation_verify.py` | `if re.search(patt, fc_full):` | L72 |
|
||||
| `.\fix_indent_smart.py` | `if re.match(r'^\s\{8,\}except\s+', line):` | L73 |
|
||||
| `.\fix_indent_smart.py` | `if re.match(r'^(\s*)try\s*:', lines[j]):` | L76 |
|
||||
| `.\fix_indent_smart.py` | `match_obj = re.match(r'^(\s*)', lines[j])` | L77 |
|
||||
| `.\web_gui.py` | `return re.findall(pattern, text)` | L62 |
|
||||
| `.\web_gui.py` | `m = re.search(r"(\d+)\s*小时", t)` | L207 |
|
||||
| `.\web_gui.py` | `m = re.search(r"(\d+)\s*分", t)` | L210 |
|
||||
| `.\web_gui.py` | `m = re.search(r"(\d+)\s*秒", t)` | L213 |
|
||||
| `.\web_gui.py` | `m = re.search(r"参与人数:\s*(\d+)", s)` | L264 |
|
||||
| `.\web_gui.py` | `m = re.search(r"福袋份数:\s*(\d+)", s)` | L269 |
|
||||
| `.\web_gui.py` | `m = re.search(r"奖品价值:\s*([0-9]+(?:\.[0-9]+)?)\s*元", s)` | L278 |
|
||||
| `.\web_gui.py` | `m = re.search(` | L424 |
|
||||
| `.\douyin_fudai_detail.py` | `if re.search(r"\.\{3,\}", s):` | L35 |
|
||||
| `.\douyin_fudai_detail.py` | `if re.search(r"[\u4e00-\u9fffA-Za-z]", seg):` | L80 |
|
||||
| `.\douyin_fudai_detail.py` | `m = re.search(r"(.*?)(…\|\.\{3,\})", best)` | L87 |
|
||||
| `.\douyin_fudai_detail.py` | `m2 = re.search(r"(.*?)(…\|\.\{3,\})", t)` | L93 |
|
||||
| `.\douyin_fudai_detail.py` | `m = re.search(r"(\d\{1,2\})[::](\d\{1,2\})", time_text)` | L722 |
|
||||
| `.\gui_core.py` | `return re.findall(pattern, text)` | L55 |
|
||||
| `.\gui_core.py` | `m = re.search(r"参与人数:\s*(\d+)", s)` | L176 |
|
||||
| `.\gui_core.py` | `m = re.search(r"福袋份数:\s*(\d+)", s)` | L182 |
|
||||
| `.\gui_core.py` | `m = re.search(r"奖品价值:\s*([0-9]+(?:\.[0-9]+)?)\s*元", s)` | L193 |
|
||||
| `.\douyin_utils.py` | `m = re.search(r"(\d\{1,2\})分(\d\{1,2\})秒", t)` | L23 |
|
||||
| `.\douyin_utils.py` | `m = re.search(r"(\d\{1,3\})秒", t)` | L31 |
|
||||
| `.\douyin_utils.py` | `m = re.search(r"(\d\{1,2\})[::](\d\{2\}).*后开奖", t)` | L38 |
|
||||
| `.\douyin_utils.py` | `m = re.search(r"(\d\{1,2\})后开奖(\d\{2\})", t)` | L50 |
|
||||
| `.\douyin_utils.py` | `m = re.search(r"^(\d\{1,2\})[::](\d\{1,2\})$", t)` | L58 |
|
||||
| `.\douyin_utils.py` | `currency_matches = re.findall(r"[¥¥](\d+(?:\.\d+)?)", t)` | L129 |
|
||||
| `.\douyin_utils.py` | `yuan_matches = re.findall(r"(\d+(?:\.\d+)?)元", t)` | L130 |
|
||||
| `.\douyin_utils.py` | `decimals = re.findall(r"\d+\.\d+", t)` | L146 |
|
||||
| `.\douyin_utils.py` | `ints = re.findall(r"\d+", t)` | L157 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\hub\api.py:853:23: R1729: Use a generator instead 'any(re.search(pattern, f) is not None for pattern in ignore_file_pattern)' (use-a-generator)` | L67658 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\hub\snapshot_download.py:526:40: R1729: Use a generator instead 'any(re.search(pattern, repo_file['Name']) is not None for pattern in ignore_regex_pattern)' (use-a-generator)` | L68259 |
|
||||
| `.\tools\legacy\test_follow_tab_coordinates.py` | `x_match = re.search(r'self\.yanghao_follow_tab_x\s*=\s*(\d+)', content)` | L24 |
|
||||
| `.\tools\legacy\test_follow_tab_coordinates.py` | `y_match = re.search(r'self\.yanghao_follow_tab_y\s*=\s*(\d+)', content)` | L25 |
|
||||
| `.\tools\legacy\test_follow_tab_coordinates.py` | `if re.search(usage_pattern, content):` | L45 |
|
||||
| `.\tools\legacy\test_follow_tab_coordinates.py` | `if re.search(log_pattern, content):` | L52 |
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="search" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "image.*truncat|PIL|Image\.open" • 1011 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
| File | Content | Line |
|
||||
|------|------|------|
|
||||
| `.\gui_app.py` | `from PIL import Image, ImageTk` | L13 |
|
||||
| `.\gui_app.py` | `from PIL import Image` | L1245 |
|
||||
| `.\gui_app.py` | `img = Image.open(screenshot_path)` | L1269 |
|
||||
| `.\gui_app.py` | `img = Image.open(img_path).convert("RGB")` | L1509 |
|
||||
| `.\douyin_detection.py` | `from PIL import Image` | L21 |
|
||||
| `.\douyin_detection.py` | `pic = Image.open(pic1_path)` | L43 |
|
||||
| `.\douyin_detection.py` | `pic = Image.open(pic1_path)` | L187 |
|
||||
| `.\douyin_detection.py` | `pic = Image.open(pic1_path)` | L193 |
|
||||
| `.\douyin_detection.py` | `# 将PIL图片转换为OpenCV格式` | L387 |
|
||||
| `.\douyin_detection.py` | `from PIL import Image as PILImage` | L476 |
|
||||
| `.\douyin_detection.py` | `search_roi_pil = PILImage.fromarray(` | L478 |
|
||||
| `.\douyin_detection.py` | `search_roi_pil,` | L482 |
|
||||
| `.\douyin_detection.py` | `from PIL import Image as PILImage` | L510 |
|
||||
| `.\douyin_detection.py` | `search_roi_pil = PILImage.fromarray(` | L512 |
|
||||
| `.\douyin_detection.py` | `search_roi_pil,` | L518 |
|
||||
| `.\douyin_detection.py` | `from PIL import Image as PILImage` | L904 |
|
||||
| `.\douyin_detection.py` | `search_roi_pil = PILImage.fromarray(` | L906 |
|
||||
| `.\douyin_detection.py` | `search_roi_pil, operation_type="template_match"` | L910 |
|
||||
| `.\douyin_detection.py` | `from PIL import Image as PILImage` | L934 |
|
||||
| `.\douyin_detection.py` | `search_roi_pil = PILImage.fromarray(` | L936 |
|
||||
| `.\douyin_detection.py` | `search_roi_pil, operation_type="template_match"` | L940 |
|
||||
| `.\douyin_detection.py` | `pic0 = Image.open(pic1_path)` | L1118 |
|
||||
| `.\douyin_detection.py` | `pic0 = Image.open(pic1_path)` | L1124 |
|
||||
| `.\fix_indentation.py` | `compile(original_content, file_path, 'exec')` | L139 |
|
||||
| `.\fix_indentation.py` | `compile(fixed_content, file_path, 'exec')` | L152 |
|
||||
| `.\douyin_screenshot_manager.py` | `from PIL import Image` | L17 |
|
||||
| `.\douyin_screenshot_manager.py` | `image: PIL Image 对象` | L181 |
|
||||
| `.\douyin_screenshot_manager.py` | `image: PIL Image 对象` | L204 |
|
||||
| `.\douyin_screenshot_manager.py` | `image = Image.open(source_path)` | L236 |
|
||||
| `.\douyin_screenshot_manager.py` | `image.load() # Force load to catch truncated files early` | L237 |
|
||||
| `.\douyin_screenshot_manager.py` | `image = Image.open(source_path)` | L260 |
|
||||
| `.\douyin_screenshot_manager.py` | `image.load() # Force load to catch truncated files early` | L261 |
|
||||
| `.\Underlying_Operations.py` | `from PIL import Image, ImageFilter` | L18 |
|
||||
| `.\Underlying_Operations.py` | `from PIL import UnidentifiedImageError` | L19 |
|
||||
| `.\Underlying_Operations.py` | `# Pillow 版本兼容:使用 Image.Resampling 或回退到 Image 常量` | L32 |
|
||||
| `.\Underlying_Operations.py` | `# devicelist = re.compile(r'(\w*)\s*device\b').findall(totalstring)` | L364 |
|
||||
| `.\Underlying_Operations.py` | `pic = Image.open(pic1_path)` | L754 |
|
||||
| `.\Underlying_Operations.py` | `pic = Image.open(pic1_path)` | L832 |
|
||||
| `.\Underlying_Operations.py` | `img = Image.open(pic_path)` | L909 |
|
||||
| `.\Underlying_Operations.py` | `img = Image.open(pic_path)` | L911 |
|
||||
| `.\Underlying_Operations.py` | `from PIL import ImageEnhance` | L934 |
|
||||
| `.\Underlying_Operations.py` | `from PIL import ImageEnhance` | L963 |
|
||||
| `.\douyin_pixel.py` | `from PIL import Image` | L5 |
|
||||
| `.\douyin_pixel.py` | `pic = Image.open(pic_path)` | L12 |
|
||||
| `.\web_gui.py` | `_ANSI_ESCAPE_RE = re.compile(r"\x1B(?:[@-Z\\-_]\|\[[0-?]*[ -/]*[@-~])")` | L18 |
|
||||
| `.\tools\legacy\view_image_coords.py` | `from PIL import Image` | L8 |
|
||||
| `.\tools\legacy\view_image_coords.py` | `img = Image.open(image_path)` | L24 |
|
||||
| `.\douyin_fudai_detail.py` | `from PIL import Image` | L21 |
|
||||
| `.\douyin_fudai_detail.py` | `pic = Image.open(path)` | L197 |
|
||||
| `.\tools\pick_coords.py` | `from PIL import Image, ImageTk` | L5 |
|
||||
| `.\tools\pick_coords.py` | `self.img = Image.open(image_path).convert("RGB")` | L85 |
|
||||
| `.\tools\pick_coords.py` | `resample = Image.Resampling.BICUBIC # Pillow>=9` | L105 |
|
||||
| `.\tools\pick_coords.py` | `resample = Image.BICUBIC # older Pillow` | L107 |
|
||||
| `.\tools\sanitize_cursor_paths.py` | `_CURSOR_RE = re.compile(r"C:\\Users\\[^\\\s]+\\.cursor\\worktrees\\")` | L24 |
|
||||
| `.\README.md` | `- **Pillow(PIL)**:图像处理库` | L154 |
|
||||
| `.\README.md` | `pip install pillow paddlepaddle paddleocr numpy opencv-python` | L268 |
|
||||
| `.\douyin_popups.py` | `from PIL import Image` | L5 |
|
||||
| `.\douyin_popups.py` | `pic = Image.open(pic_path).convert("RGB")` | L15 |
|
||||
| `.\douyin_popups.py` | `pic = Image.open(pic_path).convert("RGB")` | L49 |
|
||||
| `.\pylint_report.txt` | `douyin_detection.py:21:0: C0413: Import "from PIL import Image" should be placed at the top of the module (wrong-import-position)` | L4053 |
|
||||
| `.\pylint_report.txt` | `douyin_detection.py:416:40: C0415: Import outside toplevel (PIL.Image) (import-outside-toplevel)` | L4118 |
|
||||
| `.\pylint_report.txt` | `douyin_detection.py:442:44: C0415: Import outside toplevel (PIL.Image) (import-outside-toplevel)` | L4132 |
|
||||
| `.\pylint_report.txt` | `douyin_detection.py:808:16: C0415: Import outside toplevel (PIL.Image) (import-outside-toplevel)` | L4219 |
|
||||
| `.\pylint_report.txt` | `douyin_detection.py:833:20: C0415: Import outside toplevel (PIL.Image) (import-outside-toplevel)` | L4232 |
|
||||
| `.\pylint_report.txt` | `douyin_fudai_detail.py:21:0: C0413: Import "from PIL import Image" should be placed at the top of the module (wrong-import-position)` | L5128 |
|
||||
| `.\pylint_report.txt` | `douyin_screenshot_manager.py:17:0: C0413: Import "from PIL import Image" should be placed at the top of the module (wrong-import-position)` | L5737 |
|
||||
| `.\pylint_report.txt` | `gui_app.py:1245:16: C0415: Import outside toplevel (PIL.Image) (import-outside-toplevel)` | L6308 |
|
||||
| `.\pylint_report.txt` | `gui_app.py:1514:38: E1101: Module 'PIL.Image' has no 'LANCZOS' member (no-member)` | L6320 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:18:0: C0413: Import "from PIL import Image, ImageFilter" should be placed at the top of the module (wrong-import-position)` | L6469 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:907:57: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L6581 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:914:8: C0415: Import outside toplevel (PIL.ImageEnhance) (import-outside-toplevel)` | L6582 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:952:50: E1101: Module 'PIL.Image' has no 'LANCZOS' member (no-member)` | L6585 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:955:20: C0415: Import outside toplevel (PIL.ImageEnhance) (import-outside-toplevel)` | L6588 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:20:0: C0411: standard import "logging" should be placed before third party imports "PIL.Image", "numpy" (wrong-import-order)` | L6648 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:21:0: C0411: standard import "re" should be placed before third party imports "PIL.Image", "numpy" (wrong-import-order)` | L6649 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:22:0: C0411: standard import "random" should be placed before third party imports "PIL.Image", "numpy" (wrong-import-order)` | L6650 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:23:0: C0411: standard import "xml.etree.ElementTree" should be placed before third party imports "PIL.Image", "numpy" (wrong-import-order)` | L6651 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:24:0: C0411: standard import "shlex" should be placed before third party imports "PIL.Image", "numpy" (wrong-import-order)` | L6652 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:25:0: C0411: standard import "contextlib" should be placed before third party imports "PIL.Image", "numpy" (wrong-import-order)` | L6653 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:27:0: C0411: standard import "base64" should be placed before third party imports "PIL.Image", "numpy" (wrong-import-order)` | L6654 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:28:0: C0411: standard import "typing.Tuple" should be placed before third party imports "PIL.Image", "numpy" (wrong-import-order)` | L6655 |
|
||||
| `.\pylint_report.txt` | `Underlying_Operations.py:29:0: C0411: standard import "time" should be placed before third party imports "PIL.Image", "numpy" (wrong-import-order)` | L6656 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\pycodestyle.py:69:4: W0212: Access to a protected member _compile of a client class (protected-access)` | L7360 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\pycodestyle.py:69:34: W0212: Access to a protected member _compile of a client class (protected-access)` | L7361 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\cv2\gapi\__init__.py:21:20: E1101: Module 'cv2' has no 'GCompileArg' member (no-member)` | L32946 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\cv2\gapi\__init__.py:21:20: E1101: Module 'cv2' has no 'GCompileArg' member (no-member)` | L33248 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\cv2\gapi\wip\draw\__init__.pyi:111:101: E1101: Module 'cv2' has no 'GCompileArg' member (no-member)` | L33910 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\cv2\gapi\wip\draw\__init__.pyi:113:135: E1101: Module 'cv2' has no 'GCompileArg' member (no-member)` | L33911 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\cv2\ocl\__init__.pyi:113:4: C0103: Method name "compilerAvailable" doesn't conform to snake_case naming style (invalid-name)` | L35571 |
|
||||
| `.\pylint_report.txt` | `************* Module .venv.Lib.site-packages.google.protobuf.compiler.plugin_pb2` | L55378 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:28:0: C0301: Line too long (1860/100) (line-too-long)` | L55379 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:34:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55380 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:35:0: C0301: Line too long (180/100) (line-too-long)` | L55381 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:35:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55382 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:36:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55383 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:37:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55384 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:38:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55385 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:39:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55386 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:40:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55387 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:41:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55388 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:42:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55389 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:43:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55390 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:44:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55391 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:45:0: W0311: Bad indentation. Found 2 spaces, expected 4 (bad-indentation)` | L55392 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:25:0: C0413: Import "from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor__pb2" should be placed at the top of the module (wrong-import-position)` | L55393 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:33:7: W0212: Access to a protected member _USE_C_DESCRIPTORS of a client class (protected-access)` | L55394 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:34:2: W0212: Access to a protected member _loaded_options of a client class (protected-access)` | L55395 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:35:2: W0212: Access to a protected member _serialized_options of a client class (protected-access)` | L55396 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:36:2: W0212: Access to a protected member _serialized_start of a client class (protected-access)` | L55397 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:37:2: W0212: Access to a protected member _serialized_end of a client class (protected-access)` | L55398 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:38:2: W0212: Access to a protected member _serialized_start of a client class (protected-access)` | L55399 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:39:2: W0212: Access to a protected member _serialized_end of a client class (protected-access)` | L55400 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:40:2: W0212: Access to a protected member _serialized_start of a client class (protected-access)` | L55401 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:41:2: W0212: Access to a protected member _serialized_end of a client class (protected-access)` | L55402 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:42:2: W0212: Access to a protected member _serialized_start of a client class (protected-access)` | L55403 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:43:2: W0212: Access to a protected member _serialized_end of a client class (protected-access)` | L55404 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:44:2: W0212: Access to a protected member _serialized_start of a client class (protected-access)` | L55405 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:45:2: W0212: Access to a protected member _serialized_end of a client class (protected-access)` | L55406 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\google\protobuf\compiler\plugin_pb2.py:25:0: W0611: Unused descriptor_pb2 imported from google.protobuf as google_dot_protobuf_dot_descriptor__pb2 (unused-import)` | L55407 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\huggingface_hub\inference\_common.py:110:4: C0415: Import outside toplevel (PIL.Image) (import-outside-toplevel)` | L63794 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\huggingface_hub\inference\_common.py:176:8: C0415: Import outside toplevel (PIL.Image) (import-outside-toplevel)` | L63798 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\base\base_torch_model.py:135:4: W0221: Variadics removed in overriding 'TorchModel.compile' method (arguments-differ)` | L71408 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\dense_optical_flow_estimation\core\utils\frame_utils.py:128:24: W0613: Unused argument 'pil' (unused-argument)` | L74391 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\face_attribute_recognition\fair_face\face_attribute_recognition.py:12:0: W0611: Unused Image imported from PIL (unused-import)` | L74417 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\face_detection\mtcnn\models\box_utils.py:156:47: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L74525 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\face_detection\mtcnn\models\first_stage.py:32:33: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L74538 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\face_emotion\emotion_infer.py:13:0: C0103: Function name "transform_PIL" doesn't conform to snake_case naming style (invalid-name)` | L75216 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\face_emotion\face_alignment\face_align.py:46:0: C0103: Function name "face_detection_PIL_v2" doesn't conform to snake_case naming style (invalid-name)` | L75350 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\face_reconstruction\utils.py:717:42: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L76062 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\face_reconstruction\utils.py:721:44: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L76063 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\facial_68ldk_detection\lib\dataset\alignmentDataset.py:13:0: W0611: Unused Image imported from PIL (unused-import)` | L76832 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\facial_68ldk_detection\lib\dataset\alignmentDataset.py:13:0: W0611: Unused ImageEnhance imported from PIL (unused-import)` | L76833 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\facial_expression_recognition\fer\transforms.py:85:32: E1101: Module 'PIL.Image' has no 'FLIP_TOP_BOTTOM' member (no-member)` | L76883 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\facial_expression_recognition\fer\transforms.py:87:32: E1101: Module 'PIL.Image' has no 'FLIP_LEFT_RIGHT' member (no-member)` | L76884 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\facial_landmark_confidence\flc\facial_landmark_confidence.py:9:0: W0611: Unused Image imported from PIL (unused-import)` | L76923 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\human_image_generation\human_image_generation_infer.py:30:20: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L77527 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\human_image_generation\human_image_generation_infer.py:31:21: E1101: Module 'PIL.Image' has no 'NEAREST' member (no-member)` | L77528 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\human_reconstruction\Reconstruction.py:7:0: R0402: Use 'from PIL import Image' instead (consider-using-from-import)` | L77987 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_control_3d_portrait\image_control_3d_portrait.py:10:0: R0402: Use 'from PIL import Image' instead (consider-using-from-import)` | L79205 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_control_3d_portrait\image_control_3d_portrait.py:258:42: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L79253 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_control_3d_portrait\image_control_3d_portrait.py:262:48: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L79254 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_control_3d_portrait\image_control_3d_portrait.py:313:48: E1101: Module 'PIL.Image' has no 'LANCZOS' member (no-member)` | L79262 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_control_3d_portrait\network\triplane.py:174:21: W0613: Unused argument 'truncation_psi' (unused-argument)` | L79523 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_control_3d_portrait\network\triplane.py:175:21: W0613: Unused argument 'truncation_cutoff' (unused-argument)` | L79524 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_face_fusion\image_face_fusion.py:8:0: R0402: Use 'from PIL import Image' instead (consider-using-from-import)` | L80482 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_human_parsing\parsing_utils.py:114:21: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L81139 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_human_parsing\parsing_utils.py:142:12: C0103: Variable name "_PIL_RESIZE_TO_INTERPOLATE_MODE" doesn't conform to snake_case naming style (invalid-name)` | L81141 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_human_parsing\parsing_utils.py:143:16: E1101: Module 'PIL.Image' has no 'NEAREST' member (no-member)` | L81142 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_human_parsing\parsing_utils.py:144:16: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L81143 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_human_parsing\parsing_utils.py:145:16: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L81144 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_matching_fast\lightglue\lightglue.py:442:4: W0221: Variadics removed in overriding 'LightGlue.compile' method (arguments-differ)` | L82387 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_probing_model\backbone.py:14:0: W0611: Unused Image imported from PIL (unused-import)` | L83762 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_skychange\skychange.py:12:0: W0611: Unused Image imported from PIL (unused-import)` | L84620 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_to_3d\ldm\util.py:80:32: E1101: Module 'PIL.Image' has no 'LANCZOS' member (no-member)` | L85718 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_to_3d\ldm\modules\encoders\clip\clip.py:21:14: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L86498 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_to_image_generation\data\transforms.py:65:35: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L86657 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_to_image_generation\data\transforms.py:84:36: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L86661 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_to_image_translation\data\transforms.py:65:35: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L86940 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_to_image_translation\data\transforms.py:84:36: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L86944 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\image_try_on\try_on_infer.py:12:0: W0611: Unused Image imported from PIL (unused-import)` | L87633 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\movie_scene_segmentation\model.py:68:46: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L89286 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\nerf_recon_acc\dataloader\nerf_dataset.py:399:48: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L90025 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\nerf_recon_acc\dataloader\nerf_dataset.py:404:54: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L90026 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\nerf_recon_vq_compression\dataloader\blender.py:119:46: E1101: Module 'PIL.Image' has no 'LANCZOS' member (no-member)` | L90290 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\nerf_recon_vq_compression\dataloader\llff.py:242:46: E1101: Module 'PIL.Image' has no 'LANCZOS' member (no-member)` | L90325 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\nerf_recon_vq_compression\dataloader\nsvf.py:123:46: E1101: Module 'PIL.Image' has no 'LANCZOS' member (no-member)` | L90363 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\nerf_recon_vq_compression\dataloader\tankstemple.py:178:46: E1101: Module 'PIL.Image' has no 'LANCZOS' member (no-member)` | L90427 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\object_detection_3d\depe\mmdet3d_plugin\datasets\pipelines\transform_3d.py:187:39: E1101: Module 'PIL.Image' has no 'FLIP_LEFT_RIGHT' member (no-member)` | L91221 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\product_segmentation\seg_infer.py:6:0: W0611: Unused Image imported from PIL (unused-import)` | L92776 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\shop_segmentation\shop_seg_model.py:59:51: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L93974 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\shop_segmentation\shop_seg_model.py:77:55: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L93980 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\text_driven_segmentation\clip.py:26:14: E1101: Module 'PIL.Image' has no 'BICUBIC' member (no-member)` | L94845 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\text_driven_segmentation\lseg_model.py:58:51: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L94893 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\text_driven_segmentation\lseg_model.py:72:55: E1101: Module 'PIL.Image' has no 'BILINEAR' member (no-member)` | L94899 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\text_texture_generation\Tex2Texture.py:12:0: R0402: Use 'from PIL import Image' instead (consider-using-from-import)` | L95107 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\text_texture_generation\Tex2Texture.py:221:51: E1101: Module 'PIL.Image' has no 'LANCZOS' member (no-member)` | L95126 |
|
||||
| `.\pylint_report.txt` | `.venv\Lib\site-packages\modelscope\models\cv\text_texture_generation\Tex2Texture.py:238:51: E1101: Module 'PIL.Image' has no 'LANCZOS' member (no-member)` | L95127 |
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: douyin_fudai.py</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: douyin_fudai.py</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: douyin_fudai.py</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
检查更多可能导致这些错误的代码段:
|
||||
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: douyin_fudai.py</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: douyin_utils.py</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: douyin_fudai_core.py</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="search" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "^\s+(if|elif|else|for|while|def|class|try|except|finally)" in "douyin_fudai.py" • 378 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
| File | Content | Line |
|
||||
|------|------|------|
|
||||
| `douyin_fudai.py` | `def __init__(self) -> None:` | L43 |
|
||||
| `douyin_fudai.py` | `try:` | L58 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L62 |
|
||||
| `douyin_fudai.py` | `def click(self, x: int, y: int) -> None:` | L165 |
|
||||
| `douyin_fudai.py` | `try:` | L167 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L169 |
|
||||
| `douyin_fudai.py` | `def load_config(self) -> None:` | L172 |
|
||||
| `douyin_fudai.py` | `try:` | L178 |
|
||||
| `douyin_fudai.py` | `if not os.path.exists(path):` | L179 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L183 |
|
||||
| `douyin_fudai.py` | `try:` | L186 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L188 |
|
||||
| `douyin_fudai.py` | `try:` | L190 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L192 |
|
||||
| `douyin_fudai.py` | `def _float(name: str, default: float) -> float:` | L195 |
|
||||
| `douyin_fudai.py` | `try:` | L196 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L198 |
|
||||
| `douyin_fudai.py` | `def _int(name: str, default: int) -> int:` | L201 |
|
||||
| `douyin_fudai.py` | `try:` | L202 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L204 |
|
||||
| `douyin_fudai.py` | `try:` | L216 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L220 |
|
||||
| `douyin_fudai.py` | `if self.lucky_draw_red_ratio_threshold < 0.0:` | L243 |
|
||||
| `douyin_fudai.py` | `if self.lucky_draw_red_ratio_threshold > 1.0:` | L245 |
|
||||
| `douyin_fudai.py` | `if self.live_room_match_threshold < 0.0:` | L252 |
|
||||
| `douyin_fudai.py` | `if self.live_room_match_threshold > 1.0:` | L254 |
|
||||
| `douyin_fudai.py` | `if self.fudai_template_match_threshold < 0.0:` | L262 |
|
||||
| `douyin_fudai.py` | `if self.fudai_template_match_threshold > 1.0:` | L264 |
|
||||
| `douyin_fudai.py` | `try:` | L268 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L272 |
|
||||
| `douyin_fudai.py` | `if self.high_value_fudai_max_reservations < 1:` | L292 |
|
||||
| `douyin_fudai.py` | `if self.high_value_fudai_max_reservations > 50:` | L294 |
|
||||
| `douyin_fudai.py` | `try:` | L297 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L309 |
|
||||
| `douyin_fudai.py` | `if self.high_value_fudai_after_action not in ("stay", "continue"):` | L311 |
|
||||
| `douyin_fudai.py` | `if self.high_value_fudai_after_stay_seconds < 0:` | L318 |
|
||||
| `douyin_fudai.py` | `if self.high_value_fudai_after_stay_seconds > 3600:` | L320 |
|
||||
| `douyin_fudai.py` | `try:` | L324 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L331 |
|
||||
| `douyin_fudai.py` | `try:` | L333 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L340 |
|
||||
| `douyin_fudai.py` | `try:` | L344 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L351 |
|
||||
| `douyin_fudai.py` | `try:` | L355 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L359 |
|
||||
| `douyin_fudai.py` | `try:` | L361 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L366 |
|
||||
| `douyin_fudai.py` | `if self.reset_after_swipes < 1:` | L368 |
|
||||
| `douyin_fudai.py` | `try:` | L372 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L391 |
|
||||
| `douyin_fudai.py` | `try:` | L395 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L402 |
|
||||
| `douyin_fudai.py` | `if self.reservation_back_swipe_delay < 0.0:` | L409 |
|
||||
| `douyin_fudai.py` | `if self.reservation_preempt_min_value_yuan < 0.0:` | L416 |
|
||||
| `douyin_fudai.py` | `if self.poll_before_open_seconds < 0:` | L423 |
|
||||
| `douyin_fudai.py` | `def fudai_choujiang(` | L427 |
|
||||
| `douyin_fudai.py` | `try:` | L437 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L442 |
|
||||
| `douyin_fudai.py` | `if wait_minutes and wait_minutes > 0:` | L455 |
|
||||
| `douyin_fudai.py` | `while time.time() < end_ts:` | L457 |
|
||||
| `douyin_fudai.py` | `try:` | L458 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L460 |
|
||||
| `douyin_fudai.py` | `try:` | L462 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L469 |
|
||||
| `douyin_fudai.py` | `try:` | L472 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L474 |
|
||||
| `douyin_fudai.py` | `try:` | L479 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L481 |
|
||||
| `douyin_fudai.py` | `else:` | L483 |
|
||||
| `douyin_fudai.py` | `while True:` | L486 |
|
||||
| `douyin_fudai.py` | `try:` | L487 |
|
||||
| `douyin_fudai.py` | `except KeyboardInterrupt:` | L489 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L493 |
|
||||
| `douyin_fudai.py` | `try:` | L495 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L502 |
|
||||
| `douyin_fudai.py` | `try:` | L505 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L507 |
|
||||
| `douyin_fudai.py` | `try:` | L512 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L514 |
|
||||
| `douyin_fudai.py` | `def _diagnose_stage_from_current_screen(self) -> Tuple[str, str]:` | L518 |
|
||||
| `douyin_fudai.py` | `def cut_pic(` | L523 |
|
||||
| `douyin_fudai.py` | `try:` | L534 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L540 |
|
||||
| `douyin_fudai.py` | `try:` | L541 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L552 |
|
||||
| `douyin_fudai.py` | `def _read_pixel_stage_state(self) -> dict:` | L555 |
|
||||
| `douyin_fudai.py` | `def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]:` | L575 |
|
||||
| `douyin_fudai.py` | `try:` | L580 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L587 |
|
||||
| `douyin_fudai.py` | `try:` | L588 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L590 |
|
||||
| `douyin_fudai.py` | `def _save_step_screenshot(self, label: str) -> None:` | L593 |
|
||||
| `douyin_fudai.py` | `try:` | L595 |
|
||||
| `douyin_fudai.py` | `try:` | L602 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L604 |
|
||||
| `douyin_fudai.py` | `if not os.path.exists(src):` | L607 |
|
||||
| `douyin_fudai.py` | `try:` | L613 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L615 |
|
||||
| `douyin_fudai.py` | `try:` | L617 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L619 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L621 |
|
||||
| `douyin_fudai.py` | `def _check_in_live_room_by_icon(self) -> Tuple[bool, float]:` | L624 |
|
||||
| `douyin_fudai.py` | `try:` | L631 |
|
||||
| `douyin_fudai.py` | `try:` | L640 |
|
||||
| `douyin_fudai.py` | `except (AttributeError, Exception):` | L642 |
|
||||
| `douyin_fudai.py` | `try:` | L644 |
|
||||
| `douyin_fudai.py` | `if hasattr(cv2, "utils") and hasattr(cv2.utils, "logging"):` | L646 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L650 |
|
||||
| `douyin_fudai.py` | `try:` | L653 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L657 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L659 |
|
||||
| `douyin_fudai.py` | `try:` | L660 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L665 |
|
||||
| `douyin_fudai.py` | `try:` | L675 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L677 |
|
||||
| `douyin_fudai.py` | `if not os.path.exists(screenshot_path):` | L681 |
|
||||
| `douyin_fudai.py` | `try:` | L682 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L688 |
|
||||
| `douyin_fudai.py` | `try:` | L692 |
|
||||
| `douyin_fudai.py` | `if img is None:` | L694 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L696 |
|
||||
| `douyin_fudai.py` | `try:` | L697 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L701 |
|
||||
| `douyin_fudai.py` | `if threshold < 0.0:` | L711 |
|
||||
| `douyin_fudai.py` | `if threshold > 1.0:` | L713 |
|
||||
| `douyin_fudai.py` | `if template_threshold < 0.0:` | L715 |
|
||||
| `douyin_fudai.py` | `if template_threshold > 1.0:` | L717 |
|
||||
| `douyin_fudai.py` | `if roi.size == 0:` | L728 |
|
||||
| `douyin_fudai.py` | `try:` | L729 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L731 |
|
||||
| `douyin_fudai.py` | `try:` | L741 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L745 |
|
||||
| `douyin_fudai.py` | `try:` | L746 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L750 |
|
||||
| `douyin_fudai.py` | `for template_path, roi_path, icon_name in template_roi_pairs:` | L765 |
|
||||
| `douyin_fudai.py` | `try:` | L766 |
|
||||
| `douyin_fudai.py` | `if not os.path.exists(template_path) or not os.path.isfile(` | L768 |
|
||||
| `douyin_fudai.py` | `try:` | L772 |
|
||||
| `douyin_fudai.py` | `if os.path.getsize(template_path) == 0:` | L773 |
|
||||
| `douyin_fudai.py` | `except (OSError, IOError):` | L775 |
|
||||
| `douyin_fudai.py` | `if not os.path.exists(roi_path) or not os.path.isfile(roi_path):` | L779 |
|
||||
| `douyin_fudai.py` | `try:` | L783 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L786 |
|
||||
| `douyin_fudai.py` | `if tpl is None or roi_img is None:` | L789 |
|
||||
| `douyin_fudai.py` | `if th > rh or tw > rw:` | L796 |
|
||||
| `douyin_fudai.py` | `if scale <= 0:` | L799 |
|
||||
| `douyin_fudai.py` | `if max_val > best_score:` | L811 |
|
||||
| `douyin_fudai.py` | `if max_val >= template_threshold:` | L817 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L819 |
|
||||
| `douyin_fudai.py` | `if not detected and best_score == 0.0:` | L822 |
|
||||
| `douyin_fudai.py` | `try:` | L823 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L827 |
|
||||
| `douyin_fudai.py` | `try:` | L830 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L838 |
|
||||
| `douyin_fudai.py` | `def check_in_fudai_detail(self) -> bool:` | L843 |
|
||||
| `douyin_fudai.py` | `try:` | L845 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L847 |
|
||||
| `douyin_fudai.py` | `try:` | L848 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L850 |
|
||||
| `douyin_fudai.py` | `def _enhanced_log_kv(self, *args, **fields):` | L854 |
|
||||
| `douyin_fudai.py` | `if len(args) >= 1:` | L857 |
|
||||
| `douyin_fudai.py` | `else:` | L861 |
|
||||
| `douyin_fudai.py` | `if len(args) >= 2:` | L864 |
|
||||
| `douyin_fudai.py` | `else:` | L868 |
|
||||
| `douyin_fudai.py` | `if log_level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):` | L873 |
|
||||
| `douyin_fudai.py` | `try:` | L877 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L879 |
|
||||
| `douyin_fudai.py` | `try:` | L883 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L887 |
|
||||
| `douyin_fudai.py` | `try:` | L889 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L893 |
|
||||
| `douyin_fudai.py` | `try:` | L898 |
|
||||
| `douyin_fudai.py` | `if frame:` | L903 |
|
||||
| `douyin_fudai.py` | `if caller_frame:` | L907 |
|
||||
| `douyin_fudai.py` | `if (` | L909 |
|
||||
| `douyin_fudai.py` | `if caller_frame:` | L915 |
|
||||
| `douyin_fudai.py` | `if filename and filename not in ("<string>", "<stdin>"):` | L924 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L926 |
|
||||
| `douyin_fudai.py` | `if timestamp:` | L963 |
|
||||
| `douyin_fudai.py` | `if caller_info:` | L969 |
|
||||
| `douyin_fudai.py` | `if msg:` | L972 |
|
||||
| `douyin_fudai.py` | `if len(m) > 200:` | L974 |
|
||||
| `douyin_fudai.py` | `for k, v in fields.items():` | L979 |
|
||||
| `douyin_fudai.py` | `if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"):` | L980 |
|
||||
| `douyin_fudai.py` | `if v is None:` | L982 |
|
||||
| `douyin_fudai.py` | `if isinstance(v, float):` | L986 |
|
||||
| `douyin_fudai.py` | `if abs(v) < 1:` | L987 |
|
||||
| `douyin_fudai.py` | `elif abs(v) < 100:` | L989 |
|
||||
| `douyin_fudai.py` | `else:` | L991 |
|
||||
| `douyin_fudai.py` | `elif isinstance(v, (int, bool)):` | L993 |
|
||||
| `douyin_fudai.py` | `else:` | L995 |
|
||||
| `douyin_fudai.py` | `if len(s) > 100:` | L997 |
|
||||
| `douyin_fudai.py` | `try:` | L1006 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1008 |
|
||||
| `douyin_fudai.py` | `try:` | L1012 |
|
||||
| `douyin_fudai.py` | `if not hasattr(self, "_std_logger") or self._std_logger is None:` | L1013 |
|
||||
| `douyin_fudai.py` | `try:` | L1014 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1018 |
|
||||
| `douyin_fudai.py` | `if hasattr(self, "_std_logger") and self._std_logger:` | L1021 |
|
||||
| `douyin_fudai.py` | `if caller_info:` | L1024 |
|
||||
| `douyin_fudai.py` | `if msg:` | L1026 |
|
||||
| `douyin_fudai.py` | `for k, v in fields.items():` | L1029 |
|
||||
| `douyin_fudai.py` | `if k in (` | L1030 |
|
||||
| `douyin_fudai.py` | `if v is not None:` | L1039 |
|
||||
| `douyin_fudai.py` | `if exc_info is None:` | L1046 |
|
||||
| `douyin_fudai.py` | `if sys.exc_info()[0] is not None:` | L1047 |
|
||||
| `douyin_fudai.py` | `if exc_info:` | L1052 |
|
||||
| `douyin_fudai.py` | `else:` | L1059 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1063 |
|
||||
| `douyin_fudai.py` | `if exc_info is None:` | L1068 |
|
||||
| `douyin_fudai.py` | `if sys.exc_info()[0] is not None:` | L1069 |
|
||||
| `douyin_fudai.py` | `if exc_info:` | L1072 |
|
||||
| `douyin_fudai.py` | `try:` | L1073 |
|
||||
| `douyin_fudai.py` | `for line in tb_str:` | L1077 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1079 |
|
||||
| `douyin_fudai.py` | `def _log_step_time(` | L1083 |
|
||||
| `douyin_fudai.py` | `try:` | L1087 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1089 |
|
||||
| `douyin_fudai.py` | `if extra_info:` | L1092 |
|
||||
| `douyin_fudai.py` | `for k, v in extra_info.items():` | L1093 |
|
||||
| `douyin_fudai.py` | `try:` | L1095 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1097 |
|
||||
| `douyin_fudai.py` | `def _check_coupon_popup(self) -> bool:` | L1101 |
|
||||
| `douyin_fudai.py` | `def _check_shopping_redpacket_popup(self) -> bool:` | L1105 |
|
||||
| `douyin_fudai.py` | `def run_once_basic(self) -> None:` | L1110 |
|
||||
| `douyin_fudai.py` | `try:` | L1113 |
|
||||
| `douyin_fudai.py` | `if getattr(self, "high_value_fudai_enabled", False) and self.reservations:` | L1114 |
|
||||
| `douyin_fudai.py` | `def _swipe_down_once() -> None:` | L1116 |
|
||||
| `douyin_fudai.py` | `def _sort_reservations() -> None:` | L1119 |
|
||||
| `douyin_fudai.py` | `def _write_state() -> None:` | L1122 |
|
||||
| `douyin_fudai.py` | `try:` | L1124 |
|
||||
| `douyin_fudai.py` | `for r in self.reservations or []:` | L1135 |
|
||||
| `douyin_fudai.py` | `try:` | L1136 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1138 |
|
||||
| `douyin_fudai.py` | `try:` | L1140 |
|
||||
| `douyin_fudai.py` | `if ft` | L1145 |
|
||||
| `douyin_fudai.py` | `else ""` | L1146 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1148 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L1190 |
|
||||
| `douyin_fudai.py` | `try:` | L1191 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1198 |
|
||||
| `douyin_fudai.py` | `def _seek_reservation_room(item: dict) -> bool:` | L1206 |
|
||||
| `douyin_fudai.py` | `try:` | L1207 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1209 |
|
||||
| `douyin_fudai.py` | `if (` | L1216 |
|
||||
| `douyin_fudai.py` | `if waiting:` | L1236 |
|
||||
| `douyin_fudai.py` | `if focus_ref:` | L1238 |
|
||||
| `douyin_fudai.py` | `if self.queue_full_waiting_at_earliest and not self.reservations:` | L1244 |
|
||||
| `douyin_fudai.py` | `try:` | L1245 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1250 |
|
||||
| `douyin_fudai.py` | `try:` | L1255 |
|
||||
| `douyin_fudai.py` | `if back_times > 0:` | L1258 |
|
||||
| `douyin_fudai.py` | `for i in range(back_times):` | L1259 |
|
||||
| `douyin_fudai.py` | `if hasattr(self, "_swipe_times"):` | L1263 |
|
||||
| `douyin_fudai.py` | `try:` | L1265 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1271 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1273 |
|
||||
| `douyin_fudai.py` | `if focus_ref:` | L1292 |
|
||||
| `douyin_fudai.py` | `if after_action_ref:` | L1294 |
|
||||
| `douyin_fudai.py` | `if preempted:` | L1297 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1300 |
|
||||
| `douyin_fudai.py` | `if not ok:` | L1305 |
|
||||
| `douyin_fudai.py` | `try:` | L1316 |
|
||||
| `douyin_fudai.py` | `try:` | L1318 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1320 |
|
||||
| `douyin_fudai.py` | `if top_pkg and (` | L1322 |
|
||||
| `douyin_fudai.py` | `try:` | L1327 |
|
||||
| `douyin_fudai.py` | `try:` | L1334 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1336 |
|
||||
| `douyin_fudai.py` | `try:` | L1342 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1348 |
|
||||
| `douyin_fudai.py` | `try:` | L1350 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1358 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L1362 |
|
||||
| `douyin_fudai.py` | `try:` | L1363 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1365 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1367 |
|
||||
| `douyin_fudai.py` | `if stage == "COUPON_POPUP":` | L1372 |
|
||||
| `douyin_fudai.py` | `try:` | L1375 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L1379 |
|
||||
| `douyin_fudai.py` | `elif stage == "SHOPPING_REDPACKET_POPUP":` | L1382 |
|
||||
| `douyin_fudai.py` | `try:` | L1385 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L1391 |
|
||||
| `douyin_fudai.py` | `elif stage == "FUDai_DETAIL":` | L1394 |
|
||||
| `douyin_fudai.py` | `elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"):` | L1397 |
|
||||
| `douyin_fudai.py` | `elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"):` | L1400 |
|
||||
| `douyin_fudai.py` | `if stage == "RECOMMEND_PAGE":` | L1402 |
|
||||
| `douyin_fudai.py` | `try:` | L1410 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L1432 |
|
||||
| `douyin_fudai.py` | `try:` | L1435 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1438 |
|
||||
| `douyin_fudai.py` | `else:` | L1440 |
|
||||
| `douyin_fudai.py` | `elif stage in ("LIVE_CLOSED",):` | L1443 |
|
||||
| `douyin_fudai.py` | `else:` | L1447 |
|
||||
| `douyin_fudai.py` | `def swipe_up_to_next_live(self) -> None:` | L1452 |
|
||||
| `douyin_fudai.py` | `try:` | L1456 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1458 |
|
||||
| `douyin_fudai.py` | `try:` | L1462 |
|
||||
| `douyin_fudai.py` | `if not hasattr(self, "_swipe_times"):` | L1463 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1466 |
|
||||
| `douyin_fudai.py` | `try:` | L1470 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1472 |
|
||||
| `douyin_fudai.py` | `def swipe_down_back_from_live(self) -> None:` | L1475 |
|
||||
| `douyin_fudai.py` | `try:` | L1477 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1479 |
|
||||
| `douyin_fudai.py` | `try:` | L1481 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1483 |
|
||||
| `douyin_fudai.py` | `try:` | L1486 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1488 |
|
||||
| `douyin_fudai.py` | `def _maybe_reset_after_swipes(self) -> int:` | L1491 |
|
||||
| `douyin_fudai.py` | `try:` | L1497 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1499 |
|
||||
| `douyin_fudai.py` | `if not needswitch:` | L1501 |
|
||||
| `douyin_fudai.py` | `if not bool(getattr(self, "reset_after_swipes_enabled", False)):` | L1504 |
|
||||
| `douyin_fudai.py` | `try:` | L1507 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1509 |
|
||||
| `douyin_fudai.py` | `if swipe_times < threshold:` | L1513 |
|
||||
| `douyin_fudai.py` | `try:` | L1516 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1525 |
|
||||
| `douyin_fudai.py` | `if back_times <= 0:` | L1530 |
|
||||
| `douyin_fudai.py` | `try:` | L1534 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1537 |
|
||||
| `douyin_fudai.py` | `for i in range(back_times):` | L1540 |
|
||||
| `douyin_fudai.py` | `try:` | L1541 |
|
||||
| `douyin_fudai.py` | `try:` | L1550 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1552 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1555 |
|
||||
| `douyin_fudai.py` | `try:` | L1560 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1563 |
|
||||
| `douyin_fudai.py` | `def _seek_reservation_room(self, item: dict[str, Any]) -> bool:` | L1567 |
|
||||
| `douyin_fudai.py` | `try:` | L1574 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1576 |
|
||||
| `douyin_fudai.py` | `try:` | L1578 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1580 |
|
||||
| `douyin_fudai.py` | `try:` | L1584 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1586 |
|
||||
| `douyin_fudai.py` | `if max_back > 0 and back_times > max_back:` | L1588 |
|
||||
| `douyin_fudai.py` | `try:` | L1591 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1599 |
|
||||
| `douyin_fudai.py` | `if back_times <= 0:` | L1602 |
|
||||
| `douyin_fudai.py` | `else:` | L1605 |
|
||||
| `douyin_fudai.py` | `for _ in range(back_times):` | L1607 |
|
||||
| `douyin_fudai.py` | `try:` | L1609 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1611 |
|
||||
| `douyin_fudai.py` | `try:` | L1615 |
|
||||
| `douyin_fudai.py` | `if bool(getattr(self, "reservation_back_verify_enabled", True)):` | L1616 |
|
||||
| `douyin_fudai.py` | `if not is_valid:` | L1624 |
|
||||
| `douyin_fudai.py` | `try:` | L1625 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1629 |
|
||||
| `douyin_fudai.py` | `if detail_tuple:` | L1633 |
|
||||
| `douyin_fudai.py` | `try:` | L1634 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1637 |
|
||||
| `douyin_fudai.py` | `except Exception as e:` | L1639 |
|
||||
| `douyin_fudai.py` | `try:` | L1640 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1644 |
|
||||
| `douyin_fudai.py` | `if bool(getattr(self, "reservation_back_verify_enabled", True)):` | L1647 |
|
||||
| `douyin_fudai.py` | `def _handle_in_fudai_detail(self) -> None:` | L1653 |
|
||||
| `douyin_fudai.py` | `try:` | L1665 |
|
||||
| `douyin_fudai.py` | `if last_status == "coupon_popup":` | L1667 |
|
||||
| `douyin_fudai.py` | `try:` | L1668 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1673 |
|
||||
| `douyin_fudai.py` | `elif last_status == "validation_failed":` | L1676 |
|
||||
| `douyin_fudai.py` | `try:` | L1677 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1682 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1685 |
|
||||
| `douyin_fudai.py` | `try:` | L1689 |
|
||||
| `douyin_fudai.py` | `if not is_valid:` | L1692 |
|
||||
| `douyin_fudai.py` | `try:` | L1693 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1699 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1702 |
|
||||
| `douyin_fudai.py` | `try:` | L1706 |
|
||||
| `douyin_fudai.py` | `if isinstance(detail, tuple) and len(detail) >= 5:` | L1707 |
|
||||
| `douyin_fudai.py` | `if not content and prize_value_yuan == 0.0:` | L1710 |
|
||||
| `douyin_fudai.py` | `try:` | L1711 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1718 |
|
||||
| `douyin_fudai.py` | `except Exception:` | L1721 |
|
||||
| `douyin_fudai.py` | `def _handle_live_room_has_or_not_fudai(self) -> None:` | L1726 |
|
||||
| `douyin_fudai.py` | `if not opened:` | L1730 |
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
+511
-298
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -31,7 +31,7 @@
|
||||
"fudai_icon_retry_delay_seconds": 0.7,
|
||||
"fudai_icon_max_wait_seconds": 15.0,
|
||||
"yanghao_recommend_duration_seconds": 206,
|
||||
"yanghao_recommend_interval_seconds": 600,
|
||||
"yanghao_recommend_interval_seconds": 570,
|
||||
"yanghao_like_prob": 1.0,
|
||||
"yanghao_fav_prob": 0.85,
|
||||
"yanghao_comment_prob": 1.0,
|
||||
|
||||
+217
-92
@@ -111,7 +111,11 @@ def check_detail_height(analyser: Any) -> int:
|
||||
y = base_y * ry // 2400 + dy
|
||||
if _check_pixel_color(y):
|
||||
try:
|
||||
analyser._log_kv("检测", f"识别到福袋任务数量:{task_count}个", task_count=task_count)
|
||||
analyser._log_kv(
|
||||
"检测",
|
||||
f"识别到福袋任务数量:{task_count}个",
|
||||
task_count=task_count,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return task_count
|
||||
@@ -120,18 +124,25 @@ def check_detail_height(analyser: Any) -> int:
|
||||
|
||||
# Optional robot-check path from original implementation
|
||||
try:
|
||||
if hasattr(analyser, "check_have_robot_analyse") and analyser.check_have_robot_analyse():
|
||||
if (
|
||||
hasattr(analyser, "check_have_robot_analyse")
|
||||
and analyser.check_have_robot_analyse()
|
||||
):
|
||||
analyser.deal_robot_analyse()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv("检测", "识别福袋任务数量:0个(不需要任务)", level="INFO", task_count=0)
|
||||
analyser._log_kv(
|
||||
"检测", "识别福袋任务数量:0个(不需要任务)", level="INFO", task_count=0
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool = False):
|
||||
def check_have_fudai_with_ready_screenshot(
|
||||
analyser: Any, screenshot_ready: bool = False
|
||||
):
|
||||
"""判定直播页面福袋的小图标是否存在(像素检测版)。"""
|
||||
func_start = time.time()
|
||||
path = os.path.join(os.path.dirname(__file__), "pic")
|
||||
@@ -141,7 +152,9 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
# ===== 像素检测版(优先使用),不依赖 OpenCV =====
|
||||
# 改为按时间控制循环,而不是按次数限制
|
||||
try:
|
||||
retry_delay_s = float(getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6)
|
||||
retry_delay_s = float(
|
||||
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
|
||||
)
|
||||
except Exception:
|
||||
retry_delay_s = 0.6
|
||||
try:
|
||||
@@ -158,7 +171,9 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
# 每次循环都重新截图(除了第一次如果已经提供了截图)
|
||||
if not (screenshot_ready and loop == 0):
|
||||
try:
|
||||
analyser._shot_and_diagnose("找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False)
|
||||
analyser._shot_and_diagnose(
|
||||
"找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False
|
||||
)
|
||||
except Exception:
|
||||
# 如果截图失败,尝试直接调用 get_screenshot
|
||||
try:
|
||||
@@ -179,7 +194,7 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
pic.load()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 如果截图读取失败,等待后继续下一次循环
|
||||
if pic is None:
|
||||
loop += 1
|
||||
@@ -212,37 +227,45 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
|
||||
detected = False
|
||||
detected_x = None
|
||||
|
||||
# 初始化扫描范围变量(用于日志记录)
|
||||
scan_x_start = 41 * rx // 1080
|
||||
scan_x_end = min(410 * rx // 1080, width)
|
||||
scan_y = 403 * ry // 2400 + y_pianyi_val
|
||||
|
||||
# 先尝试 numpy 加速扫描水平带(性能优化:批量处理)
|
||||
try:
|
||||
import numpy as _np
|
||||
|
||||
# 计算检测区域,考虑分辨率缩放和偏移
|
||||
y0 = 403 * ry // 2400 + y_pianyi_val
|
||||
x1 = max(0, 41 * rx // 1080)
|
||||
x2 = min(width, 410 * rx // 1080)
|
||||
y_top = max(0, y0 - 3)
|
||||
y_bottom = min(height, y0 + 4)
|
||||
|
||||
|
||||
# 边界检查
|
||||
if x1 < x2 and y_top < y_bottom:
|
||||
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert('RGB')
|
||||
|
||||
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
|
||||
|
||||
# 双截图记录:保存实时操作截图(像素检测区域)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
douyin_screenshot_manager.save_latest_attempt(roi, operation_type="pixel_detect")
|
||||
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
roi, operation_type="pixel_detect"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
arr = _np.array(roi)
|
||||
if arr.size > 0:
|
||||
r = arr[:, :, 0]
|
||||
g = arr[:, :, 1]
|
||||
b = arr[:, :, 2]
|
||||
r = arr[:, :, 0] # type: ignore[index]
|
||||
g = arr[:, :, 1] # type: ignore[index]
|
||||
b = arr[:, :, 2] # type: ignore[index]
|
||||
# 精度优化:扩大颜色范围,提高容错性(考虑不同屏幕色温和亮度)
|
||||
# 原来的范围:R[193-203], G[176-193], B[237-247]
|
||||
# 优化后:适度放宽范围,但保持中心值权重
|
||||
mask_center = (r >= 190) & (r <= 206) & (g >= 173) & (g <= 196) & (b >= 234) & (b <= 250)
|
||||
mask_center = (r >= 190) & (r <= 206) & (g >= 173) & (g <= 196) & (b >= 234) & (b <= 250) # type: ignore[operator]
|
||||
# 速度优化:使用更宽松的预筛选,减少计算量
|
||||
mask = mask_center
|
||||
# 检查每一列是否有足够多的匹配像素(提高准确性,避免单个噪点误判)
|
||||
@@ -255,14 +278,17 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
# 计算检测到的x坐标:转换为1080基准坐标,确保精度
|
||||
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
|
||||
detected = True
|
||||
|
||||
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
douyin_screenshot_manager.save_last_success(roi, operation_type="pixel_detect")
|
||||
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
roi, operation_type="pixel_detect"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
@@ -292,19 +318,34 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
px = pix[x_scaled, check_y]
|
||||
# 检查RGB值是否匹配福袋图标颜色(适度放宽范围)
|
||||
if isinstance(px, tuple) and len(px) >= 3:
|
||||
if 190 <= px[0] <= 206 and 173 <= px[1] <= 196 and 234 <= px[2] <= 250:
|
||||
if (
|
||||
190 <= px[0] <= 206
|
||||
and 173 <= px[1] <= 196
|
||||
and 234 <= px[2] <= 250
|
||||
):
|
||||
# 转换回1080基准坐标
|
||||
detected_x = int(x_scaled * 1080.0 / max(1, rx))
|
||||
detected = True
|
||||
|
||||
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
detect_roi = pic_new.crop((scan_x_start, max(0, scan_y - 3), scan_x_end, min(pic_height, scan_y + 4))).convert('RGB')
|
||||
douyin_screenshot_manager.save_last_success(detect_roi, operation_type="pixel_detect")
|
||||
|
||||
detect_roi = pic_new.crop(
|
||||
(
|
||||
scan_x_start,
|
||||
max(0, scan_y - 3),
|
||||
scan_x_end,
|
||||
min(pic_height, scan_y + 4),
|
||||
)
|
||||
).convert("RGB")
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
detect_roi,
|
||||
operation_type="pixel_detect",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
except Exception:
|
||||
@@ -325,48 +366,57 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
try:
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
|
||||
# 获取模板路径
|
||||
base_dir = os.path.dirname(__file__)
|
||||
template_path = os.path.join(base_dir, "assets", "fudai.png")
|
||||
|
||||
|
||||
if os.path.exists(template_path):
|
||||
# 获取匹配阈值
|
||||
try:
|
||||
template_threshold = float(getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7)
|
||||
template_threshold = float(
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.7)
|
||||
or 0.7
|
||||
)
|
||||
except Exception:
|
||||
template_threshold = 0.7
|
||||
|
||||
|
||||
# 读取模板
|
||||
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
|
||||
if template is not None:
|
||||
# 将PIL图片转换为OpenCV格式
|
||||
pic_rgb = pic_new.convert("RGB")
|
||||
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
|
||||
|
||||
screenshot_bgr = cv2.cvtColor(
|
||||
np.array(pic_rgb), cv2.COLOR_RGB2BGR
|
||||
)
|
||||
|
||||
# 定义搜索区域:X=156-269(1080基准),Y=351-451(2400基准)
|
||||
x1 = max(0, 156 * rx // 1080)
|
||||
x2 = min(width, 269 * rx // 1080)
|
||||
y_top = max(0, 351 * ry // 2400 + y_pianyi_val)
|
||||
y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val)
|
||||
|
||||
|
||||
if x1 < x2 and y_top < y_bottom:
|
||||
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2]
|
||||
|
||||
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index]
|
||||
|
||||
if search_roi.size > 0:
|
||||
th, tw = template.shape[:2]
|
||||
rh, rw = search_roi.shape[:2]
|
||||
|
||||
|
||||
# 保存搜索区域截图到 last_match.png
|
||||
try:
|
||||
base_dir = os.path.dirname(__file__)
|
||||
pic_base = os.path.join(base_dir, 'pic')
|
||||
match_dir = os.path.join(pic_base, 'template_match')
|
||||
pic_base = os.path.join(base_dir, "pic")
|
||||
match_dir = os.path.join(pic_base, "template_match")
|
||||
os.makedirs(match_dir, exist_ok=True)
|
||||
last_match_path = os.path.join(match_dir, 'last_match.png')
|
||||
|
||||
last_match_path = os.path.join(
|
||||
match_dir, "last_match.png"
|
||||
)
|
||||
|
||||
# 保存截图并检查是否成功
|
||||
save_success = cv2.imwrite(last_match_path, search_roi)
|
||||
save_success = cv2.imwrite(
|
||||
last_match_path, search_roi
|
||||
)
|
||||
if save_success:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -397,35 +447,53 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 如果模板太大,缩小模板
|
||||
if th > rh or tw > rw:
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
if scale > 0:
|
||||
template = cv2.resize(template, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
template = cv2.resize(
|
||||
template,
|
||||
(
|
||||
max(1, int(tw * scale)),
|
||||
max(1, int(th * scale)),
|
||||
),
|
||||
)
|
||||
th, tw = template.shape[:2]
|
||||
|
||||
|
||||
# 执行模板匹配
|
||||
if th <= rh and tw <= rw:
|
||||
res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
|
||||
|
||||
res = cv2.matchTemplate(
|
||||
search_roi, template, cv2.TM_CCOEFF_NORMED
|
||||
)
|
||||
_min_val, max_val, _min_loc, max_loc = (
|
||||
cv2.minMaxLoc(res)
|
||||
)
|
||||
|
||||
# 双截图记录:保存实时操作截图(搜索区域)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
search_roi_pil = PILImage.fromarray(cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB))
|
||||
douyin_screenshot_manager.save_latest_attempt(search_roi_pil, operation_type="template_match")
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
|
||||
)
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
search_roi_pil,
|
||||
operation_type="template_match",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 模板匹配兜底",
|
||||
loop=loop,
|
||||
匹配分数=round(max_val, 4),
|
||||
阈值=template_threshold,
|
||||
是否通过=bool(max_val >= template_threshold),
|
||||
是否通过=bool(
|
||||
max_val >= template_threshold
|
||||
),
|
||||
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
|
||||
搜索区域尺寸=f"{rw}x{rh}",
|
||||
模板尺寸=f"{tw}x{th}",
|
||||
@@ -434,19 +502,31 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if max_val >= template_threshold:
|
||||
# 双截图记录:保存成功识别存档截图
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
search_roi_pil = PILImage.fromarray(cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB))
|
||||
douyin_screenshot_manager.save_last_success(search_roi_pil, operation_type="template_match")
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(
|
||||
search_roi, cv2.COLOR_BGR2RGB
|
||||
)
|
||||
)
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
search_roi_pil,
|
||||
operation_type="template_match",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 计算检测到的X坐标(1080基准)
|
||||
detected_x_in_roi = max_loc[0]
|
||||
detected_x = int((x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx))
|
||||
detected_x = int(
|
||||
(x1 + detected_x_in_roi + tw // 2)
|
||||
* 1080.0
|
||||
/ max(1, rx)
|
||||
)
|
||||
detected = True
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
@@ -536,7 +616,7 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 命中时记录调试信息
|
||||
try:
|
||||
elapsed_ms = int((time.time() - func_start) * 1000)
|
||||
@@ -560,7 +640,8 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
try:
|
||||
mid_x = (scan_x_start + scan_x_end) // 2
|
||||
if 0 <= scan_y < height and 0 <= mid_x < width:
|
||||
sample_color = img.load()[mid_x, scan_y]
|
||||
pix_sample = pic_new.load()
|
||||
sample_color = pix_sample[mid_x, scan_y]
|
||||
except Exception:
|
||||
sample_color = None
|
||||
analyser._log_kv(
|
||||
@@ -601,7 +682,9 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
return False
|
||||
|
||||
try:
|
||||
retry_delay_s = float(getattr(analyser, "fudai_icon_retry_delay_seconds", 0.3) or 0.3)
|
||||
retry_delay_s = float(
|
||||
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.3) or 0.3
|
||||
)
|
||||
except Exception:
|
||||
retry_delay_s = 0.3
|
||||
try:
|
||||
@@ -614,7 +697,10 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
max_wait_s = 0.0
|
||||
|
||||
try:
|
||||
analyser._log_kv("[找福袋图标] 开始", f"最大等待时间{max_wait_s}秒,复用截图={screenshot_ready},使用模板匹配")
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 开始",
|
||||
f"最大等待时间{max_wait_s}秒,复用截图={screenshot_ready},使用模板匹配",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -627,7 +713,9 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
import numpy as np
|
||||
except Exception:
|
||||
try:
|
||||
analyser._log_kv("[找福袋图标] 错误", "OpenCV/numpy不可用,无法使用模板匹配")
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 错误", "OpenCV/numpy不可用,无法使用模板匹配"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
@@ -644,7 +732,9 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
|
||||
# 获取匹配阈值
|
||||
try:
|
||||
template_threshold = float(getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7)
|
||||
template_threshold = float(
|
||||
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
|
||||
)
|
||||
except Exception:
|
||||
template_threshold = 0.7
|
||||
|
||||
@@ -655,7 +745,9 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
# Reuse external screenshot only on first attempt if provided
|
||||
if not (screenshot_ready and attempt_count == 1):
|
||||
try:
|
||||
analyser._shot_and_diagnose("找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False)
|
||||
analyser._shot_and_diagnose(
|
||||
"找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -734,7 +826,9 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
|
||||
if template is None:
|
||||
try:
|
||||
analyser._log_kv("[找福袋图标] 错误", f"无法读取模板文件: {template_path}")
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 错误", f"无法读取模板文件: {template_path}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elapsed = time.time() - func_start
|
||||
@@ -771,13 +865,15 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
# 模板太大,缩小模板
|
||||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||||
if scale > 0:
|
||||
template = cv2.resize(template, (max(1, int(tw * scale)), max(1, int(th * scale))))
|
||||
template = cv2.resize(
|
||||
template, (max(1, int(tw * scale)), max(1, int(th * scale)))
|
||||
)
|
||||
th, tw = template.shape[:2]
|
||||
|
||||
# 执行模板匹配(使用彩色匹配)
|
||||
try:
|
||||
template_match_start = time.time()
|
||||
|
||||
|
||||
# 详细日志:记录搜索区域和模板信息
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -797,22 +893,27 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 使用彩色匹配(BGR三通道)
|
||||
res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED)
|
||||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
|
||||
|
||||
|
||||
# 双截图记录:保存实时操作截图(搜索区域)
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
search_roi_pil = PILImage.fromarray(cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB))
|
||||
douyin_screenshot_manager.save_latest_attempt(search_roi_pil, operation_type="template_match")
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
|
||||
)
|
||||
douyin_screenshot_manager.save_latest_attempt(
|
||||
search_roi_pil, operation_type="template_match"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
template_match_elapsed = (time.time() - template_match_start) * 1000
|
||||
|
||||
|
||||
# 详细日志:记录匹配结果
|
||||
try:
|
||||
analyser._log_kv(
|
||||
@@ -831,42 +932,57 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
try:
|
||||
import douyin_screenshot_manager
|
||||
from PIL import Image as PILImage
|
||||
search_roi_pil = PILImage.fromarray(cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB))
|
||||
douyin_screenshot_manager.save_last_success(search_roi_pil, operation_type="template_match")
|
||||
|
||||
search_roi_pil = PILImage.fromarray(
|
||||
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
|
||||
)
|
||||
douyin_screenshot_manager.save_last_success(
|
||||
search_roi_pil, operation_type="template_match"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# 计算检测到的X坐标(1080基准)
|
||||
detected_x_in_roi = max_loc[0]
|
||||
detected_x = int((search_x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx))
|
||||
detected_x = int(
|
||||
(search_x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)
|
||||
)
|
||||
detected_y_in_roi = max_loc[1]
|
||||
detected_y = int((search_y1 + detected_y_in_roi + th // 2) * 2400.0 / max(1, ry))
|
||||
detected_y = int(
|
||||
(search_y1 + detected_y_in_roi + th // 2) * 2400.0 / max(1, ry)
|
||||
)
|
||||
detected_any = True
|
||||
|
||||
|
||||
# 保存匹配位置的图片
|
||||
try:
|
||||
# 计算匹配区域在原图中的坐标(扩大一些范围以便查看上下文)
|
||||
margin = 20 # 扩大20像素的边距
|
||||
match_x1 = max(0, search_x1 + detected_x_in_roi - margin)
|
||||
match_y1 = max(0, search_y1 + detected_y_in_roi - margin)
|
||||
match_x2 = min(screenshot_img.shape[1], search_x1 + detected_x_in_roi + tw + margin)
|
||||
match_y2 = min(screenshot_img.shape[0], search_y1 + detected_y_in_roi + th + margin)
|
||||
|
||||
match_x2 = min(
|
||||
screenshot_img.shape[1],
|
||||
search_x1 + detected_x_in_roi + tw + margin,
|
||||
)
|
||||
match_y2 = min(
|
||||
screenshot_img.shape[0],
|
||||
search_y1 + detected_y_in_roi + th + margin,
|
||||
)
|
||||
|
||||
# 裁剪匹配区域
|
||||
match_roi = screenshot_img[match_y1:match_y2, match_x1:match_x2]
|
||||
|
||||
|
||||
# 保存到 pic/template_match/ 目录
|
||||
base_dir = os.path.dirname(__file__)
|
||||
pic_base = os.path.join(base_dir, 'pic')
|
||||
match_dir = os.path.join(pic_base, 'template_match')
|
||||
pic_base = os.path.join(base_dir, "pic")
|
||||
match_dir = os.path.join(pic_base, "template_match")
|
||||
os.makedirs(match_dir, exist_ok=True)
|
||||
|
||||
|
||||
# 文件名包含时间戳和匹配分数
|
||||
timestamp = int(time.time() * 1000)
|
||||
score_str = f"{max_val:.4f}".replace('.', '_')
|
||||
score_str = f"{max_val:.4f}".replace(".", "_")
|
||||
match_filename = f"fudai_match_{timestamp}_score_{score_str}.png"
|
||||
match_path = os.path.join(match_dir, match_filename)
|
||||
|
||||
|
||||
# 检查裁剪区域是否有效
|
||||
if match_roi.size == 0:
|
||||
analyser._log_kv(
|
||||
@@ -877,11 +993,11 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
else:
|
||||
# 保存图片
|
||||
save_success = cv2.imwrite(match_path, match_roi)
|
||||
|
||||
|
||||
# 验证文件是否真的保存成功
|
||||
file_exists = os.path.exists(match_path)
|
||||
file_size = os.path.getsize(match_path) if file_exists else 0
|
||||
|
||||
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 已保存匹配位置图片",
|
||||
f"路径: {match_path}",
|
||||
@@ -892,7 +1008,7 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
文件存在=file_exists,
|
||||
文件大小字节=file_size,
|
||||
)
|
||||
|
||||
|
||||
if not file_exists or file_size == 0:
|
||||
analyser._log_kv(
|
||||
"[找福袋图标] 警告",
|
||||
@@ -914,7 +1030,7 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
try:
|
||||
analyser.last_find_fudai_time = time.time()
|
||||
analyser._log_kv(
|
||||
@@ -1057,7 +1173,9 @@ def check_in_fudai_detail(analyser: Any) -> bool:
|
||||
# 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)
|
||||
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)
|
||||
@@ -1068,7 +1186,15 @@ def check_in_fudai_detail(analyser: Any) -> bool:
|
||||
|
||||
analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮")
|
||||
t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
|
||||
keywords = ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看")
|
||||
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):
|
||||
@@ -1079,4 +1205,3 @@ def check_in_fudai_detail(analyser: Any) -> bool:
|
||||
|
||||
analyser._detection_cache[cache_key] = (now, False)
|
||||
return False
|
||||
|
||||
+413
-156
File diff suppressed because it is too large.
Load diff
+7
-10
@@ -176,13 +176,13 @@ def check_contain(analyser, contains: str = "") -> bool:
|
||||
analyser._log_kv("筛选", "福袋内容命中黑名单,将丢弃", keyword=contain, contains=contains[:80] if contains else "")
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
return True
|
||||
|
||||
try:
|
||||
analyser._log_kv("筛选", "福袋内容未命中黑名单,保留", contains=contains[:80] if contains else "")
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
return False
|
||||
except Exception:
|
||||
# 容错:异常时不过滤
|
||||
try:
|
||||
@@ -396,6 +396,7 @@ def check_lucky_draw_result(analyser):
|
||||
if "没有抽中" in (lucky_draw_result or ""):
|
||||
# 速度优化:使用缓存避免重复OCR
|
||||
cache_key2 = ("no_award_confirm", 0)
|
||||
dur2 = 0.0 # Initialize dur2 to avoid unbound variable
|
||||
if cache_key2 in analyser._ocr_cache:
|
||||
cached_ts2, cached_result2 = analyser._ocr_cache[cache_key2]
|
||||
if (now - cached_ts2) < analyser._ocr_cache_ttl:
|
||||
@@ -412,11 +413,6 @@ def check_lucky_draw_result(analyser):
|
||||
no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认")
|
||||
analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm)
|
||||
dur2 = time.time() - t1
|
||||
|
||||
try:
|
||||
dur2
|
||||
except NameError:
|
||||
dur2 = 0.0
|
||||
try:
|
||||
brief2 = (no_award_confirm or "").replace("\n", " ")[:140]
|
||||
except Exception:
|
||||
@@ -677,7 +673,7 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
|
||||
try:
|
||||
skip_if_gt = int(getattr(analyser, "skip_if_countdown_gt_seconds", 0) or 0)
|
||||
except Exception:
|
||||
skip_if_lt = 0
|
||||
skip_if_gt = 0
|
||||
|
||||
# 记录所有配置值和实际值,便于调试
|
||||
try:
|
||||
@@ -851,7 +847,7 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
|
||||
analyser._log_kv(
|
||||
"筛选",
|
||||
"倒计时过滤:跳过(配置阈值为0,不启用倒计时过滤)",
|
||||
配置阈值秒数=skip_if_lt,
|
||||
配置阈值秒数=skip_if_gt,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1220,7 +1216,8 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
# 记录高价值直播间(在记录预约之前)
|
||||
try:
|
||||
import douyin_high_value_room
|
||||
douyin_high_value_room.touch_high_value_room(
|
||||
if hasattr(douyin_high_value_room, 'touch_high_value_room'):
|
||||
douyin_high_value_room.touch_high_value_room( # type: ignore[attr-defined]
|
||||
analyser=analyser,
|
||||
title_norm=room_title,
|
||||
title_raw=room_title_raw,
|
||||
|
||||
@@ -195,7 +195,10 @@ def _is_wrong_coupon_popup(analyser: Any) -> bool:
|
||||
path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
try:
|
||||
pic = Image.open(path)
|
||||
pic.load()
|
||||
pic.load() # Force load to catch truncated files early
|
||||
except (OSError, IOError, SyntaxError):
|
||||
# Handle truncated image files
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
@@ -764,4 +767,5 @@ def is_abnormal_time_value(v: float) -> bool:
|
||||
if v <= 0:
|
||||
return True
|
||||
if v > 24 * 3600 * 7:
|
||||
return True
|
||||
return True
|
||||
return False
|
||||
+1
-1
@@ -19,7 +19,7 @@ class fudai_guaji:
|
||||
self.guaji(y_pianyi)
|
||||
|
||||
if __name__ == '__main__':
|
||||
if callable(print_version_banner):
|
||||
if print_version_banner is not None and callable(print_version_banner):
|
||||
print_version_banner("douyin_guaji")
|
||||
choujiang = fudai_guaji()
|
||||
choujiang.guaji(0) # 运行只需改这里的0,对应是你手机纵轴y的偏移值
|
||||
+41
-46
@@ -51,13 +51,13 @@ def get_log_level() -> str:
|
||||
env_level = os.environ.get("DOUYIN_LOG_LEVEL", "").upper()
|
||||
if env_level in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
|
||||
return env_level
|
||||
|
||||
|
||||
# 从配置文件读取
|
||||
log_config = get_log_config()
|
||||
level = log_config.get("level", DEFAULT_LOG_LEVEL).upper()
|
||||
if level in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
|
||||
return level
|
||||
|
||||
|
||||
return DEFAULT_LOG_LEVEL
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ def get_rotation_config() -> Dict[str, Any]:
|
||||
"""获取日志轮转配置"""
|
||||
log_config = get_log_config()
|
||||
rotation = log_config.get("rotation", {})
|
||||
|
||||
|
||||
return {
|
||||
"enabled": rotation.get("enabled", True),
|
||||
"max_bytes": rotation.get("max_bytes", DEFAULT_MAX_BYTES),
|
||||
@@ -93,59 +93,56 @@ def setup_logging(
|
||||
) -> logging.Logger:
|
||||
"""
|
||||
配置并返回一个增强的 logger 实例
|
||||
|
||||
|
||||
参数:
|
||||
logger_name: logger 名称
|
||||
log_file: 日志文件路径(None 则从配置读取)
|
||||
log_level: 日志级别(None 则从配置读取)
|
||||
enable_console: 是否启用控制台输出
|
||||
enable_file: 是否启用文件输出
|
||||
|
||||
|
||||
返回:
|
||||
配置好的 logger 实例
|
||||
"""
|
||||
logger = logging.getLogger(logger_name)
|
||||
|
||||
|
||||
# 避免重复配置
|
||||
if logger.handlers:
|
||||
return logger
|
||||
|
||||
|
||||
# 设置日志级别
|
||||
if log_level is None:
|
||||
log_level = get_log_level()
|
||||
level = getattr(logging, log_level.upper(), logging.INFO)
|
||||
logger.setLevel(level)
|
||||
|
||||
|
||||
# 日志格式:时间戳 - [级别] - 模块名:函数名:行号 - 消息
|
||||
detailed_format = (
|
||||
"%(asctime)s - [%(levelname)s] - %(name)s:%(funcName)s:%(lineno)d - %(message)s"
|
||||
)
|
||||
simple_format = "%(asctime)s - [%(levelname)s] - %(message)s"
|
||||
|
||||
formatter = logging.Formatter(
|
||||
detailed_format,
|
||||
datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
|
||||
|
||||
formatter = logging.Formatter(detailed_format, datefmt="%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# 控制台处理器
|
||||
if enable_console:
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(level)
|
||||
console_handler.setFormatter(formatter)
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
|
||||
# 文件处理器(带轮转)
|
||||
if enable_file:
|
||||
if log_file is None:
|
||||
log_file = get_log_file_path()
|
||||
|
||||
|
||||
# 确保日志目录存在
|
||||
log_dir = os.path.dirname(log_file)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
|
||||
rotation_config = get_rotation_config()
|
||||
|
||||
|
||||
if rotation_config.get("enabled", True):
|
||||
# 使用 TimedRotatingFileHandler(按时间轮转)
|
||||
try:
|
||||
@@ -153,7 +150,9 @@ def setup_logging(
|
||||
log_file,
|
||||
when=rotation_config.get("when", DEFAULT_WHEN),
|
||||
interval=rotation_config.get("interval", DEFAULT_INTERVAL),
|
||||
backupCount=rotation_config.get("backup_count", DEFAULT_BACKUP_COUNT),
|
||||
backupCount=rotation_config.get(
|
||||
"backup_count", DEFAULT_BACKUP_COUNT
|
||||
),
|
||||
encoding="utf-8-sig", # 使用 BOM 避免 Windows 乱码
|
||||
errors="replace",
|
||||
)
|
||||
@@ -163,7 +162,9 @@ def setup_logging(
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_file,
|
||||
maxBytes=rotation_config.get("max_bytes", DEFAULT_MAX_BYTES),
|
||||
backupCount=rotation_config.get("backup_count", DEFAULT_BACKUP_COUNT),
|
||||
backupCount=rotation_config.get(
|
||||
"backup_count", DEFAULT_BACKUP_COUNT
|
||||
),
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
)
|
||||
@@ -181,11 +182,11 @@ def setup_logging(
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
)
|
||||
|
||||
|
||||
file_handler.setLevel(level)
|
||||
file_handler.setFormatter(formatter)
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
@@ -200,7 +201,7 @@ def get_logger(name: str = "douyin") -> logging.Logger:
|
||||
|
||||
class LogContext:
|
||||
"""日志上下文管理器,用于记录函数调用、参数、返回值、耗时等"""
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
logger: logging.Logger,
|
||||
@@ -219,39 +220,37 @@ class LogContext:
|
||||
self.start_time: Optional[float] = None
|
||||
self.args: tuple = ()
|
||||
self.kwargs: dict = {}
|
||||
|
||||
|
||||
def __enter__(self):
|
||||
import time
|
||||
|
||||
self.start_time = time.time()
|
||||
return self
|
||||
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
import time
|
||||
|
||||
duration = time.time() - self.start_time if self.start_time else 0
|
||||
|
||||
|
||||
# 记录函数调用信息
|
||||
if self.log_args and (self.args or self.kwargs):
|
||||
args_str = ", ".join([repr(a) for a in self.args])
|
||||
kwargs_str = ", ".join([f"{k}={repr(v)}" for k, v in self.kwargs.items()])
|
||||
params_str = ", ".join(filter(None, [args_str, kwargs_str]))
|
||||
self.logger.log(
|
||||
self.level,
|
||||
f"[函数调用] {self.func_name}({params_str})"
|
||||
)
|
||||
|
||||
self.logger.log(self.level, f"[函数调用] {self.func_name}({params_str})")
|
||||
|
||||
# 记录异常
|
||||
if exc_type is not None:
|
||||
self.logger.exception(
|
||||
f"[函数异常] {self.func_name} 发生异常: {exc_type.__name__}",
|
||||
exc_info=(exc_type, exc_val, exc_tb)
|
||||
exc_info=(exc_type, exc_val, exc_tb),
|
||||
)
|
||||
# 记录耗时
|
||||
elif self.log_duration:
|
||||
self.logger.log(
|
||||
self.level,
|
||||
f"[函数完成] {self.func_name} 耗时: {duration:.3f}秒"
|
||||
self.level, f"[函数完成] {self.func_name} 耗时: {duration:.3f}秒"
|
||||
)
|
||||
|
||||
|
||||
return False # 不抑制异常
|
||||
|
||||
|
||||
@@ -259,32 +258,32 @@ def log_function_call(
|
||||
logger: logging.Logger,
|
||||
func_name: str,
|
||||
args: tuple = (),
|
||||
kwargs: dict = None,
|
||||
kwargs: Optional[dict] = None,
|
||||
result: Any = None,
|
||||
duration: float = None,
|
||||
duration: Optional[float] = None,
|
||||
level: int = logging.DEBUG,
|
||||
):
|
||||
"""记录函数调用的详细信息"""
|
||||
if kwargs is None:
|
||||
kwargs = {}
|
||||
|
||||
|
||||
parts = [f"[函数调用] {func_name}"]
|
||||
|
||||
|
||||
# 参数
|
||||
if args or kwargs:
|
||||
args_str = ", ".join([repr(a) for a in args])
|
||||
kwargs_str = ", ".join([f"{k}={repr(v)}" for k, v in kwargs.items()])
|
||||
params_str = ", ".join(filter(None, [args_str, kwargs_str]))
|
||||
parts.append(f"参数: {params_str}")
|
||||
|
||||
|
||||
# 返回值
|
||||
if result is not None:
|
||||
parts.append(f"返回值: {repr(result)}")
|
||||
|
||||
|
||||
# 耗时
|
||||
if duration is not None:
|
||||
parts.append(f"耗时: {duration:.3f}秒")
|
||||
|
||||
|
||||
logger.log(level, " | ".join(parts))
|
||||
|
||||
|
||||
@@ -298,7 +297,3 @@ def get_global_logger() -> logging.Logger:
|
||||
if _global_logger is None:
|
||||
_global_logger = setup_logging("douyin")
|
||||
return _global_logger
|
||||
|
||||
|
||||
|
||||
|
||||
+91
-85
@@ -29,42 +29,44 @@ _logging_configured = False
|
||||
_logger_cache: Dict[str, logging.Logger] = {}
|
||||
|
||||
|
||||
def get_logger(name: str = None) -> logging.Logger:
|
||||
def get_logger(name: Optional[str] = None) -> logging.Logger:
|
||||
"""获取指定名称的 logger,如果未配置则自动配置"""
|
||||
if not _logging_configured:
|
||||
configure_logging()
|
||||
|
||||
|
||||
if name is None:
|
||||
# 自动获取调用者模块名
|
||||
try:
|
||||
frame = inspect.currentframe()
|
||||
if frame and frame.f_back:
|
||||
caller_frame = frame.f_back
|
||||
name = caller_frame.f_globals.get('__name__', 'root')
|
||||
name = caller_frame.f_globals.get("__name__", "root")
|
||||
else:
|
||||
name = 'root'
|
||||
name = "root"
|
||||
except Exception:
|
||||
name = 'root'
|
||||
name = "root"
|
||||
finally:
|
||||
if 'frame' in locals():
|
||||
if "frame" in locals():
|
||||
del frame
|
||||
|
||||
if name not in _logger_cache:
|
||||
_logger_cache[name] = logging.getLogger(name)
|
||||
|
||||
return _logger_cache[name]
|
||||
|
||||
logger_name = name or "root"
|
||||
if logger_name not in _logger_cache:
|
||||
_logger_cache[logger_name] = logging.getLogger(logger_name)
|
||||
|
||||
logger_name = name or "root"
|
||||
return _logger_cache[logger_name]
|
||||
|
||||
|
||||
def configure_logging(
|
||||
log_level: str = None,
|
||||
log_file: str = None,
|
||||
log_level: Optional[str] = None,
|
||||
log_file: Optional[str] = None,
|
||||
max_bytes: int = 10 * 1024 * 1024, # 10MB
|
||||
backup_count: int = 5,
|
||||
enable_console: bool = True,
|
||||
enable_file: bool = True,
|
||||
) -> None:
|
||||
"""配置日志系统
|
||||
|
||||
|
||||
参数:
|
||||
log_level: 日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL),默认从 config.json 读取
|
||||
log_file: 日志文件路径,默认使用 logs/unified.log
|
||||
@@ -74,28 +76,31 @@ def configure_logging(
|
||||
enable_file: 是否输出到文件
|
||||
"""
|
||||
global _logging_configured
|
||||
|
||||
|
||||
# 从 config.json 读取配置
|
||||
if log_level is None or log_file is None:
|
||||
try:
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
if log_level is None:
|
||||
log_level = config.get('log_level', 'INFO')
|
||||
log_level = config.get("log_level", "INFO")
|
||||
if log_file is None:
|
||||
log_file = config.get('log_unified_path', 'logs/unified.log')
|
||||
log_file = config.get("log_unified_path", "logs/unified.log")
|
||||
except Exception:
|
||||
if log_level is None:
|
||||
log_level = 'INFO'
|
||||
log_level = "INFO"
|
||||
if log_file is None:
|
||||
log_file = 'logs/unified.log'
|
||||
|
||||
log_file = "logs/unified.log"
|
||||
|
||||
# 规范化日志级别
|
||||
if log_level is None:
|
||||
log_level = "INFO"
|
||||
numeric_level = getattr(logging, log_level.upper(), logging.INFO)
|
||||
|
||||
|
||||
# 确保日志目录存在
|
||||
if enable_file:
|
||||
log_dir = os.path.dirname(log_file)
|
||||
@@ -104,31 +109,30 @@ def configure_logging(
|
||||
log_dir = os.path.dirname(log_file)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
|
||||
# 配置根 logger
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(numeric_level)
|
||||
|
||||
|
||||
# 清除已有的 handlers(避免重复配置)
|
||||
root_logger.handlers.clear()
|
||||
|
||||
|
||||
# 日志格式:时间戳 - [级别] - 模块名:函数名:行号 - 消息
|
||||
detailed_format = (
|
||||
'%(asctime)s - [%(levelname)s] - %(name)s:%(funcName)s:%(lineno)d - %(message)s'
|
||||
"%(asctime)s - [%(levelname)s] - %(name)s:%(funcName)s:%(lineno)d - %(message)s"
|
||||
)
|
||||
simple_format = '%(asctime)s - [%(levelname)s] - %(message)s'
|
||||
|
||||
simple_format = "%(asctime)s - [%(levelname)s] - %(message)s"
|
||||
|
||||
# 控制台输出
|
||||
if enable_console:
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(numeric_level)
|
||||
console_formatter = logging.Formatter(
|
||||
simple_format,
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
simple_format, datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
console_handler.setFormatter(console_formatter)
|
||||
root_logger.addHandler(console_handler)
|
||||
|
||||
|
||||
# 文件输出(带轮转)
|
||||
if enable_file:
|
||||
try:
|
||||
@@ -137,15 +141,14 @@ def configure_logging(
|
||||
log_file,
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding='utf-8-sig', # 使用 BOM 避免 Windows 乱码
|
||||
errors='replace'
|
||||
encoding="utf-8-sig", # 使用 BOM 避免 Windows 乱码
|
||||
errors="replace",
|
||||
)
|
||||
file_handler.setLevel(numeric_level)
|
||||
file_formatter = logging.Formatter(
|
||||
detailed_format,
|
||||
datefmt='%Y-%m-%d %H:%M:%S.%f'
|
||||
detailed_format, datefmt="%Y-%m-%d %H:%M:%S.%f"
|
||||
)
|
||||
file_formatter.default_msec_format = '%s.%03d' # 毫秒精度
|
||||
file_formatter.default_msec_format = "%s.%03d" # 毫秒精度
|
||||
file_handler.setFormatter(file_formatter)
|
||||
root_logger.addHandler(file_handler)
|
||||
except Exception as e:
|
||||
@@ -154,7 +157,7 @@ def configure_logging(
|
||||
print(f"[日志配置] 警告:无法创建日志文件 {log_file}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
_logging_configured = True
|
||||
|
||||
|
||||
@@ -166,7 +169,7 @@ def log_function_call(
|
||||
min_duration: float = 0.0, # 只记录超过此耗时的调用
|
||||
):
|
||||
"""装饰器:记录函数调用信息(参数、返回值、耗时)
|
||||
|
||||
|
||||
参数:
|
||||
logger: 使用的 logger,默认自动获取
|
||||
log_args: 是否记录函数参数
|
||||
@@ -174,6 +177,7 @@ def log_function_call(
|
||||
log_time: 是否记录执行时间
|
||||
min_duration: 最小耗时阈值(秒),低于此值不记录耗时
|
||||
"""
|
||||
|
||||
def decorator(func: Callable) -> Callable:
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
@@ -181,48 +185,54 @@ def log_function_call(
|
||||
_logger = get_logger()
|
||||
else:
|
||||
_logger = logger
|
||||
|
||||
|
||||
func_name = func.__name__
|
||||
start_time = time.time()
|
||||
|
||||
|
||||
# 记录函数调用
|
||||
if log_args:
|
||||
args_str = ', '.join([str(arg)[:100] for arg in args[:3]]) # 只记录前3个参数,避免过长
|
||||
kwargs_str = ', '.join([f"{k}={str(v)[:50]}" for k, v in list(kwargs.items())[:3]])
|
||||
call_info = f"{func_name}({args_str}{', ' + kwargs_str if kwargs_str else ''})"
|
||||
args_str = ", ".join(
|
||||
[str(arg)[:100] for arg in args[:3]]
|
||||
) # 只记录前3个参数,避免过长
|
||||
kwargs_str = ", ".join(
|
||||
[f"{k}={str(v)[:50]}" for k, v in list(kwargs.items())[:3]]
|
||||
)
|
||||
call_info = (
|
||||
f"{func_name}({args_str}{', ' + kwargs_str if kwargs_str else ''})"
|
||||
)
|
||||
if len(args) > 3 or len(kwargs) > 3:
|
||||
call_info += "..."
|
||||
_logger.debug(f"调用函数: {call_info}")
|
||||
|
||||
|
||||
# 执行函数
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
elapsed = time.time() - start_time
|
||||
|
||||
|
||||
# 记录执行结果
|
||||
if log_time and elapsed >= min_duration:
|
||||
_logger.debug(f"函数 {func_name} 执行完成,耗时: {elapsed:.3f}秒")
|
||||
|
||||
|
||||
if log_result:
|
||||
result_str = str(result)[:200] # 限制长度
|
||||
_logger.debug(f"函数 {func_name} 返回值: {result_str}")
|
||||
|
||||
|
||||
return result
|
||||
except Exception as e:
|
||||
elapsed = time.time() - start_time
|
||||
_logger.exception(
|
||||
f"函数 {func_name} 执行异常,耗时: {elapsed:.3f}秒",
|
||||
exc_info=True
|
||||
f"函数 {func_name} 执行异常,耗时: {elapsed:.3f}秒", exc_info=True
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
class LogContext:
|
||||
"""上下文管理器:记录代码块执行时间"""
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
@@ -234,40 +244,40 @@ class LogContext:
|
||||
self.logger = logger or get_logger()
|
||||
self.level = getattr(logging, level.upper(), logging.DEBUG)
|
||||
self.log_on_exit = log_on_exit
|
||||
self.start_time = None
|
||||
|
||||
self.start_time: Optional[float] = None
|
||||
|
||||
def __enter__(self):
|
||||
self.start_time = time.time()
|
||||
self.logger.log(self.level, f"{self.message} [开始]")
|
||||
return self
|
||||
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
if not self.log_on_exit:
|
||||
return False
|
||||
|
||||
elapsed = time.time() - self.start_time
|
||||
|
||||
|
||||
if self.start_time is None:
|
||||
elapsed = 0.0
|
||||
else:
|
||||
elapsed = time.time() - self.start_time
|
||||
|
||||
if exc_type is None:
|
||||
self.logger.log(
|
||||
self.level,
|
||||
f"{self.message} [完成] 耗时: {elapsed:.3f}秒"
|
||||
)
|
||||
self.logger.log(self.level, f"{self.message} [完成] 耗时: {elapsed:.3f}秒")
|
||||
else:
|
||||
self.logger.log(
|
||||
logging.ERROR,
|
||||
f"{self.message} [异常] 耗时: {elapsed:.3f}秒",
|
||||
exc_info=(exc_type, exc_val, exc_tb)
|
||||
exc_info=(exc_type, exc_val, exc_tb),
|
||||
)
|
||||
|
||||
|
||||
return False # 不抑制异常
|
||||
|
||||
|
||||
def get_caller_info(skip_frames: int = 0) -> Dict[str, Any]:
|
||||
"""获取调用者信息(模块名、函数名、行号)
|
||||
|
||||
|
||||
参数:
|
||||
skip_frames: 跳过的栈帧数(用于在装饰器中获取真正的调用者)
|
||||
|
||||
|
||||
返回:
|
||||
包含 module, function, line, file 的字典
|
||||
"""
|
||||
@@ -280,45 +290,45 @@ def get_caller_info(skip_frames: int = 0) -> Dict[str, Any]:
|
||||
frame = frame.f_back
|
||||
else:
|
||||
break
|
||||
|
||||
|
||||
if frame:
|
||||
return {
|
||||
'module': os.path.basename(frame.f_code.co_filename),
|
||||
'function': frame.f_code.co_name,
|
||||
'line': frame.f_lineno,
|
||||
'file': frame.f_code.co_filename,
|
||||
"module": os.path.basename(frame.f_code.co_filename),
|
||||
"function": frame.f_code.co_name,
|
||||
"line": frame.f_lineno,
|
||||
"file": frame.f_code.co_filename,
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if 'frame' in locals():
|
||||
if "frame" in locals():
|
||||
del frame
|
||||
|
||||
|
||||
return {
|
||||
'module': 'unknown',
|
||||
'function': 'unknown',
|
||||
'line': 0,
|
||||
'file': 'unknown',
|
||||
"module": "unknown",
|
||||
"function": "unknown",
|
||||
"line": 0,
|
||||
"file": "unknown",
|
||||
}
|
||||
|
||||
|
||||
def format_exception_info(exc_info=None) -> str:
|
||||
"""格式化异常信息为字符串
|
||||
|
||||
|
||||
参数:
|
||||
exc_info: 异常信息元组 (type, value, traceback),默认使用 sys.exc_info()
|
||||
|
||||
|
||||
返回:
|
||||
格式化的异常堆栈字符串
|
||||
"""
|
||||
if exc_info is None:
|
||||
exc_info = sys.exc_info()
|
||||
|
||||
|
||||
if exc_info[0] is None:
|
||||
return ""
|
||||
|
||||
|
||||
try:
|
||||
return ''.join(traceback.format_exception(*exc_info))
|
||||
return "".join(traceback.format_exception(*exc_info))
|
||||
except Exception:
|
||||
return f"异常: {exc_info[1]}"
|
||||
|
||||
@@ -330,7 +340,3 @@ if not _logging_configured:
|
||||
configure_logging()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
+4
-97
@@ -38,7 +38,10 @@ def wait_for_lottery_result(
|
||||
first_detect_ts = time.time()
|
||||
# 若有"预约应抢占"回调,则在等待期间尊重其判断
|
||||
try:
|
||||
if reservation_should_preempt_callback is not None and reservation_should_preempt_callback():
|
||||
if (
|
||||
reservation_should_preempt_callback is not None
|
||||
and reservation_should_preempt_callback()
|
||||
):
|
||||
return True, detect_attempts, first_detect_ts, initial_check_result or 0
|
||||
except Exception:
|
||||
pass
|
||||
@@ -81,99 +84,3 @@ def process_lottery_result(
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
|
||||
"""
|
||||
Lottery helpers shim (WebGUI version)
|
||||
=====================================
|
||||
|
||||
Exports:
|
||||
- wait_for_lottery_result
|
||||
- process_lottery_result
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, Tuple
|
||||
import time
|
||||
|
||||
|
||||
def wait_for_lottery_result(
|
||||
analyser: Any,
|
||||
lastsecond: int,
|
||||
future_timestamp: float,
|
||||
reservation_after_action_pending: bool,
|
||||
reservation_should_preempt_callback,
|
||||
) -> Tuple[bool, int, float | None, int | None]:
|
||||
"""Shim version matching original signature.
|
||||
|
||||
为了安全起见,这里不做真实的开奖结果 OCR,仅按时间简单等待并返回
|
||||
“未被预约抢占、未检测到结果”的占位信息,避免打断主流程。
|
||||
"""
|
||||
start = time.time()
|
||||
# 简单轮询等待一小段时间,保留结构但不做重型逻辑
|
||||
detect_attempts = 0
|
||||
first_detect_ts: float | None = None
|
||||
initial_check_result: int | None = None
|
||||
|
||||
# 最多等待 min(倒计时+5, 15) 秒,避免阻塞过久
|
||||
total_wait_s = max(0.0, float(lastsecond or 0) + 5.0)
|
||||
total_wait_s = min(total_wait_s, 15.0)
|
||||
step_s = 1.5
|
||||
|
||||
while (time.time() - start) < total_wait_s:
|
||||
detect_attempts += 1
|
||||
if first_detect_ts is None:
|
||||
first_detect_ts = time.time()
|
||||
# 若有"预约应抢占"回调,则在等待期间尊重其判断
|
||||
try:
|
||||
if reservation_should_preempt_callback is not None and reservation_should_preempt_callback():
|
||||
return True, detect_attempts, first_detect_ts, initial_check_result or 0
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.delay(step_s)
|
||||
except Exception:
|
||||
time.sleep(step_s)
|
||||
|
||||
# 占位返回:未被预约抢占,未检测到明确结果
|
||||
return False, detect_attempts, first_detect_ts, initial_check_result
|
||||
|
||||
|
||||
def process_lottery_result(
|
||||
analyser: Any,
|
||||
x: int,
|
||||
t_participate: float,
|
||||
detect_attempts: int,
|
||||
first_detect_ts: float | None,
|
||||
initial_check_result: int | None,
|
||||
reservation_focus_until_ts: float,
|
||||
reservation_focus_until_ts_ref: list,
|
||||
reservation_after_action_pending_ref: list,
|
||||
needswitch: bool,
|
||||
post_switch_delay_s: float,
|
||||
swipe_up_switch_callback,
|
||||
clear_reservations_callback,
|
||||
get_recommend_seconds_callback,
|
||||
yanghao_wait_callback,
|
||||
) -> bool:
|
||||
"""Shim: match original signature and record basic diagnostics.
|
||||
|
||||
为了安全起见,这里不再做复杂的开奖 OCR/状态机,仅:
|
||||
- 记录一次日志方便事后分析;
|
||||
- 不修改预约/房间状态;
|
||||
- 始终返回 False(表示不主动中断主循环)。
|
||||
"""
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"开奖",
|
||||
"process_lottery_result",
|
||||
x=x,
|
||||
detect_attempts=detect_attempts,
|
||||
first_detect_ts=first_detect_ts,
|
||||
initial_check_result=initial_check_result,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
+6
-2
@@ -10,7 +10,11 @@ def _safe_open_screenshot_rgb(pic_path: str) -> Image.Image | None:
|
||||
if not pic_path or (not os.path.exists(pic_path)):
|
||||
return None
|
||||
pic = Image.open(pic_path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
return pic.convert("RGB")
|
||||
except (OSError, IOError, SyntaxError):
|
||||
# Handle truncated image files
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@@ -48,7 +52,7 @@ def detect_coupon_popup_background(pic_rgb: Image.Image) -> bool:
|
||||
return False
|
||||
|
||||
bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
|
||||
roi = bgr[y1:y2, x1:x2]
|
||||
roi = bgr[y1:y2, x1:x2] # type: ignore[index]
|
||||
if roi.size == 0:
|
||||
return False
|
||||
|
||||
@@ -378,7 +382,7 @@ def detect_fudai_detail_page(pic_rgb: Image.Image, resolution_ratio_x: int = 108
|
||||
if x1 < x2 and y1 < y2:
|
||||
# 转为 OpenCV BGR 图像
|
||||
bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
|
||||
roi = bgr[y1:y2, x1:x2]
|
||||
roi = bgr[y1:y2, x1:x2] # type: ignore[index]
|
||||
if roi.size > 0:
|
||||
base_dir = os.path.dirname(__file__)
|
||||
# 使用用户提供的超级福袋标题模板:assets/xiangqing.png
|
||||
|
||||
+79
-15
@@ -12,8 +12,17 @@ def check_coupon_popup(analyser) -> bool:
|
||||
check_start = time.time()
|
||||
try:
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
pic = Image.open(pic_path).convert("RGB")
|
||||
pic = Image.open(pic_path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
pic = pic.convert("RGB")
|
||||
matched = bool(douyin_pixel.detect_coupon_popup_background(pic))
|
||||
except (OSError, IOError, SyntaxError) as e:
|
||||
# Handle truncated image files
|
||||
try:
|
||||
analyser._log_kv("彈窗檢測步驟", "優惠券-圖片文件損壞或截斷", error=str(e))
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except Exception as e:
|
||||
try:
|
||||
analyser._log_kv("彈窗檢測步驟", "優惠券-讀取截圖失敗", error=str(e))
|
||||
@@ -46,11 +55,17 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
has_popup_pixel = False
|
||||
try:
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
pic = Image.open(pic_path).convert("RGB")
|
||||
pic = Image.open(pic_path)
|
||||
pic.load() # Force load to catch truncated files early
|
||||
pic = pic.convert("RGB")
|
||||
has_popup_pixel = bool(douyin_pixel.detect_redpacket_popup_background(pic))
|
||||
_ = time.time() - pixel_check_start
|
||||
if not has_popup_pixel:
|
||||
return False
|
||||
except (OSError, IOError, SyntaxError):
|
||||
# Handle truncated image files
|
||||
_ = time.time() - pixel_check_start
|
||||
has_popup_pixel = False
|
||||
except Exception:
|
||||
_ = time.time() - pixel_check_start
|
||||
has_popup_pixel = False
|
||||
@@ -62,7 +77,12 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
_ = time.time() - cut_start
|
||||
except Exception as e:
|
||||
cut_elapsed = time.time() - cut_start
|
||||
analyser._log_kv("彈窗檢測步驟", "購物紅包-截圖區域失敗", error=str(e), 耗時秒=f"{cut_elapsed:.3f}")
|
||||
analyser._log_kv(
|
||||
"彈窗檢測步驟",
|
||||
"購物紅包-截圖區域失敗",
|
||||
error=str(e),
|
||||
耗時秒=f"{cut_elapsed:.3f}",
|
||||
)
|
||||
return False
|
||||
|
||||
# OCR 模式0
|
||||
@@ -74,7 +94,12 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
except Exception as e:
|
||||
hay = ""
|
||||
ocr_mode0_elapsed = time.time() - ocr_mode0_start
|
||||
analyser._log_kv("彈窗檢測步驟", "購物紅包-OCR(模式0)失敗", error=str(e), 耗時秒=f"{ocr_mode0_elapsed:.3f}")
|
||||
analyser._log_kv(
|
||||
"彈窗檢測步驟",
|
||||
"購物紅包-OCR(模式0)失敗",
|
||||
error=str(e),
|
||||
耗時秒=f"{ocr_mode0_elapsed:.3f}",
|
||||
)
|
||||
|
||||
if not hay:
|
||||
if has_popup_pixel:
|
||||
@@ -90,10 +115,18 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
# 嘗試按鈕區域快速 OCR(兜底)
|
||||
try:
|
||||
analyser.cut_pic(400, 1200, 680, 1400, "", "診斷購物紅包按鈕")
|
||||
btn_text = str(analyser.operation.analyse_pic_word("診斷購物紅包按鈕", 0) or "").strip()
|
||||
btn_text = str(
|
||||
analyser.operation.analyse_pic_word("診斷購物紅包按鈕", 0) or ""
|
||||
).strip()
|
||||
if "搶" in btn_text:
|
||||
total_elapsed = time.time() - check_start
|
||||
analyser._log_kv("彈窗檢測步驟", "購物紅包-檢測到彈窗(按鈕區域)", 識別文本=btn_text[:50], 總耗時秒=f"{total_elapsed:.3f}", 檢測方式="按鈕區域快速檢測")
|
||||
analyser._log_kv(
|
||||
"彈窗檢測步驟",
|
||||
"購物紅包-檢測到彈窗(按鈕區域)",
|
||||
識別文本=btn_text[:50],
|
||||
總耗時秒=f"{total_elapsed:.3f}",
|
||||
檢測方式="按鈕區域快速檢測",
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
@@ -103,7 +136,13 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
if any(kw in hay for kw in keywords):
|
||||
matched = [kw for kw in keywords if kw in hay]
|
||||
total_elapsed = time.time() - check_start
|
||||
analyser._log_kv("彈窗檢測步驟", "購物紅包-檢測到彈窗", 匹配到的關鍵詞=matched, 總耗時秒=f"{total_elapsed:.3f}", OCR耗時秒=f"{ocr_mode0_elapsed:.3f}")
|
||||
analyser._log_kv(
|
||||
"彈窗檢測步驟",
|
||||
"購物紅包-檢測到彈窗",
|
||||
匹配到的關鍵詞=matched,
|
||||
總耗時秒=f"{total_elapsed:.3f}",
|
||||
OCR耗時秒=f"{ocr_mode0_elapsed:.3f}",
|
||||
)
|
||||
return True
|
||||
|
||||
texts = [hay]
|
||||
@@ -121,11 +160,22 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
if any(kw in hay1 for kw in keywords):
|
||||
matched = [kw for kw in keywords if kw in hay1]
|
||||
total_elapsed = time.time() - check_start
|
||||
analyser._log_kv("彈窗檢測步驟", "購物紅包-檢測到彈窗(模式1)", 匹配到的關鍵詞=matched, 總耗時秒=f"{total_elapsed:.3f}", OCR耗時秒=f"{(ocr_mode0_elapsed + ocr_mode1_elapsed):.3f}")
|
||||
analyser._log_kv(
|
||||
"彈窗檢測步驟",
|
||||
"購物紅包-檢測到彈窗(模式1)",
|
||||
匹配到的關鍵詞=matched,
|
||||
總耗時秒=f"{total_elapsed:.3f}",
|
||||
OCR耗時秒=f"{(ocr_mode0_elapsed + ocr_mode1_elapsed):.3f}",
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
ocr_mode1_elapsed = time.time() - ocr_mode1_start
|
||||
analyser._log_kv("彈窗檢測步驟", "購物紅包-OCR(模式1)失敗", error=str(e), 耗時秒=f"{ocr_mode1_elapsed:.3f}")
|
||||
analyser._log_kv(
|
||||
"彈窗檢測步驟",
|
||||
"購物紅包-OCR(模式1)失敗",
|
||||
error=str(e),
|
||||
耗時秒=f"{ocr_mode1_elapsed:.3f}",
|
||||
)
|
||||
|
||||
# 模式2
|
||||
ocr_mode2_start = time.time()
|
||||
@@ -148,7 +198,12 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
return True
|
||||
except Exception as e:
|
||||
ocr_mode2_elapsed = time.time() - ocr_mode2_start
|
||||
analyser._log_kv("彈窗檢測步驟", "購物紅包-OCR(模式2)失敗", error=str(e), 耗時秒=f"{ocr_mode2_elapsed:.3f}")
|
||||
analyser._log_kv(
|
||||
"彈窗檢測步驟",
|
||||
"購物紅包-OCR(模式2)失敗",
|
||||
error=str(e),
|
||||
耗時秒=f"{ocr_mode2_elapsed:.3f}",
|
||||
)
|
||||
|
||||
combined_text = " ".join(texts).strip()
|
||||
final_keywords = ("購物紅包", "邀你搶", "搶紅包")
|
||||
@@ -160,10 +215,19 @@ def check_shopping_redpacket_popup(analyser) -> bool:
|
||||
ocr_total = ocr_mode0_elapsed + ocr_mode1_elapsed + ocr_mode2_elapsed
|
||||
if result:
|
||||
matched = [kw for kw in final_keywords if kw in combined_text]
|
||||
analyser._log_kv("彈窗檢測步驟", "購物紅包-檢測到彈窗(合併檢查)", 匹配到的關鍵詞=matched, 總耗時秒=f"{total_elapsed:.3f}", OCR耗時秒=f"{ocr_total:.3f}")
|
||||
analyser._log_kv(
|
||||
"彈窗檢測步驟",
|
||||
"購物紅包-檢測到彈窗(合併檢查)",
|
||||
匹配到的關鍵詞=matched,
|
||||
總耗時秒=f"{total_elapsed:.3f}",
|
||||
OCR耗時秒=f"{ocr_total:.3f}",
|
||||
)
|
||||
else:
|
||||
analyser._log_kv("彈窗檢測步驟", "購物紅包-未檢測到彈窗", 合併文本=combined_text[:100] if combined_text else "空", 總耗時秒=f"{total_elapsed:.3f}", OCR耗時秒=f"{ocr_total:.3f}")
|
||||
analyser._log_kv(
|
||||
"彈窗檢測步驟",
|
||||
"購物紅包-未檢測到彈窗",
|
||||
合併文本=combined_text[:100] if combined_text else "空",
|
||||
總耗時秒=f"{total_elapsed:.3f}",
|
||||
OCR耗時秒=f"{ocr_total:.3f}",
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@@ -178,7 +178,10 @@ def validate_back_to_reservation(
|
||||
try:
|
||||
# 使用 douyin_high_value_room 中的规范化函数
|
||||
import douyin_high_value_room
|
||||
expected_title = douyin_high_value_room._normalize_room_title(item.get("room_title") or "")
|
||||
if hasattr(douyin_high_value_room, '_normalize_room_title'):
|
||||
expected_title = douyin_high_value_room._normalize_room_title(item.get("room_title") or "") # type: ignore[attr-defined]
|
||||
else:
|
||||
expected_title = str(item.get("room_title") or "").strip()
|
||||
except Exception:
|
||||
try:
|
||||
expected_title_raw_text = str(item.get("room_title") or "")
|
||||
|
||||
@@ -234,6 +234,7 @@ def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool:
|
||||
if not os.path.exists(source_path):
|
||||
return False
|
||||
image = Image.open(source_path)
|
||||
image.load() # Force load to catch truncated files early
|
||||
return save_latest_attempt(image, operation_type)
|
||||
except Exception as e:
|
||||
try:
|
||||
@@ -257,6 +258,7 @@ def save_success_from_file(source_path: str, operation_type: str = "") -> bool:
|
||||
if not os.path.exists(source_path):
|
||||
return False
|
||||
image = Image.open(source_path)
|
||||
image.load() # Force load to catch truncated files early
|
||||
return save_last_success(image, operation_type)
|
||||
except Exception as e:
|
||||
try:
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
智能修复 Python 文件中的缩进语法错误
|
||||
=====================================
|
||||
|
||||
使用 AST 和 tokenize 来更准确地修复缩进问题
|
||||
"""
|
||||
|
||||
import ast
|
||||
import tokenize
|
||||
import io
|
||||
import sys
|
||||
from typing import List, Tuple, Optional
|
||||
|
||||
|
||||
def analyze_indentation_errors(file_path: str) -> List[Tuple[int, str, str]]:
|
||||
"""分析文件中的缩进错误
|
||||
|
||||
返回: [(行号, 错误类型, 建议修复)]
|
||||
"""
|
||||
errors = []
|
||||
|
||||
try:
|
||||
with open(file_path, 'rb') as f:
|
||||
tokens = list(tokenize.tokenize(f.readline))
|
||||
except Exception as e:
|
||||
return [(-1, "读取文件失败", str(e))]
|
||||
|
||||
# 分析 try-except 块
|
||||
try_blocks = []
|
||||
for i, token in enumerate(tokens):
|
||||
if token.type == tokenize.NAME and token.string == 'try':
|
||||
# 查找对应的 except
|
||||
try_indent = token.start[1] # 列号
|
||||
try_blocks.append((token.start[0], try_indent)) # (行号, 缩进)
|
||||
|
||||
# 检查 except 是否与对应的 try 对齐
|
||||
for try_line, try_indent in try_blocks:
|
||||
# 查找这个 try 后面的 except
|
||||
for i, token in enumerate(tokens):
|
||||
if (token.type == tokenize.NAME and token.string == 'except' and
|
||||
token.start[0] > try_line):
|
||||
except_indent = token.start[1]
|
||||
if except_indent != try_indent:
|
||||
errors.append((
|
||||
token.start[0],
|
||||
"except 缩进错误",
|
||||
f"应该与 try (第 {try_line} 行) 对齐,当前缩进 {except_indent},应为 {try_indent}"
|
||||
))
|
||||
break
|
||||
|
||||
return errors
|
||||
|
||||
|
||||
def fix_indentation_with_ast(file_path: str) -> Tuple[bool, str]:
|
||||
"""使用 AST 尝试修复缩进错误"""
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# 尝试解析
|
||||
try:
|
||||
ast.parse(content)
|
||||
return True, "文件语法正确"
|
||||
except SyntaxError as e:
|
||||
# 有语法错误,尝试修复
|
||||
lines = content.split('\n')
|
||||
|
||||
# 修复常见的 except 缩进错误
|
||||
fixed_lines = []
|
||||
for i, line in enumerate(lines):
|
||||
# 检查是否是 except 语句且缩进可能有问题
|
||||
if re.match(r'^\s{8,}except\s+', line):
|
||||
# 向前查找 try
|
||||
for j in range(i-1, max(-1, i-30), -1):
|
||||
if re.match(r'^(\s*)try\s*:', lines[j]):
|
||||
try_indent = len(re.match(r'^(\s*)', lines[j]).group(1))
|
||||
# 修复缩进
|
||||
fixed_line = ' ' * try_indent + line.lstrip()
|
||||
fixed_lines.append(fixed_line)
|
||||
break
|
||||
else:
|
||||
fixed_lines.append(line)
|
||||
else:
|
||||
fixed_lines.append(line)
|
||||
|
||||
fixed_content = '\n'.join(fixed_lines)
|
||||
|
||||
# 验证修复
|
||||
try:
|
||||
ast.parse(fixed_content)
|
||||
with open(file_path, 'w', encoding='utf-8') as f:
|
||||
f.write(fixed_content)
|
||||
return True, "修复成功"
|
||||
except SyntaxError:
|
||||
return False, "无法自动修复"
|
||||
|
||||
except Exception as e:
|
||||
return False, f"错误: {e}"
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import re
|
||||
if len(sys.argv) < 2:
|
||||
print("使用方法: python fix_indent_smart.py <文件路径>")
|
||||
sys.exit(1)
|
||||
|
||||
file_path = sys.argv[1]
|
||||
success, msg = fix_indentation_with_ast(file_path)
|
||||
print(msg)
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
批量修复 Python 文件中的缩进语法错误
|
||||
=====================================
|
||||
|
||||
这个脚本可以修复常见的缩进导致的语法错误:
|
||||
1. except 语句缩进错误
|
||||
2. else 语句缩进错误
|
||||
3. finally 语句缩进错误
|
||||
4. 其他常见的缩进问题
|
||||
|
||||
使用方法:
|
||||
python fix_indentation.py <文件路径>
|
||||
python fix_indentation.py --all # 修复当前目录下所有 .py 文件
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
|
||||
def fix_except_indentation(content: str) -> str:
|
||||
"""修复 except 语句的缩进错误"""
|
||||
lines = content.split('\n')
|
||||
fixed_lines = []
|
||||
i = 0
|
||||
|
||||
while i < len(lines):
|
||||
line = lines[i]
|
||||
|
||||
# 检查是否有缩进错误的 except
|
||||
# 模式:行首有空格,但 except 前面有额外的缩进
|
||||
if re.match(r'^\s{4,}except\s+', line):
|
||||
# 检查前一行是否是 try 块
|
||||
if i > 0:
|
||||
prev_line = lines[i-1].rstrip()
|
||||
# 查找对应的 try 语句
|
||||
try_indent = None
|
||||
for j in range(i-1, max(-1, i-20), -1): # 向前查找最多20行
|
||||
if re.match(r'^(\s*)try\s*:', lines[j]):
|
||||
try_indent = len(re.match(r'^(\s*)', lines[j]).group(1))
|
||||
break
|
||||
|
||||
if try_indent is not None:
|
||||
# 修复缩进:except 应该和 try 对齐
|
||||
fixed_line = ' ' * try_indent + line.lstrip()
|
||||
fixed_lines.append(fixed_line)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
fixed_lines.append(line)
|
||||
i += 1
|
||||
|
||||
return '\n'.join(fixed_lines)
|
||||
|
||||
|
||||
def fix_else_indentation(content: str) -> str:
|
||||
"""修复 else 语句的缩进错误"""
|
||||
lines = content.split('\n')
|
||||
fixed_lines = []
|
||||
i = 0
|
||||
|
||||
while i < len(lines):
|
||||
line = lines[i]
|
||||
|
||||
# 检查是否有缩进错误的 else
|
||||
if re.match(r'^\s{4,}else\s*:', line):
|
||||
# 查找对应的 if/for/while/try 语句
|
||||
if_indent = None
|
||||
for j in range(i-1, max(-1, i-50), -1): # 向前查找
|
||||
prev_line = lines[j].rstrip()
|
||||
if prev_line and not prev_line.strip().startswith('#'):
|
||||
# 检查是否是 if/for/while/try 语句
|
||||
if re.match(r'^(\s*)(if|for|while|try|elif)\s+.*:', prev_line):
|
||||
if_indent = len(re.match(r'^(\s*)', prev_line).group(1))
|
||||
break
|
||||
|
||||
if if_indent is not None:
|
||||
# 修复缩进:else 应该和 if/for/while/try 对齐
|
||||
fixed_line = ' ' * if_indent + line.lstrip()
|
||||
fixed_lines.append(fixed_line)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
fixed_lines.append(line)
|
||||
i += 1
|
||||
|
||||
return '\n'.join(fixed_lines)
|
||||
|
||||
|
||||
def fix_common_indentation_errors(content: str) -> str:
|
||||
"""修复常见的缩进错误模式"""
|
||||
# 修复模式1: except Exception: 前面有多余缩进
|
||||
# 从: " except Exception:"
|
||||
# 到: " except Exception:" (与对应的 try 对齐)
|
||||
content = re.sub(
|
||||
r'^(\s{8,})except\s+',
|
||||
lambda m: ' ' * (len(m.group(1)) - 4) + 'except ',
|
||||
content,
|
||||
flags=re.MULTILINE
|
||||
)
|
||||
|
||||
# 修复模式2: else: 前面有多余缩进
|
||||
content = re.sub(
|
||||
r'^(\s{8,})else\s*:',
|
||||
lambda m: ' ' * (len(m.group(1)) - 4) + 'else:',
|
||||
content,
|
||||
flags=re.MULTILINE
|
||||
)
|
||||
|
||||
# 修复模式3: finally: 前面有多余缩进
|
||||
content = re.sub(
|
||||
r'^(\s{8,})finally\s*:',
|
||||
lambda m: ' ' * (len(m.group(1)) - 4) + 'finally:',
|
||||
content,
|
||||
flags=re.MULTILINE
|
||||
)
|
||||
|
||||
return content
|
||||
|
||||
|
||||
def fix_file(file_path: str, dry_run: bool = False) -> Tuple[bool, str]:
|
||||
"""修复单个文件的缩进错误
|
||||
|
||||
返回: (是否成功, 错误信息)
|
||||
"""
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
original_content = f.read()
|
||||
|
||||
# 先尝试用 Python 解析,如果成功则不需要修复
|
||||
try:
|
||||
compile(original_content, file_path, 'exec')
|
||||
return True, "文件语法正确,无需修复"
|
||||
except SyntaxError:
|
||||
pass # 有语法错误,继续修复
|
||||
|
||||
# 应用修复
|
||||
fixed_content = original_content
|
||||
fixed_content = fix_except_indentation(fixed_content)
|
||||
fixed_content = fix_else_indentation(fixed_content)
|
||||
fixed_content = fix_common_indentation_errors(fixed_content)
|
||||
|
||||
# 验证修复后的代码
|
||||
try:
|
||||
compile(fixed_content, file_path, 'exec')
|
||||
if not dry_run:
|
||||
with open(file_path, 'w', encoding='utf-8') as f:
|
||||
f.write(fixed_content)
|
||||
return True, "修复成功" if not dry_run else "可以修复(预览模式)"
|
||||
except SyntaxError as e:
|
||||
return False, f"修复后仍有语法错误: {e}"
|
||||
|
||||
except Exception as e:
|
||||
return False, f"处理文件时出错: {e}"
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
if len(sys.argv) < 2:
|
||||
print("使用方法:")
|
||||
print(" python fix_indentation.py <文件路径>")
|
||||
print(" python fix_indentation.py --all [目录路径]")
|
||||
print(" python fix_indentation.py --dry-run <文件路径> # 预览模式,不实际修改")
|
||||
sys.exit(1)
|
||||
|
||||
dry_run = '--dry-run' in sys.argv
|
||||
if dry_run:
|
||||
sys.argv.remove('--dry-run')
|
||||
|
||||
if sys.argv[1] == '--all':
|
||||
# 修复目录下所有 .py 文件
|
||||
target_dir = sys.argv[2] if len(sys.argv) > 2 else '.'
|
||||
py_files = list(Path(target_dir).rglob('*.py'))
|
||||
|
||||
print(f"找到 {len(py_files)} 个 Python 文件")
|
||||
success_count = 0
|
||||
fail_count = 0
|
||||
|
||||
for py_file in py_files:
|
||||
# 跳过虚拟环境和缓存目录
|
||||
if any(skip in str(py_file) for skip in ['__pycache__', '.venv', 'venv', '.git']):
|
||||
continue
|
||||
|
||||
print(f"处理: {py_file}")
|
||||
success, msg = fix_file(str(py_file), dry_run=dry_run)
|
||||
if success:
|
||||
print(f" ✓ {msg}")
|
||||
success_count += 1
|
||||
else:
|
||||
print(f" ✗ {msg}")
|
||||
fail_count += 1
|
||||
|
||||
print(f"\n完成: 成功 {success_count} 个,失败 {fail_count} 个")
|
||||
else:
|
||||
# 修复单个文件
|
||||
file_path = sys.argv[1]
|
||||
if not os.path.exists(file_path):
|
||||
print(f"错误: 文件不存在: {file_path}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"处理文件: {file_path}")
|
||||
success, msg = fix_file(file_path, dry_run=dry_run)
|
||||
if success:
|
||||
print(f"✓ {msg}")
|
||||
else:
|
||||
print(f"✗ {msg}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+1006
-338
File diff suppressed because it is too large.
Load diff
@@ -117,6 +117,57 @@ def ensure_dir(path: str) -> None:
|
||||
os.makedirs(dir_path, exist_ok=True)
|
||||
|
||||
|
||||
def find_executable(cmd: str) -> str | None:
|
||||
"""尝试在系统环境中定位可执行命令的完整路径。
|
||||
|
||||
处理策略:
|
||||
- 若 `cmd` 已是存在的路径则直接返回;
|
||||
- 使用 `shutil.which` 尝试查找;
|
||||
- 在 Windows 上回退到 `where`,在类 Unix 上回退到 `command -v` / `which`。
|
||||
|
||||
返回命令的绝对路径,找不到时返回 `None`。
|
||||
"""
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
|
||||
if not cmd:
|
||||
return None
|
||||
# 如果传入的是已有文件路径,直接返回绝对路径
|
||||
if os.path.exists(cmd):
|
||||
return os.path.abspath(cmd)
|
||||
|
||||
# 首选 shutil.which
|
||||
try:
|
||||
found = shutil.which(cmd)
|
||||
if found:
|
||||
return found
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 平台回退检查
|
||||
try:
|
||||
if sys.platform.startswith("win"):
|
||||
# 使用 where 查找(Windows)
|
||||
proc = subprocess.run(["where", cmd], capture_output=True, text=True)
|
||||
if proc.returncode == 0 and proc.stdout:
|
||||
first = proc.stdout.splitlines()[0].strip()
|
||||
if first:
|
||||
return first
|
||||
else:
|
||||
# 类 Unix:尝试 command -v 再 which
|
||||
proc = subprocess.run(["/bin/sh", "-c", f"command -v {cmd} || which {cmd}"], capture_output=True, text=True)
|
||||
if proc.returncode == 0 and proc.stdout:
|
||||
first = proc.stdout.splitlines()[0].strip()
|
||||
if first:
|
||||
return first
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
+179
-45
@@ -39,7 +39,10 @@ _load_local_shim("douyin_reservation_ops", "douyin_reservation_ops.py")
|
||||
|
||||
# 2) 再把完整逻辑所在目录追加到 sys.path,供 `douyin_fudai` 等模块导入
|
||||
try:
|
||||
if os.path.isdir(_EXTERNAL_DOUYIN_FUDAI_DIR) and _EXTERNAL_DOUYIN_FUDAI_DIR not in sys.path:
|
||||
if (
|
||||
os.path.isdir(_EXTERNAL_DOUYIN_FUDAI_DIR)
|
||||
and _EXTERNAL_DOUYIN_FUDAI_DIR not in sys.path
|
||||
):
|
||||
sys.path.append(_EXTERNAL_DOUYIN_FUDAI_DIR)
|
||||
except Exception:
|
||||
# 不影响主流程;如果目录不存在,后续导入会按默认逻辑报错
|
||||
@@ -65,7 +68,9 @@ def ensure_adb_in_path() -> None:
|
||||
candidates.append(os.path.join(localapp, "platform-tools"))
|
||||
userprofile = os.environ.get("USERPROFILE") or ""
|
||||
if userprofile:
|
||||
candidates.append(os.path.join(userprofile, "AppData", "Local", "platform-tools"))
|
||||
candidates.append(
|
||||
os.path.join(userprofile, "AppData", "Local", "platform-tools")
|
||||
)
|
||||
for d in candidates:
|
||||
adb_exe = os.path.join(d, "adb.exe")
|
||||
if os.path.exists(adb_exe):
|
||||
@@ -79,45 +84,145 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
|
||||
p.add_argument("--device-id", default="", help="ADB 设备 ID(为空则自动选择)")
|
||||
p.add_argument("--y-pianyi", type=int, default=0, help="y 轴偏移(通常 -50~50)")
|
||||
p.add_argument("--needswitch", action="store_true", help="是否允许上划切换直播间")
|
||||
p.add_argument("--wait-minutes", type=int, default=0, help="运行时长(分钟),0或负数表示无限运行,默认0(无限运行)")
|
||||
p.add_argument("--test-yanghao-flow", action="store_true", help="测试:只执行一次推荐页养号流程并退出")
|
||||
p.add_argument("--test-yanghao-flow-seconds", type=int, default=10, help="测试:推荐页养号停留秒数")
|
||||
p.add_argument(
|
||||
"--wait-minutes",
|
||||
type=int,
|
||||
default=0,
|
||||
help="运行时长(分钟),0或负数表示无限运行,默认0(无限运行)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--test-yanghao-flow",
|
||||
action="store_true",
|
||||
help="测试:只执行一次推荐页养号流程并退出",
|
||||
)
|
||||
p.add_argument(
|
||||
"--test-yanghao-flow-seconds",
|
||||
type=int,
|
||||
default=10,
|
||||
help="测试:推荐页养号停留秒数",
|
||||
)
|
||||
|
||||
p.add_argument("--test-comment", action="store_true", help="测试:按配置坐标执行一次评论输入+键盘确认发送并退出")
|
||||
p.add_argument(
|
||||
"--test-comment",
|
||||
action="store_true",
|
||||
help="测试:按配置坐标执行一次评论输入+键盘确认发送并退出",
|
||||
)
|
||||
p.add_argument("--test-comment-text", default="测试评论123", help="测试评论内容")
|
||||
|
||||
# 允许从 GUI 覆盖关键配置(不改动 config.json 也能生效)
|
||||
p.add_argument("--min-prize-value-yuan", type=float, default=None, help="最低奖品价值(元),低于则不参与")
|
||||
p.add_argument("--min-participants", type=int, default=None, help="最少参与人数(0/空表示不启用)")
|
||||
p.add_argument("--max-participants", type=int, default=None, help="最多参与人数(0/空表示不启用)")
|
||||
p.add_argument("--skip-if-countdown-gt-seconds", type=int, default=None, help="倒计时大于该秒数则不参与,高价值福袋可预约(needswitch 生效)")
|
||||
p.add_argument(
|
||||
"--min-prize-value-yuan",
|
||||
type=float,
|
||||
default=None,
|
||||
help="最低奖品价值(元),低于则不参与",
|
||||
)
|
||||
p.add_argument(
|
||||
"--min-participants",
|
||||
type=int,
|
||||
default=None,
|
||||
help="最少参与人数(0/空表示不启用)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--max-participants",
|
||||
type=int,
|
||||
default=None,
|
||||
help="最多参与人数(0/空表示不启用)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--skip-if-countdown-gt-seconds",
|
||||
type=int,
|
||||
default=None,
|
||||
help="倒计时大于该秒数则不参与,高价值福袋可预约(needswitch 生效)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--reset-after-swipes",
|
||||
type=int,
|
||||
default=None,
|
||||
help="切换直播间达到该次数后,在直播间页面下滑回退到本轮第一个直播间(需配合 --reset-after-swipes-enabled)",
|
||||
)
|
||||
p.add_argument("--reset-after-swipes-enabled", action="store_true", help="开启切换次数阈值回退到第一个直播间")
|
||||
p.add_argument("--reset-after-swipes-disabled", action="store_true", help="关闭切换次数阈值回退到第一个直播间")
|
||||
p.add_argument(
|
||||
"--reset-after-swipes-enabled",
|
||||
action="store_true",
|
||||
help="开启切换次数阈值回退到第一个直播间",
|
||||
)
|
||||
p.add_argument(
|
||||
"--reset-after-swipes-disabled",
|
||||
action="store_true",
|
||||
help="关闭切换次数阈值回退到第一个直播间",
|
||||
)
|
||||
|
||||
# 高价值直播间回访运行时开关(GUI 可在启动时传参覆盖)
|
||||
p.add_argument("--high-value-room-revisit-enabled", action="store_true", help="启用高价值直播间定时回访")
|
||||
p.add_argument("--high-value-room-revisit-disabled", action="store_true", help="禁用高价值直播间定时回访")
|
||||
p.add_argument("--high-value-room-revisit-only-current-run", action="store_true", help="仅回访本次运行记录的高价值直播间")
|
||||
p.add_argument("--reservation-back-verify-enabled", action="store_true", help="启用回退后预约校验(默认启用)")
|
||||
p.add_argument("--reservation-back-verify-disabled", action="store_true", help="禁用回退后预约校验")
|
||||
p.add_argument("--reservation-back-swipe-delay", type=float, default=None, help="运行时覆盖:回退后滑动等待(秒),仅在未启用回退校验时生效,可加快回退速度")
|
||||
p.add_argument("--reservation-preempt-min-value", type=float, default=None, help="运行时覆盖:预约抢占最小价值(元),低于该值的预约不会抢占当前任务")
|
||||
p.add_argument("--fudai-find-max-attempts", type=int, default=None, help="运行时覆盖:找福袋图标最多尝试次数(整数)")
|
||||
p.add_argument(
|
||||
"--high-value-room-revisit-enabled",
|
||||
action="store_true",
|
||||
help="启用高价值直播间定时回访",
|
||||
)
|
||||
p.add_argument(
|
||||
"--high-value-room-revisit-disabled",
|
||||
action="store_true",
|
||||
help="禁用高价值直播间定时回访",
|
||||
)
|
||||
p.add_argument(
|
||||
"--high-value-room-revisit-only-current-run",
|
||||
action="store_true",
|
||||
help="仅回访本次运行记录的高价值直播间",
|
||||
)
|
||||
p.add_argument(
|
||||
"--reservation-back-verify-enabled",
|
||||
action="store_true",
|
||||
help="启用回退后预约校验(默认启用)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--reservation-back-verify-disabled",
|
||||
action="store_true",
|
||||
help="禁用回退后预约校验",
|
||||
)
|
||||
p.add_argument(
|
||||
"--reservation-back-swipe-delay",
|
||||
type=float,
|
||||
default=None,
|
||||
help="运行时覆盖:回退后滑动等待(秒),仅在未启用回退校验时生效,可加快回退速度",
|
||||
)
|
||||
p.add_argument(
|
||||
"--reservation-preempt-min-value",
|
||||
type=float,
|
||||
default=None,
|
||||
help="运行时覆盖:预约抢占最小价值(元),低于该值的预约不会抢占当前任务",
|
||||
)
|
||||
p.add_argument(
|
||||
"--fudai-find-max-attempts",
|
||||
type=int,
|
||||
default=None,
|
||||
help="运行时覆盖:找福袋图标最多尝试次数(整数)",
|
||||
)
|
||||
|
||||
# 按需求:删除“自动养号/随机等待/轻微扰动”等参数,仅保留“推荐页养号流程”。
|
||||
# 推荐页养号的动作/概率/阈值等由 config.json 控制(GUI 会保存)。
|
||||
p.add_argument("--auto-join-fansclub", action="store_true", help="自动尝试加入粉丝团(可能消耗钻石)")
|
||||
p.add_argument("--fansclub-fail-action", choices=["stay", "switch"], default=None,
|
||||
help="粉丝团门槛无法处理时:stay=停留当前直播间;switch=切换下一个")
|
||||
p.add_argument("--enable-ocr-mode1", action="store_true", help="启用OCR模式1(二值化模式,默认关闭)")
|
||||
p.add_argument("--disable-ocr-mode1", action="store_true", help="禁用OCR模式1(默认已禁用)")
|
||||
p.add_argument("--fudai-template-threshold", type=float, default=None, help="福袋模板匹配阈值(0.0-1.0,默认0.7)")
|
||||
p.add_argument(
|
||||
"--auto-join-fansclub",
|
||||
action="store_true",
|
||||
help="自动尝试加入粉丝团(可能消耗钻石)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--fansclub-fail-action",
|
||||
choices=["stay", "switch"],
|
||||
default=None,
|
||||
help="粉丝团门槛无法处理时:stay=停留当前直播间;switch=切换下一个",
|
||||
)
|
||||
p.add_argument(
|
||||
"--enable-ocr-mode1",
|
||||
action="store_true",
|
||||
help="启用OCR模式1(二值化模式,默认关闭)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--disable-ocr-mode1", action="store_true", help="禁用OCR模式1(默认已禁用)"
|
||||
)
|
||||
p.add_argument(
|
||||
"--fudai-template-threshold",
|
||||
type=float,
|
||||
default=None,
|
||||
help="福袋模板匹配阈值(0.0-1.0,默认0.7)",
|
||||
)
|
||||
|
||||
return p.parse_args(argv)
|
||||
|
||||
@@ -136,7 +241,9 @@ def main(argv: list[str]) -> int:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if bool(getattr(args, "test_yanghao_flow", False)) or bool(getattr(args, "test_comment", False)):
|
||||
if bool(getattr(args, "test_yanghao_flow", False)) or bool(
|
||||
getattr(args, "test_comment", False)
|
||||
):
|
||||
os.environ.setdefault("SKIP_OCR_INIT", "1")
|
||||
os.environ.setdefault("NO_TEE_STDOUT", "1")
|
||||
os.environ.setdefault("FAST_UI", "1")
|
||||
@@ -152,8 +259,14 @@ def main(argv: list[str]) -> int:
|
||||
return 2
|
||||
analyser.device_id = device_id
|
||||
analyser.y_pianyi = int(args.y_pianyi or 0)
|
||||
analyser.resolution_ratio_x, analyser.resolution_ratio_y = analyser.operation.get_device_resolution(device_id)
|
||||
print("[TEST-COMMENT] device_id={} res={}x{}".format(device_id, analyser.resolution_ratio_x, analyser.resolution_ratio_y))
|
||||
analyser.resolution_ratio_x, analyser.resolution_ratio_y = (
|
||||
analyser.operation.get_device_resolution(device_id)
|
||||
)
|
||||
print(
|
||||
"[TEST-COMMENT] device_id={} res={}x{}".format(
|
||||
device_id, analyser.resolution_ratio_x, analyser.resolution_ratio_y
|
||||
)
|
||||
)
|
||||
|
||||
msg = str(getattr(args, "test_comment_text", "测试评论123") or "测试评论123")
|
||||
# 逐步截图
|
||||
@@ -164,15 +277,22 @@ def main(argv: list[str]) -> int:
|
||||
analyser.operation.click(device_id, sx, sy)
|
||||
|
||||
try:
|
||||
_scaled_click(analyser.yanghao_comment_btn_x, analyser.yanghao_comment_btn_y)
|
||||
_scaled_click(
|
||||
getattr(analyser, "yanghao_comment_btn_x", 540), getattr(analyser, "yanghao_comment_btn_y", 2000)
|
||||
)
|
||||
analyser.operation.delay(1)
|
||||
analyser._save_step_screenshot("test_comment_after_open")
|
||||
|
||||
_scaled_click(analyser.yanghao_comment_input_x, analyser.yanghao_comment_input_y)
|
||||
_scaled_click(
|
||||
getattr(analyser, "yanghao_comment_input_x", 540), getattr(analyser, "yanghao_comment_input_y", 1900)
|
||||
)
|
||||
analyser.operation.delay(1)
|
||||
analyser._save_step_screenshot("test_comment_after_focus")
|
||||
|
||||
ix, iy = analyser._scale_from_base(int(analyser.yanghao_comment_input_x), int(analyser.yanghao_comment_input_y))
|
||||
ix, iy = analyser._scale_from_base(
|
||||
int(getattr(analyser, "yanghao_comment_input_x", 540)),
|
||||
int(getattr(analyser, "yanghao_comment_input_y", 1900)),
|
||||
)
|
||||
ok_input = bool(analyser.operation.paste_text_at(device_id, ix, iy, msg))
|
||||
print("[TEST-COMMENT] input {}".format("OK" if ok_input else "FAIL"))
|
||||
analyser.operation.delay(1)
|
||||
@@ -183,7 +303,9 @@ def main(argv: list[str]) -> int:
|
||||
analyser.operation.delay(1)
|
||||
analyser._save_step_screenshot("test_comment_after_send")
|
||||
|
||||
_scaled_click(analyser.yanghao_comment_close_x, analyser.yanghao_comment_close_y)
|
||||
_scaled_click(
|
||||
getattr(analyser, "yanghao_comment_close_x", 900), getattr(analyser, "yanghao_comment_close_y", 300)
|
||||
)
|
||||
analyser.operation.delay(1)
|
||||
analyser._save_step_screenshot("test_comment_after_close")
|
||||
except Exception as e:
|
||||
@@ -201,15 +323,21 @@ def main(argv: list[str]) -> int:
|
||||
return 2
|
||||
analyser.device_id = device_id
|
||||
analyser.y_pianyi = int(args.y_pianyi or 0)
|
||||
analyser.resolution_ratio_x, analyser.resolution_ratio_y = analyser.operation.get_device_resolution(device_id)
|
||||
analyser.yanghao_use_recommend_flow = True
|
||||
analyser.resolution_ratio_x, analyser.resolution_ratio_y = (
|
||||
analyser.operation.get_device_resolution(device_id)
|
||||
)
|
||||
setattr(analyser, "yanghao_use_recommend_flow", True)
|
||||
# 加载配置(包括养号相关配置)
|
||||
analyser.load_config()
|
||||
print("[TEST] device_id={} res={}x{}".format(device_id, analyser.resolution_ratio_x, analyser.resolution_ratio_y))
|
||||
print(
|
||||
"[TEST] device_id={} res={}x{}".format(
|
||||
device_id, analyser.resolution_ratio_x, analyser.resolution_ratio_y
|
||||
)
|
||||
)
|
||||
seconds = int(getattr(args, "test_yanghao_flow_seconds", 10) or 10)
|
||||
if seconds < 1:
|
||||
seconds = 1
|
||||
analyser._yanghao_recommend_flow(seconds)
|
||||
getattr(analyser, "_yanghao_recommend_flow", lambda _: None)(seconds) # type: ignore[attr-defined]
|
||||
print("[TEST] done")
|
||||
return 0
|
||||
|
||||
@@ -220,7 +348,9 @@ def main(argv: list[str]) -> int:
|
||||
if args.max_participants is not None:
|
||||
analyser.max_participants = int(args.max_participants or 0)
|
||||
if args.skip_if_countdown_gt_seconds is not None:
|
||||
analyser.skip_if_countdown_gt_seconds = int(args.skip_if_countdown_gt_seconds or 900)
|
||||
analyser.skip_if_countdown_gt_seconds = int(
|
||||
args.skip_if_countdown_gt_seconds or 900
|
||||
)
|
||||
if args.reset_after_swipes is not None:
|
||||
analyser.reset_after_swipes = max(1, int(args.reset_after_swipes or 0))
|
||||
analyser.reset_after_swipes_enabled = True
|
||||
@@ -229,9 +359,9 @@ def main(argv: list[str]) -> int:
|
||||
if args.reset_after_swipes_disabled:
|
||||
analyser.reset_after_swipes_enabled = False
|
||||
if args.auto_join_fansclub:
|
||||
analyser.auto_join_fansclub = True
|
||||
setattr(analyser, "auto_join_fansclub", True)
|
||||
if args.fansclub_fail_action is not None:
|
||||
analyser.fansclub_fail_action = args.fansclub_fail_action
|
||||
setattr(analyser, "fansclub_fail_action", args.fansclub_fail_action)
|
||||
# 高价值直播间回访开关(优先级:命令行 > config)
|
||||
if getattr(args, "high_value_room_revisit_enabled", False):
|
||||
analyser.high_value_room_revisit_enabled = True
|
||||
@@ -247,12 +377,16 @@ def main(argv: list[str]) -> int:
|
||||
# 运行时覆盖:回退后滑动等待(快速值,仅在未启用回退校验时使用)
|
||||
if getattr(args, "reservation_back_swipe_delay", None) is not None:
|
||||
try:
|
||||
analyser.reservation_back_swipe_delay_fast_seconds = float(args.reservation_back_swipe_delay)
|
||||
setattr(analyser, "reservation_back_swipe_delay_fast_seconds", float(
|
||||
args.reservation_back_swipe_delay
|
||||
))
|
||||
except Exception:
|
||||
pass
|
||||
if getattr(args, "reservation_preempt_min_value", None) is not None:
|
||||
try:
|
||||
analyser.reservation_preempt_min_value_yuan = max(0.0, float(args.reservation_preempt_min_value))
|
||||
analyser.reservation_preempt_min_value_yuan = max(
|
||||
0.0, float(args.reservation_preempt_min_value)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 运行时覆盖:找福袋最大尝试次数
|
||||
@@ -263,9 +397,9 @@ def main(argv: list[str]) -> int:
|
||||
pass
|
||||
# OCR模式1开关(命令行优先)
|
||||
if getattr(args, "enable_ocr_mode1", False):
|
||||
analyser.enable_ocr_mode1 = True
|
||||
setattr(analyser, "enable_ocr_mode1", True)
|
||||
if getattr(args, "disable_ocr_mode1", False):
|
||||
analyser.enable_ocr_mode1 = False
|
||||
setattr(analyser, "enable_ocr_mode1", False)
|
||||
# 福袋模板匹配阈值(命令行优先)
|
||||
if getattr(args, "fudai_template_threshold", None) is not None:
|
||||
try:
|
||||
@@ -299,4 +433,4 @@ if __name__ == "__main__":
|
||||
print_version_banner("run_cli")
|
||||
except Exception:
|
||||
pass
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
+22
-12
@@ -1,19 +1,29 @@
|
||||
{
|
||||
"updated_ts": 1766208769.6966574,
|
||||
"reason": "record_reservation",
|
||||
"room_pos": 4,
|
||||
"current_room_title": "礻1390亘未四",
|
||||
"current_room_title_raw": "礻1390亘》未四",
|
||||
"updated_ts": 1766296646.5161223,
|
||||
"reason": "process_reservation",
|
||||
"room_pos": 3,
|
||||
"current_room_title": "瑛瑛服饰",
|
||||
"current_room_title_raw": "瑛瑛服饰",
|
||||
"reservations": [
|
||||
{
|
||||
"prize_value_yuan": 5999.0,
|
||||
"content": "(董先生专属1ihone172566B颜色随机发",
|
||||
"future_ts": 1766209419.662086,
|
||||
"future_str": "2025-12-20 13:43:39",
|
||||
"pos_seen": 4,
|
||||
"room_title": "礻1390亘未四",
|
||||
"room_title_raw": "礻1390亘》未四",
|
||||
"created_ts": 1766208769.695657
|
||||
"content": "(瓜瓜专属1jhone17256GB颜色随机发货",
|
||||
"future_ts": 1766296724.971495,
|
||||
"future_str": "2025-12-21 13:58:44",
|
||||
"pos_seen": 3,
|
||||
"room_title": "朱瓜瓜21",
|
||||
"room_title_raw": "朱瓜瓜21.",
|
||||
"created_ts": 1766296094.8779616
|
||||
},
|
||||
{
|
||||
"prize_value_yuan": 1299.0,
|
||||
"content": "(刘一一专属]小米RedmiPadSE新款平板11英寸护",
|
||||
"future_ts": 1766296734.30947,
|
||||
"future_str": "2025-12-21 13:58:54",
|
||||
"pos_seen": 5,
|
||||
"room_title": "刘11生活",
|
||||
"room_title_raw": "刘11生活。。",
|
||||
"created_ts": 1766296163.6473088
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -10,7 +10,7 @@ from PIL import Image
|
||||
# 修复 Windows 控制台编码问题
|
||||
if sys.platform == 'win32':
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
||||
sys.stdout.reconfigure(encoding='utf-8', errors='replace') # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -101,7 +101,11 @@ class CoordPicker:
|
||||
|
||||
disp_img = self.img
|
||||
if self.scale < 1.0:
|
||||
disp_img = self.img.resize((self.disp_w, self.disp_h), Image.BICUBIC)
|
||||
try:
|
||||
resample = Image.Resampling.BICUBIC # Pillow>=9
|
||||
except Exception:
|
||||
resample = Image.BICUBIC # older Pillow
|
||||
disp_img = self.img.resize((self.disp_w, self.disp_h), resample)
|
||||
|
||||
self.tk_img = ImageTk.PhotoImage(disp_img)
|
||||
self.canvas.config(width=self.disp_w, height=self.disp_h)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Sanitize logs and text files by replacing absolute .cursor worktree paths
|
||||
with a safer relative marker. Example absolute paths are shown using
|
||||
forward-slashes to avoid source-level escape issues, e.g.:
|
||||
|
||||
C:/Users/<user>/.cursor/worktrees/...
|
||||
|
||||
Creates a backup copy with suffix .bak for each file modified.
|
||||
|
||||
Usage:
|
||||
python tools/sanitize_cursor_paths.py path/to/logs [--dry-run]
|
||||
|
||||
This is safe to run on a logs directory. It will only update files that contain
|
||||
matches and will save a backup as <file>.bak before writing changes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
# Regex to match Windows absolute .cursor worktree paths
|
||||
# Use raw string to avoid Unicode escape issues
|
||||
_CURSOR_RE = re.compile(r"C:\\Users\\[^\\\s]+\\.cursor\\worktrees\\")
|
||||
|
||||
|
||||
def sanitize_file(p: Path, dry_run: bool = False) -> int:
|
||||
"""Sanitize a single file by replacing .cursor worktree paths.
|
||||
|
||||
Args:
|
||||
p: Path to the file to sanitize
|
||||
dry_run: If True, only check for matches without modifying
|
||||
|
||||
Returns:
|
||||
1 if file was modified or would be modified, 0 otherwise
|
||||
"""
|
||||
text = p.read_text(encoding="utf-8", errors="replace")
|
||||
if not _CURSOR_RE.search(text):
|
||||
return 0
|
||||
new_text = _CURSOR_RE.sub(".cursor/worktrees/", text)
|
||||
if dry_run:
|
||||
return 1
|
||||
bak = p.with_suffix(p.suffix + ".bak")
|
||||
bak.write_text(text, encoding="utf-8")
|
||||
p.write_text(new_text, encoding="utf-8")
|
||||
return 1
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Main entry point for the sanitize script."""
|
||||
ap = argparse.ArgumentParser(description="Sanitize .cursor absolute paths in files")
|
||||
ap.add_argument("path", type=Path, help="File or directory to scan")
|
||||
ap.add_argument(
|
||||
"--dry-run", action="store_true", help="Only report matches, do not modify"
|
||||
)
|
||||
args = ap.parse_args()
|
||||
|
||||
target = args.path
|
||||
files = []
|
||||
if target.is_dir():
|
||||
files = list(target.rglob("*.log")) + list(target.rglob("*.txt"))
|
||||
elif target.is_file():
|
||||
files = [target]
|
||||
else:
|
||||
print(f"No such file or directory: {target}")
|
||||
raise SystemExit(2)
|
||||
|
||||
modified = 0
|
||||
for f in files:
|
||||
try:
|
||||
res = sanitize_file(f, dry_run=args.dry_run)
|
||||
if res:
|
||||
modified += 1
|
||||
print(("DRY:" if args.dry_run else "MODIFIED:"), f)
|
||||
except Exception as e:
|
||||
print("ERROR processing", f, e)
|
||||
|
||||
print("Done. Files matched/modified:", modified)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+181
-73
@@ -15,14 +15,14 @@ CONFIG_PATH = os.path.join(BASE_DIR, "config.json")
|
||||
WEBUI_DIR = os.path.join(BASE_DIR, "webui")
|
||||
|
||||
# ANSI转义序列清理正则表达式
|
||||
_ANSI_ESCAPE_RE = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
|
||||
_ANSI_ESCAPE_RE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
|
||||
|
||||
|
||||
def strip_ansi_escape_codes(text: str) -> str:
|
||||
"""移除字符串中的ANSI转义序列(颜色代码等)。"""
|
||||
if not isinstance(text, str):
|
||||
return str(text)
|
||||
return _ANSI_ESCAPE_RE.sub('', text)
|
||||
return _ANSI_ESCAPE_RE.sub("", text)
|
||||
|
||||
|
||||
def find_adb_executable() -> str:
|
||||
@@ -35,7 +35,9 @@ def find_adb_executable() -> str:
|
||||
candidates.append(os.path.join(localapp, "platform-tools", "adb.exe"))
|
||||
userprofile = os.environ.get("USERPROFILE") or ""
|
||||
if userprofile:
|
||||
candidates.append(os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe"))
|
||||
candidates.append(
|
||||
os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe")
|
||||
)
|
||||
for p in candidates:
|
||||
if os.path.exists(p):
|
||||
return p
|
||||
@@ -46,7 +48,13 @@ def list_adb_devices(adb_exe: str) -> list[str]:
|
||||
try:
|
||||
if not adb_exe:
|
||||
return []
|
||||
proc = subprocess.run([adb_exe, "devices", "-l"], capture_output=True, text=True, encoding="utf-8", errors="replace")
|
||||
proc = subprocess.run(
|
||||
[adb_exe, "devices", "-l"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
text = (proc.stdout or "") + "\n" + (proc.stderr or "")
|
||||
@@ -72,7 +80,9 @@ class ProcRunner:
|
||||
self._proc: subprocess.Popen | None = None
|
||||
self._lock = threading.Lock()
|
||||
self._log: list[str] = []
|
||||
self._log_capacity: int = 10000 # 0=不限制(可能占用大量内存),增加到10000避免日志被过早截断
|
||||
self._log_capacity: int = (
|
||||
10000 # 0=不限制(可能占用大量内存),增加到10000避免日志被过早截断
|
||||
)
|
||||
self._log_file_enabled: bool = True
|
||||
self._log_file_path: str = os.path.join(BASE_DIR, "logs", "unified.log")
|
||||
self._start_ts: float | None = None
|
||||
@@ -132,18 +142,20 @@ class ProcRunner:
|
||||
pass
|
||||
try:
|
||||
# 使用 utf-8-sig:文件首次创建时会写入 BOM,避免 Windows PowerShell 误按 ANSI 读取导致中文乱码
|
||||
with open(self._log_file_path, "a", encoding="utf-8-sig", errors="replace") as f:
|
||||
with open(
|
||||
self._log_file_path, "a", encoding="utf-8-sig", errors="replace"
|
||||
) as f:
|
||||
f.write(line + "\n")
|
||||
f.flush() # 确保立即写入磁盘,避免缓冲区延迟导致日志丢失
|
||||
except PermissionError as e:
|
||||
# 权限错误,只输出一次警告避免刷屏
|
||||
if not hasattr(self, '_log_permission_warned'):
|
||||
if not hasattr(self, "_log_permission_warned"):
|
||||
print(f"[WEB_GUI] 警告:日志文件写入权限错误: {self._log_file_path}")
|
||||
print(f"[WEB_GUI] 错误详情: {e}")
|
||||
self._log_permission_warned = True
|
||||
except Exception as e:
|
||||
# 其他文件写失败不应影响主流程,但记录第一次错误以便调试
|
||||
if not hasattr(self, '_log_write_error_warned'):
|
||||
if not hasattr(self, "_log_write_error_warned"):
|
||||
print(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}")
|
||||
print(f"[WEB_GUI] 错误详情: {e}")
|
||||
self._log_write_error_warned = True
|
||||
@@ -159,7 +171,7 @@ class ProcRunner:
|
||||
}
|
||||
self._events.append(ev)
|
||||
if len(self._events) > self._events_cap:
|
||||
self._events = self._events[-self._events_cap:]
|
||||
self._events = self._events[-self._events_cap :]
|
||||
|
||||
def _record_win(self) -> None:
|
||||
item = {
|
||||
@@ -168,10 +180,10 @@ class ProcRunner:
|
||||
}
|
||||
self._wins.append(item)
|
||||
if len(self._wins) > self._wins_cap:
|
||||
self._wins = self._wins[-self._wins_cap:]
|
||||
self._wins = self._wins[-self._wins_cap :]
|
||||
|
||||
@staticmethod
|
||||
def _parse_countdown_seconds(text: str) -> int | None:
|
||||
def _parse_countdown_seconds(text: str) -> int | None: # type: ignore[misc]
|
||||
t = str(text or "").strip()
|
||||
if not t:
|
||||
return None
|
||||
@@ -213,7 +225,7 @@ class ProcRunner:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _bucket(value: float, edges: list[float]) -> str:
|
||||
def _bucket(value: float, edges: list[float]) -> str: # type: ignore[misc]
|
||||
# edges 例如 [0,10,50,100] => 0-10,10-50,50-100,100+
|
||||
if not edges:
|
||||
return "all"
|
||||
@@ -225,7 +237,7 @@ class ProcRunner:
|
||||
return f"{edges[-1]:g}+"
|
||||
|
||||
@staticmethod
|
||||
def _inc_map(m: dict, k: str, n: int = 1) -> None:
|
||||
def _inc_map(m: dict, k: str, n: int = 1) -> None: # type: ignore[misc]
|
||||
m[k] = int(m.get(k, 0)) + int(n)
|
||||
|
||||
def _snapshot_fudai(self) -> dict:
|
||||
@@ -296,22 +308,34 @@ class ProcRunner:
|
||||
# --- 福袋:跳过/过滤原因 ---
|
||||
if "参与人数" in s and "< 阈值" in s and "不参与" in s:
|
||||
self._inc("fudai_skip_participants_low")
|
||||
self._record_event("fudai_skip", {"reason": "participants_low", **self._snapshot_fudai()})
|
||||
self._record_event(
|
||||
"fudai_skip", {"reason": "participants_low", **self._snapshot_fudai()}
|
||||
)
|
||||
if "参与人数" in s and "> 阈值" in s and "不参与" in s:
|
||||
self._inc("fudai_skip_participants_high")
|
||||
self._record_event("fudai_skip", {"reason": "participants_high", **self._snapshot_fudai()})
|
||||
self._record_event(
|
||||
"fudai_skip", {"reason": "participants_high", **self._snapshot_fudai()}
|
||||
)
|
||||
if "奖品价值" in s and "< 阈值" in s and "不参与" in s:
|
||||
self._inc("fudai_skip_value_low")
|
||||
self._record_event("fudai_skip", {"reason": "value_low", **self._snapshot_fudai()})
|
||||
self._record_event(
|
||||
"fudai_skip", {"reason": "value_low", **self._snapshot_fudai()}
|
||||
)
|
||||
if "福袋内容不理想" in s:
|
||||
self._inc("fudai_skip_content")
|
||||
self._record_event("fudai_skip", {"reason": "content", **self._snapshot_fudai()})
|
||||
self._record_event(
|
||||
"fudai_skip", {"reason": "content", **self._snapshot_fudai()}
|
||||
)
|
||||
if "抽奖倒计时时间小于" in s and "不参与" in s:
|
||||
self._inc("fudai_skip_countdown_short")
|
||||
self._record_event("fudai_skip", {"reason": "countdown_short", **self._snapshot_fudai()})
|
||||
self._record_event(
|
||||
"fudai_skip", {"reason": "countdown_short", **self._snapshot_fudai()}
|
||||
)
|
||||
if "抽奖倒计时时间大于" in s and "暂不参与" in s:
|
||||
self._inc("fudai_skip_countdown_long")
|
||||
self._record_event("fudai_skip", {"reason": "countdown_long", **self._snapshot_fudai()})
|
||||
self._record_event(
|
||||
"fudai_skip", {"reason": "countdown_long", **self._snapshot_fudai()}
|
||||
)
|
||||
# 看播门槛:默认不参与(新结构化日志)
|
||||
if (
|
||||
"需要看播时长:默认不参与" in s
|
||||
@@ -319,7 +343,9 @@ class ProcRunner:
|
||||
or ("[参与]" in s and "结果=看播门槛" in s)
|
||||
):
|
||||
self._inc("fudai_skip_watch_required")
|
||||
self._record_event("fudai_skip", {"reason": "watch_required", **self._snapshot_fudai()})
|
||||
self._record_event(
|
||||
"fudai_skip", {"reason": "watch_required", **self._snapshot_fudai()}
|
||||
)
|
||||
if "打开福袋异常" in s:
|
||||
self._inc("fudai_open_error")
|
||||
self._record_event("fudai_open_error", self._snapshot_fudai())
|
||||
@@ -339,13 +365,17 @@ class ProcRunner:
|
||||
self._record_event("fansclub_unresolved", self._snapshot_fudai())
|
||||
|
||||
# --- 预约队列/回退校验 ---
|
||||
if ("[预约]" in s and "回退校验通过" in s) or "回退校验通过:已回到目标直播间" in s:
|
||||
if (
|
||||
"[预约]" in s and "回退校验通过" in s
|
||||
) or "回退校验通过:已回到目标直播间" in s:
|
||||
self._inc("reservation_back_verify_ok")
|
||||
self._record_event("reservation_back_verify_ok", {})
|
||||
if ("[预约]" in s and "回退校验失败" in s) or "回退校验失败" in s:
|
||||
self._inc("reservation_back_verify_fail")
|
||||
self._record_event("reservation_back_verify_fail", {})
|
||||
if ("[预约]" in s and "预约队列已满,丢弃最低价值" in s) or "预约队列已满,丢弃最低价值" in s:
|
||||
if (
|
||||
"[预约]" in s and "预约队列已满,丢弃最低价值" in s
|
||||
) or "预约队列已满,丢弃最低价值" in s:
|
||||
self._inc("reservation_drop_low_value")
|
||||
self._record_event("reservation_drop_low_value", {})
|
||||
if ("[预约]" in s and "清空预约队列" in s) or "清空预约队列" in s:
|
||||
@@ -386,10 +416,15 @@ class ProcRunner:
|
||||
elif "参与抽奖失败" in s:
|
||||
self._inc("switch_room_attend_fail")
|
||||
meta_reason = "attend_fail"
|
||||
self._record_event("switch_room", {"reason": meta_reason, **self._snapshot_fudai()})
|
||||
self._record_event(
|
||||
"switch_room", {"reason": meta_reason, **self._snapshot_fudai()}
|
||||
)
|
||||
|
||||
# --- 性能:进入直播间到识别福袋耗时 ---
|
||||
m = re.search(r"进入直播间到识别福袋耗时:\s*([0-9]+(?:\.[0-9]+)?)\s*秒(?:\s*进入原因=(.*))?", s)
|
||||
m = re.search(
|
||||
r"进入直播间到识别福袋耗时:\s*([0-9]+(?:\.[0-9]+)?)\s*秒(?:\s*进入原因=(.*))?",
|
||||
s,
|
||||
)
|
||||
if m:
|
||||
try:
|
||||
secs = float(m.group(1))
|
||||
@@ -397,7 +432,10 @@ class ProcRunner:
|
||||
secs = None
|
||||
reason = str(m.group(2) or "")
|
||||
# 记录为事件,便于后续做分布/趋势分析
|
||||
self._record_event("enter_to_fudai_seen", {"secs": secs, "enter_reason": reason, **self._snapshot_fudai()})
|
||||
self._record_event(
|
||||
"enter_to_fudai_seen",
|
||||
{"secs": secs, "enter_reason": reason, **self._snapshot_fudai()},
|
||||
)
|
||||
# 同时做一个计数器
|
||||
try:
|
||||
self._inc("enter_to_fudai_seen")
|
||||
@@ -418,8 +456,18 @@ class ProcRunner:
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
except Exception:
|
||||
return {"reservations": [], "room_pos": 0, "updated_ts": 0.0, "reason": "state_read_or_parse_failed"}
|
||||
return {"reservations": [], "room_pos": 0, "updated_ts": 0.0, "reason": "no_state_file"}
|
||||
return {
|
||||
"reservations": [],
|
||||
"room_pos": 0,
|
||||
"updated_ts": 0.0,
|
||||
"reason": "state_read_or_parse_failed",
|
||||
}
|
||||
return {
|
||||
"reservations": [],
|
||||
"room_pos": 0,
|
||||
"updated_ts": 0.0,
|
||||
"reason": "no_state_file",
|
||||
}
|
||||
|
||||
def get_high_value_rooms(self) -> dict:
|
||||
"""获取永久记录的高价值直播间列表(来自 state/high_value_rooms.json)。"""
|
||||
@@ -431,9 +479,19 @@ class ProcRunner:
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
if isinstance(data, list):
|
||||
return {"updated_ts": 0.0, "reason": "legacy_list", "total": len(data), "rooms": data}
|
||||
return {
|
||||
"updated_ts": 0.0,
|
||||
"reason": "legacy_list",
|
||||
"total": len(data),
|
||||
"rooms": data,
|
||||
}
|
||||
except Exception:
|
||||
return {"updated_ts": 0.0, "reason": "state_read_or_parse_failed", "total": 0, "rooms": []}
|
||||
return {
|
||||
"updated_ts": 0.0,
|
||||
"reason": "state_read_or_parse_failed",
|
||||
"total": 0,
|
||||
"rooms": [],
|
||||
}
|
||||
return {"updated_ts": 0.0, "reason": "no_state_file", "total": 0, "rooms": []}
|
||||
|
||||
def stop(self) -> None:
|
||||
@@ -545,33 +603,34 @@ class ProcRunner:
|
||||
series["switch_room"][bi] += 1
|
||||
|
||||
# 分布/Top
|
||||
if typ == "fudai_skip":
|
||||
r = str(meta.get("reason") or "unknown")
|
||||
self._inc_map(skip_reason, r, 1)
|
||||
if typ == "switch_room":
|
||||
r = str(meta.get("reason") or "unknown")
|
||||
self._inc_map(switch_reason, r, 1)
|
||||
if meta is not None:
|
||||
if typ == "fudai_skip":
|
||||
r = str(meta.get("reason") or "unknown")
|
||||
self._inc_map(skip_reason, r, 1)
|
||||
if typ == "switch_room":
|
||||
r = str(meta.get("reason") or "unknown")
|
||||
self._inc_map(switch_reason, r, 1)
|
||||
|
||||
content = str(meta.get("content") or "").strip()
|
||||
if content:
|
||||
# 只取前 60 字符作为展示 key,避免超长撑爆
|
||||
key = (content[:60] + "…") if len(content) > 60 else content
|
||||
self._inc_map(content_top, key, 1)
|
||||
content = str(meta.get("content") or "").strip()
|
||||
if content:
|
||||
# 只取前 60 字符作为展示 key,避免超长撑爆
|
||||
key = (content[:60] + "…") if len(content) > 60 else content
|
||||
self._inc_map(content_top, key, 1)
|
||||
|
||||
v = meta.get("prize_value_yuan")
|
||||
if isinstance(v, (int, float)):
|
||||
b = self._bucket(float(v), value_edges)
|
||||
self._inc_map(value_buckets, b, 1)
|
||||
p = meta.get("participants")
|
||||
if isinstance(p, int):
|
||||
b = self._bucket(float(p), participants_edges)
|
||||
self._inc_map(participants_buckets, b, 1)
|
||||
cd = meta.get("countdown")
|
||||
if isinstance(cd, str) and cd.strip():
|
||||
sec = self._parse_countdown_seconds(cd)
|
||||
if isinstance(sec, int):
|
||||
b = self._bucket(float(sec), countdown_edges)
|
||||
self._inc_map(countdown_buckets, b, 1)
|
||||
v = meta.get("prize_value_yuan")
|
||||
if isinstance(v, (int, float)):
|
||||
b = self._bucket(float(v), value_edges)
|
||||
self._inc_map(value_buckets, b, 1)
|
||||
p = meta.get("participants")
|
||||
if isinstance(p, int):
|
||||
b = self._bucket(float(p), [float(e) for e in participants_edges])
|
||||
self._inc_map(participants_buckets, b, 1)
|
||||
cd = meta.get("countdown")
|
||||
if isinstance(cd, str) and cd.strip():
|
||||
sec = self._parse_countdown_seconds(cd)
|
||||
if isinstance(sec, int):
|
||||
b = self._bucket(float(sec), [float(e) for e in countdown_edges])
|
||||
self._inc_map(countdown_buckets, b, 1)
|
||||
|
||||
def _top_k(m: dict, k: int = 10) -> list[dict]:
|
||||
items = [{"key": kk, "count": int(vv)} for kk, vv in m.items()]
|
||||
@@ -679,7 +738,11 @@ class ProcRunner:
|
||||
cfg = {}
|
||||
|
||||
def _pick(key: str, default):
|
||||
if isinstance(params, dict) and key in params and params.get(key) is not None:
|
||||
if (
|
||||
isinstance(params, dict)
|
||||
and key in params
|
||||
and params.get(key) is not None
|
||||
):
|
||||
return params.get(key)
|
||||
if isinstance(cfg, dict) and key in cfg and cfg.get(key) is not None:
|
||||
return cfg.get(key)
|
||||
@@ -690,11 +753,12 @@ class ProcRunner:
|
||||
needswitch = bool(_pick("needswitch", False))
|
||||
reset_after_swipes_enabled = bool(_pick("reset_after_swipes_enabled", False))
|
||||
wait_minutes = int(_pick("wait_minutes", 5) or 5)
|
||||
|
||||
|
||||
# 启动时自动截图
|
||||
if device_id:
|
||||
try:
|
||||
from Underlying_Operations import underlying_operations
|
||||
|
||||
ops = underlying_operations()
|
||||
self._append_log(f"[启动] 自动截图: device={device_id}")
|
||||
result = ops.get_screenshot(device_id)
|
||||
@@ -709,7 +773,9 @@ class ProcRunner:
|
||||
min_prize_value_yuan = float(_pick("min_prize_value_yuan", 0) or 0)
|
||||
min_participants = int(_pick("min_participants", 0) or 0)
|
||||
max_participants = int(_pick("max_participants", 0) or 0)
|
||||
skip_if_countdown_lt_seconds = int(_pick("skip_if_countdown_lt_seconds", 15) or 15)
|
||||
skip_if_countdown_lt_seconds = int(
|
||||
_pick("skip_if_countdown_lt_seconds", 15) or 15
|
||||
)
|
||||
try:
|
||||
reset_after_swipes = int(_pick("reset_after_swipes", 10))
|
||||
except Exception:
|
||||
@@ -717,7 +783,9 @@ class ProcRunner:
|
||||
if reset_after_swipes < 1:
|
||||
reset_after_swipes = 1
|
||||
auto_join_fansclub = bool(_pick("auto_join_fansclub", False))
|
||||
fansclub_fail_action = str(_pick("fansclub_fail_action", "") or "").strip().lower()
|
||||
fansclub_fail_action = (
|
||||
str(_pick("fansclub_fail_action", "") or "").strip().lower()
|
||||
)
|
||||
|
||||
cmd = [
|
||||
sys.executable,
|
||||
@@ -750,8 +818,12 @@ class ProcRunner:
|
||||
cmd += ["--fansclub-fail-action", fansclub_fail_action]
|
||||
|
||||
# 高价值直播间回访运行时开关(由 GUI 在启动时覆盖)
|
||||
high_value_room_revisit_enabled = bool(_pick("high_value_room_revisit_enabled", True))
|
||||
high_value_room_revisit_only_current_run = bool(_pick("high_value_room_revisit_only_current_run", False))
|
||||
high_value_room_revisit_enabled = bool(
|
||||
_pick("high_value_room_revisit_enabled", True)
|
||||
)
|
||||
high_value_room_revisit_only_current_run = bool(
|
||||
_pick("high_value_room_revisit_only_current_run", False)
|
||||
)
|
||||
if high_value_room_revisit_enabled:
|
||||
cmd.append("--high-value-room-revisit-enabled")
|
||||
else:
|
||||
@@ -760,7 +832,9 @@ class ProcRunner:
|
||||
cmd.append("--high-value-room-revisit-only-current-run")
|
||||
|
||||
# 预约回退校验开关(由 Run 面板控制)
|
||||
reservation_back_verify_enabled = bool(_pick("reservation_back_verify_enabled", True))
|
||||
reservation_back_verify_enabled = bool(
|
||||
_pick("reservation_back_verify_enabled", True)
|
||||
)
|
||||
if reservation_back_verify_enabled:
|
||||
cmd.append("--reservation-back-verify-enabled")
|
||||
else:
|
||||
@@ -863,7 +937,7 @@ class ProcRunner:
|
||||
# 使用迭代器读取,Python会自动处理缓冲
|
||||
# 配合PYTHONUNBUFFERED=1和line_buffering=True,应该能实时获取输出
|
||||
# iter(out.readline, '') 会在readline返回空字符串(EOF)时自动停止
|
||||
for line in iter(out.readline, ''):
|
||||
for line in iter(out.readline, ""):
|
||||
try:
|
||||
cleaned_line = line.rstrip("\n\r")
|
||||
if cleaned_line: # 忽略空行
|
||||
@@ -962,7 +1036,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return self._send_json(cfg)
|
||||
if u.path == "/api/stats":
|
||||
qs = parse_qs(u.query)
|
||||
detail = str((qs.get("detail") or [""])[0] or "").strip().lower() in ("1", "true", "yes")
|
||||
detail = str((qs.get("detail") or [""])[0] or "").strip().lower() in (
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
)
|
||||
return self._send_json(RUNNER.get_stats(include_events=detail))
|
||||
if api_path in ("/api/reservations", "/api/reservation"):
|
||||
# 返回当前预约队列信息
|
||||
@@ -983,12 +1061,23 @@ class Handler(BaseHTTPRequestHandler):
|
||||
since = 0
|
||||
try:
|
||||
next_idx, lines = RUNNER.get_logs_since(since)
|
||||
return self._send_json({"next": next_idx, "lines": lines, "running": RUNNER.is_running()})
|
||||
return self._send_json(
|
||||
{
|
||||
"next": next_idx,
|
||||
"lines": lines,
|
||||
"running": RUNNER.is_running(),
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
# 记录错误但不中断请求,返回空日志
|
||||
import traceback
|
||||
print(f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}")
|
||||
return self._send_json({"next": 0, "lines": [], "running": RUNNER.is_running()})
|
||||
|
||||
print(
|
||||
f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}"
|
||||
)
|
||||
return self._send_json(
|
||||
{"next": 0, "lines": [], "running": RUNNER.is_running()}
|
||||
)
|
||||
if u.path == "/api/logfile-tail":
|
||||
# 返回统一日志文件的尾部若干行,便于在内存日志不同步时调试
|
||||
qs = parse_qs(u.query)
|
||||
@@ -996,7 +1085,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
n = int((qs.get("lines") or [100])[0])
|
||||
except Exception:
|
||||
n = 100
|
||||
path = RUNNER._log_file_path if hasattr(RUNNER, "_log_file_path") else os.path.join(BASE_DIR, "logs", "unified.log")
|
||||
path = (
|
||||
RUNNER._log_file_path
|
||||
if hasattr(RUNNER, "_log_file_path")
|
||||
else os.path.join(BASE_DIR, "logs", "unified.log")
|
||||
)
|
||||
out_lines = []
|
||||
try:
|
||||
if os.path.exists(path):
|
||||
@@ -1050,7 +1143,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.send_error(HTTPStatus.NOT_FOUND)
|
||||
return
|
||||
ext = os.path.splitext(full)[1].lower()
|
||||
ctype = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg"}.get(ext, "application/octet-stream")
|
||||
ctype = {
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
}.get(ext, "application/octet-stream")
|
||||
with open(full, "rb") as f:
|
||||
data = f.read()
|
||||
self.send_response(HTTPStatus.OK)
|
||||
@@ -1068,7 +1165,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if u.path == "/api/config":
|
||||
body = self._read_json()
|
||||
cfg = read_config()
|
||||
update = body.get("config") if isinstance(body.get("config"), dict) else body
|
||||
update = (
|
||||
body.get("config") if isinstance(body.get("config"), dict) else body
|
||||
)
|
||||
|
||||
int_keys = {
|
||||
"min_participants",
|
||||
@@ -1152,7 +1251,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if isinstance(v, list):
|
||||
cfg[k] = [str(x) for x in v if str(x).strip()]
|
||||
else:
|
||||
cfg[k] = [str(x).strip() for x in str(v).splitlines() if str(x).strip()]
|
||||
cfg[k] = [
|
||||
str(x).strip()
|
||||
for x in str(v).splitlines()
|
||||
if str(x).strip()
|
||||
]
|
||||
else:
|
||||
cfg[k] = v
|
||||
|
||||
@@ -1196,19 +1299,22 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if u.path == "/api/stop":
|
||||
RUNNER.stop()
|
||||
return self._send_json({"ok": True})
|
||||
|
||||
|
||||
if u.path == "/api/screenshot":
|
||||
# 手动截图接口
|
||||
body = self._read_json()
|
||||
device_id = str(body.get("device_id") or "").strip()
|
||||
try:
|
||||
from Underlying_Operations import underlying_operations
|
||||
|
||||
ops = underlying_operations()
|
||||
result = ops.get_screenshot(device_id)
|
||||
if result:
|
||||
return self._send_json({"ok": True, "message": "截图成功"})
|
||||
else:
|
||||
return self._send_json({"ok": False, "error": "截图失败"}, status=500)
|
||||
return self._send_json(
|
||||
{"ok": False, "error": "截图失败"}, status=500
|
||||
)
|
||||
except Exception as e:
|
||||
return self._send_json({"ok": False, "error": str(e)}, status=500)
|
||||
|
||||
@@ -1233,7 +1339,9 @@ def main() -> int:
|
||||
httpd = ThreadingHTTPServer((host, port), Handler)
|
||||
except OSError as e:
|
||||
print(f"[WEBGUI] 端口 {port} 启动失败:{e}")
|
||||
print("[WEBGUI] 处理建议:1) 关闭占用该端口的进程 2) 改为其他端口,例如前置设置 PORT=8001")
|
||||
print(
|
||||
"[WEBGUI] 处理建议:1) 关闭占用该端口的进程 2) 改为其他端口,例如前置设置 PORT=8001"
|
||||
)
|
||||
raise
|
||||
print(f"Web GUI: http://{host}:{port}")
|
||||
print("- 可在页面里设置养号时长/间隔并保存到 config.json")
|
||||
|
||||
+80
-91
@@ -30,119 +30,109 @@ class WebGUILauncher:
|
||||
self.root.title("抖音挂机 Web GUI 启动器")
|
||||
self.root.geometry("700x550")
|
||||
self.root.resizable(True, True)
|
||||
|
||||
|
||||
# 服务进程
|
||||
self.webgui_process = None
|
||||
self.monitor_thread = None
|
||||
self.is_running = False
|
||||
self.port = DEFAULT_PORT
|
||||
|
||||
|
||||
# 创建UI
|
||||
self.create_ui()
|
||||
|
||||
|
||||
# 检查初始状态
|
||||
self.check_service_status()
|
||||
|
||||
|
||||
# 定期检查服务状态
|
||||
self.schedule_status_check()
|
||||
|
||||
|
||||
def create_ui(self):
|
||||
"""创建用户界面"""
|
||||
# 主框架
|
||||
main_frame = ttk.Frame(self.root, padding="10")
|
||||
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
|
||||
|
||||
main_frame.grid(row=0, column=0, sticky="nsew") # type: ignore[arg-type]
|
||||
|
||||
# 配置网格权重
|
||||
self.root.columnconfigure(0, weight=1)
|
||||
self.root.rowconfigure(0, weight=1)
|
||||
main_frame.columnconfigure(1, weight=1)
|
||||
main_frame.rowconfigure(2, weight=1)
|
||||
|
||||
|
||||
# 标题
|
||||
title_label = ttk.Label(
|
||||
main_frame,
|
||||
text="抖音挂机 Web GUI 启动器",
|
||||
font=("Arial", 16, "bold")
|
||||
main_frame, text="抖音挂机 Web GUI 启动器", font=("Arial", 16, "bold")
|
||||
)
|
||||
title_label.grid(row=0, column=0, columnspan=3, pady=(0, 20))
|
||||
|
||||
|
||||
# 状态区域
|
||||
status_frame = ttk.LabelFrame(main_frame, text="服务状态", padding="10")
|
||||
status_frame.grid(row=1, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
|
||||
status_frame.grid(row=1, column=0, columnspan=3, sticky="ew", pady=(0, 10)) # type: ignore[arg-type]
|
||||
status_frame.columnconfigure(1, weight=1)
|
||||
|
||||
self.status_label = ttk.Label(status_frame, text="检查中...", font=("Arial", 10))
|
||||
|
||||
self.status_label = ttk.Label(
|
||||
status_frame, text="检查中...", font=("Arial", 10)
|
||||
)
|
||||
self.status_label.grid(row=0, column=0, columnspan=2, sticky=tk.W)
|
||||
|
||||
|
||||
self.port_label = ttk.Label(status_frame, text=f"端口: {self.port}")
|
||||
self.port_label.grid(row=1, column=0, sticky=tk.W, pady=(5, 0))
|
||||
|
||||
|
||||
# 按钮区域
|
||||
button_frame = ttk.Frame(main_frame)
|
||||
button_frame.grid(row=2, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
|
||||
|
||||
button_frame.grid(row=2, column=0, columnspan=3, sticky="ew", pady=(0, 10)) # type: ignore[arg-type]
|
||||
|
||||
self.start_button = ttk.Button(
|
||||
button_frame,
|
||||
text="启动服务",
|
||||
command=self.start_service,
|
||||
width=15
|
||||
button_frame, text="启动服务", command=self.start_service, width=15
|
||||
)
|
||||
self.start_button.pack(side=tk.LEFT, padx=(0, 5))
|
||||
|
||||
|
||||
self.stop_button = ttk.Button(
|
||||
button_frame,
|
||||
text="停止服务",
|
||||
command=self.stop_service,
|
||||
width=15,
|
||||
state=tk.DISABLED
|
||||
state=tk.DISABLED,
|
||||
)
|
||||
self.stop_button.pack(side=tk.LEFT, padx=(0, 5))
|
||||
|
||||
|
||||
self.open_browser_button = ttk.Button(
|
||||
button_frame,
|
||||
text="打开浏览器",
|
||||
command=self.open_browser,
|
||||
width=15,
|
||||
state=tk.DISABLED
|
||||
state=tk.DISABLED,
|
||||
)
|
||||
self.open_browser_button.pack(side=tk.LEFT, padx=(0, 5))
|
||||
|
||||
|
||||
self.refresh_button = ttk.Button(
|
||||
button_frame,
|
||||
text="刷新状态",
|
||||
command=self.check_service_status,
|
||||
width=15
|
||||
button_frame, text="刷新状态", command=self.check_service_status, width=15
|
||||
)
|
||||
self.refresh_button.pack(side=tk.LEFT)
|
||||
|
||||
|
||||
# 日志区域
|
||||
log_frame = ttk.LabelFrame(main_frame, text="启动日志", padding="10")
|
||||
log_frame.grid(row=3, column=0, columnspan=3, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
|
||||
log_frame.grid(row=3, column=0, columnspan=3, sticky="nsew", pady=(0, 10)) # type: ignore[arg-type]
|
||||
log_frame.columnconfigure(0, weight=1)
|
||||
log_frame.rowconfigure(0, weight=1)
|
||||
main_frame.rowconfigure(3, weight=1)
|
||||
|
||||
|
||||
self.log_text = scrolledtext.ScrolledText(
|
||||
log_frame,
|
||||
height=15,
|
||||
width=80,
|
||||
wrap=tk.WORD,
|
||||
font=("Consolas", 9)
|
||||
log_frame, height=15, width=80, wrap=tk.WORD, font=("Consolas", 9)
|
||||
)
|
||||
self.log_text.pack(fill=tk.BOTH, expand=True)
|
||||
|
||||
|
||||
# 底部信息
|
||||
info_frame = ttk.Frame(main_frame)
|
||||
info_frame.grid(row=4, column=0, columnspan=3, sticky=(tk.W, tk.E))
|
||||
|
||||
info_frame.grid(row=4, column=0, columnspan=3, sticky="ew") # type: ignore[arg-type]
|
||||
|
||||
info_label = ttk.Label(
|
||||
info_frame,
|
||||
text="提示: 服务启动后会自动打开浏览器,也可以手动点击'打开浏览器'按钮",
|
||||
font=("Arial", 9),
|
||||
foreground="gray"
|
||||
foreground="gray",
|
||||
)
|
||||
info_label.pack()
|
||||
|
||||
|
||||
def log(self, message):
|
||||
"""添加日志"""
|
||||
timestamp = time.strftime("%H:%M:%S")
|
||||
@@ -150,16 +140,17 @@ class WebGUILauncher:
|
||||
self.log_text.insert(tk.END, log_message)
|
||||
self.log_text.see(tk.END)
|
||||
print(log_message.strip()) # 同时输出到控制台
|
||||
|
||||
|
||||
def check_service_status(self):
|
||||
"""检查服务状态"""
|
||||
try:
|
||||
import socket
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(1)
|
||||
result = sock.connect_ex(('127.0.0.1', self.port))
|
||||
result = sock.connect_ex(("127.0.0.1", self.port))
|
||||
sock.close()
|
||||
|
||||
|
||||
if result == 0:
|
||||
# 端口已监听,服务运行中
|
||||
self.is_running = True
|
||||
@@ -178,31 +169,31 @@ class WebGUILauncher:
|
||||
self.log(f"检查服务状态时出错: {e}")
|
||||
self.is_running = False
|
||||
self.status_label.config(text="? 状态未知", foreground="orange")
|
||||
|
||||
|
||||
def start_service(self):
|
||||
"""启动服务"""
|
||||
if self.is_running:
|
||||
messagebox.showwarning("警告", "服务已经在运行中")
|
||||
return
|
||||
|
||||
|
||||
# 检查文件是否存在
|
||||
if not WEB_GUI_PY.exists():
|
||||
messagebox.showerror("错误", f"未找到 web_gui.py 文件\n路径: {WEB_GUI_PY}")
|
||||
return
|
||||
|
||||
|
||||
self.log("=" * 50)
|
||||
self.log("开始启动 Web GUI 服务...")
|
||||
|
||||
|
||||
# 停止旧进程
|
||||
self.stop_old_processes()
|
||||
|
||||
|
||||
# 设置环境变量
|
||||
env = os.environ.copy()
|
||||
env['PYTHONIOENCODING'] = 'utf-8'
|
||||
env['PYTHONUNBUFFERED'] = '1'
|
||||
if 'PORT' not in env and 'WEB_GUI_PORT' not in env:
|
||||
env['PORT'] = str(self.port)
|
||||
|
||||
env["PYTHONIOENCODING"] = "utf-8"
|
||||
env["PYTHONUNBUFFERED"] = "1"
|
||||
if "PORT" not in env and "WEB_GUI_PORT" not in env:
|
||||
env["PORT"] = str(self.port)
|
||||
|
||||
try:
|
||||
# 检查是否有虚拟环境
|
||||
venv_python = BASE_DIR / ".venv" / "Scripts" / "python.exe"
|
||||
@@ -212,13 +203,13 @@ class WebGUILauncher:
|
||||
else:
|
||||
python_exe = sys.executable
|
||||
self.log("使用系统Python启动...")
|
||||
|
||||
|
||||
# 启动进程(在Windows上显示控制台窗口以便查看日志)
|
||||
creation_flags = 0
|
||||
if sys.platform == 'win32':
|
||||
if sys.platform == "win32":
|
||||
# 使用普通窗口,不隐藏,这样可以看到日志
|
||||
creation_flags = 0
|
||||
|
||||
|
||||
self.webgui_process = subprocess.Popen(
|
||||
[python_exe, str(WEB_GUI_PY)],
|
||||
cwd=str(BASE_DIR),
|
||||
@@ -227,37 +218,36 @@ class WebGUILauncher:
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
creationflags=creation_flags
|
||||
creationflags=creation_flags,
|
||||
)
|
||||
|
||||
|
||||
self.log(f"服务进程已启动 (PID: {self.webgui_process.pid})")
|
||||
|
||||
|
||||
# 启动监控线程
|
||||
self.monitor_thread = threading.Thread(
|
||||
target=self.monitor_process,
|
||||
daemon=True
|
||||
target=self.monitor_process, daemon=True
|
||||
)
|
||||
self.monitor_thread.start()
|
||||
|
||||
|
||||
# 等待服务启动
|
||||
self.wait_for_service()
|
||||
|
||||
|
||||
except Exception as e:
|
||||
self.log(f"启动服务失败: {e}")
|
||||
messagebox.showerror("错误", f"启动服务失败:\n{e}")
|
||||
self.webgui_process = None
|
||||
|
||||
|
||||
def stop_service(self):
|
||||
"""停止服务"""
|
||||
if not self.is_running and not self.webgui_process:
|
||||
messagebox.showinfo("提示", "服务未运行")
|
||||
return
|
||||
|
||||
|
||||
self.log("正在停止服务...")
|
||||
|
||||
|
||||
# 停止进程
|
||||
self.stop_old_processes()
|
||||
|
||||
|
||||
if self.webgui_process:
|
||||
try:
|
||||
self.webgui_process.terminate()
|
||||
@@ -270,14 +260,14 @@ class WebGUILauncher:
|
||||
self.log(f"停止服务时出错: {e}")
|
||||
finally:
|
||||
self.webgui_process = None
|
||||
|
||||
|
||||
time.sleep(1)
|
||||
self.check_service_status()
|
||||
|
||||
|
||||
def stop_old_processes(self):
|
||||
"""停止旧的web_gui.py进程"""
|
||||
try:
|
||||
if sys.platform == 'win32':
|
||||
if sys.platform == "win32":
|
||||
# 使用PowerShell命令停止旧进程
|
||||
ps_cmd = (
|
||||
"Get-CimInstance Win32_Process | "
|
||||
@@ -285,27 +275,27 @@ class WebGUILauncher:
|
||||
"ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"
|
||||
)
|
||||
subprocess.run(
|
||||
['powershell', '-NoProfile', '-Command', ps_cmd],
|
||||
["powershell", "-NoProfile", "-Command", ps_cmd],
|
||||
capture_output=True,
|
||||
timeout=5
|
||||
timeout=5,
|
||||
)
|
||||
else:
|
||||
# Linux/Mac
|
||||
subprocess.run(
|
||||
['pkill', '-f', 'web_gui.py'],
|
||||
capture_output=True,
|
||||
timeout=5
|
||||
["pkill", "-f", "web_gui.py"], capture_output=True, timeout=5
|
||||
)
|
||||
except Exception as e:
|
||||
self.log(f"停止旧进程时出错: {e}")
|
||||
|
||||
|
||||
def monitor_process(self):
|
||||
"""监控进程输出"""
|
||||
if not self.webgui_process:
|
||||
return
|
||||
|
||||
|
||||
try:
|
||||
for line in iter(self.webgui_process.stdout.readline, ''):
|
||||
if self.webgui_process.stdout is None:
|
||||
return
|
||||
for line in iter(self.webgui_process.stdout.readline, ""):
|
||||
if not line:
|
||||
break
|
||||
line = line.strip()
|
||||
@@ -313,7 +303,7 @@ class WebGUILauncher:
|
||||
self.root.after(0, self.log, line)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def wait_for_service(self):
|
||||
"""等待服务启动"""
|
||||
self.log("等待服务启动...")
|
||||
@@ -326,10 +316,10 @@ class WebGUILauncher:
|
||||
self.open_browser()
|
||||
return
|
||||
self.root.update()
|
||||
|
||||
|
||||
self.log("服务启动超时,请检查日志")
|
||||
messagebox.showwarning("警告", "服务启动超时,请检查日志窗口")
|
||||
|
||||
|
||||
def open_browser(self):
|
||||
"""打开浏览器"""
|
||||
url = f"http://127.0.0.1:{self.port}"
|
||||
@@ -339,7 +329,7 @@ class WebGUILauncher:
|
||||
except Exception as e:
|
||||
self.log(f"打开浏览器失败: {e}")
|
||||
messagebox.showerror("错误", f"打开浏览器失败:\n{e}")
|
||||
|
||||
|
||||
def schedule_status_check(self):
|
||||
"""定期检查服务状态"""
|
||||
self.check_service_status()
|
||||
@@ -351,16 +341,16 @@ def main():
|
||||
"""主函数"""
|
||||
root = tk.Tk()
|
||||
app = WebGUILauncher(root)
|
||||
|
||||
|
||||
# 处理窗口关闭事件
|
||||
def on_closing():
|
||||
if app.is_running:
|
||||
if messagebox.askyesno("确认", "服务正在运行,是否要停止服务?"):
|
||||
app.stop_service()
|
||||
root.destroy()
|
||||
|
||||
|
||||
root.protocol("WM_DELETE_WINDOW", on_closing)
|
||||
|
||||
|
||||
try:
|
||||
root.mainloop()
|
||||
except KeyboardInterrupt:
|
||||
@@ -369,4 +359,3 @@ def main():
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in new issue
Block a user