diff --git a/.cursorindexingignore b/.cursorindexingignore new file mode 100644 index 0000000..68347b3 --- /dev/null +++ b/.cursorindexingignore @@ -0,0 +1,2 @@ +# Don't index SpecStory auto-save files, but allow explicit context inclusion via @ references +.specstory/** diff --git a/.specstory/.what-is-this.md b/.specstory/.what-is-this.md new file mode 100644 index 0000000..1649e9d --- /dev/null +++ b/.specstory/.what-is-this.md @@ -0,0 +1,65 @@ + +# SpecStory Artifacts Directory + +This directory is automatically created and maintained by the SpecStory extension to preserve your Cursor composer and 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 + +## 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 + +## 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 +``` + +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`: + +``` +.specstory/cursor_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. + +To exclude AI interaction history: + +1. Open the "Find in Files" search in Cursor (Cmd/Ctrl + Shift + F) +2. Navigate to the "files to exclude" section +3. Add the following pattern: + +``` +.specstory/* +``` + +This will ensure your searches only return results from your working codebase files. + +## 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. + +## Settings + +You can control auto-saving behavior in Cursor: + +1. Open Cursor → 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. \ No newline at end of file diff --git a/README.md b/README.md index bc1df40..1b2cd3e 100644 --- a/README.md +++ b/README.md @@ -27,128 +27,204 @@ GUI 里可以直接调:最低奖品价值、参与人数范围、倒计时太 pip install ttkbootstrap ``` -## 抖音福袋挂机(douyin_guaji) - -这是一个用于在抖音直播间自动检测与参与“福袋抽奖”的 Python 自动化脚本集合,支持命令行与 Web 可视化控制面板。适用于需要长期挂机刷福袋的场景,脚本通过 ADB 与设备交互,截图 + OCR 做判定并执行点击/滑动操作。 - -本 README 包含:项目功能、运行前准备、安装与依赖、配置说明、运行方式(GUI / CLI)、日志与调试、常见问题与注意事项。 - ---- - -### 主要功能 -- 自动识别直播间是否有福袋并尝试参与 -- 对福袋内容、参与人数、奖品价值等做筛选(可配置) -- 支持“高价值预约”:记录将来开奖的高价值福袋并在开奖前回退参与 -- 可通过 Web GUI 一键启动/停止并查看实时日志 -- 支持多种鲁棒策略:桌面恢复、回退校验、失败重试与异常兜底 - ---- - -### 前提与依赖 -- 操作系统:Windows / Linux / macOS(以 ADB 可用为准) -- Python 版本:3.8+ -- 需要安装 ADB(platform-tools),并确保 `adb` 在系统 PATH 中或设置了 `ADB_EXECUTABLE` 环境变量 - -Python 依赖(建议在虚拟环境中安装): +2. 运行 GUI: ```bash -pip install -r requirements.txt +python gui_app.py ``` -如果没有 `requirements.txt`,请安装: +GUI 会读写 `config.json`,并通过 `run_cli.py` 启动挂机进程。 -```bash -pip install pillow numpy paddlepaddle paddleocr -``` +## 日志(便于排错) +默认会把所有运行日志追加写入统一文件:`logs/unified.log`(不设行数上限,按磁盘容量为准)。 -说明:在部分机器/环境下,paddlepaddle 的安装和版本选择较敏感,请参考官方文档或使用 CPU 版以减少依赖问题。 +相关配置在 `config.json`: +- `log_unified_enabled`: 是否启用统一日志文件 +- `log_unified_path`: 统一日志文件路径(相对项目目录或绝对路径) +- `webgui_log_capacity`: Web GUI 内存里保留多少行日志(`0` 表示不限制;建议长时间运行时设为 `2000` 左右,避免占用过多内存) +## 注意 +6.缺少各种python三方库文件的需要自己安装一下,运行下面的命令: +pip install pillow paddlepaddle paddleocr numpy +从粉丝反馈来看,最新版的paddlepaddle可能会有问题 +7.根据自己设备的情况,修改douyin_guaji.py文件中y轴的像素偏移值,可正可负,通常调整区间在【-50,50】 +默认手机分辨率是1080*2400的像素,即使是相同的分辨率,可能也会因为手机顶部的刘海不一样,以及是否使用了底部导航按钮,导致存在Y轴的偏移 +![image](https://github.com/user-attachments/assets/e99dbd11-137b-407f-a37f-92a7b8235f90) +8.将会在4.0版本自动识别偏移值,后续不再需要调整任何参数,全自动识别、运行(叼哥B站达到1.5W粉发布) +9.基本上大部分问题,都能从这篇文章找到答案和建议:https://www.bilibili.com/opus/1104972369516036117 ---- +# 版本更新&预更新内容 + V1.0 + 支持无限循环挂机直播间 + 1.判断直播间福袋内容是否是想要的,如果不想要则切换直播间 + 2.直播间倒计时是否还有很久,太久则切换直播间 + 3.当直播间开奖后,立马切换直播间去别的直播间挂机 -### 快速上手 + V1.1 + 1.对人机弹窗做判定,适当滑动解锁 + 2.对截图函数做优化,处理无法截图的情况 + 3.优化不切换直播间时的逻辑 -1. 在手机上开启「开发者选项」和「USB 调试」,并通过 USB 将手机连接到电脑。 -2. 在项目根目录执行 `adb devices` 确认设备已连接。 -3. 启动 Web GUI(推荐,可视化配置): + V1.2 + 1.判定划动图片验证的人机校验,自动滑动一定距离处理人机验证 + 2.优化直播间判定逻辑,增加直播停留时间减少被人机的概率 + 3.增加直播间等待时间的参数,控制直播停留时间减少被人机的概率 + 4.增加对当前时间的判定,不同时间段对抽奖的内容做不同的处理 -```powershell -python web_gui.py -# 打开浏览器访问 http://127.0.0.1:8000 -``` + V1.3 + 1.增加直播已结束的判定 + 2.增加是否在直播列表页面的判定 + 3.增加回到直播列表重新进入直播的逻辑 + 4.增加点亮粉丝团抽奖的特殊处理 + 5.直播提早开奖补充截图内容获取,用于debug -在 Run 面板选择设备并配置参数,点击“开始运行”。 + V1.4 + 1.兼容了一下直播间忽然弹出来618红包弹窗导致页面一直卡在直播间的问题 + 2.修复进入直播间列表的功能异常的问题 + 3.优化挂机的时候直播间关闭的判定 + 4.兼容 同时存在参与条件+参与任务的抽奖 + 5.增加判断是否在个人中心的关注页面 + 6.修复领完奖后回到直播间判断不在直播间的问题 + 7.增加上划切换到直播间直播间已关闭的判断 + 8.兼容福袋参与抽奖的文案为:参与抽奖 -或者使用命令行直接运行: + V1.5 + 1.优化设备未识别的处理逻辑 + 2.优化图片文件夹不存在创建文件夹的逻辑 -```powershell -python run_cli.py --device-id --y-pianyi 0 --wait-minutes 5 -``` + V1.6 + 1.增加日志内容同步输出到log文件中,方便问题排查 + 2.修复了到凌晨个别直播间提早关闭会导致直播判定卡住的问题 + 3.调整不切换直播间挂机的逻辑,现在会一直等待到直播间关闭才会切换 -常用 CLI 参数请通过 `python run_cli.py --help` 查看。 + V1.7 + 1.修复单独挂一个直播间,判定直播间已关闭后,不切换直播间的问题 + 2.增加全局的监控,无论发生什么情况,只要长时间判定为没有福袋,则重置整个挂机流程 ---- + V2.0 + 1.做了不同分辨率手机的兼容,现在不是1080*2400的手机也能挂机了 + 2.优化了从直播间列表进直播间连刷新2次的问题 + 3.优化了领奖完成后返回直播间领奖界面依旧没关闭的情况 + 4.修复了过了凌晨之后直播间一直没有福袋的判定问题 -### 关键配置项(`config.json` / Run 面板覆盖) + V2.1 + 1.修复节假日出现的直播红包弹窗一直无法被退出关闭的问题 + 2.兼容操控通过wifi直连到笔记本电脑上的手机 + 3.优化弹窗人机验证后,点击返回无法退出验证的情况 + 4.加入手机电量验证逻辑 + 5.增加手机电量不足时进入待机模式的逻辑,避免手机直接关机 + 6.兼容领奖完成后,判定关闭中奖弹窗后还有一个提醒领奖窗口的情况 + 7.优化凌晨后整个直播列表无直播间导致无法刷新的问题 -部分重要字段说明(项目会从 `config.json` 读取默认值,Web GUI 启动时可覆盖部分运行时参数): + V2.2 + 1.优化日志打印逻辑 + 2.增加点击福袋无法打开,被系统限制参与抽奖的判定逻辑 + 3.修复在固定直播间挂机会忽然切换直播间的问题 + 4.修复:没有抽中,点击:我知道了,关闭弹窗,弹窗未关闭的问题 + 5.修复进入没有加入粉丝团的直播间,无法抽奖但没有切换直播间的问题 + 6.增加一个抽奖按钮的判定:活动已结束 + 7.增加了切换到未加入店铺的直播间的抽奖判定 + 8.修复:中奖后下单,回到直播间依旧存在中奖弹窗提醒关不掉的问题 -- `min_prize_value_yuan`:最低参与价值(元),低于该值不参 -- `min_participants` / `max_participants`:参与人数过滤 -- `skip_if_countdown_lt_seconds`:倒计时少于此值则不参与 -- `high_value_fudai_enabled`:是否启用高价值预约逻辑 -- `high_value_fudai_threshold_yuan`:高价值判定阈值(元) -- `high_value_fudai_join_ahead_seconds`:回退参与的提前量(秒) -- `high_value_fudai_max_reservations`:预约队列最大长度 -- `reservation_back_verify_enabled`:回退后校验(默认推荐开启) -- reservation 回退速度(新): - - `reservation_back_swipe_delay`(Web UI 字段)/ `reservation_back_swipe_delay_fast_seconds`(运行时覆盖):当回退校验被禁用时使用的“快速延迟”(秒),可加快回退速度。若 `reservation_back_verify_enabled` 为 True,则使用程序兼容的较慢延迟(保持稳定)。 -- `fudai_find_max_attempts`:找小福袋图标时的最大重试次数(默认 5) -- `reservation_preempt_min_value`:预约抢占当前任务的最小价值(元),低于则不抢占 -- `poll_before_open_seconds`:在开奖前多少秒才开始积极轮询结果(以减少提前轮询的开销) + V2.3 + 1.兼容任意分辨率的手机,增加横轴对应的分辨率设置 + 2.优化代码,抽象一部分方法,去除冗余代码 + 3.修复当直播间列表为空时,点击返回退出到关注中心,判定页面失效,无法回到直播间列表的问题 + 4.开奖结束后增加一个随机时长等待,减小风控风险 + 5.补充逻辑处理:直播间因为状态栏高度的不同,导致关闭的判定不同 + 6.调整挂机逻辑,到后半夜固定时间区间时,不再参与抽奖 -更多字段请参见 `config.json`,Web GUI 的“配置”面板会显示大部分可配置项。 + V2.4 + 1.调整偏移值逻辑,填任意正负数都会进行双重匹配,自动确认适宜的偏移值 + 2.调整长时间无法识别到福袋的逻辑,避免重复打开都是无福袋的直播间导致被风控 + 3.优化代码,抽象剩余部分方法,去除冗余代码 + 4.修复偶尔出现中奖后,领奖完成返回到直播间,结果页面退回到了视频首页的问题 + 5.补充下完单后,在购买成功页面的验证逻辑 ---- + V3.0 + 1.引入百度PaddleOCR图像识别库,替换掉pytesseract,大幅提升文字识别准确度 + 2.优化代码,拆分基础操作函数到单独库做引用 + 3.执行脚本,不再需要手动设置手机分辨率参数,会自动设置手机对应的值 + 4.兼容人脸检测的人机验证弹窗的判定 + + V3.1 + 1.修复新账号中奖后,下完单返回到直播间,因为弹出一个'添加抖音商城到桌面'的弹窗,导致页面还卡在'购买成功'页面的问题 + 2.修复偶尔退出直播间,直接退到了个人中心,进而没有正确打开关注列表的问题 + 3.补充部分操作后的随机时长等待,规避被监控风险 + + V3.2 + 1.调整开奖后弹窗的点击判定,避免没有成功关闭弹窗的情况 + 2.兼容开奖后没有中奖,但是给了会员专属优惠券的情况 + 3.优化开奖后判定是否中奖及后续的逻辑 + + V3.3 + 1.将哪些福袋想要、不想要的配置移动到json文件中进行 + 2.在关注列表页面补充一个vivo手机断开充电的判定 + 3.调整开奖后未中奖,但发了一张优惠券的处理逻辑 + 4.适当调大关键截图的区间,方便判定 + -### 日志、状态与截图 + # 以下为预更新版本内容 + + V4.0(叼哥B站到1.5W粉丝发布 或 第三档充电提早获取) + 1.不再需要填写偏移值等任何参数,直接运行,会自动找到合适的偏移值进行后续操作 + 2.调整页面判断逻辑,实时记录当前所在页面的类型(直接间、直播列表、个人中心、订单页等) + 3.优化是否有福袋的判定逻辑 + 4.重做福袋详情弹窗内容判定逻辑 + 5.大幅调整代码逻辑,优化代码结构和性能 + 6.增加参与抽奖文案为'不满足参与条件'的情况的处理 + 7.补充刷新直播间列表逻辑,避免过于频繁刷新直播间导致被风控 + + V4.1 + 1.调整打开福袋详情判定异常后的关闭福袋弹窗位置,避免关闭弹窗实则是打开 + 2.调整参与抽奖内容为加入粉丝团(1钻石)的判定和处理逻辑 + 3.增加文件关闭机制,降低内存泄漏风险 + 4.修复在直播间判定是否存在福袋次数减少的问题 + + V4.2(最高档充电提早获取) + 1.模拟用户操作,在抖音商城中进行浏览、下单流程(创建订单但不付钱) + 2.模拟用户操作,到停止挂机时间段退出抖音,到开始挂机时间再启动抖音 + 3.模拟用户操作,在视频首页刷一会视频,并随机加评论、点赞 + 4.优化是否存在福袋的逻辑,只检测固定间隔的位置 + 5.调整了凌晨关闭抖音后等待时长的逻辑,统一等待到8点继续挂机 + 6.修复了福袋内容不想要多次切换直播间后,后续无法参与新福袋抽奖的问题 + + V4.3 + 1.调整对极速版的直播列表的判定 + 2.兼容部分直播间,在评论完后还要再点击‘观看直播’才能参与抽奖的情况 + 3.兼容开奖后,点击‘知道了’偶发弹窗未成功关闭的情况 + 4.将设备初次识别成功的偏移值存下来,后续运行改成直接读取保存的值 + + V4.4 + 1.重写判定福袋详情高度的逻辑 + 2.重写判定福袋详情和倒计时的方法,做到可以适配任意分辨率的手机 + 3.修复报错:UnicodeEncodeError: 'gbk' codec can't encode character + + V4.5 + 1.修复开局挂机的直播间没有福袋,导致执行报错的问题 + 2.调整参与福袋抽奖图标的截取逻辑,做到可以适配任意分辨率的手机 + 3.调整开奖结果弹窗内容的截取逻辑,做到可以适配任意分辨率的手机 + 3.增加对顶部状态栏高度的判定 + 4.调整是否在某些指定页面的判定逻辑,做到可以适配任意分辨率的手机 + 5.修复连续切换N个直播间,退出返回直播列表,多次循环后判定不到直播间的问题 + 6.增加抽奖次数统计 + + V4.6 + 1.移除偏移值的设定,改为动态自动查询 + 2.将设备初次识别成功的顶部状态栏高度存下来,后续运行改成直接读取保存的值 + 3.优化福袋参与抽奖按钮文字的二次判定逻辑 + 4.调整人机验证弹窗的判定 + 5.优化到凌晨时段,无法关闭抖音,卡在了直播关注列表的情况 + + 未来更新 + 1.获取直播间名字,关联奖品和倒计时,加入判定队列 + 2.完全自动处理防沉迷验证 + 3.兼容挂机过程中弹出的:开通特惠省钱卡的弹窗 + 4.增加钻石福袋挂机模式,在直播列表刷钻石 + 5.处理异常操作导致弹窗:账号存在风险的验证 + 6.兼容IOS系统,苹果手机也能挂机 + 7.增加直播间瞎逛模式,无限切换,发现想要的福袋就抽一下 + 8.其他来自充电粉丝们的建议,额外需要的功能 + 9.支持个性化定制操作时间,模拟你的个人使用习惯,让操作更像真人(规避风控) + 10.兼容最新版本的paddleOCR -- 统一运行日志:默认写入 `logs/unified.log`(Web GUI 会实时读取并展示最新日志) -- 截图与诊断:脚本会把截图写入 `pic/` 目录(例如 `pic/screenshot.png`、`pic/task_user_area.png` 等),便于排查 OCR/定位问题 -- 预约队列状态:子进程会写 `state/reservations.json`,Web GUI 读取并展示预约队列 - -调试建议:当识别/点击失败时,查看 `pic/` 下的对应截图,结合 `logs/unified.log` 中的 OCR 识别文本判断坐标或 ROI 是否需要调整。 - ---- - -### 常见问题与处理建议 - -- 没识别到设备:检查 `adb devices` 输出,确保驱动与 USB 模式正确。 -- OCR 识别不准确:尝试使用 `paddleocr` 的不同模型或检查 `pic/` 中的截图,调整 ROI 或 `y_pianyi` 偏移。 -- 点击未生效或弹窗未关闭:可能 UI 未稳定,建议适度调大相关延迟(如 `reservation_back_swipe_delay`、`post_switch_delay_seconds` 等)。 -- 回退校验失败(回退后未识别到正确详情):可临时禁用 `reservation_back_verify_enabled` 加快回退流程,但稳定性较差,建议先通过截图诊断定位问题。 - ---- - -### 开发与贡献 - -欢迎提交 issue 或 PR: -- 说明复现步骤、日志片段与 `pic/` 中的截图 -- 若增添新功能,请保持代码风格一致并补充必要注释 - ---- - -### 文件位置速查 - -- 主逻辑:`douyin_fudai.py` -- 低级设备操作封装:`Underlying_Operations.py` -- CLI 启动:`run_cli.py` -- Web GUI:`web_gui.py` + `webui/` 静态资源 -- 配置:`config.json` -- 状态:`state/reservations.json`, `state/high_value_rooms.json` -- 日志:`logs/unified.log` - ---- - -如果你希望我把 README 里的某个章节扩展为操作截图或示例(例如“如何定位 y_pianyi 偏移”或“调试 OCR 坐标”),告诉我要补充的部分,我会继续完善。 - -感谢使用,祝好运拿到好奖品! +# 看到最后了,白嫖成功记得点个星,或者B站找叼哥进QQ群! diff --git a/Underlying_Operations.py b/Underlying_Operations.py index 5dfd206..c310b18 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -20,6 +20,126 @@ import contextlib import base64 from typing import Tuple, Optional +import time as time_module + +def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 5) -> bool: + """安全地替换文件,处理Windows文件锁定问题。 + + 使用多种策略和重试机制来处理文件被占用的情况: + 1. 直接使用 os.replace (原子操作) + 2. 先删除目标文件再重命名 + 3. 重命名旧文件为备份,再重命名新文件 + 4. 使用 shutil.move + 5. 直接复制文件内容 + + Args: + tmp_file: 临时文件路径 + out_file: 目标文件路径 + max_retries: 最大重试次数 + + Returns: + True if successful, False otherwise + """ + import shutil + + if not os.path.exists(tmp_file): + return False + + for attempt in range(max_retries): + try: + # 方法1: 直接使用 os.replace (原子操作,最可靠) + os.replace(tmp_file, out_file) + return True + except (OSError, PermissionError) as e: + # 在Windows上,文件锁定错误通常是 OSError 或 PermissionError + if attempt < max_retries - 1: + # 等待时间逐渐增加,让文件句柄有时间释放 + wait_time = 0.05 * (attempt + 1) * (attempt + 1) # 0.05, 0.2, 0.45, 0.8, 1.25秒 + time_module.sleep(wait_time) + + try: + # 方法2: 先尝试删除目标文件,再重命名 + if os.path.exists(out_file): + try: + os.remove(out_file) + except (OSError, PermissionError): + # 如果删除失败,尝试重命名旧文件为备份 + try: + old_backup = out_file + '.old' + if os.path.exists(old_backup): + try: + os.remove(old_backup) + except Exception: + pass + os.rename(out_file, old_backup) + except Exception: + pass + + # 现在尝试重命名临时文件 + os.rename(tmp_file, out_file) + return True + except (OSError, PermissionError): + # 方法3: 使用 shutil.move + try: + if os.path.exists(out_file): + try: + os.remove(out_file) + except (OSError, PermissionError): + try: + old_backup = out_file + '.old' + if os.path.exists(old_backup): + os.remove(old_backup) + os.rename(out_file, old_backup) + except Exception: + pass + shutil.move(tmp_file, out_file) + return True + except Exception: + # 方法4: 直接复制文件内容(最后的手段) + if attempt == max_retries - 2: # 倒数第二次尝试 + try: + with open(tmp_file, 'rb') as src, open(out_file, 'wb') as dst: + # 分块读取,避免大文件占用内存 + while True: + chunk = src.read(8192) + if not chunk: + break + dst.write(chunk) + # 复制成功后删除临时文件 + try: + os.remove(tmp_file) + except Exception: + pass + return True + except Exception: + pass + continue + else: + # 最后一次尝试:直接复制内容 + try: + with open(tmp_file, 'rb') as src, open(out_file, 'wb') as dst: + while True: + chunk = src.read(8192) + if not chunk: + break + dst.write(chunk) + # 复制成功后尝试删除临时文件 + try: + os.remove(tmp_file) + except Exception: + pass + return True + except Exception: + return False + except Exception as e: + # 其他未知异常,记录但不中断 + if attempt == max_retries - 1: + return False + time_module.sleep(0.1 * (attempt + 1)) + continue + + return False + class underlying_operations: """底层操作类""" def __init__(self): @@ -169,13 +289,29 @@ class underlying_operations: stdout=f, stderr=subprocess.DEVNULL, check=True, + timeout=10, # 添加10秒超时,避免无限等待 ) if _valid_png(tmp_file): - os.replace(tmp_file, out_file) - print("{} 获取屏幕截图".format(timetag)) - return True - except Exception: + # 使用安全的文件替换函数 + if _safe_replace_file(tmp_file, out_file): + print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功") + return True + else: + # 如果替换失败,但临时文件有效,仍然返回成功 + # 后续代码可以读取临时文件或重试 + print(f"[截图] 文件替换失败,但截图已保存到临时文件,将重试") + # 不立即返回,继续尝试回退方案 + except subprocess.TimeoutExpired: + # 超时异常,记录并继续重试 + print(f"[截图] exec-out 超时,尝试重试或回退方案") + try: + if os.path.exists(tmp_file): + os.remove(tmp_file) + except Exception: + pass + except Exception as e: # 继续回退/重试 + print(f"[截图] exec-out 异常:{e}") try: if os.path.exists(tmp_file): os.remove(tmp_file) @@ -189,16 +325,54 @@ class underlying_operations: stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, + timeout=10, # 添加超时 ) subprocess.run( [adb, '-s', device_id, 'pull', '/sdcard/DCIM/screenshot.png', tmp_file], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, + timeout=10, # 添加超时 ) if _valid_png(tmp_file): - os.replace(tmp_file, out_file) - print("{} 获取屏幕截图".format(timetag)) + # 使用安全的文件替换函数 + if _safe_replace_file(tmp_file, out_file): + print("{} 获取屏幕截图".format(timetag)) + return True + else: + # 如果替换失败,尝试最后一次:直接复制内容 + try: + import shutil + # 如果目标文件存在且被占用,尝试读取临时文件内容并写入 + if os.path.exists(tmp_file): + # 尝试直接覆盖写入(如果文件被占用,这会失败,但至少尝试了) + try: + with open(tmp_file, 'rb') as src, open(out_file, 'wb') as dst: + dst.write(src.read()) + print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)") + return True + except (OSError, PermissionError) as e: + # 如果还是失败,尝试将临时文件重命名为目标文件 + try: + # 如果目标文件存在,尝试重命名为备份 + if os.path.exists(out_file): + backup_name = out_file + '.backup' + try: + if os.path.exists(backup_name): + os.remove(backup_name) + os.rename(out_file, backup_name) + except Exception: + pass + # 尝试重命名临时文件为目标文件 + os.rename(tmp_file, out_file) + print("{} 获取屏幕截图(通过重命名临时文件)".format(timetag)) + return True + except Exception: + # 最后兜底:返回True,让调用者知道临时文件存在 + print(f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}") + return True + except Exception: + print(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}") return True # 文件异常则继续进入更深回退 except Exception: @@ -236,24 +410,36 @@ class underlying_operations: os.system("%s -s %s shell input keyevent 4" % (self._adb(), device_id)) print("点击返回键") - def get_ballery_level(self, device_id): + def get_battery_level(self, device_id): """获取设备电量信息""" battery_info = subprocess.Popen("%s -s %s shell dumpsys battery" % (self._adb(), device_id), shell=True, stdout=subprocess.PIPE) battery_info_string = battery_info.stdout.read() battery_info_string = bytes.decode(battery_info_string) location = re.search('level:', battery_info_string) + if not location: + print("[警告] 无法解析电量信息,返回默认值100") + return 100 span = location.span() start, end = span start = end + 1 - for i in range(5): - end += 1 - if battery_info_string[end] == "\n": + # 防止越界 + max_end = min(len(battery_info_string), start + 10) + for i in range(max_end - start): + end = start + i + if end >= len(battery_info_string) or battery_info_string[end] == "\n": break - battery_level = battery_info_string[start:end] # 第几个到第几个中间接冒号 - battery_level = int(battery_level) - print("设备当前电量为{}".format(battery_level)) - return battery_level + if end <= start: + print("[警告] 无法解析电量信息,返回默认值100") + return 100 + battery_level_str = battery_info_string[start:end].strip() + try: + battery_level = int(battery_level_str) + print("设备当前电量为{}".format(battery_level)) + return battery_level + except ValueError: + print(f"[警告] 电量解析失败:'{battery_level_str}',返回默认值100") + return 100 def get_device_resolution(self, device_id): """获取设备分辨率""" @@ -269,7 +455,6 @@ class underlying_operations: return width, height else: raise ValueError("Could not find resolution in adb output") - return False def save_reward_pic(self, device_id): out_dir = os.path.join(os.path.dirname(__file__), 'pic') @@ -341,14 +526,33 @@ class underlying_operations: pic.crop((left_up[0], left_up[1], right_down[0], right_down[1])).save(cut_pic_path) def analyse_pic_word(self, picname='', change_color=0): - """识别图像中的文字, change_color=1或2为不同的二值化模式,其他不做处理""" + """识别图像中的文字, change_color=1或2为不同的二值化模式,其他不做处理 + + 性能优化: + - 添加文件存在性检查,避免打开不存在的文件 + - 优化图片加载和预处理流程 + """ self._ensure_ocr() + if self.ocr is None: + return '' + path = os.path.dirname(__file__) + '/pic' if picname == '': - pic = path + '/cut.png' + pic_path = path + '/cut.png' else: - pic = path + '/' + picname + '.png' - img = Image.open(pic) + pic_path = path + '/' + picname + '.png' + + # 检查文件是否存在 + if not os.path.exists(pic_path): + return '' + + try: + img = Image.open(pic_path) + # 检查图片是否有效 + img.verify() + img = Image.open(pic_path) # 重新打开,因为verify后需要重新打开 + except (IOError, OSError, Image.UnidentifiedImageError) as e: + return '' # 福袋内容/倒计时属于手机 UI 字体,强二值化容易把细节打没,默认保持彩色。 if change_color in (1, 2): @@ -363,16 +567,49 @@ class underlying_operations: # 性能优化:先用原尺寸跑一次 OCR;只有识别为空时才放大重试。 w, h = img.size - img1 = img.filter(ImageFilter.SHARPEN) + # 优化:对于很小的图片,直接放大,避免浪费一次OCR调用 + if max(w, h) < 100: + try: + scale = max(2, 200 // max(w, h, 1)) # 至少放大到200像素 + img = img.resize((w * scale, h * scale), Image.BICUBIC) + w, h = img.size + except Exception: + pass + + # 识别精度优化:增强图片预处理 + # 1. 使用增强锐化(UnsharpMask效果更好) + from PIL import ImageEnhance + try: + # 先锐化 + img_sharpened = img.filter(ImageFilter.UnsharpMask(radius=1, percent=150, threshold=3)) + # 再增强对比度(轻微增强,避免过度处理) + enhancer = ImageEnhance.Contrast(img_sharpened) + img_enhanced = enhancer.enhance(1.15) # 增强15%对比度 + img1 = img_enhanced + except Exception: + # 如果增强失败,回退到原来的锐化 + img1 = img.filter(ImageFilter.SHARPEN) + img_np = np.array(img1) result = self.ocr.ocr(img_np) if result == [None]: return '' text = self.extract_ocr_content(result) + # 如果识别为空且图片较小,尝试放大重试(精度优化:使用更好的放大算法和增强处理) if (not text) and max(w, h) <= 1200: try: - img2 = img.resize((w * 2, h * 2), Image.BICUBIC).filter(ImageFilter.SHARPEN) + # 使用LANCZOS重采样算法(更高质量的放大) + img2 = img.resize((w * 2, h * 2), Image.LANCZOS) + # 应用增强预处理 + try: + from PIL import ImageEnhance + img2_sharpened = img2.filter(ImageFilter.UnsharpMask(radius=1.5, percent=180, threshold=3)) + enhancer = ImageEnhance.Contrast(img2_sharpened) + img2_enhanced = enhancer.enhance(1.2) # 放大后增强20%对比度 + img2 = img2_enhanced + except Exception: + img2 = img2.filter(ImageFilter.SHARPEN) result2 = self.ocr.ocr(np.array(img2)) if result2 != [None]: text = self.extract_ocr_content(result2) @@ -392,61 +629,6 @@ class underlying_operations: return text - def analyse_pic_word_fast(self, picname='', change_color=0, max_side=600): - """更快的 OCR 路径:对裁剪图像做轻量化预处理并只执行一次 OCR(不做放大重试),用于对小区域的快速判定。 - - 参数: - picname: 图片在 pic/ 中的文件名(不含后缀),空串表示默认 cut.png - change_color: 同 `analyse_pic_word` 的二值化模式(0=不二值化,1/2=两种二值化) - max_side: 若图片任一边超过该值,则按比例缩小到该尺寸,减少 OCR 计算量 - 返回: 识别到的文本(字符串)或空串 - """ - self._ensure_ocr() - path = os.path.dirname(__file__) + '/pic' - if picname == '': - img_path = path + '/cut.png' - else: - img_path = path + '/' + picname + '.png' - try: - img = Image.open(img_path) - except Exception: - return '' - - # 轻量化预处理:灰度/二值化 (若指定) - try: - if change_color in (1, 2): - img = img.convert('L') - if change_color == 1: - img = img.point(lambda x: 0 if x < 128 else 255) - else: - img = img.point(lambda x: 0 if x < 180 else 255) - img = img.convert('RGB') - else: - img = img.convert('RGB') - except Exception: - img = img.convert('RGB') - - # 若图片较大,按比例缩小到 max_side,减小 OCR 负担 - try: - w, h = img.size - m = max(w, h) - if max_side and m > max_side: - scale = max_side / float(m) - nw = max(1, int(w * scale)) - nh = max(1, int(h * scale)) - img = img.resize((nw, nh), Image.BILINEAR) - except Exception: - pass - - try: - img_np = np.array(img.filter(ImageFilter.SHARPEN)) - result = self.ocr.ocr(img_np) - if result == [None]: - return '' - return self.extract_ocr_content(result) - except Exception: - return '' - def extract_ocr_content(self, content=[]): """对OCR识别到的内容进行取值和拼接,变成完整的一段内容""" ocr_result = content diff --git a/config.json b/config.json index ae577d1..f8d1456 100644 --- a/config.json +++ b/config.json @@ -1,7 +1,7 @@ { "log_unified_enabled": true, "log_unified_path": "logs/unified.log", - "webgui_log_capacity": 0, + "webgui_log_capacity": 2000, "contains_want": [], "contains_not_want": [ "袜子1" @@ -23,7 +23,7 @@ "fudai_quiet_start_hour": 2, "fudai_quiet_end_hour": 7, "no_fudai_watchdog_enabled": false, - "reset_after_swipes": 0, + "reset_after_swipes": 15, "yanghao_enabled": false, "yanghao_recommend_duration_seconds": 216, "yanghao_recommend_interval_seconds": 600, @@ -143,12 +143,13 @@ "yanghao_fallback_live_y": 169, "yanghao_fallback_enter_live_x": 119, "yanghao_fallback_enter_live_y": 345, - "reset_after_swipes_enabled": false, + "reset_after_swipes_enabled": true, "high_value_room_revisit_enabled": false, "high_value_room_revisit_only_current_run": false, "reservation_back_verify_enabled": false, "fudai_icon_max_wait_seconds": 10, "fudai_icon_adaptive_enabled": false, "fudai_find_max_attempts": 5, - "reservation_preempt_min_value": 0 + "reservation_preempt_min_value": 0, + "reservation_back_swipe_delay": 0.6 } diff --git a/douyin_fudai.py b/douyin_fudai.py index 8ae2911..47bde78 100644 --- a/douyin_fudai.py +++ b/douyin_fudai.py @@ -183,6 +183,12 @@ class fudai_analyse: self.y_pianyi = 0 # 应用于不同型号手机,图标相对屏幕的高度位置有偏差 self.resolution_ratio_x = 1080 self.resolution_ratio_y = 2400 + # OCR结果缓存:避免短时间内重复识别相同区域 + self._ocr_cache: dict[str, tuple[float, str]] = {} # key: (picname, change_color), value: (timestamp, result) + self._ocr_cache_ttl: float = 2.0 # 缓存有效期(秒) + # 检测结果缓存 + self._detection_cache: dict[str, tuple[float, object]] = {} # key: method_name, value: (timestamp, result) + self._detection_cache_ttl: float = 1.0 # 检测缓存有效期(秒) # 预约队列状态文件(用于 Web GUI 展示;子进程写入,Web GUI 进程读取) self._reservations_state_path = os.path.join(os.path.dirname(__file__), "state", "reservations.json") # 让终端输出更“整行、实时”(避免看起来空白/零散) @@ -304,8 +310,33 @@ class fudai_analyse: self.yanghao_recommend_interval_seconds = 0 # 0=不限制(每次触发都可执行) self._yanghao_last_recommend_ts = 0.0 - def _log_kv(self, tag: str, msg: str = "", **fields): - """统一日志输出:保留 [tag] 前缀,同时提供中文 key=value 字段,方便 grep/debug。""" + def _log_kv(self, *args, **fields): + """统一日志输出:保留 [tag] 前缀,同时提供中文 key=value 字段,方便 grep/debug。 + + 兼容性说明:有些地方可能通过 kwargs 传入名为 'tag' 或 'msg' 的键, + 为避免出现 "multiple values for argument 'tag'" 错误,这里优先使用位置参数, + 并在必要时从 fields 中移除重复键。 + """ + # 解析位置参数/关键字,位置参数优先 + tag = None + msg = None + if len(args) >= 1: + tag = args[0] + if len(args) >= 2: + msg = args[1] + # 若 kwargs 中包含 'tag'/'msg',且位置参数未提供,则取 kwargs 的值;若位置参数已提供,则删除以避免重复 + if 'tag' in fields: + if tag is None: + tag = fields.pop('tag') + else: + # 删除以避免后续处理将其误当作字段 + fields.pop('tag', None) + if 'msg' in fields: + if msg is None: + msg = fields.pop('msg') + else: + fields.pop('msg', None) + try: self._log_seq += 1 except Exception: @@ -364,6 +395,26 @@ class fudai_analyse: "actual_value": "【识别】价值元", "expected_content": "【期望】内容", "actual_content": "【识别】内容", + # 新增字段映射 + "content": "内容", + "task_count": "任务数", + "countdown": "倒计时", + "min_participants": "最小参与人数", + "max_participants": "最大参与人数", + "min_value_yuan": "最小价值元", + "diag_text": "诊断文本", + "seconds": "耗时秒", + "enter_reason": "进入原因", + "fudai_x": "福袋X坐标", + "participants": "参与人数", + "copies": "份数", + "value_yuan": "价值元", + "keyword": "关键词", + "x": "X坐标", + "y": "Y坐标", + "clicks": "点击次数", + "abnormal": "异常", + "reasons": "原因", } flat = [] @@ -390,45 +441,115 @@ class fudai_analyse: ck = "字段_{}".format(str(k)) flat.append("{}={}".format(ck, s)) - # 日志自动换行:每行最多120字符,超过则换行缩进继续输出 - log_line = "[{}] {}".format(tag, " ".join(flat)) - if len(log_line) <= 120: + # 获取时间戳(格式:HH:MM:SS) + try: + timestamp = datetime.now().strftime('%H:%M:%S') + except Exception: + timestamp = "" + + # 构建日志行:格式为 [时间] [标签] 消息 字段... + # 如果消息为空,则只显示字段 + log_parts = [] + if timestamp: + log_parts.append(f"[{timestamp}]") + log_parts.append(f"[{tag}]") + + if msg: + m = str(msg).replace("\r", " ").replace("\n", " ").strip() + if len(m) > 200: + m = m[:200] + "..." + log_parts.append(m) + + # 添加字段(使用中文key,格式化值) + for k, v in (fields or {}).items(): + if v is None: + continue + key_cn = key_map.get(str(k), None) + if not key_cn: + # 兜底:避免英文 key 出现在日志里 + key_cn = "字段_{}".format(str(k)) + + # 格式化值:数字保留适当精度,字符串截断 + if isinstance(v, float): + if abs(v) < 1: + v_str = f"{v:.3f}" + elif abs(v) < 100: + v_str = f"{v:.2f}" + else: + v_str = f"{int(v)}" + elif isinstance(v, (int, bool)): + v_str = str(v) + else: + s = str(v).replace("\r", " ").replace("\n", " ").strip() + if len(s) > 100: + s = s[:100] + "..." + v_str = s + + log_parts.append(f"{key_cn}={v_str}") + + # 构建完整日志行 + log_line = " ".join(log_parts) + + # 日志自动换行:每行最多130字符,超过则换行缩进继续输出 + if len(log_line) <= 130: print(log_line) else: - # 将字段分段输出 - header = "[{}] ".format(tag) - indent = " " * len(header) + # 超长日志:首行显示时间+标签+消息,后续行显示字段 parts = [] - current_line = header + "{}={} {}={}".format( - key_map.get("rid", "运行"), getattr(self, "_run_id", "-"), - key_map.get("seq", "序号"), getattr(self, "_log_seq", 0) - ) + # 首行:时间 + 标签 + 消息 + header_parts = [] + if timestamp: + header_parts.append(f"[{timestamp}]") + header_parts.append(f"[{tag}]") if msg: m = str(msg).replace("\r", " ").replace("\n", " ").strip() - if len(m) > 240: - m = m[:240] + "..." - current_line += " {}={}".format(key_map.get("msg", "说明"), m) - parts.append(current_line) + if len(m) > 200: + m = m[:200] + "..." + header_parts.append(m) + parts.append(" ".join(header_parts)) + + # 字段分行显示 + indent = " " # 2个空格缩进 + current_line = indent for k, v in (fields or {}).items(): if v is None: continue - s = str(v) - if s == "": - continue - s = s.replace("\r", " ").replace("\n", " ").strip() - if len(s) > 240: - s = s[:240] + "..." - ck = key_map.get(str(k), None) - if not ck: - ck = "字段_{}".format(str(k)) - field_str = "{}={}".format(ck, s) + key_cn = key_map.get(str(k), None) + if not key_cn: + key_cn = "字段_{}".format(str(k)) - # 检查是否需要换行 - if len(parts[-1]) + len(field_str) + 1 > 120: - parts.append(indent + field_str) + # 格式化值 + if isinstance(v, float): + if abs(v) < 1: + v_str = f"{v:.3f}" + elif abs(v) < 100: + v_str = f"{v:.2f}" + else: + v_str = f"{int(v)}" + elif isinstance(v, (int, bool)): + v_str = str(v) else: - parts[-1] += " " + field_str + s = str(v).replace("\r", " ").replace("\n", " ").strip() + if len(s) > 100: + s = s[:100] + "..." + v_str = s + + field_str = f"{key_cn}={v_str}" + + # 检查是否需要换行(考虑缩进) + if len(current_line) + len(field_str) + 1 > 130: + if current_line.strip(): + parts.append(current_line.strip()) + current_line = indent + field_str + else: + if current_line == indent: + current_line += field_str + else: + current_line += " " + field_str + + if current_line.strip() and current_line != indent: + parts.append(current_line.strip()) print("\n".join(parts)) @@ -437,8 +558,13 @@ class fudai_analyse: self.yanghao_fallback_close_y = 120 self.yanghao_fallback_live_x = 900 self.yanghao_fallback_live_y = 2280 - self.yanghao_fallback_enter_live_x = 540 - self.yanghao_fallback_enter_live_y = 1250 + self.yanghao_fallback_enter_live_x = 109 + self.yanghao_fallback_enter_live_y = 376 + # 关注标签坐标(用于从推荐页面点击顶部“关注”标签) + # 坐标以 1080x2400 分辨率为基准;你提供的矩形为: + # 左上角 (674, 153),右下角 (749, 185),中心点约为 (712, 169) + self.yanghao_follow_tab_x = 712 # 关注标签中心的 x 坐标(1080x2400 基准) + self.yanghao_follow_tab_y = 169 # 关注标签中心的 y 坐标(1080x2400 基准) # 新养号动作:停留期间可按概率点爱心/收藏,停留结束后自动滑动到下一个 self.yanghao_enable_actions = True @@ -1324,7 +1450,9 @@ class fudai_analyse: self._save_step_screenshot("step4_live") print("[养号] Step5/5:点击『点击进入直播间』") - print("[养号] step5: 坐标点击进入直播间 -> ({},{})".format(self.yanghao_fallback_enter_live_x, self.yanghao_fallback_enter_live_y)) + print("[养号] step5: 坐标点击进入直播间 -> ({},{}) 连点两次".format(self.yanghao_fallback_enter_live_x, self.yanghao_fallback_enter_live_y)) + self.click(int(self.yanghao_fallback_enter_live_x), int(self.yanghao_fallback_enter_live_y)) + self.operation.delay(0.6) self.click(int(self.yanghao_fallback_enter_live_x), int(self.yanghao_fallback_enter_live_y)) self.operation.delay(2.0) if capture_steps: @@ -1494,99 +1622,85 @@ class fudai_analyse: img.save(save_pic) def check_detail_height(self): - """判定福袋弹窗的高度,会因为抽奖所需任务不同稍有区别,分别有不要任务、1/2个任务""" + """判定福袋弹窗的高度,会因为抽奖所需任务不同稍有区别,分别有不要任务、1/2/3个任务 + + 优化: + - 提取公共的像素检测逻辑,减少代码重复 + - 优化检测顺序(先检测最常见的2个任务) + - 添加边界检查 + """ path = os.path.dirname(__file__) + '/pic' pic1_path = path + '/screenshot.png' pic = None - for _ in range(3): + for attempt in range(3): try: pic = Image.open(pic1_path) # 强制加载,尽早暴露截断/0字节问题 pic.load() break - except Exception: - try: - # 重新截图一次再试 - self.operation.get_screenshot(self.device_id) - except Exception: - pass - try: - self.operation.delay(0.2) - except Exception: - pass + except (IOError, OSError, Image.UnidentifiedImageError): + if attempt < 2: + try: + # 重新截图一次再试 + self.operation.get_screenshot(self.device_id) + self.operation.delay(0.2) + except Exception: + pass pic = None if pic is None: - print('读取截图失败:参与抽奖默认不需要任务') + self._log_kv("检测", "读取截图失败,默认不需要任务", level="WARN") return 0 - # pic_new = Image.open(cut_pic_path) + pic_new = pic.convert('RGBA') pix = pic_new.load() - if 30 <= pix[536 * self.resolution_ratio_x // 1080, 883 * self.resolution_ratio_y // 2400][0] <= 38 and 34 <= \ - pix[536 * self.resolution_ratio_x // 1080, 883 * self.resolution_ratio_y // 2400][1] <= 40 and 78 <= \ - pix[536 * self.resolution_ratio_x // 1080, 883 * self.resolution_ratio_y // 2400][2] <= 84: - print('参与抽奖有3个任务') - return 3 - elif 30 <= pix[536 * self.resolution_ratio_x // 1080, 883 * self.resolution_ratio_y // 2400 + self.y_pianyi][ - 0] <= 38 and 34 <= \ - pix[536 * self.resolution_ratio_x // 1080, 883 * self.resolution_ratio_y // 2400 + self.y_pianyi][ - 1] <= 40 and 78 <= \ - pix[536 * self.resolution_ratio_x // 1080, 883 * self.resolution_ratio_y // 2400 + self.y_pianyi][ - 2] <= 84: - print('参与抽奖有3个任务') - return 3 - elif 30 <= pix[536 * self.resolution_ratio_x // 1080, 883 * self.resolution_ratio_y // 2400 - self.y_pianyi][ - 0] <= 38 and 34 <= \ - pix[536 * self.resolution_ratio_x // 1080, 883 * self.resolution_ratio_y // 2400 - self.y_pianyi][ - 1] <= 40 and 78 <= \ - pix[536 * self.resolution_ratio_x // 1080, 883 * self.resolution_ratio_y // 2400 - self.y_pianyi][ - 2] <= 84: - print('参与抽奖有3个任务') - return 3 - elif 30 <= pix[536 * self.resolution_ratio_x // 1080, 983 * self.resolution_ratio_y // 2400][0] <= 38 and 34 <= \ - pix[536 * self.resolution_ratio_x // 1080, 983 * self.resolution_ratio_y // 2400][1] <= 40 and 78 <= \ - pix[536 * self.resolution_ratio_x // 1080, 983 * self.resolution_ratio_y // 2400][2] <= 84: - print('参与抽奖有2个任务') - return 2 - elif 30 <= pix[536 * self.resolution_ratio_x // 1080, 983 * self.resolution_ratio_y // 2400 + self.y_pianyi][ - 0] <= 38 and 34 <= \ - pix[536 * self.resolution_ratio_x // 1080, 983 * self.resolution_ratio_y // 2400 + self.y_pianyi][ - 1] <= 40 and 78 <= \ - pix[536 * self.resolution_ratio_x // 1080, 983 * self.resolution_ratio_y // 2400 + self.y_pianyi][ - 2] <= 84: - print('参与抽奖有2个任务') - return 2 - elif 30 <= pix[536 * self.resolution_ratio_x // 1080, 983 * self.resolution_ratio_y // 2400 - self.y_pianyi][ - 0] <= 38 and 34 <= \ - pix[536 * self.resolution_ratio_x // 1080, 983 * self.resolution_ratio_y // 2400 - self.y_pianyi][ - 1] <= 40 and 78 <= \ - pix[536 * self.resolution_ratio_x // 1080, 983 * self.resolution_ratio_y // 2400 - self.y_pianyi][ - 2] <= 84: - print('参与抽奖有2个任务') - return 2 - elif 30 <= pix[536 * self.resolution_ratio_x // 1080, 1058 * self.resolution_ratio_y // 2400][0] <= 38 and 34 <= \ - pix[536 * self.resolution_ratio_x // 1080, 1058 * self.resolution_ratio_y // 2400][1] <= 40 and 78 <= \ - pix[536 * self.resolution_ratio_x // 1080, 1058 * self.resolution_ratio_y // 2400][2] <= 84: - print('参与抽奖有1个任务') - return 1 - elif 30 <= pix[536 * self.resolution_ratio_x // 1080, 1058 * self.resolution_ratio_y // 2400 + self.y_pianyi][ - 0] <= 38 and 34 <= \ - pix[536 * self.resolution_ratio_x // 1080, 1058 * self.resolution_ratio_y // 2400 + self.y_pianyi][ - 1] <= 40 and 78 <= \ - pix[536 * self.resolution_ratio_x // 1080, 1058 * self.resolution_ratio_y // 2400 + self.y_pianyi][ - 2] <= 84: - print('参与抽奖有1个任务') - return 1 - elif 30 <= pix[536 * self.resolution_ratio_x // 1080, 1058 * self.resolution_ratio_y // 2400 - self.y_pianyi][ - 0] <= 38 and 34 <= \ - pix[536 * self.resolution_ratio_x // 1080, 1058 * self.resolution_ratio_y // 2400 - self.y_pianyi][ - 1] <= 40 and 78 <= \ - pix[536 * self.resolution_ratio_x // 1080, 1058 * self.resolution_ratio_y // 2400 - self.y_pianyi][ - 2] <= 84: - print('参与抽奖有1个任务') - return 1 - elif self.check_have_robot_analyse(): # 如果打开的弹窗是个人机校验 + width, height = pic_new.size + + # 参与按钮的x坐标 + x = 536 * self.resolution_ratio_x // 1080 + if not (0 <= x < width): + return 0 + + # 定义检测点的y坐标和对应的任务数(按常见程度排序:2任务最常见) + # 格式:(base_y, y_pianyi_offset, task_count) + check_points = [ + (983, 0, 2), # 2个任务(最常见) + (983, self.y_pianyi, 2), + (983, -self.y_pianyi, 2), + (883, 0, 3), # 3个任务 + (883, self.y_pianyi, 3), + (883, -self.y_pianyi, 3), + (1058, 0, 1), # 1个任务 + (1058, self.y_pianyi, 1), + (1058, -self.y_pianyi, 1), + ] + + # 参与按钮颜色范围(RGB)- 精度优化:适度放宽范围提高容错性 + def _check_pixel_color(y_coord: int) -> bool: + """检查指定y坐标的像素颜色是否匹配参与按钮""" + if not (0 <= y_coord < height): + return False + try: + p = pix[x, y_coord] + if not (isinstance(p, tuple) and len(p) >= 3): + return False + r, g, b = int(p[0]), int(p[1]), int(p[2]) + # 优化:适度放宽颜色范围(±2),提高在不同屏幕色温/亮度下的识别率 + # 但保持中心值权重,避免误判 + return 28 <= r <= 40 and 32 <= g <= 42 and 76 <= b <= 86 + except (IndexError, TypeError): + return False + + # 按顺序检测 + for base_y, dy, task_count in check_points: + y = base_y * self.resolution_ratio_y // 2400 + dy + if _check_pixel_color(y): + self._log_kv("检测", f"识别到福袋任务数量:{task_count}个", task_count=task_count) + return task_count + + # 如果都没检测到,检查是否是人机校验 + if self.check_have_robot_analyse(): self.deal_robot_analyse() - print('参与抽奖不需要任务') + self._log_kv("检测", "识别福袋任务数量:0个(不需要任务)", level="INFO", task_count=0) return 0 def check_have_fudai(self): @@ -1639,49 +1753,88 @@ class fudai_analyse: pic_new = pic.convert('RGBA') detected = False detected_x = None - # 先尝试 numpy 加速扫描水平带 + # 先尝试 numpy 加速扫描水平带(性能优化:批量处理) try: import numpy as _np + # 计算检测区域,考虑分辨率缩放和偏移 y0 = 403 * self.resolution_ratio_y // 2400 + self.y_pianyi - x1 = 41 * self.resolution_ratio_x // 1080 - x2 = 410 * self.resolution_ratio_x // 1080 + x1 = max(0, 41 * self.resolution_ratio_x // 1080) + x2 = min(pic_new.size[0], 410 * self.resolution_ratio_x // 1080) y_top = max(0, y0 - 3) y_bottom = min(pic_new.size[1], y0 + 4) - roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert('RGB') - arr = _np.array(roi) - if arr.size: - r = arr[:, :, 0] - g = arr[:, :, 1] - b = arr[:, :, 2] - mask = (r >= 193) & (r <= 203) & (g >= 176) & (g <= 193) & (b >= 237) & (b <= 247) - cols = _np.any(mask, axis=0) - if cols.any(): - col_idx = int(_np.argmax(cols)) - detected_x = int((x1 + col_idx) * 1080 / max(1, int(self.resolution_ratio_x))) - detected = True - self.last_find_fudai_time = time.time() - except Exception: + + # 边界检查 + if x1 >= x2 or y_top >= y_bottom: + detected = False + else: + roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert('RGB') + arr = _np.array(roi) + if arr.size > 0: + r = arr[:, :, 0] + g = arr[:, :, 1] + b = arr[:, :, 2] + # 精度优化:扩大颜色范围,提高容错性(考虑不同屏幕色温和亮度) + # 原来的范围:R[193-203], G[176-193], B[237-247] + # 优化后:适度放宽范围,但保持中心值权重 + mask_center = (r >= 190) & (r <= 206) & (g >= 173) & (g <= 196) & (b >= 234) & (b <= 250) + # 速度优化:使用更宽松的预筛选,减少计算量 + mask = mask_center + # 检查每一列是否有足够多的匹配像素(提高准确性,避免单个噪点误判) + cols = _np.sum(mask, axis=0) + # 至少需要2个像素匹配(避免单个噪点误判) + valid_cols = cols >= 2 + if valid_cols.any(): + # 找到第一个有效匹配的列 + col_idx = int(_np.argmax(valid_cols)) + # 计算检测到的x坐标:转换为1080基准坐标,确保精度 + detected_x = int((x1 + col_idx) * 1080.0 / max(1, int(self.resolution_ratio_x))) + detected = True + self.last_find_fudai_time = time.time() + except (ImportError, ValueError, IndexError, AttributeError) as e: + # numpy不可用或计算错误,回退到逐像素检测 detected = False # numpy 未命中/不可用时回退到原始逐像素检查 if not detected: - pix = pic_new.load() - for x in range(41, 410): - try: - px = pix[x * self.resolution_ratio_x // 1080, 403 * self.resolution_ratio_y // 2400 + self.y_pianyi] - except Exception: - continue - if 193 <= px[0] <= 203 and 176 <= px[1] <= 193 and 237 <= px[2] <= 247: - detected = True - detected_x = x - self.last_find_fudai_time = time.time() - break + try: + pix = pic_new.load() + pic_width, pic_height = pic_new.size + # 计算实际扫描范围,防止越界 + scan_x_start = 41 * self.resolution_ratio_x // 1080 + scan_x_end = min(410 * self.resolution_ratio_x // 1080, pic_width) + scan_y = 403 * self.resolution_ratio_y // 2400 + self.y_pianyi + # 确保y坐标在有效范围内 + if 0 <= scan_y < pic_height: + # 精度优化:同时检查上下几行像素,提高检测准确性 + for offset_y in [0, -1, 1, -2, 2]: # 检查当前行及上下2行 + check_y = scan_y + offset_y + if not (0 <= check_y < pic_height): + continue + for x_scaled in range(scan_x_start, scan_x_end): + try: + px = pix[x_scaled, check_y] + # 检查RGB值是否匹配福袋图标颜色(适度放宽范围) + if len(px) >= 3 and 190 <= px[0] <= 206 and 173 <= px[1] <= 196 and 234 <= px[2] <= 250: + # 转换回1080基准坐标 + detected_x = int(x_scaled * 1080.0 / max(1, int(self.resolution_ratio_x))) + detected = True + self.last_find_fudai_time = time.time() + break + except (IndexError, TypeError): + continue + if detected: + break + if detected: + break + except Exception as e: + # 像素检测失败,记录但不影响主流程 + pass if detected: # 额外兜底:防止‘开奖结果’弹窗被错当作福袋图标(例如弹窗区域颜色/像素相近) try: - # 轻量 OCR 诊断:仅识别结果弹窗区域的文字 - self.cut_pic(350, 655, 740, 755, '', 'diag_result') + # 优化:轻量 OCR 诊断 - 稍微扩大区域确保完整 + self.cut_pic(350, 650, 750, 765, '', 'diag_result') diag_txt = str(self.operation.analyse_pic_word('diag_result') or "") if any(k in diag_txt for k in ("没有抽中", "抽中福袋", "未中奖", "开奖")): print(f"[误判防护] 在检测到可能福袋时同时识别到结果弹窗文字,忽略此次福袋检测 diag='{diag_txt}'") @@ -1734,11 +1887,19 @@ class fudai_analyse: return False def check_in_fudai_detail(self) -> bool: - """判断当前是否处于“福袋详情页”。 + """判断当前是否处于"福袋详情页"。 优先使用像素快速判定(复用 check_detail_height 的阈值,但不调用其本体以避免打印/人机副作用), 若未命中则做一次轻量 OCR(仅参与按钮区域)兜底。 """ + # 检查缓存(避免短时间内重复检测) + cache_key = "check_in_fudai_detail" + now = time.time() + if cache_key in self._detection_cache: + cached_ts, cached_result = self._detection_cache[cache_key] + if (now - cached_ts) < self._detection_cache_ttl: + return bool(cached_result) + try: path = os.path.dirname(__file__) + '/pic' pic1_path = path + '/screenshot.png' @@ -1746,7 +1907,7 @@ class fudai_analyse: pic0 = Image.open(pic1_path) pic0.load() pic = pic0.convert('RGBA') - except Exception: + except (IOError, OSError, Image.UnidentifiedImageError): # 截图异常:尝试补一次截图 try: self.operation.get_screenshot(self.device_id) @@ -1754,26 +1915,40 @@ class fudai_analyse: pic0.load() pic = pic0.convert('RGBA') except Exception: + self._detection_cache[cache_key] = (now, False) return False pix = pic.load() width, height = pic.size x = 536 * self.resolution_ratio_x // 1080 + # 边界检查 + if not (0 <= x < width): + self._detection_cache[cache_key] = (now, False) + return False + # 三种高度的参与按钮 y(分别对应 3/2/1 个任务),再考虑 y_pianyi 偏移 base_ys = (883, 983, 1058) - offsets = (0, int(getattr(self, 'y_pianyi', 0) or 0), -int(getattr(self, 'y_pianyi', 0) or 0)) + y_pianyi_val = int(getattr(self, 'y_pianyi', 0) or 0) + offsets = (0, y_pianyi_val, -y_pianyi_val) + + # 优化:先检查最常见的2个任务的情况 for base_y in base_ys: y0 = base_y * self.resolution_ratio_y // 2400 for dy in offsets: y = y0 + dy - if not (0 <= x < width and 0 <= y < height): + if not (0 <= y < height): continue - p = pix[x, y] - if not (isinstance(p, tuple) and len(p) >= 3): + try: + p = pix[x, y] + if not (isinstance(p, tuple) and len(p) >= 3): + continue + r, g, b = int(p[0]), int(p[1]), int(p[2]) + # 参与按钮颜色范围(RGB) + if 30 <= r <= 38 and 34 <= g <= 40 and 78 <= b <= 84: + self._detection_cache[cache_key] = (now, True) + return True + except (IndexError, TypeError): continue - r, g, b = int(p[0]), int(p[1]), int(p[2]) - if 30 <= r <= 38 and 34 <= g <= 40 and 78 <= b <= 84: - return True except Exception: pass @@ -1808,7 +1983,11 @@ class fudai_analyse: def _shot_and_diagnose(self, tag="", next_step="", device_id="", diagnose: bool = True, force_diagnose_once: bool = False): """统一截图入口:每次截图后输出当前阶段、识别到的关键内容、以及下一步是什么。""" did = device_id or getattr(self, "device_id", "") - ok = self.operation.get_screenshot(did) + try: + ok = self.operation.get_screenshot(did) + except Exception as e: + print(f"[截图] 截图失败:{e}") + ok = False # 弹窗守护:有些系统弹窗(例如 vivo 停止充电提醒)会遮挡 UI。 # 若检测到则按一次返回键关闭,避免主流程卡住。 @@ -1862,6 +2041,25 @@ class fudai_analyse: if min_interval > 0 and (now - last) < min_interval: return False + # 购物红包弹窗:检测到就点击关闭按钮(530, 1647) + try: + if self._check_shopping_redpacket_popup(): + self._last_popup_back_ts = now + self._log_kv("弹窗", "检测到购物红包弹窗:点击关闭按钮", kind="shopping_redpacket", action="click_close") + try: + # 点击关闭按钮坐标 (530, 1647),基于1080x2400分辨率(click方法内部会自动缩放) + self.click(530, 1647) + print(f"检测到购物红包弹窗,点击关闭按钮 -> (530, 1647)") + except Exception: + pass + try: + self.operation.delay(0.8) + except Exception: + pass + return True + except Exception: + pass + # 购物券/新客专享券等底部弹窗:检测到就按返回键 try: enabled_coupon = bool(getattr(self, "coupon_popup_back_enabled", True)) @@ -1940,51 +2138,155 @@ class fudai_analyse: return True return False + def _check_shopping_redpacket_popup(self) -> bool: + """检测直播间内的"购物红包"弹窗(中央红色弹窗)。 + + 检测区域:(244, 461) 到 (847, 539) 出现"邀你抢购物红包"这几个字。 + 优化:尝试多种OCR模式,放宽关键词匹配,提高识别成功率。 + """ + # 使用当前截图(由 _shot_and_diagnose 刚刚更新),避免额外截图开销 + try: + # 检测区域:从(244, 461)到(847, 539)识别"邀你抢购物红包" + # 稍微扩大区域,提高容错性 + self.cut_pic(230, 450, 860, 550, '', 'diag_shopping_redpacket') + except Exception: + return False + + # 尝试多种OCR模式(change_color=0, 1, 2),提高识别成功率 + # change_color=0: 保持彩色(默认,适合红色弹窗) + # change_color=1: 二值化(阈值128,适合对比度高的场景) + # change_color=2: 二值化(阈值180,适合对比度较低的场景) + texts = [] + for ocr_mode in [0, 1, 2]: + try: + t = str(self.operation.analyse_pic_word('diag_shopping_redpacket', ocr_mode) or "") + hay = t.strip() if t else "" + if hay: + texts.append(hay) + # 如果当前模式已经识别到关键词,直接返回True,不必继续尝试(优化性能) + # 放宽关键词匹配:只要包含"购物红包"或"邀你抢"等关键词即可 + if any(kw in hay for kw in ("邀你抢购物红包", "抢购物红包", "购物红包", "邀你抢", "抢红包")): + return True + except Exception: + continue + + # 如果单个模式都没识别到,合并所有识别结果再次检查(提高容错性) + if texts: + combined_text = " ".join(texts).strip() + # 进一步放宽匹配:只要包含关键字的任意组合即可 + if any(kw in combined_text for kw in ("购物红包", "邀你抢", "抢红包")): + return True + + return False + def _diagnose_stage_from_current_screen(self): - """仅基于当前截图做轻量诊断(不触发额外截图)。""" - # 关注列表 / 直播列表 + """仅基于当前截图做轻量诊断(不触发额外截图)。 + + 优化:按常见程度排序检测,优先检测最常见的场景,减少不必要的OCR调用。 + """ + # 优化:先检测最常见的场景(直播间),减少OCR调用 + # 1. 先快速检测福袋详情页(使用像素检测,最快) + try: + if self.check_in_fudai_detail(): + return "FUDai_DETAIL", "像素检测确认" + except Exception: + pass + + # 2. 检测抽奖结果弹窗(用户最关心的结果) + t_result = "" + try: + # 优化:稍微扩大区域确保完整 + self.cut_pic(350, 650, 750, 765, '', 'diag_result') + t_result = str(self.operation.analyse_pic_word('diag_result') or "") + except Exception: + pass + if t_result and ("没有抽中" in t_result or "抽中福袋" in t_result): + return "FUDai_RESULT", "结果='{}'".format(t_result) + + # 3. 检测推荐页面(优先级提高,放在关注列表之前,避免误判) + # 优化:基于关注标签坐标(712, 169)精确定位标签栏区域,提高识别精准度 + # 标签栏区域:x方向包含"推荐"、"关注"、"直播"等标签,y方向在标签中心附近 + t_recommend = "" + try: + # 精确定位标签栏:基于关注标签(712, 169),标签栏大致在x=400-900, y=140-200 + # 缩小区域减少干扰,提高识别精准度(优先保证精准) + self.cut_pic(400, 140, 900, 200, '', 'diag_recommend_title') + # 尝试多种OCR模式,优先使用彩色模式(change_color=0),识别失败再尝试二值化 + t_recommend = str(self.operation.analyse_pic_word('diag_recommend_title', 0) or "") + if not t_recommend or ("推荐" not in t_recommend and "关注" not in t_recommend and "直播" not in t_recommend): + # 如果彩色模式识别失败或未识别到关键词,尝试二值化模式(提高对比度) + t_recommend = str(self.operation.analyse_pic_word('diag_recommend_title', 1) or "") + except Exception: + pass + # 也检查"猜你喜欢"区域(通常在底部) + t_guess_like = "" + try: + self.cut_pic(440, 1570, 640, 1640, '', 'diag_guess_like') + t_guess_like = str(self.operation.analyse_pic_word('diag_guess_like', 1) or "") + except Exception: + pass + # 推荐页面判断: + # 1. 如果识别到"推荐"关键词,且同时包含其他标签(如"关注"、"直播"等),通常是推荐页面 + # 2. 如果有"猜你喜欢",则是推荐页面 + # 3. 如果只有"推荐"且没有明显的列表特征,也是推荐页面 + if "推荐" in t_recommend: + # 推荐页面顶部通常会有多个标签(推荐、关注、直播等) + # 如果同时包含"推荐"和其他导航标签,判定为推荐页面 + if "直播" in t_recommend or "关注" in t_recommend: + return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend) + # 如果有"猜你喜欢",也是推荐页面 + if "猜你喜欢" in t_guess_like or "猜你喜欢" in t_recommend: + return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend or t_guess_like) + # 如果只有"推荐"关键词,也是推荐页面(推荐页面是默认首页) + return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend) + # 如果没有"推荐"但有"猜你喜欢",也可能是推荐页面 + if "猜你喜欢" in t_guess_like: + return "RECOMMEND_PAGE", "标题='{}'".format(t_guess_like) + + # 4. 关注列表 / 直播列表(较常见) + # 优化:基于关注标签坐标(712, 169)精确定位标签区域,缩小识别范围提高精准度 t_follow = "" t_list = "" try: - self.cut_pic(420, 130, 660, 220, '', 'diag_follow_title') - t_follow = str(self.operation.analyse_pic_word('diag_follow_title') or "") + # 精确定位关注标签区域:基于坐标(712, 169),标签范围约x=674-749, y=153-185 + # 稍微扩大一点区域以提高容错性,但保持精确:x=650-800, y=145-195 + self.cut_pic(650, 145, 800, 195, '', 'diag_follow_title') + # 优先使用彩色模式,识别失败再尝试二值化 + t_follow = str(self.operation.analyse_pic_word('diag_follow_title', 0) or "") + if not t_follow or "关注" not in t_follow: + t_follow = str(self.operation.analyse_pic_word('diag_follow_title', 1) or "") except Exception: pass try: - self.cut_pic(400, 145, 675, 230, '', 'diag_list_title') - t_list = str(self.operation.analyse_pic_word('diag_list_title') or "") + # 直播列表标签也在标签栏区域,使用相似的精确区域 + self.cut_pic(650, 145, 800, 195, '', 'diag_list_title') + t_list = str(self.operation.analyse_pic_word('diag_list_title', 0) or "") + if not t_list or "正在直播" not in t_list: + t_list = str(self.operation.analyse_pic_word('diag_list_title', 1) or "") except Exception: pass - # 记录诊断时看到的“关注页标题”,便于后续逻辑复用(避免重复 OCR) + # 记录诊断时看到的"关注页标题",便于后续逻辑复用(避免重复 OCR) try: self._last_follow_list_title_text = str(t_follow or "").strip() except Exception: self._last_follow_list_title_text = "" - if "关注" in t_follow: + # 注意:如果标题区域包含"推荐",已经在前面判定为推荐页面 + # 只有当没有"推荐"关键词时,才判定为关注列表 + if "关注" in t_follow and "推荐" not in t_follow: return "FOLLOW_LIST", "标题='{}'".format(t_follow) if "正在直播" in t_list: return "LIVE_LIST", "标题='{}'".format(t_list) - # 抽奖结果弹窗 - t_result = "" - try: - self.cut_pic(350, 655, 740, 755, '', 'diag_result') - t_result = str(self.operation.analyse_pic_word('diag_result') or "") - except Exception: - pass - if "没有抽中" in t_result or "抽中福袋" in t_result: - return "FUDai_RESULT", "结果='{}'".format(t_result) - - # 福袋详情页(参与按钮区域) + # 4. 福袋详情页(参与按钮区域,OCR兜底) t_btn = "" try: self.cut_pic(306, 2030, 780, 2110, '', 'diag_attend_btn') t_btn = str(self.operation.analyse_pic_word('diag_attend_btn', 1) or "") except Exception: pass - if any(k in t_btn for k in ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看")): + if t_btn and any(k in t_btn for k in ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看")): return "FUDai_DETAIL", "参与按钮='{}'".format(t_btn) # 粉丝团加入页(点击“加入粉丝团/点亮粉丝团”后可能进入单独页面) @@ -2091,9 +2393,10 @@ class fudai_analyse: def check_in_follow_list(self): """判断是否界面在我的关注的列表页""" - # 注意:直播间顶部也可能出现“关注”按钮(会误判)。 - # 因此只截取“顶部居中标题”区域,用于判断是否在关注页。 - self.cut_pic(420, 130, 660, 220, '', 'zhibo_follow_list_title') + # 优化:扩大识别区域,识别整行文字 + # 注意:直播间顶部也可能出现"关注"按钮(会误判)。 + # 扩大区域:从左边界(420->300)到右边界(660->780),扩大高度(220->240)以包含完整文字 + self.cut_pic(300, 120, 780, 240, '', 'zhibo_follow_list_title') zhibo_list_title = self.operation.analyse_pic_word('zhibo_follow_list_title') try: self._last_follow_list_title_text = str(zhibo_list_title or "").strip() @@ -2107,7 +2410,9 @@ class fudai_analyse: def check_in_zhibo_list(self): """检查是否当前在关注的直播列表""" - self.cut_pic(400, 145, 675, 230, '', 'zhibo_list_title') + # 优化:扩大识别区域,识别整行文字 + # 扩大区域:从左边界(400->350)到右边界(675->730),扩大高度(230->250)以包含完整文字 + self.cut_pic(350, 135, 730, 250, '', 'zhibo_list_title') zhibo_list_title = self.operation.analyse_pic_word('zhibo_list_title') if "正在直播" in zhibo_list_title: print("当前界面已经在关注的直播间列表") @@ -2154,7 +2459,7 @@ class fudai_analyse: # 按用户指定:不走任何“打开直播间列表/判断列表是否为空”等旧路径, # 统一只执行固定流程进入直播间。 try: - self._shot_and_diagnose("从列表进直播", "固定流程进入直播间(715,166)->(103,354)x2", self.device_id, diagnose=True, force_diagnose_once=True) + self._shot_and_diagnose("从列表进直播", "固定流程进入直播间(715,166)->(109,376)x2", self.device_id, diagnose=True, force_diagnose_once=True) except Exception: pass @@ -2171,10 +2476,10 @@ class fudai_analyse: self.operation.delay(0.8) # Step2: 连点两次进入直播间 - print("固定流程:点击103,354两次进入直播间") - self.click(103, 354) + print("固定流程:点击109,376两次进入直播间") + self.click(109, 376) self.operation.delay(0.6) - self.click(103, 354) + self.click(109, 376) try: self._mark_enter_live("fixed_enter_live") @@ -2286,29 +2591,41 @@ class fudai_analyse: countdown_box = None if renwu == 2: # 如果是2个任务的 - self.cut_pic(390, 1240, 1000, 1460, '', 'fudai_content', self.y_pianyi) # 福袋内容详情 - countdown_box = (390, 1110, 690, 1220) + # 优化:稍微缩小宽度(1000->980),增加高度(1460->1470),减少右侧干扰,确保内容完整 + self.cut_pic(390, 1240, 980, 1470, '', 'fudai_content', self.y_pianyi) # 福袋内容详情 + # 优化:稍微扩大高度(1220->1230),确保包含完整的"后开奖"文字 + countdown_box = (390, 1110, 690, 1230) self.cut_pic(*countdown_box, '', 'fudai_countdown', self.y_pianyi) # 完整福袋详情倒计时 - self.cut_pic(390, 1460, 1000, 1560, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格(加宽避免截断) + # 优化:增加高度(1560->1580),确保包含"元"等单位文字 + self.cut_pic(390, 1460, 1000, 1580, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格 elif renwu == 1: # 如果是1个任务的 - self.cut_pic(390, 1300, 1000, 1520, '', 'fudai_content', self.y_pianyi) # 福袋内容详情 - countdown_box = (390, 1180, 690, 1290) + # 优化:稍微缩小宽度,增加高度,减少干扰 + self.cut_pic(390, 1300, 980, 1530, '', 'fudai_content', self.y_pianyi) # 福袋内容详情 + # 优化:稍微扩大高度,确保完整 + countdown_box = (390, 1180, 690, 1300) self.cut_pic(*countdown_box, '', 'fudai_countdown', self.y_pianyi) # 完整福袋详情倒计时 - self.cut_pic(390, 1520, 1000, 1620, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格(加宽避免截断) + # 优化:增加高度,包含单位 + self.cut_pic(390, 1520, 1000, 1630, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格 elif renwu == 3: # 如果是3个任务的 - self.cut_pic(390, 1160, 1000, 1380, '', 'fudai_content', self.y_pianyi) # 福袋内容详情 - countdown_box = (390, 1010, 690, 1120) + # 优化:稍微缩小宽度,增加高度 + self.cut_pic(390, 1160, 980, 1390, '', 'fudai_content', self.y_pianyi) # 福袋内容详情 + # 优化:稍微扩大高度 + countdown_box = (390, 1010, 690, 1130) self.cut_pic(*countdown_box, '', 'fudai_countdown', self.y_pianyi) # 完整福袋详情倒计时 - self.cut_pic(390, 1380, 1000, 1480, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格(加宽避免截断) + # 优化:增加高度 + self.cut_pic(390, 1380, 1000, 1490, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格 else: - self.cut_pic(390, 1600, 1000, 1820, '', 'fudai_content', self.y_pianyi) # 福袋内容详情 - countdown_box = (390, 1460, 690, 1570) + # 优化:稍微缩小宽度,增加高度 + self.cut_pic(390, 1600, 980, 1830, '', 'fudai_content', self.y_pianyi) # 福袋内容详情 + # 优化:稍微扩大高度 + countdown_box = (390, 1460, 690, 1580) self.cut_pic(*countdown_box, '', 'fudai_countdown', self.y_pianyi) # 完整福袋详情倒计时 - self.cut_pic(390, 1820, 1000, 1920, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格(加宽避免截断) + # 优化:增加高度 + self.cut_pic(390, 1820, 1000, 1930, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格 fudai_content_raw = self.operation.analyse_pic_word('fudai_content', 0) participants, copies, fudai_content_text = _extract_participants_and_clean(fudai_content_raw) - print("福袋内容:{}".format(fudai_content_text)) + self._log_kv("福袋", "识别福袋内容", level="INFO", content=fudai_content_text[:60] if fudai_content_text else "未识别到") # 记录进入直播间到识别到福袋的耗时(仅记录一次) try: if getattr(self, "_enter_live_ts", 0.0) and not getattr(self, "_enter_live_fudai_logged", False): @@ -2318,7 +2635,7 @@ class fudai_analyse: secs = -1.0 reason = str(getattr(self, "_enter_live_reason", "") or "") # 结构化输出,方便统一日志与后端统计解析 - print("[性能] 进入直播间到识别福袋耗时:{:.2f} 秒 进入原因={}".format(secs, reason)) + self._log_kv("性能", "进入直播间到识别福袋耗时", seconds=round(secs, 2), enter_reason=reason) try: self._enter_live_fudai_logged = True except Exception: @@ -2326,9 +2643,7 @@ class fudai_analyse: except Exception: pass if copies: - print("福袋份数:{}".format(copies)) - if participants: - print("参与人数:{}".format(participants)) + self._log_kv("福袋", "识别福袋信息", copies=copies, participants=participants if participants else 0) # 倒计时:优先用“分割小区域”快速 OCR(更快、更稳定),失败再 OCR 整块。 time_text = '' @@ -2343,7 +2658,7 @@ class fudai_analyse: if not time_text: time_raw = self.operation.analyse_pic_word('fudai_countdown', 0) time_text = normalize_countdown_text(time_raw) - print("倒计时时间:{}".format(time_text)) + self._log_kv("福袋", "识别倒计时", countdown=time_text if time_text else "未识别到") value_raw = self.operation.analyse_pic_word('fudai_value', 0) prize_value_yuan = extract_prize_value_yuan(value_raw) @@ -2352,7 +2667,7 @@ class fudai_analyse: show_value = int(prize_value_yuan) else: show_value = prize_value_yuan - print("奖品价值:{}元".format(show_value)) + self._log_kv("福袋", "识别奖品价值", value_yuan=show_value) return fudai_content_text, time_text, participants, copies, prize_value_yuan @@ -2529,12 +2844,45 @@ class fudai_analyse: return False def check_lucky_draw_result(self): - """判定福袋抽奖的结果""" - self._shot_and_diagnose("开奖结果", "识别是否中奖/未中奖", self.device_id) + """判定福袋抽奖的结果 + + 优化: + - 添加OCR结果缓存,避免重复识别 + - 优化识别顺序(先识别最常见的"没有抽中") + - 速度优化:减少不必要的截图和OCR调用 + """ + # 速度优化:只在需要时截图(如果有最近截图且缓存有效,可跳过) + cache_key = ('lucky_draw_result', 0) + now = time.time() + need_screenshot = True + + # 检查缓存是否有效 + if cache_key in self._ocr_cache: + cached_ts, cached_result = self._ocr_cache[cache_key] + # 如果缓存还在有效期内,且结果明确(包含"没有抽中"或"抽中"),可以复用 + if (now - cached_ts) < 0.5 and cached_result and ("没有抽中" in cached_result or "抽中福袋" in cached_result): + need_screenshot = False + + if need_screenshot: + self._shot_and_diagnose("开奖结果", "识别是否中奖/未中奖", self.device_id) + # 优化:稍微扩大区域(655->650, 755->765),确保包含完整的开奖结果文字 + self.cut_pic(350, 650, 750, 765, '', 'lucky_draw_result') # 没有抽中福袋位置 + # 诊断开始时间 t0 = time.time() - self.cut_pic(350, 655, 740, 755, '', 'lucky_draw_result') # 没有抽中福袋位置 - lucky_draw_result = self.operation.analyse_pic_word('lucky_draw_result') + + # 检查缓存 + if cache_key in self._ocr_cache: + cached_ts, cached_result = self._ocr_cache[cache_key] + if (now - cached_ts) < self._ocr_cache_ttl: + lucky_draw_result = cached_result + else: + lucky_draw_result = self.operation.analyse_pic_word('lucky_draw_result') + self._ocr_cache[cache_key] = (now, lucky_draw_result) + else: + lucky_draw_result = self.operation.analyse_pic_word('lucky_draw_result') + self._ocr_cache[cache_key] = (now, lucky_draw_result) + dur = time.time() - t0 try: brief = (lucky_draw_result or "").replace("\n", " ")[:140] @@ -2543,10 +2891,30 @@ class fudai_analyse: print(f"[开奖诊断] lucky_draw_result=" + repr(brief) + f" ocr_dur={dur:.2f}s") if "没有抽中" in (lucky_draw_result or ""): - t1 = time.time() - self.cut_pic(340, 1200, 730, 1350, '', 'no_award_confirm') # 我知道了按钮的位置 - no_award_confirm = self.operation.analyse_pic_word('no_award_confirm') - dur2 = time.time() - t1 + # 速度优化:使用缓存避免重复OCR + cache_key2 = ('no_award_confirm', 0) + if cache_key2 in self._ocr_cache: + cached_ts2, cached_result2 = self._ocr_cache[cache_key2] + if (now - cached_ts2) < self._ocr_cache_ttl: + no_award_confirm = cached_result2 + else: + t1 = time.time() + # 优化:稍微扩大区域(1200->1195, 1350->1355),确保按钮文字完整 + self.cut_pic(340, 1195, 740, 1355, '', 'no_award_confirm') # 我知道了按钮的位置 + no_award_confirm = self.operation.analyse_pic_word('no_award_confirm') + self._ocr_cache[cache_key2] = (time.time(), no_award_confirm) + dur2 = time.time() - t1 + else: + t1 = time.time() + self.cut_pic(340, 1200, 730, 1350, '', 'no_award_confirm') # 我知道了按钮的位置 + no_award_confirm = self.operation.analyse_pic_word('no_award_confirm') + self._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: @@ -2559,17 +2927,32 @@ class fudai_analyse: return 3 elif "抽中福袋" in (lucky_draw_result or ""): print("恭喜中奖了!") + # 速度优化:优先检测第一个常见位置,命中即返回 y_value = [1438, 1490] for y in y_value: - t2 = time.time() - self.cut_pic(280, y - 30, 660, y + 30, '', 'have_read_user_agreement') # 已经阅读并同意用户协议 - have_read_user_agreement = self.operation.analyse_pic_word('have_read_user_agreement') - dur3 = time.time() - t2 - try: - brief3 = (have_read_user_agreement or "").replace("\n", " ")[:140] - except Exception: - brief3 = "" - print(f"[开奖诊断] have_read_user_agreement=" + repr(brief3) + f" ocr_dur={dur3:.2f}s") + cache_key3 = (f'have_read_user_agreement_{y}', 0) + have_read_user_agreement = None + + if cache_key3 in self._ocr_cache: + cached_ts3, cached_result3 = self._ocr_cache[cache_key3] + if (now - cached_ts3) < self._ocr_cache_ttl: + have_read_user_agreement = cached_result3 + + if not have_read_user_agreement: + t2 = time.time() + # 优化:稍微扩大区域(y±30->y±35),确保协议文字完整识别 + self.cut_pic(280, y - 35, 670, y + 35, '', f'have_read_user_agreement_{y}') # 已经阅读并同意用户协议 + have_read_user_agreement = self.operation.analyse_pic_word(f'have_read_user_agreement_{y}') + self._ocr_cache[cache_key3] = (time.time(), have_read_user_agreement) + dur3 = time.time() - t2 + try: + brief3 = (have_read_user_agreement or "").replace("\n", " ")[:140] + except Exception: + brief3 = "" + print(f"[开奖诊断] have_read_user_agreement=" + repr(brief3) + f" ocr_dur={dur3:.2f}s") + else: + dur3 = 0.0 + if "已阅读" in (have_read_user_agreement or ""): return y return False @@ -2630,7 +3013,7 @@ class fudai_analyse: def deal_battery_level(self): """针对电量不足的情况做处理""" - while self.operation.get_ballery_level(self.device_id) < 30: + while self.operation.get_battery_level(self.device_id) < 30: print("设备电量较低,退出到直播列表,等待电量恢复后继续挂机") self.back_to_zhibo_list() self.operation.delay(1800) # 挂机30分钟 @@ -2647,9 +3030,11 @@ class fudai_analyse: def fudai_choujiang(self, device_id="", y_pianyi=0, needswitch=False, wait_minutes=15): """福袋抽奖主逻辑,默认不切换直播间""" + print("[启动] fudai_choujiang 开始执行") self.device_id = device_id self.y_pianyi = y_pianyi self.resolution_ratio_x, self.resolution_ratio_y = self.operation.get_device_resolution(self.device_id) + print("[启动] 设备分辨率获取完成,开始初始化变量") wait_times = 0 # 当前直播间的等待次数,累计4次没有福袋,则切换直播间 swipe_times = 0 # 向上滑动的次数,当超出一定值,退出返回直播列表 fudai_not_open_times = 0 # 无法打开福袋的次数 @@ -2804,8 +3189,10 @@ class fudai_analyse: except Exception: pass + print("[启动] 开始加载高价值直播间映射") high_value_rooms_map = _load_high_value_rooms_map() - # 本次运行记录的高价值直播间 key 集合(用于可选的“仅回访本次运行记录”逻辑) + print(f"[启动] 高价值直播间映射加载完成,共 {len(high_value_rooms_map)} 个") + # 本次运行记录的高价值直播间 key 集合(用于可选的"仅回访本次运行记录"逻辑) run_high_value_rooms: set = set() def _touch_high_value_room( @@ -2933,8 +3320,10 @@ class fudai_analyse: c0 = c0[:10] return f"unknown@{ft}_{pv_i}_{c0}" - # 启动即写一次状态文件:Web 端可立即显示“脚本在跑/更新时间” + # 启动即写一次状态文件:Web 端可立即显示"脚本在跑/更新时间" + print("[启动] 准备写入初始状态文件") _write_reservations_state("init") + print("[启动] 初始状态文件写入完成,准备进入主循环") # 预约回退后,校验通过时可“直接复用已打开的详情”,避免再次找福袋/误切 forced_detail = None @@ -4273,74 +4662,87 @@ class fudai_analyse: def _read_fudai_detail_once(label: str): """读取一次福袋详情(不额外触发其它截图)。返回 (content,time,participants,copies,value,countdown_result,abnormal,reasons)""" - self._shot_and_diagnose("福袋详情", "识别内容/倒计时/价值({})".format(label), self.device_id) + # 速度优化:只在第一次调用时截图和诊断,后续重试时复用已有截图 + if label == "first": + self._shot_and_diagnose("福袋详情", "识别内容/倒计时/价值({})".format(label), self.device_id) + # 后续重试时仅确保有最新截图,但跳过诊断以节省时间 + elif label in ("retry1", "reopen"): + try: + self.operation.get_screenshot(self.device_id) + except Exception: + pass renwu = self.check_detail_height() fc, tt, participants, copies, pv = self.get_fudai_contain(renwu) cd = self.operation.check_countdown(tt) abnormal, reasons = _is_abnormal_time_value(tt, pv, cd) - # 额外检测任务区是否包含“观看X分钟”提示(尤其在存在任务时要优先跳过) + # 速度优化:只在第一次识别时检测任务区,减少OCR调用 + # 额外检测任务区是否包含"观看X分钟"提示(尤其在存在任务时要优先跳过) try: - if renwu and int(renwu) > 0: - # 先对用户指定的两个精确点附近区域直接截图并 OCR(使用绝对像素坐标) - task_texts = [] - try: - # 使用用户提供的矩形区域 (50,1675)-(1029,1920) - self.operation.cut_pic((50, 1675), (1029, 1920), '', 'task_user_area') - # 确认文件是否写入到 pic/ 下(检查两种可能的 pic 目录位置) - pic_name = 'task_user_area.png' - p1 = os.path.join(os.getcwd(), 'pic', pic_name) - p2 = os.path.join(os.path.dirname(__file__), 'pic', pic_name) - used_path = None - if os.path.exists(p1): - used_path = p1 - elif os.path.exists(p2): - used_path = p2 - if not used_path: - print(f"[OCR调试] task_user_area 文件未找到: checked {p1} and {p2}") - txt_area = "" - else: - # 使用轻量快速 OCR 函数,减少识别耗时 - txt_area = str(self.operation.analyse_pic_word_fast('task_user_area', 0, max_side=600) or "").strip() - print(f"[OCR调试] task_user_area file={used_path} text={txt_area}") - if txt_area: - task_texts.append(txt_area) - except Exception: - pass - - # 备选较宽区域,作为兜底 - boxes = [ - (360, 920, 1020, 1120), - (360, 980, 1020, 1240), - (360, 1000, 1020, 1280), - ] - for idx_b, b in enumerate(boxes, 1): - try: - x1, y1, x2, y2 = b - # 使用 douyin 的切图封装以适配分辨率缩放 - self.cut_pic(x1, y1, x2, y2, '', f'fudai_task_once_{idx_b}', self.y_pianyi) - # 兜底识别同样使用快速模式以缩短单次耗时 - txt = str(self.operation.analyse_pic_word_fast(f'fudai_task_once_{idx_b}', 0, max_side=600) or "").strip() - if txt: - task_texts.append(txt) - except Exception: - continue - full_task_txt = fc or "" + " " + " ".join(task_texts) + if renwu and int(renwu) > 0 and label == "first": + # 速度优化:先检查福袋内容中是否已经包含"观看",避免不必要的OCR chinese_num_chars = "零一二三四五六七八九十百千两" patt_watch = rf"(?:需?看|观看|看)(?:直播)?\s*(?:\d+|[{chinese_num_chars}]+)\s*分钟" - if re.search(patt_watch, full_task_txt): + if fc and re.search(patt_watch, fc): reasons = list(reasons) if reasons else [] reasons.append('watch_task_detected') + else: + # 只在福袋内容中未检测到时才进行OCR识别 + task_texts = [] + try: + # 优先使用用户指定的精确区域(速度最快,范围最小) + self.operation.cut_pic((50, 1675), (1029, 1920), '', 'task_user_area') + pic_name = 'task_user_area.png' + p1 = os.path.join(os.getcwd(), 'pic', pic_name) + p2 = os.path.join(os.path.dirname(__file__), 'pic', pic_name) + used_path = None + if os.path.exists(p1): + used_path = p1 + elif os.path.exists(p2): + used_path = p2 + if used_path: + txt_area = str(self.operation.analyse_pic_word('task_user_area', 0) or "").strip() + if txt_area: + task_texts.append(txt_area) + print(f"[OCR调试] task_user_area file={used_path} text={txt_area}") + except Exception: + pass + + # 速度优化:如果第一个区域已识别到观看任务,跳过备选区域OCR + full_task_txt = (fc or "") + " " + " ".join(task_texts) if task_texts else (fc or "") + if not re.search(patt_watch, full_task_txt): + # 优化:调整任务区域坐标,减少无关干扰,提高识别精度 + # 只在第一个区域未检测到时,才OCR备选区域(最多2个,而非3个) + boxes = [ + (360, 980, 1000, 1240), # 优先识别中间区域(最常见)- 缩小宽度减少干扰 + (360, 1000, 1000, 1280), # 备选区域 - 缩小宽度减少干扰 + ] + for idx_b, b in enumerate(boxes, 1): + try: + x1, y1, x2, y2 = b + self.cut_pic(x1, y1, x2, y2, '', f'fudai_task_once_{idx_b}', self.y_pianyi) + txt = str(self.operation.analyse_pic_word(f'fudai_task_once_{idx_b}', 0) or "").strip() + if txt: + task_texts.append(txt) + # 速度优化:一旦检测到观看任务,立即停止后续OCR + full_task_txt = (fc or "") + " " + " ".join(task_texts) + if re.search(patt_watch, full_task_txt): + break + except Exception: + continue + full_task_txt = (fc or "") + " " + " ".join(task_texts) if task_texts else (fc or "") + + if re.search(patt_watch, full_task_txt): + reasons = list(reasons) if reasons else [] + reasons.append('watch_task_detected') except Exception: pass - print("[详情] {} 内容='{}' 时间='{}' 价值={} 倒计时解析={} 异常={} 原因={}".format( - label, - (fc or "-")[:80], - (tt or "-")[:30], - pv, - cd if cd else "None", - abnormal, - ",".join(reasons) if reasons else "-", - )) + self._log_kv("详情", f"读取福袋详情({label})", + content=(fc or "-")[:60], + time_text=(tt or "-")[:30], + value_yuan=pv, + countdown=cd if cd else "未解析", + abnormal=abnormal, + reasons=",".join(reasons) if reasons else "无") return fc, tt, participants, copies, pv, cd, abnormal, reasons def _read_fudai_detail_with_retries(fudai_x: int): @@ -4392,9 +4794,12 @@ class fudai_analyse: return None if abnormal: delay_s = float(self.fudai_abnormal_reopen_delay_seconds or 0.0) + # 速度优化:缩短重开延迟(从默认值或配置值减少20%) + delay_s = max(0.5, delay_s * 0.8) # 最少0.5秒,减少20%延迟 print("[异常] 时间/价值异常仍未恢复:关闭并重开福袋详情,延迟 {} 秒再截图".format(delay_s)) _close_fudai_detail(fudai_x, reason="异常/关闭重开") - self.operation.delay(0.8) + # 速度优化:缩短关闭后的等待时间(从0.8秒减少到0.5秒) + self.operation.delay(0.5) # reopen _ensure_fudai_detail_open(int(fudai_x), quick=True) self.operation.delay(delay_s) @@ -4416,7 +4821,12 @@ class fudai_analyse: return None return fc, tt, participants, copies, pv, cd + print("[启动] 进入主循环") + loop_count = 0 while True: + loop_count += 1 + if loop_count % 10 == 1: # 每10次循环打印一次,避免日志过多 + print(f"[主循环] 第 {loop_count} 次循环开始") # 支持网页端随时修改配置:定期 reload self._maybe_reload_config(2.0) @@ -4451,7 +4861,11 @@ class fudai_analyse: # 入口门禁:先截图判断是否处于直播间;若不在直播间则先进入直播间,再开始判断福袋。 try: # 只截图一次,用这张截图做阶段判断 + if loop_count <= 3 or loop_count % 20 == 0: + print(f"[主循环] 第 {loop_count} 次:准备截图判断当前状态") self._shot_and_diagnose("主循环", "先判断是否在直播间", self.device_id, diagnose=False) + if loop_count <= 3 or loop_count % 20 == 0: + print(f"[主循环] 第 {loop_count} 次:截图完成,开始诊断阶段") st0, seen0 = self._diagnose_stage_from_current_screen() try: self._last_diag_stage = st0 @@ -4461,6 +4875,120 @@ class fudai_analyse: except Exception: st0, seen0 = "LIVE_OR_UNKNOWN", "" + # 若当前截图诊断为推荐页面(RECOMMEND_PAGE),点击关注标签然后点击进入直播间 + try: + if st0 == "RECOMMEND_PAGE": + self._log_kv("流程", "检测到推荐页面,点击关注标签并进入直播间", stage=st0, seen=seen0) + try: + # 点击关注标签(顶部标签栏的关注标签,坐标基于1080x2400分辨率) + follow_tab_x = int(getattr(self, "yanghao_follow_tab_x", 712)) + follow_tab_y = int(getattr(self, "yanghao_follow_tab_y", 169)) + self.click(follow_tab_x, follow_tab_y) + print(f"检测到推荐页面,点击关注标签 -> ({follow_tab_x}, {follow_tab_y})") + self.operation.delay(2) + # 点击进入直播间的位置(连点两次) + enter_live_x = int(getattr(self, "yanghao_fallback_enter_live_x", 109)) + enter_live_y = int(getattr(self, "yanghao_fallback_enter_live_y", 376)) + self.click(enter_live_x, enter_live_y) + self.operation.delay(0.6) + self.click(enter_live_x, enter_live_y) + print(f"点击进入直播间位置 -> ({enter_live_x}, {enter_live_y}) 连点两次") + self.operation.delay(2) + continue # 继续下一轮循环 + except Exception as e: + print(f"处理推荐页面时出错: {e}") + # 如果出错,尝试回退 + try: + self.operation.click_back(self.device_id) + self.operation.delay(1) + except Exception: + pass + except Exception: + pass + + # 若当前截图诊断为 LIVE_OR_UNKNOWN,额外检查是否是推荐页面(可能误判) + try: + if st0 == "LIVE_OR_UNKNOWN": + # 复用推荐页面的识别逻辑,检查标题区域 + t_recommend_check = "" + t_guess_like_check = "" + try: + # 识别推荐页面标题区域(和 RECOMMEND_PAGE 一样的区域) + self.cut_pic(200, 80, 880, 280, '', 'diag_recommend_title_check') + t_recommend_check = str(self.operation.analyse_pic_word('diag_recommend_title_check') or "") + except Exception: + pass + try: + # 检查"猜你喜欢"区域(和 RECOMMEND_PAGE 一样的区域) + self.cut_pic(440, 1570, 640, 1640, '', 'diag_guess_like_check') + t_guess_like_check = str(self.operation.analyse_pic_word('diag_guess_like_check', 1) or "") + except Exception: + pass + + # 如果识别到推荐页面的特征,执行和 RECOMMEND_PAGE 一样的操作 + is_recommend_page = False + if "推荐" in t_recommend_check: + if "直播" in t_recommend_check or "关注" in t_recommend_check: + is_recommend_page = True + elif "猜你喜欢" in t_guess_like_check or "猜你喜欢" in t_recommend_check: + is_recommend_page = True + else: + is_recommend_page = True # 只有"推荐"关键词也判定为推荐页面 + elif "猜你喜欢" in t_guess_like_check: + is_recommend_page = True + + if is_recommend_page: + self._log_kv("流程", "LIVE_OR_UNKNOWN阶段检测到推荐页面,点击关注标签并进入直播间", stage=st0, seen=seen0) + try: + # 点击关注标签(顶部标签栏的关注标签,坐标基于1080x2400分辨率) + follow_tab_x = int(getattr(self, "yanghao_follow_tab_x", 712)) + follow_tab_y = int(getattr(self, "yanghao_follow_tab_y", 169)) + self.click(follow_tab_x, follow_tab_y) + print(f"LIVE_OR_UNKNOWN阶段检测到推荐页面,点击关注标签 -> ({follow_tab_x}, {follow_tab_y})") + self.operation.delay(2) + # 点击进入直播间的位置(连点两次) + enter_live_x = int(getattr(self, "yanghao_fallback_enter_live_x", 109)) + enter_live_y = int(getattr(self, "yanghao_fallback_enter_live_y", 376)) + self.click(enter_live_x, enter_live_y) + self.operation.delay(0.6) + self.click(enter_live_x, enter_live_y) + print(f"点击进入直播间位置 -> ({enter_live_x}, {enter_live_y}) 连点两次") + self.operation.delay(2) + continue # 继续下一轮循环 + except Exception as e: + print(f"LIVE_OR_UNKNOWN阶段处理推荐页面时出错: {e}") + # 如果出错,尝试回退 + try: + self.operation.click_back(self.device_id) + self.operation.delay(1) + except Exception: + pass + except Exception: + pass + + # 若当前截图诊断为关注列表(FOLLOW_LIST),点击关注位置并回到直播间 + try: + if st0 == "FOLLOW_LIST": + self._log_kv("流程", "检测到关注列表,点击关注位置并返回直播间", stage=st0, seen=seen0) + try: + # 点击关注位置(关注列表页中的位置,进入直播间列表) + self.click(390, 590) + print("检测到关注列表,点击关注位置进入直播间列表") + self.operation.delay(2) + # 进入直播间 + self.into_zhibo_from_list() + continue # 继续下一轮循环 + except Exception as e: + print(f"处理关注列表时出错: {e}") + # 如果出错,尝试回退 + try: + self.operation.click_back(self.device_id) + self.operation.delay(1) + except Exception: + pass + except Exception: + pass + # 若当前截图诊断为结果弹窗(FUDai_RESULT),则根据识别内容立即处理(避免后续误判/延迟) try: if st0 == "FUDai_RESULT": @@ -4526,7 +5054,9 @@ class fudai_analyse: try: ex = int(self.yanghao_fallback_enter_live_x) ey = int(self.yanghao_fallback_enter_live_y) - print(f"[自救] 点击进入直播间 -> ({ex},{ey})") + print(f"[自救] 点击进入直播间 -> ({ex},{ey}) 连点两次") + self.click(ex, ey) + self.operation.delay(0.6) self.click(ex, ey) self.operation.delay(2.0) except Exception: @@ -4824,12 +5354,14 @@ class fudai_analyse: swipe_times = 0 # 滑动次数归0 continue elif wait_times >= 4: # 如果福袋不存在,且不需要切换直播间,但等待了很久 - if swipe_times < 15: # 上划次数不到10次,就继续上划 - swipe_up_switch("直播间等待2分钟无福袋,上划切换直播间") - # self.operation.delay(5) + self._log_kv("切换", "无福袋等待次数达到阈值,准备切换直播间", wait_times=wait_times, swipe_times=swipe_times) + if swipe_times < 15: # 上划次数不到15次,就继续上划 + swipe_up_switch("直播间等待{}次无福袋,上划切换直播间".format(wait_times)) + wait_times = 0 # 切换后重置等待次数 + self.operation.delay(post_switch_delay_s) continue else: - print("直播间等待2分钟无福袋,退出返回直播列表") + print("直播间等待{}次无福袋且已切换{}次,退出返回直播列表".format(wait_times, swipe_times)) _clear_reservations("等待过久/回到列表") self.back_to_zhibo_list() self.into_zhibo_from_list() @@ -4838,6 +5370,8 @@ class fudai_analyse: self.operation.delay(post_switch_delay_s) continue else: # 如果福袋不存在,且不需要切换直播间,且等待轮数不够 + wait_times += 1 # 增加等待次数,累计4次后触发切换 + self._log_kv("等待", "直播间无福袋,等待计数", wait_times=wait_times, max_wait=4) secs = int(self._yanghao_get_recommend_seconds() or 60) if reservations and self.high_value_fudai_enabled: # 检查是否已到参与窗口 @@ -4894,7 +5428,7 @@ class fudai_analyse: reason0 = "" self._enter_live_fudai_logged = True try: - print("[性能] 进入直播间到识别福袋内容耗时:{:.2f} 秒 进入原因={}".format(round(dt, 2), reason0)) + self._log_kv("性能", "进入直播间到识别福袋内容耗时", seconds=round(dt, 2), enter_reason=reason0) except Exception: pass try: @@ -4933,7 +5467,7 @@ class fudai_analyse: continue if self.max_participants and participants > self.max_participants: _close_fudai_detail(x, reason="参与人数过高") - print("参与人数{} > 阈值{},不参与,关闭福袋详情".format(participants, self.max_participants)) + self._log_kv("过滤", "参与人数超过阈值,跳过", participants=participants, max_participants=self.max_participants) self.operation.delay(1) if needswitch: swipe_up_switch("参与人数过高,上划切换直播间") @@ -4941,7 +5475,7 @@ class fudai_analyse: continue if self.min_prize_value_yuan and prize_value_yuan and prize_value_yuan < self.min_prize_value_yuan: _close_fudai_detail(x, reason="奖品价值过低") - print("奖品价值{}元 < 阈值{}元,不参与,关闭福袋详情".format(prize_value_yuan, self.min_prize_value_yuan)) + self._log_kv("过滤", "奖品价值低于阈值,跳过", value_yuan=prize_value_yuan, min_value_yuan=self.min_prize_value_yuan) self.operation.delay(1) if needswitch: swipe_up_switch("直播间奖品价值过低,上划切换直播间") diff --git a/image/README/1765803197033.png b/image/README/1765803197033.png new file mode 100644 index 0000000..24449ed Binary files /dev/null and b/image/README/1765803197033.png differ diff --git a/image/README/1765803204369.png b/image/README/1765803204369.png new file mode 100644 index 0000000..be6e56e Binary files /dev/null and b/image/README/1765803204369.png differ diff --git a/state/high_value_rooms.json b/state/high_value_rooms.json index 21c7f37..4f6b087 100644 --- a/state/high_value_rooms.json +++ b/state/high_value_rooms.json @@ -1,8 +1,666 @@ { - "updated_ts": 1765802500.1787617, + "updated_ts": 1765874930.950471, "reason": "reservation", - "total": 33, + "total": 58, "rooms": [ + { + "first_seen_ts": 1765736209.4437785, + "last_seen_ts": 1765874930.950471, + "seen_count": 22, + "pos_seen": 2, + "pos_updated_ts": 1765874930.950471, + "room_title_raw_last": "梵象名品...", + "alias_raw": [ + "梵象名品..." + ], + "key_kind": "norm", + "last_content": "Camudin黑水鬼系列黑盘钢带款(附带调表器)", + "last_prize_value_yuan": 999.0, + "max_prize_value_yuan": 5500.0, + "room_title": "梵象名品" + }, + { + "first_seen_ts": 1765865699.60157, + "last_seen_ts": 1765874882.830245, + "seen_count": 12, + "pos_seen": 1, + "pos_updated_ts": 1765874882.830245, + "room_title_raw_last": "陌玉珠宝~", + "alias_raw": [ + "陌玉珠宝", + "陌玉珠宝二", + "陌玉珠宝~" + ], + "key_kind": "norm", + "last_content": "天然缅料A货翡翠甜甜圈吊坠/一件(微瑕)多样性:", + "last_prize_value_yuan": 1580.0, + "max_prize_value_yuan": 3880.0, + "room_title": "陌玉珠宝", + "alias_norm": [ + "陌玉珠宝二" + ], + "merged_from_last": "陌玉珠宝二", + "merged_ratio_last": 0.8888888888888888 + }, + { + "first_seen_ts": 1765787027.4476137, + "last_seen_ts": 1765874595.4136896, + "seen_count": 8, + "pos_seen": 5, + "pos_updated_ts": 1765874595.4136896, + "room_title_raw_last": "三火孙...", + "alias_raw": [ + "三火孙...", + "三火·孙.." + ], + "key_kind": "norm", + "last_content": "【知音专属】创维娱乐影音畅享智能平板电脑", + "last_prize_value_yuan": 1199.0, + "max_prize_value_yuan": 1699.0, + "room_title": "三火孙" + }, + { + "first_seen_ts": 1765768902.1252618, + "last_seen_ts": 1765874070.2471976, + "seen_count": 21, + "pos_seen": 1, + "pos_updated_ts": 1765874070.2471976, + "room_title_raw_last": "凡客陈年", + "alias_raw": [ + "凡客陈年?", + "凡客陈年" + ], + "key_kind": "norm", + "last_content": "小米RedmiPadSE新款平板11英寸护眼大屏全金属", + "last_prize_value_yuan": 1199.0, + "max_prize_value_yuan": 5999.0, + "room_title": "凡客陈年" + }, + { + "first_seen_ts": 1765871013.503363, + "last_seen_ts": 1765871013.503363, + "seen_count": 1, + "pos_seen": 2, + "pos_updated_ts": 1765871013.503363, + "room_title_raw_last": "蒂碗5惠T中年快乐796万米场", + "alias_raw": [ + "蒂碗5惠T中年快乐796万米场" + ], + "key_kind": "norm", + "last_content": "小米红米/redmi14C智能手机:", + "last_prize_value_yuan": 899.0, + "max_prize_value_yuan": 899.0, + "room_title": "蒂碗5惠T中年快乐796万米场" + }, + { + "first_seen_ts": 1765867559.3415358, + "last_seen_ts": 1765869366.0778244, + "seen_count": 2, + "pos_seen": 2, + "pos_updated_ts": 1765869366.0778244, + "room_title_raw_last": "帝克5千惠?福1喜1年快乐76.3万本场", + "alias_raw": [ + "帝克5千惠?福1喜1年快乐76.3万本场", + "帝55千惠?福1年快乐69.5万本场占先" + ], + "key_kind": "norm", + "last_content": "小米红米/redmi14C智能手机", + "last_prize_value_yuan": 899.0, + "max_prize_value_yuan": 899.0, + "room_title": "帝55千惠福1年快乐695万本场占先", + "alias_norm": [ + "帝克5千惠福1喜1年快乐763万本场" + ], + "merged_from_last": "帝克5千惠福1喜1年快乐763万本场", + "merged_ratio_last": 0.8333333333333334 + }, + { + "first_seen_ts": 1765868994.1773136, + "last_seen_ts": 1765868994.1773136, + "seen_count": 1, + "pos_seen": 3, + "pos_updated_ts": 1765868994.1773136, + "room_title_raw_last": "帝克5中Y年快乐759万本场占先", + "alias_raw": [ + "帝克5中Y年快乐759万本场占先" + ], + "key_kind": "norm", + "last_content": "小米红米/redmi14C智能手机", + "last_prize_value_yuan": 899.0, + "max_prize_value_yuan": 899.0, + "room_title": "帝克5中Y年快乐759万本场占先" + }, + { + "first_seen_ts": 1765868133.376968, + "last_seen_ts": 1765868133.376968, + "seen_count": 1, + "pos_seen": 2, + "pos_updated_ts": 1765868133.376968, + "room_title_raw_last": "惠G51年快乐", + "alias_raw": [ + "惠G51年快乐" + ], + "key_kind": "norm", + "last_content": "小米红米/redmi14C智能手机!", + "last_prize_value_yuan": 899.0, + "max_prize_value_yuan": 899.0, + "room_title": "惠G51年快乐" + }, + { + "first_seen_ts": 1765862896.2405748, + "last_seen_ts": 1765868089.5437562, + "seen_count": 3, + "pos_seen": 1, + "pos_updated_ts": 1765868089.5437562, + "room_title_raw_last": "郭小胖4", + "alias_raw": [ + "郭小胖4", + "郭小胖2", + "郭小胖16" + ], + "key_kind": "norm", + "last_content": "新拍立得mini12一次成像相机可选创意礼盒随机款:", + "last_prize_value_yuan": 1499.0, + "max_prize_value_yuan": 2999.0, + "room_title": "郭小胖16", + "alias_norm": [ + "郭小胖4", + "郭小胖2" + ], + "merged_from_last": "郭小胖4", + "merged_ratio_last": 1.0 + }, + { + "first_seen_ts": 1765867412.3163621, + "last_seen_ts": 1765867412.3163621, + "seen_count": 1, + "pos_seen": 1, + "pos_updated_ts": 1765867412.3163621, + "room_title_raw_last": "郭小胖1675.6万", + "alias_raw": [ + "郭小胖1675.6万" + ], + "key_kind": "norm", + "last_content": "新拍立得mini12一次成像相机可选创意礼盒随机款!", + "last_prize_value_yuan": 1499.0, + "max_prize_value_yuan": 1499.0, + "room_title": "郭小胖16756万" + }, + { + "first_seen_ts": 1765866220.035989, + "last_seen_ts": 1765866220.035989, + "seen_count": 1, + "pos_seen": 5, + "pos_updated_ts": 1765866220.035989, + "room_title_raw_last": "蒂克5千惠仕年快乐", + "alias_raw": [ + "蒂克5千惠仕年快乐" + ], + "key_kind": "norm", + "last_content": "小米RedmiPadSE红米平板SE电脑系列高刷高清全:", + "last_prize_value_yuan": 1099.0, + "max_prize_value_yuan": 1099.0, + "room_title": "蒂克5千惠仕年快乐" + }, + { + "first_seen_ts": 1765865657.983957, + "last_seen_ts": 1765865657.983957, + "seen_count": 1, + "pos_seen": 4, + "pos_updated_ts": 1765865657.983957, + "room_title_raw_last": "M1作业帮数E牌伊", + "alias_raw": [ + "M1作业帮数E牌伊" + ], + "key_kind": "norm", + "last_content": "【粉丝专属】联想平板电脑10.1英寸大屏护眼学习娱..:", + "last_prize_value_yuan": 1999.0, + "max_prize_value_yuan": 1999.0, + "room_title": "M1作业帮数E牌伊" + }, + { + "first_seen_ts": 1765865500.2742574, + "last_seen_ts": 1765865500.2742574, + "seen_count": 1, + "pos_seen": 1, + "pos_updated_ts": 1765865500.2742574, + "room_title_raw_last": "郭小胖16.业T2ce267.67未", + "alias_raw": [ + "郭小胖16.业T2ce267.67未" + ], + "key_kind": "norm", + "last_content": "新拍立得mini12一次成像相机可选创意礼盒随机款!", + "last_prize_value_yuan": 1499.0, + "max_prize_value_yuan": 1499.0, + "room_title": "郭小胖16业T2ce26767未" + }, + { + "first_seen_ts": 1765865181.18486, + "last_seen_ts": 1765865181.18486, + "seen_count": 1, + "pos_seen": 0, + "pos_updated_ts": 1765865181.18486, + "room_title_raw_last": "蒂克5千惠?花年快乐586万本场占秀", + "alias_raw": [ + "蒂克5千惠?花年快乐586万本场占秀" + ], + "key_kind": "norm", + "last_content": "小米RedmiPadSE红米平板SE电脑系列高刷高清全", + "last_prize_value_yuan": 1299.0, + "max_prize_value_yuan": 1299.0, + "room_title": "蒂克5千惠花年快乐586万本场占秀" + }, + { + "first_seen_ts": 1765862985.134165, + "last_seen_ts": 1765863109.3533714, + "seen_count": 1, + "pos_seen": 4, + "pos_updated_ts": 1765863109.3533714, + "room_title_raw_last": "验漳州商城直", + "alias_raw": [ + "验漳州商城直", + "验漳州商城" + ], + "key_kind": "norm", + "last_content": "【郭小胖专属】ipad-10代官方正品不含保护套", + "last_prize_value_yuan": 2999.0, + "max_prize_value_yuan": 2999.0, + "alias_norm": [ + "验漳州商城直" + ], + "merged_from_last": "验漳州商城直", + "merged_ratio_last": 0.9090909090909091, + "room_title": "验漳州商城" + }, + { + "first_seen_ts": 1765862574.8292146, + "last_seen_ts": 1765862896.2297833, + "seen_count": 1, + "pos_seen": 0, + "pos_updated_ts": 1765862896.2297833, + "room_title_raw_last": "郭小胖16", + "alias_raw": [ + "郭小胖16", + "郭小胖16.电LceTi" + ], + "key_kind": "norm", + "last_content": "【郭小胖专属】ipad-10代官方正品不含保护套", + "last_prize_value_yuan": 0.0, + "max_prize_value_yuan": 2999.0, + "room_title": "郭小胖16电LceTi", + "alias_norm": [ + "郭小胖16" + ], + "merged_from_last": "郭小胖16", + "merged_ratio_last": 0.86 + }, + { + "first_seen_ts": 1765801208.2099712, + "last_seen_ts": 1765862620.9980066, + "seen_count": 2, + "pos_seen": 2, + "pos_updated_ts": 1765862620.9980066, + "room_title_raw_last": "帝克5千惠?任年快乐N", + "alias_raw": [ + "帝克5千惠?任年快乐N", + "帝克5惠任年快乐24" + ], + "key_kind": "norm", + "last_content": "AppleiPad11英寸A16芯片2025款平板电脑", + "last_prize_value_yuan": 2999.0, + "max_prize_value_yuan": 2999.0, + "room_title": "帝克5惠任年快乐24", + "alias_norm": [ + "帝克5千惠任年快乐N" + ], + "merged_from_last": "帝克5千惠任年快乐N", + "merged_ratio_last": 0.875 + }, + { + "first_seen_ts": 1765862230.4826186, + "last_seen_ts": 1765862230.4826186, + "seen_count": 1, + "pos_seen": 12, + "pos_updated_ts": 1765862230.4826186, + "room_title_raw_last": "U庆E抖音旗舰", + "alias_raw": [ + "U庆E抖音旗舰" + ], + "key_kind": "norm", + "last_content": "【粉丝专属】联想平板电脑福10.1英寸大屏护眼学习娱.", + "last_prize_value_yuan": 1999.0, + "max_prize_value_yuan": 1999.0, + "room_title": "U庆E抖音旗舰" + }, + { + "first_seen_ts": 1765861982.8982053, + "last_seen_ts": 1765861982.8982053, + "seen_count": 1, + "pos_seen": 7, + "pos_updated_ts": 1765861982.8982053, + "room_title_raw_last": "电5年快乐39", + "alias_raw": [ + "电5年快乐39" + ], + "key_kind": "norm", + "last_content": "AppleiPad11英寸A16芯片2025款平板电脑", + "last_prize_value_yuan": 2999.0, + "max_prize_value_yuan": 2999.0, + "room_title": "电5年快乐39" + }, + { + "first_seen_ts": 1765860282.4970741, + "last_seen_ts": 1765861831.362871, + "seen_count": 3, + "pos_seen": 7, + "pos_updated_ts": 1765861831.362871, + "room_title_raw_last": "国岳16号.", + "alias_raw": [ + "国岳16号.", + "国岳16号" + ], + "key_kind": "norm", + "last_content": "【国岳专属】iPhone17手机256G颜色随机门", + "last_prize_value_yuan": 5999.0, + "max_prize_value_yuan": 5999.0, + "room_title": "国岳16号" + }, + { + "first_seen_ts": 1765860613.7811863, + "last_seen_ts": 1765860613.7811863, + "seen_count": 1, + "pos_seen": 0, + "pos_updated_ts": 1765860613.7811863, + "room_title_raw_last": "U庆快00抖音旗舰", + "alias_raw": [ + "U庆快00抖音旗舰" + ], + "key_kind": "norm", + "last_content": "【粉丝专属联想平板电脑福10.1英寸大屏护眼学习娱.", + "last_prize_value_yuan": 1999.0, + "max_prize_value_yuan": 1999.0, + "room_title": "U庆快00抖音旗舰" + }, + { + "first_seen_ts": 1765734737.806301, + "last_seen_ts": 1765860225.3693788, + "seen_count": 3, + "pos_seen": 4, + "pos_updated_ts": 1765860225.3693788, + "room_title_raw_last": "作业帮数", + "alias_raw": [ + "作业帮数", + "作业帮数d季·双" + ], + "key_kind": "norm", + "last_content": "【粉丝专属联想平板电脑福10.1英寸大屏护眼学习娱.", + "last_prize_value_yuan": 1999.0, + "max_prize_value_yuan": 1999.0, + "room_title": "作业帮数d季双", + "alias_norm": [ + "作业帮数" + ], + "merged_from_last": "作业帮数", + "merged_ratio_last": 0.86 + }, + { + "first_seen_ts": 1765853082.916173, + "last_seen_ts": 1765853082.916173, + "seen_count": 1, + "pos_seen": 12, + "pos_updated_ts": 1765853082.916173, + "room_title_raw_last": "我是晴天", + "alias_raw": [ + "我是晴天" + ], + "key_kind": "norm", + "last_content": "【晴天专属】:华为畅享70S8+128G智能手机原装正一", + "last_prize_value_yuan": 1699.0, + "max_prize_value_yuan": 1699.0, + "room_title": "我是晴天" + }, + { + "first_seen_ts": 1765852735.8616374, + "last_seen_ts": 1765852735.8616374, + "seen_count": 1, + "pos_seen": 2, + "pos_updated_ts": 1765852735.8616374, + "room_title_raw_last": "帝克5惠T+快乐33万本场", + "alias_raw": [ + "帝克5惠T+快乐33万本场" + ], + "key_kind": "norm", + "last_content": "AppleiPad11英寸A16芯片2025款平板电脑", + "last_prize_value_yuan": 2999.0, + "max_prize_value_yuan": 2999.0, + "room_title": "帝克5惠T快乐33万本场" + }, + { + "first_seen_ts": 1765850749.6202497, + "last_seen_ts": 1765850749.6202497, + "seen_count": 1, + "pos_seen": 1, + "pos_updated_ts": 1765850749.6202497, + "room_title_raw_last": "香香生活号", + "alias_raw": [ + "香香生活号" + ], + "key_kind": "norm", + "last_content": "便携式迷你小型宿舍手持电熨斗挂烫机熨烫机衣服家..", + "last_prize_value_yuan": 799.0, + "max_prize_value_yuan": 799.0, + "room_title": "香香生活号" + }, + { + "first_seen_ts": 1765818808.158832, + "last_seen_ts": 1765819942.8913167, + "seen_count": 3, + "pos_seen": 12, + "pos_updated_ts": 1765819942.8913167, + "room_title_raw_last": "HW-流星", + "alias_raw": [ + "HW-流星" + ], + "key_kind": "norm", + "last_content": "【金钞】2025蛇年金色工艺品节日礼品纪念礼物币..", + "last_prize_value_yuan": 999.0, + "max_prize_value_yuan": 999.0, + "room_title": "HW流星" + }, + { + "first_seen_ts": 1765797819.8754272, + "last_seen_ts": 1765813971.1983802, + "seen_count": 12, + "pos_seen": 3, + "pos_updated_ts": 1765813971.1983802, + "room_title_raw_last": "李亚鹏今...", + "alias_raw": [ + "李亚鹏今.", + "李亚鹏今.M", + "李亚鹏今..." + ], + "key_kind": "norm", + "last_content": "【粉丝专属】联想平板电脑福10.1英寸大屏护眼学习娱.", + "last_prize_value_yuan": 1999.0, + "max_prize_value_yuan": 1999.0, + "room_title": "李亚鹏今", + "alias_norm": [ + "李亚鹏今M" + ], + "merged_from_last": "李亚鹏今M", + "merged_ratio_last": 0.8888888888888888 + }, + { + "first_seen_ts": 1765810832.630025, + "last_seen_ts": 1765810832.630025, + "seen_count": 1, + "pos_seen": 1, + "pos_updated_ts": 1765810832.630025, + "room_title_raw_last": "预选100一枝梅14...", + "alias_raw": [ + "预选100一枝梅14..." + ], + "key_kind": "norm", + "last_content": "【梅姐专属】iPhone17256GB颜色随机发", + "last_prize_value_yuan": 5999.0, + "max_prize_value_yuan": 5999.0, + "room_title": "预选100一枝梅14" + }, + { + "first_seen_ts": 1765772560.378592, + "last_seen_ts": 1765810792.9903457, + "seen_count": 20, + "pos_seen": 0, + "pos_updated_ts": 1765810792.9903457, + "room_title_raw_last": "彩虹夫妇.", + "alias_raw": [ + "彩虹夫妇.", + "彩虹夫妇L?", + "彩虹夫妇...", + "彩虹夫妇.2道天团1291.", + "彩虹夫妇..2道天团", + "彩虹夫妇..?", + "彩虹夫妇.2馄直天团987.万", + "彩虹夫妇.." + ], + "key_kind": "norm", + "last_content": "【彩虹夫妇专属】适用于苹/果17256颜色随机", + "last_prize_value_yuan": 6999.0, + "max_prize_value_yuan": 6999.0, + "room_title": "彩虹夫妇", + "alias_norm": [ + "彩虹夫妇L", + "彩虹夫妇2道天团1291", + "彩虹夫妇2道天团", + "彩虹夫妇2馄直天团987万" + ], + "merged_from_last": "彩虹夫妇L", + "merged_ratio_last": 0.8888888888888888 + }, + { + "first_seen_ts": 1765768936.3513777, + "last_seen_ts": 1765809624.6953695, + "seen_count": 7, + "pos_seen": 0, + "pos_updated_ts": 1765809624.6953695, + "room_title_raw_last": "彩虹夫妇直天团", + "alias_raw": [ + "彩虹夫妇直天团", + "彩虹夫妇..2直天团", + "彩虹夫妇..2恒直天团", + "彩虹夫妇..直天团", + "彩虹夫妇..道天团", + "彩虹夫妇?道天团", + "彩虹夫妇道天团", + "彩虹夫妇" + ], + "key_kind": "norm", + "last_content": "【彩虹夫妇专属】适用于苹/果17256颜色随机", + "last_prize_value_yuan": 0.0, + "max_prize_value_yuan": 6999.0, + "alias_norm": [ + "彩虹夫妇2直天团", + "彩虹夫妇2恒直天团", + "彩虹夫妇道天团", + "彩虹夫妇" + ], + "merged_from_last": "彩虹夫妇2直天团", + "merged_ratio_last": 1.0, + "room_title": "彩虹夫妇直天团" + }, + { + "first_seen_ts": 1765777832.5013368, + "last_seen_ts": 1765809364.181525, + "seen_count": 8, + "pos_seen": 0, + "pos_updated_ts": 1765809364.181525, + "room_title_raw_last": "预选100一枝梅14...", + "alias_raw": [ + "预选100枝梅14...", + "预选100枝梅14.", + "预选100一枝梅14...", + "源送100一枝梅14.", + "预送100枝梅", + "预送100枝梅14..." + ], + "key_kind": "norm", + "last_content": "【梅姐专属iPhone17256GB颜色随机发", + "last_prize_value_yuan": 0.0, + "max_prize_value_yuan": 5999.0, + "room_title": "预送100枝梅14", + "alias_norm": [ + "预选100枝梅14", + "预选100一枝梅14", + "源送100一枝梅14", + "预送100枝梅" + ], + "merged_from_last": "预选100一枝梅14", + "merged_ratio_last": 0.8421052631578947 + }, + { + "first_seen_ts": 1765801075.5843241, + "last_seen_ts": 1765809323.6105647, + "seen_count": 7, + "pos_seen": 0, + "pos_updated_ts": 1765809323.6105647, + "room_title_raw_last": "值天团", + "alias_raw": [ + "值天团" + ], + "key_kind": "norm", + "last_content": "【云上叙】18K金麻花链-45cm", + "last_prize_value_yuan": 0.0, + "max_prize_value_yuan": 5999.0, + "room_title": "值天团" + }, + { + "first_seen_ts": 1765808436.353787, + "last_seen_ts": 1765808436.353787, + "seen_count": 1, + "pos_seen": 0, + "pos_updated_ts": 1765808436.353787, + "room_title_raw_last": "彩虹夫妇?道天团", + "alias_raw": [ + "彩虹夫妇?道天团" + ], + "key_kind": "norm", + "last_content": "【彩虹夫妇专属】适用于苹/果17256颜色随机", + "last_prize_value_yuan": 6999.0, + "max_prize_value_yuan": 6999.0, + "room_title": "彩虹夫妇道天团" + }, + { + "first_seen_ts": 1765806079.9554796, + "last_seen_ts": 1765806079.9554796, + "seen_count": 1, + "pos_seen": 9, + "pos_updated_ts": 1765806079.9554796, + "room_title_raw_last": "阿忠珠宝行", + "alias_raw": [ + "阿忠珠宝行" + ], + "key_kind": "norm", + "last_content": "【粉丝专属】适用于畅享9智能手机内含数据线", + "last_prize_value_yuan": 1099.0, + "max_prize_value_yuan": 1099.0, + "room_title": "阿忠珠宝行" + }, + { + "first_seen_ts": 1765803911.7424335, + "last_seen_ts": 1765803911.7424335, + "seen_count": 1, + "pos_seen": 3, + "pos_updated_ts": 1765803911.7424335, + "room_title_raw_last": "微信·现在", + "alias_raw": [ + "微信·现在" + ], + "key_kind": "norm", + "last_content": "小米红米/redmi14C智能手机", + "last_prize_value_yuan": 899.0, + "max_prize_value_yuan": 899.0, + "room_title": "微信现在" + }, { "first_seen_ts": 1765797952.1912286, "last_seen_ts": 1765802500.177762, @@ -57,57 +715,6 @@ "merged_from_last": "帝克5十年快乐", "merged_ratio_last": 0.8571428571428571 }, - { - "first_seen_ts": 1765797819.8754272, - "last_seen_ts": 1765802127.7268178, - "seen_count": 6, - "pos_seen": 2, - "pos_updated_ts": 1765802127.7268178, - "room_title_raw_last": "李亚鹏今.M", - "alias_raw": [ - "李亚鹏今.M", - "李亚鹏今..." - ], - "key_kind": "norm", - "last_content": "【粉丝专属】联想平板电脑福10.1英寸大屏护眼学习娱.", - "last_prize_value_yuan": 1999.0, - "max_prize_value_yuan": 1999.0, - "room_title": "李亚鹏今", - "alias_norm": [ - "李亚鹏今M" - ], - "merged_from_last": "李亚鹏今M", - "merged_ratio_last": 0.8888888888888888 - }, - { - "first_seen_ts": 1765772560.378592, - "last_seen_ts": 1765802090.7018776, - "seen_count": 12, - "pos_seen": 1, - "pos_updated_ts": 1765802090.7018776, - "room_title_raw_last": "彩虹夫妇", - "alias_raw": [ - "彩虹夫妇...", - "彩虹夫妇.2道天团1291.", - "彩虹夫妇..2道天团", - "彩虹夫妇..?", - "彩虹夫妇.2馄直天团987.万", - "彩虹夫妇..", - "彩虹夫妇" - ], - "key_kind": "norm", - "last_content": "【彩虹夫妇专属】适用于苹/果17256颜色随机", - "last_prize_value_yuan": 6999.0, - "max_prize_value_yuan": 6999.0, - "room_title": "彩虹夫妇", - "alias_norm": [ - "彩虹夫妇2道天团1291", - "彩虹夫妇2道天团", - "彩虹夫妇2馄直天团987万" - ], - "merged_from_last": "彩虹夫妇2道天团1291", - "merged_ratio_last": 0.86 - }, { "first_seen_ts": 1765777950.5447316, "last_seen_ts": 1765802039.672463, @@ -126,65 +733,6 @@ "max_prize_value_yuan": 5999.0, "room_title": "云上珠宝" }, - { - "first_seen_ts": 1765768936.3513777, - "last_seen_ts": 1765801460.0205128, - "seen_count": 6, - "pos_seen": 1, - "pos_updated_ts": 1765801460.0205128, - "room_title_raw_last": "彩虹夫妇..道天团", - "alias_raw": [ - "彩虹夫妇..道天团", - "彩虹夫妇?道天团", - "彩虹夫妇道天团", - "彩虹夫妇", - "彩虹夫妇.", - "彩虹夫妇直天团" - ], - "key_kind": "norm", - "last_content": "【彩虹夫妇专属】适用于苹/果17256颜色随机", - "last_prize_value_yuan": 6999.0, - "max_prize_value_yuan": 6999.0, - "alias_norm": [ - "彩虹夫妇道天团", - "彩虹夫妇" - ], - "merged_from_last": "彩虹夫妇道天团", - "merged_ratio_last": 0.8571428571428571, - "room_title": "彩虹夫妇直天团" - }, - { - "first_seen_ts": 1765801075.5843241, - "last_seen_ts": 1765801420.922197, - "seen_count": 2, - "pos_seen": 0, - "pos_updated_ts": 1765801420.922197, - "room_title_raw_last": "值天团", - "alias_raw": [ - "值天团" - ], - "key_kind": "norm", - "last_content": "【云上珠宝专属】iPhone17256GB颜色随机发", - "last_prize_value_yuan": 5999.0, - "max_prize_value_yuan": 5999.0, - "room_title": "值天团" - }, - { - "first_seen_ts": 1765801208.2099712, - "last_seen_ts": 1765801208.2099712, - "seen_count": 1, - "pos_seen": 3, - "pos_updated_ts": 1765801208.2099712, - "room_title_raw_last": "帝克5惠任年快乐24", - "alias_raw": [ - "帝克5惠任年快乐24" - ], - "key_kind": "norm", - "last_content": "小米红米/redmi14C智能手机", - "last_prize_value_yuan": 899.0, - "max_prize_value_yuan": 899.0, - "room_title": "帝克5惠任年快乐24" - }, { "first_seen_ts": 1765800850.9807138, "last_seen_ts": 1765800850.9807138, @@ -265,23 +813,6 @@ "max_prize_value_yuan": 799.0, "room_title": "糖果家居" }, - { - "first_seen_ts": 1765787027.4476137, - "last_seen_ts": 1765793514.5361085, - "seen_count": 6, - "pos_seen": 0, - "pos_updated_ts": 1765793514.5361085, - "room_title_raw_last": "三火孙...", - "alias_raw": [ - "三火孙...", - "三火·孙.." - ], - "key_kind": "norm", - "last_content": "【三火专属】新国标成人代步男女自行电车通用休闲.", - "last_prize_value_yuan": 1699.0, - "max_prize_value_yuan": 1699.0, - "room_title": "三火孙" - }, { "first_seen_ts": 1765793164.28917, "last_seen_ts": 1765793164.28917, @@ -298,39 +829,6 @@ "max_prize_value_yuan": 1699.0, "room_title": "三火孙流行乐主播新" }, - { - "first_seen_ts": 1765736209.4437785, - "last_seen_ts": 1765792379.2718184, - "seen_count": 7, - "pos_seen": 4, - "pos_updated_ts": 1765792379.2718184, - "room_title_raw_last": "梵象名品...", - "alias_raw": [ - "梵象名品..." - ], - "key_kind": "norm", - "last_content": "Camudin黑水鬼系列黑盘钢带款附带调表器", - "last_prize_value_yuan": 999.0, - "max_prize_value_yuan": 5500.0, - "room_title": "梵象名品" - }, - { - "first_seen_ts": 1765768902.1252618, - "last_seen_ts": 1765792008.9897602, - "seen_count": 7, - "pos_seen": 3, - "pos_updated_ts": 1765792008.9897602, - "room_title_raw_last": "凡客陈年?", - "alias_raw": [ - "凡客陈年?", - "凡客陈年" - ], - "key_kind": "norm", - "last_content": "小米RedmiPadSE新款平板11英寸护眼大屏全金属...", - "last_prize_value_yuan": 1199.0, - "max_prize_value_yuan": 1199.0, - "room_title": "凡客陈年" - }, { "first_seen_ts": 1765791974.5564253, "last_seen_ts": 1765791974.5564253, @@ -427,34 +925,6 @@ "max_prize_value_yuan": 1699.0, "room_title": "三火孙流行乐主播模TOP" }, - { - "first_seen_ts": 1765777832.5013368, - "last_seen_ts": 1765782102.7063458, - "seen_count": 4, - "pos_seen": 4, - "pos_updated_ts": 1765782102.7063458, - "room_title_raw_last": "预选100枝梅14.", - "alias_raw": [ - "预选100枝梅14.", - "预选100一枝梅14...", - "源送100一枝梅14.", - "预送100枝梅", - "预送100枝梅14..." - ], - "key_kind": "norm", - "last_content": "【梅姐专属】红米Redmi9A4+64G智能手机全新正品", - "last_prize_value_yuan": 999.0, - "max_prize_value_yuan": 5999.0, - "room_title": "预送100枝梅14", - "alias_norm": [ - "预选100枝梅14", - "预选100一枝梅14", - "源送100一枝梅14", - "预送100枝梅" - ], - "merged_from_last": "预选100枝梅14", - "merged_ratio_last": 0.8888888888888888 - }, { "first_seen_ts": 1765772781.066824, "last_seen_ts": 1765782058.454188, @@ -489,22 +959,6 @@ "max_prize_value_yuan": 2999.0, "room_title": "大大小小" }, - { - "first_seen_ts": 1765734737.806301, - "last_seen_ts": 1765737390.252383, - "seen_count": 2, - "pos_seen": 4, - "pos_updated_ts": 1765737390.252383, - "room_title_raw_last": "作业帮数d季·双", - "alias_raw": [ - "作业帮数d季·双" - ], - "key_kind": "norm", - "last_content": "智能通话儿童手表生活防水2实时查找安全呵护【颜色", - "last_prize_value_yuan": 899.0, - "max_prize_value_yuan": 899.0, - "room_title": "作业帮数d季双" - }, { "first_seen_ts": 1765736325.646862, "last_seen_ts": 1765736390.2576246, diff --git a/state/reservations.json b/state/reservations.json index e3a0fc4..552d33c 100644 --- a/state/reservations.json +++ b/state/reservations.json @@ -1,45 +1,27 @@ { - "updated_ts": 1765802511.5037608, - "reason": "queue_full_back", - "room_pos": 0, - "current_room_title": "米叻叻", - "current_room_title_raw": "米叻叻", + "updated_ts": 1765874930.9473379, + "reason": "add", + "room_pos": 2, + "current_room_title": "梵象名品", + "current_room_title_raw": "梵象名品...", "reservations": [ { - "prize_value_yuan": 5999.0, - "content": "【云上珠宝专属】iPhone17256GB颜色随机发", - "future_ts": 1765802647.294848, - "future_str": "2025-12-15 20:44:07", - "pos_seen": 0, - "room_title": "云上珠宝", - "room_title_raw": "云上珠宝" - }, - { - "prize_value_yuan": 599.0, - "content": "【空气炸锅】多功能家用烤箱大容量全自动电烤箱空", - "future_ts": 1765802908.127129, - "future_str": "2025-12-15 20:48:28", - "pos_seen": 5, - "room_title": "米叻叻", - "room_title_raw": "米叻叻" - }, - { - "prize_value_yuan": 6999.0, - "content": "【彩虹夫妇专属】适用于苹/果17256颜色随机", - "future_ts": 1765802914.512486, - "future_str": "2025-12-15 20:48:34", + "prize_value_yuan": 1580.0, + "content": "天然缅料A货翡翠甜甜圈吊坠/一件(微瑕)多样性:", + "future_ts": 1765875275.730418, + "future_str": "2025-12-16 16:54:35", "pos_seen": 1, - "room_title": "彩虹夫妇", - "room_title_raw": "彩虹夫妇" + "room_title": "陌玉珠宝", + "room_title_raw": "陌玉珠宝~" }, { - "prize_value_yuan": 899.0, - "content": "小米红米/redmi14C智能手机", - "future_ts": 1765803199.541887, - "future_str": "2025-12-15 20:53:19", - "pos_seen": 3, - "room_title": "在年快乐399万米场", - "room_title_raw": "在年快乐399万米场" + "prize_value_yuan": 999.0, + "content": "Camudin黑水鬼系列黑盘钢带款(附带调表器)", + "future_ts": 1765875733.617007, + "future_str": "2025-12-16 17:02:13", + "pos_seen": 2, + "room_title": "梵象名品", + "room_title_raw": "梵象名品..." } ] } diff --git a/target_pic/screenshot.png b/target_pic/screenshot.png new file mode 100644 index 0000000..0b7145a Binary files /dev/null and b/target_pic/screenshot.png differ diff --git a/test_follow_tab_coordinates.py b/test_follow_tab_coordinates.py new file mode 100644 index 0000000..1af6388 --- /dev/null +++ b/test_follow_tab_coordinates.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +测试关注标签坐标功能 +用于验证关注标签坐标 (712, 169) 是否正确配置 +""" + +import re +import os + +def test_coordinates(): + """测试关注标签坐标是否正确配置""" + script_dir = os.path.dirname(os.path.abspath(__file__)) + douyin_fudai_path = os.path.join(script_dir, "douyin_fudai.py") + + if not os.path.exists(douyin_fudai_path): + print("错误: 未找到 douyin_fudai.py 文件") + return False + + with open(douyin_fudai_path, "r", encoding="utf-8") as f: + content = f.read() + + # 检查坐标定义 + x_match = re.search(r'self\.yanghao_follow_tab_x\s*=\s*(\d+)', content) + y_match = re.search(r'self\.yanghao_follow_tab_y\s*=\s*(\d+)', content) + + if not x_match or not y_match: + print("错误: 未找到关注标签坐标定义") + return False + + x_coord = int(x_match.group(1)) + y_coord = int(y_match.group(1)) + + print("=" * 50) + print("关注标签坐标测试") + print("=" * 50) + print(f"当前配置的坐标: ({x_coord}, {y_coord})") + print(f"预期坐标: (712, 169)") + + if x_coord == 712 and y_coord == 169: + print("\n[OK] 坐标配置正确!") + + # 检查坐标使用位置 + usage_pattern = r'follow_tab_x\s*=\s*int\(getattr\(self,\s*"yanghao_follow_tab_x"' + if re.search(usage_pattern, content): + print("[OK] 坐标在使用位置正确获取") + else: + print("[WARN] 警告: 未找到坐标使用代码") + + # 检查日志输出 + log_pattern = r'检测到推荐页面,点击关注标签 ->' + if re.search(log_pattern, content): + print("[OK] 日志输出代码存在") + + print("\n测试通过!") + print("\n下一步:") + print("1. 运行脚本,观察日志中是否显示: 检测到推荐页面,点击关注标签 -> (712, 169)") + print("2. 验证点击位置是否准确落在关注标签上") + print("3. 如果点击位置不准确,可以微调坐标值") + + return True + else: + print(f"\n[ERROR] 坐标配置不匹配!") + print(f" 当前: ({x_coord}, {y_coord})") + print(f" 预期: (712, 169)") + return False + +if __name__ == "__main__": + success = test_coordinates() + exit(0 if success else 1) + diff --git a/web_gui.py b/web_gui.py index 079994d..443607f 100644 --- a/web_gui.py +++ b/web_gui.py @@ -14,6 +14,16 @@ BASE_DIR = os.path.dirname(__file__) 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-?]*[ -/]*[@-~])') + + +def strip_ansi_escape_codes(text: str) -> str: + """移除字符串中的ANSI转义序列(颜色代码等)。""" + if not isinstance(text, str): + return str(text) + return _ANSI_ESCAPE_RE.sub('', text) + def find_adb_executable() -> str: adb = shutil.which("adb") @@ -62,7 +72,7 @@ class ProcRunner: self._proc: subprocess.Popen | None = None self._lock = threading.Lock() self._log: list[str] = [] - self._log_capacity: int = 2000 # 0=不限制(可能占用大量内存) + 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 @@ -107,9 +117,9 @@ class ProcRunner: self._log_file_path = path try: - cap = int(cfg.get("webgui_log_capacity", 2000)) + cap = int(cfg.get("webgui_log_capacity", 10000)) except Exception: - cap = 2000 + cap = 10000 self._log_capacity = cap def _append_to_unified_file(self, line: str) -> None: @@ -117,15 +127,26 @@ class ProcRunner: return try: os.makedirs(os.path.dirname(self._log_file_path), exist_ok=True) - except Exception: + except Exception as e: + # 目录创建失败,可能是权限问题,但继续尝试写入(可能目录已存在) pass try: # 使用 utf-8-sig:文件首次创建时会写入 BOM,避免 Windows PowerShell 误按 ANSI 读取导致中文乱码 with open(self._log_file_path, "a", encoding="utf-8-sig", errors="replace") as f: f.write(line + "\n") - except Exception: - # 文件写失败不应影响主流程 - pass + f.flush() # 确保立即写入磁盘,避免缓冲区延迟导致日志丢失 + except PermissionError as e: + # 权限错误,只输出一次警告避免刷屏 + 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'): + print(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}") + print(f"[WEB_GUI] 错误详情: {e}") + self._log_write_error_warned = True def _inc(self, key: str, n: int = 1) -> None: self._counters[key] = int(self._counters.get(key, 0)) + int(n) @@ -429,8 +450,18 @@ class ProcRunner: p.kill() except Exception: pass + # 清理进程引用,避免后续 stop/状态查询混淆 + with self._lock: + try: + self._proc = None + self._pid = None + except Exception: + pass + self._append_log("[网页] 停止:已尝试终止并清理进程引用") def _append_log(self, line: str) -> None: + # 清理ANSI转义序列,避免在Web界面显示异常字符 + line = strip_ansi_escape_codes(line) # 先写入统一文件:不受内存容量影响 self._append_to_unified_file(line) with self._lock: @@ -592,10 +623,13 @@ class ProcRunner: with self._lock: if idx < 0: idx = 0 - if idx > len(self._log): - idx = len(self._log) + log_len = len(self._log) + # 如果索引越界,说明日志可能被截断了(比如内存日志被清理) + # 返回所有日志,让前端能够检测到并重置索引 + if idx > log_len: + idx = 0 lines = self._log[idx:] - return len(self._log), lines + return log_len, lines def start_test_yanghao(self, device_id: str, seconds: int) -> None: if self.is_running(): @@ -770,14 +804,18 @@ class ProcRunner: errors="replace", env=env, cwd=BASE_DIR, + bufsize=1, # 行缓冲模式,确保实时输出 ) + # 立即记录进程信息并初始化状态 with self._lock: self._proc = p self._pid = p.pid self._start_ts = time.time() self._exit_code = None self._last_log_ts = time.time() + # 清空旧日志,确保新启动的进程只显示新日志 + self._log = [] self._counters = {} self._fudai_last = { "content": "", @@ -791,14 +829,52 @@ class ProcRunner: self._wins = [] self._append_log(f"[网页] 启动:{' '.join(cmd)}") + self._append_log(f"[网页] 子进程 PID={p.pid} 已创建,准备启动读取线程") def _reader() -> None: + self._append_log(f"[网页] 读取线程启动,监视 PID={p.pid}") out = p.stdout if out is None: + self._append_log(f"[网页] 读取线程:stdout 为 None,无法读取子进程输出") + try: + rc = p.wait() + except Exception: + rc = None + self._append_log(f"[网页] 进程退出(无输出):退出码={rc}") + with self._lock: + self._exit_code = rc return - for line in out: - self._append_log(line.rstrip("\n")) - rc = p.wait() + + try: + # 使用迭代器读取,Python会自动处理缓冲 + # 配合PYTHONUNBUFFERED=1和line_buffering=True,应该能实时获取输出 + # iter(out.readline, '') 会在readline返回空字符串(EOF)时自动停止 + for line in iter(out.readline, ''): + try: + cleaned_line = line.rstrip("\n\r") + if cleaned_line: # 忽略空行 + self._append_log(cleaned_line) + except Exception: + # 避免单条日志处理异常中断读取循环 + pass + except BrokenPipeError: + # 进程已关闭stdout + self._append_log(f"[网页] 读取线程:子进程stdout已关闭") + except Exception as e: + self._append_log(f"[网页] 读取线程异常:{e}") + + try: + rc = p.wait(timeout=1) + except subprocess.TimeoutExpired: + rc = None + self._append_log(f"[网页] 等待进程退出超时,强制终止") + try: + p.kill() + rc = p.wait(timeout=5) + except Exception: + pass + except Exception: + rc = None self._append_log(f"[网页] 进程退出:退出码={rc}") with self._lock: self._exit_code = rc @@ -889,10 +965,39 @@ class Handler(BaseHTTPRequestHandler): since = 0 try: since = int((qs.get("since") or [0])[0]) - except Exception: + except (ValueError, TypeError, IndexError): since = 0 - next_idx, lines = RUNNER.get_logs_since(since) - return self._send_json({"next": next_idx, "lines": lines, "running": RUNNER.is_running()}) + try: + next_idx, lines = RUNNER.get_logs_since(since) + 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()}) + if u.path == "/api/logfile-tail": + # 返回统一日志文件的尾部若干行,便于在内存日志不同步时调试 + qs = parse_qs(u.query) + try: + 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") + out_lines = [] + try: + if os.path.exists(path): + # 读取尾部若干行(简单实现:读全文件或最后 64KB) + size = os.path.getsize(path) + read_bytes = min(size, 65536) + with open(path, "rb") as f: + if read_bytes < size: + f.seek(-read_bytes, os.SEEK_END) + data = f.read().decode("utf-8", errors="replace") + parts = data.splitlines() + out_lines = parts[-n:] + except Exception: + out_lines = [""] + return self._send_json({"ok": True, "path": path, "lines": out_lines}) self.send_error(HTTPStatus.NOT_FOUND) return diff --git a/webui/app.js b/webui/app.js index c54f72d..f1c7a7e 100644 --- a/webui/app.js +++ b/webui/app.js @@ -2,6 +2,8 @@ let logIdx = 0; let pollTimer = null; let statsTimer = null; let shotTimer = null; +let lastLogUpdateTime = 0; // 最后成功获取日志的时间 +let logErrorCount = 0; // 连续错误计数 const DEFAULTS = { // 筛选 @@ -81,8 +83,24 @@ function initTabs() { function appendLog(lines) { const log = $("log"); if (!lines || lines.length === 0) return; - log.textContent += lines.join("\n") + "\n"; - log.scrollTop = log.scrollHeight; + + // 检查是否在底部附近(用户可能在看最新日志) + const wasNearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 100; + + // 性能优化:批量追加文本,减少重排次数 + const newText = lines.join("\n") + "\n"; + log.textContent += newText; + + // 性能优化:限制日志长度,避免内存溢出(保留最近 50000 字符) + const maxLength = 50000; + if (log.textContent.length > maxLength) { + log.textContent = log.textContent.slice(-maxLength); + } + + // 只有在底部附近时才自动滚动,避免打断用户查看历史日志 + if (wasNearBottom) { + log.scrollTop = log.scrollHeight; + } } function fmtTime(ts) { @@ -108,7 +126,11 @@ function pollShot() { const img = $("liveShot"); if (!img) return; + // 性能优化:避免重复加载相同的图片(如果正在加载中) + if (img.dataset.loading === "true") return; + const url = `/pic/screenshot.png?t=${Date.now()}`; + img.dataset.loading = "true"; img.src = url; const status = $("liveShotStatus"); @@ -122,14 +144,17 @@ function startShotPolling() { const status = $("liveShotStatus"); if (img) { img.addEventListener("load", () => { + img.dataset.loading = "false"; if (status) status.textContent = `已更新:${new Date().toLocaleTimeString()}`; }); img.addEventListener("error", () => { + img.dataset.loading = "false"; if (status) status.textContent = "暂无截图(等待脚本生成 pic/screenshot.png)"; }); } - shotTimer = setInterval(pollShot, 900); + // 性能优化:截图轮询间隔从 900ms 调整为 1500ms,减少服务器压力 + shotTimer = setInterval(pollShot, 1500); } function setTextIfExists(id, text) { @@ -404,8 +429,15 @@ async function apiPost(path, body) { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}), }); - if (!res.ok) throw new Error(await res.text()); - return await res.json(); + const data = await res.json(); + if (!res.ok) { + const errorMsg = data.error || data.message || res.statusText; + const error = new Error(errorMsg); + error.status = res.status; + error.data = data; + throw error; + } + return data; } async function refreshDevices() { @@ -503,33 +535,64 @@ async function saveConfig() { } async function startRun() { - const deviceId = $("device").value || ""; - const yPianyi = parseInt($("y_pianyi").value || "0", 10); - const waitMinutes = parseInt($("wait_minutes").value || "5", 10); - const needswitch = $("needswitch").checked; - const cfgPart = collectConfigFromUI(); + try { + const deviceId = $("device").value || ""; + const yPianyi = parseInt($("y_pianyi").value || "0", 10); + const waitMinutes = parseInt($("wait_minutes").value || "5", 10); + const needswitch = $("needswitch").checked; + const cfgPart = collectConfigFromUI(); - await apiPost("/api/start-run", { - device_id: deviceId, - y_pianyi: yPianyi, - wait_minutes: waitMinutes, - needswitch, - reset_after_swipes_enabled: cfgPart.reset_after_swipes_enabled, - min_prize_value_yuan: cfgPart.min_prize_value_yuan, - min_participants: cfgPart.min_participants, - max_participants: cfgPart.max_participants, - skip_if_countdown_lt_seconds: cfgPart.skip_if_countdown_lt_seconds, - reset_after_swipes: cfgPart.reset_after_swipes, - auto_join_fansclub: cfgPart.auto_join_fansclub, - fansclub_fail_action: cfgPart.fansclub_fail_action, - high_value_room_revisit_enabled: cfgPart.high_value_room_revisit_enabled, - high_value_room_revisit_only_current_run: cfgPart.high_value_room_revisit_only_current_run, - reservation_back_verify_enabled: cfgPart.reservation_back_verify_enabled, - reservation_back_swipe_delay: cfgPart.reservation_back_swipe_delay, - fudai_find_max_attempts: cfgPart.fudai_find_max_attempts, - reservation_preempt_min_value: cfgPart.reservation_preempt_min_value, - }); - appendLog([`[WEB] 已开始运行:device=${deviceId || '(auto)'}`]); + appendLog([`[WEB] 正在启动...`]); + + const result = await apiPost("/api/start-run", { + device_id: deviceId, + y_pianyi: yPianyi, + wait_minutes: waitMinutes, + needswitch, + reset_after_swipes_enabled: cfgPart.reset_after_swipes_enabled, + min_prize_value_yuan: cfgPart.min_prize_value_yuan, + min_participants: cfgPart.min_participants, + max_participants: cfgPart.max_participants, + skip_if_countdown_lt_seconds: cfgPart.skip_if_countdown_lt_seconds, + reset_after_swipes: cfgPart.reset_after_swipes, + auto_join_fansclub: cfgPart.auto_join_fansclub, + fansclub_fail_action: cfgPart.fansclub_fail_action, + high_value_room_revisit_enabled: cfgPart.high_value_room_revisit_enabled, + high_value_room_revisit_only_current_run: cfgPart.high_value_room_revisit_only_current_run, + reservation_back_verify_enabled: cfgPart.reservation_back_verify_enabled, + reservation_back_swipe_delay: cfgPart.reservation_back_swipe_delay, + fudai_find_max_attempts: cfgPart.fudai_find_max_attempts, + reservation_preempt_min_value: cfgPart.reservation_preempt_min_value, + }); + + // 检查返回结果 + if (result && result.ok === false) { + const errorMsg = result.error || "未知错误"; + appendLog([`[WEB] 启动失败: ${errorMsg}`]); + if (errorMsg === "running") { + appendLog([`[WEB] 提示:已有进程在运行中,请先点击"停止"按钮`]); + } + return; + } + + appendLog([`[WEB] 已开始运行:device=${deviceId || '(auto)'}`]); + + // 重置本地日志索引并清空显示区域,然后立即拉取最新日志 + try { + logIdx = 0; + // 清空日志显示区域,准备显示新进程的日志 + const logEl = $("log"); + if (logEl) { + logEl.textContent = ""; + } + await pollLogs(); + } catch (e) { + console.error("[WEB] pollLogs error after start:", e); + } + } catch (e) { + console.error("[WEB] startRun error:", e); + appendLog([`[WEB] 启动时出错: ${e.message || e}`]); + } } async function testYanghao() { @@ -549,15 +612,89 @@ async function testComment() { async function stopRun() { await apiPost("/api/stop", {}); appendLog(["[WEB] 已发送停止"]); + // 重置并拉取日志,确保能看到后端的停止确认输出 + try { + logIdx = 0; + await pollLogs(); + } catch (e) { + // ignore + } } async function pollLogs() { try { const data = await apiGet(`/api/logs?since=${logIdx}`); - logIdx = data.next ?? logIdx; - appendLog(data.lines || []); + + // 检查返回数据是否有效 + if (!data || typeof data !== 'object') { + console.error('[WEB_DBG] pollLogs: invalid response data', data); + logErrorCount++; + return; + } + + // 重置错误计数 + logErrorCount = 0; + lastLogUpdateTime = Date.now(); + + // 先检查索引是否异常(后端返回的next小于当前索引,说明日志被截断了) + const nextIdx = typeof data.next === 'number' ? data.next : logIdx; + if (nextIdx < logIdx && logIdx > 0) { + console.warn('[WEB_DBG] pollLogs: 检测到日志截断,重置索引', { oldIdx: logIdx, newIdx: nextIdx }); + logIdx = 0; + // 重新请求一次以获取所有日志 + const retryData = await apiGet(`/api/logs?since=0`); + if (retryData && typeof retryData === 'object' && Array.isArray(retryData.lines)) { + logIdx = typeof retryData.next === 'number' ? retryData.next : 0; + if (retryData.lines.length > 0) { + appendLog(retryData.lines); + } + } + return; + } + + // 更新日志索引 + if (typeof data.next === 'number') { + logIdx = data.next; + } + + // 追加日志 + if (Array.isArray(data.lines) && data.lines.length > 0) { + appendLog(data.lines); + lastLogUpdateTime = Date.now(); + } + + // 容错:确保索引不为负数 + if (logIdx < 0) { + console.warn('[WEB_DBG] pollLogs: logIdx为负数,重置为0'); + logIdx = 0; + } + + // 如果超过30秒没有获取到新日志且索引很大,可能是索引卡住了,重置索引 + const now = Date.now(); + if (lastLogUpdateTime > 0 && (now - lastLogUpdateTime > 30000) && logIdx > 1000) { + console.warn('[WEB_DBG] pollLogs: 长时间未更新,重置索引尝试恢复', { logIdx, lastUpdate: now - lastLogUpdateTime }); + logIdx = 0; + lastLogUpdateTime = 0; + } } catch (e) { - appendLog([`[WEB] poll logs failed: ${e.message}`]); + logErrorCount++; + console.error('[WEB_DBG] pollLogs error:', e); + // 如果连续10次出错,重置索引 + if (logErrorCount >= 10) { + console.warn('[WEB_DBG] pollLogs: 连续10次错误,重置索引'); + logIdx = 0; + logErrorCount = 0; + } + // 错误时不追加日志到界面,避免刷屏,只在控制台输出 + // 如果是网络错误或超时,不重置索引;如果是其他错误,考虑重置 + if (e.message && !e.message.includes('NetworkError') && !e.message.includes('Failed to fetch') && !e.message.includes('timeout')) { + console.error('[WEB_DBG] pollLogs failed:', e.message); + // 非网络错误,可能是数据格式错误,重置索引尝试恢复 + if (e.message.includes('JSON') || e.message.includes('parse')) { + console.warn('[WEB_DBG] pollLogs: 数据解析错误,重置索引'); + logIdx = 0; + } + } } } @@ -874,7 +1011,8 @@ async function pollStats() { function startPolling() { if (pollTimer) clearInterval(pollTimer); - pollTimer = setInterval(pollLogs, 700); + // 性能优化:日志轮询间隔从 700ms 调整为 800ms,减少服务器压力同时保持实时性 + pollTimer = setInterval(pollLogs, 800); } function startStatsPolling() { diff --git a/一键启动WebGUI.bat b/一键启动WebGUI.bat new file mode 100644 index 0000000..76b94ea --- /dev/null +++ b/一键启动WebGUI.bat @@ -0,0 +1,100 @@ +@echo off +chcp 65001 >nul +setlocal enabledelayedexpansion + +REM 切到脚本所在目录 +pushd "%~dp0" + +echo ======================================== +echo 抖音挂机 Web GUI 一键启动 +echo ======================================== +echo. + +REM 检查Python是否安装 +python --version >nul 2>&1 +if errorlevel 1 ( + echo [错误] 未检测到Python,请先安装Python + echo 下载地址: https://www.python.org/downloads/ + pause + exit /b 1 +) + +echo [1/5] Python环境检查... OK +echo. + +REM 检查web_gui.py是否存在 +if not exist "web_gui.py" ( + echo [错误] 未找到 web_gui.py 文件 + pause + exit /b 1 +) + +echo [2/5] 文件检查... OK +echo. + +REM 停止旧的web_gui.py进程(避免端口占用) +echo [3/5] 停止旧进程... +powershell -NoProfile -Command "$ps = Get-CimInstance Win32_Process | Where-Object { ($_.CommandLine -like '*web_gui.py*') -and ($_.Name -like 'python*') }; if ($ps) { $ps | ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue; Write-Host \" [已停止] PID=$($_.ProcessId)\" } catch {} } } else { Write-Host \" [无旧进程]\" }" 2>nul +timeout /t 1 /nobreak >nul +echo [3/5] 停止旧进程... OK +echo. + +REM 设置端口(支持环境变量,默认8000) +set "WEB_PORT=8000" +if defined PORT set "WEB_PORT=%PORT%" +if defined WEB_GUI_PORT set "WEB_PORT=%WEB_GUI_PORT%" + +REM 设置Python环境变量 +set PYTHONIOENCODING=utf-8 +set PYTHONUNBUFFERED=1 + +REM 启动Web GUI +echo [4/5] 启动Web GUI服务(端口: %WEB_PORT%)... +echo. + +REM 检查是否有虚拟环境,如果有则使用,否则直接使用python +if exist ".venv\Scripts\activate.bat" ( + start "抖音挂机 Web GUI" /D "%~dp0" cmd /c ".venv\Scripts\activate.bat && python web_gui.py" +) else ( + start "抖音挂机 Web GUI" /D "%~dp0" python web_gui.py +) + +REM 等待服务启动 +echo 正在启动服务,请稍候... +set /a count=0 +:wait_loop +timeout /t 1 /nobreak >nul +set /a count+=1 +powershell -NoProfile -Command "$listener = Get-NetTCPConnection -LocalPort %WEB_PORT% -State Listen -ErrorAction SilentlyContinue; if ($listener) { exit 0 } else { exit 1 }" >nul 2>&1 +if not errorlevel 1 ( + echo [4/5] Web GUI服务已启动 + goto :open_browser +) +if !count! geq 10 ( + echo [警告] 服务启动超时,但仍将尝试打开浏览器 + goto :open_browser +) +goto :wait_loop + +:open_browser +echo. +echo [5/5] 打开浏览器... +start "" "http://127.0.0.1:%WEB_PORT%" + +echo. +echo ======================================== +echo 启动完成! +echo ======================================== +echo. +echo Web GUI地址: http://127.0.0.1:%WEB_PORT% +echo. +echo 提示: +echo - 关闭此窗口不会停止Web GUI服务 +echo - 要停止服务,请运行"停止WebGUI服务.bat" +echo. +echo 按任意键退出... +pause >nul + +popd +endlocal + diff --git a/停止WebGUI服务.bat b/停止WebGUI服务.bat new file mode 100644 index 0000000..fd7edee --- /dev/null +++ b/停止WebGUI服务.bat @@ -0,0 +1,16 @@ +@echo off +chcp 65001 >nul +echo ======================================== +echo 停止抖音挂机 Web GUI 服务 +echo ======================================== +echo. + +echo 正在查找Web GUI进程... + +REM 查找并停止web_gui.py进程 +powershell -NoProfile -Command "$ps = Get-CimInstance Win32_Process | Where-Object { ($_.CommandLine -like '*web_gui.py*') -and ($_.Name -like 'python*') }; if ($ps) { $ps | ForEach-Object { try { $pid = $_.ProcessId; Stop-Process -Id $pid -Force -ErrorAction SilentlyContinue; Write-Host \"[已停止] PID=$pid\" } catch { Write-Host \"[停止失败] PID=$($_.ProcessId): $_\" } } } else { Write-Host \"[未找到] 没有运行中的Web GUI进程\" }" + +echo. +echo 操作完成! +echo. +pause diff --git a/抖音挂机WebGUI-一键启动.bat b/抖音挂机WebGUI-一键启动.bat deleted file mode 100644 index 212bb39..0000000 --- a/抖音挂机WebGUI-一键启动.bat +++ /dev/null @@ -1,20 +0,0 @@ -@echo off -setlocal - -REM 切到脚本所在目录(项目根目录) -pushd "%~dp0" - -REM 先尝试停止旧的 web_gui.py(避免端口占用/版本未更新) -powershell -NoProfile -Command "$ps = Get-CimInstance Win32_Process | Where-Object { ($_.CommandLine -like '*web_gui.py*') -and ($_.Name -like 'python*') }; $ps | ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force } catch {} }" >nul 2>nul - -REM 启动 Web GUI(隐藏窗口) -powershell -NoProfile -Command "Start-Process -FilePath python -ArgumentList @('web_gui.py') -WorkingDirectory (Get-Location).Path -WindowStyle Hidden" >nul 2>nul - -REM 稍等服务起来 -timeout /t 1 /nobreak >nul - -REM 打开浏览器 -start "" "http://127.0.0.1:8765" - -popd -endlocal diff --git a/抖音挂机WebGUI-后台启动.bat b/抖音挂机WebGUI-后台启动.bat new file mode 100644 index 0000000..8a473ca --- /dev/null +++ b/抖音挂机WebGUI-后台启动.bat @@ -0,0 +1,53 @@ +@echo off +chcp 65001 >nul +setlocal enabledelayedexpansion + +REM 切到脚本所在目录(项目根目录) +pushd "%~dp0" + +echo ======================================== +echo 抖音挂机 Web GUI 后台启动脚本 +echo ======================================== +echo. + +REM 检查Python是否安装 +python --version >nul 2>&1 +if errorlevel 1 ( + echo [错误] 未检测到Python,请先安装Python + pause + exit /b 1 +) + +REM 检查web_gui.py是否存在 +if not exist "web_gui.py" ( + echo [错误] 未找到 web_gui.py 文件 + pause + exit /b 1 +) + +REM 停止旧的web_gui.py进程 +powershell -NoProfile -Command "$ps = Get-CimInstance Win32_Process | Where-Object { ($_.CommandLine -like '*web_gui.py*') -and ($_.Name -like 'python*') }; $ps | ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } catch {} }" >nul 2>&1 +timeout /t 1 /nobreak >nul + +REM 读取端口配置 +set "WEB_PORT=8000" +if defined PORT set "WEB_PORT=%PORT%" +if defined WEB_GUI_PORT set "WEB_PORT=%WEB_GUI_PORT%" + +REM 启动Web GUI(隐藏窗口) +powershell -NoProfile -Command "Start-Process -FilePath python -ArgumentList 'web_gui.py' -WorkingDirectory (Get-Location).Path -WindowStyle Hidden" >nul 2>&1 + +REM 等待服务启动 +timeout /t 2 /nobreak >nul + +REM 打开浏览器 +start "" "http://127.0.0.1:%WEB_PORT%" + +echo Web GUI已启动(后台运行) +echo 访问地址: http://127.0.0.1:%WEB_PORT% +echo. +echo 3秒后自动关闭此窗口... +timeout /t 3 /nobreak >nul + +popd +endlocal diff --git a/测试关注标签坐标.md b/测试关注标签坐标.md new file mode 100644 index 0000000..a91f393 --- /dev/null +++ b/测试关注标签坐标.md @@ -0,0 +1,63 @@ +# 关注标签坐标功能测试计划 + +## 测试目标 +验证更新后的关注标签坐标 (712, 169) 是否正常工作。 + +## 更新内容 +- **坐标位置**:左上角 (674, 153),右下角 (749, 185) +- **中心点**:x=712, y=169(基于1080x2400分辨率) +- **代码位置**:`douyin_fudai.py` 第566-567行 + +## 测试步骤 + +### 1. 代码验证测试 +- [x] 确认坐标已更新为 (712, 169) +- [ ] 验证代码中使用了正确的坐标 +- [ ] 确认坐标会在运行时被正确读取 + +### 2. 功能测试(需要实际运行) + +#### 测试场景1:推荐页面检测 +1. 确保脚本运行在推荐页面(推荐标签页) +2. 观察日志中是否输出:`检测到推荐页面,点击关注标签 -> (712, 169)` +3. 验证点击位置是否准确落在关注标签上 + +#### 测试场景2:页面跳转 +1. 从推荐页面点击关注标签后 +2. 验证是否成功切换到关注页面 +3. 检查后续流程是否正常(进入直播间) + +### 3. 坐标精度测试 +- 如果点击位置不够准确,可以微调: + - 如果点击偏左:增加 x 值(例如 715) + - 如果点击偏右:减少 x 值(例如 710) + - 如果点击偏上:减少 y 值(例如 167) + - 如果点击偏下:增加 y 值(例如 171) + +## 关键代码位置 + +### 坐标定义 +```python +# douyin_fudai.py 第566-567行 +self.yanghao_follow_tab_x = 712 # 关注标签中心的 x 坐标(1080x2400 基准) +self.yanghao_follow_tab_y = 169 # 关注标签中心的 y 坐标(1080x2400 基准) +``` + +### 坐标使用 +```python +# douyin_fudai.py 第4810-4812行 +follow_tab_x = int(getattr(self, "yanghao_follow_tab_x", 270)) +follow_tab_y = int(getattr(self, "yanghao_follow_tab_y", 2340)) +self.click(follow_tab_x, follow_tab_y) +``` + +## 注意事项 +1. 坐标基于 1080x2400 分辨率,不同分辨率会自动缩放 +2. 如果设备分辨率不是 1080x2400,需要确认缩放是否正确 +3. 关注标签位于页面顶部,不在底部标签栏 + +## 预期结果 +- 日志中显示正确的坐标值 (712, 169) +- 点击后成功切换到关注页面 +- 后续流程正常执行 + diff --git a/测试结果总结.md b/测试结果总结.md new file mode 100644 index 0000000..6109033 --- /dev/null +++ b/测试结果总结.md @@ -0,0 +1,62 @@ +# 关注标签坐标更新 - 测试结果总结 + +## ✅ 测试通过 + +### 1. 坐标配置验证 +- **当前坐标**: (712, 169) +- **预期坐标**: (712, 169) +- **状态**: ✅ 配置正确 + +### 2. 代码逻辑验证 +- ✅ 坐标定义正确(douyin_fudai.py 第566-567行) +- ✅ 坐标使用代码正确(douyin_fudai.py 第4810-4811行) +- ✅ 日志输出代码存在(会显示点击的坐标值) + +### 3. 功能说明 + +#### 坐标位置 +- **左上角**: (674, 153) +- **右下角**: (749, 185) +- **中心点**: (712, 169) +- **分辨率基准**: 1080x2400 + +#### 使用场景 +当脚本检测到当前在"推荐页面"(RECOMMEND_PAGE)时: +1. 会点击关注标签(坐标712, 169) +2. 等待2秒后点击进入直播间位置 +3. 日志中会显示:`检测到推荐页面,点击关注标签 -> (712, 169)` + +## 📝 后续测试建议 + +### 实际运行测试 +1. **启动脚本** + - 通过Web GUI或命令行启动脚本 + - 确保设备在推荐页面 + +2. **观察日志** + - 查看日志中是否出现:`检测到推荐页面,点击关注标签 -> (712, 169)` + - 验证坐标值是否正确 + +3. **验证点击准确性** + - 观察点击是否准确落在关注标签上 + - 如果位置不准确,可以微调坐标 + +### 坐标微调指南 +如果点击位置不够准确: +- **偏左**: 增加x值(例如 715) +- **偏右**: 减少x值(例如 710) +- **偏上**: 减少y值(例如 167) +- **偏下**: 增加y值(例如 171) + +## 🔧 已修复的问题 +- ✅ 更新了默认值从 (270, 2340) 改为 (712, 169) +- ✅ 更新了注释说明(从"底部标签栏"改为"顶部标签栏") + +## 📋 测试完成清单 +- [x] 坐标配置验证 +- [x] 代码逻辑验证 +- [x] 默认值更新 +- [x] 注释更新 +- [ ] 实际运行测试(需要连接设备) +- [ ] 点击位置准确性验证(需要实际运行) + diff --git a/问题排查说明.md b/问题排查说明.md new file mode 100644 index 0000000..d4a9f83 --- /dev/null +++ b/问题排查说明.md @@ -0,0 +1,70 @@ +# "开始运行"按钮没反应 - 问题排查 + +## 已完成的修复 + +### 1. 改进了错误处理 +- ✅ 添加了 try-catch 包裹整个 startRun 函数 +- ✅ 添加了"正在启动..."的提示信息 +- ✅ 检查API返回结果,如果 `ok === false` 会显示错误信息 +- ✅ 改进了 apiPost 函数,更好地处理错误响应 + +### 2. 代码改进点 + +**前端错误处理 (`webui/app.js`)**: +- 添加了启动提示:`[WEB] 正在启动...` +- 检查API返回结果,如果失败会显示错误信息 +- 如果错误是"running",会提示用户先点击"停止"按钮 + +**API错误处理**: +- apiPost 函数现在会正确解析错误响应 +- 如果API返回错误,会在日志中显示 + +## 可能的问题原因 + +根据测试,发现以下情况: + +1. **进程启动成功但可能立即退出** + - 从日志看,进程确实启动了 + - 但退出码是1,说明可能有错误 + - 需要查看具体错误信息 + +2. **日志清空问题** + - 启动时会清空日志显示区域 + - 但新的日志可能没有及时显示 + - 需要检查日志轮询是否正常 + +3. **按钮点击可能被阻止** + - 如果已有进程在运行,会返回409错误 + - 但现在会正确显示错误信息 + +## 排查步骤 + +### 步骤1:检查是否有进程在运行 +1. 查看页面上的"运行状态"统计信息 +2. 如果显示"运行中",说明已有进程 +3. 需要先点击"停止"按钮 + +### 步骤2:查看日志 +1. 点击"开始运行"后,查看日志区域 +2. 应该会看到:`[WEB] 正在启动...` +3. 然后会看到:`[WEB] 已开始运行:device=...` +4. 或者错误信息:`[WEB] 启动失败: ...` + +### 步骤3:查看浏览器控制台 +1. 按F12打开开发者工具 +2. 查看Console标签,看是否有错误信息 +3. 查看Network标签,检查 `/api/start-run` 请求的响应 + +### 步骤4:检查后端日志 +如果前端没有显示错误,可以查看: +- Web GUI的命令行窗口输出 +- `logs/unified.log` 文件的最后几行 + +## 如果问题仍然存在 + +请提供以下信息: +1. 点击"开始运行"后,日志区域显示了什么? +2. 浏览器控制台(F12)有什么错误信息? +3. 页面上的"运行状态"显示什么? +4. 是否有其他提示信息? +