From 0b5f150691977065693e532f4437432145b78ce5 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 2 Jan 2026 23:57:03 +0800 Subject: [PATCH] Refactor and clean up code across multiple scripts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Removed trailing whitespace and ensured files end with a single newline in cleanup_unused_files.py. - Added fix_trailing_whitespace.py to batch remove trailing whitespace from Python files. - Updated install_dependencies.py to improve dependency installation prompts. - Cleaned up pick_coords.py by removing unnecessary whitespace and improving code readability. - Enhanced region_selector.py by disabling specific pylint checks for better compatibility with third-party libraries. - Improved WPS流程图生成工具.py by cleaning up whitespace and enhancing readability. - Updated __init__.py in typings to remove unnecessary lines. - Modified app.js to adjust default configuration values and clean up unused code. --- .github/copilot-instructions.md | 35 ++ .pylintrc | 2 + Underlying_Operations.py | 66 +-- check_jpeg_support.py | 523 ----------------- check_screenshot.py | 61 -- check_screenshot_service_status.py | 73 --- config/config.json | 8 +- .../test_adb_screenshot_timing.py | 51 +- ...t_completely_disable_screenshot_service.py | 0 .../test_direct_screenshot.py | 89 ++- .../test_disable_streaming_screenshots.py | 0 .../test_loop_screenshot_stop.py | 4 - .../test_ocr_multithread.py | 22 +- .../test_ocr_multithread_performance.py | 91 ++- .../test_ocr_speed.py | 59 +- .../test_ocr_speed_optimized.py | 66 +-- .../test_parallel_ocr_performance.py | 111 ++-- .../test_parallel_ocr_quick.py | 50 +- .../test_parallel_ocr_simple.py | 67 +-- .../test_real_parallel_ocr.py | 111 ++-- .../test_screenshot_error_handling.py | 4 - .../test_screenshot_file_wait.py | 0 .../test_screenshot_performance.py | 35 +- .../test_screenshot_reuse_optimization.py | 0 .../test_screenshot_service_fix.py | 0 ...est_screenshot_service_ocr_optimization.py | 0 .../test_screenshot_service_ocr_simple.py | 0 .../test_screenshot_service_ocr_stop.py | 0 .../test_time_import_fix.py | 0 diagnose_screenshot_service.py | 72 --- douyin/__init__.py | 4 - douyin/core/__init__.py | 3 - douyin/core/douyin_flow_control.py | 482 ++++++---------- douyin/core/douyin_fudai.py | 60 +- douyin/core/douyin_main_flow.py | 2 - douyin/core/fudai_modules/base_interface.py | 50 -- .../fudai_modules/fudai_lottery_result.py | 16 - douyin/core/fudai_modules/fudai_room_utils.py | 50 -- douyin/core/state/reservations.json | 2 +- douyin/detection/__init__.py | 1 - douyin/detection/core/__init__.py | 50 -- douyin/detection/douyin_detection.py | 88 +-- douyin/detection/douyin_pixel.py | 18 +- douyin/fudai/__init__.py | 4 - douyin/fudai/core/fudai_attend.py | 6 +- douyin/fudai/core/fudai_debug_utils.py | 68 +-- douyin/fudai/core/fudai_detail_reader.py | 2 +- douyin/fudai/core/fudai_filter.py | 2 +- douyin/fudai/core/fudai_result_checker.py | 2 +- douyin/fudai/douyin_fudai_core.py | 545 +++++++++++++++--- douyin/fudai/douyin_fudai_finder.py | 12 +- douyin/fudai/finder/__init__.py | 51 -- douyin/handlers/douyin_popup_handler.py | 2 - douyin/handlers/douyin_screenshot_handler.py | 2 - douyin/handlers/douyin_screenshot_manager.py | 2 +- douyin/handlers/douyin_swipe_handler.py | 6 - douyin/handlers/douyin_swipe_ops.py | 14 +- douyin/logging/__init__.py | 4 - douyin/logging/action_logger.py | 2 - douyin/logging/action_tracker.py | 38 -- douyin/logging/debug_logger.py | 2 - douyin/logging/douyin_logging_wrapper.py | 2 +- douyin/logging/error_logger.py | 21 - douyin/logging/log_formatter.py | 2 - douyin/logging/performance_tracker.py | 2 - douyin/other/__init__.py | 4 - douyin/other/douyin_live_room.py | 1 - douyin/other/douyin_popups.py | 30 +- douyin/other/douyin_robot.py | 2 - douyin/other/douyin_yanghao.py | 3 - douyin/reservation/__init__.py | 4 - douyin/reservation/core/__init__.py | 51 -- .../core/reservation_error_utils.py | 39 +- douyin/reservation/douyin_reservation.py | 11 +- .../reservation/douyin_reservation_handler.py | 2 - .../reservation/douyin_reservation_logic.py | 122 ++-- .../reservation/douyin_reservation_verify.py | 35 +- douyin/stage/__init__.py | 4 - douyin/stage/douyin_stage.py | 128 ++-- douyin/stage/douyin_stage_handler.py | 47 +- douyin/utils/__init__.py | 4 - douyin/utils/douyin_config.py | 100 ++-- douyin/utils/douyin_helpers.py | 6 +- douyin/utils/douyin_text_utils.py | 58 -- douyin/utils/douyin_utils.py | 176 ++---- douyin/utils/ocr_preprocess.py | 18 - douyin_guaji.code-workspace | 39 ++ duplicate_screenshot_analysis.py | 113 ---- evaluate_screenshot_performance.py | 156 ----- final_check.txt | Bin 15772 -> 0 bytes final_check2.txt | Bin 6624 -> 0 bytes fudai_detail_modules/__init__.py | 1 - .../fudai_detail_coupon_detection.py | 2 +- .../fudai_detail_operations.py | 11 +- fudai_detail_modules/fudai_detail_reader.py | 211 ++++--- .../fudai_detail_room_title.py | 15 +- fudai_detail_modules/fudai_detail_utils.py | 1 - .../fudai_detail_validator.py | 25 +- gui/components/__init__.py | 51 -- gui/components/actions_log_viewer.py | 9 +- gui/components/config_manager.py | 51 -- gui/components/device_selector.py | 51 -- gui/components/high_value_rooms_display.py | 3 +- gui/components/image_viewer.py | 55 +- gui/components/log_color_config.py | 68 +-- gui/components/log_color_config_fixed.py | 16 - gui/components/log_viewer.py | 1 - gui/components/main_window.py | 51 -- gui/components/ocr_panel.py | 53 +- gui/components/reservation_display.py | 3 +- gui/components/stats_display.py | 3 +- gui/gui_app.py | 284 ++++----- gui/gui_core.py | 105 ++-- gui/web_components/__init__.py | 51 -- gui/web_components/proc_runner.py | 51 -- gui/web_gui.py | 30 +- install_scrcpy.bat | 132 ----- manage_logs.py | 11 - operations/__init__.py | 1 - operations/device_operations.py | 1 - operations/image_operations.py | 1 - operations/ocr_operations.py | 15 +- operations/scrcpy_screenshot.py | 36 +- operations/screenshot_operations.py | 12 +- operations/screenshot_service.py | 417 ++------------ operations/screenshot_service_new.py | 2 - path_config.py | 77 +-- pyproject.toml | 11 + pyright_out.txt | Bin 7720 -> 0 bytes pyright_output.txt | Bin 26618 -> 0 bytes .../pyrightconfig.json => pyrightconfig.json | 24 +- restore_screenshot_service.py | 64 +- run_test.py | 7 +- scripts/annotate_image.py | 2 - tools/analyze_optimization_effect.py | 35 +- tools/analyze_screenshot_logs.py | 41 +- tools/check_dependencies.py | 112 ---- tools/check_gpu_available.py | 28 +- tools/check_gui_params_conflicts.py | 37 +- tools/check_screenshot_optimization.py | 81 ++- tools/check_system_config.py | 77 ++- tools/cleanup_unused_files.py | 113 ++-- tools/fix_trailing_whitespace.py | 46 ++ tools/install_dependencies.py | 31 +- tools/pick_coords.py | 98 ++-- tools/region_selector.py | 10 +- tools/生成WPS流程图.py | 139 +---- typings/__init__.py | 1 - webui/app.js | 116 +--- 149 files changed, 2437 insertions(+), 4913 deletions(-) create mode 100644 .github/copilot-instructions.md create mode 100644 .pylintrc delete mode 100644 check_jpeg_support.py delete mode 100644 check_screenshot.py delete mode 100644 check_screenshot_service_status.py rename test_adb_screenshot_timing.py => deleted_tests_backup/test_adb_screenshot_timing.py (97%) rename test_completely_disable_screenshot_service.py => deleted_tests_backup/test_completely_disable_screenshot_service.py (100%) rename test_direct_screenshot.py => deleted_tests_backup/test_direct_screenshot.py (96%) rename test_disable_streaming_screenshots.py => deleted_tests_backup/test_disable_streaming_screenshots.py (100%) rename test_loop_screenshot_stop.py => deleted_tests_backup/test_loop_screenshot_stop.py (99%) rename test_ocr_multithread.py => deleted_tests_backup/test_ocr_multithread.py (98%) rename test_ocr_multithread_performance.py => deleted_tests_backup/test_ocr_multithread_performance.py (97%) rename test_ocr_speed.py => deleted_tests_backup/test_ocr_speed.py (96%) rename test_ocr_speed_optimized.py => deleted_tests_backup/test_ocr_speed_optimized.py (96%) rename test_parallel_ocr_performance.py => deleted_tests_backup/test_parallel_ocr_performance.py (97%) rename test_parallel_ocr_quick.py => deleted_tests_backup/test_parallel_ocr_quick.py (97%) rename test_parallel_ocr_simple.py => deleted_tests_backup/test_parallel_ocr_simple.py (97%) rename test_real_parallel_ocr.py => deleted_tests_backup/test_real_parallel_ocr.py (96%) rename test_screenshot_error_handling.py => deleted_tests_backup/test_screenshot_error_handling.py (99%) rename test_screenshot_file_wait.py => deleted_tests_backup/test_screenshot_file_wait.py (100%) rename test_screenshot_performance.py => deleted_tests_backup/test_screenshot_performance.py (97%) rename test_screenshot_reuse_optimization.py => deleted_tests_backup/test_screenshot_reuse_optimization.py (100%) rename test_screenshot_service_fix.py => deleted_tests_backup/test_screenshot_service_fix.py (100%) rename test_screenshot_service_ocr_optimization.py => deleted_tests_backup/test_screenshot_service_ocr_optimization.py (100%) rename test_screenshot_service_ocr_simple.py => deleted_tests_backup/test_screenshot_service_ocr_simple.py (100%) rename test_screenshot_service_ocr_stop.py => deleted_tests_backup/test_screenshot_service_ocr_stop.py (100%) rename test_time_import_fix.py => deleted_tests_backup/test_time_import_fix.py (100%) delete mode 100644 diagnose_screenshot_service.py delete mode 100644 duplicate_screenshot_analysis.py delete mode 100644 evaluate_screenshot_performance.py delete mode 100644 final_check.txt delete mode 100644 final_check2.txt delete mode 100644 install_scrcpy.bat create mode 100644 pyproject.toml delete mode 100644 pyright_out.txt delete mode 100644 pyright_output.txt rename config/pyrightconfig.json => pyrightconfig.json (82%) create mode 100644 tools/fix_trailing_whitespace.py diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..15a9c43 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,35 @@ +# Copilot 指令(douyin_guaji-main) + +## 先从这里入手(入口/主链路) +- CLI 入口:`run_cli.py`;主调度器:`douyin/core/douyin_fudai.py` 的 `fudai_analyse`(`fudai_choujiang()` -> 循环 `run_once_basic()`)。 +- 设备/ADB/OCR 兼容层:`Underlying_Operations.py`(OCR:优先 EasyOCR,失败回退 PaddleOCR;可用 `SKIP_OCR_INIT=1` 跳过初始化)。 +- 路径与配置:以 `config/config.json` 为准,统一用 `path_config.py` 取路径(不要硬编码 `assets/`、`pic/`、`logs/`)。 + +## 架构要点(理解模块边界) +- 核心包:`douyin/`;主要分层:`core/`(流程/状态) + `stage/`(阶段诊断) + `handlers/`(截图/弹窗/滑动等操作) + `fudai/`(福袋查找/详情/流程) + `reservation/`(高价值预约/回退校验) + `detection/`(像素/模板检测)。 +- 分辨率适配以 1080x2400 为基准:坐标/ROI 一般需要走“缩放/偏移”路径(见 `fudai_analyse` 的分辨率字段与相关 helper)。 +- 开发以模块化为主:新功能/修复优先落在 `douyin/*`(业务流程)与 `operations/*`(底层封装);`Underlying_Operations.py` 多为兼容与兜底,避免把新逻辑持续堆进去。 + +## 配置加载与覆盖优先级(以 config.json 为核心) +- 真实配置文件:`config/config.json`(`path_config.get_config_path()`);GUI/WebGUI 会读写它。 +- `douyin/utils/douyin_config.py:ConfigManager.load_config_from_file()` 会把配置写回 analyser;命令行传入的 `needswitch` 会被保留(命令行优先)。 +- `run_cli.py` 会在创建 `fudai_analyse()` 后,用 CLI 参数覆盖部分字段(如 `min_prize_value_yuan`、`skip_if_countdown_*`、OCR/模板开关等)。 + +## 日志与调试图像(排障首选路径) +- 日志初始化:`douyin/logging/douyin_logging.py:configure_logging()`;统一日志能力在 `unified_logger.py`(traceId/MDC/脱敏)。 +- 业务日志优先用 `analyser._log_kv(...)`(实现见 `douyin/logging/douyin_logging_wrapper.py`):始终 stdout 可被 GUI 捕获,并带阶段分隔。 +- 截图/调试图像:`douyin/handlers/douyin_screenshot_manager.py`(可异步保存;行为日志写入 `logs/actions.log`,路径用 `path_config.get_actions_log_path()`)。 +- 排障开关以 `config/config.json` 为准:优先通过 `debug_captures.*` 控制调试图像(enabled/keep_days/max_files/async_save/log_on_complete),环境变量只作为性能/临时诊断手段。 + +## 状态文件(别改路径/格式) +- 预约队列落盘:`douyin/core/state/reservations.json`(见 `fudai_analyse._reservations_state_path`)。 +- 高价值直播间等状态:`state/high_value_rooms.json`(路径见 `path_config.get_high_value_rooms_path()`)。 + +## 兼容/遗留机制(默认不用,但别误删) +- `run_cli.py` 仍保留 shim + `EXTERNAL_DOUYIN_FUDAI_DIR` 的兼容加载逻辑;本仓库已内置“本地完整版”实现,日常开发以本仓库代码为主。 +- `Underlying_Operations.py` 可能会把 `pic/screenshot.png` 镜像到外部目录;如做性能排查可设 `DISABLE_SCREENSHOT_MIRROR=1`。 + +## 开发约束(本仓库高频踩坑) +- 代码修改规范(硬性):严格 4 空格缩进(禁用 Tab);`try` 必须配 `except/finally`,`if` 必须配对 `else/elif`,`for/while`/`def/class` 块必须完整且缩进正确。 +- 修改流程:先理清缩进层级再改;改完做一次语法自检,避免孤立的 `except/else/elif`、括号/引号不配对、冒号后缺缩进块(详见 `docs/完整技术文档.md`)。 +- 当前仓库没有可运行的 `pytest` 测试集;常用验证方式是跑 `python run_cli.py ...` 或 GUI/WebGUI,并结合 `logs/` + `pic/` 调试输出定位问题。 diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..49fbbfa --- /dev/null +++ b/.pylintrc @@ -0,0 +1,2 @@ +[MASTER] +disable = broad-except,protected-access,unused-argument,unnecessary-pass,unused-variable,unused-import \ No newline at end of file diff --git a/Underlying_Operations.py b/Underlying_Operations.py index eeaad73..8685501 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -55,7 +55,7 @@ _EXTERNAL_AXF_SCREENSHOT = os.path.join( def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 2) -> bool: """安全地替换文件,处理Windows文件锁定问题。 - + 根本优化:优先使用直接复制而不是替换,避免文件锁定问题。 如果文件被占用,直接复制内容而不是等待释放。 @@ -81,7 +81,7 @@ def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 2) -> bo # 如果原子替换失败(文件被占用),直接使用复制方法(避免等待) # 这样可以避免文件锁定导致的长时间等待 pass - + # 方法2: 直接复制文件内容(避免文件锁定问题) # 这是最可靠的方法,即使文件被占用也能成功 try: @@ -128,13 +128,13 @@ def _mirror_screenshot_to_external(src_file: str) -> None: """将当前项目下的 screenshot.png 同步一份到外部 axf 目录,便于完整版代码复用。 若外部目录/路径不存在或复制失败,会静默忽略,不影响主流程。 - + 可通过环境变量 DISABLE_SCREENSHOT_MIRROR=1 禁用此功能以提升性能。 """ # 检查环境变量:是否禁用镜像功能(用于性能测试) if os.environ.get("DISABLE_SCREENSHOT_MIRROR", "0") == "1": return - + mirror_start = time_module.time() try: external_path = _EXTERNAL_AXF_SCREENSHOT @@ -143,7 +143,7 @@ def _mirror_screenshot_to_external(src_file: str) -> None: external_dir = os.path.dirname(external_path) if not external_dir: return - + # 检查外部路径是否是网络路径或可能较慢的路径 external_base = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "") is_network_path = False @@ -156,7 +156,7 @@ def _mirror_screenshot_to_external(src_file: str) -> None: elif ":" in external_base and len(external_base) > 3: # 可能是网络驱动器,但无法确定,记录路径供诊断 logging.debug("[截图] 镜像目标路径: %s", external_path) - + os.makedirs(external_dir, exist_ok=True) if not os.path.exists(src_file): return @@ -168,13 +168,13 @@ def _mirror_screenshot_to_external(src_file: str) -> None: copy_dur = (time_module.time() - copy_start) * 1000.0 if copy_dur > 50.0 or is_network_path: logging.info("[截图] 镜像复制耗时(ms)=%.1f src=%s dst=%s (网络路径=%s)", copy_dur, src_file, tmp, is_network_path) - + replace_start = time_module.time() _safe_replace_file(tmp, external_path) replace_dur = (time_module.time() - replace_start) * 1000.0 if replace_dur > 50.0 or is_network_path: logging.info("[截图] 镜像文件替换耗时(ms)=%.1f (网络路径=%s)", replace_dur, is_network_path) - + mirror_total_dur = (time_module.time() - mirror_start) * 1000.0 if mirror_total_dur > 100.0 or is_network_path: logging.info("[截图] 镜像总耗时(ms)=%.1f path=%s (网络路径=%s)", mirror_total_dur, external_path, is_network_path) @@ -467,12 +467,12 @@ class underlying_operations: def get_screenshot(self, device_id, path="pic", use_service: bool = False): """截图(支持后台服务模式) - + 参数: device_id: 设备ID path: 路径(默认"pic") use_service: 是否使用后台截图服务(默认False,强制使用直接截图) - + 返回: 是否成功获取截图 """ @@ -482,7 +482,7 @@ class underlying_operations: try: from operations.screenshot_service import ScreenshotService service = ScreenshotService.get_instance() - + # 诊断:检查服务是否在运行 service_running = getattr(service, "_running", False) if not service_running: @@ -493,7 +493,7 @@ class underlying_operations: time_module.sleep(0.2) except Exception as start_err: logging.warning("[截图] 启动后台服务失败: %s,将使用直接截图", start_err) - + try: service_result = service.get_screenshot(device_id, force=False) if service_result: @@ -523,11 +523,11 @@ class underlying_operations: dur = (time.time() - start_ts) * 1000.0 logging.info("[截图] 总耗时(ms)=%.1f device=%s use_service=%s result=%s", dur, device_id, bool(use_service), result) return result - + def _get_screenshot_direct(self, device_id, path="pic"): """直接截图(不使用服务模式)""" overall_start = time_module.time() - + if path == "pic": try: import path_config @@ -549,7 +549,7 @@ class underlying_operations: # 检查环境变量:是否跳过PNG验证(用于性能测试) skip_verify = os.environ.get("SKIP_SCREENSHOT_VERIFY", "0") == "1" - + def _valid_png(path0: str) -> bool: if skip_verify: # 快速路径:只检查文件存在和大小 @@ -560,7 +560,7 @@ class underlying_operations: return sz >= 1024 except Exception: return False - + verify_start = time_module.time() try: if not os.path.exists(path0): @@ -587,7 +587,7 @@ class underlying_operations: header_check_dur = (time_module.time() - header_check_start) * 1000.0 if header_check_dur > 10.0: # 只记录超过10ms的 logging.debug("[截图] PNG头尾校验耗时(ms)=%.1f path=%s", header_check_dur, path0) - + # 优化:只在必要时使用 PIL 验证(PIL verify 可能很慢) # 对于临时文件,快速验证已足够;对于最终文件,可以跳过完整验证以提高速度 # 如果文件头尾都正确,大概率是有效的PNG文件 @@ -603,7 +603,7 @@ class underlying_operations: # pil_verify_dur = (time_module.time() - pil_verify_start) * 1000.0 # if pil_verify_dur > 50.0: # 只记录超过50ms的 # logging.debug("[截图] PIL verify耗时(ms)=%.1f path=%s", pil_verify_dur, path0) - + verify_total_dur = (time_module.time() - verify_start) * 1000.0 if verify_total_dur > 100.0: # 只记录超过100ms的 logging.info("[截图] _valid_png总耗时(ms)=%.1f path=%s", verify_total_dur, path0) @@ -635,7 +635,7 @@ class underlying_operations: stderr=subprocess.DEVNULL, bufsize=0, # 无缓冲,立即传输 ) - + # 使用更大的缓冲区(256KB)提高写入效率 if process.stdout is None: raise RuntimeError("ADB process stdout is None") @@ -645,15 +645,15 @@ class underlying_operations: if not chunk: break f.write(chunk) - + # 等待进程完成 return_code = process.wait(timeout=10) if return_code != 0: raise subprocess.CalledProcessError(return_code, [adb, "-s", device_id, "exec-out", "screencap", "-p"]) - + adb_subprocess_dur = (time_module.time() - adb_start) * 1000.0 logging.info("[截图] ADB exec-out subprocess耗时(ms)=%.1f device=%s attempt=%d", adb_subprocess_dur, device_id, attempt + 1) - + # 优化:移除 fsync(现代文件系统会自动同步,减少不必要的磁盘I/O) # 文件写入已经完成,操作系统会在适当时机同步到磁盘 # 这样可以减少 10-50ms 的等待时间 @@ -674,14 +674,14 @@ class underlying_operations: replace_dur = (time_module.time() - replace_start) * 1000.0 if replace_dur > 50.0: logging.info("[截图] 文件替换耗时(ms)=%.1f result=%s", replace_dur, replace_success) - + if replace_success: mirror_start = time_module.time() _mirror_screenshot_to_external(out_file) mirror_dur = (time_module.time() - mirror_start) * 1000.0 if mirror_dur > 50.0: logging.info("[截图] 镜像到外部路径耗时(ms)=%.1f", mirror_dur) - + # 优化:快速验证目标文件(只检查存在和大小,不进行完整PNG验证) # 完整验证可以在读取时进行,不阻塞截图流程 validate_out_start = time_module.time() @@ -698,14 +698,14 @@ class underlying_operations: validate_out_dur = (time_module.time() - validate_out_start) * 1000.0 if validate_out_dur > 50.0: logging.info("[截图] 目标文件快速验证耗时(ms)=%.1f", validate_out_dur) - + overall_dur = (time_module.time() - overall_start) * 1000.0 logging.info("[截图] _get_screenshot_direct总耗时(ms)=%.1f device=%s (exec-out成功)", overall_dur, device_id) print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功") return True except Exception: pass - + # 如果快速验证失败,记录诊断信息 try: st = os.stat(out_file) @@ -770,7 +770,7 @@ class underlying_operations: ) shell_screencap_dur = (time_module.time() - shell_screencap_start) * 1000.0 logging.info("[截图] 回退方案-shell screencap耗时(ms)=%.1f device=%s", shell_screencap_dur, device_id) - + pull_start = time_module.time() subprocess.run( [adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", tmp_file], @@ -781,26 +781,26 @@ class underlying_operations: ) pull_dur = (time_module.time() - pull_start) * 1000.0 logging.info("[截图] 回退方案-adb pull耗时(ms)=%.1f device=%s", pull_dur, device_id) - + fallback_validate_start = time_module.time() if _valid_png(tmp_file): fallback_validate_dur = (time_module.time() - fallback_validate_start) * 1000.0 if fallback_validate_dur > 50.0: logging.info("[截图] 回退方案-临时文件验证耗时(ms)=%.1f", fallback_validate_dur) - + # 使用安全的文件替换函数 fallback_replace_start = time_module.time() if _safe_replace_file(tmp_file, out_file): fallback_replace_dur = (time_module.time() - fallback_replace_start) * 1000.0 if fallback_replace_dur > 50.0: logging.info("[截图] 回退方案-文件替换耗时(ms)=%.1f", fallback_replace_dur) - + fallback_mirror_start = time_module.time() _mirror_screenshot_to_external(out_file) fallback_mirror_dur = (time_module.time() - fallback_mirror_start) * 1000.0 if fallback_mirror_dur > 50.0: logging.info("[截图] 回退方案-镜像耗时(ms)=%.1f", fallback_mirror_dur) - + try: if _valid_png(out_file): overall_dur = (time_module.time() - overall_start) * 1000.0 @@ -1078,7 +1078,7 @@ class underlying_operations: save_debug = os.environ.get("SAVE_DEBUG_IMAGES", "0") == "1" except Exception: pass - + if save_debug: from douyin.handlers import douyin_screenshot_manager @@ -1301,7 +1301,7 @@ class underlying_operations: save_debug = bool(getattr(self, "save_ocr_debug_images", False)) except Exception: pass - + if save_debug: from douyin.handlers import douyin_screenshot_manager import path_config diff --git a/check_jpeg_support.py b/check_jpeg_support.py deleted file mode 100644 index 9939208..0000000 --- a/check_jpeg_support.py +++ /dev/null @@ -1,523 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# pyright: reportOptionalMemberAccess=false -""" -详细检查设备是否支持 JPEG 截图 -测试各种可能的 JPEG 截图方法 -""" - -import os -import sys -import subprocess -import tempfile -import time -from datetime import datetime -from typing import Dict, List, Tuple, cast, IO - -def get_adb_path() -> str: - """获取 adb 路径""" - adb = os.environ.get("ADB_EXECUTABLE", "adb") - if adb.startswith('"') and adb.endswith('"'): - adb = adb[1:-1] - return adb - -def get_device_info(device_id: str) -> Dict[str, str]: - """获取设备信息""" - adb = get_adb_path() - info = {} - - try: - # Android 版本 - result = subprocess.run( - [adb, "-s", device_id, "shell", "getprop", "ro.build.version.release"], - capture_output=True, - text=True, - timeout=3 - ) - info["android_version"] = result.stdout.strip() if result.returncode == 0 else "未知" - except: - info["android_version"] = "未知" - - try: - # 设备型号 - result = subprocess.run( - [adb, "-s", device_id, "shell", "getprop", "ro.product.model"], - capture_output=True, - text=True, - timeout=3 - ) - info["model"] = result.stdout.strip() if result.returncode == 0 else "未知" - except: - info["model"] = "未知" - - try: - # 制造商 - result = subprocess.run( - [adb, "-s", device_id, "shell", "getprop", "ro.product.manufacturer"], - capture_output=True, - text=True, - timeout=3 - ) - info["manufacturer"] = result.stdout.strip() if result.returncode == 0 else "未知" - except: - info["manufacturer"] = "未知" - - return info - -def check_root_access(device_id: str) -> bool: - """检查 root 权限""" - adb = get_adb_path() - try: - result = subprocess.run( - [adb, "-s", device_id, "shell", "su", "-c", "id"], - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - timeout=3, - capture_output=True, - ) - return "uid=0" in result.stdout.decode('utf-8', errors='ignore') - except: - return False - -def test_screencap_jpeg_direct(device_id: str) -> Tuple[bool, str, float]: - """测试方法1: screencap 直接输出 JPEG(如果支持)""" - adb = get_adb_path() - tmp_file = os.path.join(tempfile.gettempdir(), "test_jpeg_direct.jpg") - - # 测试各种可能的 JPEG 参数 - test_commands = [ - ["exec-out", "screencap", "-j"], # 标准 JPEG 参数 - ["exec-out", "screencap", "--jpeg"], # 长参数 - ["exec-out", "screencap", "-f", "jpeg"], # 格式参数 - ["exec-out", "screencap", "-p", "-j"], # PNG + JPEG - ["shell", "screencap", "-j", "/sdcard/test.jpg"], # shell 模式 - ] - - for cmd in test_commands: - try: - if os.path.exists(tmp_file): - try: - os.remove(tmp_file) - except: - pass - - start_time = time.time() - full_cmd = [adb, "-s", device_id] + cmd - - if "exec-out" in cmd: - # 流式读取 - process = subprocess.Popen( - full_cmd, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - ) - - if process.stdout is None: - continue - - assert process.stdout is not None - stdout = cast(IO[bytes], process.stdout) - with open(tmp_file, "wb") as f: - while True: - chunk = stdout.read(65536) # type: ignore[union-attr] - if not chunk: - break - f.write(chunk) - - return_code = process.wait(timeout=5) - else: - # shell 模式 - result = subprocess.run( - full_cmd, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - timeout=5, - ) - return_code = result.returncode - - if return_code == 0 and "shell" in cmd: - # 如果是 shell 模式,需要 pull - subprocess.run( - [adb, "-s", device_id, "pull", "/sdcard/test.jpg", tmp_file], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - timeout=5, - ) - - elapsed = (time.time() - start_time) * 1000 - - if return_code == 0 and os.path.exists(tmp_file): - file_size = os.path.getsize(tmp_file) - # 检查是否是有效的 JPEG(检查文件头) - if file_size > 100: - with open(tmp_file, "rb") as f: - header = f.read(2) - if header == b'\xff\xd8': # JPEG 文件头 - return True, f"命令: {' '.join(cmd)}", elapsed - - except Exception as e: - continue - - return False, "不支持直接 JPEG 输出", 0.0 - -def test_screencap_help(device_id: str) -> Dict[str, bool]: - """检查 screencap 帮助信息,查看支持的参数""" - adb = get_adb_path() - result = {} - - try: - # 获取 screencap 帮助信息 - help_output = "" - try: - help_output += subprocess.run( - [adb, "-s", device_id, "shell", "screencap", "-h"], - capture_output=True, - text=True, - timeout=3, - ).stdout - except: - pass - - try: - help_output += subprocess.run( - [adb, "-s", device_id, "shell", "screencap", "--help"], - capture_output=True, - text=True, - timeout=3, - ).stdout - except: - pass - - # 检查是否包含 JPEG 相关参数 - result["has_jpeg_flag"] = any(keyword in help_output.lower() for keyword in ["-j", "jpeg", "--jpeg"]) - result["has_format_flag"] = any(keyword in help_output.lower() for keyword in ["-f", "format", "--format"]) - result["has_quality_flag"] = any(keyword in help_output.lower() for keyword in ["-q", "quality", "--quality"]) - - except: - result["has_jpeg_flag"] = False - result["has_format_flag"] = False - result["has_quality_flag"] = False - - return result - -def test_device_tools(device_id: str) -> Dict[str, bool]: - """检查设备上是否有可用的转换工具""" - adb = get_adb_path() - tools = {} - - # 检查 ImageMagick convert - try: - result = subprocess.run( - [adb, "-s", device_id, "shell", "which", "convert"], - capture_output=True, - text=True, - timeout=3, - ) - tools["imagemagick"] = result.returncode == 0 and result.stdout.strip() != "" - except: - tools["imagemagick"] = False - - # 检查 /data/local/tmp/convert - try: - result = subprocess.run( - [adb, "-s", device_id, "shell", "test", "-f", "/data/local/tmp/convert"], - capture_output=True, - text=True, - timeout=3, - ) - tools["imagemagick_tmp"] = result.returncode == 0 - except: - tools["imagemagick_tmp"] = False - - # 检查 Python - try: - result = subprocess.run( - [adb, "-s", device_id, "shell", "which", "python3"], - capture_output=True, - text=True, - timeout=3, - ) - tools["python3"] = result.returncode == 0 and result.stdout.strip() != "" - except: - tools["python3"] = False - - # 检查 Python (python) - try: - result = subprocess.run( - [adb, "-s", device_id, "shell", "which", "python"], - capture_output=True, - text=True, - timeout=3, - ) - tools["python"] = result.returncode == 0 and result.stdout.strip() != "" - except: - tools["python"] = False - - # 检查 BusyBox - try: - result = subprocess.run( - [adb, "-s", device_id, "shell", "which", "busybox"], - capture_output=True, - text=True, - timeout=3, - ) - tools["busybox"] = result.returncode == 0 and result.stdout.strip() != "" - except: - tools["busybox"] = False - - return tools - -def test_pc_conversion(device_id: str) -> Tuple[bool, str, float]: - """测试方法2: PC 端转换(PNG -> JPEG)""" - try: - from PIL import Image - import io - except ImportError: - return False, "PIL/Pillow 未安装", 0.0 - - adb = get_adb_path() - tmp_jpg = os.path.join(tempfile.gettempdir(), "test_jpeg_pc.jpg") - - try: - start_time = time.time() - - # 流式接收 PNG - process = subprocess.Popen( - [adb, "-s", device_id, "exec-out", "screencap", "-p"], - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - ) - - if process.stdout is None: - return False, "无法创建进程输出流", 0.0 - - assert process.stdout is not None - stdout = cast(IO[bytes], process.stdout) - png_data = b"" - while True: - chunk = stdout.read(65536) # type: ignore[union-attr] - if not chunk: - break - png_data += chunk - - process.wait(timeout=10) - - if len(png_data) < 100: - return False, "PNG 数据无效", 0.0 - - # 转换为 JPEG(RGBA 需要先转换为 RGB) - img = Image.open(io.BytesIO(png_data)) - if img.mode == 'RGBA': - # 创建白色背景 - rgb_img = Image.new('RGB', img.size, (255, 255, 255)) - rgb_img.paste(img, mask=img.split()[3]) # 使用 alpha 通道作为 mask - img = rgb_img - elif img.mode != 'RGB': - img = img.convert('RGB') - - jpeg_data = io.BytesIO() - img.save(jpeg_data, format='JPEG', quality=85, optimize=True) - - with open(tmp_jpg, "wb") as f: - f.write(jpeg_data.getvalue()) - - elapsed = (time.time() - start_time) * 1000 - file_size = os.path.getsize(tmp_jpg) - - return True, f"PC 端转换成功,文件大小: {file_size/1024:.1f}KB", elapsed - - except Exception as e: - return False, f"PC 端转换失败: {str(e)}", 0.0 - -def test_device_conversion(device_id: str) -> Tuple[bool, str, float]: - """测试方法3: 设备端转换(如果工具可用)""" - adb = get_adb_path() - tools = test_device_tools(device_id) - - # 测试 ImageMagick - if tools.get("imagemagick") or tools.get("imagemagick_tmp"): - convert_path = "/data/local/tmp/convert" if tools.get("imagemagick_tmp") else "convert" - - try: - start_time = time.time() - tmp_file = os.path.join(tempfile.gettempdir(), "test_jpeg_device.jpg") - - # 使用 shell 命令组合 - cmd = f"screencap -p | {convert_path} - -quality 85 jpg:-" - process = subprocess.Popen( - [adb, "-s", device_id, "exec-out", "sh", "-c", cmd], - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - ) - - if process.stdout is None: - raise Exception("无法创建进程输出流") - - assert process.stdout is not None - stdout = cast(IO[bytes], process.stdout) - with open(tmp_file, "wb") as f: - while True: - chunk = stdout.read(65536) # type: ignore[union-attr] - if not chunk: - break - f.write(chunk) - - return_code = process.wait(timeout=10) - elapsed = (time.time() - start_time) * 1000 - - if return_code == 0 and os.path.exists(tmp_file): - file_size = os.path.getsize(tmp_file) - if file_size > 100: - with open(tmp_file, "rb") as f: - header = f.read(2) - if header == b'\xff\xd8': - return True, f"ImageMagick 转换成功,文件大小: {file_size/1024:.1f}KB", elapsed - except Exception as e: - pass - - return False, "设备端无可用转换工具", 0.0 - -def main(): - """主函数""" - print("=" * 70) - print("设备 JPEG 截图支持检查工具") - print("=" * 70) - print() - - # 获取设备ID - device_id = None - if len(sys.argv) > 1: - device_id = sys.argv[1] - else: - device_id = os.environ.get("ANDROID_DEVICE_ID") - - if not device_id: - # 尝试从 adb devices 获取 - try: - adb = get_adb_path() - result = subprocess.run( - [adb, "devices"], - capture_output=True, - text=True, - timeout=3, - ) - lines = result.stdout.strip().split('\n')[1:] # 跳过第一行 - devices = [line.split()[0] for line in lines if line.strip() and 'device' in line] - if len(devices) == 1: - device_id = devices[0] - elif len(devices) > 1: - print(f"[INFO] 发现多个设备: {', '.join(devices)}") - print(f"[INFO] 使用第一个设备: {devices[0]}") - device_id = devices[0] - except: - pass - - if not device_id: - print("[ERROR] 未找到设备ID") - print("使用方法: python check_jpeg_support.py [设备ID]") - print("或设置环境变量: set ANDROID_DEVICE_ID=设备ID") - return - - print(f"设备ID: {device_id}") - print() - - # 获取设备信息 - print("1. 设备信息") - print("-" * 70) - info = get_device_info(device_id) - print(f" 制造商: {info.get('manufacturer', '未知')}") - print(f" 型号: {info.get('model', '未知')}") - print(f" Android 版本: {info.get('android_version', '未知')}") - - has_root = check_root_access(device_id) - print(f" Root 权限: {'是' if has_root else '否'}") - print() - - # 检查 screencap 帮助信息 - print("2. screencap 命令支持检查") - print("-" * 70) - help_info = test_screencap_help(device_id) - print(f" 支持 -j/--jpeg 参数: {'是' if help_info.get('has_jpeg_flag') else '否'}") - print(f" 支持 -f/--format 参数: {'是' if help_info.get('has_format_flag') else '否'}") - print(f" 支持质量参数: {'是' if help_info.get('has_quality_flag') else '否'}") - print() - - # 测试直接 JPEG 输出 - print("3. 测试直接 JPEG 截图") - print("-" * 70) - success, msg, elapsed = test_screencap_jpeg_direct(device_id) - if success: - print(f" [OK] 支持直接 JPEG 输出") - print(f" 方法: {msg}") - print(f" 耗时: {elapsed:.0f}ms") - else: - print(f" [X] 不支持直接 JPEG 输出") - print(f" 原因: {msg}") - print() - - # 检查设备工具 - print("4. 设备端工具检查") - print("-" * 70) - tools = test_device_tools(device_id) - print(f" ImageMagick (convert): {'是' if tools.get('imagemagick') else '否'}") - print(f" ImageMagick (/data/local/tmp): {'是' if tools.get('imagemagick_tmp') else '否'}") - print(f" Python3: {'是' if tools.get('python3') else '否'}") - print(f" Python: {'是' if tools.get('python') else '否'}") - print(f" BusyBox: {'是' if tools.get('busybox') else '否'}") - print() - - # 测试设备端转换 - print("5. 测试设备端转换") - print("-" * 70) - success, msg, elapsed = test_device_conversion(device_id) - if success: - print(f" [OK] 设备端转换可用") - print(f" 方法: {msg}") - print(f" 耗时: {elapsed:.0f}ms") - else: - print(f" [X] 设备端转换不可用") - print(f" 原因: {msg}") - print() - - # 测试 PC 端转换 - print("6. 测试 PC 端转换") - print("-" * 70) - success, msg, elapsed = test_pc_conversion(device_id) - if success: - print(f" [OK] PC 端转换可用") - print(f" 方法: {msg}") - print(f" 耗时: {elapsed:.0f}ms") - else: - print(f" [X] PC 端转换不可用") - print(f" 原因: {msg}") - print() - - # 总结 - print("=" * 70) - print("检查结果总结") - print("=" * 70) - - recommendations = [] - - direct_success, _, _ = test_screencap_jpeg_direct(device_id) - pc_success, _, _ = test_pc_conversion(device_id) - device_success, _, _ = test_device_conversion(device_id) - - if direct_success: - recommendations.append("[OK] 设备支持直接 JPEG 截图(推荐使用)") - elif pc_success: - recommendations.append("[OK] 可以使用 PC 端转换方法(推荐,无需设备端工具)") - elif device_success: - recommendations.append("[OK] 可以使用设备端转换方法(需要安装工具)") - else: - recommendations.append("[X] 当前设备不支持 JPEG 截图,建议使用 PNG 格式") - - for rec in recommendations: - print(f" {rec}") - - print() - print("=" * 70) - -if __name__ == "__main__": - main() - diff --git a/check_screenshot.py b/check_screenshot.py deleted file mode 100644 index db81aa3..0000000 --- a/check_screenshot.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -检查截图文件状态 -""" - -import os -import sys - -def check_screenshot_file(): - pic_path = r"C:\Users\12742\Desktop\douyin_guaji-main\pic\screenshot.png" - - if os.path.exists(pic_path): - size = os.path.getsize(pic_path) - print(f"screenshot.png exists, size: {size} bytes") - - if size == 0: - print("WARNING: Screenshot file is empty!") - elif size < 1024: - print("WARNING: Screenshot file is too small (possibly corrupted)") - else: - print("Screenshot file size looks normal") - - # Try to read first 4 bytes to check PNG header - try: - with open(pic_path, 'rb') as f: - header = f.read(4) - if header == b'\x89PNG': - print("PNG file format is correct") - else: - print(f"WARNING: File format issue, header: {header}") - except Exception as e: - print(f"ERROR reading file: {e}") - - else: - print("screenshot.png does not exist") - - # Check tmp file - tmp_path = pic_path + ".tmp" - if os.path.exists(tmp_path): - tmp_size = os.path.getsize(tmp_path) - print(f"screenshot.png.tmp exists, size: {tmp_size} bytes") - else: - print("screenshot.png.tmp does not exist") - -if __name__ == "__main__": - check_screenshot_file() - - - - - - - - - - - - - - diff --git a/check_screenshot_service_status.py b/check_screenshot_service_status.py deleted file mode 100644 index 15b044c..0000000 --- a/check_screenshot_service_status.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python3 -"""检查后台截图服务状态""" - -import time -from operations.screenshot_service import ScreenshotService - -def main(): - print("=== 后台截图服务状态检查 ===\n") - - service = ScreenshotService.get_instance() - info = service.get_cache_info() - - print("服务状态:") - print(f" 运行中: {info['running']}") - print(f" 设备ID: {info.get('device_id', 'None')}") - print(f" 截图间隔: {info.get('interval', 'N/A')}秒") - print(f" 缓存有效期: {info.get('cache_valid_duration', 'N/A')}秒") - - last_time = info.get('last_screenshot_time', 0) - if last_time > 0: - time_since = time.time() - last_time - print(f"\n最后截图时间: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(last_time))}") - print(f" 距离现在: {time_since:.1f}秒前") - print(f" 缓存状态: {'有效' if time_since < info.get('cache_valid_duration', 4.0) else '已过期'}") - print(f" 最后成功: {info.get('last_success', False)}") - else: - print("\n最后截图时间: 从未截图") - print(" 缓存状态: 无缓存") - - print("\n=== 诊断结果 ===") - - if not info['running']: - print("[ERROR] 后台截图服务未运行") - print(" 原因: 服务可能未启动或已停止") - elif not info.get('device_id'): - print("[ERROR] 设备ID为空") - print(" 原因: 服务启动时未设置设备ID") - elif last_time == 0: - print("[WARN] 服务运行中但从未成功截图") - print(" 可能原因:") - print(" 1. ADB连接问题") - print(" 2. 设备未连接") - print(" 3. 截图操作失败") - elif time.time() - last_time > 10: - print("[WARN] 服务运行中但最近未截图") - print(f" 距离上次截图已过: {time.time() - last_time:.1f}秒") - print(" 可能原因: 后台线程异常或截图失败") - else: - print("[OK] 后台截图服务运行正常") - print(f" 缓存有效,响应时间应该 < 10ms") - - # 检查是否有后台线程在运行 - if hasattr(service, '_thread') and service._thread: - print(f"\n后台线程状态:") - print(f" 线程存在: True") - print(f" 线程存活: {service._thread.is_alive() if service._thread else False}") - else: - print("\n后台线程状态: 未创建") - -if __name__ == '__main__': - main() - - - - - - - - - - - - diff --git a/config/config.json b/config/config.json index bed0103..b6d9411 100644 --- a/config/config.json +++ b/config/config.json @@ -1,11 +1,11 @@ { - "needswitch": false, + "needswitch": true, "infinite_loop_enabled": true, "wait_minutes": 5, "min_prize_value_yuan": 200.0, "min_participants": 0, "max_participants": 0, - "skip_if_countdown_gt_seconds": 1800, + "skip_if_countdown_gt_seconds": 180, "reset_after_swipes_enabled": true, "reset_after_swipes": 10, "auto_join_fansclub": true, @@ -134,9 +134,9 @@ "async_save": false, "log_on_complete": false }, - "fudai_detail_template_threshold": 0.54, + "fudai_detail_template_threshold": 0.53, "switch_room_wait_after_stage_diag_seconds": 4.0, - "coupon_template_match_threshold": 0.4, + "coupon_template_match_threshold": 0.37, "attend_button_red_ratio_threshold": 0.25, "fansclub_join_red_ratio_threshold": 0.25, "reservation_test_mode": false, diff --git a/test_adb_screenshot_timing.py b/deleted_tests_backup/test_adb_screenshot_timing.py similarity index 97% rename from test_adb_screenshot_timing.py rename to deleted_tests_backup/test_adb_screenshot_timing.py index b81ea39..3b8604a 100644 --- a/test_adb_screenshot_timing.py +++ b/deleted_tests_backup/test_adb_screenshot_timing.py @@ -47,7 +47,7 @@ def get_device_id() -> Optional[str]: if result.returncode != 0: print(f"[错误] adb devices 失败: {result.stderr}") return None - + lines = result.stdout.strip().split("\n")[1:] # 跳过第一行 "List of devices attached" devices = [] for line in lines: @@ -55,14 +55,14 @@ def get_device_id() -> Optional[str]: device_id = line.split("\t")[0].strip() if device_id: devices.append(device_id) - + if not devices: print("[错误] 未找到连接的设备") return None - + if len(devices) > 1: print(f"[提示] 找到多个设备: {devices},使用第一个: {devices[0]}") - + return devices[0] except Exception as e: print(f"[错误] 获取设备列表失败: {e}") @@ -77,10 +77,10 @@ def test_exec_out_screencap(device_id: str, iterations: int = 5) -> None: print(f"设备: {device_id}") print(f"迭代次数: {iterations}") print(f"{'='*60}\n") - + times = [] sizes = [] - + for i in range(iterations): try: start = time.time() @@ -90,7 +90,7 @@ def test_exec_out_screencap(device_id: str, iterations: int = 5) -> None: timeout=15, ) elapsed = (time.time() - start) * 1000.0 # 转换为毫秒 - + if result.returncode == 0: size = len(result.stdout) times.append(elapsed) @@ -102,13 +102,13 @@ def test_exec_out_screencap(device_id: str, iterations: int = 5) -> None: print(f" 迭代 {i+1}: 超时 (>15秒)") except Exception as e: print(f" 迭代 {i+1}: 异常: {e}") - + if times: avg_time = sum(times) / len(times) min_time = min(times) max_time = max(times) avg_size = sum(sizes) / len(sizes) if sizes else 0 - + print(f"\n{'='*60}") print(f"统计结果:") print(f" 平均耗时: {avg_time:.1f}ms") @@ -116,7 +116,7 @@ def test_exec_out_screencap(device_id: str, iterations: int = 5) -> None: print(f" 最大耗时: {max_time:.1f}ms") print(f" 平均大小: {avg_size/1024:.1f}KB") print(f"{'='*60}\n") - + if avg_time > 3000: print("[警告] 平均耗时超过3秒,可能存在问题:") print(" - 检查 USB 连接是否稳定") @@ -136,17 +136,17 @@ def test_shell_screencap_pull(device_id: str, iterations: int = 3) -> None: print(f"设备: {device_id}") print(f"迭代次数: {iterations}") print(f"{'='*60}\n") - + times = [] - + for i in range(iterations): try: # 清理旧文件 subprocess.run([adb, "-s", device_id, "shell", "rm", "/sdcard/DCIM/screenshot.png"], capture_output=True, timeout=5) - + start = time.time() - + # Step 1: shell screencap step1_start = time.time() result1 = subprocess.run( @@ -155,11 +155,11 @@ def test_shell_screencap_pull(device_id: str, iterations: int = 3) -> None: timeout=10, ) step1_dur = (time.time() - step1_start) * 1000.0 - + if result1.returncode != 0: print(f" 迭代 {i+1}: shell screencap 失败") continue - + # Step 2: pull step2_start = time.time() result2 = subprocess.run( @@ -168,9 +168,9 @@ def test_shell_screencap_pull(device_id: str, iterations: int = 3) -> None: timeout=10, ) step2_dur = (time.time() - step2_start) * 1000.0 - + elapsed = (time.time() - start) * 1000.0 - + if result2.returncode == 0 and os.path.exists("test_screenshot.png"): size = os.path.getsize("test_screenshot.png") times.append(elapsed) @@ -183,12 +183,12 @@ def test_shell_screencap_pull(device_id: str, iterations: int = 3) -> None: print(f" 迭代 {i+1}: pull 失败") except Exception as e: print(f" 迭代 {i+1}: 异常: {e}") - + if times: avg_time = sum(times) / len(times) min_time = min(times) max_time = max(times) - + print(f"\n{'='*60}") print(f"统计结果 (回退方案):") print(f" 平均耗时: {avg_time:.1f}ms") @@ -203,23 +203,20 @@ def main(): device_id = sys.argv[1] else: device_id = get_device_id() - + if not device_id: print("[错误] 无法获取设备ID") sys.exit(1) - + print(f"使用设备: {device_id}") print(f"ADB 路径: {get_adb_path()}") - + # 测试 exec-out(主要方案) test_exec_out_screencap(device_id, iterations=5) - + # 测试 shell + pull(回退方案,较少迭代) test_shell_screencap_pull(device_id, iterations=3) if __name__ == "__main__": main() - - - diff --git a/test_completely_disable_screenshot_service.py b/deleted_tests_backup/test_completely_disable_screenshot_service.py similarity index 100% rename from test_completely_disable_screenshot_service.py rename to deleted_tests_backup/test_completely_disable_screenshot_service.py diff --git a/test_direct_screenshot.py b/deleted_tests_backup/test_direct_screenshot.py similarity index 96% rename from test_direct_screenshot.py rename to deleted_tests_backup/test_direct_screenshot.py index da7d6d9..85058b0 100644 --- a/test_direct_screenshot.py +++ b/deleted_tests_backup/test_direct_screenshot.py @@ -17,10 +17,10 @@ def test_screenshot_operations(): print("=" * 80) print("测试 1: operations.screenshot_operations.get_screenshot()") print("=" * 80) - + try: from operations.screenshot_operations import get_screenshot, ScreenshotOperations - + # 获取设备ID device_id = os.environ.get("DEVICE_ID", "") if not device_id: @@ -34,11 +34,11 @@ def test_screenshot_operations(): except Exception: print("[ERROR] 无法获取设备ID,请设置环境变量 DEVICE_ID") return False - + print(f"设备ID: {device_id}") print(f"测试模式: 直接截图 (use_service=False)") print() - + # 测试1: 使用默认参数(应该是 False) print("测试 1.1: 使用默认参数调用 get_screenshot()") start = time.time() @@ -50,9 +50,9 @@ def test_screenshot_operations(): except Exception as e: elapsed = (time.time() - start) * 1000 print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms") - + print() - + # 测试2: 显式传递 use_service=False print("测试 1.2: 显式传递 use_service=False") start = time.time() @@ -65,9 +65,9 @@ def test_screenshot_operations(): except Exception as e: elapsed = (time.time() - start) * 1000 print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms") - + print() - + # 测试3: 验证不会使用服务模式 print("测试 1.3: 验证不会调用后台服务") try: @@ -75,22 +75,22 @@ def test_screenshot_operations(): service = ScreenshotService.get_instance() service_running_before = service.is_running() print(f" 服务运行状态(测试前): {service_running_before}") - + # 调用截图(应该不会启动服务) get_screenshot(device_id) - + service_running_after = service.is_running() print(f" 服务运行状态(测试后): {service_running_after}") - + if not service_running_after: print(" [OK] 确认:服务未被启动(符合预期)") else: print(" [WARN] 警告:服务仍在运行(可能之前已启动)") except Exception as e: print(f" [WARN] 无法检查服务状态: {e}") - + return True - + except ImportError as e: print(f"[ERROR] 导入错误: {e}") return False @@ -107,16 +107,16 @@ def test_underlying_operations(): print("=" * 80) print("测试 2: Underlying_Operations.get_screenshot()") print("=" * 80) - + try: from Underlying_Operations import underlying_operations - + device_id = os.environ.get("DEVICE_ID", "MB75DEFQZHZTGMLJ") print(f"设备ID: {device_id}") print() - + ops = underlying_operations() - + # 测试默认参数 print("测试 2.1: 使用默认参数(应该是 False)") start = time.time() @@ -125,7 +125,7 @@ def test_underlying_operations(): elapsed = (time.time() - start) * 1000 status = "[OK] 成功" if result else "[FAIL] 失败" print(f" 结果: {status}, 耗时: {elapsed:.1f}ms") - + if elapsed > 2000: print(f" [WARN] 警告:耗时较长 ({elapsed:.1f}ms),但应该 < 2秒") elif elapsed > 6000: @@ -137,9 +137,9 @@ def test_underlying_operations(): print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms") import traceback traceback.print_exc() - + return True - + except Exception as e: print(f"[ERROR] 测试失败: {e}") import traceback @@ -153,17 +153,17 @@ def test_stage_diagnosis_screenshot(): print("=" * 80) print("测试 3: 阶段诊断截图调用(模拟)") print("=" * 80) - + try: # 检查关键文件中的调用 import inspect from douyin.core import douyin_fudai - + # 查找 get_screenshot 调用 source_file = inspect.getfile(douyin_fudai.fudai_analyse) with open(source_file, 'r', encoding='utf-8') as f: content = f.read() - + # 检查是否包含 use_service=False if 'get_screenshot(self.device_id, use_service=False)' in content: print(" [OK] 确认:douyin_fudai.py 中已使用 use_service=False") @@ -172,9 +172,9 @@ def test_stage_diagnosis_screenshot(): print(" (但默认值应该是 False)") else: print(" [WARN] 未找到 get_screenshot 调用") - + return True - + except Exception as e: print(f" [WARN] 无法检查: {e}") return False @@ -186,25 +186,25 @@ def check_logs_for_timeouts(): print("=" * 80) print("测试 4: 检查日志中的超时记录") print("=" * 80) - + try: import glob log_files = glob.glob("logs/unified_*.log") if not log_files: print(" [WARN] 未找到日志文件") return True - + # 读取最新的日志文件 latest_log = max(log_files, key=os.path.getmtime) print(f" 检查日志文件: {latest_log}") - + timeout_count = 0 screenshot_count = 0 - + with open(latest_log, 'r', encoding='utf-8', errors='ignore') as f: # 只读取最后 1000 行 lines = f.readlines()[-1000:] - + for line in lines: if '[TIMEOUT] 等待超时' in line or '等待超时' in line: timeout_count += 1 @@ -220,17 +220,17 @@ def check_logs_for_timeouts(): print(f" [WARN] 发现耗时过长的截图: {elapsed:.2f}秒") except Exception: pass - + print(f" 超时记录数(最近1000行): {timeout_count}") print(f" 截图耗时记录数: {screenshot_count}") - + if timeout_count == 0: print(" [OK] 未发现超时记录(符合预期)") else: print(f" [WARN] 发现 {timeout_count} 条超时记录") - + return True - + except Exception as e: print(f" [WARN] 无法检查日志: {e}") return False @@ -244,37 +244,37 @@ def main(): print("=" * 80) print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print() - + results = [] - + # 测试1: screenshot_operations results.append(("screenshot_operations", test_screenshot_operations())) - + # 测试2: underlying_operations results.append(("underlying_operations", test_underlying_operations())) - + # 测试3: 代码检查 results.append(("stage_diagnosis", test_stage_diagnosis_screenshot())) - + # 测试4: 日志检查 results.append(("log_check", check_logs_for_timeouts())) - + # 总结 print() print("=" * 80) print("测试总结") print("=" * 80) - + passed = sum(1 for _, result in results if result) total = len(results) - + for name, result in results: status = "[PASS] 通过" if result else "[FAIL] 失败" print(f" {name}: {status}") - + print() print(f"总计: {passed}/{total} 测试通过") - + if passed == total: print("[SUCCESS] 所有测试通过!") return 0 @@ -285,4 +285,3 @@ def main(): if __name__ == "__main__": exit(main()) - diff --git a/test_disable_streaming_screenshots.py b/deleted_tests_backup/test_disable_streaming_screenshots.py similarity index 100% rename from test_disable_streaming_screenshots.py rename to deleted_tests_backup/test_disable_streaming_screenshots.py diff --git a/test_loop_screenshot_stop.py b/deleted_tests_backup/test_loop_screenshot_stop.py similarity index 99% rename from test_loop_screenshot_stop.py rename to deleted_tests_backup/test_loop_screenshot_stop.py index bb7c3ff..ece2c48 100644 --- a/test_loop_screenshot_stop.py +++ b/deleted_tests_backup/test_loop_screenshot_stop.py @@ -93,7 +93,3 @@ def test_loop_screenshot_service_stop(): if __name__ == "__main__": success = test_loop_screenshot_service_stop() sys.exit(0 if success else 1) - - - - diff --git a/test_ocr_multithread.py b/deleted_tests_backup/test_ocr_multithread.py similarity index 98% rename from test_ocr_multithread.py rename to deleted_tests_backup/test_ocr_multithread.py index 7d4b779..3e347dd 100644 --- a/test_ocr_multithread.py +++ b/deleted_tests_backup/test_ocr_multithread.py @@ -16,25 +16,25 @@ def test_ocr_multithread_config(): print("OCR多线程配置检查") print("=" * 70) print() - + # 1. CPU信息 cpu_count = os.cpu_count() or 4 print(f"1. CPU信息") print("-" * 70) print(f" CPU核心数: {cpu_count}") print() - + # 2. OMP线程数配置 print("2. OMP线程数配置(底层库多线程)") print("-" * 70) omp_threads = os.environ.get("OMP_NUM_THREADS", "未设置") print(f" OMP_NUM_THREADS: {omp_threads}") - + # 计算推荐的OMP线程数 optimal_omp_threads = min(4, max(2, cpu_count // 3)) print(f" 推荐值: {optimal_omp_threads} (根据CPU核心数动态计算)") print() - + # 3. 线程池大小配置 print("3. 线程池大小配置(任务级多线程)") print("-" * 70) @@ -42,7 +42,7 @@ def test_ocr_multithread_config(): print(f" 推荐线程池大小: {optimal_workers} (根据CPU核心数动态计算)") print(f" 说明: 用于并行执行多个OCR任务") print() - + # 4. 优化说明 print("4. 优化说明") print("-" * 70) @@ -60,7 +60,7 @@ def test_ocr_multithread_config(): print(" - 充分利用多核CPU资源") print(" - 预计性能提升: 30-50% (取决于任务数量和CPU核心数)") print() - + # 5. 验证OCR引擎是否已初始化 print("5. OCR引擎状态") print("-" * 70) @@ -74,7 +74,7 @@ def test_ocr_multithread_config(): except Exception as e: print(f" 状态: 检查失败 - {e}") print() - + print("=" * 70) print("检查完成") print("=" * 70) @@ -98,11 +98,3 @@ def test_ocr_performance(): if __name__ == "__main__": test_ocr_multithread_config() test_ocr_performance() - - - - - - - - diff --git a/test_ocr_multithread_performance.py b/deleted_tests_backup/test_ocr_multithread_performance.py similarity index 97% rename from test_ocr_multithread_performance.py rename to deleted_tests_backup/test_ocr_multithread_performance.py index e6eba3f..87fbd71 100644 --- a/test_ocr_multithread_performance.py +++ b/deleted_tests_backup/test_ocr_multithread_performance.py @@ -17,27 +17,27 @@ def test_ocr_single(image_path, ocr_processor, omp_threads): """测试单个OCR任务的性能""" old_omp = os.environ.get('OMP_NUM_THREADS', '4') os.environ['OMP_NUM_THREADS'] = str(omp_threads) - + try: img = Image.open(image_path) if img.mode != 'RGB': img = img.convert('RGB') img_np = np.array(img) - + start_time = time.time() - + if ocr_processor.ocr_type == "easyocr": result = ocr_processor.ocr.readtext(img_np) else: result = ocr_processor.ocr.ocr(img_np) - + elapsed = (time.time() - start_time) * 1000 - + # 提取文本 from Underlying_Operations import underlying_operations ops = underlying_operations() text = ops.extract_ocr_content(result) - + return { 'time': elapsed, 'text': text, @@ -61,24 +61,24 @@ def test_ocr_config(image_path, config_name, omp_threads, num_iterations=5): print(f"OMP_NUM_THREADS: {omp_threads}") print(f"迭代次数: {num_iterations}") print() - + # 初始化OCR try: from operations.ocr_operations import OCRProcessor ocr_processor = OCRProcessor() ensure_ocr = getattr(ocr_processor, '_ensure_ocr') ensure_ocr() - + if ocr_processor.ocr is None: print("[ERROR] OCR引擎未初始化") return None - + print(f"OCR引擎: {ocr_processor.ocr_type}") print() except Exception as e: print(f"[ERROR] OCR引擎初始化失败: {e}") return None - + # 执行多次测试 times = [] for i in range(num_iterations): @@ -88,21 +88,21 @@ def test_ocr_config(image_path, config_name, omp_threads, num_iterations=5): print(f" 第{i+1}次: {result['time']:.0f}ms - {result['text'][:30] if result['text'] else '(空)'}") else: print(f" 第{i+1}次: 失败 - {result.get('error', 'Unknown')}") - + if not times: print("[ERROR] 所有测试都失败") return None - + avg_time = sum(times) / len(times) min_time = min(times) max_time = max(times) - + print() print(f"平均耗时: {avg_time:.0f}ms") print(f"最快: {min_time:.0f}ms") print(f"最慢: {max_time:.0f}ms") print() - + return { 'avg_time': avg_time, 'min_time': min_time, @@ -119,42 +119,42 @@ def test_parallel_ocr(image_path, config_name, omp_threads, max_workers, num_tas print(f"线程池大小: {max_workers}") print(f"任务数量: {num_tasks}") print() - + # 设置OMP线程数 old_omp = os.environ.get('OMP_NUM_THREADS', '4') os.environ['OMP_NUM_THREADS'] = str(omp_threads) - + # 初始化OCR try: from operations.ocr_operations import OCRProcessor ocr_processor = OCRProcessor() ensure_ocr = getattr(ocr_processor, '_ensure_ocr') ensure_ocr() - + if ocr_processor.ocr is None: print("[ERROR] OCR引擎未初始化") os.environ['OMP_NUM_THREADS'] = old_omp return None - + print(f"OCR引擎: {ocr_processor.ocr_type}") print() except Exception as e: print(f"[ERROR] OCR引擎初始化失败: {e}") os.environ['OMP_NUM_THREADS'] = old_omp return None - + # 创建多个相同的任务(使用同一张图片) def ocr_task(): return test_ocr_single(image_path, ocr_processor, omp_threads) - + # 并行执行 print("开始并行OCR识别...") start_time = time.time() results = [] - + with ThreadPoolExecutor(max_workers=max_workers) as executor: futures = [executor.submit(ocr_task) for _ in range(num_tasks)] - + for i, future in enumerate(futures): try: result = future.result(timeout=60) @@ -166,12 +166,12 @@ def test_parallel_ocr(image_path, config_name, omp_threads, max_workers, num_tas except Exception as e: print(f" 任务{i+1}: 异常 - {e}") results.append({'success': False, 'error': str(e)}) - + total_elapsed = (time.time() - start_time) * 1000 - + # 恢复OMP设置 os.environ['OMP_NUM_THREADS'] = old_omp - + # 统计结果 successful_results = [r for r in results if r.get('success', False)] efficiency = 0 # 初始化效率变量 @@ -188,7 +188,7 @@ def test_parallel_ocr(image_path, config_name, omp_threads, max_workers, num_tas efficiency = total_task_time / total_elapsed print(f"并行效率: {efficiency:.2f}x (理想值: {num_tasks:.1f}x)") print() - + return { 'total_time': total_elapsed, 'avg_task_time': avg_task_time, @@ -203,26 +203,26 @@ def main(): """主函数""" # 默认图片路径 default_image = "pic/debug_captures/2025-12-31/20251231_152118_ocr_福袋倒计时_分钟_识别后_(390,1110)-(480,1230)_模式_1_文本长度_2_数字_14_类型_digits_平均置信度_0.9991_最小置信度_0.9991_最大置信度_0.9991_置信度项数_1_有完整截图_是_有坐标_是.png" - + if len(sys.argv) > 1: image_path = sys.argv[1] else: image_path = default_image - + if not os.path.isabs(image_path): project_root = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(project_root, image_path) - + if not os.path.exists(image_path): print(f"[ERROR] 图片文件不存在: {image_path}") return - + print("=" * 70) print("OCR多线程性能测试") print("=" * 70) print() print(f"测试图片: {os.path.basename(image_path)}") - + # 获取系统信息 cpu_count = os.cpu_count() or 4 print(f"CPU核心数: {cpu_count}") @@ -233,7 +233,7 @@ def main(): except (ImportError, AttributeError): optimal_workers = 6 print() - + # 测试1: 单次OCR - 优化前 print("\n" + "="*70) print("测试1: 单次OCR性能对比") @@ -244,9 +244,9 @@ def main(): omp_threads=1, num_iterations=5 ) - + time.sleep(1) - + # 测试2: 单次OCR - 优化后 result_single_new = test_ocr_config( image_path, @@ -254,7 +254,7 @@ def main(): omp_threads=6, num_iterations=5 ) - + # 测试3: 并行OCR - 优化前 print("\n" + "="*70) print("测试2: 并行OCR性能对比") @@ -266,9 +266,9 @@ def main(): max_workers=6, num_tasks=6 ) - + time.sleep(1) - + # 测试4: 并行OCR - 优化后 result_parallel_new = test_parallel_ocr( image_path, @@ -277,38 +277,38 @@ def main(): max_workers=optimal_workers, num_tasks=6 ) - + # 性能对比总结 print() print("=" * 70) print("性能对比总结") print("=" * 70) print() - + if result_single_old and result_single_new: old_avg = result_single_old['avg_time'] new_avg = result_single_new['avg_time'] speedup = old_avg / new_avg if new_avg > 0 else 0 - + print("单次OCR性能:") print(f" 优化前平均: {old_avg:.0f}ms") print(f" 优化后平均: {new_avg:.0f}ms") print(f" 性能提升: {speedup:.2f}x") print(f" 时间减少: {(1 - new_avg/old_avg)*100:.1f}%") print() - + if result_parallel_old and result_parallel_new: old_total = result_parallel_old['total_time'] new_total = result_parallel_new['total_time'] speedup = old_total / new_total if new_total > 0 else 0 - + print("并行OCR性能:") print(f" 优化前总耗时: {old_total:.0f}ms ({old_total/1000:.2f}秒)") print(f" 优化后总耗时: {new_total:.0f}ms ({new_total/1000:.2f}秒)") print(f" 性能提升: {speedup:.2f}x") print(f" 时间减少: {(1 - new_total/old_total)*100:.1f}%") print() - + old_avg = result_parallel_old['avg_task_time'] new_avg = result_parallel_new['avg_task_time'] print("单任务性能:") @@ -316,13 +316,10 @@ def main(): print(f" 优化后平均任务: {new_avg:.0f}ms") print(f" 单任务性能提升: {old_avg/new_avg:.2f}x" if new_avg > 0 else " 单任务性能提升: N/A") print() - + print("=" * 70) print("测试完成") print("=" * 70) if __name__ == "__main__": main() - - - diff --git a/test_ocr_speed.py b/deleted_tests_backup/test_ocr_speed.py similarity index 96% rename from test_ocr_speed.py rename to deleted_tests_backup/test_ocr_speed.py index a5414ce..ba01984 100644 --- a/test_ocr_speed.py +++ b/deleted_tests_backup/test_ocr_speed.py @@ -15,18 +15,18 @@ def test_ocr_speed(image_path: str, iterations: int = 5): print("OCR速度测试") print("=" * 70) print() - + # 检查图片文件是否存在 if not os.path.exists(image_path): print(f"[ERROR] 图片文件不存在: {image_path}") return - + file_size = os.path.getsize(image_path) / 1024 # KB print(f"测试图片: {image_path}") print(f"文件大小: {file_size:.2f} KB") print(f"测试次数: {iterations} 次") print() - + # 获取图片信息 try: from PIL import Image @@ -34,11 +34,11 @@ def test_ocr_speed(image_path: str, iterations: int = 5): width, height = img.size print(f"图片尺寸: {width}x{height}") print(f"图片模式: {img.mode}") - + # 计算图片像素数 total_pixels = width * height print(f"总像素数: {total_pixels:,}") - + # 判断图片大小 if total_pixels > 2000000: # 大于200万像素 print(f" [提示] 图片较大,OCR处理可能需要较长时间") @@ -47,44 +47,44 @@ def test_ocr_speed(image_path: str, iterations: int = 5): except Exception as e: print(f"[WARNING] 无法读取图片信息: {e}") print() - + # 检查OCR引擎 print("1. OCR引擎信息") print("-" * 70) try: from operations.ocr_operations import _ocr_processor _ocr_processor._ensure_ocr() - + if _ocr_processor.ocr is None: print("[ERROR] OCR引擎未初始化") return - + print(f" OCR引擎: {_ocr_processor.ocr_type}") print(f" OMP线程数: {os.environ.get('OMP_NUM_THREADS', '未设置')}") print() except Exception as e: print(f"[ERROR] OCR引擎检查失败: {e}") return - + # 测试OCR速度 print("2. OCR速度测试") print("-" * 70) - + times = [] results = [] - + for i in range(iterations): try: # 导入OCR操作 from Underlying_Operations import underlying_operations ops = underlying_operations() - + # 确保OCR已初始化 ops._ensure_ocr() - + # 执行OCR(使用analyse_pic_digits,因为这是数字识别) start_time = time.time() - + # 直接使用图片路径进行OCR # 注意:如果图片很大,OCR会处理整个图片,这可能会很慢 # 建议使用预处理后的小图片进行测试 @@ -93,23 +93,23 @@ def test_ocr_speed(image_path: str, iterations: int = 5): change_color=1, # 数字识别模式 pic_path=image_path ) - + # 记录各个阶段的耗时(如果可能) # 注意:analyse_pic_digits 内部会进行图像预处理和OCR识别 - + elapsed = (time.time() - start_time) * 1000 # 转换为毫秒 times.append(elapsed) results.append(result) - + print(f" 第 {i+1} 次: {elapsed:.0f}ms, 识别结果: {result[:50] if result else '(空)'}") - + except Exception as e: print(f" 第 {i+1} 次: 失败 - {e}") import traceback traceback.print_exc() - + print() - + # 统计结果 if times: print("3. 性能统计") @@ -117,13 +117,13 @@ def test_ocr_speed(image_path: str, iterations: int = 5): avg_time = sum(times) / len(times) min_time = min(times) max_time = max(times) - + print(f" 平均耗时: {avg_time:.0f}ms") print(f" 最快耗时: {min_time:.0f}ms") print(f" 最慢耗时: {max_time:.0f}ms") print(f" 耗时范围: {max_time - min_time:.0f}ms") print() - + # 识别结果统计 print("4. 识别结果") print("-" * 70) @@ -132,7 +132,7 @@ def test_ocr_speed(image_path: str, iterations: int = 5): count = results.count(result) print(f" 结果 {i}: {result[:100] if result else '(空)'} (出现 {count} 次)") print() - + # 性能评估 print("5. 性能评估") print("-" * 70) @@ -147,7 +147,7 @@ def test_ocr_speed(image_path: str, iterations: int = 5): else: print(" [很慢] OCR速度很慢 (> 5000ms)") print(" 提示: 如果图片很大,建议先裁剪到目标区域再OCR") - + # 多线程效果评估 cpu_count = os.cpu_count() or 4 omp_threads = int(os.environ.get('OMP_NUM_THREADS', '1')) @@ -160,7 +160,7 @@ def test_ocr_speed(image_path: str, iterations: int = 5): print() else: print("[ERROR] 所有测试都失败了") - + print("=" * 70) print("测试完成") print("=" * 70) @@ -169,13 +169,13 @@ def main(): """主函数""" # 默认图片路径 default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" - + # 从命令行参数获取图片路径 if len(sys.argv) > 1: image_path = sys.argv[1] else: image_path = default_image - + # 获取测试次数 iterations = 5 if len(sys.argv) > 2: @@ -183,15 +183,14 @@ def main(): iterations = int(sys.argv[2]) except: pass - + # 转换为绝对路径 if not os.path.isabs(image_path): # 尝试相对于项目根目录 project_root = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(project_root, image_path) - + test_ocr_speed(image_path, iterations) if __name__ == "__main__": main() - diff --git a/test_ocr_speed_optimized.py b/deleted_tests_backup/test_ocr_speed_optimized.py similarity index 96% rename from test_ocr_speed_optimized.py rename to deleted_tests_backup/test_ocr_speed_optimized.py index 4e20d06..b64c5e5 100644 --- a/test_ocr_speed_optimized.py +++ b/deleted_tests_backup/test_ocr_speed_optimized.py @@ -16,12 +16,12 @@ def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iteratio print("OCR速度测试(区域优化版)") print("=" * 70) print() - + # 检查图片文件是否存在 if not os.path.exists(image_path): print(f"[ERROR] 图片文件不存在: {image_path}") return - + # 加载图片 try: img = Image.open(image_path) @@ -33,7 +33,7 @@ def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iteratio except Exception as e: print(f"[ERROR] 无法加载图片: {e}") return - + # 如果指定了区域,裁剪图片 if region: x1, y1, x2, y2 = region @@ -42,7 +42,7 @@ def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iteratio print(f"裁剪后尺寸: {img.size[0]}x{img.size[1]}") print(f"裁剪后像素数: {img.size[0] * img.size[1]:,}") print() - + # 保存裁剪后的临时图片 import tempfile temp_dir = tempfile.gettempdir() @@ -51,70 +51,70 @@ def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iteratio test_image_path = temp_image else: test_image_path = image_path - + # 测试OCR速度 print("开始OCR速度测试...") print("-" * 70) - + try: from operations.ocr_operations import _ocr_processor _ocr_processor._ensure_ocr() - + if _ocr_processor.ocr is None: print("[ERROR] OCR引擎未初始化") return - + print(f"OCR引擎: {_ocr_processor.ocr_type}") print(f"OMP线程数: {os.environ.get('OMP_NUM_THREADS', '未设置')}") print() except Exception as e: print(f"[ERROR] OCR引擎检查失败: {e}") return - + # 执行多次测试 times = [] results = [] - + for i in range(iterations): try: import numpy as np - + # 准备图像 if img.mode != 'RGB': img_rgb = img.convert('RGB') else: img_rgb = img - + # 转换为numpy数组 img_np = np.array(img_rgb) - + # 执行OCR start_time = time.time() - + if _ocr_processor.ocr_type == "easyocr": result = _ocr_processor.ocr.readtext(img_np) else: result = _ocr_processor.ocr.ocr(img_np) - + elapsed = (time.time() - start_time) * 1000 # 转换为毫秒 - + # 提取文本 from Underlying_Operations import underlying_operations ops = underlying_operations() text = ops.extract_ocr_content(result) - + times.append(elapsed) results.append(text) - + print(f"第 {i+1} 次: {elapsed:.0f}ms, 识别结果: {text[:50] if text else '(空)'}") - + except Exception as e: print(f"第 {i+1} 次: 失败 - {e}") import traceback traceback.print_exc() - + print() - + # 统计结果 if times: print("性能统计") @@ -122,13 +122,13 @@ def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iteratio avg_time = sum(times) / len(times) min_time = min(times) max_time = max(times) - + print(f"平均耗时: {avg_time:.0f}ms ({avg_time/1000:.2f}秒)") print(f"最快耗时: {min_time:.0f}ms ({min_time/1000:.2f}秒)") print(f"最慢耗时: {max_time:.0f}ms ({max_time/1000:.2f}秒)") print(f"耗时范围: {max_time - min_time:.0f}ms") print() - + # 识别结果 print("识别结果") print("-" * 70) @@ -137,7 +137,7 @@ def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iteratio count = results.count(result) print(f"结果 {i}: {result[:100] if result else '(空)'} (出现 {count} 次)") print() - + # 性能对比 if region: original_pixels = original_size[0] * original_size[1] @@ -150,14 +150,14 @@ def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iteratio print(f"像素减少: {reduction:.1f}%") print(f"预计原始图片OCR耗时: {avg_time * (original_pixels / crop_pixels):.0f}ms") print() - + # 清理临时文件 if region and os.path.exists(test_image_path): try: os.remove(test_image_path) except: pass - + print("=" * 70) print("测试完成") print("=" * 70) @@ -166,18 +166,18 @@ def main(): """主函数""" # 默认图片路径 default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" - + # 从命令行参数获取图片路径 if len(sys.argv) > 1: image_path = sys.argv[1] else: image_path = default_image - + # 转换为绝对路径 if not os.path.isabs(image_path): project_root = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(project_root, image_path) - + # 从文件名提取区域信息(如果文件名包含坐标) region = None if "(480,1110)-(570,1230)" in image_path: @@ -185,7 +185,7 @@ def main(): region = (480, 1110, 570, 1230) print("[INFO] 检测到文件名中的坐标信息,将使用裁剪区域进行测试") print() - + # 获取测试次数 iterations = 5 if len(sys.argv) > 2: @@ -193,13 +193,13 @@ def main(): iterations = int(sys.argv[2]) except: pass - + # 先测试完整图片 print("=" * 70) print("测试1: 完整图片OCR") print("=" * 70) test_ocr_on_region(image_path, region=None, iterations=iterations) - + # 如果检测到区域信息,再测试裁剪区域 if region: print() @@ -210,5 +210,3 @@ def main(): if __name__ == "__main__": main() - - diff --git a/test_parallel_ocr_performance.py b/deleted_tests_backup/test_parallel_ocr_performance.py similarity index 97% rename from test_parallel_ocr_performance.py rename to deleted_tests_backup/test_parallel_ocr_performance.py index ee4dfd6..724962d 100644 --- a/test_parallel_ocr_performance.py +++ b/deleted_tests_backup/test_parallel_ocr_performance.py @@ -19,7 +19,7 @@ def test_serial_ocr(image_path: str, num_tasks: int = 3): print(f"任务数量: {num_tasks}") print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}") print() - + # 加载图片 try: img = Image.open(image_path) @@ -31,55 +31,55 @@ def test_serial_ocr(image_path: str, num_tasks: int = 3): except Exception as e: print(f"[ERROR] 无法加载图片: {e}") return None - + # 初始化OCR try: from operations.ocr_operations import _ocr_processor _ocr_processor._ensure_ocr() - + if _ocr_processor.ocr is None: print("[ERROR] OCR引擎未初始化") return None - + print(f"OCR引擎: {_ocr_processor.ocr_type}") print() except Exception as e: print(f"[ERROR] OCR引擎初始化失败: {e}") return None - + # 串行执行OCR任务 start_time = time.time() results = [] - + print("开始串行OCR测试...") for i in range(num_tasks): task_start = time.time() - + try: if _ocr_processor.ocr_type == "easyocr": result = _ocr_processor.ocr.readtext(img_np) else: result = _ocr_processor.ocr.ocr(img_np) - + # 提取文本 from Underlying_Operations import underlying_operations ops = underlying_operations() text = ops.extract_ocr_content(result) - + task_elapsed = (time.time() - task_start) * 1000 results.append(text) print(f" 任务 {i+1}/{num_tasks}: {task_elapsed:.0f}ms, 结果: {text[:30] if text else '(空)'}") except Exception as e: print(f" 任务 {i+1}/{num_tasks}: 失败 - {e}") results.append(None) - + total_elapsed = (time.time() - start_time) * 1000 - + print() print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") print(f"平均每个任务: {total_elapsed/num_tasks:.0f}ms") print() - + return total_elapsed def test_parallel_ocr(image_path: str, num_tasks: int = 3): @@ -89,7 +89,7 @@ def test_parallel_ocr(image_path: str, num_tasks: int = 3): print("=" * 70) print(f"任务数量: {num_tasks}") print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}") - + # 获取最优线程数 try: from operations.screenshot_service import get_optimal_workers @@ -99,7 +99,7 @@ def test_parallel_ocr(image_path: str, num_tasks: int = 3): optimal_workers = 6 print(f"线程池大小: {optimal_workers} (默认)") print() - + # 加载图片 try: img = Image.open(image_path) @@ -111,22 +111,22 @@ def test_parallel_ocr(image_path: str, num_tasks: int = 3): except Exception as e: print(f"[ERROR] 无法加载图片: {e}") return None - + # 初始化OCR try: from operations.ocr_operations import _ocr_processor _ocr_processor._ensure_ocr() - + if _ocr_processor.ocr is None: print("[ERROR] OCR引擎未初始化") return None - + print(f"OCR引擎: {_ocr_processor.ocr_type}") print() except Exception as e: print(f"[ERROR] OCR引擎初始化失败: {e}") return None - + # 定义OCR任务函数 def ocr_task(task_id): """单个OCR任务""" @@ -135,26 +135,26 @@ def test_parallel_ocr(image_path: str, num_tasks: int = 3): result = _ocr_processor.ocr.readtext(img_np) else: result = _ocr_processor.ocr.ocr(img_np) - + # 提取文本 from Underlying_Operations import underlying_operations ops = underlying_operations() text = ops.extract_ocr_content(result) - + return text except Exception as e: print(f" 任务 {task_id} 失败: {e}") return None - + # 并行执行OCR任务 start_time = time.time() results = [] - + print("开始并行OCR测试...") with ThreadPoolExecutor(max_workers=optimal_workers) as executor: # 提交所有任务 futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)} - + # 收集结果 task_times = {} for future in futures: @@ -169,9 +169,9 @@ def test_parallel_ocr(image_path: str, num_tasks: int = 3): except Exception as e: print(f" 任务 {task_id}/{num_tasks}: 失败 - {e}") results.append(None) - + total_elapsed = (time.time() - start_time) * 1000 - + print() print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") if task_times: @@ -179,7 +179,7 @@ def test_parallel_ocr(image_path: str, num_tasks: int = 3): print(f"平均每个任务: {avg_task_time:.0f}ms") print(f"并行效率: {avg_task_time * num_tasks / total_elapsed:.1f}x (理想情况下应该接近{num_tasks}x)") print() - + return total_elapsed def test_parallel_ocr_old_config(image_path: str, num_tasks: int = 3): @@ -188,14 +188,14 @@ def test_parallel_ocr_old_config(image_path: str, num_tasks: int = 3): print("测试3: 并行OCR(旧配置:OMP=1, 线程池=6)") print("=" * 70) print(f"任务数量: {num_tasks}") - + # 临时设置旧配置 old_omp = os.environ.get('OMP_NUM_THREADS', '4') os.environ['OMP_NUM_THREADS'] = '1' print(f"OMP_NUM_THREADS: 1 (临时设置)") print(f"线程池大小: 6 (固定)") print() - + # 加载图片 try: img = Image.open(image_path) @@ -208,7 +208,7 @@ def test_parallel_ocr_old_config(image_path: str, num_tasks: int = 3): print(f"[ERROR] 无法加载图片: {e}") os.environ['OMP_NUM_THREADS'] = old_omp return None - + # 重新初始化OCR(使用新的OMP设置) try: from operations.ocr_operations import _ocr_processor @@ -221,7 +221,7 @@ def test_parallel_ocr_old_config(image_path: str, num_tasks: int = 3): print(f"[ERROR] OCR引擎检查失败: {e}") os.environ['OMP_NUM_THREADS'] = old_omp return None - + # 定义OCR任务函数 def ocr_task(task_id): """单个OCR任务""" @@ -230,26 +230,26 @@ def test_parallel_ocr_old_config(image_path: str, num_tasks: int = 3): result = _ocr_processor.ocr.readtext(img_np) else: result = _ocr_processor.ocr.ocr(img_np) - + # 提取文本 from Underlying_Operations import underlying_operations ops = underlying_operations() text = ops.extract_ocr_content(result) - + return text except Exception as e: print(f" 任务 {task_id} 失败: {e}") return None - + # 并行执行OCR任务(使用旧的线程池大小) start_time = time.time() results = [] - + print("开始并行OCR测试(旧配置)...") with ThreadPoolExecutor(max_workers=6) as executor: # 提交所有任务 futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)} - + # 收集结果 task_times = {} for future in futures: @@ -264,42 +264,42 @@ def test_parallel_ocr_old_config(image_path: str, num_tasks: int = 3): except Exception as e: print(f" 任务 {task_id}/{num_tasks}: 失败 - {e}") results.append(None) - + total_elapsed = (time.time() - start_time) * 1000 - + # 恢复OMP设置 os.environ['OMP_NUM_THREADS'] = old_omp - + print() print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") if task_times: avg_task_time = sum(task_times.values()) / len(task_times) print(f"平均每个任务: {avg_task_time:.0f}ms") print() - + return total_elapsed def main(): """主函数""" # 默认图片路径 default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" - + # 从命令行参数获取图片路径 if len(sys.argv) > 1: image_path = sys.argv[1] else: image_path = default_image - + # 转换为绝对路径 if not os.path.isabs(image_path): project_root = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(project_root, image_path) - + # 检查文件是否存在 if not os.path.exists(image_path): print(f"[ERROR] 图片文件不存在: {image_path}") return - + # 获取任务数量(默认3个,减少测试时间) num_tasks = 3 if len(sys.argv) > 2: @@ -307,7 +307,7 @@ def main(): num_tasks = int(sys.argv[2]) except: pass - + print("=" * 70) print("并行OCR性能对比测试") print("=" * 70) @@ -315,7 +315,7 @@ def main(): print(f"测试图片: {os.path.basename(image_path)}") print(f"任务数量: {num_tasks}") print() - + # 获取当前配置信息 cpu_count = os.cpu_count() or 4 omp_threads = os.environ.get('OMP_NUM_THREADS', '未设置') @@ -330,43 +330,43 @@ def main(): pass print() print() - + # 测试1: 串行OCR serial_time = test_serial_ocr(image_path, num_tasks) - + print() print() - + # 测试2: 并行OCR(优化后) parallel_time = test_parallel_ocr(image_path, num_tasks) - + print() print() - + # 测试3: 并行OCR(旧配置) parallel_old_time = test_parallel_ocr_old_config(image_path, num_tasks) - + # 性能对比总结 print() print("=" * 70) print("性能对比总结") print("=" * 70) print() - + if serial_time and parallel_time: speedup = serial_time / parallel_time print(f"串行OCR: {serial_time:.0f}ms ({serial_time/1000:.2f}秒)") print(f"并行OCR: {parallel_time:.0f}ms ({parallel_time/1000:.2f}秒)") print(f"性能提升: {speedup:.2f}x ({(1 - parallel_time/serial_time)*100:.1f}% 时间减少)") print() - + if parallel_old_time and parallel_time: speedup_vs_old = parallel_old_time / parallel_time print(f"旧配置并行: {parallel_old_time:.0f}ms ({parallel_old_time/1000:.2f}秒)") print(f"新配置并行: {parallel_time:.0f}ms ({parallel_time/1000:.2f}秒)") print(f"配置优化提升: {speedup_vs_old:.2f}x ({(1 - parallel_time/parallel_old_time)*100:.1f}% 时间减少)") print() - + if serial_time and parallel_time and parallel_old_time: total_speedup = serial_time / parallel_time print(f"总体优化效果:") @@ -374,11 +374,10 @@ def main(): print(f" 旧配置 → 新配置: {parallel_old_time/parallel_time:.2f}x") print(f" 串行 → 新配置: {total_speedup:.2f}x") print() - + print("=" * 70) print("测试完成") print("=" * 70) if __name__ == "__main__": main() - diff --git a/test_parallel_ocr_quick.py b/deleted_tests_backup/test_parallel_ocr_quick.py similarity index 97% rename from test_parallel_ocr_quick.py rename to deleted_tests_backup/test_parallel_ocr_quick.py index 346287c..28f6e8d 100644 --- a/test_parallel_ocr_quick.py +++ b/deleted_tests_backup/test_parallel_ocr_quick.py @@ -17,12 +17,12 @@ def test_parallel_ocr_quick(image_path: str, num_tasks: int = 3): print("并行OCR性能测试(快速版)") print("=" * 70) print() - + # 检查文件 if not os.path.exists(image_path): print(f"[ERROR] 图片文件不存在: {image_path}") return None - + # 加载图片 try: img = Image.open(image_path) @@ -36,19 +36,19 @@ def test_parallel_ocr_quick(image_path: str, num_tasks: int = 3): except Exception as e: print(f"[ERROR] 无法加载图片: {e}") return None - + # 初始化OCR try: from operations.ocr_operations import _ocr_processor _ocr_processor._ensure_ocr() - + if _ocr_processor.ocr is None: print("[ERROR] OCR引擎未初始化") return None - + print(f"OCR引擎: {_ocr_processor.ocr_type}") print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}") - + from operations.screenshot_service import get_optimal_workers optimal_workers = get_optimal_workers() print(f"线程池大小: {optimal_workers}") @@ -56,7 +56,7 @@ def test_parallel_ocr_quick(image_path: str, num_tasks: int = 3): except Exception as e: print(f"[ERROR] OCR引擎初始化失败: {e}") return None - + # 定义OCR任务 def ocr_task(task_id): try: @@ -64,22 +64,22 @@ def test_parallel_ocr_quick(image_path: str, num_tasks: int = 3): result = _ocr_processor.ocr.readtext(img_np) else: result = _ocr_processor.ocr.ocr(img_np) - + from Underlying_Operations import underlying_operations ops = underlying_operations() text = ops.extract_ocr_content(result) return text except Exception as e: return f"错误: {e}" - + # 执行并行OCR print("开始并行OCR测试...") start_time = time.time() - + with ThreadPoolExecutor(max_workers=optimal_workers) as executor: futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)} results = [] - + for future in futures: task_id = futures[future] try: @@ -89,61 +89,53 @@ def test_parallel_ocr_quick(image_path: str, num_tasks: int = 3): except Exception as e: print(f" 任务 {task_id}: 失败 - {e}") results.append(None) - + total_elapsed = (time.time() - start_time) * 1000 - + print() print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") print(f"平均每个任务: {total_elapsed/num_tasks:.0f}ms") print() - + # 估算串行时间(基于单次OCR耗时) print("性能估算:") print("-" * 70) single_task_time = total_elapsed / num_tasks estimated_serial_time = single_task_time * num_tasks speedup = estimated_serial_time / total_elapsed if total_elapsed > 0 else 0 - + print(f"估算串行时间: {estimated_serial_time:.0f}ms ({estimated_serial_time/1000:.2f}秒)") print(f"实际并行时间: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") print(f"性能提升: {speedup:.2f}x (节省 {(1 - total_elapsed/estimated_serial_time)*100:.1f}% 时间)") print() - + return total_elapsed def main(): """主函数""" default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" - + if len(sys.argv) > 1: image_path = sys.argv[1] else: image_path = default_image - + if not os.path.isabs(image_path): project_root = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(project_root, image_path) - + num_tasks = 3 if len(sys.argv) > 2: try: num_tasks = int(sys.argv[2]) except: pass - + test_parallel_ocr_quick(image_path, num_tasks) - + print("=" * 70) print("测试完成") print("=" * 70) if __name__ == "__main__": main() - - - - - - - - diff --git a/test_parallel_ocr_simple.py b/deleted_tests_backup/test_parallel_ocr_simple.py similarity index 97% rename from test_parallel_ocr_simple.py rename to deleted_tests_backup/test_parallel_ocr_simple.py index da983e6..d4d0aeb 100644 --- a/test_parallel_ocr_simple.py +++ b/deleted_tests_backup/test_parallel_ocr_simple.py @@ -19,11 +19,11 @@ def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_ print(f"{'='*70}") print(f"OMP_NUM_THREADS={omp_threads}, max_workers={max_workers}, 任务数={num_tasks}") print() - + # 设置OMP old_omp = os.environ.get('OMP_NUM_THREADS', '4') os.environ['OMP_NUM_THREADS'] = str(omp_threads) - + # 加载图片 try: img = Image.open(image_path) @@ -37,25 +37,25 @@ def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_ print(f"[ERROR] 无法加载图片: {e}") os.environ['OMP_NUM_THREADS'] = old_omp return None - + # 初始化OCR try: from operations.ocr_operations import OCRProcessor ocr_processor = OCRProcessor() ocr_processor._ensure_ocr() - + if ocr_processor.ocr is None: print("[ERROR] OCR引擎未初始化") os.environ['OMP_NUM_THREADS'] = old_omp return None - + print(f"OCR引擎: {ocr_processor.ocr_type}") print() except Exception as e: print(f"[ERROR] OCR引擎初始化失败: {e}") os.environ['OMP_NUM_THREADS'] = old_omp return None - + # OCR任务函数 def ocr_task(task_id): try: @@ -64,7 +64,7 @@ def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_ result = ocr_processor.ocr.readtext(img_np) else: result = ocr_processor.ocr.ocr(img_np) - + from Underlying_Operations import underlying_operations ops = underlying_operations() text = ops.extract_ocr_content(result) @@ -72,15 +72,15 @@ def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_ return {'task_id': task_id, 'text': text, 'time': elapsed, 'success': True} except Exception as e: return {'task_id': task_id, 'text': '', 'time': 0, 'success': False, 'error': str(e)} - + # 执行并行OCR print("开始并行OCR测试...") start_time = time.time() results = [] - + with ThreadPoolExecutor(max_workers=max_workers) as executor: futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)} - + for future in futures: try: result = future.result() @@ -89,17 +89,17 @@ def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_ print(f" {status} 任务{result['task_id']}: {result['time']:.0f}ms, 结果: {result['text'][:20] if result['text'] else '(空)'}") except Exception as e: print(f" ✗ 任务失败: {e}") - + total_elapsed = (time.time() - start_time) * 1000 - + # 恢复OMP设置 os.environ['OMP_NUM_THREADS'] = old_omp - + # 统计 successful = [r for r in results if r['success']] total_task_time = sum(r['time'] for r in successful) avg_task_time = total_task_time / len(successful) if successful else 0 - + print() print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") print(f"任务总耗时: {total_task_time:.0f}ms") @@ -108,7 +108,7 @@ def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_ efficiency = total_task_time / total_elapsed print(f"并行效率: {efficiency:.2f}x (理想值: {num_tasks:.1f}x)") print() - + return { 'total_time': total_elapsed, 'avg_task_time': avg_task_time, @@ -118,26 +118,26 @@ def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_ def main(): """主函数""" default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" - + if len(sys.argv) > 1: image_path = sys.argv[1] else: image_path = default_image - + if not os.path.isabs(image_path): project_root = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(project_root, image_path) - + if not os.path.exists(image_path): print(f"[ERROR] 图片文件不存在: {image_path}") return - + print("=" * 70) print("并行OCR性能对比测试(简化版)") print("=" * 70) print() print(f"测试图片: {os.path.basename(image_path)}") - + # 获取系统信息 cpu_count = os.cpu_count() or 4 print(f"CPU核心数: {cpu_count}") @@ -147,22 +147,22 @@ def main(): print(f"推荐线程池大小: {optimal_workers}") except: optimal_workers = 6 - + num_tasks = 6 print(f"测试任务数: {num_tasks}") print() - + # 测试1: 优化前 result_old = test_ocr_with_config( - image_path, + image_path, "优化前配置 (OMP=1, workers=6)", omp_threads=1, max_workers=6, num_tasks=num_tasks ) - + time.sleep(1) # 等待系统稳定 - + # 测试2: 优化后 result_new = test_ocr_with_config( image_path, @@ -171,32 +171,32 @@ def main(): max_workers=optimal_workers, num_tasks=num_tasks ) - + # 对比结果 print() print("=" * 70) print("性能对比总结") print("=" * 70) print() - + if result_old and result_new: old_time = result_old['total_time'] new_time = result_new['total_time'] speedup = old_time / new_time if new_time > 0 else 0 - + print(f"优化前总耗时: {old_time:.0f}ms ({old_time/1000:.2f}秒)") print(f"优化后总耗时: {new_time:.0f}ms ({new_time/1000:.2f}秒)") print(f"性能提升: {speedup:.2f}x") print(f"时间减少: {(1 - new_time/old_time)*100:.1f}%") print() - + old_avg = result_old['avg_task_time'] new_avg = result_new['avg_task_time'] print(f"优化前平均任务耗时: {old_avg:.0f}ms") print(f"优化后平均任务耗时: {new_avg:.0f}ms") if new_avg > 0: print(f"单任务性能提升: {old_avg/new_avg:.2f}x") - + print() print("=" * 70) print("测试完成") @@ -204,10 +204,3 @@ def main(): if __name__ == "__main__": main() - - - - - - - diff --git a/test_real_parallel_ocr.py b/deleted_tests_backup/test_real_parallel_ocr.py similarity index 96% rename from test_real_parallel_ocr.py rename to deleted_tests_backup/test_real_parallel_ocr.py index 2721b7e..381b34e 100644 --- a/test_real_parallel_ocr.py +++ b/deleted_tests_backup/test_real_parallel_ocr.py @@ -19,12 +19,12 @@ def create_test_regions(full_image_path): img = Image.open(full_image_path) if img.mode != 'RGB': img = img.convert('RGB') - + width, height = img.size - + # 判断是否是完整截图(1080x2400)还是裁剪区域 is_full_screenshot = width >= 1000 and height >= 2000 - + if is_full_screenshot: # 完整截图:创建多个测试区域 # 模拟真实的OCR区域(基于福袋详情页的常见区域) @@ -42,12 +42,12 @@ def create_test_regions(full_image_path): coords_from_filename = None if "(480,1110)-(570,1230)" in full_image_path: coords_from_filename = (480, 1110, 570, 1230) - + # 创建多个相似大小的测试区域 # 如果图片较小,创建多个相同大小的区域用于测试 # 这些区域会在完整截图的合理位置 regions = {} - + # 使用当前图片作为第一个区域 if coords_from_filename: x1, y1, x2, y2 = coords_from_filename @@ -67,11 +67,11 @@ def create_test_regions(full_image_path): regions["区域4"] = (0, 0, width, height) # 相同区域,用于测试并行 regions["区域5"] = (0, 0, width, height) # 相同区域,用于测试并行 regions["区域6"] = (0, 0, width, height) # 相同区域,用于测试并行 - + # 裁剪并保存区域图片 region_images = {} temp_dir = tempfile.gettempdir() - + for name, (x1, y1, x2, y2) in regions.items(): try: # 确保坐标在图片范围内 @@ -79,7 +79,7 @@ def create_test_regions(full_image_path): y1 = max(0, min(y1, img.height)) x2 = max(x1, min(x2, img.width)) y2 = max(y1, min(y2, img.height)) - + if x2 > x1 and y2 > y1: crop_img = img.crop((x1, y1, x2, y2)) temp_path = os.path.join(temp_dir, f"ocr_test_{name}.png") @@ -91,7 +91,7 @@ def create_test_regions(full_image_path): } except (ValueError, OSError, IOError) as e: print(f"[WARNING] 无法裁剪区域 {name}: {e}") - + return region_images, img.size except (OSError, IOError, ValueError) as e: print(f"[ERROR] 无法处理图片: {e}") @@ -104,21 +104,21 @@ def ocr_single_region(image_path, region_name, ocr_processor): if img.mode != 'RGB': img = img.convert('RGB') img_np = np.array(img) - + start_time = time.time() - + if ocr_processor.ocr_type == "easyocr": result = ocr_processor.ocr.readtext(img_np) else: result = ocr_processor.ocr.ocr(img_np) - + elapsed = (time.time() - start_time) * 1000 - + # 提取文本 from Underlying_Operations import underlying_operations ops = underlying_operations() text = ops.extract_ocr_content(result) - + return { 'region': region_name, 'text': text, @@ -145,11 +145,11 @@ def test_parallel_ocr_real(region_images, config_name, omp_threads, max_workers) print(f"配置: OMP_NUM_THREADS={omp_threads}, max_workers={max_workers}") print(f"区域数量: {len(region_images)}") print() - + # 设置OMP线程数 old_omp = os.environ.get('OMP_NUM_THREADS', '4') os.environ['OMP_NUM_THREADS'] = str(omp_threads) - + # 初始化OCR(使用新的OMP设置) try: from operations.ocr_operations import OCRProcessor @@ -158,40 +158,40 @@ def test_parallel_ocr_real(region_images, config_name, omp_threads, max_workers) # 使用 getattr 来避免 pylance 警告 ensure_ocr = getattr(ocr_processor, '_ensure_ocr') ensure_ocr() - + if ocr_processor.ocr is None: print("[ERROR] OCR引擎未初始化") os.environ['OMP_NUM_THREADS'] = old_omp return None - + print(f"OCR引擎: {ocr_processor.ocr_type}") print() except (ImportError, AttributeError, RuntimeError) as e: print(f"[ERROR] OCR引擎初始化失败: {e}") os.environ['OMP_NUM_THREADS'] = old_omp return None - + # 显示区域信息 print("OCR区域信息:") for name, info in region_images.items(): print(f" {name}: {info['size'][0]}x{info['size'][1]} 像素, 坐标: {info['coords']}") print() - + # 并行执行OCR print("开始并行OCR识别...") start_time = time.time() results = [] - + def ocr_task(name, path): return ocr_single_region(path, name, ocr_processor) - + with ThreadPoolExecutor(max_workers=max_workers) as executor: # 提交所有任务 futures = { - executor.submit(ocr_task, name, info['path']): name + executor.submit(ocr_task, name, info['path']): name for name, info in region_images.items() } - + # 收集结果 for future in futures: region_name = futures[future] @@ -218,17 +218,17 @@ def test_parallel_ocr_real(region_images, config_name, omp_threads, max_workers) 'success': False, 'error': str(e) }) - + total_elapsed = (time.time() - start_time) * 1000 - + # 恢复OMP设置 os.environ['OMP_NUM_THREADS'] = old_omp - + # 统计结果 successful_results = [r for r in results if r['success']] total_task_time = sum(r['time'] for r in successful_results) avg_task_time = total_task_time / len(successful_results) if successful_results else 0 - + print() print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") print(f"任务总耗时: {total_task_time:.0f}ms") @@ -237,7 +237,7 @@ def test_parallel_ocr_real(region_images, config_name, omp_threads, max_workers) efficiency = total_task_time / total_elapsed print(f"并行效率: {efficiency:.2f}x (理想值: {len(region_images):.1f}x)") print() - + return { 'total_time': total_elapsed, 'task_times': [r['time'] for r in successful_results], @@ -249,42 +249,42 @@ def main(): """主函数""" # 默认图片路径(完整截图) default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" - + if len(sys.argv) > 1: image_path = sys.argv[1] else: image_path = default_image - + if not os.path.isabs(image_path): project_root = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(project_root, image_path) - + if not os.path.exists(image_path): print(f"[ERROR] 图片文件不存在: {image_path}") return - + print("=" * 70) print("真实场景并行OCR性能对比测试") print("=" * 70) print() print(f"测试图片: {os.path.basename(image_path)}") print() - + # 创建测试区域 print("准备测试区域...") region_images, full_size = create_test_regions(image_path) - + if not region_images: print("[ERROR] 无法创建测试区域") return - + if full_size is not None: print(f"完整截图尺寸: {full_size[0]}x{full_size[1]}") else: print("完整截图尺寸: 未知") print(f"成功创建 {len(region_images)} 个测试区域") print() - + # 获取系统信息 cpu_count = os.cpu_count() or 4 print("系统信息:") @@ -296,67 +296,67 @@ def main(): except (ImportError, AttributeError): optimal_workers = 6 print() - + # 测试1: 优化前配置(OMP=1, workers=6) result_old = test_parallel_ocr_real( - region_images, - "优化前配置", - omp_threads=1, + region_images, + "优化前配置", + omp_threads=1, max_workers=6 ) - + # 等待一下,让系统稳定 time.sleep(1) - + # 测试2: 优化后配置(OMP=4, workers=10) result_new = test_parallel_ocr_real( - region_images, - "优化后配置", - omp_threads=4, + region_images, + "优化后配置", + omp_threads=4, max_workers=optimal_workers ) - + # 性能对比总结 print() print("=" * 70) print("性能对比总结") print("=" * 70) print() - + if result_old and result_new: old_time = result_old['total_time'] new_time = result_new['total_time'] speedup = old_time / new_time if new_time > 0 else 0 - + print(f"优化前总耗时: {old_time:.0f}ms ({old_time/1000:.2f}秒)") print(f"优化后总耗时: {new_time:.0f}ms ({new_time/1000:.2f}秒)") print(f"性能提升: {speedup:.2f}x") print(f"时间减少: {(1 - new_time/old_time)*100:.1f}%") print() - + # 详细对比 if result_old['task_times'] and result_new['task_times']: old_avg = sum(result_old['task_times']) / len(result_old['task_times']) new_avg = sum(result_new['task_times']) / len(result_new['task_times']) - + print("任务级性能对比:") print(f" 优化前平均任务耗时: {old_avg:.0f}ms") print(f" 优化后平均任务耗时: {new_avg:.0f}ms") print(f" 单任务性能提升: {old_avg/new_avg:.2f}x") print() - + # 识别结果对比 print("识别结果对比:") for old_result in result_old['results']: region_name = old_result['region'] new_result = next((r for r in result_new['results'] if r['region'] == region_name), None) - + if old_result['success'] and new_result and new_result['success']: old_text = old_result['text'][:20] if old_result['text'] else '(空)' new_text = new_result['text'][:20] if new_result['text'] else '(空)' match = "✓" if old_text == new_text else "✗" print(f" {match} {region_name}: 结果一致") - + # 清理临时文件 print() print("清理临时文件...") @@ -366,7 +366,7 @@ def main(): os.remove(info['path']) except (OSError, PermissionError): pass - + print() print("=" * 70) print("测试完成") @@ -374,4 +374,3 @@ def main(): if __name__ == "__main__": main() - diff --git a/test_screenshot_error_handling.py b/deleted_tests_backup/test_screenshot_error_handling.py similarity index 99% rename from test_screenshot_error_handling.py rename to deleted_tests_backup/test_screenshot_error_handling.py index 42cb80b..4dec6fe 100644 --- a/test_screenshot_error_handling.py +++ b/deleted_tests_backup/test_screenshot_error_handling.py @@ -107,7 +107,3 @@ if __name__ == "__main__": print("2. 改进错误消息,提供更详细的诊断信息") print("3. 在douyin_fudai.py中添加截图重试机制") print("4. 当截图失败时会重试3次,而不是直接放弃") - - - - diff --git a/test_screenshot_file_wait.py b/deleted_tests_backup/test_screenshot_file_wait.py similarity index 100% rename from test_screenshot_file_wait.py rename to deleted_tests_backup/test_screenshot_file_wait.py diff --git a/test_screenshot_performance.py b/deleted_tests_backup/test_screenshot_performance.py similarity index 97% rename from test_screenshot_performance.py rename to deleted_tests_backup/test_screenshot_performance.py index e6e35b7..7dd849b 100644 --- a/test_screenshot_performance.py +++ b/deleted_tests_backup/test_screenshot_performance.py @@ -27,7 +27,7 @@ def test_screenshot_with_timing(): except ImportError: print("[错误] 无法导入 Underlying_Operations") return - + # 获取设备ID import subprocess try: @@ -35,7 +35,7 @@ def test_screenshot_with_timing(): if result.returncode != 0: print("[错误] adb devices 失败") return - + lines = result.stdout.strip().split("\n")[1:] devices = [] for line in lines: @@ -43,36 +43,36 @@ def test_screenshot_with_timing(): device_id = line.split("\t")[0].strip() if device_id: devices.append(device_id) - + if not devices: print("[错误] 未找到连接的设备") return - + device_id = devices[0] print(f"[信息] 使用设备: {device_id}") except Exception as e: print(f"[错误] 获取设备ID失败: {e}") return - + # 创建操作对象 ops = underlying_operations() - + print("\n" + "="*60) print("测试 1: 正常截图(启用所有验证和镜像)") print("="*60) - + # 测试1: 正常截图 start = time.time() result1 = ops.get_screenshot(device_id, use_service=False) # 禁用服务,使用直接截图以便看到详细日志 elapsed1 = (time.time() - start) * 1000.0 print(f"\n[结果] 测试1完成: 成功={result1}, 总耗时={elapsed1:.1f}ms") - + time.sleep(1) - + print("\n" + "="*60) print("测试 2: 禁用 PNG 验证 (SKIP_SCREENSHOT_VERIFY=1)") print("="*60) - + # 测试2: 禁用验证 os.environ["SKIP_SCREENSHOT_VERIFY"] = "1" start = time.time() @@ -82,13 +82,13 @@ def test_screenshot_with_timing(): if elapsed1 > 0: improvement = ((elapsed1 - elapsed2) / elapsed1) * 100 print(f"[对比] 相比测试1: {improvement:+.1f}% ({elapsed1 - elapsed2:+.1f}ms)") - + time.sleep(1) - + print("\n" + "="*60) print("测试 3: 禁用 PNG 验证 + 禁用镜像 (SKIP_SCREENSHOT_VERIFY=1, DISABLE_SCREENSHOT_MIRROR=1)") print("="*60) - + # 测试3: 禁用验证和镜像 os.environ["DISABLE_SCREENSHOT_MIRROR"] = "1" start = time.time() @@ -98,24 +98,24 @@ def test_screenshot_with_timing(): if elapsed1 > 0: improvement = ((elapsed1 - elapsed3) / elapsed1) * 100 print(f"[对比] 相比测试1: {improvement:+.1f}% ({elapsed1 - elapsed3:+.1f}ms)") - + # 恢复环境变量 if "SKIP_SCREENSHOT_VERIFY" in os.environ: del os.environ["SKIP_SCREENSHOT_VERIFY"] if "DISABLE_SCREENSHOT_MIRROR" in os.environ: del os.environ["DISABLE_SCREENSHOT_MIRROR"] - + print("\n" + "="*60) print("测试总结") print("="*60) print(f"测试1 (正常): {elapsed1:.1f}ms") print(f"测试2 (禁用验证): {elapsed2:.1f}ms") print(f"测试3 (禁用全部): {elapsed3:.1f}ms") - + if elapsed1 > 0 and elapsed3 > 0: total_improvement = ((elapsed1 - elapsed3) / elapsed1) * 100 print(f"\n最大优化效果: {total_improvement:+.1f}% ({elapsed1 - elapsed3:+.1f}ms)") - + if total_improvement > 10: print("\n[建议] 如果优化效果明显,可以考虑:") print(" 1. 在生产环境谨慎使用 SKIP_SCREENSHOT_VERIFY(可能影响数据完整性)") @@ -125,4 +125,3 @@ def test_screenshot_with_timing(): if __name__ == "__main__": test_screenshot_with_timing() - diff --git a/test_screenshot_reuse_optimization.py b/deleted_tests_backup/test_screenshot_reuse_optimization.py similarity index 100% rename from test_screenshot_reuse_optimization.py rename to deleted_tests_backup/test_screenshot_reuse_optimization.py diff --git a/test_screenshot_service_fix.py b/deleted_tests_backup/test_screenshot_service_fix.py similarity index 100% rename from test_screenshot_service_fix.py rename to deleted_tests_backup/test_screenshot_service_fix.py diff --git a/test_screenshot_service_ocr_optimization.py b/deleted_tests_backup/test_screenshot_service_ocr_optimization.py similarity index 100% rename from test_screenshot_service_ocr_optimization.py rename to deleted_tests_backup/test_screenshot_service_ocr_optimization.py diff --git a/test_screenshot_service_ocr_simple.py b/deleted_tests_backup/test_screenshot_service_ocr_simple.py similarity index 100% rename from test_screenshot_service_ocr_simple.py rename to deleted_tests_backup/test_screenshot_service_ocr_simple.py diff --git a/test_screenshot_service_ocr_stop.py b/deleted_tests_backup/test_screenshot_service_ocr_stop.py similarity index 100% rename from test_screenshot_service_ocr_stop.py rename to deleted_tests_backup/test_screenshot_service_ocr_stop.py diff --git a/test_time_import_fix.py b/deleted_tests_backup/test_time_import_fix.py similarity index 100% rename from test_time_import_fix.py rename to deleted_tests_backup/test_time_import_fix.py diff --git a/diagnose_screenshot_service.py b/diagnose_screenshot_service.py deleted file mode 100644 index 742fb29..0000000 --- a/diagnose_screenshot_service.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python3 -"""截图服务诊断工具""" - -import time -from operations.screenshot_service import ScreenshotService - -def diagnose_screenshot_service(): - """诊断截图服务状态""" - print("=== 截图服务诊断工具 ===\n") - - service = ScreenshotService.get_instance() - cache_info = service.get_cache_info() - - print(f"1. 服务运行状态: {'[OK] 运行中' if cache_info['running'] else '[ERROR] 未运行'}") - print(f"2. 设备ID: {cache_info.get('device_id', 'None')}") - print(f"3. 截图间隔: {cache_info.get('interval', 'N/A')}秒") - print(f"4. 缓存有效期: {cache_info.get('cache_valid_duration', 'N/A')}秒") - - last_time = cache_info.get('last_screenshot_time', 0) - if last_time > 0: - time_since = time.time() - last_time - print(".1f") - print(f"6. 缓存状态: {'[OK] 有效' if time_since < cache_info.get('cache_valid_duration', 2.0) else '[EXPIRED] 过期'}") - else: - print("5. 最后截图时间: 从未截图") - print("6. 缓存状态: 无缓存") - - print(f"7. 最后截图成功: {cache_info.get('last_success', False)}") - - # 诊断建议 - print("\n=== 诊断结果 ===") - - issues = [] - - if not cache_info['running']: - issues.append("[ERROR] 后台截图服务未运行 - 每次截图都会很慢") - - if not cache_info.get('device_id'): - issues.append("[ERROR] 设备ID为空 - 无法启动截图服务") - - if last_time == 0: - issues.append("[ERROR] 从未成功截图 - 检查ADB连接和设备状态") - - if issues: - print("发现问题:") - for issue in issues: - print(f" {issue}") - else: - print("[OK] 截图服务运行正常") - - # 显示性能预期 - print("\n=== 性能预期 ===") - print("- 缓存命中时: < 10ms") - print("- 缓存未命中时: < 1秒") - print("- 后台截图间隔: 1.5秒") - - print("\n=== 解决建议 ===") - if not cache_info['running']: - print("1. 重启程序,确保设备ID正确设置") - print("2. 检查ADB连接: adb devices") - print("3. 查看程序日志中的截图服务相关信息") - - if cache_info['running'] and last_time == 0: - print("1. 检查ADB连接是否正常") - print("2. 尝试手动截图测试连接") - print("3. 检查设备是否进入睡眠模式") - - print("\n=== 测试命令 ===") - print("运行测试: python test_full_screenshot_flow.py") - -if __name__ == "__main__": - diagnose_screenshot_service() diff --git a/douyin/__init__.py b/douyin/__init__.py index 1ddb214..076ecae 100644 --- a/douyin/__init__.py +++ b/douyin/__init__.py @@ -1,7 +1,3 @@ """ 抖音挂机项目核心模块 """ - - - - diff --git a/douyin/core/__init__.py b/douyin/core/__init__.py index 605cbee..702c547 100644 --- a/douyin/core/__init__.py +++ b/douyin/core/__init__.py @@ -1,6 +1,3 @@ """ 核心调度和流程控制模块 """ - - - diff --git a/douyin/core/douyin_flow_control.py b/douyin/core/douyin_flow_control.py index 726ddd5..e2e781e 100644 --- a/douyin/core/douyin_flow_control.py +++ b/douyin/core/douyin_flow_control.py @@ -1,5 +1,3 @@ -from __future__ import annotations - """ Flow control main helpers (本地模块化实现,基础版) ================================================ @@ -11,43 +9,44 @@ Flow control main helpers (本地模块化实现,基础版) - filter_fudai_detail:根据 config.json 对福袋进行基础筛选 """ -from typing import Any, List, Tuple +from __future__ import annotations + +from typing import Any, Callable, List, Optional, Tuple import time import os from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config -from douyin.reservation import douyin_reservation_logic import path_config -from PIL import Image def handle_stage_after_diagnosis( analyser: Any, stage: str, seen: str, - loop_count: int, -) -> bool: - """记录阶段诊断结果,当前不改变主流程走向。""" - try: - analyser._log_kv( - "流程", - "handle_stage_after_diagnosis", - stage=stage, - seen=seen, - loop_count=loop_count, - ) - except Exception: - pass - return False + func_start_time: float | None = None, +): + if func_start_time is None: + func_start_time = time.time() + + return find_and_open_fudai_detail( + analyser=analyser, + stage=stage, + seen=seen, + func_start_time=func_start_time, + ) def find_and_open_fudai_detail( analyser: Any, - room_pos_ref: List[int], -) -> bool: - """在当前直播间查找福袋图标并尝试点击打开详情(基础版,不做预约)。""" - func_start_time = time.time() + stage: Any = "", + seen: Any = "", + func_start_time: float | None = None, +): + """主实现:检测福袋图标并点击打开详情页。""" + if func_start_time is None: + func_start_time = time.time() + # 如果正在等待开奖,不应该再次打开福袋详情 try: if getattr(analyser, "_waiting_for_lottery_result", False): @@ -59,7 +58,11 @@ def find_and_open_fudai_detail( except Exception: pass elapsed = time.time() - func_start_time - analyser._log_kv("流程", "find_and_open_fudai_detail完成(等待开奖中)", elapsed_seconds=round(elapsed, 2)) + analyser._log_kv( + "流程", + "find_and_open_fudai_detail完成(等待开奖中)", + elapsed_seconds=round(elapsed, 2), + ) return False except Exception: pass @@ -79,13 +82,10 @@ def find_and_open_fudai_detail( x = False while (time.time() - start_time) < max_wait_seconds: - # 优先尝试复用已有截图,如果失败再强制刷新 x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True) if not x: - # 如果复用截图失败,强制刷新后重试 x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False) if x: - # 找到福袋图标,跳出循环 try: analyser._log_kv( "流程", @@ -97,13 +97,11 @@ def find_and_open_fudai_detail( pass break - # 未找到,等待一段时间后重试 elapsed = time.time() - start_time remaining = max_wait_seconds - elapsed if remaining <= 0: break - # 计算本次等待时间(不超过剩余时间和重试延迟) wait_time = min(retry_delay_seconds, remaining) try: analyser._log_kv( @@ -134,7 +132,11 @@ def find_and_open_fudai_detail( except Exception: pass elapsed = time.time() - func_start_time - analyser._log_kv("流程", "find_and_open_fudai_detail完成(未找到福袋)", elapsed_seconds=round(elapsed, 2)) + analyser._log_kv( + "流程", + "find_and_open_fudai_detail完成(未找到福袋)", + elapsed_seconds=round(elapsed, 2), + ) return False # 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度) @@ -162,17 +164,17 @@ def find_and_open_fudai_detail( try: from PIL import Image import importlib - douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") + + douyin_screenshot_manager = importlib.import_module( + "douyin.handlers.douyin_screenshot_manager" + ) screenshot_path = path_config.get_screenshot_path() if os.path.exists(screenshot_path): img = Image.open(screenshot_path) img.load() pic_rgb_full = img.convert("RGB") - # 使用与检测处相同的命名(pixel_detect + fudai_icon + detected) - # 为了在调试图像中标注检测到的位置,传入 coords 和 detected_x_scaled try: - # 在点击位置附近画一个小框以便定位(30px 半径) box_r = 30 coord_box = ( max(0, click_x - box_r), @@ -206,158 +208,29 @@ def find_and_open_fudai_detail( except Exception: pass except Exception: - # 不要让调试保存影响主流程 pass # 优先走底层 operation.click,失败再尝试 analyser.click try: analyser.operation.click(device_id, click_x, click_y) - - # 智能等待:先等待最小时间,然后循环检测详情页是否已打开 - # 这样可以减少不必要的等待时间 - min_wait_seconds = 0.5 # 最小等待时间(确保点击生效) - max_wait_seconds = float( - getattr(analyser, "fudai_click_wait_seconds", 2.0) or 2.0 - ) - check_interval = 0.2 # 每次检测间隔(秒) - - try: - analyser._log_kv( - "流程", - "find_and_open_fudai_detail:开始智能等待", - min_wait_seconds=min_wait_seconds, - max_wait_seconds=max_wait_seconds, - check_interval=check_interval, - ) - except Exception: - pass - - # 先等待最小时间 - analyser.operation.delay(min_wait_seconds) - - try: - analyser._log_kv( - "流程", - "find_and_open_fudai_detail:最小等待时间已过,开始循环检测", - elapsed_seconds=min_wait_seconds, - ) - except Exception: - pass - - # 智能等待:循环检测详情页是否已打开 - from douyin.stage import douyin_stage - wait_start = time.time() - detail_opened = False - check_count = 0 - - while (time.time() - wait_start) < (max_wait_seconds - min_wait_seconds): - check_count += 1 - elapsed_in_loop = time.time() - wait_start - try: - analyser.operation.get_screenshot(device_id, use_service=False) - pic_path = path_config.get_screenshot_path() - if os.path.exists(pic_path): - # 快速检测是否已在详情页(只检测关键特征,不执行完整阶段诊断) - result = douyin_stage.diagnose_stage_from_current_screen(analyser) - if result is not None: - stage, reason = result - try: - analyser._log_kv( - "流程", - "find_and_open_fudai_detail:智能等待检测中", - check_count=check_count, - elapsed_in_loop=round(elapsed_in_loop, 2), - total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2), - current_stage=stage, - reason=reason[:50] if reason else "", - ) - except Exception: - pass - if stage == "FUDai_DETAIL": - detail_opened = True - elapsed_wait = time.time() - wait_start - try: - analyser._log_kv( - "流程", - "find_and_open_fudai_detail:智能等待检测到详情页已打开", - check_count=check_count, - wait_seconds=round(elapsed_wait + min_wait_seconds, 2), - elapsed_in_loop=round(elapsed_wait, 2), - ) - except Exception: - pass - break - else: - try: - analyser._log_kv( - "流程", - "find_and_open_fudai_detail:智能等待检测中(阶段诊断返回None)", - check_count=check_count, - elapsed_in_loop=round(elapsed_in_loop, 2), - total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2), - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "流程", - "find_and_open_fudai_detail:智能等待检测中(截图文件不存在)", - check_count=check_count, - elapsed_in_loop=round(elapsed_in_loop, 2), - total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2), - pic_path=pic_path, - ) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "流程", - "find_and_open_fudai_detail:智能等待检测中(检测异常)", - check_count=check_count, - elapsed_in_loop=round(elapsed_in_loop, 2), - total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2), - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - - # 等待一小段时间后再次检测 - try: - analyser.operation.delay(check_interval) - except Exception: - time.sleep(check_interval) - - # 记录智能等待结束状态 - total_elapsed = time.time() - wait_start + min_wait_seconds - if not detail_opened: - try: - analyser._log_kv( - "流程", - "find_and_open_fudai_detail:智能等待超时,未检测到详情页", - check_count=check_count, - total_elapsed=round(total_elapsed, 2), - max_wait_seconds=max_wait_seconds, - ) - except Exception: - pass - - # 如果智能等待已检测到详情页,直接返回成功,无需再次检测 - if detail_opened: - # 清除第一次读取标志,确保新打开的福袋会进行完整的OCR识别 - try: - analyser._fudai_detail_first_read = False - analyser._last_fudai_detail_tuple = None - except Exception: - pass - elapsed = time.time() - func_start_time - analyser._log_kv("流程", "find_and_open_fudai_detail完成(成功打开详情)", elapsed_seconds=round(elapsed, 2)) - return True - # 如果智能等待未检测到详情页,执行完整的验证流程 - # 确保有最新截图 + wait_seconds = float(getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0) + try: + analyser._log_kv( + "流程", + "find_and_open_fudai_detail:点击后固定等待", + wait_seconds=wait_seconds, + ) + except Exception: + pass + + try: + analyser.operation.delay(wait_seconds) + except Exception: + time.sleep(wait_seconds) + + from douyin.stage import douyin_stage + analyser.operation.get_screenshot(device_id, use_service=False) pic_path = path_config.get_screenshot_path() if not os.path.exists(pic_path): @@ -370,11 +243,13 @@ def find_and_open_fudai_detail( pass return False - # 点击后进行阶段检测,确认当前页面状态 try: result = douyin_stage.diagnose_stage_from_current_screen(analyser) if result is None: - stage, reason = ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间") + stage, reason = ( + "IN_LIVE_ROOM", + "阶段诊断返回 None,默认判定为在直播间", + ) else: stage, reason = result try: @@ -387,7 +262,6 @@ def find_and_open_fudai_detail( except Exception: pass - # 如果阶段检测已经确认在福袋详情页,直接返回成功 if stage == "FUDai_DETAIL": try: analyser._log_kv( @@ -398,17 +272,19 @@ def find_and_open_fudai_detail( ) except Exception: pass - # 清除第一次读取标志,确保新打开的福袋会进行完整的OCR识别 try: analyser._fudai_detail_first_read = False analyser._last_fudai_detail_tuple = None except Exception: pass elapsed = time.time() - func_start_time - analyser._log_kv("流程", "find_and_open_fudai_detail完成(成功打开详情)", elapsed_seconds=round(elapsed, 2)) + analyser._log_kv( + "流程", + "find_and_open_fudai_detail完成(成功打开详情)", + elapsed_seconds=round(elapsed, 2), + ) return True else: - # 如果不在福袋详情页,可能是误点击,通过点击固定坐标返回直播间 try: analyser._log_kv( "流程", @@ -419,8 +295,6 @@ def find_and_open_fudai_detail( except Exception: pass - # 使用固定坐标 (520, 505) 进行点击,而不是系统返回键 - # 根据当前分辨率进行等比例换算(基准分辨率 1080x2400) rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) try: @@ -432,7 +306,6 @@ def find_and_open_fudai_detail( try: analyser.operation.click(device_id, back_click_x, back_click_y) except Exception: - # 兜底:直接用 analyser.click try: analyser.click(back_click_x, back_click_y) except Exception: @@ -443,16 +316,18 @@ def find_and_open_fudai_detail( except Exception: time.sleep(1.0) - # 清除历史位置,避免下次继续误点击 try: analyser.last_fudai_x = 0 except Exception: pass elapsed = time.time() - func_start_time - analyser._log_kv("流程", "find_and_open_fudai_detail完成(误点击)", elapsed_seconds=round(elapsed, 2)) + analyser._log_kv( + "流程", + "find_and_open_fudai_detail完成(误点击)", + elapsed_seconds=round(elapsed, 2), + ) return False except Exception as e: - # 阶段检测失败,返回False try: analyser._log_kv( "流程", @@ -462,139 +337,41 @@ def find_and_open_fudai_detail( except Exception: pass elapsed = time.time() - func_start_time - analyser._log_kv("流程", "find_and_open_fudai_detail完成(阶段检测异常)", elapsed_seconds=round(elapsed, 2)) + analyser._log_kv( + "流程", + "find_and_open_fudai_detail完成(阶段检测异常)", + elapsed_seconds=round(elapsed, 2), + ) return False except Exception: try: analyser.click(x, base_y) - # 点击后等待福袋详情页加载(可配置) - fudai_click_wait_seconds = float( - getattr(analyser, "fudai_click_wait_seconds", 2.0) or 2.0 + wait_seconds = float( + getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0 ) - analyser.operation.delay(fudai_click_wait_seconds) + analyser.operation.delay(wait_seconds) elapsed = time.time() - func_start_time - analyser._log_kv("流程", "find_and_open_fudai_detail完成(兜底成功)", elapsed_seconds=round(elapsed, 2)) + analyser._log_kv( + "流程", + "find_and_open_fudai_detail完成(兜底成功)", + elapsed_seconds=round(elapsed, 2), + ) return True except Exception: elapsed = time.time() - func_start_time - analyser._log_kv("流程", "find_and_open_fudai_detail完成(兜底失败)", elapsed_seconds=round(elapsed, 2)) - return False - - -def handle_no_fudai_situation( - analyser: Any, - x: int, - swipe_times: int, - wait_times_ref: List[int], - needswitch: bool, - reservation_focus_until_ts: float, - reservations: list, - room_pos: int, - post_switch_delay_s: float, - swipe_up_switch_callback, - swipe_down_back_callback, - sort_reservations_callback, - clear_reservations_callback, - write_state_callback, - back_to_list_callback, - into_list_callback, - reservation_focus_until_ts_ref: List[float], - reset_to_list_after_reservations_ref: List[bool], - swipe_times_ref: List[int], -) -> bool: - """当前直播间没有福袋时的基础处理。 - - 本地版实现: - - 先让预约模块有机会“抢占”流程(例如到点需要回退到预约直播间); - - 若未触发预约回退,则执行简单的等待 + 上滑切换。 - """ - try: - analyser._log_kv( - "流程", - "handle_no_fudai_situation", - x=x, - swipe_times=swipe_times, - room_pos=room_pos, - reservations=len(reservations), - ) - except Exception: - pass - - # --- 优先让“预约回退窗口”有机会执行 --- - try: - if getattr(analyser, "high_value_fudai_enabled", False) and reservations: - # 构造回调:下滑回退一个直播间 - def _swipe_down_once() -> None: - try: - if swipe_down_back_callback: - swipe_down_back_callback() - except Exception: - pass - - def _sort_reservations() -> None: - try: - # 使用统一核心逻辑排序 - douyin_reservation_logic._sort_reservations_inplace(reservations) # type: ignore[attr-defined] - except Exception: - pass - - def _write_state() -> None: - try: - if write_state_callback: - write_state_callback() - except Exception: - pass - - # 调用预约窗口处理:若返回 True,表示已触发回退,本轮不再上滑 - def _seek_reservation_room(item: dict) -> bool: - """委托给 analyser._seek_reservation_room,避免简化为恒 True。""" - try: - fn = getattr(analyser, "_seek_reservation_room", None) - if not fn: - return False - return bool(fn(item)) - except Exception: - return False - - preempted = douyin_reservation_logic.process_reservation_attend_window( - analyser=analyser, - reservations=reservations, - room_pos=room_pos, - reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, - reservation_after_action_pending_ref=[False], - reservation_back_swipe_delay_s=float( - getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6 - ), - swipe_down_back_callback=_swipe_down_once, - seek_reservation_room_callback=_seek_reservation_room, - sort_reservations_callback=_sort_reservations, - write_state_callback=_write_state, + analyser._log_kv( + "流程", + "find_and_open_fudai_detail完成(兜底失败)", + elapsed_seconds=round(elapsed, 2), ) - if preempted: - return True - except Exception: - # 预约处理异常不影响基础切换逻辑 - pass - - # 简单策略:轻微等待 + 上滑切换 - try: - analyser.operation.delay(1.0) - except Exception: - time.sleep(1.0) - - if needswitch and swipe_up_switch_callback: - swipe_up_switch_callback() - try: - analyser.operation.delay(post_switch_delay_s or 1.2) - except Exception: - time.sleep(post_switch_delay_s or 1.2) + return False return False def filter_fudai_detail( analyser: Any, - detail: Tuple, + detail: tuple, x: int, needswitch: bool, post_switch_delay_s: float, @@ -625,7 +402,11 @@ def filter_fudai_detail( if not skip: elapsed = time.time() - start_time - analyser._log_kv("流程", "filter_fudai_detail完成(筛选通过)", elapsed_seconds=round(elapsed, 2)) + analyser._log_kv( + "流程", + "filter_fudai_detail完成(筛选通过)", + elapsed_seconds=round(elapsed, 2), + ) return False try: @@ -647,7 +428,86 @@ def filter_fudai_detail( pass elapsed = time.time() - start_time - analyser._log_kv("流程", "filter_fudai_detail完成(筛选不通过)", elapsed_seconds=round(elapsed, 2), reason=reason) + analyser._log_kv( + "流程", + "filter_fudai_detail完成(筛选不通过)", + elapsed_seconds=round(elapsed, 2), + reason=reason, + ) return True + +def handle_no_fudai_situation( + analyser: Any, + x: int, + swipe_times: int, + wait_times_ref: List[int], + needswitch: bool, + reservation_focus_until_ts: float, + reservations: list, + room_pos: int, + post_switch_delay_s: float, + swipe_up_switch_callback: Optional[Callable[[], None]], + swipe_down_back_callback: Callable[[], None], + sort_reservations_callback: Callable[[], None], + clear_reservations_callback: Callable[[], None], + write_state_callback: Callable[[], None], + back_to_list_callback: Callable[[], None], + into_list_callback: Callable[[], None], + reservation_focus_until_ts_ref: List[float], + reset_to_list_after_reservations_ref: List[bool], + swipe_times_ref: List[int], + seek_reservation_room_callback: Optional[Callable[[dict[str, Any]], bool]] = None, + reservation_after_action_pending_ref: Optional[List[bool]] = None, + reservation_back_swipe_delay_s: Optional[float] = None, +) -> bool: + """处理未找到福袋的逻辑(预约回退 / 切换直播间)。""" + + handled_reservation = False + seek_callback = seek_reservation_room_callback or (lambda item: False) + reservation_after_action_pending_ref = ( + reservation_after_action_pending_ref if reservation_after_action_pending_ref else [False] + ) + reservation_back_swipe_delay_s = ( + reservation_back_swipe_delay_s + if reservation_back_swipe_delay_s is not None + else float(getattr(analyser, "reservation_back_swipe_delay_s", 0.5) or 0.5) + ) + + try: + from douyin.reservation import douyin_reservation_logic + + handled_reservation = douyin_reservation_logic.process_reservation_attend_window( + analyser, + reservations, + room_pos, + reservation_focus_until_ts_ref, + reservation_after_action_pending_ref, + reservation_back_swipe_delay_s, + swipe_down_back_callback, + seek_callback, + sort_reservations_callback, + write_state_callback, + ) + except Exception: + handled_reservation = False + + if handled_reservation: + return True + + if wait_times_ref: + wait_times_ref[0] += 1 + + if needswitch and swipe_up_switch_callback: + try: + swipe_up_switch_callback() + except Exception: + pass + delay_seconds = float(post_switch_delay_s or 1.0) + try: + analyser.operation.delay(delay_seconds) + except Exception: + time.sleep(delay_seconds) + if swipe_times_ref: + swipe_times_ref[0] += 1 return False diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index f58a4d3..4e0c5de 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -1,5 +1,3 @@ -from __future__ import annotations - """ 本地完整版 douyin_fudai(模块化调度器) ====================================== @@ -10,6 +8,8 @@ from __future__ import annotations - 将核心逻辑拆分到各子模块,仅在此做"组装 + 调度"。 """ +from __future__ import annotations + from typing import Any, List, Tuple, Optional import os import time @@ -139,7 +139,7 @@ class fudai_analyse: self.fudai_icon_retry_delay_seconds: float = 0.6 self.fudai_icon_max_wait_seconds: float = 5.0 # 点击福袋图标后等待详情页加载的时间(秒) - self.fudai_click_wait_seconds: float = 2.0 + self.fudai_click_wait_seconds: float = 1.0 # 切换直播间后等待阶段诊断的时间(秒) self.switch_room_wait_after_stage_diag_seconds: float = 7.0 # 滑动速度(毫秒),影响滑动持续时间,值越大滑动越慢 @@ -299,9 +299,16 @@ class fudai_analyse: """兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。""" # DEBUG: 记录函数入口 try: - self._log_kv("DEBUG", "entered fudai_choujiang", device_id=device_id, wait_minutes=wait_minutes) + self._log_kv( + "DEBUG", + "entered fudai_choujiang", + device_id=device_id, + wait_minutes=wait_minutes, + ) except Exception: - print(f"[DEBUG] entered fudai_choujiang device_id={device_id} wait_minutes={wait_minutes}") + print( + f"[DEBUG] entered fudai_choujiang device_id={device_id} wait_minutes={wait_minutes}" + ) self.device_id = device_id or self.device_id self.y_pianyi = int(y_pianyi or 0) # 保存是否允许切换直播间的配置,供后续所有逻辑统一使用 @@ -322,9 +329,16 @@ class fudai_analyse: break except Exception as e: try: - self._log_kv("截图", "获取分辨率失败,重试中", attempt=attempt + 1, error=str(e)) + self._log_kv( + "截图", + "获取分辨率失败,重试中", + attempt=attempt + 1, + error=str(e), + ) except Exception: - print(f"[DEBUG] get_device_resolution attempt {attempt+1} failed: {e}") + print( + f"[DEBUG] get_device_resolution attempt {attempt+1} failed: {e}" + ) time.sleep(1.0) if not resolved: # 回退到默认分辨率 @@ -359,9 +373,12 @@ class fudai_analyse: pass except Exception as top_exc: try: - self._log_kv("ERROR", "fudai_choujiang top-level exception", error=str(top_exc)) + self._log_kv( + "ERROR", "fudai_choujiang top-level exception", error=str(top_exc) + ) except Exception: import traceback + traceback.print_exc() raise @@ -456,7 +473,9 @@ class fudai_analyse: errors="replace", ) as f: f.write("=" * 80 + "\n") - f.write(f"{end_time} - [GUI] - [运行] 程序运行结束(中断退出)\n") + f.write( + f"{end_time} - [GUI] - [运行] 程序运行结束(中断退出)\n" + ) f.flush() except Exception: pass @@ -486,7 +505,9 @@ class fudai_analyse: time.sleep(1.0) # ========== 阶段诊断 ========== - def _diagnose_stage_from_current_screen(self, force_screenshot: bool = False) -> Tuple[str, str]: + def _diagnose_stage_from_current_screen( + self, force_screenshot: bool = False + ) -> Tuple[str, str]: """封装到子模块的阶段诊断入口。 参数: @@ -590,7 +611,9 @@ class fudai_analyse: 注意:此方法复杂度较高,已通过模块化重构将部分逻辑拆分到子模块。 """ - from douyin.reservation import douyin_reservation_logic # 确保在函数作用域内可用 + from douyin.reservation import ( + douyin_reservation_logic, + ) # 确保在函数作用域内可用 start_time = time.time() # 0. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果 @@ -874,7 +897,9 @@ class fudai_analyse: state_path = getattr(self, "_reservations_state_path", None) if state_path: # 写入空队列到状态文件 - from douyin.reservation.douyin_reservation import write_reservations_state + from douyin.reservation.douyin_reservation import ( + write_reservations_state, + ) write_reservations_state( state_path=state_path, @@ -1546,7 +1571,7 @@ class fudai_analyse: retries=max_screenshot_retries, elapsed_seconds=round(elapsed, 2), screenshot_elapsed_seconds=round(screenshot_elapsed, 2), - suggestion="检查设备连接状态和ADB服务" + suggestion="检查设备连接状态和ADB服务", ) return @@ -2379,8 +2404,8 @@ class fudai_analyse: and len(detail) >= 6 ): # 类型检查:detail 已经通过 isinstance 检查,可以安全地索引 - # 直接使用 detail,因为已经通过了类型和长度检查 - countdown_tuple: Any = detail[5] # type: ignore[index] + detail_values = detail + countdown_tuple: Any = detail_values[5] # type: ignore[index] if ( isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2 @@ -2492,8 +2517,9 @@ class fudai_analyse: prize_value_yuan = 0.0 countdown_tuple = None if isinstance(detail, tuple) and len(detail) >= 6: - prize_value_yuan = float(detail[4] or 0.0) - countdown_tuple = detail[5] + detail_values = detail + prize_value_yuan = float(detail_values[4] or 0.0) + countdown_tuple = detail_values[5] # 检查是否启用高价值预约 high_value_enabled = bool( diff --git a/douyin/core/douyin_main_flow.py b/douyin/core/douyin_main_flow.py index 0b5d22c..1c999a9 100644 --- a/douyin/core/douyin_main_flow.py +++ b/douyin/core/douyin_main_flow.py @@ -132,5 +132,3 @@ class MainFlowController: # 由于 run_once_basic 方法过于复杂,暂时保持原实现 # 但通过模块化组织,后续可以进一步拆分 analyser.run_once_basic_original() # type: ignore[attr-defined] - - diff --git a/douyin/core/fudai_modules/base_interface.py b/douyin/core/fudai_modules/base_interface.py index 5c13f83..9da6124 100644 --- a/douyin/core/fudai_modules/base_interface.py +++ b/douyin/core/fudai_modules/base_interface.py @@ -72,53 +72,3 @@ class BaseFudaiMixin: except Exception as e: self._safe_log("错误", f"调用 {operation_name} 失败", error=str(e)) return None - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/douyin/core/fudai_modules/fudai_lottery_result.py b/douyin/core/fudai_modules/fudai_lottery_result.py index d6caccc..c201bab 100644 --- a/douyin/core/fudai_modules/fudai_lottery_result.py +++ b/douyin/core/fudai_modules/fudai_lottery_result.py @@ -27,19 +27,3 @@ class LotteryResultMixin: """ from douyin.utils import douyin_helpers douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(self, result_type) - - - - - - - - - - - - - - - - diff --git a/douyin/core/fudai_modules/fudai_room_utils.py b/douyin/core/fudai_modules/fudai_room_utils.py index f38d62a..5489a9f 100644 --- a/douyin/core/fudai_modules/fudai_room_utils.py +++ b/douyin/core/fudai_modules/fudai_room_utils.py @@ -46,53 +46,3 @@ class RoomUtilsMixin: return douyin_reservation_handler.ReservationHandler.seek_reservation_room( self, item ) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index 6b9fbae..e24df52 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,5 +1,5 @@ { - "updated_ts": 1767290732.5810602, + "updated_ts": 1767357328.7936106, "reason": "startup_clear", "room_pos": 0, "current_room_title": "", diff --git a/douyin/detection/__init__.py b/douyin/detection/__init__.py index 319b845..3df2dbb 100644 --- a/douyin/detection/__init__.py +++ b/douyin/detection/__init__.py @@ -6,4 +6,3 @@ from . import douyin_detection from . import douyin_pixel __all__ = ["douyin_detection", "douyin_pixel"] - diff --git a/douyin/detection/core/__init__.py b/douyin/detection/core/__init__.py index 46a6672..304fd4b 100644 --- a/douyin/detection/core/__init__.py +++ b/douyin/detection/core/__init__.py @@ -18,53 +18,3 @@ __all__ = [ "check_have_fudai_with_ready_screenshot", "check_in_fudai_detail", ] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/douyin/detection/douyin_detection.py b/douyin/detection/douyin_detection.py index 029c219..f595afc 100644 --- a/douyin/detection/douyin_detection.py +++ b/douyin/detection/douyin_detection.py @@ -43,7 +43,7 @@ def check_detail_height(analyser: Any) -> int: # 回退到旧路径(向后兼容) import path_config pic1_path = path_config.get_screenshot_path() - + # 记录截图文件的时间戳(如果存在) screenshot_timestamp = None try: @@ -51,7 +51,7 @@ def check_detail_height(analyser: Any) -> int: screenshot_timestamp = os.path.getmtime(pic1_path) except Exception: pass - + pic = None for attempt in range(3): try: @@ -162,13 +162,13 @@ def check_detail_height(analyser: Any) -> int: try: import importlib douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") - + # 计算检测区域(参与按钮附近的区域) check_region_x1 = max(0, x - 50) check_region_x2 = min(width, x + 50) check_region_y1 = max(0, (883 * ry // 2400) - 100) # 3个任务的Y坐标附近 check_region_y2 = min(height, (1058 * ry // 2400) + 100) # 1个任务的Y坐标附近 - + # 标注检测点 coords_list = [] for base_y, dy, task_count_val in check_points: @@ -181,7 +181,7 @@ def check_detail_height(analyser: Any) -> int: min(width, x + 10), min(height, check_y + 5) )) - + # 保存调试图片 pic_rgb = pic.convert("RGB") debug_path = douyin_screenshot_manager.save_debug_image( @@ -244,7 +244,7 @@ def check_have_fudai_with_ready_screenshot( analyser: Any, screenshot_ready: bool = False ): """判定直播页面福袋的小图标是否存在(优化版,优先使用模块化查找器)。 - + 如果启用了优化查找器(fudai_finder_optimized_enabled=True),则使用新的模块化查找器。 否则使用原版像素检测实现。 """ @@ -255,7 +255,7 @@ def check_have_fudai_with_ready_screenshot( ) except Exception: use_optimized = False - + if use_optimized: try: from douyin.fudai.douyin_fudai_finder import check_have_fudai_with_ready_screenshot_optimized @@ -283,7 +283,7 @@ def check_have_fudai_with_ready_screenshot( ) except Exception: pass - + # 原版实现(像素检测版) func_start = time.time() # 使用统一的截图路径配置 @@ -337,7 +337,7 @@ def check_have_fudai_with_ready_screenshot( except Exception: pass break - + # 每次循环都重新截图(除了第一次如果已经提供了截图) if not (screenshot_ready and loop == 0): try: @@ -431,7 +431,7 @@ def check_have_fudai_with_ready_screenshot( scan_x_start = 41 * rx // 1080 scan_x_end = min(410 * rx // 1080, width) scan_y = 403 * ry // 2400 + y_pianyi_val - + # 获取最优搜索起始位置(使用历史记录或默认值) try: # 尝试获取上次找到的福袋位置(1080基准) @@ -444,7 +444,7 @@ def check_have_fudai_with_ready_screenshot( except Exception: # 使用默认最优位置 optimal_x_scaled = 169 * rx // 1080 - + # 确保最优位置在搜索范围内 optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1)) @@ -452,7 +452,7 @@ def check_have_fudai_with_ready_screenshot( try: from douyin.handlers import douyin_screenshot_manager pic_rgb_full = pic_new.convert("RGB") - + # 保存完整截图 debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb_full, @@ -526,11 +526,11 @@ def check_have_fudai_with_ready_screenshot( roi_width = x2 - x1 optimal_col = optimal_x_scaled - x1 # 转换为ROI内的列索引 optimal_col = max(0, min(optimal_col, roi_width - 1)) - + # 从最优位置开始,向左右两侧交替搜索 found_col = None search_range = max(optimal_col, roi_width - optimal_col) - + # 先检查最优位置本身 if valid_cols[optimal_col]: found_col = optimal_col @@ -547,16 +547,16 @@ def check_have_fudai_with_ready_screenshot( if left_col >= 0 and valid_cols[left_col]: found_col = left_col break - + # 如果没找到,回退到原来的方法(从左到右) if found_col is None: found_col = int(_np.argmax(valid_cols)) - + col_idx = found_col # 计算检测到的x坐标:转换为1080基准坐标,确保精度 detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx)) detected = True - + # 保存找到的位置作为下次的最优位置 try: analyser.last_fudai_x = detected_x @@ -571,7 +571,7 @@ def check_have_fudai_with_ready_screenshot( douyin_screenshot_manager.save_last_success( roi, operation_type="pixel_detect" ) - + # 保存完整截图(检测成功) pic_rgb_full = pic_new.convert("RGB") debug_path = douyin_screenshot_manager.save_debug_image( @@ -618,7 +618,7 @@ def check_have_fudai_with_ready_screenshot( scan_x_start = 41 * rx // 1080 scan_x_end = min(410 * rx // 1080, pic_width) scan_y = 403 * ry // 2400 + y_pianyi_val - + # 获取最优搜索起始位置(使用历史记录或默认值) try: # 尝试获取上次找到的福袋位置(1080基准) @@ -631,10 +631,10 @@ def check_have_fudai_with_ready_screenshot( except Exception: # 使用默认最优位置 optimal_x_scaled = 169 * rx // 1080 - + # 确保最优位置在搜索范围内 optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1)) - + # 确保y坐标在有效范围内 if 0 <= scan_y < pic_height: # 精度优化:同时检查上下几行像素,提高检测准确性 @@ -642,11 +642,11 @@ def check_have_fudai_with_ready_screenshot( check_y = scan_y + offset_y if not (0 <= check_y < pic_height): continue - + # 优化:从最优位置开始向左右两侧搜索 found_x = None search_range = max(optimal_x_scaled - scan_x_start, scan_x_end - optimal_x_scaled) - + # 先检查最优位置本身 try: px = pix[optimal_x_scaled, check_y] @@ -659,7 +659,7 @@ def check_have_fudai_with_ready_screenshot( found_x = optimal_x_scaled except (IndexError, TypeError): pass - + # 如果最优位置没找到,向左右两侧交替搜索 if found_x is None: for offset in range(1, search_range + 1): @@ -678,7 +678,7 @@ def check_have_fudai_with_ready_screenshot( break except (IndexError, TypeError): continue - + # 再检查左侧 left_x = optimal_x_scaled - offset if left_x >= scan_x_start: @@ -694,7 +694,7 @@ def check_have_fudai_with_ready_screenshot( break except (IndexError, TypeError): continue - + # 如果还是没找到,回退到原来的方法(从左到右) if found_x is None: for x_scaled in range(scan_x_start, scan_x_end): @@ -710,12 +710,12 @@ def check_have_fudai_with_ready_screenshot( break except (IndexError, TypeError): continue - + if found_x is not None: # 转换回1080基准坐标 detected_x = int(found_x * 1080.0 / max(1, rx)) detected = True - + # 保存找到的位置作为下次的最优位置 try: analyser.last_fudai_x = detected_x @@ -739,7 +739,7 @@ def check_have_fudai_with_ready_screenshot( detect_roi, operation_type="pixel_detect", ) - + # 保存完整截图(检测成功) pic_rgb_full = pic_new.convert("RGB") debug_path = douyin_screenshot_manager.save_debug_image( @@ -779,7 +779,7 @@ def check_have_fudai_with_ready_screenshot( except Exception: pass break # 找到后退出offset_y循环 - + if detected: break # 找到后退出外层循环 except Exception: @@ -1017,7 +1017,7 @@ def check_have_fudai_with_ready_screenshot( if detected and detected_x is not None: # 重置连续失败计数 consecutive_failures = 0 - + # 统计:每次"进入直播间"后首次找到福袋图标耗时 try: enter_ts = float(getattr(analyser, "_enter_live_ts", 0.0) or 0.0) @@ -1069,7 +1069,7 @@ def check_have_fudai_with_ready_screenshot( loop += 1 consecutive_failures += 1 - + # 如果连续失败太多次,提前退出(避免无效循环) if consecutive_failures >= max_consecutive_failures: try: @@ -1085,7 +1085,7 @@ def check_have_fudai_with_ready_screenshot( except Exception: pass break - + # 每轮记录一次轻量调试信息(帮助诊断为何未命中) # 只在每3次循环记录一次,减少日志量 if loop % 3 == 0: @@ -1374,7 +1374,7 @@ def check_have_fudai_with_ready_screenshot( douyin_screenshot_manager.save_latest_attempt( search_roi_pil, operation_type="template_match" ) - + # 保存调试图像(匹配前)- 使用完整截图 screenshot_pil = PILImage.fromarray( cv2.cvtColor(screenshot_img, cv2.COLOR_BGR2RGB) @@ -1433,7 +1433,7 @@ def check_have_fudai_with_ready_screenshot( douyin_screenshot_manager.save_last_success( search_roi_pil, operation_type="template_match" ) - + # 保存带匹配结果的调试图像(带匹配框)- 使用完整截图 screenshot_pil = PILImage.fromarray( cv2.cvtColor(screenshot_img, cv2.COLOR_BGR2RGB) @@ -1446,7 +1446,7 @@ def check_have_fudai_with_ready_screenshot( match_x2 = search_x1 + match_x_in_roi + tw match_y2 = search_y1 + match_y_in_roi + th match_coords = (match_x1, match_y1, match_x2, match_y2) - + debug_path = douyin_screenshot_manager.save_debug_image( screenshot_pil, operation_type="template_match", @@ -1635,7 +1635,7 @@ def check_have_fudai_with_ready_screenshot( def check_in_fudai_detail(analyser: Any) -> bool: """Detect whether we are currently on the fudai detail page. - + 使用模板匹配检测,与 detect_fudai_detail_page 保持一致。 """ _ensure_detection_cache(analyser) @@ -1652,7 +1652,7 @@ def check_in_fudai_detail(analyser: Any) -> bool: try: from douyin.detection import douyin_pixel import path_config - + # 获取截图 pic_path = path_config.get_screenshot_path() if not os.path.exists(pic_path): @@ -1665,26 +1665,26 @@ def check_in_fudai_detail(analyser: Any) -> bool: if not os.path.exists(pic_path): analyser._detection_cache[cache_key] = (now, False) return False - + pic = Image.open(pic_path) pic.load() pic_rgb = pic.convert("RGB") - + # 获取分辨率比例和Y偏移 rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) - + # 获取模板匹配阈值(优先使用福袋详情页专用阈值) template_threshold = float( - getattr(analyser, "fudai_detail_template_threshold", None) or + getattr(analyser, "fudai_detail_template_threshold", None) or getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7 ) if template_threshold < 0.0: template_threshold = 0.0 if template_threshold > 1.0: template_threshold = 1.0 - + # 使用任务数量检测 result = douyin_pixel.detect_fudai_detail_page( pic_rgb, @@ -1695,7 +1695,7 @@ def check_in_fudai_detail(analyser: Any) -> bool: return_info=False, # 不需要详细信息 analyser=analyser, ) - + is_in_detail = bool(result) analyser._detection_cache[cache_key] = (now, is_in_detail) return is_in_detail diff --git a/douyin/detection/douyin_pixel.py b/douyin/detection/douyin_pixel.py index 62354c5..d4d5d35 100644 --- a/douyin/detection/douyin_pixel.py +++ b/douyin/detection/douyin_pixel.py @@ -664,7 +664,7 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: try: from PIL import ImageDraw import numpy as np - + width, height = pic_rgb.size # 缩放坐标到实际尺寸(基于1080x2400) scale_x = width / 1080.0 @@ -675,7 +675,7 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: (1002, 172), (999, 174), (1011, 186), (999, 199), (1002, 202), (1013, 190), (1025, 201), (1028, 198), (1017, 187), (1028, 174), (1025, 172), (1014, 184) ] - + # 缩放多边形坐标到实际截图尺寸 polygon_points = [ (int(x * scale_x), int(y * scale_y)) @@ -685,13 +685,13 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: # 创建多边形mask mask = Image.new('L', (width, height), 0) draw = ImageDraw.Draw(mask) - + # 绘制多边形(填充为白色) draw.polygon(polygon_points, fill=255) # 将mask转换为numpy数组 mask_array = np.array(mask) - + # 获取原始图像的像素数据 img_array = np.array(pic_rgb) @@ -937,9 +937,9 @@ def read_pixel_stage_state_from_screenshot( } except Exception as e: # type: ignore[general-exception] return False, {"method": "pixel_detection", "error": str(e)} - + # 模板匹配已删除,只使用像素检测 - + detection_tasks = { "has_coupon_bg": lambda pic: detect_coupon_popup_background( pic, @@ -1025,9 +1025,9 @@ def read_pixel_stage_state_from_screenshot( if return_details: return state, details return state - + # 模板匹配已删除,只使用像素检测 - + detection_tasks = { "has_coupon_bg": lambda pic: detect_coupon_popup_background( pic, @@ -1112,4 +1112,4 @@ def read_pixel_stage_state_from_screenshot( if return_details: return state, details - return state \ No newline at end of file + return state diff --git a/douyin/fudai/__init__.py b/douyin/fudai/__init__.py index e1cdabd..f2e308d 100644 --- a/douyin/fudai/__init__.py +++ b/douyin/fudai/__init__.py @@ -1,7 +1,3 @@ """ 福袋相关模块 """ - - - - diff --git a/douyin/fudai/core/fudai_attend.py b/douyin/fudai/core/fudai_attend.py index b85c54f..e00d126 100644 --- a/douyin/fudai/core/fudai_attend.py +++ b/douyin/fudai/core/fudai_attend.py @@ -21,7 +21,7 @@ def attend_choujiang(analyser) -> bool: attend_button_text = "" button_status = getattr(analyser, "_fudai_button_status", None) button_text = getattr(analyser, "_fudai_button_text", "") - + # 如果并行OCR已经识别了按钮,且识别时间较近(5秒内),直接使用 if button_text and button_status: try: @@ -38,7 +38,7 @@ def attend_choujiang(analyser) -> bool: ) except Exception: pass - + # 如果并行OCR结果不可用,则重新识别 if not attend_button_text: analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字 @@ -1378,4 +1378,4 @@ def attend_choujiang(analyser) -> bool: last_text=attend_button_text or "", # type: ignore[possibly-unbound] result="参与失败", ) - return False \ No newline at end of file + return False diff --git a/douyin/fudai/core/fudai_debug_utils.py b/douyin/fudai/core/fudai_debug_utils.py index dc1a1ea..68cdfd9 100644 --- a/douyin/fudai/core/fudai_debug_utils.py +++ b/douyin/fudai/core/fudai_debug_utils.py @@ -21,7 +21,7 @@ def log_debug_error( level: str = "WARNING", ) -> None: """统一的错误日志记录函数。 - + 参数: analyser: 分析器对象 error: 异常对象 @@ -31,7 +31,7 @@ def log_debug_error( try: error_type = type(error).__name__ error_msg = str(error) - + # 构建详细的错误信息 error_info = { "error": error_msg, @@ -39,7 +39,7 @@ def log_debug_error( "level": level, **context, } - + # 对于严重错误,添加调用栈信息 if level == "ERROR": try: @@ -47,7 +47,7 @@ def log_debug_error( error_info["stack_trace"] = stack_trace[:500] # 限制长度 except Exception: pass - + analyser._log_kv( "调试工具", f"调试工具错误:{error_type}", @@ -67,51 +67,51 @@ def validate_coords( height: int, ) -> Tuple[bool, Optional[str], Tuple[int, int, int, int]]: """验证和修正坐标。 - + 参数: coords: 原始坐标 (x1, y1, x2, y2) width: 图像宽度 height: 图像高度 - + 返回: (是否有效, 错误信息, 修正后的坐标) """ x1, y1, x2, y2 = coords - + # 检查坐标是否有效 if x1 >= x2: return False, f"x1({x1}) >= x2({x2})", coords if y1 >= y2: return False, f"y1({y1}) >= y2({y2})", coords - + # 修正坐标到图像范围内 x1_corrected = max(0, min(x1, width - 1)) y1_corrected = max(0, min(y1, height - 1)) x2_corrected = max(0, min(x2, width - 1)) y2_corrected = max(0, min(y2, height - 1)) - + corrected_coords = (x1_corrected, y1_corrected, x2_corrected, y2_corrected) - + # 检查是否需要修正 - if (x1 != x1_corrected or y1 != y1_corrected or + if (x1 != x1_corrected or y1 != y1_corrected or x2 != x2_corrected or y2 != y2_corrected): return True, "坐标已修正", corrected_coords - + return True, None, corrected_coords def safe_image_load(image_path: str) -> Optional[Image.Image]: """安全地加载图像,带详细的错误处理。 - + 参数: image_path: 图像文件路径 - + 返回: PIL Image 对象,失败返回 None """ if not os.path.exists(image_path): return None - + try: pic = Image.open(image_path) pic.load() # 确保图像数据已加载 @@ -128,19 +128,19 @@ def safe_image_load(image_path: str) -> Optional[Image.Image]: def save_full_screenshot_with_ocr_region( - analyser: Any, - picname: str, - coords: Tuple[int, int, int, int], + analyser: Any, + picname: str, + coords: Tuple[int, int, int, int], y_pianyi: int = 0 ) -> None: """保存完整截图并标注OCR区域(用于调试)。 - + 参数: analyser: 分析器对象 picname: 图片名称(如"福袋内容") coords: OCR区域坐标 (x1, y1, x2, y2) - 基准坐标(1080x2400) y_pianyi: Y轴偏移 - + 错误处理: - FileNotFoundError: 截图文件不存在 - PermissionError: 文件权限错误 @@ -154,7 +154,7 @@ def save_full_screenshot_with_ocr_region( "coords": coords, "y_pianyi": y_pianyi, } - + try: import importlib douyin_screenshot_manager = importlib.import_module("douyin.handlers.douyin_screenshot_manager") @@ -166,11 +166,11 @@ def save_full_screenshot_with_ocr_region( level="ERROR", ) return - + # 读取完整截图 pic_path = path_config.get_screenshot_path() context["screenshot_path"] = pic_path - + if not os.path.exists(pic_path): log_debug_error( analyser, @@ -179,7 +179,7 @@ def save_full_screenshot_with_ocr_region( level="WARNING", ) return - + # 安全加载图像 try: pic_rgb = safe_image_load(pic_path) @@ -209,7 +209,7 @@ def save_full_screenshot_with_ocr_region( level="ERROR", ) return - + # 获取分辨率信息 width, height = pic_rgb.size try: @@ -223,12 +223,12 @@ def save_full_screenshot_with_ocr_region( level="WARNING", ) rx, ry = 1080, 2400 # 使用默认值 - + context.update({ "image_size": f"{width}x{height}", "base_resolution": f"{rx}x{ry}", }) - + # 缩放坐标到实际分辨率 try: x1_base, y1_base, x2_base, y2_base = coords @@ -236,7 +236,7 @@ def save_full_screenshot_with_ocr_region( y1 = int((y1_base + y_pianyi) * height / ry) x2 = int(x2_base * width / rx) y2 = int((y2_base + y_pianyi) * height / ry) - + scaled_coords = (x1, y1, x2, y2) except (ValueError, ZeroDivisionError) as e: log_debug_error( @@ -246,12 +246,12 @@ def save_full_screenshot_with_ocr_region( level="ERROR", ) return - + # 验证和修正坐标 is_valid, error_msg, corrected_coords = validate_coords( scaled_coords, width, height ) - + if not is_valid: log_debug_error( analyser, @@ -260,9 +260,9 @@ def save_full_screenshot_with_ocr_region( level="WARNING", ) return - + x1, y1, x2, y2 = corrected_coords - + # 如果坐标被修正,记录警告 if error_msg: try: @@ -277,7 +277,7 @@ def save_full_screenshot_with_ocr_region( ) except Exception: pass - + # 保存调试图片 try: debug_path = douyin_screenshot_manager.save_debug_image( @@ -292,7 +292,7 @@ def save_full_screenshot_with_ocr_region( "y_offset": y_pianyi, }, ) - + if debug_path: try: analyser._log_kv( diff --git a/douyin/fudai/core/fudai_detail_reader.py b/douyin/fudai/core/fudai_detail_reader.py index cb115a1..d195390 100644 --- a/douyin/fudai/core/fudai_detail_reader.py +++ b/douyin/fudai/core/fudai_detail_reader.py @@ -1150,4 +1150,4 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass - return fudai_content_text, time_text, participants, copies, prize_value_yuan \ No newline at end of file + return fudai_content_text, time_text, participants, copies, prize_value_yuan diff --git a/douyin/fudai/core/fudai_filter.py b/douyin/fudai/core/fudai_filter.py index 55b6564..f623f13 100644 --- a/douyin/fudai/core/fudai_filter.py +++ b/douyin/fudai/core/fudai_filter.py @@ -1027,4 +1027,4 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: elapsed_seconds=round(elapsed, 2), result=result, ) - return result \ No newline at end of file + return result diff --git a/douyin/fudai/core/fudai_result_checker.py b/douyin/fudai/core/fudai_result_checker.py index d9f09dc..68fb695 100644 --- a/douyin/fudai/core/fudai_result_checker.py +++ b/douyin/fudai/core/fudai_result_checker.py @@ -300,4 +300,4 @@ def get_reward(analyser, reward_y: int = 0) -> None: analyser._log_kv("领奖", "关闭中奖提醒后等待", wait_seconds=30) except Exception: pass - analyser.operation.delay(30) \ No newline at end of file + analyser.operation.delay(30) diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index 4c999a5..6bf6aba 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -4,7 +4,8 @@ import re import time import os import sys -from typing import Tuple, Any +import threading +from typing import Tuple, Any, Optional, Dict from PIL import Image from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np @@ -19,19 +20,51 @@ from douyin.fudai.core.fudai_debug_utils import ( ) try: from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore -except Exception: +except Exception: # pyright: ignore # 在运行环境中可能缺少 OCR 预处理依赖,提供回退实现以避免导入失败导致程序中断。 - def preprocess_for_ocr(analyser, picname: str) -> str: # type: ignore + def preprocess_for_ocr(_analyser, picname: str) -> str: # type: ignore # pyright: ignore """回退的 preprocess_for_ocr:直接返回 picname(不做预处理)。""" try: return str(picname) - except Exception: + except TypeError: # pyright: ignore return picname +# 模块级线程池状态,用于复用 OCR 并行执行,避免频繁创建/销毁 + + +class _FudaiOcrExecutorState: + def __init__(self) -> None: + self.executor: Optional[ThreadPoolExecutor] = None + self.workers: int = 0 + self.lock = threading.Lock() + + +_fudai_ocr_executor_state = _FudaiOcrExecutorState() + + +def _get_fudai_ocr_executor(optimal_workers: int) -> ThreadPoolExecutor: + """获取复用的 OCR 线程池;如线程数变化则重建。""" + state = _fudai_ocr_executor_state + with state.lock: + if state.executor and state.workers == optimal_workers: + return state.executor + # 若线程数变化,安全关闭旧池 + if state.executor: + try: + state.executor.shutdown(wait=False, cancel_futures=True) + except RuntimeError: + pass + state.executor = None + executor = ThreadPoolExecutor(max_workers=optimal_workers) + state.executor = executor + state.workers = optimal_workers + return executor + + def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: """获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。""" - + # 检查是否启用调试截图保存(默认False,正常运行时跳过以提升性能) try: save_debug_images = bool(getattr(analyser, "fudai_detail_save_debug_images", False)) @@ -46,18 +79,26 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo with open(cfg_path, "r", encoding="utf-8") as f: cfg = json.load(f) save_debug_images = bool(cfg.get("fudai_detail_save_debug_images", False)) - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass + # 轻重分流模式:auto(缺失字段才跑重)、light(只跑轻)、heavy(轻后必跑重) + try: + ocr_mode = str(getattr(analyser, "fudai_detail_ocr_mode", "auto") or "auto").lower() + except Exception: + ocr_mode = "auto" + force_light = ocr_mode == "light" + force_heavy = ocr_mode == "heavy" + def _parse_mm_ss(text: str): m = re.search(r"(\d{1,2})[::](\d{2})", str(text or "")) if not m: return None try: return int(m.group(1)), int(m.group(2)) - except Exception as e: + except Exception as e: # pyright: ignore try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore "验证", "解析倒计时格式失败", error=str(e), @@ -65,7 +106,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo text=text[:50] if text else "", level="WARNING", ) - except Exception: + except Exception: # pyright: ignore pass return None @@ -110,9 +151,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo (x1 + seg1, y1, x1 + seg1 + seg2, y2), analyser.y_pianyi, ) - except Exception as e: + except Exception as e: # pyright: ignore[reportTooBroadExceptionType] try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "错误", "保存倒计时调试截图失败", error=str(e), @@ -120,7 +161,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo box=box, level="WARNING", ) - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass # 切割分钟区域(左侧) @@ -142,7 +183,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo try: mm_name = preprocess_for_ocr(analyser, "福袋倒计时_分钟") ss_name = preprocess_for_ocr(analyser, "福袋倒计时_秒") - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] mm_name = "福袋倒计时_分钟" ss_name = "福袋倒计时_秒" @@ -185,7 +226,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo ss_int = int(ss) if ss else 0 if ss_int >= 60: try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "验证", "分割识别:检测到秒数>=60(可能是识别错误)", mm=mm_int, @@ -194,11 +235,11 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo ss_raw=ss_raw, level="WARNING", ) - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass - except Exception as e: + except Exception as e: # pyright: ignore[reportTooBroadExceptionType] try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "错误", "验证倒计时数值失败", error=str(e), @@ -207,40 +248,40 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo ss=ss, level="WARNING", ) - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass if mm and ss: result = f"{mm}:{ss}" try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "福袋倒计时", "分割识别成功", mm_raw=mm_raw, ss_raw=ss_raw, result=result, ) - except Exception as e: + except Exception as e: # pyright: ignore[reportTooBroadExceptionType] try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "错误", "记录倒计时识别成功日志失败", error=str(e), error_type=type(e).__name__, level="WARNING", ) - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass return result - except Exception as e: + except Exception as e: # pyright: ignore[reportTooBroadExceptionType] try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "福袋倒计时", "分割识别失败", error=str(e), error_type=type(e).__name__, ) - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass return "" @@ -263,7 +304,126 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo cleaned = re.sub(r"\d+人已参与", "", cleaned) return participants, copies, cleaned + def _is_blank_text(text: Any) -> bool: + return len(str(text or "").strip()) == 0 + + def _should_use_heavy( + content_text: Any, + mm_raw: Any, + ss_raw: Any, + value_text: Any, + task_text: Any, + button_text: Any, + ) -> set: + fields: set[str] = set() + if force_light: + return fields + if force_heavy or _is_blank_text(content_text): + fields.add("content") + if force_heavy or not (mm_raw and ss_raw): + fields.update({"countdown_mm", "countdown_ss"}) + if force_heavy or _is_blank_text(value_text): + fields.add("value") + if force_heavy or _is_blank_text(task_text): + fields.add("task_list") + if force_heavy or _is_blank_text(button_text): + fields.add("button") + return fields + + def _run_heavy_ocr(fields: set[str]) -> Dict[str, Any]: + """按需补充较重的OCR,避免默认就跑全量重模型。""" + results: Dict[str, Any] = {} + heavy_start = time.time() + + def _safe_preprocess(name: str) -> str: + try: + return preprocess_for_ocr(analyser, name) + except Exception: + return name + + # 任务列表:用于兜底检测观看任务 + if "task_list" in fields: + try: + name_tl = _safe_preprocess("福袋任务列表") + results["task_list"] = analyser.operation.analyse_pic_word(name_tl, 1) + except Exception: + pass + + # 内容:使用更重的文本模型兜底 + if "content" in fields: + try: + name_fc = _safe_preprocess("福袋内容") + results["content"] = analyser.operation.analyse_pic_word(name_fc, 1) + except Exception: + pass + + # 倒计时:先数字模型,失败再文本提取数字 + if "countdown_mm" in fields: + mm_digits = "" + try: + raw = analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 1) + mm_digits = "".join(ch for ch in str(raw or "") if ch.isdigit()) + except Exception: + pass + if not mm_digits: + try: + raw = analyser.operation.analyse_pic_word("福袋倒计时_分钟", 1) + mm_digits = "".join(ch for ch in str(raw or "") if ch.isdigit()) + except Exception: + pass + if mm_digits: + results["countdown_mm"] = mm_digits + + if "countdown_ss" in fields: + ss_digits = "" + try: + raw = analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) + ss_digits = "".join(ch for ch in str(raw or "") if ch.isdigit()) + except Exception: + pass + if not ss_digits: + try: + raw = analyser.operation.analyse_pic_word("福袋倒计时_秒", 1) + ss_digits = "".join(ch for ch in str(raw or "") if ch.isdigit()) + except Exception: + pass + if ss_digits: + results["countdown_ss"] = ss_digits + + # 价值:重模型兜底一次,兼容带符号文本 + if "value" in fields: + val_digits = "" + try: + name_val = _safe_preprocess("福袋价值") + raw_val = analyser.operation.analyse_pic_digits(name_val, 1) + val_digits = "".join(ch for ch in str(raw_val or "") if ch.isdigit()) + except Exception: + pass + if not val_digits: + try: + raw_val = analyser.operation.analyse_pic_word(name_val, 1) + val_digits = "".join(ch for ch in str(raw_val or "") if ch.isdigit()) + except Exception: + pass + if val_digits: + results["value"] = val_digits + + # 按钮状态:重模型兜底,避免轻量误判 + if "button" in fields: + try: + name_btn = _safe_preprocess("参与按钮") + results["button"] = analyser.operation.analyse_pic_word(name_btn, 1) + except Exception: + pass + + try: + results["_duration_ms"] = round((time.time() - heavy_start) * 1000, 1) + except Exception: + pass + return results + countdown_box = None + value_box = (633, 1580, 783, 1696) if renwu == 2: # 如果是2个任务的 # 优化:扩大Y范围向上,确保包含任务描述(如"观看X分钟"等) # 从1240向上扩展到1100,确保包含任务描述区域 @@ -301,11 +461,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo # 优化:向上扩大范围(1460->1440),防止识别不完整 if save_debug_images: _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1440, 1000, 1580), analyser.y_pianyi + analyser, "福袋价值", value_box, analyser.y_pianyi ) - analyser.cut_pic( - 390, 1440, 1000, 1580, "", "福袋价值", analyser.y_pianyi - ) # 奖品价值/价格 + analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi) elif renwu == 1: # 如果是1个任务的 # 优化:扩大Y范围向上,确保包含任务描述 if save_debug_images: @@ -342,11 +500,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo # 优化:向上扩大范围(1520->1500),防止识别不完整 if save_debug_images: _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1500, 1000, 1630), analyser.y_pianyi + analyser, "福袋价值", value_box, analyser.y_pianyi ) - analyser.cut_pic( - 390, 1500, 1000, 1630, "", "福袋价值", analyser.y_pianyi - ) # 奖品价值/价格 + analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi) elif renwu == 3: # 如果是3个任务的 # 优化:扩大Y范围向上,确保包含任务描述 if save_debug_images: @@ -383,11 +539,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo # 优化:向上扩大范围(1380->1360),防止识别不完整 if save_debug_images: _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1360, 1000, 1490), analyser.y_pianyi + analyser, "福袋价值", value_box, analyser.y_pianyi ) - analyser.cut_pic( - 390, 1360, 1000, 1490, "", "福袋价值", analyser.y_pianyi - ) # 奖品价值/价格 + analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi) else: # 优化:稍微缩小宽度,增加高度 if save_debug_images: @@ -424,11 +578,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo # 优化:向上扩大范围(1820->1800),防止识别不完整 if save_debug_images: _save_full_screenshot_with_ocr_region( - analyser, "福袋价值", (390, 1800, 1000, 1930), analyser.y_pianyi + analyser, "福袋价值", value_box, analyser.y_pianyi ) - analyser.cut_pic( - 390, 1800, 1000, 1930, "", "福袋价值", analyser.y_pianyi - ) # 奖品价值/价格 + analyser.cut_pic(*value_box, "", "福袋价值", analyser.y_pianyi) # 准备任务列表区域的截图(用于并行OCR) # 任务列表区域(任务位置:50,1621到1032,1960),用于检测"观看X分钟"任务 @@ -439,15 +591,15 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser, "福袋任务列表", (50, 1621, 1032, 1960), analyser.y_pianyi ) analyser.cut_pic(50, 1621, 1032, 1960, "", "福袋任务列表", analyser.y_pianyi) - except Exception as e: + except Exception as e: # pyright: ignore[reportTooBroadExceptionType] # 任务列表截图失败不影响后续流程,记录日志即可 try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "福袋", "任务列表截图失败,继续后续流程", error=str(e), ) - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass # 准备参与按钮区域的截图(用于并行OCR识别按钮状态) @@ -458,10 +610,10 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser, "参与按钮", (306, 2030, 780, 2110), analyser.y_pianyi ) analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮", analyser.y_pianyi) - except Exception as e: + except Exception as e: # pyright: ignore[reportTooBroadExceptionType] # 按钮截图失败不影响后续流程,记录日志即可 try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "福袋", "参与按钮截图失败,继续后续流程", error=str(e), @@ -478,9 +630,13 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo countdown_ss_raw = None value_raw = None button_text_raw = None + # 并行子任务耗时收集(ms),由各子任务在 finally 中写入 + perf_task_durations: Dict[str, float] = {} + perf_task_lock = threading.Lock() def ocr_task_list(): """OCR识别任务列表(用于检测观看任务)""" + start = time.time() try: name_tl = preprocess_for_ocr(analyser, "福袋任务列表") return analyser.operation.analyse_pic_word(name_tl, 0) @@ -496,9 +652,21 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass return None + finally: + try: + dur = round((time.time() - start) * 1000, 1) + with perf_task_lock: + perf_task_durations["ocr_task_list"] = dur + try: + analyser._log_kv("性能", "并行OCR子任务单项耗时(ms)", field="task_list", duration_ms=dur) + except Exception: + pass + except Exception: + pass def ocr_content(): """OCR识别福袋内容""" + start = time.time() try: name_fc = preprocess_for_ocr(analyser, "福袋内容") return analyser.operation.analyse_pic_word(name_fc, 0) @@ -514,11 +682,25 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass return None + finally: + try: + dur = round((time.time() - start) * 1000, 1) + with perf_task_lock: + perf_task_durations["ocr_content"] = dur + try: + analyser._log_kv("性能", "并行OCR子任务单项耗时(ms)", field="content", duration_ms=dur) + except Exception: + pass + except Exception: + pass def ocr_countdown_mm(): - """OCR识别福袋倒计时分钟(使用轻量数字OCR)""" + """OCR识别福袋倒计时分钟(纯数字模型,无回退)。""" + start = time.time() try: - return analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 1) + raw = str(analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 0) or "") + digits = "".join(ch for ch in raw if ch.isdigit()) + return digits except Exception as e: try: analyser._log_kv( @@ -531,11 +713,25 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass return None + finally: + try: + dur = round((time.time() - start) * 1000, 1) + with perf_task_lock: + perf_task_durations["ocr_countdown_mm"] = dur + try: + analyser._log_kv("性能", "并行OCR子任务单项耗时(ms)", field="countdown_mm", duration_ms=dur) + except Exception: + pass + except Exception: + pass def ocr_countdown_ss(): - """OCR识别福袋倒计时秒(使用轻量数字OCR)""" + """OCR识别福袋倒计时秒(纯数字模型,无回退)。""" + start = time.time() try: - return analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) + raw = str(analyser.operation.analyse_pic_digits("福袋倒计时_秒", 0) or "") + digits = "".join(ch for ch in raw if ch.isdigit()) + return digits except Exception as e: try: analyser._log_kv( @@ -548,12 +744,37 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass return None + finally: + try: + dur = round((time.time() - start) * 1000, 1) + with perf_task_lock: + perf_task_durations["ocr_countdown_ss"] = dur + try: + analyser._log_kv("性能", "并行OCR子任务单项耗时(ms)", field="countdown_ss", duration_ms=dur) + except Exception: + pass + except Exception: + pass def ocr_value(): - """OCR识别福袋价值(使用普通OCR)""" + """OCR识别福袋价值:优先用数字模型提取金额,回退文本模型。""" + start = time.time() try: - name_val = preprocess_for_ocr(analyser, "福袋价值") - return analyser.operation.analyse_pic_word(name_val, 0) + try: + name_val = preprocess_for_ocr(analyser, "福袋价值") + except Exception: + name_val = "福袋价值" + + # 先用数字模型提取金额,避免整段文本的开销 + digits_raw = str(analyser.operation.analyse_pic_digits(name_val, 1) or "") + digits_only = "".join(ch for ch in digits_raw if ch.isdigit()) + if digits_only: + return digits_only + + # 回退:再跑一次文本模型,兼容包含货币符号的情况 + word_raw = str(analyser.operation.analyse_pic_word(name_val, 0) or "") + word_digits = "".join(ch for ch in word_raw if ch.isdigit()) + return word_digits or word_raw except Exception as e: try: analyser._log_kv( @@ -566,6 +787,17 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass return None + finally: + try: + dur = round((time.time() - start) * 1000, 1) + with perf_task_lock: + perf_task_durations["ocr_value"] = dur + try: + analyser._log_kv("性能", "并行OCR子任务单项耗时(ms)", field="value", duration_ms=dur) + except Exception: + pass + except Exception: + pass def ocr_button(): """OCR识别参与按钮(用于检测参与状态)""" @@ -592,7 +824,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo return button_text # 只有在模式0完全失败时才尝试模式1 if not button_text: - button_text = str(analyser.operation.analyse_pic_word(name_btn, 1) or "") + button_text = str(analyser.operation.analyse_pic_word(name_btn, 0) or "") return button_text except Exception as e: try: @@ -610,24 +842,94 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数 try: - # 使用动态线程池大小,根据CPU核心数优化 + # 使用动态线程池大小,根据CPU核心数优化,并复用线程池 from operations.screenshot_service import get_optimal_workers optimal_workers = get_optimal_workers() - with ThreadPoolExecutor(max_workers=optimal_workers) as executor: - future_task_list = executor.submit(ocr_task_list) - future_content = executor.submit(ocr_content) - future_countdown_mm = executor.submit(ocr_countdown_mm) - future_countdown_ss = executor.submit(ocr_countdown_ss) - future_value = executor.submit(ocr_value) - future_button = executor.submit(ocr_button) + executor = _get_fudai_ocr_executor(optimal_workers) - # 等待所有操作完成 - task_list_raw = future_task_list.result() - fudai_content_raw = future_content.result() - countdown_mm_raw = future_countdown_mm.result() - countdown_ss_raw = future_countdown_ss.result() - value_raw = future_value.result() - button_text_raw = future_button.result() + task_funcs = { + "task_list": ocr_task_list, + "content": ocr_content, + "countdown_mm": ocr_countdown_mm, + "countdown_ss": ocr_countdown_ss, + "value": ocr_value, + "button": ocr_button, + } + futures: Dict[str, Any] = {} + start_ts: Dict[str, float] = {} + + for name, func in task_funcs.items(): + start_ts[name] = time.time() + futures[name] = executor.submit(func) + + task_list_raw = fudai_content_raw = countdown_mm_raw = None + countdown_ss_raw = value_raw = button_text_raw = None + + # 收集结果并记录耗时 + durations = {} + for name, fut in futures.items(): + try: + res = fut.result() + finally: + durations[name] = round((time.time() - start_ts.get(name, time.time())) * 1000, 1) + if name == "task_list": + task_list_raw = res + elif name == "content": + fudai_content_raw = res + elif name == "countdown_mm": + countdown_mm_raw = res + elif name == "countdown_ss": + countdown_ss_raw = res + elif name == "value": + value_raw = res + elif name == "button": + button_text_raw = res + + try: + analyser._log_kv( + "性能", + "并行OCR子任务耗时(ms)", + **{f"ocr_{k}": v for k, v in durations.items()}, + ) + except Exception: + pass + + # 轻重分流:轻量OCR跑完后,仅在缺字段或强制时补充重OCR + try: + heavy_fields = _should_use_heavy( + fudai_content_raw, + countdown_mm_raw, + countdown_ss_raw, + value_raw, + task_list_raw, + button_text_raw, + ) + except Exception: + heavy_fields = set() + + if heavy_fields: + heavy_res = _run_heavy_ocr(heavy_fields) + + def _prefer(new_val: Any, old_val: Any): + return new_val if not _is_blank_text(new_val) else old_val + + task_list_raw = _prefer(heavy_res.get("task_list"), task_list_raw) + fudai_content_raw = _prefer(heavy_res.get("content"), fudai_content_raw) + countdown_mm_raw = _prefer(heavy_res.get("countdown_mm"), countdown_mm_raw) + countdown_ss_raw = _prefer(heavy_res.get("countdown_ss"), countdown_ss_raw) + value_raw = _prefer(heavy_res.get("value"), value_raw) + button_text_raw = _prefer(heavy_res.get("button"), button_text_raw) + + try: + analyser._log_kv( + "性能", + "福袋详情OCR轻重分流:触发重OCR补齐", + mode=ocr_mode, + heavy_fields=sorted(list(heavy_fields)), + heavy_duration_ms=heavy_res.get("_duration_ms"), + ) + except Exception: + pass # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) if task_list_raw: @@ -758,17 +1060,36 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo except Exception: pass except Exception as e: - # 如果并行执行失败,回退到备用并行执行(使用新的线程池) + # 如果并行执行失败,按需决定是否走备用并行(可跳过以节省时间) try: analyser._log_kv( "错误", - "并行OCR失败,使用备用并行执行", + "并行OCR失败", error=str(e), error_type=type(e).__name__, level="ERROR", ) except Exception: pass + + # 可选跳过备用并行,加快失败路径(默认启用备用;可通过 analyser.enable_fudai_ocr_fallback 控制) + try: + enable_fallback_parallel = bool(getattr(analyser, "enable_fudai_ocr_fallback", True)) + except Exception: + enable_fallback_parallel = True + + if not enable_fallback_parallel: + try: + analyser._log_kv( + "性能", + "跳过备用并行OCR以节省时间", + reason="fallback_disabled", + level="WARNING", + ) + except Exception: + pass + return "", "", 0, 0, 0.0 + # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行) try: @@ -807,7 +1128,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo def ocr_countdown_mm_fallback(): try: - return analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 1) + return analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 0) except Exception as e: try: analyser._log_kv( @@ -823,7 +1144,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo def ocr_countdown_ss_fallback(): try: - return analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) + return analyser.operation.analyse_pic_digits("福袋倒计时_秒", 0) except Exception as e: try: analyser._log_kv( @@ -872,7 +1193,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo "未达成", ) ): - button_text = str(analyser.operation.analyse_pic_word(name_btn, 1) or "") + button_text = str(analyser.operation.analyse_pic_word(name_btn, 0) or "") return button_text except Exception as e: try: @@ -887,24 +1208,54 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo pass return None - # 使用动态线程池大小 + # 使用动态线程池大小,并复用线程池 from operations.screenshot_service import get_optimal_workers optimal_workers = get_optimal_workers() - with ThreadPoolExecutor(max_workers=optimal_workers) as executor: - future_task_list = executor.submit(ocr_task_list_fallback) - future_content = executor.submit(ocr_content_fallback) - future_countdown_mm = executor.submit(ocr_countdown_mm_fallback) - future_countdown_ss = executor.submit(ocr_countdown_ss_fallback) - future_value = executor.submit(ocr_value_fallback) - future_button = executor.submit(ocr_button_fallback) + executor = _get_fudai_ocr_executor(optimal_workers) - # 等待所有操作完成 - task_list_raw = future_task_list.result() - fudai_content_raw = future_content.result() - countdown_mm_raw = future_countdown_mm.result() - countdown_ss_raw = future_countdown_ss.result() - value_raw = future_value.result() - button_text_raw = future_button.result() + task_funcs = { + "task_list": ocr_task_list_fallback, + "content": ocr_content_fallback, + "countdown_mm": ocr_countdown_mm_fallback, + "countdown_ss": ocr_countdown_ss_fallback, + "value": ocr_value_fallback, + "button": ocr_button_fallback, + } + futures: Dict[str, Any] = {} + start_ts: Dict[str, float] = {} + for name, func in task_funcs.items(): + start_ts[name] = time.time() + futures[name] = executor.submit(func) + + durations = {} + task_list_raw = fudai_content_raw = countdown_mm_raw = None + countdown_ss_raw = value_raw = button_text_raw = None + for name, fut in futures.items(): + try: + res = fut.result() + finally: + durations[name] = round((time.time() - start_ts.get(name, time.time())) * 1000, 1) + if name == "task_list": + task_list_raw = res + elif name == "content": + fudai_content_raw = res + elif name == "countdown_mm": + countdown_mm_raw = res + elif name == "countdown_ss": + countdown_ss_raw = res + elif name == "value": + value_raw = res + elif name == "button": + button_text_raw = res + + try: + analyser._log_kv( + "性能", + "备用并行OCR子任务耗时(ms)", + **{f"ocr_{k}": v for k, v in durations.items()}, + ) + except Exception: + pass # 检查任务列表中是否包含"观看X分钟"任务(在并行OCR完成后检查) if task_list_raw: @@ -1051,9 +1402,9 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo pass fudai_content_raw = analyser.operation.analyse_pic_word("福袋内容", 0) countdown_mm_raw = analyser.operation.analyse_pic_digits( - "福袋倒计时_分钟", 1 + "福袋倒计时_分钟", 0 ) - countdown_ss_raw = analyser.operation.analyse_pic_digits("福袋倒计时_秒", 1) + countdown_ss_raw = analyser.operation.analyse_pic_digits("福袋倒计时_秒", 0) value_raw = analyser.operation.analyse_pic_word("福袋价值", 0) # 串行执行按钮OCR try: @@ -1074,8 +1425,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo "未达成", ) ): - button_text_raw = str(analyser.operation.analyse_pic_word(name_btn3, 1) or "") - + button_text_raw = str(analyser.operation.analyse_pic_word(name_btn3, 0) or "") + # 处理串行执行的按钮识别结果 button_status = None if button_text_raw: @@ -1464,6 +1815,12 @@ def check_contain(analyser, contains: str = "") -> bool: - True : “建议丢弃”(内容命中黑名单 contains_not_want) - False : “可以保留”(未命中黑名单,或凌晨时段不做内容过滤) """ + + # 以下抑制为静态检查方便添加: + # - W0212: protected-access(许多地方访问分析器/底层对象的受保护属性,运行时可用) + # - W0718: broad-exception-caught(代码中大量使用 broad except 用于鲁棒性) + # 这些抑制只影响静态检查,不改变运行时行为。 + # pylint: disable=W0212,W0718 try: hour = int(analyser.operation.get_current_hour()) except Exception: @@ -3739,7 +4096,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: # 检查是否是预约回退后强制参与(跳过验证) # 注意:必须在检查 _last_fudai_detail_status 之前检查,否则强制参与标志会被忽略 force_attend = getattr(analyser, "_force_attend_after_reservation_back", False) - + # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 # 但如果设置了强制参与标志,则跳过状态检查(预约回退时使用预约记录,可能不满足验证条件) try: diff --git a/douyin/fudai/douyin_fudai_finder.py b/douyin/fudai/douyin_fudai_finder.py index 26324a0..712658c 100644 --- a/douyin/fudai/douyin_fudai_finder.py +++ b/douyin/fudai/douyin_fudai_finder.py @@ -12,6 +12,8 @@ from __future__ import annotations 5. 详细日志:记录每个步骤的耗时和结果 """ +# pylint: disable=E1101 + import os import time from typing import Any, Optional, Tuple, Dict @@ -1056,12 +1058,12 @@ class FudaiClickExecutor: self.analyser.operation.click(device_id, click_x, click_y) # 点击后等待足够时间让详情页加载(避免连续点击导致详情页被关闭) - # 默认等待2.5秒,确保详情页完全打开并稳定 + # 默认等待1.0秒,可通过 GUI 配置 click_wait_time = float( - getattr(self.analyser, "fudai_click_wait_seconds", 2.5) or 2.5 + getattr(self.analyser, "fudai_click_wait_seconds", 1.0) or 1.0 ) - if click_wait_time < 1.5: - click_wait_time = 1.5 # 最小1.5秒 + if click_wait_time < 1.0: + click_wait_time = 1.0 # 最小1.0秒 self.analyser.operation.delay(click_wait_time) elapsed = (time.time() - start_time) * 1000 @@ -1081,7 +1083,7 @@ class FudaiClickExecutor: self.analyser.click(fudai_x, base_y) # 回退模式也需要等待 click_wait_time = float( - getattr(self.analyser, "fudai_click_wait_seconds", 1.5) or 1.5 + getattr(self.analyser, "fudai_click_wait_seconds", 1.0) or 1.0 ) if click_wait_time < 1.0: click_wait_time = 1.0 diff --git a/douyin/fudai/finder/__init__.py b/douyin/fudai/finder/__init__.py index 4a13b5c..4c3a743 100644 --- a/douyin/fudai/finder/__init__.py +++ b/douyin/fudai/finder/__init__.py @@ -22,54 +22,3 @@ __all__ = [ "FudaiFinder", "check_have_fudai_with_ready_screenshot_optimized", ] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/douyin/handlers/douyin_popup_handler.py b/douyin/handlers/douyin_popup_handler.py index 775e3ac..8489e9f 100644 --- a/douyin/handlers/douyin_popup_handler.py +++ b/douyin/handlers/douyin_popup_handler.py @@ -40,5 +40,3 @@ class PopupHandler: bool: 是否检测到弹窗 """ return douyin_popups.check_shopping_redpacket_popup(analyser) - - diff --git a/douyin/handlers/douyin_screenshot_handler.py b/douyin/handlers/douyin_screenshot_handler.py index 4bc75e6..1f5167e 100644 --- a/douyin/handlers/douyin_screenshot_handler.py +++ b/douyin/handlers/douyin_screenshot_handler.py @@ -123,5 +123,3 @@ class ScreenshotHandler: pass except Exception: pass - - diff --git a/douyin/handlers/douyin_screenshot_manager.py b/douyin/handlers/douyin_screenshot_manager.py index bda48e2..210f097 100644 --- a/douyin/handlers/douyin_screenshot_manager.py +++ b/douyin/handlers/douyin_screenshot_manager.py @@ -1506,4 +1506,4 @@ def save_debug_image( # type: ignore return None # 结束 save_debug_image 的主逻辑,返回 None 表示保存失败 - return None \ No newline at end of file + return None diff --git a/douyin/handlers/douyin_swipe_handler.py b/douyin/handlers/douyin_swipe_handler.py index 28a98e8..230d576 100644 --- a/douyin/handlers/douyin_swipe_handler.py +++ b/douyin/handlers/douyin_swipe_handler.py @@ -422,9 +422,3 @@ class SwipeHandler: ) except Exception: pass # 日志系统本身出错时忽略 - - - - - - diff --git a/douyin/handlers/douyin_swipe_ops.py b/douyin/handlers/douyin_swipe_ops.py index 269745b..1b27347 100644 --- a/douyin/handlers/douyin_swipe_ops.py +++ b/douyin/handlers/douyin_swipe_ops.py @@ -7,7 +7,7 @@ import os def _adb_swipe_direct(device_id: str, start_x: int, start_y: int, end_x: int, end_y: int, duration_ms: int = 300, operation=None) -> bool: """直接使用 ADB 内部滑动命令执行滑动操作。 - + Args: device_id: 设备 ID start_x: 起始 X 坐标 @@ -16,7 +16,7 @@ def _adb_swipe_direct(device_id: str, start_x: int, start_y: int, end_x: int, en end_y: 结束 Y 坐标 duration_ms: 滑动持续时间(毫秒) operation: operation 对象,用于获取 ADB 路径(可选) - + Returns: True 如果成功,False 如果失败 """ @@ -28,7 +28,7 @@ def _adb_swipe_direct(device_id: str, start_x: int, start_y: int, end_x: int, en adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb" if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'): adb_cmd = f'"{adb_cmd}"' - + # 直接使用 ADB 命令执行滑动 cmd = f"{adb_cmd} -s {device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} {duration_ms}" result = subprocess.run( @@ -39,7 +39,7 @@ def _adb_swipe_direct(device_id: str, start_x: int, start_y: int, end_x: int, en timeout=5.0, text=True, ) - + return result.returncode == 0 except Exception: return False @@ -111,14 +111,14 @@ def swipe_up_switch_live(analyser: Any) -> None: analyser.swipe(start_x_base, start_y_base, end_x_base, end_y_base, swipe_duration_ms) except Exception: pass - + # 注意:滑动后的延迟由调用方控制(如 reservation_back_swipe_delay) # 这里不添加额外延迟,避免双重延迟 def swipe_down_back_live(analyser: Any) -> None: """下滑回退到上一个直播间(基础版封装)。 - + 直接使用 ADB 内部滑动命令,不通过坐标计算。 在直播间内,向下滑动(从上往下)可以回退到上一个直播间。 采用 1080x2400 基准坐标,在屏幕中上部向下滑一段距离。 @@ -185,6 +185,6 @@ def swipe_down_back_live(analyser: Any) -> None: analyser.swipe(start_x_base, start_y_base, end_x_base, end_y_base, swipe_duration_ms) except Exception: pass - + # 注意:滑动后的延迟由调用方控制(如 reservation_back_swipe_delay) # 这里不添加额外延迟,避免双重延迟 diff --git a/douyin/logging/__init__.py b/douyin/logging/__init__.py index d93403b..852bf14 100644 --- a/douyin/logging/__init__.py +++ b/douyin/logging/__init__.py @@ -58,7 +58,3 @@ __all__ = [ "track_action", "_get_debug_logger", ] - - - - diff --git a/douyin/logging/action_logger.py b/douyin/logging/action_logger.py index f9b20ad..1e0245b 100644 --- a/douyin/logging/action_logger.py +++ b/douyin/logging/action_logger.py @@ -60,5 +60,3 @@ class ActionLogger: self.log_operation("Step", name, elapsed=elapsed) __all__ = ["ActionLogger"] - - diff --git a/douyin/logging/action_tracker.py b/douyin/logging/action_tracker.py index 92a3a94..675ff67 100644 --- a/douyin/logging/action_tracker.py +++ b/douyin/logging/action_tracker.py @@ -26,41 +26,3 @@ def track_action(name: str = ""): return decorator __all__ = ["track_action"] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/douyin/logging/debug_logger.py b/douyin/logging/debug_logger.py index ae30c88..80b3b8e 100644 --- a/douyin/logging/debug_logger.py +++ b/douyin/logging/debug_logger.py @@ -96,5 +96,3 @@ def _get_debug_logger() -> DebugLogger: return DebugLogger(True) __all__ = ["DebugLogger", "_get_debug_logger"] - - diff --git a/douyin/logging/douyin_logging_wrapper.py b/douyin/logging/douyin_logging_wrapper.py index 3b64bdd..94ffca9 100644 --- a/douyin/logging/douyin_logging_wrapper.py +++ b/douyin/logging/douyin_logging_wrapper.py @@ -500,7 +500,7 @@ class LoggingWrapper: console_handlers = [h for h in root_logger.handlers if isinstance(h, logging.StreamHandler) and h.stream == sys.stdout] for handler in console_handlers: handler.setLevel(logging.CRITICAL + 1) # 临时禁用 - + try: if exc_info: root_logger.log( diff --git a/douyin/logging/error_logger.py b/douyin/logging/error_logger.py index 159371c..c6bf2e6 100644 --- a/douyin/logging/error_logger.py +++ b/douyin/logging/error_logger.py @@ -60,24 +60,3 @@ class ErrorLogger: self.log_exception(exc, context=context, level=level) __all__ = ["ErrorLogger"] - - - - - - - - - - - - - - - - - - - - - diff --git a/douyin/logging/log_formatter.py b/douyin/logging/log_formatter.py index ab0fe43..4d9d479 100644 --- a/douyin/logging/log_formatter.py +++ b/douyin/logging/log_formatter.py @@ -152,5 +152,3 @@ __all__ = [ "beautify_log_output", "colorize_log_line", ] - - diff --git a/douyin/logging/performance_tracker.py b/douyin/logging/performance_tracker.py index caaa85e..68a6e5c 100644 --- a/douyin/logging/performance_tracker.py +++ b/douyin/logging/performance_tracker.py @@ -65,5 +65,3 @@ class PerformanceTracker: return stats __all__ = ["PerformanceTracker"] - - diff --git a/douyin/other/__init__.py b/douyin/other/__init__.py index 60dfc1f..4384a43 100644 --- a/douyin/other/__init__.py +++ b/douyin/other/__init__.py @@ -1,7 +1,3 @@ """ 其他功能模块 """ - - - - diff --git a/douyin/other/douyin_live_room.py b/douyin/other/douyin_live_room.py index 90bff8f..0cbe700 100644 --- a/douyin/other/douyin_live_room.py +++ b/douyin/other/douyin_live_room.py @@ -53,4 +53,3 @@ def get_no_fudai_wait_time(analyser: Any) -> float: def check_no_fudai_time(analyser: Any) -> float: """Shim: compatibility wrapper returning the same as get_no_fudai_wait_time.""" return get_no_fudai_wait_time(analyser) - diff --git a/douyin/other/douyin_popups.py b/douyin/other/douyin_popups.py index ff530a5..1bf1b03 100644 --- a/douyin/other/douyin_popups.py +++ b/douyin/other/douyin_popups.py @@ -12,16 +12,16 @@ from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore def check_coupon_popup(analyser) -> bool: """优惠券弹窗检测(模板匹配 + OCR兜底确认)。 - + 流程: 1. 使用模板匹配检测优惠券弹窗背景(assets/coupon.png) 2. 如果模板匹配成功,使用OCR检测"开心收下"按钮文字进行确认 3. OCR检测区域与"粉丝团加入"相同:(200, 1940)-(880, 2140) - + 注意:优惠券弹窗中的数字可能不同,但"开心收下"按钮位置固定。 """ check_start = time.time() - + # 步骤1:模板匹配 template_matched = False try: @@ -52,7 +52,7 @@ def check_coupon_popup(analyser) -> bool: return False template_elapsed = time.time() - check_start - + # 如果模板匹配失败,直接返回False if not template_matched: try: @@ -70,19 +70,19 @@ def check_coupon_popup(analyser) -> bool: ocr_start = time.time() coupon_text = "" ocr_confirmed = False - + try: # 截图按钮区域 analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮") cut_elapsed = time.time() - ocr_start - + # OCR模式0 ocr_mode0_start = time.time() try: pname0 = preprocess_for_ocr(analyser, "参与按钮") coupon_text = str(analyser.operation.analyse_pic_word(pname0, 0) or "") ocr_mode0_elapsed = time.time() - ocr_mode0_start - + if coupon_text and "开心收下" in coupon_text: ocr_confirmed = True total_elapsed = time.time() - check_start @@ -109,7 +109,7 @@ def check_coupon_popup(analyser) -> bool: ) except Exception: pass - + # OCR模式1(如果模式0未识别到) enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False)) if enable_ocr_mode1 and not ocr_confirmed: @@ -118,7 +118,7 @@ def check_coupon_popup(analyser) -> bool: pname1 = preprocess_for_ocr(analyser, "参与按钮") coupon_text = str(analyser.operation.analyse_pic_word(pname1, 1) or "") ocr_mode1_elapsed = time.time() - ocr_mode1_start - + if coupon_text and "开心收下" in coupon_text: ocr_confirmed = True total_elapsed = time.time() - check_start @@ -145,7 +145,7 @@ def check_coupon_popup(analyser) -> bool: ) except Exception: pass - + # OCR未确认,但模板匹配成功,信任模板匹配结果 total_elapsed = time.time() - check_start try: @@ -161,7 +161,7 @@ def check_coupon_popup(analyser) -> bool: except Exception: pass return True - + except Exception as e: ocr_elapsed = time.time() - ocr_start total_elapsed = time.time() - check_start @@ -384,16 +384,16 @@ def check_shopping_redpacket_popup(analyser) -> bool: def handle_lottery_result_popup(analyser) -> None: """处理抽奖结果弹窗:通过OCR识别并点击"我知道了"或"领取并使用"按钮。 - + 根据阶段诊断,已经确认是 FUDai_RESULT 阶段,这里使用OCR识别按钮文本后点击。 """ try: analyser._log_kv("开奖结果", "开始处理抽奖结果弹窗") - + # 使用OCR识别开奖结果按钮 from douyin.utils import douyin_helpers result_type = douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(analyser) - + if result_type: # 根据OCR识别结果处理 douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(analyser, result_type) @@ -402,7 +402,7 @@ def handle_lottery_result_popup(analyser) -> None: analyser._log_kv("开奖结果", "OCR未识别到按钮,使用返回键关闭") analyser.operation.click_back(analyser.device_id) analyser.operation.delay(0.5) - + analyser._log_kv("开奖结果", "处理完成") except Exception as e: analyser._log_kv("开奖结果", "处理失败", error=str(e)) diff --git a/douyin/other/douyin_robot.py b/douyin/other/douyin_robot.py index 2daffe1..a040f2a 100644 --- a/douyin/other/douyin_robot.py +++ b/douyin/other/douyin_robot.py @@ -144,5 +144,3 @@ def check_robot_pic_distance(analyser) -> int: return x1 - x # 如果没有检测到,返回一个兜底值 0 return 0 - - diff --git a/douyin/other/douyin_yanghao.py b/douyin/other/douyin_yanghao.py index a4d3ad3..c26cb48 100644 --- a/douyin/other/douyin_yanghao.py +++ b/douyin/other/douyin_yanghao.py @@ -530,6 +530,3 @@ def maybe_reset_after_swipes(analyser, needswitch: bool, swipe_times: int) -> in # 回到第一个后,计数归零 analyser.operation.delay(3) return 0 - - - diff --git a/douyin/reservation/__init__.py b/douyin/reservation/__init__.py index 49765a9..df15356 100644 --- a/douyin/reservation/__init__.py +++ b/douyin/reservation/__init__.py @@ -1,7 +1,3 @@ """ 预约相关模块 """ - - - - diff --git a/douyin/reservation/core/__init__.py b/douyin/reservation/core/__init__.py index 9781516..3beefff 100644 --- a/douyin/reservation/core/__init__.py +++ b/douyin/reservation/core/__init__.py @@ -32,54 +32,3 @@ __all__ = [ "process_reservation_attend_window", "record_high_value_reservation", ] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/douyin/reservation/core/reservation_error_utils.py b/douyin/reservation/core/reservation_error_utils.py index 4631e52..c0688b3 100644 --- a/douyin/reservation/core/reservation_error_utils.py +++ b/douyin/reservation/core/reservation_error_utils.py @@ -18,17 +18,17 @@ def format_reservation_context( **kwargs ) -> Dict[str, Any]: """格式化预约上下文信息。 - + 参数: item: 预约项字典(可选) reservations: 预约队列列表(可选) **kwargs: 其他上下文信息 - + 返回: 格式化的上下文信息字典 """ context: Dict[str, Any] = {} - + # 添加预约项信息 if item: try: @@ -51,7 +51,7 @@ def format_reservation_context( pass except Exception: pass - + # 添加队列信息 if reservations is not None: try: @@ -68,10 +68,10 @@ def format_reservation_context( } except Exception: pass - + # 添加其他上下文信息 context.update(kwargs) - + return context @@ -83,7 +83,7 @@ def log_reservation_error( stage: str = "", ) -> None: """统一的预约错误日志记录函数。 - + 参数: analyser: 分析器对象 error: 异常对象 @@ -94,7 +94,7 @@ def log_reservation_error( try: error_type = type(error).__name__ error_msg = str(error) - + # 构建详细的错误信息 error_info = { "error": error_msg, @@ -103,7 +103,7 @@ def log_reservation_error( "stage": stage, **context, } - + # 对于严重错误,添加调用栈信息 if level == "ERROR": try: @@ -111,7 +111,7 @@ def log_reservation_error( error_info["stack_trace"] = stack_trace[:500] # 限制长度 except Exception: pass - + analyser._log_kv( "预约", f"[预约] 错误:{stage or '未知操作'}" if stage else "[预约] 错误", @@ -131,18 +131,18 @@ def safe_write_state( context: Optional[Dict[str, Any]] = None, ) -> bool: """安全的状态文件写入,带详细的错误处理。 - + 参数: write_callback: 写入状态的回调函数 analyser: 分析器对象(可选,用于日志记录) context: 上下文信息(可选) - + 返回: bool: 是否成功写入 """ if context is None: context = {} - + try: write_callback() return True @@ -190,22 +190,22 @@ def safe_write_state( def validate_reservation_item(item: ReservationItem) -> Tuple[bool, Optional[str]]: """验证预约项数据的有效性。 - + 参数: item: 预约项字典 - + 返回: (是否有效, 错误信息) """ if not isinstance(item, dict): return False, "预约项不是字典类型" - + # 检查必需字段 required_fields = ["future_ts", "prize_value_yuan"] for field in required_fields: if field not in item: return False, f"缺少必需字段: {field}" - + # 验证 future_ts try: future_ts = float(item.get("future_ts", 0)) @@ -213,7 +213,7 @@ def validate_reservation_item(item: ReservationItem) -> Tuple[bool, Optional[str return False, f"future_ts 无效: {future_ts}" except (ValueError, TypeError) as e: return False, f"future_ts 格式错误: {e}" - + # 验证 prize_value_yuan try: prize_value = float(item.get("prize_value_yuan", 0)) @@ -221,6 +221,5 @@ def validate_reservation_item(item: ReservationItem) -> Tuple[bool, Optional[str return False, f"prize_value_yuan 无效: {prize_value}" except (ValueError, TypeError) as e: return False, f"prize_value_yuan 格式错误: {e}" - - return True, None + return True, None diff --git a/douyin/reservation/douyin_reservation.py b/douyin/reservation/douyin_reservation.py index fa3753c..2fb9406 100644 --- a/douyin/reservation/douyin_reservation.py +++ b/douyin/reservation/douyin_reservation.py @@ -26,7 +26,7 @@ except ImportError: def _write_json_atomic(path: str, data: object, *, indent: int = 2, analyser: Optional[Any] = None) -> None: """原子写入 JSON 文件,带详细的错误处理。 - + 参数: path: 文件路径 data: 要写入的数据 @@ -55,7 +55,7 @@ def _write_json_atomic(path: str, data: object, *, indent: int = 2, analyser: Op stage="创建状态文件目录(系统错误)", ) raise - + tmp = path + ".tmp" try: with open(tmp, "w", encoding="utf-8") as f: @@ -91,7 +91,7 @@ def _write_json_atomic(path: str, data: object, *, indent: int = 2, analyser: Op stage="写入状态文件(系统错误)", ) raise - + try: os.replace(tmp, path) except OSError as e: @@ -123,7 +123,7 @@ def write_reservations_state( analyser: Optional[Any] = None, ) -> None: """寫入預約隊列狀態(跨進程可讀)。 - + 参数: state_path: 状态文件路径 reservations: 预约队列列表 @@ -239,6 +239,3 @@ def write_high_value_rooms_state(path: str, rooms_map: dict, *, reason: str = "" _write_json_atomic(path, data, indent=2) except Exception: pass - - - diff --git a/douyin/reservation/douyin_reservation_handler.py b/douyin/reservation/douyin_reservation_handler.py index 0a79d7d..1b55e1c 100644 --- a/douyin/reservation/douyin_reservation_handler.py +++ b/douyin/reservation/douyin_reservation_handler.py @@ -16,9 +16,7 @@ import difflib from typing import Any, Optional, Dict from douyin.fudai import douyin_fudai_detail -from douyin.fudai import douyin_fudai_core from douyin.reservation import douyin_reservation_logic -from douyin.reservation import douyin_reservation_verify from douyin.handlers import douyin_swipe_handler # 导入预约错误处理工具 diff --git a/douyin/reservation/douyin_reservation_logic.py b/douyin/reservation/douyin_reservation_logic.py index 83c7467..2ab2fe0 100644 --- a/douyin/reservation/douyin_reservation_logic.py +++ b/douyin/reservation/douyin_reservation_logic.py @@ -70,7 +70,7 @@ def _now_ts() -> float: def _normalize_room_title_for_matching(title: str) -> str: """规范化直播间标题用于匹配比较。 - + 去除数字、特殊字符等,只保留核心名称部分。 例如:"王媛媛" 和 "王媛媛2" 会被规范化为相同的字符串。 """ @@ -92,39 +92,39 @@ def _normalize_room_title_for_matching(title: str) -> str: def _calculate_string_similarity(s1: str, s2: str) -> float: """计算两个字符串的相似度(简单的字符重叠比例)。 - + 返回 0.0 到 1.0 之间的值,1.0 表示完全相同。 """ if not s1 or not s2: return 0.0 if s1 == s2: return 1.0 - + # 计算字符集合的交集和并集 set1 = set(s1) set2 = set(s2) intersection = len(set1 & set2) union = len(set1 | set2) - + if union == 0: return 0.0 - + # Jaccard相似度 jaccard = intersection / union - + # 如果长度相近,额外加分 len_ratio = min(len(s1), len(s2)) / max(len(s1), len(s2)) if max(len(s1), len(s2)) > 0 else 0.0 - + # 综合相似度(Jaccard占70%,长度比例占30%) similarity = jaccard * 0.7 + len_ratio * 0.3 - + return similarity def _extract_content_core(content: str) -> str: """提取福袋内容的核心部分(去除倒计时等变化部分)。 - - 例如:"10后开奖03(琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方" + + 例如:"10后开奖03(琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方" 提取为:"琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方" """ if not content: @@ -171,13 +171,13 @@ def add_reservation_core_logic( bool: 如果队列已满且需要回到最早开奖的预约直播间等待,返回 True;否则返回 False。 """ start_time = time.time() - + ft = float(item.get("future_ts") or 0.0) content = str(item.get("content") or "") prize_value = float(item.get("prize_value_yuan") or 0.0) room_title = str(item.get("room_title") or "") room_title_normalized = _normalize_room_title_for_matching(room_title) - + # 添加函数入口日志 try: from datetime import datetime @@ -216,24 +216,24 @@ def add_reservation_core_logic( r_prize_value = float(r.get("prize_value_yuan") or 0.0) r_room_title = str(r.get("room_title") or "") r_room_title_normalized = _normalize_room_title_for_matching(r_room_title) - + # 判断是否为同一个预约: # 1. (future_ts, content) 相同,且直播间名字相同(规范化后) # 2. 或者 (future_ts, content) 相同(兼容旧数据,没有直播间名字的情况) # 3. 或者通过相似度匹配:直播间名称相似 + 开奖时间相近 + 奖品价值相同 + 内容核心部分相似 is_same_future_and_content = (r_ft == ft and r_content == content) is_same_room_title = ( - room_title_normalized - and r_room_title_normalized + room_title_normalized + and r_room_title_normalized and room_title_normalized == r_room_title_normalized ) - + # 相似度匹配(处理OCR误差) is_similar_room_title = False is_similar_time = False is_same_prize_value = False is_similar_content = False - + if room_title_normalized and r_room_title_normalized: # 计算直播间名称相似度 room_title_similarity = _calculate_string_similarity( @@ -241,26 +241,26 @@ def add_reservation_core_logic( ) # 如果一个是另一个的子串,或者相似度 >= 0.6,视为相似 is_similar_room_title = ( - room_title_normalized in r_room_title_normalized + room_title_normalized in r_room_title_normalized or r_room_title_normalized in room_title_normalized or room_title_similarity >= 0.6 ) - + # 开奖时间相近(相差60秒内,放宽容忍度以处理OCR误差和实际时间差) time_diff = abs(r_ft - ft) is_similar_time = time_diff <= 60.0 - + # 奖品价值相同(允许0.01的误差) prize_diff = abs(r_prize_value - prize_value) is_same_prize_value = prize_diff < 0.01 - + # 内容核心部分相似 content_core = _extract_content_core(content) r_content_core = _extract_content_core(r_content) if content_core and r_content_core: content_similarity = _calculate_string_similarity(content_core, r_content_core) is_similar_content = content_similarity >= 0.7 - + # 判断是否为同一个预约 if is_same_future_and_content: # 如果 (future_ts, content) 相同 @@ -402,7 +402,7 @@ def add_reservation_core_logic( # 按当前排序规则,队尾是"优先级最低"的记录 del reservations[max_reservations:] queue_full = True - + try: analyser._log_kv( "预约", @@ -440,7 +440,7 @@ def add_reservation_core_logic( ) except Exception: pass - + # 添加函数完成日志 try: elapsed = time.time() - start_time @@ -498,7 +498,7 @@ def cleanup_expired_reservations( try: now_ts_drop = _now_ts() before = len(reservations) - + # 记录被清理的预约详情 dropped_items_detail = [] for r in reservations: @@ -513,7 +513,7 @@ def cleanup_expired_reservations( }) except Exception: pass - + reservations[:] = [ r for r in reservations if float(r.get("future_ts") or 0.0) > now_ts_drop ] @@ -561,7 +561,7 @@ def cleanup_expired_reservations( ) except Exception: pass - + try: elapsed = time.time() - start_time analyser._log_kv( @@ -590,7 +590,7 @@ def handle_queue_full_wait_at_earliest( bool: 如果已回退到最早开奖的预约直播间,返回 True;否则返回 False。 """ start_time = time.time() - + try: analyser._log_kv( "预约", @@ -600,7 +600,7 @@ def handle_queue_full_wait_at_earliest( ) except Exception: pass - + if not reservations: try: analyser._log_kv( @@ -747,7 +747,7 @@ def handle_queue_full_wait_at_earliest( current_room_pos = int(getattr(analyser, "room_pos", room_pos) or room_pos) except Exception: current_room_pos = int(room_pos) - + # 计算位置差 try: target_pos = int(earliest.get("pos_seen") or 0) @@ -774,7 +774,7 @@ def handle_queue_full_wait_at_earliest( analyser.operation.delay(1.5) # 等待页面加载 except Exception: time.sleep(1.5) - + # 队列满后回退到最早直播间,继续执行后续流程 try: analyser._log_kv( @@ -786,7 +786,7 @@ def handle_queue_full_wait_at_earliest( ) except Exception: pass - + # 队列满后立即参与,不设置锁定期(设置为0),使用标志控制 # 这样不会影响切换直播间的逻辑,同时后续的 process_reservation_attend_window 不会因为锁定期而跳过 focus_until_new = 0.0 # 设置为0,表示不设置锁定期,使用标志控制 @@ -815,7 +815,7 @@ def handle_queue_full_wait_at_earliest( write_state_callback() except Exception: pass - + try: elapsed = time.time() - start_time analyser._log_kv( @@ -827,7 +827,7 @@ def handle_queue_full_wait_at_earliest( pass return True - + try: elapsed = time.time() - start_time analyser._log_kv( @@ -860,7 +860,7 @@ def process_reservation_attend_window( 让上层逻辑继续后续处理(例如识别详情并参与)。 """ start_time = time.time() - + # 添加函数入口日志 try: analyser._log_kv( @@ -880,7 +880,7 @@ def process_reservation_attend_window( ) else: pass - + if not reservations: try: analyser._log_kv( @@ -1056,7 +1056,7 @@ def process_reservation_attend_window( time_window_end_ts = ft + max(0.0, poll_before) time_window_end_str = datetime.fromtimestamp(time_window_end_ts).strftime("%Y-%m-%d %H:%M:%S") if time_window_end_ts > 0 else "无效" ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" - + analyser._log_kv( "预约", "[预约] process_reservation_attend_window 详细检查", @@ -1097,7 +1097,7 @@ def process_reservation_attend_window( is_queue_full_immediate_attend_check = True except Exception: pass - + if focus_until > 0 and now_ts < focus_until and abs(focus_until - now_ts) > 1.0 and not is_queue_full_immediate_attend_check: # 锁定期还没结束,检查是否是同一个预约(允许5秒误差) expected_focus_until = ft + max(0.0, poll_before) @@ -1122,14 +1122,14 @@ def process_reservation_attend_window( current_room_pos_check = int(getattr(analyser, "room_pos", room_pos) or room_pos) except Exception: current_room_pos_check = int(room_pos) - + # 计算位置差 try: target_pos_check = int(target.get("pos_seen") or 0) except Exception: target_pos_check = 0 pos_diff_check = current_room_pos_check - target_pos_check - + # 如果已经在目标位置(pos_diff == 0),说明已经在目标直播间,不需要再次回退 # 但是需要检查时间窗口是否到达,如果到达了,应该返回 True 表示需要参与 # 或者如果是队列满立即参与模式,直接返回 True @@ -1142,7 +1142,7 @@ def process_reservation_attend_window( is_queue_full_immediate_attend_pos = True except Exception: pass - + # 检查时间窗口是否到达,或者是队列满立即参与模式 if is_queue_full_immediate_attend_pos or (now_ts >= ft - dynamic_ahead and now_ts <= ft + max(0.0, poll_before)): # 时间窗口已到达或队列满立即参与模式,虽然已在目标位置,但需要参与,返回 True @@ -1173,12 +1173,12 @@ def process_reservation_attend_window( reservation_after_action_pending_ref[0] = True else: reservation_after_action_pending_ref.append(True) - + try: write_state_callback() except Exception: pass - + return True else: # 时间窗口未到达,跳过 @@ -1202,7 +1202,7 @@ def process_reservation_attend_window( if reservation_after_action_pending_ref: reservation_after_action_pending_ref[0] = False return False - + # 如果不在目标位置,继续检查时间窗口 try: analyser._log_kv( @@ -1235,7 +1235,7 @@ def process_reservation_attend_window( pass except Exception: pass - + if not is_queue_full_immediate_attend and now_ts < ft - dynamic_ahead: # 还没到窗口(非队列满立即参与模式) try: @@ -1296,7 +1296,7 @@ def process_reservation_attend_window( current_room_pos = int(getattr(analyser, "room_pos", room_pos) or room_pos) except Exception: current_room_pos = int(room_pos) - + # 计算位置差 try: target_pos = int(target.get("pos_seen") or 0) @@ -1357,7 +1357,7 @@ def process_reservation_attend_window( target_room_title_raw = str(target.get("room_title_raw") or "").strip() target_content = str(target.get("content") or "").strip() target_value = float(target.get("prize_value_yuan") or 0.0) - + try: analyser._log_kv( "预约", @@ -1373,7 +1373,7 @@ def process_reservation_attend_window( ) except Exception: pass - + # 回退成功后,进行回退校验(如果启用了回退校验) verify_ok = True verify_detail = None @@ -1388,7 +1388,7 @@ def process_reservation_attend_window( ) except Exception: pass - + if verify_enabled: try: try: @@ -1401,7 +1401,7 @@ def process_reservation_attend_window( ) except Exception: pass - + from douyin.reservation import douyin_reservation_verify verify_ok, verify_detail = douyin_reservation_verify.validate_back_to_reservation( analyser=analyser, @@ -1409,7 +1409,7 @@ def process_reservation_attend_window( quick=False, max_checks=3, ) - + try: analyser._log_kv( "预约", @@ -1445,7 +1445,7 @@ def process_reservation_attend_window( ) except Exception: pass - + # 校验失败,尝试根据映射表查找正确位置并自动回退 try: if hasattr(analyser, "_find_room_pos_by_title"): @@ -1463,7 +1463,7 @@ def process_reservation_attend_window( ) except Exception: pass - + # 更新目标位置并重新回退 target["pos_seen"] = correct_pos try: @@ -1605,7 +1605,7 @@ def process_reservation_attend_window( ) except Exception: pass - + # 如果回退或校验失败,直接返回 False if not ok: try: @@ -1625,7 +1625,7 @@ def process_reservation_attend_window( except Exception: pass return False - + # 进入锁定期:在开奖附近一段时间内不再切换直播间 focus_until_new = ft + max(0.0, poll_before) if reservation_focus_until_ts_ref: @@ -1637,11 +1637,11 @@ def process_reservation_attend_window( reservation_after_action_pending_ref[0] = True else: reservation_after_action_pending_ref.append(True) - + try: from datetime import datetime ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" - + # 运行日志 analyser._log_kv( "预约", @@ -1656,7 +1656,7 @@ def process_reservation_attend_window( target_content=target_content, target_value_yuan=target_value, ) - + # 行为日志 analyser._log_kv( "行为", @@ -1681,7 +1681,7 @@ def process_reservation_attend_window( write_state_callback() except Exception: pass - + # 添加函数完成日志 try: from datetime import datetime @@ -1718,7 +1718,7 @@ def process_reservation_attend_window( write_state_callback() except Exception: pass - + # 添加函数完成日志 try: from datetime import datetime @@ -2037,4 +2037,4 @@ def record_high_value_reservation( ) except Exception: pass - return False \ No newline at end of file + return False diff --git a/douyin/reservation/douyin_reservation_verify.py b/douyin/reservation/douyin_reservation_verify.py index 3732872..9ffec0c 100644 --- a/douyin/reservation/douyin_reservation_verify.py +++ b/douyin/reservation/douyin_reservation_verify.py @@ -44,11 +44,11 @@ def _compact_text(text: str) -> str: def match_reservation(item: Dict[str, Any], detail: Tuple) -> Tuple[bool, str, Dict[str, Any]]: """校验回退后的福袋详情是否匹配预约。返回 (ok, reason, debug_dict) - + 参数: item: 预约项字典 detail: 福袋详情 tuple (content, time_text, participants, copies, prize_value_yuan, countdown_tuple) - + 返回: (is_match, reason, debug_dict) """ @@ -172,15 +172,15 @@ def validate_back_to_reservation( max_checks: int = 3, ) -> Tuple[bool, Optional[Tuple]]: """回退后校验:只校验直播间标题,不校验福袋。 - + 如果直播间标题不符合,则根据映射表找到正确位置并回退。 - + 参数: analyser: 分析器对象 item: 预约项字典 quick: 是否快速模式(减少检查次数) max_checks: 最大检查次数(未使用,保留兼容性) - + 返回: (is_valid, None) - 如果校验通过返回 True,否则返回 False """ @@ -196,7 +196,7 @@ def validate_back_to_reservation( ) except Exception: pass - + # 若开关关闭,则跳过复杂校验,直接认为回退成功以加速流程 try: verify_enabled = bool(getattr(analyser, "reservation_back_verify_enabled", True)) @@ -229,7 +229,7 @@ def validate_back_to_reservation( except Exception: expected_title = str(item.get("room_title") or "").strip() expected_title_raw = str(item.get("room_title_raw") or "").strip() - + # 使用运行时映射表验证位置信息 target_pos_seen = int(item.get("pos_seen") or 0) try: @@ -248,7 +248,7 @@ def validate_back_to_reservation( ) except Exception: pass - + # 如果映射表中的标题与预期标题匹配,增强验证信心 if expected_title and recorded_title: try: @@ -299,7 +299,7 @@ def validate_back_to_reservation( ) except Exception: pass - + if expected_title: try: y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) @@ -312,14 +312,14 @@ def validate_back_to_reservation( analyser.current_room_title_raw = current_title_raw except Exception: pass - + if current_title: ratio = 0.0 try: ratio = float(difflib.SequenceMatcher(None, expected_title, current_title).ratio()) except Exception: ratio = 0.0 - + try: analyser._log_kv( "预约", @@ -332,7 +332,7 @@ def validate_back_to_reservation( ) except Exception: pass - + # 强不匹配:根据映射表找到正确位置并回退 if current_title and (expected_title not in current_title) and (current_title not in expected_title) and ratio < 0.45: try: @@ -345,7 +345,7 @@ def validate_back_to_reservation( ) except Exception: pass - + # 根据映射表找到正确位置 try: if hasattr(analyser, "_find_room_pos_by_title"): @@ -361,7 +361,7 @@ def validate_back_to_reservation( ) except Exception: pass - + # 回退到正确位置 try: # 更新 item 中的 pos_seen @@ -382,7 +382,7 @@ def validate_back_to_reservation( new_ratio = float(difflib.SequenceMatcher(None, expected_title, new_title).ratio()) except Exception: pass - + if (expected_title in new_title) or (new_title in expected_title) or new_ratio >= 0.45: try: analyser._log_kv( @@ -519,7 +519,7 @@ def validate_back_to_reservation( analyser._log_kv("预约", "回退校验:读取直播间标题失败", error=str(e)) except Exception: pass - + # 如果标题匹配或没有标题,校验通过 try: analyser._log_kv( @@ -529,6 +529,5 @@ def validate_back_to_reservation( ) except Exception: pass - - return True, None + return True, None diff --git a/douyin/stage/__init__.py b/douyin/stage/__init__.py index 86caf1c..efcdd0a 100644 --- a/douyin/stage/__init__.py +++ b/douyin/stage/__init__.py @@ -1,7 +1,3 @@ """ 阶段处理模块 """ - - - - diff --git a/douyin/stage/douyin_stage.py b/douyin/stage/douyin_stage.py index 164c465..cf060b2 100644 --- a/douyin/stage/douyin_stage.py +++ b/douyin/stage/douyin_stage.py @@ -7,9 +7,9 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: """完整抽離自 `douyin_fudai.fudai_analyse._diagnose_stage_from_current_screen`。 日志輸出已從 print 改為 _log_kv,方便結構化查看。 - + 当前模式:优先使用像素检测,OCR检测已暂时关闭用于测试像素检测精准度。 - + 注意:此函数复杂度较高,包含多个检测步骤和条件分支,这是设计上的权衡。 """ import time @@ -38,7 +38,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: except Exception: # 兜底:避免任何日志异常影响主流程 pass - + def _log_separator(title: str = "", char: str = "="): """输出简洁分隔符(仅在 verbose=True 时启用),方便阅读详细日志。""" if not verbose: @@ -69,14 +69,14 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: in_live_room = False live_room_score = 0.0 detection_method = "" - + # 获取像素检测阈值(用于判断置信度是否达到要求) pixel_threshold = float(getattr(analyser, "live_room_match_threshold", 0.8) or 0.8) if pixel_threshold < 0.0: pixel_threshold = 0.0 if pixel_threshold > 1.0: pixel_threshold = 1.0 - + # ========== 第一步:基于同一张截图并行采集所有像素特征(包括直播间图标检测)========== # 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行 # 包括:直播间图标像素检测(多边形区域白色像素检测)以及其他所有阶段检测 @@ -90,18 +90,18 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: else: pixel_state = result pixel_details = {} - + pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000 - + # 从并行检测结果中获取直播间图标检测结果 # 只使用像素检测(多边形区域白色像素检测),白色比例 >= 阈值则判定为在直播间 live_room_pixel_detected = bool(pixel_state.get("has_live_room_pixel", False)) - + # 获取检测分数(白色像素比例) pixel_confidence = 0.0 if "has_live_room_pixel" in pixel_details: pixel_confidence = float(pixel_details["has_live_room_pixel"].get("confidence", 0.0) or 0.0) - + # 如果像素检测通过(白色比例 >= 阈值),判定为在直播间 if live_room_pixel_detected: in_live_room = True @@ -136,11 +136,11 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: except Exception: # 此处为容错:若 pixel_state/pixel_details 格式异常,继续保持未命中 pass - + if in_live_room: total_elapsed = (time.time() - step_start) * 1000 _log("步骤0[检测直播间]-最终结果:在直播间", 检测方法=detection_method, 分数=live_room_score, 总耗时毫秒=total_elapsed) - + # 记录每个检测步骤的详细信息 for key, detail in pixel_details.items(): step_name_map = { @@ -155,13 +155,13 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: step_name = step_name_map.get(key, key) detected = detail.get("detected", False) method = detail.get("method", "unknown") - + log_fields = { "步骤": step_name, "检测结果": "命中" if detected else "未命中", "检测方法": method, } - + # 添加分数信息 if "template_score" in detail and detail["template_score"] is not None: log_fields["分数"] = round(detail["template_score"], 4) @@ -215,7 +215,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: log_fields["任务数量"] = "未获取" try: configured_threshold = float( - getattr(analyser, "fudai_detail_template_threshold", None) or + getattr(analyser, "fudai_detail_template_threshold", None) or getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7 ) log_fields["配置阈值"] = round(configured_threshold, 4) @@ -225,9 +225,9 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: log_fields["原因"] = detail["reason"] if "error" in detail: log_fields["错误"] = detail["error"] - + _log(f"并行检测-{step_name}", **log_fields) - + _log( "像素状态(并行检测完成)", 耗时毫秒=pixel_detection_elapsed, @@ -245,11 +245,11 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: _log("并行检测异常", 耗时毫秒=pixel_detection_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) pixel_state = {} pixel_details = {} - + # ========== 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)========== if not in_live_room: _log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)") - + # 步骤3:检测推荐页面、关注列表、直播列表(OCR标签栏,整合在一起检测) step_start = time.time() remaining_time_before = max_diag_time - (time.time() - diag_start) @@ -292,7 +292,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 文本预览=t_recommend[:50] if t_recommend else "", ) elapsed_recommend = (time.time() - step_start) * 1000 - + # 如果识别到"推荐",直接返回推荐页面 if "推荐" in t_recommend: total_elapsed = (time.time() - diag_start) * 1000 @@ -311,7 +311,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: ) _log_separator(f"最终结果:RECOMMEND_PAGE(推荐页)") return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend) - + # 如果识别到"关注"但没有"推荐",可能是关注列表 if "关注" in t_recommend and "推荐" not in t_recommend: _log("步骤3[OCR关注列表]-检测到关注关键词,准备精确确认", 精确区域="(658,147)-(765,194)") @@ -349,7 +349,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: except Exception as e: import traceback _log("步骤3[OCR关注列表]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc()) - + elapsed_follow = (time.time() - step_start_follow) * 1000 if "关注" in t_follow: total_elapsed = (time.time() - diag_start) * 1000 @@ -372,7 +372,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: ) _log_separator(f"最终结果:FOLLOW_LIST(关注列表)") return "FOLLOW_LIST", "标题='{}'".format(t_follow) - + # 如果识别到"正在直播"标签,判定为直播列表 if "正在直播" in t_recommend or ("直播" in t_recommend and "推荐" not in t_recommend and "关注" not in t_recommend): _log("步骤3[OCR直播列表]-检测到直播关键词,准备精确确认", 精确区域="(650,145)-(800,195)") @@ -412,7 +412,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: except Exception as e: import traceback _log("步骤3[OCR直播列表]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc()) - + elapsed_list = (time.time() - step_start_list) * 1000 if "正在直播" in t_list: total_elapsed = (time.time() - diag_start) * 1000 @@ -431,13 +431,13 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: ) _log_separator(f"最终结果:LIVE_LIST(直播列表)") return "LIVE_LIST", "标题='{}'".format(t_list) - + # 记录诊断时看到的"关注页标题" try: analyser._last_follow_list_title_text = str(t_follow or "").strip() except Exception: analyser._last_follow_list_title_text = "" - + elapsed_total = (time.time() - step_start) * 1000 if elapsed_total > max_step_time * 1000: _log("步骤3[OCR推荐页/关注列表/直播列表]-步骤超时", 耗时毫秒=elapsed_total, 阈值毫秒=max_step_time * 1000) @@ -457,7 +457,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 异常信息=str(e), 堆栈=traceback.format_exc(), ) - + # 如果不在直播间且OCR也未识别到特定页面,默认返回在直播间 total_elapsed = (time.time() - diag_start) * 1000 _log_summary( @@ -468,14 +468,14 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: ) _log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)") return "IN_LIVE_ROOM", "不在直播间且未识别到特定页面,默认判定为在直播间" - + # ========== 在直播间:继续执行像素检测结果处理 ========== _log_separator("在直播间,继续执行像素检测结果处理") _log("在直播间,继续执行像素检测结果处理") # ========== 优先使用像素检测结果判断阶段(按优先级顺序)========== # 根据像素检测结果,按优先级返回阶段 - + # 优先级1:抽奖结果弹窗(大片红色+我知道了) if pixel_state.get("has_lucky_draw_result", False): _log_separator("步骤1:检测抽奖结果弹窗") @@ -483,7 +483,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: step_result_start = time.time() remaining_time_before = max_diag_time - (time.time() - diag_start) _log("步骤1[检测抽奖结果弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到抽奖结果弹窗,OCR兜底确认") - + result_verified = False try: # 检测抽奖结果文字区域 (300, 600)-(800, 800) - 扩大区域以覆盖"没有抽中福袋"文字 @@ -516,7 +516,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 文本长度=len(result_text), 文本预览=result_text[:50] if result_text else "", ) - + # 检测"我知道了"按钮区域 (181, 1261)-(890, 1389) - 与像素检测区域一致 if result_text and ("没有抽中" in result_text or "抽中福袋" in result_text): if time.time() - step_result_start < max_step_time: @@ -536,7 +536,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 文本长度=len(confirm_text), 文本预览=confirm_text[:50] if confirm_text else "", ) - + if confirm_text and ("我知道了" in confirm_text or "领取并使用" in confirm_text): result_verified = True else: @@ -550,7 +550,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: _log("步骤1[检测抽奖结果弹窗]-异常", 耗时毫秒=result_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) # OCR异常时,不判定为抽奖结果弹窗(需要OCR确认) _log("步骤1[检测抽奖结果弹窗]-OCR异常,不判定为抽奖结果弹窗", 说明="需要OCR确认才能判定") - + if result_verified: total_elapsed = (time.time() - diag_start) * 1000 result_elapsed = (time.time() - step_result_start) * 1000 @@ -563,14 +563,14 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: ) _log_separator(f"最终结果:FUDai_RESULT(抽奖结果弹窗)") return "FUDai_RESULT", "像素检测+OCR确认(抽奖结果弹窗)" - + # 优先级1.5:购物红包弹窗检测(保持现有检测方式) if pixel_state.get("has_redpacket_bg", False): _log_separator("步骤1.5:检测购物红包弹窗") step_redpacket_start = time.time() remaining_time_before = max_diag_time - (time.time() - diag_start) _log("步骤1.5[检测购物红包弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到购物红包背景") - + redpacket_detected = False try: if time.time() - step_redpacket_start < max_step_time: @@ -590,7 +590,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 文本长度=len(redpacket_text), 文本预览=redpacket_text[:50] if redpacket_text else "", ) - + # 检查是否包含购物红包关键词 redpacket_keywords = ("购物红包", "邀你抢", "抢红包") if redpacket_text and any(kw in redpacket_text for kw in redpacket_keywords): @@ -603,7 +603,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: _log("步骤1.5[检测购物红包弹窗]-异常", 耗时毫秒=redpacket_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) # OCR异常时,不判定为购物红包弹窗(以OCR为准) _log("步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗", 说明="需要OCR确认才能判定") - + if redpacket_detected: total_elapsed = (time.time() - diag_start) * 1000 redpacket_elapsed = (time.time() - step_redpacket_start) * 1000 @@ -615,7 +615,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 红包检测耗时毫秒=redpacket_elapsed, ) return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(购物红包弹窗)" - + # 优先级2:优惠券弹窗检测(使用参与按钮区域,检测"开心收下") # 优惠券弹窗和参与福袋按钮在同一个位置,需要通过OCR区分 # ========== 步骤2:OCR检测(已暂时禁用)========== @@ -632,7 +632,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: # 注意:即使 has_fudai_detail 为 False,pixel_details 中可能仍然有任务数量信息 detail_detected = bool(pixel_state.get("has_fudai_detail", False)) detail_task_count = None - + # 尝试从 pixel_details 中获取任务数量(无论 has_fudai_detail 是否为 True) if "has_fudai_detail" in pixel_details: detail_task_count = pixel_details["has_fudai_detail"].get("task_count") @@ -681,7 +681,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: ) except Exception: pass - + # 如果并行检测到福袋详情页,直接返回 if detail_detected: total_elapsed = (time.time() - diag_start) * 1000 @@ -694,7 +694,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: ) _log_separator(f"最终结果:FUDai_DETAIL(福袋详情页)") return "FUDai_DETAIL", f"任务数量检测确认(任务数量={detail_task_count})" - + # 额外检测:在指定区域检测"邀你抢红包"文字(用于检测红包/福袋详情页) # 区域:(238,454) 到 (847,545) - 基准坐标(1080x2400) # 优化:当模板匹配分数很低(<0.4)时,说明明显不在福袋详情页,跳过OCR检测以节省时间 @@ -704,7 +704,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: # 获取模板匹配分数(如果存在),用于判断是否跳过OCR template_match_score = float(getattr(analyser, "_last_template_match_score", 0.0) or 0.0) should_skip_redpacket_ocr = (not detail_detected and template_match_score > 0 and template_match_score < template_match_score_threshold) - + if should_skip_redpacket_ocr: _log( "步骤1.5[OCR检测邀你抢红包]-跳过(模板匹配分数过低)", @@ -712,7 +712,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 阈值=template_match_score_threshold, 说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间" ) - + if not detail_detected and enable_invite_redpacket_ocr and not should_skip_redpacket_ocr: step_ocr_redpacket_start = time.time() remaining_time_before = max_diag_time - (time.time() - diag_start) @@ -721,7 +721,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: if remaining_time_before > ocr_max_step_time: try: _log("步骤1.5[OCR检测邀你抢红包]-开始", 剩余时间秒=remaining_time_before, 说明="在指定区域检测邀你抢红包文字") - + if time.time() - step_ocr_redpacket_start < ocr_max_step_time: cut_start = time.time() y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) @@ -732,28 +732,28 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: import path_config import os from PIL import Image - + pic_path = path_config.get_screenshot_path() if os.path.exists(pic_path): pic = Image.open(pic_path) pic.load() pic_rgb = pic.convert("RGB") - + width, height = pic_rgb.size rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - + x1_base, y1_base, x2_base, y2_base = 238, 454, 847, 545 x1 = int(x1_base * width / rx) y1 = int((y1_base + y_pianyi) * height / ry) x2 = int(x2_base * width / rx) y2 = int((y2_base + y_pianyi) * height / ry) - + x1 = max(0, min(x1, width - 1)) y1 = max(0, min(y1, height - 1)) x2 = max(0, min(x2, width - 1)) y2 = max(0, min(y2, height - 1)) - + if x1 < x2 and y1 < y2: debug_path = douyin_screenshot_manager.save_debug_image( pic_rgb, @@ -774,11 +774,11 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: pass except Exception: pass - + analyser.cut_pic(238, 454, 847, 545, "", "阶段诊断邀你抢红包区域", y_pianyi) cut_elapsed = (time.time() - cut_start) * 1000 _log("步骤1.5[OCR检测邀你抢红包]-截图完成", 耗时毫秒=cut_elapsed) - + if time.time() - step_ocr_redpacket_start < ocr_max_step_time: ocr_start = time.time() name_red0 = preprocess_for_ocr(analyser, "阶段诊断邀你抢红包区域") @@ -790,7 +790,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 文本长度=len(ocr_text), 文本预览=ocr_text[:50] if ocr_text else "", ) - + # 如果模式0未识别到,尝试模式1 enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False)) if enable_ocr_mode1 and (not ocr_text or not any(kw in ocr_text for kw in ("邀你抢", "抢红包", "抢手气"))): @@ -802,7 +802,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 文本长度=len(ocr_text), 文本预览=ocr_text[:50] if ocr_text else "", ) - + # 检测是否包含"邀你抢红包"相关关键词(支持变体) redpacket_keywords = ("邀你抢红包", "邀你抢手气红包", "邀你抢", "抢红包", "抢手气") if ocr_text and any(kw in ocr_text for kw in redpacket_keywords): @@ -833,15 +833,15 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: # 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要OCR再次确认 # 因为有些直播间背景颜色可能与弹窗颜色相似,导致误判 has_suspicious_popup_pixel = ( - pixel_state.get("has_coupon_bg", False) or + pixel_state.get("has_coupon_bg", False) or pixel_state.get("has_redpacket_bg", False) ) - + if has_suspicious_popup_pixel: step_ocr_verify_start = time.time() remaining_time_before = max_diag_time - (time.time() - diag_start) _log("步骤3[OCR确认弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认") - + # 检测优惠券弹窗(使用参与按钮区域,检测"开心收下") if pixel_state.get("has_coupon_bg", False): coupon_verified = False @@ -890,13 +890,13 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 文本长度=len(coupon_text), 文本预览=coupon_text[:50] if coupon_text else "", ) - + if coupon_text and "开心收下" in coupon_text: coupon_verified = True except Exception as e: coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000 _log("步骤3[OCR确认弹窗]-优惠券异常", 耗时毫秒=coupon_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) - + if coupon_verified: total_elapsed = (time.time() - diag_start) * 1000 coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000 @@ -908,7 +908,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 优惠券检测耗时毫秒=coupon_elapsed, ) return "COUPON_POPUP", "OCR确认(开心收下)" - + # 检测购物红包弹窗 if pixel_state.get("has_redpacket_bg", False): redpacket_verified = False @@ -930,14 +930,14 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 文本长度=len(redpacket_text), 文本预览=redpacket_text[:50] if redpacket_text else "", ) - + redpacket_keywords = ("购物红包", "邀你抢", "抢红包") if redpacket_text and any(kw in redpacket_text for kw in redpacket_keywords): redpacket_verified = True except Exception as e: redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000 _log("步骤3[OCR确认弹窗]-购物红包异常", 耗时毫秒=redpacket_elapsed, 异常类型=type(e).__name__, 异常信息=str(e)) - + if redpacket_verified: total_elapsed = (time.time() - diag_start) * 1000 redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000 @@ -949,11 +949,11 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 红包检测耗时毫秒=redpacket_elapsed, ) return "SHOPPING_REDPACKET_POPUP", "OCR确认(购物红包弹窗)" - + # OCR确认后仍未匹配到弹窗,说明是直播间背景颜色误判 ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000 _log("步骤3[OCR确认弹窗]-未匹配到弹窗", 耗时毫秒=ocr_verify_elapsed, 说明="OCR确认后未匹配,判定为直播间背景颜色") - + # 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段 if in_live_room: total_elapsed = (time.time() - diag_start) * 1000 @@ -968,7 +968,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: ) _log_separator(f"最终结果:IN_LIVE_ROOM(在直播间)") return "IN_LIVE_ROOM", f"识别到在直播间({detection_method}),其他阶段未识别" - + # 如果不在直播间,默认返回:在直播间内(IN_LIVE_ROOM) # 这种情况可能是检测失败,但为了流程继续,默认返回在直播间 total_elapsed = (time.time() - diag_start) * 1000 @@ -979,4 +979,4 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 原因="像素检测未命中,默认直播间", 总耗时毫秒=total_elapsed, ) - _log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)") \ No newline at end of file + _log_separator(f"最终结果:IN_LIVE_ROOM(默认直播间)") diff --git a/douyin/stage/douyin_stage_handler.py b/douyin/stage/douyin_stage_handler.py index 2618c71..07e72fd 100644 --- a/douyin/stage/douyin_stage_handler.py +++ b/douyin/stage/douyin_stage_handler.py @@ -10,15 +10,13 @@ from __future__ import annotations - 直播间图标检测 """ +# pylint: disable=E1101 + import time -from typing import Any, Tuple, List, Optional +from typing import Any, Tuple, List from douyin.stage import douyin_stage -from douyin.fudai import douyin_fudai_detail -from douyin.fudai import douyin_fudai_core import douyin.core.douyin_flow_control as douyin_flow_control -from douyin.reservation import douyin_reservation_logic -from douyin.handlers import douyin_swipe_handler class StageHandler: @@ -100,7 +98,7 @@ class StageHandler: except Exception: # 回退到旧路径(向后兼容) assets_dir = os.path.join(base_dir, "assets") - + # 使用统一的截图路径配置 try: import path_config @@ -135,7 +133,7 @@ class StageHandler: screenshot_path = alt_path except Exception: pass - + # 如果仍然不存在,记录错误 if not os.path.exists(screenshot_path): try: @@ -178,26 +176,26 @@ class StageHandler: # 第一步:裁剪右上角图标区域(使用固定坐标,基于1080x2400基准分辨率) # 直播间图标区域:(972, 147) 到 (1047, 216) - 与像素检测区域一致 ih, iw = img.shape[:2] - + # 基准分辨率 base_width = 1080 base_height = 2400 - + # 固定坐标(基于1080x2400) base_x1 = 972 base_y1 = 147 base_x2 = 1047 base_y2 = 216 - + # 缩放坐标到实际分辨率 scale_x = iw / base_width scale_y = ih / base_height - + roi_x1 = max(0, int(base_x1 * scale_x)) roi_y1 = max(0, int(base_y1 * scale_y)) roi_x2 = min(iw, int(base_x2 * scale_x)) roi_y2 = min(ih, int(base_y2 * scale_y)) - + # 确保区域有效 if roi_x1 >= roi_x2 or roi_y1 >= roi_y2: try: @@ -209,7 +207,7 @@ class StageHandler: except Exception: pass return False, 0.0 - + roi = img[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index] # 同步裁剪彩色 ROI,用于后续颜色特征检测(白色比例等) @@ -370,10 +368,9 @@ class StageHandler: # 方法1:固定阈值二值化(针对白色x和深灰背景,阈值约160-180) # 先尝试多个阈值,选择最佳 best_binary_score = 0.0 - best_binary_thresh = 160 roi_binary_fixed = None tpl_binary_fixed = None - + for thresh_val in [140, 160, 180, 200]: try: _, roi_bin = cv2.threshold(roi_img, thresh_val, 255, cv2.THRESH_BINARY) # type: ignore[attr-defined] @@ -383,12 +380,11 @@ class StageHandler: _min_val, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res_test) # type: ignore[attr-defined] if max_val > best_binary_score: best_binary_score = max_val - best_binary_thresh = thresh_val roi_binary_fixed = roi_bin tpl_binary_fixed = tpl_bin except: continue - + # 方法2:自适应二值化(调整参数,blockSize使用较小值以提高精度) roi_binary_adaptive = cv2.adaptiveThreshold( # type: ignore[attr-defined] roi_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2 # type: ignore[attr-defined] @@ -396,24 +392,24 @@ class StageHandler: tpl_binary_adaptive = cv2.adaptiveThreshold( # type: ignore[attr-defined] tpl, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2 # type: ignore[attr-defined] ) - + # 方法3:Otsu二值化(全局阈值) _, roi_binary_otsu = cv2.threshold(roi_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # type: ignore[attr-defined] _, tpl_binary_otsu = cv2.threshold(tpl, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # type: ignore[attr-defined] - + # 方法4:边缘检测(Canny,针对白色x和深灰背景,调整参数) roi_edges = cv2.Canny(roi_img, 50, 150) # type: ignore[attr-defined] tpl_edges = cv2.Canny(tpl, 50, 150) # type: ignore[attr-defined] - + # 方法5:边缘检测(更激进的参数,检测更多边缘) roi_edges_aggressive = cv2.Canny(roi_img, 30, 80) # type: ignore[attr-defined] tpl_edges_aggressive = cv2.Canny(tpl, 30, 80) # type: ignore[attr-defined] - + # 方法6:形态学处理(去除噪声,增强边缘) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # type: ignore[attr-defined] roi_edges_morph = cv2.morphologyEx(roi_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined] tpl_edges_morph = cv2.morphologyEx(tpl_edges, cv2.MORPH_CLOSE, kernel) # type: ignore[attr-defined] - + # 使用固定阈值二值化图像作为主要匹配图像(针对白色x和深灰背景优化) if roi_binary_fixed is not None and tpl_binary_fixed is not None: roi_img_enhanced = roi_binary_fixed @@ -422,7 +418,7 @@ class StageHandler: # 回退到自适应二值化 roi_img_enhanced = roi_binary_adaptive tpl_enhanced = tpl_binary_adaptive - + # 保存所有预处理图像用于多方法匹配 roi_binary_adaptive_backup = roi_binary_adaptive tpl_binary_adaptive_backup = tpl_binary_adaptive @@ -434,7 +430,7 @@ class StageHandler: tpl_edges_aggressive_backup = tpl_edges_aggressive roi_edges_morph_backup = roi_edges_morph tpl_edges_morph_backup = tpl_edges_morph - + # 方法7:强对比度增强(针对实际测试中表现较好的配置) roi_contrast = cv2.convertScaleAbs(roi_img_enhanced, alpha=2.0, beta=30) # type: ignore[attr-defined] tpl_contrast = cv2.convertScaleAbs(tpl_enhanced, alpha=2.0, beta=30) # type: ignore[attr-defined] @@ -442,7 +438,7 @@ class StageHandler: tpl_contrast_backup = tpl_contrast roi_edges_morph_backup = roi_edges_morph tpl_edges_morph_backup = tpl_edges_morph - + use_edges = True except Exception: roi_img_enhanced = roi_img @@ -738,7 +734,6 @@ class StageHandler: join_ahead = float(getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120) poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0) time_window_start_ts = ft - join_ahead - time_window_end_ts = ft + max(0.0, poll_before) if now_ts < time_window_start_ts: try: analyser._log_kv( # type: ignore[attr-defined] diff --git a/douyin/utils/__init__.py b/douyin/utils/__init__.py index 0cc2ca0..1c64f0a 100644 --- a/douyin/utils/__init__.py +++ b/douyin/utils/__init__.py @@ -1,7 +1,3 @@ """ 工具函数模块 """ - - - - diff --git a/douyin/utils/douyin_config.py b/douyin/utils/douyin_config.py index 2821a08..48d720a 100644 --- a/douyin/utils/douyin_config.py +++ b/douyin/utils/douyin_config.py @@ -14,13 +14,13 @@ from typing import Any, Optional class ConfigManager: """配置管理器类""" - + @staticmethod # type: ignore[misc] def load_config_from_file( analyser: Any, config_path: Optional[str] = None ) -> None: """从配置文件加载配置并设置到 analyser 对象 - + 参数: analyser: fudai_analyse 实例 config_path: 配置文件路径,如果为 None 则使用 analyser.config_path @@ -33,71 +33,71 @@ class ConfigManager: import path_config default_config_path = path_config.get_config_path() config_path = getattr(analyser, "config_path", default_config_path) - + # 如果 config_path 仍然为 None,直接返回(使用默认值) if config_path is None: return - + # 如果配置文件不存在,直接返回(使用默认值) if not os.path.exists(config_path): return - + try: with open(config_path, "r", encoding="utf-8") as f: config = json.load(f) except (json.JSONDecodeError, IOError, OSError): # 如果 JSON 解析失败或文件读取失败,直接返回(使用默认值) return - + # 保存 needswitch 的原始值(如果已通过命令行设置,则保留) original_needswitch = getattr(analyser, "needswitch", None) - + # 加载基本配置 if "min_prize_value_yuan" in config: analyser.min_prize_value_yuan = float(config["min_prize_value_yuan"] or 0.0) - + if "min_participants" in config: analyser.min_participants = int(config["min_participants"] or 0) - + if "max_participants" in config: analyser.max_participants = int(config["max_participants"] or 0) - + if "skip_if_countdown_gt_seconds" in config: analyser.skip_if_countdown_gt_seconds = int( config["skip_if_countdown_gt_seconds"] or 900 ) - + if "skip_if_countdown_lt_seconds" in config: analyser.skip_if_countdown_lt_seconds = int( config["skip_if_countdown_lt_seconds"] or 0 ) - + if "fudai_icon_max_wait_seconds" in config: analyser.fudai_icon_max_wait_seconds = float( config["fudai_icon_max_wait_seconds"] or 5.0 ) - + if "fudai_icon_retry_delay_seconds" in config: analyser.fudai_icon_retry_delay_seconds = float( config["fudai_icon_retry_delay_seconds"] or 0.6 ) - + # 高价值福袋配置 if "high_value_fudai_enabled" in config: analyser.high_value_fudai_enabled = bool( config["high_value_fudai_enabled"] ) - + if "high_value_fudai_threshold_yuan" in config: analyser.high_value_fudai_threshold_yuan = float( config["high_value_fudai_threshold_yuan"] or 500.0 ) - + if "high_value_fudai_max_reservations" in config: max_reservations = int(config["high_value_fudai_max_reservations"] or 3) # 限制最大预约数量为50 analyser.high_value_fudai_max_reservations = min(max_reservations, 50) - + # needswitch 配置(如果已通过命令行设置,则保留原值) if original_needswitch is not None: # 保留命令行参数值(优先级最高) @@ -108,31 +108,31 @@ class ConfigManager: else: # 如果配置文件中没有,使用默认值 True analyser.needswitch = True - + # 列表配置 if "contains_not_want" in config: analyser.contains_not_want = list(config["contains_not_want"] or []) - + if "contains_want" in config: analyser.contains_want = list(config["contains_want"] or []) - + # 阈值配置(限制在 0.0~1.0 范围内) if "lucky_draw_red_ratio_threshold" in config: threshold = float(config["lucky_draw_red_ratio_threshold"] or 0.9) analyser.lucky_draw_red_ratio_threshold = max(0.0, min(1.0, threshold)) - + if "coupon_template_match_threshold" in config: threshold = float(config["coupon_template_match_threshold"] or 0.75) analyser.coupon_template_match_threshold = max(0.0, min(1.0, threshold)) - + if "attend_button_red_ratio_threshold" in config: threshold = float(config["attend_button_red_ratio_threshold"] or 0.25) analyser.attend_button_red_ratio_threshold = max(0.0, min(1.0, threshold)) - + if "fansclub_join_red_ratio_threshold" in config: threshold = float(config["fansclub_join_red_ratio_threshold"] or 0.25) analyser.fansclub_join_red_ratio_threshold = max(0.0, min(1.0, threshold)) - + # 粉丝团等待/点击延迟配置 if "fansclub_click_delay" in config: analyser.fansclub_click_delay = float(config["fansclub_click_delay"] or 0.6) @@ -152,116 +152,116 @@ class ConfigManager: ) else: analyser.fansclub_manual_wait_seconds = 3.0 - + # 其他配置项(根据实际需要添加) if "no_attend_timeout_minutes" in config: analyser._no_attend_timeout_minutes = float( config["no_attend_timeout_minutes"] or 30.0 ) - + if "auto_join_fansclub" in config: analyser.auto_join_fansclub = bool(config["auto_join_fansclub"]) - + if "fansclub_fail_action" in config: analyser.fansclub_fail_action = str(config["fansclub_fail_action"] or "stay") - + if "high_value_fudai_join_ahead_seconds" in config: analyser.high_value_fudai_join_ahead_seconds = int( config["high_value_fudai_join_ahead_seconds"] or 120 ) - + if "high_value_fudai_max_swipe_back" in config: analyser.high_value_fudai_max_swipe_back = int( config["high_value_fudai_max_swipe_back"] or 35 ) - + if "high_value_fudai_after_action" in config: analyser.high_value_fudai_after_action = str( config["high_value_fudai_after_action"] or "continue" ) - + if "high_value_fudai_after_stay_seconds" in config: analyser.high_value_fudai_after_stay_seconds = int( config["high_value_fudai_after_stay_seconds"] or 120 ) - + if "reservation_back_verify_enabled" in config: analyser.reservation_back_verify_enabled = bool( config["reservation_back_verify_enabled"] ) - + if "record_room_title_mapping_enabled" in config: analyser.record_room_title_mapping_enabled = bool( config["record_room_title_mapping_enabled"] ) - + if "reservation_back_swipe_delay" in config: analyser.reservation_back_swipe_delay = float( config["reservation_back_swipe_delay"] or 0.6 ) - + if "reservation_preempt_min_value_yuan" in config: analyser.reservation_preempt_min_value_yuan = float( config["reservation_preempt_min_value_yuan"] or 0.0 ) - + if "poll_before_open_seconds" in config: analyser.poll_before_open_seconds = int( config["poll_before_open_seconds"] or 10 ) - + if "reset_after_swipes_enabled" in config: analyser.reset_after_swipes_enabled = bool( config["reset_after_swipes_enabled"] ) - + if "reset_after_swipes" in config: analyser.reset_after_swipes = int(config["reset_after_swipes"] or 10) - + if "fudai_click_wait_seconds" in config: analyser.fudai_click_wait_seconds = float( - config["fudai_click_wait_seconds"] or 2.0 + config["fudai_click_wait_seconds"] or 1.0 ) - + if "switch_room_wait_after_stage_diag_seconds" in config: analyser.switch_room_wait_after_stage_diag_seconds = float( config["switch_room_wait_after_stage_diag_seconds"] or 7.0 ) - + if "swipe_duration_ms" in config: analyser.swipe_duration_ms = int(config["swipe_duration_ms"] or 600) - + if "fudai_finder_optimized_enabled" in config: analyser.fudai_finder_optimized_enabled = bool( config["fudai_finder_optimized_enabled"] ) - + if "fudai_click_verify_enabled" in config: analyser.fudai_click_verify_enabled = bool( config["fudai_click_verify_enabled"] ) - + if "fudai_find_max_retries" in config: analyser.fudai_find_max_retries = int(config["fudai_find_max_retries"] or 3) - + if "screenshot_diagnose_min_interval_seconds" in config: analyser.screenshot_diagnose_min_interval_seconds = float( config["screenshot_diagnose_min_interval_seconds"] or 8.0 ) - + if "live_room_match_threshold" in config: threshold = float(config["live_room_match_threshold"] or 0.8) analyser.live_room_match_threshold = max(0.0, min(1.0, threshold)) - + if "fudai_template_match_enabled" in config: analyser.fudai_template_match_enabled = bool( config["fudai_template_match_enabled"] ) - + if "fudai_template_match_threshold" in config: threshold = float(config["fudai_template_match_threshold"] or 0.7) analyser.fudai_template_match_threshold = max(0.0, min(1.0, threshold)) - + if "y_pianyi" in config: analyser.y_pianyi = int(config["y_pianyi"] or 0) diff --git a/douyin/utils/douyin_helpers.py b/douyin/utils/douyin_helpers.py index d89e3dc..5af8d51 100644 --- a/douyin/utils/douyin_helpers.py +++ b/douyin/utils/douyin_helpers.py @@ -210,10 +210,10 @@ class HelperFunctions: """保存误识别文本到记录文件""" false_positive_file = HelperFunctions._get_false_positive_file_path() os.makedirs(os.path.dirname(false_positive_file), exist_ok=True) - + false_positives = HelperFunctions._load_false_positives() false_positives.add(text.strip()) - + try: with open(false_positive_file, "w", encoding="utf-8") as f: json.dump({"false_positives": list(false_positives)}, f, ensure_ascii=False, indent=2) @@ -395,4 +395,4 @@ class HelperFunctions: tag, f"{msg} - 异常: {type(e).__name__}" ) except Exception: - pass \ No newline at end of file + pass diff --git a/douyin/utils/douyin_text_utils.py b/douyin/utils/douyin_text_utils.py index 7a0b2cb..6791888 100644 --- a/douyin/utils/douyin_text_utils.py +++ b/douyin/utils/douyin_text_utils.py @@ -93,61 +93,3 @@ def extract_participants_count(text: Optional[str]) -> int: return 0 # 简化策略:返回最大值(通常人数是文本里最大的数字) return max(nums) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/douyin/utils/douyin_utils.py b/douyin/utils/douyin_utils.py index 87c7ac5..92f5b75 100644 --- a/douyin/utils/douyin_utils.py +++ b/douyin/utils/douyin_utils.py @@ -1,6 +1,6 @@ import os import re -from typing import Iterable +import unicodedata def normalize_countdown_text(text: str) -> str: @@ -143,146 +143,40 @@ def extract_prize_value_yuan(text: str) -> float: """从 OCR 文本中抽取奖品价值金额(元),抽离自 douyin_fudai.py。""" if not text: return 0.0 - t = re.sub(r"\s+", "", str(text)) - # 先去掉倒计时类数字,避免把 00:31 解析成 31 元 - t = re.sub(r"\b\d{1,2}[::]\d{2}\b", "", t) - - # 优先匹配带币种符号/单位的金额:参考价值¥199 / ¥199.9 / ¥199 / 199元 - # 先尝试匹配带¥符号的金额(¥符号可能被OCR识别成各种形式) - currency_matches = re.findall(r"[¥¥\u00A5\uFFE5](\d+(?:\.\d+)?)", t) - yuan_matches = re.findall(r"(\d+(?:\.\d+)?)元", t) - tagged: Iterable[str] = list(currency_matches) + list(yuan_matches) - if tagged: - vals: list[float] = [] - for n in tagged: - try: - vals.append(float(n)) - except ValueError: - pass - if vals: - return max(vals) - - # 清理¥符号:OCR可能把¥符号识别成数字或其他字符,先清理掉 - # ¥符号的Unicode编码是 \u00A5,全角¥是 \uFFE5 - # 使用更精确的匹配:只在数字前清理¥符号 - t = re.sub(r"[¥¥\u00A5\uFFE5]\s*(\d)", r"\1", t) # 清理¥符号(保留后面的数字) - # 处理¥被识别成Y/y的情况:Y/y后跟数字 - t = re.sub(r"[Yy]\s*(\d)", r"\1", t) # 清理Y/y(保留后面的数字) - - # 注意:不在这里处理¥被识别成8的情况,因为真正的8199元是合理的 - # 将在后续提取整数时,根据上下文更智能地判断 - - # 清理后再次尝试匹配"元"后缀 - yuan_matches_after_clean = re.findall(r"(\d+(?:\.\d+)?)元", t) - if yuan_matches_after_clean: - vals_after_clean: list[float] = [] - for n in yuan_matches_after_clean: - try: - vals_after_clean.append(float(n)) - except ValueError: - pass - if vals_after_clean: - return max(vals_after_clean) + s = unicodedata.normalize("NFKC", str(text)) + values: list[float] = [] - # 去掉常见干扰:份数/参与人数 - t = re.sub(r"共\d+份", "", t) - t = re.sub(r"\d+人已参与", "", t) - - # 退化:抓小数 - decimals = re.findall(r"\d+\.\d+", t) - if decimals: - vals = [] - for n in decimals: - try: - val = float(n) - # 过滤掉明显不合理的值(比如小数点前有多个数字,可能是误识别) - if 0.01 <= val <= 99999.99: - vals.append(val) - except ValueError: - pass - if vals: - return max(vals) - - # 再退化:抓整数 - ints = re.findall(r"\d+", t) - if ints: - vals = [] - for n in ints: - try: - v = int(n) - # 处理¥被识别成8的情况:需要更智能的判断,避免误识别真正的8199元 - # 只在以下情况才考虑去掉第一个8: - # 1. 数字非常大(>=50000),且去掉8后的数字在合理范围内(100-9999) - # 2. 文本中没有明确的单位(如"元"),说明可能是纯数字OCR误识别 - # 3. 如果数字本身就在合理范围内(1-99999),优先保留原值(可能是真正的8199元) - if len(n) >= 5 and n.startswith("8"): # 5位以上数字才考虑 - corrected = int(n[1:]) - # 只在原数字非常大(>=50000)且去掉8后数字在合理范围(100-9999)时,才考虑修正 - # 这样可以避免把真正的8199、81999等误识别 - if v >= 50000 and 100 <= corrected <= 9999: - # 检查文本中是否有"元"等明确单位 - has_yuan_unit = "元" in t - # 如果没有明确单位,更可能是误识别(¥被识别成8) - if not has_yuan_unit: - vals.append(float(corrected)) - else: - # 有明确单位,保留原值(可能是真正的价值,如81999元) - if 1 <= v <= 99999: - vals.append(float(v)) - elif 1 <= v <= 99999: - # 数字在合理范围内,保留原值(包括8199、81999等) - vals.append(float(v)) - elif 1 <= v <= 99999: - vals.append(float(v)) - except ValueError: + for idx, ch in enumerate(s): + if ch != "¥": + continue + j = idx + 1 + while j < len(s) and s[j].isspace(): + j += 1 + start = j + has_digit = False + dot_seen = False + while j < len(s): + cj = s[j] + if cj.isdigit(): + has_digit = True + j += 1 continue - if vals: - return max(vals) + if cj == ".": + if dot_seen: + break + dot_seen = True + j += 1 + continue + if cj == ",": + j += 1 + continue + break + if not has_digit: + continue + num_text = s[start:j].replace(",", "") + try: + values.append(float(num_text)) + except ValueError: + continue - return 0.0 - - -def parse_countdown_seconds(text: str) -> int: - """ - 将福袋倒计时文本解析为总秒数。 - - 这是对 ``normalize_countdown_text`` 的简单封装,方便在其它模块或测试中直接得到秒数。 - - 示例:: - - >>> parse_countdown_seconds("5分30秒") - 330 - >>> parse_countdown_seconds("30秒") - 30 - >>> parse_countdown_seconds("5:00") - 300 - """ - norm = normalize_countdown_text(text) - if not norm: - return 0 - # 期望格式 "mm:ss" 或 "mm:ss后开奖" - m = re.search(r"(\d{1,3}):(\d{1,2})", norm) - if not m: - return 0 - try: - mm = int(m.group(1)) - ss = int(m.group(2)) - except ValueError: - return 0 - return mm * 60 + ss - - -class Tee: - """将 print 输出同时写入多个文件对象的简单工具类。""" - - def __init__(self, *files): - self.files = files - - def write(self, obj): - for f in self.files: - f.write(obj) - f.flush() - - def flush(self): - for f in self.files: - f.flush() + return max(values) if values else 0.0 diff --git a/douyin/utils/ocr_preprocess.py b/douyin/utils/ocr_preprocess.py index bc1d575..8bd314f 100644 --- a/douyin/utils/ocr_preprocess.py +++ b/douyin/utils/ocr_preprocess.py @@ -50,21 +50,3 @@ def preprocess_for_ocr(analyser: Any, cut_pic_name: str) -> str: return cut_pic_name except Exception: return cut_pic_name - - - - - - - - - - - - - - - - - - diff --git a/douyin_guaji.code-workspace b/douyin_guaji.code-workspace index dbe2735..0024223 100644 --- a/douyin_guaji.code-workspace +++ b/douyin_guaji.code-workspace @@ -16,6 +16,45 @@ "markdown.preview.fontSize": 14, "editor.wordWrap": "on", "editor.renderWhitespace": "boundary", + "files.exclude": { + ".git": true, + ".venv": true, + "logs": true, + "assets": true, + "docs": true, + "pic": true, + "state": true, + "webui": true, + "typings": true, + ".cursor": true + }, + "search.exclude": { + "**/node_modules": true, + ".git": true, + ".venv": true, + "logs": true, + "assets": true, + "docs": true, + "pic": true, + "state": true, + "webui": true + }, + "files.watcherExclude": { + "**/.git/**": true, + "**/.venv/**": true, + "**/logs/**": true, + "**/assets/**": true, + "**/docs/**": true, + "**/pic/**": true, + "**/state/**": true, + "**/webui/**": true, + "**/.cursor/**": true + }, + "search.followSymlinks": false, + "search.useIgnoreFiles": true, + "search.useGlobalIgnoreFiles": true, + "git.autorefresh": false, + "editor.largeFileOptimizations": true, "[markdown]": { "editor.wordWrap": "on", "editor.quickSuggestions": { diff --git a/duplicate_screenshot_analysis.py b/duplicate_screenshot_analysis.py deleted file mode 100644 index d370f54..0000000 --- a/duplicate_screenshot_analysis.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -重复截图场景分析报告 -""" - -def analyze_duplicate_screenshots(): - """分析所有重复截图的场景""" - - print("=" * 80) - print("重复截图场景系统分析报告") - print("=" * 80) - print() - - scenarios = [ - { - "场景": "阶段诊断重复截图", - "位置": "douyin/stage/douyin_stage.py", - "问题": "阶段诊断函数内部会重新截图,但调用方可能已经截过图", - "频率": "高 (每次诊断都可能发生)", - "影响": "每次阶段诊断都截一次图" - }, - { - "场景": "预约检测后重复截图", - "位置": "douyin/core/douyin_fudai.py", - "问题": "预约检测使用缓存,找福袋图标强制截图", - "频率": "中 (预约流程中)", - "影响": "预约→福袋查找间的重复截图" - }, - { - "场景": "福袋查找重试截图", - "位置": "douyin/fudai/douyin_fudai_finder.py", - "问题": "查找失败时会重新截图重试", - "频率": "中 (查找失败时)", - "影响": "多次查找尝试间的重复截图" - }, - { - "场景": "OCR密集操作截图", - "位置": "fudai_detail_modules/fudai_detail_reader.py", - "问题": "OCR前停止截图服务,后续操作需要重新截图", - "频率": "低 (仅OCR操作时)", - "影响": "OCR过程中的额外截图" - }, - { - "场景": "错误处理截图", - "位置": "多个错误处理块", - "问题": "异常处理中重新截图确认状态", - "频率": "低 (异常时)", - "影响": "错误恢复时的额外截图" - }, - { - "场景": "不同模块间的截图", - "位置": "各种模块接口", - "问题": "不同模块使用不同的截图策略", - "频率": "中", - "影响": "模块间的重复截图" - } - ] - - total_scenarios = len(scenarios) - high_freq = sum(1 for s in scenarios if s["频率"] == "高") - med_freq = sum(1 for s in scenarios if s["频率"] == "中") - low_freq = sum(1 for s in scenarios if s["频率"] == "低") - - print(f"[STATS] 发现 {total_scenarios} 个重复截图场景:") - print(f" [HIGH] 高频场景: {high_freq} 个") - print(f" [MED] 中频场景: {med_freq} 个") - print(f" [LOW] 低频场景: {low_freq} 个") - print() - - print("[ANALYSIS] 详细分析:") - print("-" * 60) - - for i, scenario in enumerate(scenarios, 1): - freq_tag = { - "高": "[HIGH]", - "中": "[MED]", - "低": "[LOW]" - }[scenario["频率"]] - - print(f"{i}. {freq_tag} {scenario['场景']}") - print(f" [LOCATION] {scenario['位置']}") - print(f" [ISSUE] {scenario['问题']}") - print(f" [IMPACT] {scenario['影响']}") - print() - - print("[SUGGESTIONS] 优化建议:") - print("-" * 60) - - optimizations = [ - "1. 统一截图策略:所有模块都使用相同的截图服务", - "2. 添加截图时间戳检查:避免短时间内重复截图", - "3. 智能缓存管理:根据操作类型调整缓存有效期", - "4. 模块间协调:减少不同模块间的截图竞争", - "5. 错误处理优化:异常时优先使用现有截图", - "6. 批量操作优化:连续操作中复用截图" - ] - - for opt in optimizations: - print(f" ✅ {opt}") - - print() - print("🎯 优先优化顺序:") - print(" 1. 阶段诊断重复截图 (影响最大)") - print(" 2. 预约流程重复截图 (用户可见)") - print(" 3. 福袋查找重试截图 (性能影响)") - print(" 4. 其他场景优化") - - print() - print("=" * 80) - -if __name__ == "__main__": - analyze_duplicate_screenshots() diff --git a/evaluate_screenshot_performance.py b/evaluate_screenshot_performance.py deleted file mode 100644 index c6c93a7..0000000 --- a/evaluate_screenshot_performance.py +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -评估截图性能:分析后台截图服务 vs 直接截图的性能对比 -""" - -import time -import sys -import os -import statistics - -# 添加项目根目录到路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -def evaluate_screenshot_performance(): - """评估截图性能""" - - print("=" * 60) - print("截图性能评估工具") - print("=" * 60) - - # 1. 分析后台截图服务的配置 - print("\n1. 后台截图服务配置分析:") - print("-" * 40) - - from operations.screenshot_service import ScreenshotService - service = ScreenshotService.get_instance() - - config_info = service.get_cache_info() - print(f"服务运行状态: {'运行中' if config_info['running'] else '未运行'}") - print(f"截图间隔: {config_info['interval']}秒") - print(f"缓存有效期: {config_info['cache_valid_duration']}秒") - print(f"最后截图时间: {config_info['last_screenshot_time']}") - print(f"最后成功状态: {config_info['last_success']}") - - # 2. 模拟性能测试 - print("\n2. 性能测试模拟:") - print("-" * 40) - - # 模拟缓存命中的情况 - print("缓存命中场景:") - print("- 响应时间: < 1ms (直接返回缓存)") - print("- CPU占用: 几乎为0") - print("- 网络开销: 0") - - # 模拟缓存失效的情况 - print("\n缓存失效场景:") - print("- 等待后台截图: 0-6秒 (取决于后台截图进度)") - print("- 总响应时间: 0.1-6秒") - print("- 实际截图耗时: 1.4-1.7秒 (从日志观察)") - - # 3. 分析优化效果 - print("\n3. 优化效果分析:") - print("-" * 40) - - # 计算理论性能提升 - direct_screenshot_time = 1.5 # 直接截图平均耗时(秒) - cache_hit_time = 0.001 # 缓存命中耗时(秒) - cache_miss_time = 2.0 # 缓存失效平均等待时间(秒) - - # 假设缓存命中率 - cache_hit_rate = 0.8 # 80%缓存命中 - cache_miss_rate = 0.2 # 20%缓存失效 - - avg_response_time = (cache_hit_time * cache_hit_rate) + (cache_miss_time * cache_miss_rate) - improvement_ratio = direct_screenshot_time / avg_response_time - - print(f"直接截图平均耗时: {direct_screenshot_time}s") - print(f"缓存命中响应时间: {cache_hit_time}s ({cache_hit_rate*100:.0f}%概率)") - print(f"缓存失效响应时间: {cache_miss_time}s ({cache_miss_rate*100:.0f}%概率)") - print(f"平均响应时间: {avg_response_time:.3f}s") - print(f"性能提升倍数: {improvement_ratio:.1f}x") - - # 4. 分析当前问题 - print("\n4. 当前问题分析:") - print("-" * 40) - - issues = [] - - # 检查服务状态 - if not config_info['running']: - issues.append("[ERROR] 后台截图服务未运行") - else: - issues.append("[OK] 后台截图服务正在运行") - - # 检查缓存配置 - cache_duration = config_info['cache_valid_duration'] - interval = config_info['interval'] - - if cache_duration <= interval: - issues.append(f"[WARN] 缓存有效期({cache_duration}s) <= 截图间隔({interval}s),可能导致缓存频繁过期") - else: - issues.append(f"[OK] 缓存有效期({cache_duration}s) > 截图间隔({interval}s),缓存利用率良好") - - # 检查重复截图问题 - issues.append("[WARN] 日志显示存在重复截图,可能的原因:") - issues.append(" - 循环中多次调用阶段诊断") - issues.append(" - 服务状态管理不当") - issues.append(" - 并发访问导致的竞争条件") - - for issue in issues: - print(issue) - - # 5. 优化建议 - print("\n5. 优化建议:") - print("-" * 40) - - suggestions = [ - "[DONE] 已实现: 后台截图服务避免主流程等待", - "[DONE] 已实现: 智能缓存机制减少重复截图", - "[DONE] 已实现: 循环期间停止服务避免重复截图", - "[DONE] 已实现: OCR期间停止服务避免资源竞争", - "[TODO] 可优化: 调整截图间隔与缓存有效期比例", - "[TODO] 可优化: 实现更智能的缓存失效策略", - "[TODO] 可优化: 优化后台线程调度优先级" - ] - - for suggestion in suggestions: - print(suggestion) - - # 6. 性能对比总结 - print("\n6. 性能对比总结:") - print("-" * 40) - - print("原先方案 (直接截图):") - print(f" - 每次截图耗时: {direct_screenshot_time}s") - print(" - 响应延迟: 高") - print(" - 系统负载: 高") - print(" - 用户体验: 卡顿") - - print(f"\n当前方案 (后台服务+缓存):") - print(f" - 平均响应时间: {avg_response_time:.3f}s") - print(" - 响应延迟: 低") - print(" - 系统负载: 中等") - print(" - 用户体验: 流畅") - - print(f"\n性能提升: {improvement_ratio:.1f}倍") - print("主要优势: 后台预加载 + 缓存复用") - - return { - 'avg_response_time': avg_response_time, - 'improvement_ratio': improvement_ratio, - 'cache_hit_rate': cache_hit_rate, - 'issues': issues - } - -if __name__ == "__main__": - result = evaluate_screenshot_performance() - - print(f"\n{'='*60}") - print("评估完成") - print(f"平均响应时间: {result['avg_response_time']:.3f}秒") - print(f"性能提升倍数: {result['improvement_ratio']:.1f}x") - print(f"缓存命中率: {result['cache_hit_rate']*100:.0f}%") - print(f"发现问题数量: {len([i for i in result['issues'] if '❌' in i or '⚠️' in i])}") - print(f"{'='*60}") diff --git a/final_check.txt b/final_check.txt deleted file mode 100644 index 1d7d1b4f75cfa7efb840297997177ea920790c87..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 15772 zcmeHO&u<$=6rKVH3PRjCfS^$%E1_yb^TSPIsaQcRrBW$vNkLVUtenJgmSopv?IaDf zrK*IAgw%sw&KyurAW;DqP8<*wSN?(uIHFzjvK6%*SkAAyYIbu z-fUQ^LNr`dTU>eq$hE#{~ zqkSByO$ukTINrwp&Cbxbuff z8d}pv8L^IywO=Y6$}AYvJ#M|Vy=&Vt&oJ%J=e)QM`TUhGp;jhheDa4`)wDUMx+7F9=UHkj<$wHz$Xm3jmFL~nB2->XHRwL2|3dzQ!GG&(& zu#PG@U9H3G^YD>h^7}u&Sb6b}Tkqff;^zF_D?jGna(*+1Z$CKy^=GS-u3o=-JyCwj)^WLWeH*oH^@b>PN|d!myV0UMeP%Xwi64>#y@(N9|FG+ObIb+6+dvC5%$kn9GaXnVPa*L2fgd!eh4` zt>eaTkY=4AxE($HMpN;kI7suoj^jy*_7l^~Go9 zfBk*Tmi1kJ9?-4vbXfVqV?9dC#2o{|Xx~XZh|(5*UJ`Gd2xFc0Vn*C-02wyL;B5kD zZhu=pYWKg(9bKA0ad&wie|g%Kn*6{KL_Bf@%~*o8WJ63?DT_>E3HBlzw^)r&%c&1z;o#oVl$+=-5B>J~I1oD}h{wH)<5w=VIQFom9aO3tw*17~nvL8LU% zPcLH6-j}m(oU7v8A?MXhu?gF-T;&(^j(BEty1}|?i?w6RX+h>DiOnyPCd&S{%)^RB zM6A9IX}cqGMllIXHn(9G9!OLc`*xE)H!8>8N3joYH^#Lb5KSv`cD0XWu7sc$j$&q; z|2y$Q3nNMg(Qmcyk-K5}JY~BEQJ>3}e{)jd9$TO3O^dMd7mDz>mSO4{KthD0zfnP>HmcG~K#n2koAIzc<_6E&h; zo9`60@noj$B9}N}9@?6R=jtYo{1v~U(Lkh-vtvH6?m-E8^+9mwC&U|Ag?SRkyjL+K zy8h#YrpM6+eaywRR=pFi(#$9U1yQ*LyxUA$itTS$x=U5#nC2)0lf`$y8rA;>)?X>_B~H7=DG0JMY?Rm35RB zXk3YrC_inJS&CjuzjYhhwzc0TxVCh^6(UPFJCOZ`S4gFSvd3Iy>}DkCowB(OGY49^)2_zsIJabITabDdKTzy_@kO{ z;g@5ls(hz|EUFmWw`*Jgd^Velf|_O60-|vW?cN%s*$G$VbKBHsK^7ipbIJ z1WSYV8gx>t^QaBKe;sQJH!Azmvjs)TP7u{w;5ZySS$(akuk&2TVV6}a$}dR&13x{6 AD*ylh diff --git a/final_check2.txt b/final_check2.txt deleted file mode 100644 index ba702b7c774f840fcfb42411f9b065a27e52dbbb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6624 zcmeHM&2LOm6hF1AkFAA7Oq#s31ksjMo6wN@N+_x=O8xiiNPUvJjRMe}RNpiH(gNe!qJ=?tFJlO%ct@ym#+?_uhBDe&?Kf=KHs^(ji0A zCvkDa$9+herA69gJMKf$h0(Z-NkXC$LqCM)ge1k4h}aTFJ1FPT+aexX9L=3GBxkY0 z$1b_!wv1wJNUhn5os+UgR!RWZ-$GA^v`V||gmjwG3V_3al8~?X=|FEF-E{72a>Y!S zb!z(Q+#7rK)EV#NwtJ_VZh!8npK-%?y!xsBbdUYu1bM49Uq+tUGB=|(WSzj}Kt~~2 zTA3RvDyL1$y$!NwtG%cOtW;gZ@MOyfY>NG;vQF}P2|X+II_lf;+YhgLk-C}nBhwQB zX;L;BQ@TvZF+AhAT95RQjR5ZEzd}_v6r25bZIn zrnWaK``L|qx00hHo6!zJznq<%mo(?@!B`T{%UN>+vMZ~{mGo*6g(g}U*L5jrCu9(N zB|r~n>Ai;0D!rSbj20IKHCF0Xw0>$Jz3%<3lTYTZ4?ns5JbKW7>(Z}0x^XVuIQTfw z3BB?%t22C29`vJEX0OctKN2#WRw5V5=6L$y)w`o^_=U69)2ka4=Ba@ONqhHCQ`Vh7 z?S*64hFA5r$BcZr4=*dVB2r3sR_cRCTXCS*&OE=f2ev}56UKWFGiXu0l0-brc$uY$ zh`%4RZ53eFRp{{)c6z{Xp|3kMKf~B~FFbM#`f-4=3|fdYjksKt4OfYy!_WskiLX4v zAoStmtB!C#qj_U*e}WJ5^?YlujQUdc|7-HiMoH=KmdDL!Z*dy6Qt!NS`pS*-3*+tg zM|I}NF0x-n3=h_;eF2fqTwBL!TP88bK^&vq)jDEVOA(_n^WlY}G2?Cm{E$;dMiUQ1 z;4cAOx!^mV^)45=h0%7CY{Geg5*kPDs#ogRYJ7wKN_DX_-+CLRu_WIAF77J#1cf}6 z@&a0t<eZ~vvbw@^PYjm9 z>KyBJ9Q9RRU+a@kr4+E@%(`PU;!3f~|I732}e2!q2uKGlfw;h^46Z+~rs4L4nU-2BM|7nP;ERS?tM5gCsUt%hZJ(&G* Soc&QHL;eSoIeEoZmHG!rslvek diff --git a/fudai_detail_modules/__init__.py b/fudai_detail_modules/__init__.py index e08d97a..3597f72 100644 --- a/fudai_detail_modules/__init__.py +++ b/fudai_detail_modules/__init__.py @@ -6,4 +6,3 @@ """ __all__ = [] - diff --git a/fudai_detail_modules/fudai_detail_coupon_detection.py b/fudai_detail_modules/fudai_detail_coupon_detection.py index ff6ce3e..dfe17d4 100644 --- a/fudai_detail_modules/fudai_detail_coupon_detection.py +++ b/fudai_detail_modules/fudai_detail_coupon_detection.py @@ -337,4 +337,4 @@ def is_wrong_coupon_popup(analyser: Any) -> bool: ) except Exception: pass - return False \ No newline at end of file + return False diff --git a/fudai_detail_modules/fudai_detail_operations.py b/fudai_detail_modules/fudai_detail_operations.py index 90e37f0..bf70ada 100644 --- a/fudai_detail_modules/fudai_detail_operations.py +++ b/fudai_detail_modules/fudai_detail_operations.py @@ -20,7 +20,7 @@ def close_fudai_detail(analyser: Any) -> None: # 计算关闭详情页的坐标(基准坐标 500, 470) close_x = int(500 * rx // 1080) close_y = int(470 * ry // 2400) - + # 坐标验证:检查坐标是否在合理范围内 # 获取屏幕尺寸(如果可用) screen_width = rx @@ -35,7 +35,7 @@ def close_fudai_detail(analyser: Any) -> None: pass except Exception: pass - + # 验证坐标边界 if close_x < 0 or close_x >= screen_width or close_y < 0 or close_y >= screen_height: try: @@ -55,7 +55,7 @@ def close_fudai_detail(analyser: Any) -> None: # 修正坐标到屏幕范围内 close_x = max(0, min(close_x, screen_width - 1)) close_y = max(0, min(close_y, screen_height - 1)) - + analyser._log_kv( "详情", "close_fudai_detail:点击关闭详情页坐标", @@ -81,7 +81,7 @@ def close_fudai_detail(analyser: Any) -> None: analyser._log_kv("详情", "close_fudai_detail:使用默认坐标关闭详情页") except Exception: pass - + try: analyser.operation.click(analyser.device_id, close_x, close_y) except Exception as e1: @@ -141,7 +141,7 @@ def close_fudai_detail(analyser: Any) -> None: def ensure_fudai_detail_open(analyser: Any, fudai_x: int = 0) -> bool: """确保福袋详情已打开:当前实现只记录日志并假定已打开。 - + Args: analyser: 分析器实例 fudai_x: 福袋的x坐标(可选,当前实现未使用) @@ -160,4 +160,3 @@ def ensure_fudai_detail_open(analyser: Any, fudai_x: int = 0) -> bool: except Exception: pass return True - diff --git a/fudai_detail_modules/fudai_detail_reader.py b/fudai_detail_modules/fudai_detail_reader.py index e80e96d..918a114 100644 --- a/fudai_detail_modules/fudai_detail_reader.py +++ b/fudai_detail_modules/fudai_detail_reader.py @@ -5,6 +5,7 @@ 执行福袋详情的OCR识别和读取,包括单次读取和重试读取。 """ + from __future__ import annotations from typing import Any, Dict, Tuple, Optional @@ -27,6 +28,42 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: 4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。 """ start_time = time.time() + # 性能标记变量 + screenshot_reused = False + screenshot_start = None + screenshot_end = None + ocr_start = None + ocr_end = None + wait_file_ms: Optional[float] = None + image_load_ms: Optional[float] = None + service_stop_ms: Optional[float] = None + countdown_parse_ms: Optional[float] = None + + def _log_perf(tag: str) -> None: + try: + total_ms = round((time.time() - start_time) * 1000, 1) + screenshot_ms = None + if screenshot_start is not None and screenshot_end is not None: + screenshot_ms = round((screenshot_end - screenshot_start) * 1000, 1) + ocr_ms = None + if ocr_start is not None and ocr_end is not None: + ocr_ms = round((ocr_end - ocr_start) * 1000, 1) + analyser._log_kv( + "性能", + "福袋详情关键耗时(ms)", + total_ms=total_ms, + screenshot_ms=screenshot_ms, + ocr_ms=ocr_ms, + wait_file_ms=wait_file_ms, + image_load_ms=image_load_ms, + service_stop_ms=service_stop_ms, + countdown_parse_ms=countdown_parse_ms, + screenshot_reused=bool(screenshot_reused), + tag=tag, + ) + except Exception: + pass + # 步骤1:从阶段检测结果中获取任务数量(不需要截图,直接从阶段检测结果读取) # 任务数量已在阶段检测中检测并保存到 analyser._fudai_detail_task_count_from_stage task_count = 0 @@ -52,16 +89,17 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: ) except Exception: pass + pass # 使用默认值 task_count = 2 - - # 清除标志,避免影响后续调用 + + # 清除任务数量标志,截图复用标志留给后续OCR阶段使用 try: analyser._fudai_detail_task_count_from_stage = None - analyser._screenshot_ready_for_ocr = False # 清除截图复用标志 except Exception: + # 忽略异常,继续处理 pass - + # 如果任务数量为0,说明不在福袋详情页(阶段检测应该已经过滤掉了,这里作为兜底) # 在获取截图之前就返回错误,避免不必要的截图 if task_count <= 0: @@ -77,8 +115,9 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time analyser._log_kv("福袋详情", "read_fudai_detail_once完成(任务数量为0)", elapsed_seconds=round(elapsed, 2)) + _log_perf("taskcount_zero") return "error", tup_err, {"reason": "not_in_fudai_detail", "task_count": task_count} - + # 如果任务数不在(1,2,3)范围内,默认按2个任务处理 if task_count not in (1, 2, 3): task_count = 2 @@ -93,7 +132,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: pass # 异常时使用默认值 task_count = 2 - + # 步骤2:获取截图(仅用于后续OCR识别内容/倒计时/价值,不是为了获取任务数量) # 注意:此时后台截图服务已被停止,直接调用底层截图避免递归 @@ -101,22 +140,41 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: screenshot_reused = False try: if getattr(analyser, '_screenshot_ready_for_ocr', False): - analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用 - screenshot_reused = True try: - analyser._log_kv( - "福袋详情", - "read_fudai_detail_once:复用阶段诊断截图", - reason="stage_diagnosed_task_count_gt_zero" - ) + import path_config + pic_path = path_config.get_screenshot_path() except Exception: - pass + pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + + if os.path.exists(pic_path) and os.path.getsize(pic_path) >= 1024: + analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用 + screenshot_reused = True + try: + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once:复用阶段诊断截图", + reason="stage_diagnosed_task_count_gt_zero", + path=pic_path, + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "福袋详情", + "read_fudai_detail_once:无法复用阶段诊断截图(文件不可用)", + path=pic_path, + size=os.path.getsize(pic_path) if os.path.exists(pic_path) else 0, + ) + except Exception: + pass except Exception: pass # 只有在不能复用截图时才进行新的截图 if not screenshot_reused: try: + screenshot_start = time.time() analyser.operation.get_screenshot(analyser.device_id, use_service=False) # 等待截图文件确实存在(最多等待3秒) @@ -134,9 +192,15 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: break time.sleep(0.1) + screenshot_end = time.time() + wait_file_ms = round((screenshot_end - wait_start) * 1000, 1) + + _log_perf("after_screenshot") + except Exception: + screenshot_end = time.time() if screenshot_start is not None else None pass - + # 使用统一的截图路径配置 try: import path_config @@ -148,12 +212,15 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: pic_rgb = None try: if os.path.exists(pic_path): + _img0 = time.time() pic = Image.open(pic_path) pic.load() pic_rgb = pic.convert("RGB") + image_load_ms = round((time.time() - _img0) * 1000, 1) + _log_perf("after_image_load") except Exception: pass - + if pic_rgb is None: try: analyser._log_kv("福袋详情", "read_fudai_detail_once:无法读取截图,跳过识别") @@ -163,8 +230,9 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time analyser._log_kv("福袋详情", "read_fudai_detail_once完成(截图失败)", elapsed_seconds=round(elapsed, 2)) + _log_perf("screenshot_failed") return "error", tup_err, {"reason": "screenshot_failed"} - + # 如果任务数不在(1,2,3)范围内,默认按2个任务处理 if task_count not in (1, 2, 3): task_count = 2 @@ -176,9 +244,11 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: from operations.screenshot_service import ScreenshotService service = ScreenshotService.get_instance() if service.is_running(): + _svc0 = time.time() # 临时停止后台截图服务,避免在OCR过程中继续截图 service.stop() _ocr_screenshot_service_disabled = True + service_stop_ms = round((time.time() - _svc0) * 1000, 1) try: analyser._log_kv( "截图服务", @@ -189,34 +259,37 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: pass except Exception as e: try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "截图服务", "停止后台截图服务失败", error=str(e), level="WARNING" ) - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass try: + ocr_start = time.time() content, time_text, participants, copies, prize_value_yuan = get_fudai_contain( analyser, renwu=task_count ) - except Exception as e: + ocr_end = time.time() + _log_perf("after_get_fudai_contain") + except Exception as e: # pyright: ignore[reportTooBroadExceptionType] # 出现异常时,记录详细错误和 traceback 并返回占位结果,便于排查 try: - import traceback, json + import traceback tb = traceback.format_exc() # 先尝试通过 analyser._log_kv 输出完整 trace(如果可用) try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "福袋详情", "read_fudai_detail_once 异常", error=str(e), error_type=type(e).__name__, traceback=tb, ) - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] # fallback: 将 traceback 写入统一错误日志 try: import path_config @@ -227,21 +300,22 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: ef.write("\\n") except Exception: pass - except Exception: + except Exception: # pyright: ignore[reportTooBroadExceptionType] try: - analyser._log_kv("福袋详情", "read_fudai_detail_once 异常(无法格式化 traceback)", error=str(e)) - except Exception: + analyser._log_kv("福袋详情", "read_fudai_detail_once 异常(无法格式化 traceback)", error=str(e)) # pyright: ignore[reportPrivateUsage] + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass now = time.time() tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time try: - analyser._log_kv("福袋详情", "read_fudai_detail_once完成(识别异常)", elapsed_seconds=round(elapsed, 2)) - except Exception: + analyser._log_kv("福袋详情", "read_fudai_detail_once完成(识别异常)", elapsed_seconds=round(elapsed, 2)) # pyright: ignore[reportPrivateUsage] + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass + _log_perf("exception_in_get_fudai_contain") return "error", tup_err, {} # 由于已全局禁用流式截图,不再重新启动服务 - + # 检查是否检测到观看任务(通过 _is_watch_task_detected 标志) is_watch_task = False try: @@ -249,16 +323,16 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: # 清除标志,避免影响后续调用 if is_watch_task: try: - analyser._is_watch_task_detected = False - except Exception: + analyser._is_watch_task_detected = False # pyright: ignore[reportPrivateUsage] + except Exception: # pyright: ignore[reportTooBroadExceptionType] pass except Exception: pass - + # 如果检测到观看任务,返回 watch_task 状态 if is_watch_task: try: - analyser._log_kv( + analyser._log_kv( # pyright: ignore[reportPrivateUsage] "福袋详情", "read_fudai_detail_once:检测到'观看X分钟'任务,直接跳过", ) @@ -267,13 +341,14 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: now = time.time() tup_watch = ("", "", 0, 0, 0.0, (now, now + 60.0)) elapsed = time.time() - start_time - analyser._log_kv("福袋详情", "read_fudai_detail_once完成(观看任务)", elapsed_seconds=round(elapsed, 2)) + analyser._log_kv("福袋详情", "read_fudai_detail_once完成(观看任务)", elapsed_seconds=round(elapsed, 2)) # pyright: ignore[reportPrivateUsage] return "watch_task", tup_watch, {"reason": "watch_task_detected", "task_count": task_count} # 解析倒计时 -> (剩余秒数, 未来时间戳) countdown_start = time.time() countdown_end = countdown_start + 60.0 try: + _cd0 = time.time() if time_text: res = analyser.operation.check_countdown(time_text) if isinstance(res, tuple) and len(res) == 2: @@ -285,6 +360,8 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: if total_seconds > 0 and isinstance(future_ts, (int, float)): countdown_start = float(countdown_start) countdown_end = float(future_ts) + countdown_parse_ms = round((time.time() - _cd0) * 1000, 1) + _log_perf("after_countdown_parse") except Exception: pass @@ -299,7 +376,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: extra: Dict[str, Any] = { "task_count": task_count, } - + # 获取直播间名字 room_title = "" room_title_raw = "" @@ -308,11 +385,11 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "").strip() except Exception: pass - + # 输出所有识别到的内容到运行日志和行为日志 try: from datetime import datetime - + # 格式化时间戳为可读格式 countdown_start_str = "" countdown_end_str = "" @@ -324,12 +401,12 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: countdown_end_str = datetime.fromtimestamp(countdown_end).strftime("%Y-%m-%d %H:%M:%S") except Exception: pass - + # 计算剩余秒数 remain_seconds = 0 if countdown_end > countdown_start: remain_seconds = int(countdown_end - time.time()) - + # 输出完整的识别结果到运行日志 content_preview = (content or "")[:60] if content else "未识别到" content_full = content or "" @@ -360,7 +437,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: elapsed_seconds=round(time.time() - start_time, 2), level="DEBUG", ) - + # 输出到行为日志(使用更详细的格式) content_preview = (content or "")[:60] if content else "未识别到" analyser._log_kv( @@ -383,7 +460,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: }, level="DEBUG", ) - + # 输出简化的运行日志(兼容原有格式) analyser._log_kv( "福袋详情", @@ -415,9 +492,10 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: ) except Exception: pass - + elapsed = time.time() - start_time analyser._log_kv("福袋详情", "read_fudai_detail_once完成(成功)", elapsed_seconds=round(elapsed, 2), level="DEBUG") + _log_perf("success") return "ok", detail_tuple, extra @@ -473,7 +551,7 @@ def read_fudai_detail_with_retries( analyser.operation.delay(initial_wait) except Exception: time.sleep(initial_wait) - + max_attempts = 2 try: max_attempts = int(getattr(analyser, "fudai_detail_max_attempts", 2) or 2) @@ -514,27 +592,27 @@ def read_fudai_detail_with_retries( current_countdown_seconds = cd_end - cd_start except Exception: pass - + # 记录第一次成功读取的结果(作为基准) if first_countdown_seconds is None and current_countdown_seconds is not None and status == "ok": first_countdown_seconds = current_countdown_seconds first_tuple = current_tuple first_attempt_time = attempt_start_time last_tuple = current_tuple - + # 优化:如果第一次识别成功且数据合理,直接返回,不进行第二次重试 # 检查数据是否合理(有内容、有价值、倒计时合理) content = current_tuple[0] if len(current_tuple) > 0 else "" prize_value = current_tuple[4] if len(current_tuple) > 4 else 0.0 time_text = current_tuple[1] if len(current_tuple) > 1 else "" - + # 如果数据看起来合理(有内容或价值>0,倒计时合理),直接返回 is_data_reasonable = ( - (content and len(content.strip()) > 0) or + (content and len(content.strip()) > 0) or (prize_value and float(prize_value) > 0) or (time_text and len(time_text.strip()) > 0) ) - + if is_data_reasonable and current_countdown_seconds > 0: try: analyser._log_kv( @@ -549,30 +627,30 @@ def read_fudai_detail_with_retries( pass # 直接返回,不进行第二次重试 break - + # 倒计时一致性检查:如果后续读取的倒计时与第一次差异过大,判定为识别错误 elif first_countdown_seconds is not None and current_countdown_seconds is not None: # 计算时间流逝(从第一次读取到现在的时间差) time_elapsed = attempt_start_time - first_attempt_time if time_elapsed < 0: time_elapsed = 0.5 # 默认假设间隔0.5秒 - + # 预期倒计时 = 第一次倒计时 - 时间流逝(允许一定误差) expected_countdown = first_countdown_seconds - time_elapsed - + # 计算实际差异(与第一次相比) diff_ratio = abs(current_countdown_seconds - first_countdown_seconds) / max(first_countdown_seconds, 1.0) # 计算与预期的差异(考虑时间流逝) expected_diff_ratio = abs(current_countdown_seconds - expected_countdown) / max(expected_countdown, 1.0) if expected_countdown > 0 else 1.0 - + # 如果差异过大(超过30%)或与预期差异过大(超过20%),判定为识别错误 # 注意:如果当前倒计时明显大于第一次(时间应该减少),肯定是识别错误 is_inconsistent = ( - diff_ratio > 0.3 or + diff_ratio > 0.3 or expected_diff_ratio > 0.2 or current_countdown_seconds > first_countdown_seconds + 10 # 倒计时不应该增加 ) - + if is_inconsistent: try: analyser._log_kv( @@ -600,15 +678,15 @@ def read_fudai_detail_with_retries( else: # 倒计时合理,更新为当前结果 last_tuple = current_tuple - + # 如果没有第一次结果,直接使用当前结果 elif first_countdown_seconds is None: last_tuple = current_tuple - + # 如果成功读取,或者检测到优惠券弹窗(已处理完毕),或者检测到观看任务,都停止重试 if status == "ok" or status == "coupon_popup" or status == "watch_task": break - + # 如果任务数量为0,说明没有正确打开福袋详情页,尝试重新打开 if status == "error" and isinstance(extra, dict) and extra.get("reason") == "task_count_zero": if attempt < max_attempts - 1: @@ -639,7 +717,7 @@ def read_fudai_detail_with_retries( ) except Exception: pass - + if attempt < max_attempts - 1: try: analyser.operation.delay(retry_delay) @@ -654,11 +732,11 @@ def read_fudai_detail_with_retries( cd_start, cd_end = None, None if isinstance(cd, (tuple, list)) and len(cd) >= 2: cd_start, cd_end = cd[0], cd[1] - + # 如果是优惠券弹窗,记录日志并明确标记 is_coupon_popup = (last_status == "coupon_popup") is_watch_task = (last_status == "watch_task") - + # 获取直播间名字(所有情况都需要,用于日志输出) room_title = "" room_title_raw = "" @@ -667,7 +745,7 @@ def read_fudai_detail_with_retries( room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "").strip() except Exception: pass - + # 格式化时间信息(所有情况都需要,用于日志输出) cd_end_str = "" remain_seconds = 0 @@ -678,7 +756,7 @@ def read_fudai_detail_with_retries( remain_seconds = int(cd_end - time.time()) if cd_end > time.time() else 0 except Exception: pass - + if is_coupon_popup: try: analyser._log_kv( @@ -812,7 +890,7 @@ def read_fudai_detail_with_retries( remain_seconds=remain_seconds, fudai_x=fudai_x, ) - + # 行为日志:完整的福袋详情 analyser._log_kv( "行为", @@ -845,7 +923,7 @@ def read_fudai_detail_with_retries( ) except Exception: pass - + # 将状态信息存储在 analyser 中,供调用方检查 try: analyser._last_fudai_detail_status = last_status # type: ignore[attr-defined] @@ -856,7 +934,7 @@ def read_fudai_detail_with_retries( analyser._last_fudai_detail_extra = {} # type: ignore[attr-defined] except Exception: pass - + # 验证福袋详情数据的合理性(仅在成功读取时验证) if last_status == "ok": is_valid, reason = validate_fudai_detail(last_tuple, analyser) @@ -876,8 +954,7 @@ def read_fudai_detail_with_retries( analyser._last_fudai_detail_status = "validation_failed" # type: ignore[attr-defined] except Exception: pass - + elapsed = time.time() - start_time analyser._log_kv("福袋详情", "read_fudai_detail_with_retries完成", elapsed_seconds=round(elapsed, 2), status=last_status, attempts=max_attempts) return last_tuple - diff --git a/fudai_detail_modules/fudai_detail_room_title.py b/fudai_detail_modules/fudai_detail_room_title.py index 24be053..21b81f6 100644 --- a/fudai_detail_modules/fudai_detail_room_title.py +++ b/fudai_detail_modules/fudai_detail_room_title.py @@ -48,7 +48,7 @@ def _extract_room_title_candidate(raw_text: str) -> str: t = _strip_room_noise_text(raw_text) if not t: return "" - + segs = [x.strip() for x in re.split(r"[\n ]+", t) if x.strip()] best = "" best_score = -999 @@ -67,14 +67,14 @@ def _extract_room_title_candidate(raw_text: str) -> str: if score > best_score: best_score = score best = seg - + if best: m = re.search(r"(.*?)(…|\.{3,})", best) if m: cand = (m.group(1) + m.group(2)).strip() return cand if cand else best.strip() return best.strip() - + m2 = re.search(r"(.*?)(…|\.{3,})", t) if m2: cand2 = (m2.group(1) + m2.group(2)).strip() @@ -155,7 +155,7 @@ def read_live_room_title_core( min_len: int = 3, ) -> Tuple[str, str]: """读取当前直播间顶部区域的"主播名/直播间名"(OCR,尽量轻量)。 - + 只使用指定区域 (144,144) 到 (329,185) 进行识别,避免多次截图。 """ try: @@ -171,7 +171,7 @@ def read_live_room_title_core( ) except Exception: pass - + # 只使用指定区域 (144,144) 到 (329,185),只尝试一次OCR(mode 0) try: analyser.cut_pic(144, 144, 329, 185, '', 'live_room_title_mid', y_pianyi) @@ -191,7 +191,7 @@ def read_live_room_title_core( pass title = "" raw_text = "" - + # 更新 analyser 的属性 try: analyser.current_room_title_raw = raw_text @@ -199,6 +199,5 @@ def read_live_room_title_core( analyser.current_room_title = title except Exception: pass - - return title, raw_text + return title, raw_text diff --git a/fudai_detail_modules/fudai_detail_utils.py b/fudai_detail_modules/fudai_detail_utils.py index 951602a..9cd189e 100644 --- a/fudai_detail_modules/fudai_detail_utils.py +++ b/fudai_detail_modules/fudai_detail_utils.py @@ -15,4 +15,3 @@ def is_abnormal_time_value(v: float) -> bool: if v > 24 * 3600 * 7: return True return False - diff --git a/fudai_detail_modules/fudai_detail_validator.py b/fudai_detail_modules/fudai_detail_validator.py index 36c2575..573b2f9 100644 --- a/fudai_detail_modules/fudai_detail_validator.py +++ b/fudai_detail_modules/fudai_detail_validator.py @@ -13,14 +13,14 @@ import re def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, str]: """验证福袋详情数据的合理性。 - + 返回: (is_valid, reason) - is_valid=True 表示数据合理,False 表示识别出错 reason 为失败原因描述 """ if not isinstance(detail, tuple) or len(detail) < 6: return False, "detail_tuple_invalid" - + content = str(detail[0] or "").strip() time_text = str(detail[1] or "").strip() try: @@ -35,7 +35,7 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st prize_value_yuan = float(detail[4] or 0.0) except Exception: prize_value_yuan = 0.0 - + countdown_tuple = detail[5] countdown_start, countdown_end = None, None if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: @@ -44,19 +44,19 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st countdown_end = float(countdown_tuple[1] or 0.0) except Exception: pass - + # 检查1:内容不能为空(至少要有一些文字) if not content or len(content.strip()) < 2: return False, "content_empty_or_too_short" - + # 检查2:价值应该大于0(福袋至少应该有价值) if prize_value_yuan <= 0: return False, "prize_value_zero_or_negative" - + # 检查3:价值应该合理(不能太大,比如超过100万) if prize_value_yuan > 1000000: return False, "prize_value_too_large" - + # 检查4:倒计时应该合理 if countdown_end is not None and countdown_start is not None: remain_seconds = countdown_end - countdown_start @@ -97,23 +97,22 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st return False, f"countdown_mismatch_time_text (remain={int(remain_seconds)}, text={text_seconds}, diff={round(diff_ratio*100, 1)}%)" except Exception: pass - + # 检查5:参与人数应该合理(不能是负数) if participants < 0: return False, "participants_negative" - + # 检查6:份数应该合理(不能是负数,至少应该是1) if copies < 0: return False, "copies_negative" - + # 检查7:如果份数为0,但参与人数大于0,可能识别错误 if copies == 0 and participants > 0: return False, "copies_zero_but_participants_positive" - + # 检查8:时间文本应该存在(至少应该有倒计时信息) if not time_text and (countdown_end is None or countdown_end <= 0): return False, "no_time_text_and_no_countdown" - + # 所有检查通过 return True, "ok" - diff --git a/gui/components/__init__.py b/gui/components/__init__.py index 3d30fd1..e96a11e 100644 --- a/gui/components/__init__.py +++ b/gui/components/__init__.py @@ -2,54 +2,3 @@ 本目录包含从 gui_app.py 模块化后的GUI组件。 """ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gui/components/actions_log_viewer.py b/gui/components/actions_log_viewer.py index fe69618..5ceae2a 100644 --- a/gui/components/actions_log_viewer.py +++ b/gui/components/actions_log_viewer.py @@ -53,7 +53,7 @@ def create_actions_log_viewer( """ actions_log_text = ScrolledText(parent) actions_log_text.pack(fill="both", expand=True, padx=10, pady=10) - + try: actions_log_text.configure(font=("Consolas", 10)) except Exception: @@ -69,7 +69,7 @@ def create_actions_log_viewer( # 回退到旧路径(向后兼容) import path_config path = path_config.get_actions_log_path() - + try: if os.path.exists(path): # 仿照 web_gui 的实现:只读最后一小段,避免文件巨大 @@ -78,7 +78,7 @@ def create_actions_log_viewer( actions_log_text.delete("1.0", "end") actions_log_text.insert("1.0", "行为日志文件为空") return - + read_bytes = min(size, 65536) with open(path, "rb") as f: if read_bytes < size: @@ -136,7 +136,7 @@ def create_actions_log_viewer( break else: actions_log_text.insert("1.0", "暂无匹配的行为日志") - + # 恢复之前的滚动位置,避免自动置顶 try: actions_log_text.yview_moveto(scroll_position) @@ -154,4 +154,3 @@ def create_actions_log_viewer( ) return actions_log_text, refresh_actions_log - diff --git a/gui/components/config_manager.py b/gui/components/config_manager.py index 10f39ce..a5928fa 100644 --- a/gui/components/config_manager.py +++ b/gui/components/config_manager.py @@ -42,54 +42,3 @@ def save_ui_to_config( # TODO: 实现配置保存逻辑 # 临时从原文件导入 pass - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gui/components/device_selector.py b/gui/components/device_selector.py index a281db7..69fe3a8 100644 --- a/gui/components/device_selector.py +++ b/gui/components/device_selector.py @@ -52,54 +52,3 @@ def create_device_selector( ) return device_combo, refresh_devices - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gui/components/high_value_rooms_display.py b/gui/components/high_value_rooms_display.py index a5456ba..e0902e9 100644 --- a/gui/components/high_value_rooms_display.py +++ b/gui/components/high_value_rooms_display.py @@ -28,7 +28,7 @@ def create_high_value_rooms_display( """ high_value_text = ScrolledText(parent) high_value_text.pack(fill="both", expand=True, padx=10, pady=10) - + try: high_value_text.configure(font=("Consolas", 10)) except Exception: @@ -40,4 +40,3 @@ def create_high_value_rooms_display( pass return high_value_text, refresh_high_value_rooms - diff --git a/gui/components/image_viewer.py b/gui/components/image_viewer.py index e7cdf3f..7f66666 100644 --- a/gui/components/image_viewer.py +++ b/gui/components/image_viewer.py @@ -26,66 +26,15 @@ def create_image_viewer( (image_var, update_image_list_func, refresh_preview_func) """ image_var = tk.StringVar() - + def update_image_list(refresh_after: bool = True) -> None: """更新图像列表。""" # TODO: 从原文件迁移函数实现 pass - + def refresh_preview() -> None: """刷新图像预览。""" # TODO: 从原文件迁移函数实现 pass return image_var, update_image_list, refresh_preview - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gui/components/log_color_config.py b/gui/components/log_color_config.py index 0a642ee..925f9fb 100644 --- a/gui/components/log_color_config.py +++ b/gui/components/log_color_config.py @@ -15,7 +15,7 @@ OPERATION_KEYWORDS: Dict[str, list] = { "直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果" ], "click": [ - "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", + "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", "返回", "确认", "关闭", "发送", "加入" ], "swipe": [ @@ -68,10 +68,10 @@ OPERATION_KEYWORDS: Dict[str, list] = { } - - + + from typing import Dict, Optional @@ -83,7 +83,7 @@ OPERATION_KEYWORDS: Dict[str, list] = { "直播间标题", "福袋内容", "福袋倒计时", "福袋价值", "参与人数", "开奖结果" ], "click": [ - "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", + "点击", "click", "点击成功", "点击失败", "参与按钮", "福袋图标", "返回", "确认", "关闭", "发送", "加入" ], "swipe": [ @@ -139,25 +139,25 @@ OPERATION_KEYWORDS: Dict[str, list] = { def get_operation_type(line: str) -> Optional[str]: """ 根据日志行内容识别操作类型 - + 日志格式通常是: [时间] [GUI] - 操作类型 内容 优先识别日志内容中的操作类型关键词(如 "流程"、"滑动"、"阶段诊断"、"预约" 等) - + Args: line: 日志行内容 - + Returns: 操作类型名称,如果无法识别则返回None """ line_lower = line.lower() - + # 优先级1: 识别日志内容开头的操作类型(最精确) # 日志格式: [时间] [GUI] - 操作类型 内容 # 例如: [GUI] - 流程 find_and_open_fudai_detail完成 # [GUI] - 滑动上滑切换直播间 # [GUI] - 阶段诊断开始阶段诊断 # [GUI] - 预约[预约]记录直播间标题 - + import re # 提取日志内容部分(去掉时间戳和标签) # 匹配格式: [时间] [标签] - 内容 @@ -165,7 +165,7 @@ def get_operation_type(line: str) -> Optional[str]: if content_match: content = content_match.group(1).strip() content_lower = content.lower() - + # 操作类型关键词映射(按优先级排序,更具体的在前) operation_type_map = [ # 检测相关(最具体) @@ -212,7 +212,7 @@ def get_operation_type(line: str) -> Optional[str]: # 信息相关(最通用,放最后) ("信息", "info"), ] - + # 检查内容开头是否匹配操作类型 for keyword, op_type in operation_type_map: # 检查是否在内容开头(更精确) @@ -221,12 +221,12 @@ def get_operation_type(line: str) -> Optional[str]: # 或者检查是否紧跟在 " - " 后面 if f" - {keyword.lower()}" in line_lower or f"- {keyword.lower()}" in line_lower: return op_type - + # 优先级2: 使用日志标签识别(如果内容中没有匹配到) tag_match = re.search(r'\[([^\]]+)\]', line) if tag_match: tag = tag_match.group(1).lower() - + # 标签到操作类型的映射(精确匹配) tag_to_op_type = { "阶段诊断": "detection", @@ -249,16 +249,16 @@ def get_operation_type(line: str) -> Optional[str]: "信息": "info", "提示": "info", } - + # 精确匹配标签 if tag in tag_to_op_type: return tag_to_op_type[tag] - + # 部分匹配标签(用于更灵活的匹配) for tag_key, op_type in tag_to_op_type.items(): if tag_key in tag or tag in tag_key: return op_type - + # 优先级2: 使用关键词匹配(更具体的短语优先) # 定义更具体的关键词短语(按优先级排序) specific_patterns = [ @@ -294,12 +294,12 @@ def get_operation_type(line: str) -> Optional[str]: ("粉丝团失败", "fansclub"), ("粉丝团成功", "fansclub"), ] - + # 先检查更具体的短语 for pattern, op_type in specific_patterns: if pattern.lower() in line_lower: return op_type - + # 优先级3: 使用通用关键词匹配(按操作类型优先级) # 调整顺序,让更具体的操作类型优先 priority_order = [ @@ -320,7 +320,7 @@ def get_operation_type(line: str) -> Optional[str]: "success", # 成功(较通用) "info", # 信息(最通用,放最后) ] - + # 按优先级顺序检查 for op_type in priority_order: if op_type in OPERATION_KEYWORDS: @@ -337,26 +337,26 @@ def get_operation_type(line: str) -> Optional[str]: return op_type # 其他宽泛关键词跳过,避免误匹配 continue - + if keyword.lower() in line_lower: return op_type - + return None def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]: """ 获取颜色配置(根据主题) - + Args: theme: 主题名称("litera", "darkly" 等) - + Returns: 颜色配置字典,包含每种操作类型的颜色设置 """ light_themes = {"litera", "flatly", "journal", "minty", "cosmo"} is_light = theme.lower() in light_themes - + if is_light: # 明亮主题颜色配置(深色文字,与白色背景对比,高区分度) return { @@ -496,15 +496,15 @@ def get_color_config(theme: str = "litera") -> Dict[str, Dict[str, str]]: def apply_operation_color( - text_widget, - start_pos: str, - end_pos: str, - line: str, + text_widget, + start_pos: str, + end_pos: str, + line: str, theme: str = "litera" ) -> None: """ 为日志行应用操作类型颜色 - + Args: text_widget: tkinter Text 组件 start_pos: 起始位置 @@ -517,24 +517,24 @@ def apply_operation_color( op_type = get_operation_type(line) if not op_type: return - + # 获取颜色配置 color_config = get_color_config(theme) if op_type not in color_config: return - + colors = color_config[op_type] tag_name = f"op_{op_type}" - + # 配置标签(总是重新配置,确保主题改变时颜色也会更新) text_widget.tag_configure( tag_name, foreground=colors["foreground"], background=colors["background"], ) - + # 应用标签 text_widget.tag_add(tag_name, start_pos, end_pos) except Exception: # 忽略颜色应用失败,不影响日志显示 - pass \ No newline at end of file + pass diff --git a/gui/components/log_color_config_fixed.py b/gui/components/log_color_config_fixed.py index 0d8d0b7..36551b4 100644 --- a/gui/components/log_color_config_fixed.py +++ b/gui/components/log_color_config_fixed.py @@ -196,19 +196,3 @@ def apply_operation_color( except Exception: # 忽略颜色应用失败,不影响日志显示 pass - - - - - - - - - - - - - - - - diff --git a/gui/components/log_viewer.py b/gui/components/log_viewer.py index 2d7fb05..eae9839 100644 --- a/gui/components/log_viewer.py +++ b/gui/components/log_viewer.py @@ -429,4 +429,3 @@ def create_log_viewer( pass return viewer.log_text, pump_logs - diff --git a/gui/components/main_window.py b/gui/components/main_window.py index 2d9240a..3d7c1ec 100644 --- a/gui/components/main_window.py +++ b/gui/components/main_window.py @@ -34,54 +34,3 @@ def create_main_window( root.geometry(geometry) return root - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gui/components/ocr_panel.py b/gui/components/ocr_panel.py index c000d13..d4bc3f6 100644 --- a/gui/components/ocr_panel.py +++ b/gui/components/ocr_panel.py @@ -28,61 +28,10 @@ def create_ocr_panel( (ocr_results_var, do_screenshot_func) """ ocr_results_var = {"results": []} - + def do_screenshot() -> None: """执行截图和OCR识别。""" # TODO: 从原文件迁移函数实现 pass return ocr_results_var, do_screenshot - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gui/components/reservation_display.py b/gui/components/reservation_display.py index d4c75ba..a26b644 100644 --- a/gui/components/reservation_display.py +++ b/gui/components/reservation_display.py @@ -28,7 +28,7 @@ def create_reservation_display( """ reservation_text = ScrolledText(parent) reservation_text.pack(fill="both", expand=True, padx=10, pady=10) - + try: reservation_text.configure(font=("Consolas", 10)) except Exception: @@ -40,4 +40,3 @@ def create_reservation_display( pass return reservation_text, refresh_reservations - diff --git a/gui/components/stats_display.py b/gui/components/stats_display.py index a951496..1a2614d 100644 --- a/gui/components/stats_display.py +++ b/gui/components/stats_display.py @@ -32,7 +32,7 @@ def create_stats_display( """ stats_text = ScrolledText(parent) stats_text.pack(fill="both", expand=True, padx=10, pady=10) - + try: stats_text.configure(font=("Consolas", 10)) except Exception: @@ -44,4 +44,3 @@ def create_stats_display( pass return stats_text, refresh_stats - diff --git a/gui/gui_app.py b/gui/gui_app.py index 0b89158..0cf811f 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -406,7 +406,7 @@ def main(): value=float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0) ) fudai_click_wait_seconds_var = tk.DoubleVar( - value=float(cfg.get("fudai_click_wait_seconds", 2.0) or 2.0) + value=float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0) ) switch_room_wait_after_stage_diag_seconds_var = tk.DoubleVar( value=float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0) @@ -1151,7 +1151,7 @@ def main(): textvariable=fudai_click_wait_seconds_var, width=6, ).pack(side=LEFT) - ttk.Label(row4d, text="(等待福袋详情页加载,默认2.0秒)").pack(side=LEFT, padx=(6, 0)) + ttk.Label(row4d, text="(等待福袋详情页加载,默认1.0秒)").pack(side=LEFT, padx=(6, 0)) row4e = ttk.Frame(fudai_find_box) row4e.pack(fill=X, padx=10, pady=(0, 8)) @@ -1502,7 +1502,7 @@ def main(): float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0) ) fudai_click_wait_seconds_var.set( - float(cfg.get("fudai_click_wait_seconds", 2.0) or 2.0) + float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0) ) switch_room_wait_after_stage_diag_seconds_var.set( float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0) @@ -2086,22 +2086,22 @@ def main(): # 日志区 log_box = ttk.Frame(log_tab) log_box.pack(fill=BOTH, expand=True) - + # 搜索工具栏 log_search_frame = ttk.Frame(log_box) log_search_frame.pack(fill=X, padx=10, pady=(10, 5)) - + log_search_var = tk.StringVar(value="") log_search_entry = ttk.Entry(log_search_frame, textvariable=log_search_var, width=20) log_search_entry.pack(side=LEFT, padx=(0, 5)) - + log_search_matches = [] # 存储所有匹配的位置 log_current_match_index = -1 # 当前匹配的索引 - + def search_in_log_text(direction=1): """在运行日志中搜索文本""" nonlocal log_search_matches, log_current_match_index - + search_text = log_search_var.get().strip() if not search_text: # 清除高亮 @@ -2109,74 +2109,74 @@ def main(): log_search_matches = [] log_current_match_index = -1 return - + # 获取所有文本 content = log_text.get("1.0", "end-1c") if not content: return - + # 清除之前的高亮 log_text.tag_remove("search_highlight", "1.0", "end") log_text.tag_remove("search_current", "1.0", "end") - + # 配置高亮样式 log_text.tag_config("search_highlight", background="yellow") log_text.tag_config("search_current", background="orange") - + # 查找所有匹配项(不区分大小写) log_search_matches = [] start_pos = 0 # 使用整数索引 search_text_lower = search_text.lower() content_lower = content.lower() - + while True: # 在内容中查找 pos = content_lower.find(search_text_lower, start_pos) if pos == -1: break - + # 计算行号和列号 line_start = content[:pos].rfind("\n") + 1 line_num = content[:pos].count("\n") + 1 col_num = pos - line_start - + # 转换为 tkinter 索引格式 start_index = f"{line_num}.{col_num}" end_index = f"{line_num}.{col_num + len(search_text)}" - + log_search_matches.append((start_index, end_index)) start_pos = pos + 1 - + if not log_search_matches: # 没有找到匹配项 log_current_match_index = -1 return - + # 高亮所有匹配项 for start_idx, end_idx in log_search_matches: log_text.tag_add("search_highlight", start_idx, end_idx) - + # 根据方向更新当前匹配索引 if direction == 1: # 下一个 log_current_match_index = (log_current_match_index + 1) % len(log_search_matches) else: # 上一个 log_current_match_index = (log_current_match_index - 1) % len(log_search_matches) - + # 高亮当前匹配项并滚动到该位置 if log_current_match_index >= 0: start_idx, end_idx = log_search_matches[log_current_match_index] log_text.tag_add("search_current", start_idx, end_idx) log_text.see(start_idx) log_text.mark_set("insert", start_idx) - + def search_next_in_log(): """搜索下一个""" search_in_log_text(1) - + def search_prev_in_log(): """搜索上一个""" search_in_log_text(-1) - + def clear_search_in_log(): """清除搜索高亮""" nonlocal log_search_matches, log_current_match_index @@ -2185,19 +2185,19 @@ def main(): log_text.tag_remove("search_current", "1.0", "end") log_search_matches = [] log_current_match_index = -1 - + # 绑定回车键搜索 def on_log_search_entry_key(event): if event.keysym == "Return": search_next_in_log() - + log_search_entry.bind("", on_log_search_entry_key) - + ttk.Button(log_search_frame, text="搜索", command=search_next_in_log).pack(side=LEFT, padx=(0, 2)) ttk.Button(log_search_frame, text="上一个", command=search_prev_in_log).pack(side=LEFT, padx=(0, 2)) ttk.Button(log_search_frame, text="下一个", command=search_next_in_log).pack(side=LEFT, padx=(0, 2)) ttk.Button(log_search_frame, text="清除", command=clear_search_in_log).pack(side=LEFT, padx=(0, 5)) - + log_text = ScrolledText(log_box) try: log_text.configure(font=("Consolas", 10)) @@ -2234,7 +2234,7 @@ def main(): log_text.tag_configure("log_critical", foreground="#F44336", font=("Consolas", 10, "bold")) # 加粗亮红色 log_text.tag_configure("log_performance", foreground="#81C784") # 亮绿色,性能数据 log_text.tag_configure("log_module", foreground="#BA68C8") # 亮紫色,模块标识 - + # 配置操作类型颜色标签(使用模块化配置) try: color_config = get_color_config(current_theme) @@ -2512,7 +2512,7 @@ def main(): current_theme = str(gui_theme_var.get() or "litera") except Exception: current_theme = "litera" - + while True: line = q.get_nowait() try: @@ -2552,7 +2552,7 @@ def main(): tag = "log_performance" elif re.search(r'\[[\w\.]+\]', line): tag = "log_module" - + if tag: log_text.tag_add(tag, start_pos, end_pos) except Exception: @@ -2748,7 +2748,7 @@ def main(): lines.append("=" * 60) lines.append(f"倒计时大于阈值但价值达到高价值阈值,记录预约: {fudai_reserved_high_value}") lines.append("") - + # 等待开奖统计 fudai_waiting_lottery = counters.get("fudai_waiting_lottery", 0) if fudai_waiting_lottery > 0: @@ -2757,7 +2757,7 @@ def main(): lines.append("=" * 60) lines.append(f"等待开奖次数: {fudai_waiting_lottery}") lines.append("") - + # 阶段诊断统计 stage_diagnosis_complete = counters.get("stage_diagnosis_complete", 0) stage_diagnosis_failed = counters.get("stage_diagnosis_failed", 0) @@ -2771,7 +2771,7 @@ def main(): success_rate = (stage_diagnosis_complete / (stage_diagnosis_complete + stage_diagnosis_failed)) * 100 lines.append(f"成功率: {success_rate:.1f}%") lines.append("") - + # OCR识别统计 ocr_attempt = counters.get("ocr_attempt", 0) ocr_success = counters.get("ocr_success", 0) @@ -2790,7 +2790,7 @@ def main(): ocr_rate = (ocr_success / ocr_attempt) * 100 lines.append(f"OCR成功率: {ocr_rate:.1f}%") lines.append("") - + # 详情识别统计 fudai_detail_read_attempt = counters.get("fudai_detail_read_attempt", 0) fudai_detail_read_success = counters.get("fudai_detail_read_success", 0) @@ -2809,7 +2809,7 @@ def main(): detail_rate = (fudai_detail_read_success / fudai_detail_read_attempt) * 100 lines.append(f"详情识别成功率: {detail_rate:.1f}%") lines.append("") - + # 福袋查找统计 fudai_find_success = counters.get("fudai_find_success", 0) fudai_find_not_found = counters.get("fudai_find_not_found", 0) @@ -2822,7 +2822,7 @@ def main(): lines.append(f"未找到: {fudai_find_not_found}") lines.append(f"等待超时: {fudai_find_timeout}") lines.append("") - + # 性能统计(慢操作) slow_operation = counters.get("slow_operation", 0) if slow_operation > 0: @@ -2913,7 +2913,7 @@ def main(): reservation_queue_full_back_attend = counters.get("reservation_queue_full_back_attend", 0) reservation_duplicate_detected = counters.get("reservation_duplicate_detected", 0) reservation_back_operation = counters.get("reservation_back_operation", 0) - + reservation_total = ( reservation_recorded + reservation_window_entered @@ -2933,20 +2933,20 @@ def main(): + reservation_duplicate_detected + reservation_back_operation ) - + if reservation_total > 0 or reservation_recorded > 0: lines.append("=" * 60) lines.append("预约相关统计(详细)") lines.append("=" * 60) - + # 预约记录统计 if reservation_recorded > 0: lines.append(f"记录预约总数: {reservation_recorded}") - + # 预约回退统计 if reservation_back_success > 0: lines.append(f"成功回退到预约直播间: {reservation_back_success}") - + # 回退校验统计 verify_total = reservation_back_verify_ok + reservation_back_verify_fail if verify_total > 0: @@ -2954,13 +2954,13 @@ def main(): lines.append( f"回退校验: {reservation_back_verify_ok} 成功 / {reservation_back_verify_fail} 失败 (成功率: {verify_rate:.1f}%)" ) - + # 预约窗口统计 if reservation_window_entered > 0: lines.append(f"进入预约参与窗口: {reservation_window_entered}") if reservation_window_not_reached > 0: lines.append(f"时间窗口未到(跳过): {reservation_window_not_reached}") - + # 预约状态统计 if reservation_expired > 0: lines.append(f"过期预约(已清理): {reservation_expired}") @@ -2972,7 +2972,7 @@ def main(): lines.append(f"队列已满等待: {reservation_queue_full_wait}") if reservation_back_to_first > 0: lines.append(f"回退到第一个直播间: {reservation_back_to_first}") - + # 预约管理统计 if reservation_drop_low_value > 0: lines.append(f"丢弃低价值预约: {reservation_drop_low_value}") @@ -2980,7 +2980,7 @@ def main(): lines.append(f"清空预约队列: {reservation_clear}") if reservation_duplicate_detected > 0: lines.append(f"检测到重复预约: {reservation_duplicate_detected}") - + # 回退后直接参与统计 if reservation_back_direct_attend > 0: lines.append(f"回退后直接参与: {reservation_back_direct_attend}") @@ -2988,12 +2988,12 @@ def main(): lines.append(f"队列满回退后参与: {reservation_queue_full_back_attend}") if reservation_back_operation > 0: lines.append(f"回退操作次数: {reservation_back_operation}") - + # 预约成功率 if reservation_recorded > 0 and reservation_back_success > 0: back_rate = (reservation_back_success / reservation_recorded) * 100 lines.append(f"预约回退成功率: {back_rate:.1f}% ({reservation_back_success}/{reservation_recorded})") - + lines.append("") # 错误统计(详细版) @@ -3016,7 +3016,7 @@ def main(): error_fudai_find = counters.get("error_fudai_find", 0) fudai_open_error = counters.get("fudai_open_error", 0) fudai_open_error_too_many = counters.get("fudai_open_error_too_many", 0) - + error_all = ( error_total + error_unbound_local @@ -3038,16 +3038,16 @@ def main(): + fudai_open_error + fudai_open_error_too_many ) - + if error_all > 0: lines.append("=" * 60) lines.append("错误统计(详细)") lines.append("=" * 60) - + # 总错误数 if error_total > 0: lines.append(f"总错误数: {error_total}") - + # 福袋相关错误 fudai_errors = fudai_open_error + fudai_open_error_too_many if fudai_errors > 0: @@ -3057,7 +3057,7 @@ def main(): lines.append(f" 打开福袋异常: {fudai_open_error}") if fudai_open_error_too_many > 0: lines.append(f" 打开失败次数过多: {fudai_open_error_too_many}") - + # Python异常类型 python_errors = ( error_unbound_local @@ -3079,7 +3079,7 @@ def main(): lines.append(f" ValueError: {error_value}") if error_type > 0: lines.append(f" TypeError: {error_type}") - + # 功能模块错误 module_errors = ( error_ocr @@ -3113,7 +3113,7 @@ def main(): lines.append(f" 直播间检测错误: {error_live_room_detect}") if error_fudai_find > 0: lines.append(f" 福袋查找错误: {error_fudai_find}") - + # 网络和超时错误 network_errors = error_timeout + error_connection if network_errors > 0: @@ -3123,14 +3123,14 @@ def main(): lines.append(f" 超时错误: {error_timeout}") if error_connection > 0: lines.append(f" 连接错误: {error_connection}") - + # 错误率统计 if uptime_seconds > 0 and error_all > 0: hours = uptime_seconds / 3600.0 if hours > 0: lines.append("") lines.append(f"错误频率: {error_all / hours:.2f} 次/小时") - + lines.append("") # 价值统计(从事件中提取) @@ -3290,7 +3290,7 @@ def main(): lines.append("=" * 60) lines.append("【预约队列总览】") lines.append("=" * 60) - + if updated_ts > 0: try: updated_dt = datetime.fromtimestamp(updated_ts) @@ -3312,12 +3312,12 @@ def main(): lines.append(f"最后更新时间:{updated_str}") else: lines.append("最后更新时间:暂无数据") - + lines.append(f"当前所在直播间位置:第 {room_pos + 1} 个直播间(索引:{room_pos})") lines.append(f"当前直播间名称(清洗后):{current_title or '未知'}") lines.append(f"当前直播间名称(原始):{current_title_raw or '未知'}") lines.append(f"预约队列总数:{len(reservations)} 条") - + if reason: reason_map = { "record_reservation": "记录新预约", @@ -3327,9 +3327,9 @@ def main(): } reason_text = reason_map.get(reason, reason) lines.append(f"最近更新原因:{reason_text}") - + lines.append("") - + # 统计信息 if reservations: now_ts = datetime.now().timestamp() @@ -3337,14 +3337,14 @@ def main(): valid_future_times = [] expired_count = 0 upcoming_count = 0 - + for item in reservations: try: val = float(item.get("prize_value_yuan") or 0.0) total_value += val except Exception: pass - + ft = float(item.get("future_ts") or 0.0) if ft > 0: valid_future_times.append(ft) @@ -3353,13 +3353,13 @@ def main(): expired_count += 1 elif remain_sec <= 300: # 5分钟内 upcoming_count += 1 - + lines.append("【统计信息】") lines.append(f"预约总价值:{total_value:.2f} 元") if len(reservations) > 0: avg_value = total_value / len(reservations) lines.append(f"平均价值:{avg_value:.2f} 元") - + if valid_future_times: earliest_ts = min(valid_future_times) latest_ts = max(valid_future_times) @@ -3370,18 +3370,18 @@ def main(): lines.append(f"最晚开奖时间:{latest_str}") except Exception: pass - + if expired_count > 0: lines.append(f"⚠️ 已过期预约:{expired_count} 条") if upcoming_count > 0: lines.append(f"⏰ 即将开奖(5分钟内):{upcoming_count} 条") - + lines.append("") lines.append("=" * 60) lines.append("【预约明细列表】(按预计开奖时间从早到晚排序)") lines.append("=" * 60) lines.append("") - + for idx, item in enumerate(reservations, start=1): try: val = float(item.get("prize_value_yuan") or 0.0) @@ -3398,7 +3398,7 @@ def main(): # 计算剩余时间(更详细) now_ts = datetime.now().timestamp() remain_sec = ft - now_ts if ft > 0 else 0 - + if ft <= 0: remain_str = "❌ 开奖时间无效" status_icon = "❌" @@ -3543,10 +3543,10 @@ def main(): current_theme = str(gui_theme_var.get() or "litera") except Exception: current_theme = "litera" - + # 获取颜色配置 color_config = get_color_config(current_theme) - + # 根据主题设置背景和前景色 light_themes = {"litera", "flatly", "journal", "minty", "cosmo"} is_light = current_theme.lower() in light_themes @@ -3554,7 +3554,7 @@ def main(): actions_log_text.configure(background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C") else: actions_log_text.configure(background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF") - + # 为所有操作类型配置标签 for op_type, colors in color_config.items(): tag_name = f"op_{op_type}" @@ -3568,7 +3568,7 @@ def main(): pass # 忽略标签配置失败 except Exception: pass # 忽略颜色配置失败 - + # 初始配置 configure_actions_log_colors() @@ -3593,7 +3593,7 @@ def main(): actions_log_text.delete("1.0", "end") actions_log_text.insert("1.0", "行为日志文件为空") return - + read_bytes = min(size, 65536) with open(path, "rb") as f: if read_bytes < size: @@ -3632,7 +3632,7 @@ def main(): current_theme = str(gui_theme_var.get() or "litera") except Exception: current_theme = "litera" - + # 逐行插入并应用颜色标签 for i, line in enumerate(tail): start_pos = actions_log_text.index("end-1c") @@ -3656,7 +3656,7 @@ def main(): pass # 忽略颜色应用失败 else: actions_log_text.insert("1.0", "暂无匹配的行为日志") - + # 恢复之前的滚动位置,避免自动置顶 try: actions_log_text.yview_moveto(scroll_position) @@ -3678,22 +3678,22 @@ def main(): ttk.Button(actions_log_top, text="刷新", command=refresh_actions_log).pack( side=LEFT, padx=(0, 10) ) - + # 行为日志搜索功能 ttk.Separator(actions_log_top, orient="vertical").pack(side=LEFT, fill=Y, padx=5, pady=3) ttk.Label(actions_log_top, text="搜索:").pack(side=LEFT) - + actions_search_var = tk.StringVar(value="") actions_search_entry = ttk.Entry(actions_log_top, textvariable=actions_search_var, width=20) actions_search_entry.pack(side=LEFT, padx=(0, 5)) - + actions_search_matches = [] actions_current_match_index = -1 - + def search_in_actions_log(direction=1): """在行为日志中搜索文本""" nonlocal actions_search_matches, actions_current_match_index - + search_text = actions_search_var.get().strip() if not search_text: actions_log_text.tag_remove("search_highlight", "1.0", "end") @@ -3701,61 +3701,61 @@ def main(): actions_search_matches = [] actions_current_match_index = -1 return - + content = actions_log_text.get("1.0", "end-1c") if not content: return - + actions_log_text.tag_remove("search_highlight", "1.0", "end") actions_log_text.tag_remove("search_current", "1.0", "end") - + actions_log_text.tag_config("search_highlight", background="yellow") actions_log_text.tag_config("search_current", background="orange") - + actions_search_matches = [] start_pos = 0 # 使用整数索引 search_text_lower = search_text.lower() content_lower = content.lower() - + while True: pos = content_lower.find(search_text_lower, start_pos) if pos == -1: break - + line_start = content[:pos].rfind("\n") + 1 line_num = content[:pos].count("\n") + 1 col_num = pos - line_start - + start_index = f"{line_num}.{col_num}" end_index = f"{line_num}.{col_num + len(search_text)}" - + actions_search_matches.append((start_index, end_index)) start_pos = pos + 1 - + if not actions_search_matches: actions_current_match_index = -1 return - + for start_idx, end_idx in actions_search_matches: actions_log_text.tag_add("search_highlight", start_idx, end_idx) - + if direction == 1: actions_current_match_index = (actions_current_match_index + 1) % len(actions_search_matches) else: actions_current_match_index = (actions_current_match_index - 1) % len(actions_search_matches) - + if actions_current_match_index >= 0: start_idx, end_idx = actions_search_matches[actions_current_match_index] actions_log_text.tag_add("search_current", start_idx, end_idx) actions_log_text.see(start_idx) actions_log_text.mark_set("insert", start_idx) - + def search_next_in_actions(): search_in_actions_log(1) - + def search_prev_in_actions(): search_in_actions_log(-1) - + def clear_search_in_actions(): nonlocal actions_search_matches, actions_current_match_index actions_search_var.set("") @@ -3763,13 +3763,13 @@ def main(): actions_log_text.tag_remove("search_current", "1.0", "end") actions_search_matches = [] actions_current_match_index = -1 - + def on_actions_search_entry_key(event): if event.keysym == "Return": search_next_in_actions() - + actions_search_entry.bind("", on_actions_search_entry_key) - + ttk.Button(actions_log_top, text="搜索", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2)) ttk.Button(actions_log_top, text="上一个", command=search_prev_in_actions).pack(side=LEFT, padx=(0, 2)) ttk.Button(actions_log_top, text="下一个", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2)) @@ -3829,41 +3829,41 @@ def main(): # 中奖记录显示 win_record_top = ttk.Frame(win_record_tab) win_record_top.pack(fill=X, padx=10, pady=(10, 0)) - + win_record_left = ttk.Frame(win_record_tab) win_record_left.pack(side=LEFT, fill=BOTH, expand=True, padx=(10, 5), pady=10) - + win_record_right = ttk.Frame(win_record_tab) win_record_right.pack(side=RIGHT, fill=BOTH, expand=False, padx=(5, 10), pady=10, ipadx=10) - + # 左侧:中奖截图列表 win_list_label = ttk.Label(win_record_left, text="中奖截图列表:") win_list_label.pack(anchor="w", padx=(0, 10), pady=(0, 5)) - + win_list_frame = ttk.Frame(win_record_left) win_list_frame.pack(fill=BOTH, expand=True) - + win_list_scrollbar = ttk.Scrollbar(win_list_frame) win_list_scrollbar.pack(side=RIGHT, fill=Y) - + win_listbox = tk.Listbox(win_list_frame, yscrollcommand=win_list_scrollbar.set, font=("Consolas", 9)) win_listbox.pack(side=LEFT, fill=BOTH, expand=True) win_list_scrollbar.config(command=win_listbox.yview) - + # 存储文件路径映射(索引 -> 文件路径) _win_file_paths: dict[int, str] = {} - + # 右侧:截图预览 win_preview_label = ttk.Label(win_record_right, text="截图预览:") win_preview_label.pack(anchor="w", pady=(0, 5)) - + win_preview_frame = ttk.Frame(win_record_right) win_preview_frame.pack(fill=BOTH, expand=True) - + win_image_label = ttk.Label(win_preview_frame) win_image_label.pack(fill=BOTH, expand=True) _win_img_ref: dict[str, Any] = {"photo": None} - + def scan_win_images(): """扫描中奖截图目录""" try: @@ -3872,10 +3872,10 @@ def main(): except Exception: import path_config pic_dir = path_config.get_pic_dir() - + prize_dir = os.path.join(pic_dir, "lottery_prize_captures") win_images = [] - + if os.path.exists(prize_dir): for file in os.listdir(prize_dir): if file.lower().endswith((".png", ".jpg", ".jpeg")): @@ -3886,18 +3886,18 @@ def main(): win_images.append((file, file_path, mtime)) except Exception: win_images.append((file, file_path, 0)) - + # 按时间倒序排序(最新的在前) win_images.sort(key=lambda x: x[2], reverse=True) return win_images - + def refresh_win_record(): """刷新中奖记录列表""" try: win_images = scan_win_images() win_listbox.delete(0, tk.END) _win_file_paths.clear() - + for idx, (file, file_path, mtime) in enumerate(win_images): # 格式化显示:文件名 + 时间 try: @@ -3907,25 +3907,25 @@ def main(): display_text = f"{file} ({time_str})" except Exception: display_text = file - + win_listbox.insert(tk.END, display_text) # 存储文件路径映射 _win_file_paths[idx] = file_path - + if win_images: on_line(f"[中奖记录] 扫描到 {len(win_images)} 张中奖截图") else: on_line("[中奖记录] 暂无中奖截图") except Exception as e: on_line(f"[中奖记录] 刷新失败:{e}") - + def on_win_list_select(event): """当选择中奖截图时,显示预览""" try: selection = win_listbox.curselection() if not selection: return - + index = selection[0] # 从映射中获取文件路径 if index in _win_file_paths: @@ -3933,14 +3933,14 @@ def main(): _load_win_image(file_path) except Exception as e: on_line(f"[中奖记录] 预览失败:{e}") - + def _load_win_image(img_path: str): """加载并显示中奖截图""" if not os.path.exists(img_path): win_image_label.configure(image="") _win_img_ref["photo"] = None return - + try: img = Image.open(img_path) img.load() @@ -3948,7 +3948,7 @@ def main(): except Exception as e: on_line(f"[中奖记录] 图片加载失败:{e}") return - + # 获取预览区域尺寸 try: win_preview_frame.update_idletasks() @@ -3958,24 +3958,24 @@ def main(): w, h = 400, 600 except Exception: w, h = 400, 600 - + max_w = max(200, w - 20) max_h = max(300, h - 20) - + try: resample = Image.Resampling.LANCZOS except AttributeError: resample = 1 - + img.thumbnail((max_w, max_h), resample) photo = ImageTk.PhotoImage(img) _win_img_ref["photo"] = photo win_image_label.configure(image=photo) - + win_listbox.bind("<>", on_win_list_select) - + ttk.Button(win_record_top, text="刷新列表", command=refresh_win_record).pack(side=LEFT, padx=(0, 10)) - + def open_win_folder(): """打开中奖截图目录""" try: @@ -3984,23 +3984,23 @@ def main(): except Exception: import path_config pic_dir = path_config.get_pic_dir() - + prize_dir = os.path.join(pic_dir, "lottery_prize_captures") os.makedirs(prize_dir, exist_ok=True) try: os.startfile(prize_dir) # type: ignore[attr-defined] except Exception as e: on_line(f"[中奖记录] 打开目录失败:{e}") - + ttk.Button(win_record_top, text="打开目录", command=open_win_folder).pack(side=LEFT) - + # 误识别记录管理 false_positive_frame = ttk.LabelFrame(win_record_right, text="误识别记录管理") false_positive_frame.pack(fill=X, pady=(10, 0)) - + false_positive_text = ScrolledText(false_positive_frame, height=6) false_positive_text.pack(fill=X, padx=10, pady=10) - + def load_false_positives(): """加载误识别记录""" try: @@ -4009,13 +4009,13 @@ def main(): except Exception: import path_config pic_dir = path_config.get_pic_dir() - + false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json") if not os.path.exists(false_positive_file): false_positive_text.delete("1.0", "end") false_positive_text.insert("1.0", "暂无误识别记录") return - + try: import json with open(false_positive_file, "r", encoding="utf-8") as f: @@ -4029,7 +4029,7 @@ def main(): except Exception as e: false_positive_text.delete("1.0", "end") false_positive_text.insert("1.0", f"加载失败:{e}") - + def save_false_positives(): """保存误识别记录""" try: @@ -4038,13 +4038,13 @@ def main(): except Exception: import path_config pic_dir = path_config.get_pic_dir() - + false_positive_file = os.path.join(pic_dir, "lottery_prize_captures", "false_positives.json") os.makedirs(os.path.dirname(false_positive_file), exist_ok=True) - + content = false_positive_text.get("1.0", "end-1c") lines = [line.strip() for line in content.splitlines() if line.strip()] - + try: import json with open(false_positive_file, "w", encoding="utf-8") as f: @@ -4052,12 +4052,12 @@ def main(): on_line(f"[中奖记录] 已保存 {len(lines)} 条误识别记录") except Exception as e: on_line(f"[中奖记录] 保存失败:{e}") - + false_positive_btn_frame = ttk.Frame(false_positive_frame) false_positive_btn_frame.pack(fill=X, padx=10, pady=(0, 10)) ttk.Button(false_positive_btn_frame, text="刷新", command=load_false_positives).pack(side=LEFT, padx=(0, 5)) ttk.Button(false_positive_btn_frame, text="保存", command=save_false_positives).pack(side=LEFT) - + load_false_positives() pump_logs() @@ -4113,4 +4113,4 @@ if __name__ == "__main__": print_version_banner("gui_app") except Exception: pass - main() \ No newline at end of file + main() diff --git a/gui/gui_core.py b/gui/gui_core.py index 833791c..80de512 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -101,7 +101,7 @@ class Runner: self._on_line = on_line self._reader_thread: Optional[threading.Thread] = None self._lock = threading.Lock() - + # 统计相关 self._start_ts: Optional[float] = None self._last_log_ts: Optional[float] = None @@ -123,11 +123,11 @@ class Runner: def is_running(self) -> bool: return self._proc is not None and self._proc.poll() is None - + def _inc(self, key: str, n: int = 1) -> None: with self._lock: self._counters[key] = int(self._counters.get(key, 0)) + int(n) - + def _record_event(self, typ: str, meta: Optional[dict] = None) -> None: ev = { "ts": time.time(), @@ -138,7 +138,7 @@ class Runner: self._events.append(ev) if len(self._events) > self._events_cap: self._events = self._events[-self._events_cap:] - + def _record_win(self) -> None: item = { "ts": time.time(), @@ -148,7 +148,7 @@ class Runner: self._wins.append(item) if len(self._wins) > self._wins_cap: self._wins = self._wins[-self._wins_cap:] - + def _snapshot_fudai(self) -> dict: with self._lock: return { @@ -158,15 +158,15 @@ class Runner: "copies": self._fudai_last.get("copies"), "prize_value_yuan": self._fudai_last.get("prize_value_yuan"), } - + def _update_stats_from_line(self, line: str) -> None: s = (line or "").strip() if not s: return - + with self._lock: self._last_log_ts = time.time() - + # --- 福袋:抽取"最近一次"识别到的信息 --- # 支持多种格式:旧格式"福袋内容:"和新格式"字段_内容="或"内容=" content_extracted = False @@ -183,11 +183,11 @@ class Runner: self._fudai_last["content"] = m.group(1).strip() self._fudai_last["updated_ts"] = time.time() content_extracted = True - + if content_extracted: self._inc("fudai_seen") self._record_event("fudai_seen", self._snapshot_fudai()) - + # 参与人数:支持多种格式 m = re.search(r"(?:字段_)?参与人数[=:]?\s*(\d+)", s) if not m: @@ -196,7 +196,7 @@ class Runner: with self._lock: self._fudai_last["participants"] = int(m.group(1)) self._fudai_last["updated_ts"] = time.time() - + # 福袋份数:支持多种格式 m = re.search(r"(?:字段_)?份数[=:]?\s*(\d+)", s) if not m: @@ -205,7 +205,7 @@ class Runner: with self._lock: self._fudai_last["copies"] = int(m.group(1)) self._fudai_last["updated_ts"] = time.time() - + # 倒计时:支持多种格式 if "倒计时时间:" in s: with self._lock: @@ -217,7 +217,7 @@ class Runner: with self._lock: self._fudai_last["countdown"] = m.group(1).strip() self._fudai_last["updated_ts"] = time.time() - + # 奖品价值:支持多种格式 m = re.search(r"(?:字段_)?(?:价值|价值元|奖品价值)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s) if not m: @@ -229,7 +229,7 @@ class Runner: self._fudai_last["updated_ts"] = time.time() except Exception: pass - + # --- 福袋:关键流程计数 --- if "点击打开福袋详情" in s or ("[流程]" in s and "检测到福袋图标并点击" in s): self._inc("fudai_open_detail") @@ -237,7 +237,7 @@ class Runner: if "点击参与抽奖" in s or ("[参与]" in s and ("动作=点击参与" in s or "动作=参与" in s)): self._inc("fudai_click_attend") self._record_event("fudai_click_attend", self._snapshot_fudai()) - + # 参与成功/已参与:支持更多格式 if ( "已经参与,等待开奖" in s @@ -252,7 +252,7 @@ class Runner: if "参与抽奖失败" in s or ("[参与]" in s and "结果=失败" in s): self._inc("fudai_attend_fail") self._record_event("fudai_attend_fail", self._snapshot_fudai()) - + # --- 福袋:跳过/过滤原因 --- if "参与人数" in s and "< 阈值" in s and "不参与" in s: self._inc("fudai_skip_participants_low") @@ -361,7 +361,7 @@ class Runner: except Exception: pass self._record_event("fudai_reserved_high_value", meta) - + # --- 错误和异常统计 --- if "[错误]" in s or "[异常]" in s or "错误=" in s or "异常=" in s: self._inc("error_total") @@ -398,37 +398,37 @@ class Runner: error_type = "Detection_Error" self._inc("error_detection") self._record_event("error", {"error_type": error_type}) - + # --- 阶段诊断错误 --- if "阶段诊断" in s and ("失败" in s or "错误" in s or "异常" in s): self._inc("error_stage_diagnosis") self._record_event("error_stage_diagnosis", {}) - + # --- 详情读取错误 --- if "读取福袋详情" in s and ("失败" in s or "错误" in s or "异常" in s): self._inc("error_read_detail") self._record_event("error_read_detail", {}) - + # --- 配置加载错误 --- if "load_config" in s and ("失败" in s or "错误" in s or "异常" in s): self._inc("error_config_load") self._record_event("error_config_load", {}) - + # --- 状态文件错误 --- if ("预约队列状态文件" in s or "reservations.json" in s) and ("失败" in s or "错误" in s): self._inc("error_state_file") self._record_event("error_state_file", {}) - + # --- 直播间检测错误 --- if "直播间检测" in s and ("失败" in s or "错误" in s): self._inc("error_live_room_detect") self._record_event("error_live_room_detect", {}) - + # --- 福袋查找错误 --- if "查找福袋" in s and ("失败" in s or "错误" in s or "未找到" in s): self._inc("error_fudai_find") self._record_event("error_fudai_find", {}) - + # --- 粉丝团门槛 --- if "需要加入粉丝团才能参与" in s or ("[参与]" in s and "结果=需要粉丝团" in s): self._inc("fansclub_required") @@ -439,7 +439,7 @@ class Runner: if "粉丝团门槛仍未解决" in s or ("[参与]" in s and "粉丝团门槛仍未解决" in s): self._inc("fansclub_unresolved") self._record_event("fansclub_unresolved", self._snapshot_fudai()) - + # --- 预约队列/回退校验 --- if ("[预约]" in s and "回退校验通过" in s) or "回退校验通过:已回到目标直播间" in s: self._inc("reservation_back_verify_ok") @@ -453,7 +453,7 @@ class Runner: if ("[预约]" in s and "清空预约队列" in s) or "清空预约队列" in s: self._inc("reservation_clear") self._record_event("reservation_clear", {}) - + # --- 预约记录相关 --- if ("[预约]" in s and "已记录高价值福袋" in s) or "record_high_value_reservation:已记录高价值福袋" in s: self._inc("reservation_recorded") @@ -534,7 +534,7 @@ class Runner: if ("[预约]" in s and "通过相似度匹配识别为重复预约" in s): self._inc("reservation_duplicate_detected") self._record_event("reservation_duplicate_detected", {}) - + # --- 开奖结果 --- if "没有抽中" in s and "关闭弹窗" in s: self._inc("fudai_result_no_win") @@ -564,7 +564,7 @@ class Runner: except Exception: pass self._record_event("fudai_waiting_lottery", meta) - + # --- 直播间切换(按原因粗分) --- if "上划切换直播间" in s or ("[操作]" in s and "上滑切换直播间" in s): self._inc("switch_room") @@ -594,7 +594,7 @@ class Runner: self._inc("switch_room_locked") meta_reason = "locked" self._record_event("switch_room", {"reason": meta_reason, **self._snapshot_fudai()}) - + # --- 阶段诊断统计 --- if "[阶段诊断]" in s or "阶段诊断" in s: if "阶段诊断完成" in s: @@ -620,7 +620,7 @@ class Runner: elif "阶段诊断失败" in s or "阶段诊断错误" in s: self._inc("stage_diagnosis_failed") self._record_event("stage_diagnosis_failed", {}) - + # --- OCR识别统计 --- if "[福袋]" in s and "OCR识别" in s: self._inc("ocr_attempt") @@ -628,7 +628,7 @@ class Runner: self._inc("ocr_success") elif "识别失败" in s or "识别错误" in s: self._inc("ocr_failed") - + # --- 性能统计 --- m = re.search(r"耗时[=:]?\s*([0-9]+(?:\.[0-9]+)?)\s*秒", s) if m: @@ -640,7 +640,7 @@ class Runner: self._record_event("slow_operation", {"elapsed_seconds": elapsed, "operation": s[:100]}) except Exception: pass - + # --- 详情识别统计 --- if ("[福袋详情]" in s and "识别" in s) or "识别福袋详情" in s: self._inc("fudai_detail_read_attempt") @@ -658,7 +658,7 @@ class Runner: elif "识别失败" in s or "识别错误" in s: self._inc("fudai_detail_read_failed") self._record_event("fudai_detail_read_failed", {}) - + # --- 福袋查找统计 --- if "[福袋查找]" in s or "查找福袋" in s: if "检测完成" in s and "命中" in s: @@ -667,7 +667,7 @@ class Runner: self._inc("fudai_find_not_found") elif "等待超时" in s: self._inc("fudai_find_timeout") - + # --- 回退操作统计 --- if ("[预约]" in s and "回退" in s) or "回退到" in s: if "回退完成" in s or "回退成功" in s: @@ -681,7 +681,7 @@ class Runner: except Exception: pass self._record_event("reservation_back_operation", meta) - + def get_stats(self) -> dict: with self._lock: running = self._proc is not None and self._proc.poll() is None @@ -693,12 +693,12 @@ class Runner: fudai_last = dict(self._fudai_last) wins = list(self._wins[-20:]) # 只返回最近20条 events = list(self._events[-1000:]) # 返回最近1000条事件用于统计 - + now = time.time() uptime = 0 if start_ts and start_ts > 0: uptime = int(max(0, now - start_ts)) - + return { "running": bool(running), "pid": pid, @@ -772,27 +772,27 @@ class Runner: cmd.append("--reservation-back-verify-disabled") if params.reservation_back_swipe_delay > 0: cmd += ["--reservation-back-swipe-delay", str(params.reservation_back_swipe_delay)] - + # 预约抢占最小价值 if params.reservation_preempt_min_value > 0: cmd += ["--reservation-preempt-min-value", str(params.reservation_preempt_min_value)] - + # 找福袋最大尝试次数 if params.fudai_find_max_attempts > 0: cmd += ["--fudai-find-max-attempts", str(params.fudai_find_max_attempts)] - + # OCR模式1开关 if params.enable_ocr_mode1: cmd.append("--enable-ocr-mode1") else: cmd.append("--disable-ocr-mode1") - + # 福袋模板匹配开关 if params.fudai_template_match_enabled: cmd.append("--fudai-template-enabled") else: cmd.append("--fudai-template-disabled") - + # 添加福袋模板匹配阈值参数 cmd.extend(["--fudai-template-threshold", str(params.fudai_template_match_threshold)]) @@ -832,7 +832,7 @@ class Runner: f"命令: {' '.join(cmd)}\n" f"工作目录: {path_config.PROJECT_ROOT}" ) - + with self._lock: self._proc = p self._pid = p.pid @@ -867,12 +867,12 @@ class Runner: self._update_stats_from_line(cleaned_line) except Exception: pass - + # 等待进程结束 rc = self._proc.wait() with self._lock: self._exit_code = rc - + # 如果进程立即退出且没有输出,说明可能有问题 if not has_output and rc != 0: self._on_line(f"[警告] 进程立即退出,退出码={rc},没有输出") @@ -897,13 +897,13 @@ class Runner: # (已移除) 测试养号启动器 # (已移除) 测试评论启动器 - + def send_back_key(self, device_id: str) -> bool: """手动发送返回键到指定设备。 - + Args: device_id: 设备ID,如果为空则使用第一个可用设备 - + Returns: True if successful, False otherwise """ @@ -912,7 +912,7 @@ class Runner: if not adb_exe: self._on_line("[错误] 未找到 adb.exe") return False - + # 如果没有指定设备ID,尝试获取第一个可用设备 if not device_id or device_id.strip() == "": devices = list_adb_devices(adb_exe) @@ -920,7 +920,7 @@ class Runner: self._on_line("[错误] 未找到可用设备") return False device_id = devices[0] - + # 发送返回键 (keyevent 4) cmd = [adb_exe, "-s", device_id, "shell", "input", "keyevent", "4"] proc = subprocess.run( @@ -931,7 +931,7 @@ class Runner: errors="replace", timeout=5.0, ) - + if proc.returncode == 0: self._on_line(f"[手动操作] 已发送返回键到设备: {device_id}") return True @@ -1001,6 +1001,3 @@ class Runner: with self._lock: self._proc = None self._pid = None - - - diff --git a/gui/web_components/__init__.py b/gui/web_components/__init__.py index 313a249..ce9fb82 100644 --- a/gui/web_components/__init__.py +++ b/gui/web_components/__init__.py @@ -2,54 +2,3 @@ 本目录包含从 web_gui.py 模块化后的Web GUI组件。 """ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gui/web_components/proc_runner.py b/gui/web_components/proc_runner.py index 1178dac..6e4a5d0 100644 --- a/gui/web_components/proc_runner.py +++ b/gui/web_components/proc_runner.py @@ -10,54 +10,3 @@ from __future__ import annotations from ..web_gui import ProcRunner __all__ = ["ProcRunner"] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gui/web_gui.py b/gui/web_gui.py index 3ffc942..e8af26a 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -267,7 +267,7 @@ class ProcRunner: self._current_trace_id = trace_id elif trace_id != 'N/A': self._current_trace_id = trace_id - + # 提取MDC信息 mdc_match = re.search(r'MDC:\s*([^|]+)', s) if mdc_match: @@ -294,7 +294,7 @@ class ProcRunner: self._fudai_last["content"] = m.group(1).strip() self._fudai_last["updated_ts"] = time.time() content_extracted = True - + if content_extracted: self._inc("fudai_seen") self._record_event("fudai_seen", self._snapshot_fudai()) @@ -483,7 +483,7 @@ class ProcRunner: except Exception: pass self._record_event("fudai_reserved_high_value", meta) - + # --- 错误和异常统计(与 gui_core.py 保持一致) --- if "[错误]" in s or "[异常]" in s or "错误=" in s or "异常=" in s: self._inc("error_total") @@ -519,7 +519,7 @@ class ProcRunner: error_type = "Detection_Error" self._inc("error_detection") self._record_event("error", {"error_type": error_type}) - + if "阶段诊断" in s and ("失败" in s or "错误" in s or "异常" in s): self._inc("error_stage_diagnosis") self._record_event("error_stage_diagnosis", {}) @@ -567,7 +567,7 @@ class ProcRunner: if ("[预约]" in s and "清空预约队列" in s) or "清空预约队列" in s: self._inc("reservation_clear") self._record_event("reservation_clear", {}) - + # --- 预约记录相关(与 gui_core.py 保持一致) --- if ("[预约]" in s and "已记录高价值福袋" in s) or "record_high_value_reservation:已记录高价值福袋" in s: self._inc("reservation_recorded") @@ -709,7 +709,7 @@ class ProcRunner: self._record_event( "switch_room", {"reason": meta_reason, **self._snapshot_fudai()} ) - + # --- 阶段诊断统计 --- if "[阶段诊断]" in s or "阶段诊断" in s: if "阶段诊断完成" in s: @@ -735,7 +735,7 @@ class ProcRunner: elif "阶段诊断失败" in s or "阶段诊断错误" in s: self._inc("stage_diagnosis_failed") self._record_event("stage_diagnosis_failed", {}) - + # --- OCR识别统计 --- if "[福袋]" in s and "OCR识别" in s: self._inc("ocr_attempt") @@ -743,7 +743,7 @@ class ProcRunner: self._inc("ocr_success") elif "识别失败" in s or "识别错误" in s: self._inc("ocr_failed") - + # --- 性能统计 --- m = re.search(r"耗时[=:]?\s*([0-9]+(?:\.[0-9]+)?)\s*秒", s) if m: @@ -755,7 +755,7 @@ class ProcRunner: self._record_event("slow_operation", {"elapsed_seconds": elapsed, "operation": s[:100]}) except Exception: pass - + # --- 详情识别统计 --- if ("[福袋详情]" in s and "识别" in s) or "识别福袋详情" in s: self._inc("fudai_detail_read_attempt") @@ -773,7 +773,7 @@ class ProcRunner: elif "识别失败" in s or "识别错误" in s: self._inc("fudai_detail_read_failed") self._record_event("fudai_detail_read_failed", {}) - + # --- 福袋查找统计 --- if "[福袋查找]" in s or "查找福袋" in s: if "检测完成" in s and "命中" in s: @@ -782,7 +782,7 @@ class ProcRunner: self._inc("fudai_find_not_found") elif "等待超时" in s: self._inc("fudai_find_timeout") - + # --- 回退操作统计 --- if ("[预约]" in s and "回退" in s) or "回退到" in s: if "回退完成" in s or "回退成功" in s: @@ -1040,7 +1040,7 @@ class ProcRunner: # 获取当前traceId和MDC上下文 current_trace_id = getattr(self, "_current_trace_id", None) mdc_context = dict(getattr(self, "_mdc_context", {})) - + payload = { "running": bool(running), "pid": pid, @@ -1271,21 +1271,21 @@ class ProcRunner: fudai_find_max_attempts = 0 if fudai_find_max_attempts > 0: cmd += ["--fudai-find-max-attempts", str(fudai_find_max_attempts)] - + # OCR模式1开关(命令行优先) enable_ocr_mode1 = bool(_pick("enable_ocr_mode1", False)) if enable_ocr_mode1: cmd.append("--enable-ocr-mode1") else: cmd.append("--disable-ocr-mode1") - + # 福袋模板匹配开关(命令行优先) fudai_template_match_enabled = bool(_pick("fudai_template_match_enabled", False)) if fudai_template_match_enabled: cmd.append("--fudai-template-enabled") else: cmd.append("--fudai-template-disabled") - + # 福袋模板匹配阈值(命令行优先) try: fudai_template_match_threshold = float(_pick("fudai_template_match_threshold", 0.7) or 0.7) diff --git a/install_scrcpy.bat b/install_scrcpy.bat deleted file mode 100644 index c4a481c..0000000 --- a/install_scrcpy.bat +++ /dev/null @@ -1,132 +0,0 @@ -@echo off -chcp 65001 >nul -echo ======================================== -echo scrcpy 一键安装脚本 -echo ======================================== -echo. - -REM 检查是否已安装 -where scrcpy >nul 2>&1 -if %errorlevel% == 0 ( - echo [INFO] 检测到 scrcpy 已安装 - scrcpy -v - echo. - echo 安装完成! - pause - exit /b 0 -) - -echo [1/4] 检查安装工具... - -REM 优先使用 winget -where winget >nul 2>&1 -if %errorlevel% == 0 ( - echo [INFO] 使用 winget 安装 scrcpy... - winget install --accept-source-agreements --accept-package-agreements Genymobile.scrcpy -e --silent - if %errorlevel% == 0 ( - echo [SUCCESS] winget 安装成功! - goto :verify - ) else ( - echo [WARN] winget 安装失败,尝试其他方式... - ) -) - -REM 尝试使用 Chocolatey -where choco >nul 2>&1 -if %errorlevel% == 0 ( - echo [INFO] 使用 Chocolatey 安装 scrcpy... - choco install scrcpy -y - if %errorlevel% == 0 ( - echo [SUCCESS] Chocolatey 安装成功! - goto :verify - ) else ( - echo [WARN] Chocolatey 安装失败,尝试其他方式... - ) -) - -REM 尝试使用 Scoop -where scoop >nul 2>&1 -if %errorlevel% == 0 ( - echo [INFO] 使用 Scoop 安装 scrcpy... - scoop install scrcpy - if %errorlevel% == 0 ( - echo [SUCCESS] Scoop 安装成功! - goto :verify - ) else ( - echo [WARN] Scoop 安装失败... - ) -) - -echo [ERROR] 未找到可用的包管理器(winget/choco/scoop) -echo. -echo 请手动安装 scrcpy: -echo 1. 访问 https://github.com/Genymobile/scrcpy/releases -echo 2. 下载最新版本的 scrcpy-win64-v*.zip -echo 3. 解压到任意目录 -echo 4. 将解压目录添加到系统 PATH 环境变量 -echo. -pause -exit /b 1 - -:verify -echo. -echo [2/4] 验证安装... - -REM 刷新环境变量(尝试从注册表读取) -call :refresh_path - -REM 等待一下让系统更新 PATH -timeout /t 2 /nobreak >nul - -REM 检查是否可用 -where scrcpy >nul 2>&1 -if %errorlevel% == 0 ( - echo [SUCCESS] scrcpy 已成功安装并可访问! - scrcpy -v - echo. - echo [3/4] 测试连接设备... - adb devices - echo. - echo [4/4] 安装完成! - echo. - echo 提示:如果 scrcpy 命令仍不可用,请: - echo 1. 关闭并重新打开命令提示符/PowerShell - echo 2. 或者重启计算机 - echo. -) else ( - echo [WARN] scrcpy 已安装但当前会话中不可用 - echo. - echo 请执行以下操作之一: - echo 1. 关闭并重新打开命令提示符/PowerShell - echo 2. 或者重启计算机 - echo. - echo 安装可能位于以下位置之一: - echo - %%LOCALAPPDATA%%\Programs\scrcpy\scrcpy.exe - echo - %%USERPROFILE%%\AppData\Local\Programs\scrcpy\scrcpy.exe - echo - C:\Program Files\scrcpy\scrcpy.exe - echo. -) - -pause -exit /b 0 - -:refresh_path -REM 尝试从注册表刷新 PATH(需要管理员权限) -REM 这里只是尝试,失败不影响 -reg query "HKCU\Environment" /v Path >nul 2>&1 -if %errorlevel% == 0 ( - for /f "tokens=2*" %%A in ('reg query "HKCU\Environment" /v Path 2^>nul') do set "USER_PATH=%%B" -) -goto :eof - - - - - - - - - - - - diff --git a/manage_logs.py b/manage_logs.py index eae5596..ff22fb0 100644 --- a/manage_logs.py +++ b/manage_logs.py @@ -249,14 +249,3 @@ def main(): if __name__ == "__main__": main() - - - - - - - - - - - diff --git a/operations/__init__.py b/operations/__init__.py index 3dcaf05..fac6d3c 100644 --- a/operations/__init__.py +++ b/operations/__init__.py @@ -43,4 +43,3 @@ __all__ = [ "_mirror_screenshot_to_external", "underlying_operations", ] - diff --git a/operations/device_operations.py b/operations/device_operations.py index 0e333b5..9bb955c 100644 --- a/operations/device_operations.py +++ b/operations/device_operations.py @@ -14,4 +14,3 @@ from Underlying_Operations import underlying_operations # 导出设备操作相关方法 # TODO: 实现这些函数后添加到__all__列表中 __all__ = [] - diff --git a/operations/image_operations.py b/operations/image_operations.py index 0974dce..15aaddb 100644 --- a/operations/image_operations.py +++ b/operations/image_operations.py @@ -14,4 +14,3 @@ from Underlying_Operations import underlying_operations # 导出图像处理相关方法 # TODO: 实现这些函数后添加到__all__列表中 __all__ = [] - diff --git a/operations/ocr_operations.py b/operations/ocr_operations.py index 324142d..e9bdf2d 100644 --- a/operations/ocr_operations.py +++ b/operations/ocr_operations.py @@ -7,7 +7,7 @@ from __future__ import annotations import os import contextlib -from typing import Any, Optional +from typing import Any # PaddleOCR 3.x 会在初始化/导入时进行模型源连通性检查;在国内网络环境下容易卡住。 # 这里提前设置环境变量,避免启动耗时/卡死。 @@ -46,7 +46,7 @@ class OCRProcessor: # 首先尝试EasyOCR try: # 在Windows上,避免使用stderr重定向,可能会导致"lost sys.stderr"问题 - import easyocr # type: ignore[import-untyped, import] # pyright: ignore[reportMissingImports, reportMissingModuleSource] + import easyocr # type: ignore[import-untyped, import] # pyright: ignore[reportMissingImports, reportMissingModuleSource] # pylint: disable=import-error # 只加载中文和英文,加快初始化速度 # 自动检测GPU可用性,如果可用则启用GPU加速 @@ -73,7 +73,7 @@ class OCRProcessor: with contextlib.redirect_stdout( devnull ), contextlib.redirect_stderr(devnull): - from paddleocr import PaddleOCR + from paddleocr import PaddleOCR # type: ignore # pylint: disable=import-error # 使用 PaddleOCR(强制 CPU 模式,不进行 GPU 检测) use_gpu = False @@ -117,7 +117,7 @@ class OCRProcessor: with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr( devnull ): - import easyocr # type: ignore[import-untyped] + import easyocr # type: ignore[import-untyped] # pylint: disable=import-error self.ocr = easyocr.Reader( ["ch_sim", "en"], gpu=False, verbose=False @@ -140,7 +140,7 @@ class OCRProcessor: with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr( devnull ): - from paddleocr import PaddleOCR + from paddleocr import PaddleOCR # type: ignore # pylint: disable=import-error # 使用 PaddleOCR(强制 CPU 模式) use_gpu = False @@ -171,6 +171,10 @@ class OCRProcessor: _ocr_processor = OCRProcessor() +# 全局OCR底层操作单例(延迟初始化) +_UNDERLYING_OPS_SINGLETON = None + + def _ensure_ocr(): @@ -221,4 +225,3 @@ __all__ = [ "extract_ocr_content", "_ensure_ocr", ] - \ No newline at end of file diff --git a/operations/scrcpy_screenshot.py b/operations/scrcpy_screenshot.py index 6a42a17..5aab0d7 100644 --- a/operations/scrcpy_screenshot.py +++ b/operations/scrcpy_screenshot.py @@ -17,22 +17,22 @@ from operations.screenshot_operations import ScreenshotOperations class ScrcpyScreenshot: """使用 scrcpy server 进行截图""" - + def __init__(self): self._scrcpy_path: Optional[str] = None self._server_path: Optional[str] = None self._find_scrcpy() - + def _find_scrcpy(self): """查找 scrcpy 可执行文件""" import shutil - + # 先检查 PATH which_path = shutil.which('scrcpy') if which_path: self._scrcpy_path = which_path return - + # 检查常见安装位置 candidates = [ os.path.join(os.getenv('LOCALAPPDATA', ''), 'Programs', 'scrcpy', 'scrcpy.exe'), @@ -40,7 +40,7 @@ class ScrcpyScreenshot: r'C:\Program Files\scrcpy\scrcpy.exe', r'C:\Program Files (x86)\scrcpy\scrcpy.exe', ] - + for path in candidates: if path and os.path.exists(path): self._scrcpy_path = path @@ -49,45 +49,45 @@ class ScrcpyScreenshot: if os.path.exists(server_path): self._server_path = server_path break - + def is_available(self) -> bool: """检查 scrcpy 是否可用""" return self._scrcpy_path is not None and os.path.exists(self._scrcpy_path) - + def get_screenshot(self, device_id: str, output_path: str) -> bool: """使用 scrcpy 进行截图 - + 注意:scrcpy 本身不直接支持单次截图,这里使用变通方法: 1. 启动 scrcpy server(如果支持) 2. 或使用 scrcpy 的录制功能提取帧 - + 参数: device_id: 设备ID output_path: 输出文件路径 - + 返回: 是否成功 """ if not self.is_available(): return False - + timetag = datetime.now().strftime("%H:%M:%S") start_time = time.time() - + try: # 方法1: 使用 scrcpy 的 --record 功能(需要停止机制,较复杂) # 方法2: 使用 scrcpy server 模式(推荐,但需要额外配置) # 方法3: 回退到 adb screencap(当前实现) - + # 由于 scrcpy 不直接支持单次截图,这里先记录日志 # 实际实现需要集成 scrcpy server 或使用第三方库 print(f"[{timetag}] [scrcpy] 注意: scrcpy 不直接支持单次截图") print(f"[{timetag}] [scrcpy] 需要使用 scrcpy server 模式或集成到截图流程") - + # 暂时回退到标准截图方法 ops = ScreenshotOperations() return ops._get_screenshot_direct(device_id, os.path.dirname(output_path)) - + except Exception as e: elapsed = (time.time() - start_time) * 1000 print(f"[{timetag}] [scrcpy] 截图失败: {e},耗时: {elapsed:.0f}ms") @@ -98,9 +98,3 @@ def get_scrcpy_screenshot(device_id: str, output_path: str) -> bool: """获取 scrcpy 截图(便捷函数)""" scrcpy = ScrcpyScreenshot() return scrcpy.get_screenshot(device_id, output_path) - - - - - - diff --git a/operations/screenshot_operations.py b/operations/screenshot_operations.py index 2cd70f1..0992494 100644 --- a/operations/screenshot_operations.py +++ b/operations/screenshot_operations.py @@ -44,12 +44,12 @@ class ScreenshotOperations: def get_screenshot(self, device_id, path="pic", use_service: bool = False) -> bool: """截图(支持后台服务模式) - + 参数: device_id: 设备ID path: 路径(默认"pic") use_service: 是否使用后台截图服务(默认True,可显著提升性能) - + 返回: 是否成功获取截图 """ @@ -78,10 +78,10 @@ class ScreenshotOperations: # 服务不可用时,回退到直接截图 timetag = datetime.now().strftime("%H:%M:%S") print(f"[{timetag}] [截图操作] ⚠️ 服务模式失败,回退到直接截图: {e}") - + # 原有的直接截图逻辑(保持向后兼容) return self._get_screenshot_direct(device_id, path) - + def _get_screenshot_direct(self, device_id, path="pic") -> bool: """直接截图(不使用服务模式)""" direct_start = time.time() @@ -310,7 +310,7 @@ class ScreenshotOperations: except Exception: import path_config pic_dir = path_config.get_pic_dir() - + search_dirs = [] if for_reading: # 读取时优先搜索当前目录的pic文件夹 @@ -383,4 +383,4 @@ __all__ = [ "_find_pic_path", "cut_pic", "save_reward_pic", -] \ No newline at end of file +] diff --git a/operations/screenshot_service.py b/operations/screenshot_service.py index 3eb16d6..b0c3272 100644 --- a/operations/screenshot_service.py +++ b/operations/screenshot_service.py @@ -68,19 +68,19 @@ class ScreenshotService: self._last_screenshot_time = time.time() - self._cache_valid_duration - 1.0 timetag = datetime.now().strftime("%H:%M:%S") print(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒") - + def stop(self): """停止后台截图服务""" with self._lock: if not self._running: return self._running = False - + if self._thread and self._thread.is_alive(): self._thread.join(timeout=2.0) timetag = datetime.now().strftime("%H:%M:%S") print(f"[{timetag}] [截图服务] 已停止后台截图服务") - + def _screenshot_loop(self): """后台截图循环""" loop_count = 0 @@ -90,14 +90,14 @@ class ScreenshotService: if not device_id: time.sleep(0.1) continue - + loop_count += 1 timetag = datetime.now().strftime("%H:%M:%S") screenshot_start = time.time() - + # 执行截图(禁用服务模式,避免递归) success = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type] - + screenshot_elapsed = (time.time() - screenshot_start) * 1000 if success: # 验证文件完整性后再更新时间戳(避免读取到不完整的文件) @@ -126,7 +126,7 @@ class ScreenshotService: else: self._last_success = False print(f"[{timetag}] [截图服务] 后台截图失败 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") - + # 等待间隔时间,确保不小于0.5秒 remaining_interval = max(0.5, self._screenshot_interval - screenshot_elapsed / 1000) time.sleep(remaining_interval) @@ -139,27 +139,27 @@ class ScreenshotService: except Exception: pass time.sleep(1.0) # 异常时等待1秒再继续 - + def get_screenshot(self, device_id: str, force: bool = False) -> bool: """获取截图(优先使用缓存) - + 参数: device_id: 设备ID force: 是否强制重新截图(忽略缓存) - + 返回: 是否成功获取截图 """ request_start = time.time() timetag = datetime.now().strftime("%H:%M:%S") - + # 如果设备ID不同,需要重新启动服务 if self._current_device_id != device_id: print(f"[{timetag}] [截图服务] 设备ID变更,重新启动服务: {device_id}") self.start(device_id) # 等待第一次截图完成 time.sleep(0.1) - + # 检查缓存是否有效 if not force: now = time.time() @@ -229,11 +229,11 @@ class ScreenshotService: print(f"[{timetag}] [截图服务] [WARN] 缓存文件不存在,等待后台截图") else: print(f"[{timetag}] [截图服务] [WARN] 缓存已过期 (距离上次: {time_since_last*1000:.0f}ms > {self._cache_valid_duration*1000:.0f}ms),等待后台截图") - + # 缓存无效或强制刷新 if force: print(f"[{timetag}] [截图服务] 🔄 强制刷新,忽略缓存") - + # 等待后台截图完成 if self._running: wait_start = time.time() @@ -244,7 +244,7 @@ class ScreenshotService: elif time_since_last_before_wait > 86400: time_since_last_before_wait = 10.0 print(f"[{timetag}] [截图服务] [WAIT] 缓存未命中,等待后台截图 (距离上次: {time_since_last_before_wait*1000:.0f}ms)") - + # 等待最多6秒,让后台线程完成截图(适应较慢的截图操作) max_wait_time = 6.0 while time.time() - wait_start < max_wait_time: @@ -273,11 +273,11 @@ class ScreenshotService: # 文件验证失败,继续等待 pass time.sleep(0.1) - + # 等待超时 wait_elapsed = (time.time() - wait_start) * 1000 print(f"[{timetag}] [截图服务] [TIMEOUT] 等待超时 ({wait_elapsed:.1f}ms),回退到直接截图") - + # 如果后台服务未运行或等待超时,直接执行截图(禁用服务模式,避免递归) direct_start = time.time() result = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type] @@ -286,15 +286,15 @@ class ScreenshotService: status = "[OK]" if result else "[FAIL]" print(f"[{timetag}] [截图服务] {status} 直接截图完成,耗时: {direct_elapsed:.0f}ms,总耗时: {total_elapsed:.1f}ms") return result - + def is_running(self) -> bool: """检查服务是否正在运行""" return self._running - + def get_last_screenshot_time(self) -> float: """获取最后一次截图的时间戳""" return self._last_screenshot_time - + def get_cache_info(self) -> dict: """获取缓存信息(用于调试)""" return { @@ -308,362 +308,31 @@ class ScreenshotService: def get_optimal_workers() -> int: - """根据CPU核心数获取最优线程数 - + """根据CPU核心数获取最优线程数,支持环境变量手动覆盖。 + + 环境变量: + FUDAI_OCR_WORKERS: 手动指定并行线程数,优先级最高。 返回: 推荐的线程数 """ + # 用户可通过环境变量强制指定线程数,便于在高核机器上做A/B测试 + try: + env_workers = int(os.environ.get("FUDAI_OCR_WORKERS", "")) + if env_workers >= 1: + # 线程数上限不超过并行OCR子任务数(6)再稍微放宽到8,避免极端过载 + return max(1, min(env_workers, 8)) + except ValueError: + pass + cpu_count = os.cpu_count() or 4 - - # 针对12核CPU的优化配置 + + # 默认策略:与子任务数(6)持平或略低,避免4核CPU过度抢占 if cpu_count >= 12: - return 10 # 12核:使用10个线程 - elif cpu_count >= 8: - return 8 # 8核:使用8个线程 - elif cpu_count >= 4: - return 6 # 4核:使用6个线程 - elif cpu_count >= 2: - return 3 # 2核:使用3个线程 - else: - return 2 # 单核:使用2个线程(I/O等待) - - - - -"""后台截图服务:持续截图,主流程直接读取最新截图 - -功能: -1. 后台持续截图,避免主流程等待 -2. 截图缓存机制,减少重复截图 -3. 智能线程数配置,根据CPU核心数自动调整 -""" - -from __future__ import annotations - -import os -import threading -import time -from typing import Optional -from datetime import datetime -import path_config -from operations.screenshot_operations import ScreenshotOperations - - -class ScreenshotService: - """后台截图服务:持续截图,避免主流程等待""" - - _instance: Optional['ScreenshotService'] = None - _lock = threading.Lock() - - def __init__(self): - self._running: bool = False - self._thread: Optional[threading.Thread] = None - self._screenshot_ops: ScreenshotOperations = ScreenshotOperations() - self._current_device_id: Optional[str] = None - # 修复:初始化为过去时间,确保第一次请求时缓存过期但时间差合理 - self._last_screenshot_time = time.time() - 10.0 # 10秒前,避免巨大时间差 - self._screenshot_interval = 3.5 # 增加间隔到3.5秒,适应实际截图耗时 - self._cache_valid_duration = 4.0 # 增加缓存有效期到4.0秒,避免频繁过期 - self._screenshot_path: Optional[str] = None - self._last_success = False # 最后一次截图是否成功 - - @classmethod - def get_instance(cls) -> 'ScreenshotService': - """获取单例实例""" - if cls._instance is None: - with cls._lock: - if cls._instance is None: - cls._instance = cls() - return cls._instance - - def start(self, device_id: str, interval: float = 1.5): - """启动后台截图服务 - - 参数: - device_id: 设备ID - interval: 截图间隔(秒),默认1.5秒 - """ - with self._lock: - if self._running: - if self._current_device_id == device_id: - return # 已经在运行,且设备ID相同 - self.stop() # 设备ID不同,先停止 - - self._current_device_id = device_id - self._screenshot_interval = max(0.5, interval) # 最小0.5秒 - self._running = True - - # 初始化截图路径 - try: - self._screenshot_path = path_config.get_screenshot_path() - except (ImportError, AttributeError, OSError): - self._screenshot_path = os.path.join("pic", "screenshot.png") - - self._thread = threading.Thread( - target=self._screenshot_loop, - daemon=True, - name="ScreenshotService" - ) - self._thread.start() - # 修复:设置时间戳为过去足够长的时间,确保第一次请求能等到后台截图完成 - self._last_screenshot_time = time.time() - self._cache_valid_duration - 1.0 # 确保缓存过期但不至于太旧 - timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒") - - def stop(self): - """停止后台截图服务""" - with self._lock: - if not self._running: - return - self._running = False - - if self._thread and self._thread.is_alive(): - self._thread.join(timeout=2.0) - timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 已停止后台截图服务") - - def _screenshot_loop(self): - """后台截图循环""" - loop_count = 0 - while self._running: - try: - device_id = self._current_device_id - if not device_id: - time.sleep(0.1) - continue - - loop_count += 1 - timetag = datetime.now().strftime("%H:%M:%S") - screenshot_start = time.time() - - # 执行截图(禁用服务模式,避免递归) - success = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type] - - screenshot_elapsed = (time.time() - screenshot_start) * 1000 - if success: - # 验证文件完整性后再更新时间戳(避免读取到不完整的文件) - if self._screenshot_path and os.path.exists(self._screenshot_path): - try: - file_size = os.path.getsize(self._screenshot_path) - if file_size >= 1024: - with open(self._screenshot_path, 'rb') as f: - header = f.read(4) - if header == b'\x89PNG': - self._last_screenshot_time = time.time() - self._last_success = True - print(f"[{timetag}] [截图服务] 后台截图完成 #{loop_count},耗时: {screenshot_elapsed:.0f}ms,文件大小: {file_size/1024:.1f}KB") - else: - self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件格式错误 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") - else: - self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件太小 #{loop_count} ({file_size}B),耗时: {screenshot_elapsed:.0f}ms") - except (OSError, IOError, ValueError) as e: - self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件验证失败 #{loop_count}: {e},耗时: {screenshot_elapsed:.0f}ms") - else: - self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件不存在 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") - else: - self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图失败 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") - - # 等待间隔时间,确保不小于0.5秒 - remaining_interval = max(0.5, self._screenshot_interval - screenshot_elapsed / 1000) - time.sleep(remaining_interval) - except Exception as e: - try: - timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 后台截图异常: {e}") - import traceback - traceback.print_exc() - except Exception: - pass - time.sleep(1.0) # 异常时等待1秒再继续 - - def get_screenshot(self, device_id: str, force: bool = False) -> bool: - """获取截图(优先使用缓存) - - 参数: - device_id: 设备ID - force: 是否强制重新截图(忽略缓存) - - 返回: - 是否成功获取截图 - """ - request_start = time.time() - timetag = datetime.now().strftime("%H:%M:%S") - - # 如果设备ID不同,需要重新启动服务 - if self._current_device_id != device_id: - print(f"[{timetag}] [截图服务] 设备ID变更,重新启动服务: {device_id}") - self.start(device_id) - # 等待第一次截图完成 - time.sleep(0.1) - - # 检查缓存是否有效 - if not force: - now = time.time() - time_since_last = now - self._last_screenshot_time - - # 修复:添加边界检查,避免负数或异常值 - if time_since_last < 0: - time_since_last = 0 # 避免时钟回拨导致的负数 - elif time_since_last > 86400: # 如果超过24小时,可能是时间戳错误 - time_since_last = 10.0 # 重置为10秒前 - - # 检查缓存是否有效(时间 + 文件存在 + 文件完整性) - if time_since_last < self._cache_valid_duration: - if self._screenshot_path and os.path.exists(self._screenshot_path): - # 验证文件完整性(避免读取到不完整的文件) - # 使用重试机制,等待文件写入完成 - for retry in range(3): - try: - file_size = os.path.getsize(self._screenshot_path) - if file_size >= 1024: # PNG文件至少1KB - # 尝试快速验证文件头(PNG文件头:89 50 4E 47) - with open(self._screenshot_path, 'rb') as f: - header = f.read(4) - if header == b'\x89PNG': - # 验证文件尾(PNG文件尾:IEND) - # 更宽松的验证:检查文件末尾50字节内是否有IEND - try: - # 读取文件末尾50字节 - read_size = min(50, file_size) - f.seek(-read_size, 2) - footer = f.read(read_size) - if b'IEND' in footer: - elapsed = (time.time() - request_start) * 1000 - print(f"[{timetag}] [截图服务] [OK] 缓存命中,耗时: {elapsed:.1f}ms (距离上次截图: {time_since_last*1000:.0f}ms, 文件大小: {file_size/1024:.1f}KB)") - return True - elif retry < 2: - # 文件可能还在写入,等待一下 - time.sleep(0.1) - continue - else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件不完整(文件尾验证失败),等待后台截图") - except (OSError, IOError) as e: - if retry < 2: - time.sleep(0.1) - continue - else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件读取失败: {e},等待后台截图") - else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件格式错误,等待后台截图") - break - else: - if retry < 2: - time.sleep(0.05) - continue - else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件太小 ({file_size}B),等待后台截图") - except (OSError, IOError) as e: - if retry < 2: - time.sleep(0.05) - continue - else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件检查失败: {e},等待后台截图") - except ValueError as e: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件检查异常: {e},等待后台截图") - break - else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件不存在,等待后台截图") - else: - print(f"[{timetag}] [截图服务] [WARN] 缓存已过期 (距离上次: {time_since_last*1000:.0f}ms > {self._cache_valid_duration*1000:.0f}ms),等待后台截图") - - # 缓存无效或强制刷新 - if force: - print(f"[{timetag}] [截图服务] 强制刷新,忽略缓存") - - # 等待后台截图完成 - if self._running: - wait_start = time.time() - time_since_last_before_wait = time.time() - self._last_screenshot_time - # 修复:添加边界检查 - if time_since_last_before_wait < 0: - time_since_last_before_wait = 0 - elif time_since_last_before_wait > 86400: - time_since_last_before_wait = 10.0 - print(f"[{timetag}] [截图服务] [WAIT] 缓存未命中,等待后台截图 (距离上次: {time_since_last_before_wait*1000:.0f}ms)") - - # 等待最多6秒,让后台线程完成截图(适应较慢的截图操作) - max_wait_time = 6.0 - while time.time() - wait_start < max_wait_time: - if self._last_screenshot_time > wait_start - 0.1: - # 截图已完成,验证文件完整性 - if self._screenshot_path and os.path.exists(self._screenshot_path): - try: - file_size = os.path.getsize(self._screenshot_path) - if file_size >= 1024: - with open(self._screenshot_path, 'rb') as f: - header = f.read(4) - if header == b'\x89PNG': - # 验证文件尾(更宽松的验证) - read_size = min(50, file_size) - f.seek(-read_size, 2) - footer = f.read(read_size) - if b'IEND' in footer: - wait_elapsed = (time.time() - wait_start) * 1000 - total_elapsed = (time.time() - request_start) * 1000 - status = "[OK]" if self._last_success else "[FAIL]" - print(f"[{timetag}] [截图服务] {status} 后台截图完成,等待耗时: {wait_elapsed:.1f}ms,总耗时: {total_elapsed:.1f}ms,文件大小: {file_size/1024:.1f}KB") - return self._last_success - # 文件尾验证失败,继续等待 - # 文件太小或格式错误,继续等待 - except (OSError, IOError, ValueError): - # 文件验证失败,继续等待 - pass - time.sleep(0.1) - - # 等待超时 - wait_elapsed = (time.time() - wait_start) * 1000 - print(f"[{timetag}] [截图服务] [TIMEOUT] 等待超时 ({wait_elapsed:.1f}ms),回退到直接截图") - - # 如果后台服务未运行或等待超时,直接执行截图(禁用服务模式,避免递归) - direct_start = time.time() - result = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type] - direct_elapsed = (time.time() - direct_start) * 1000 - total_elapsed = (time.time() - request_start) * 1000 - status = "[OK]" if result else "[FAIL]" - print(f"[{timetag}] [截图服务] {status} 直接截图完成,耗时: {direct_elapsed:.0f}ms,总耗时: {total_elapsed:.1f}ms") - return result - - def is_running(self) -> bool: - """检查服务是否正在运行""" - return self._running - - def get_last_screenshot_time(self) -> float: - """获取最后一次截图的时间戳""" - return self._last_screenshot_time - - def get_cache_info(self) -> dict: - """获取缓存信息(用于调试)""" - return { - "running": self._running, - "device_id": self._current_device_id, - "last_screenshot_time": self._last_screenshot_time, - "interval": self._screenshot_interval, - "cache_valid_duration": self._cache_valid_duration, - "last_success": self._last_success, - } - - -def get_optimal_workers() -> int: - """根据CPU核心数获取最优线程数 - - 返回: - 推荐的线程数 - """ - cpu_count = os.cpu_count() or 4 - - # 针对12核CPU的优化配置 - if cpu_count >= 12: - return 10 # 12核:使用10个线程 - elif cpu_count >= 8: - return 8 # 8核:使用8个线程 - elif cpu_count >= 4: - return 6 # 4核:使用6个线程 - elif cpu_count >= 2: - return 3 # 2核:使用3个线程 - else: - return 2 # 单核:使用2个线程(I/O等待) + return 8 + if cpu_count >= 8: + return 5 + if cpu_count >= 4: + return 4 + if cpu_count >= 2: + return 3 + return 2 diff --git a/operations/screenshot_service_new.py b/operations/screenshot_service_new.py index e1f23f3..73d22f4 100644 --- a/operations/screenshot_service_new.py +++ b/operations/screenshot_service_new.py @@ -132,5 +132,3 @@ def get_optimal_workers() -> int: if cpu_count >= 2: return 3 return 2 - - diff --git a/path_config.py b/path_config.py index 15e029f..c5861ca 100644 --- a/path_config.py +++ b/path_config.py @@ -93,7 +93,7 @@ def get_webui_dir() -> str: def get_pic_file_path(filename: str) -> str: """获取 pic 目录下指定文件的路径 - + Args: filename: 文件名,可以是子目录/文件名,如 'diag_live_plaza.png' 或 'start/latest.png' """ @@ -102,7 +102,7 @@ def get_pic_file_path(filename: str) -> str: def get_cut_pic_path(cut_pic_name: str) -> str: """获取裁剪后的图片路径(用于OCR) - + Args: cut_pic_name: 图片名称(不含扩展名),如 '直播广场' """ @@ -116,7 +116,7 @@ def get_window_dump_path() -> str: def get_robot_verify_pic_path(save_subdir: bool = False) -> str: """返回机器人验证图片的路径 - + Args: save_subdir: 是否在 pic/save 子目录中 """ @@ -185,74 +185,3 @@ def find_executable(cmd: str) -> Optional[str]: pass return None - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..58a8f83 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,11 @@ +[tool.pylint.messages_control] +disable = [ + "broad-except", + "protected-access", + "unused-import", + "unused-variable", + "reimported", + "redefined-outer-name", + "pointless-string-statement", + "unreachable" +] \ No newline at end of file diff --git a/pyright_out.txt b/pyright_out.txt deleted file mode 100644 index aa682cc2cb83cf8b82a817ba33f226972d76b43e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 7720 zcmeHM&rcIk5FR4YXkt8g^B@gL6D45i52*HnBwRcxA`qmtDW$(C-8S7Vv=I0ci(p2?wjw;eDh}B=C1&` z$wPyrQjk(Od&ow1a*-2f5B1@xN-@$XK}od7aZOW}qNI?I!npU-1X>*w#~nZ2F2k)L zdIu?ha}>RIO89n>xP)(I=`@`p3yy<3LN~DLrcNN`rYjg}2Y!rV3VNpS%tGsW-{-mX za{Ty6-qNfTkqAO-9}rWZr#06@7a$*m*4$6SY$yVikU*4Whaj6m%THr83CW9x3>`ag zsve(=>9OgCl{l%(5StbyAS@&Z%TOr-JJDc2QFvY0^ccAWM#lbiOqqfwn%$cijc({^ zcDz9f-xR1le35V<-2N@TJPf{YWZ zKx3BKicH4z{3~sys{(G>X)|VzOg1o#8(d=?r&|?Xz4)RtD!b!41*aQRFMgecm`aGs_;$T)COsdmfM;9|ap| zuo4d}R>2|HK5R#_e&dHl*WdH29}C-xQ&^01S4Nh;em(hdFmE}lM4_QZqoQ&d6IxE= z>=nNKVlkq(k1oYV^rtsgLO1nKgU<$XV1w)tN${!=k@jhcOfLQJt>VT_o0nIKoKp{pE}5M)UursZn7_?+7zu>;9_ MxrN<{9 diff --git a/pyright_output.txt b/pyright_output.txt deleted file mode 100644 index 7e00fa9ae01e1baa757a33cfa535b658bcbe3133..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 26618 zcmeHQ+iw(A7(XB(BJs(@L=$1tWCJFG&{A5OU?o8!1_2Qzgu-TNw`DCeyXA)@L6KPxOIAUwksgD8vWj7u zF@?Xg;vF1q5C;C@S@%6-VjNGD@Gb8188L}xC*(65@y%87qify3I zX0a9H+JJwgP)W{b1V^{(JMUbYnKf1(o=dGY$K@<@pg>uiz&#bvN73{&=rWFHd93JI z#L{BsaHdxtXplGwnHLK<^nj#{%Y`Vg zm%aPk@k=u)4-fZ)mu39qCC93gr^j(_M$)P`{5*;GPvM7BHPwJb_tlIz1BuH5la$g@ zm$~a6i&tm3uj)rS0==~bd>#PLb*Q~}>FQk2i-#_bNrwS|J* zpfQEVZacG%8^3-t>jc5=%v0x0#fxIUnJ;!64@n#kM}lJ&IZOh_C7Bm6=i}cBjwuDx zu)&Nh_RHVi`wqJ9(n&zK{OPdc3y<|EDHFF22s8Um^g)!g&`C+WdLj&U7PrnAL|%;f zu>s`CbdmPA^)E`N&%ReVbm*TG_b&ZeoJ;*`=pyEH?N;HF>0`w&amULm=2A}~KBeED z6KAE~C_eNFoYEHV{+k8E+%Vf1H8In}yqe1L)y zkk~Yz7u3fpjokRru%i)Y#Np+DrLUOX&mr>?tflO`mKOC{Q}WNsHd6l=V4*Qj<460` z@GG5ll3*S*-o4a#(VE>(ctJbh&TEc6%qwIVkF4C~ z;oy^QbvykkQ(7h^BXQg{RJYh=bOZeO?vvWD|0{+f|qP)90Pifw}1Lvyv zeZg^WN^Ex=@kw?CnDULRs`9y=QXVVfh?LEe{C@RaM{(8v+w76C%38o^8sp-|e8DLA z${+h_YhF$~EFB8jGYvx*))C*RU%T?zWPa-F+|!17x(_m=IM65R#^=Xa>l}S3FFg1D z(bWgH742*Zzem+1mm}uW^DbTc!=S9>q^5HBODv4)SM->rr_>Cy3a^I5&H=3!+b!{B zIAr`FDq=+-BnOmPydoND4N4xA=`t!|aI^nKCAPfvVjlL} zz0w|T^nUW+8hxE8@qceHZtfeMaWq}KZ3OYFRlLP*)hVf2WQQ92$?PlLwb=H1y;j=3 zqDI8%XGjbKv4e<3b>3dO_KfT!vplsDX8UM%9NBaCr%DEWa`Yf3q(-j5)<6)lH>?_haMthD7-2hmb_ zu723o%VlDvEx%UDBWXC))JnVMF`=Q8hTEi#Vef$+)0P}2o{s9V;@T?8o}wG;4SKp+ zUUot^C*2sStLVhfL)6Jz;vwoHdzJSfHHVvOK&KQY)byt&>$t7y!o=V9;+r%aZYcsx zXy~RPSI7osA1obdRsC2SV9qGX-H>XEdd(%U7u1VBpU*YpdDP)K8v}8_s_n5B%(dr~ zEB9*43^Jv8oIfM4#hu%aVsu<>Oe@##W997XlU;o#8rZqleC6nQT3d7UR>YdWk39puuapJL zu9A#}geLzHu~NoJd9#mIR^5V!E4vp8EdHbnP+Z#Z0+#!W8;Cl&<7H3hX53 z-W06DF!QbYW8K_(9rvj<`&=KtdtNWG`c?+o;@g>`U5-(=sD8?R9}1;w%hB_dg|20- zX;N07EP8YGcLkc4pN~?_seNj(?z%~8WWOk`m(+^h#Fq-E?f;wLU7vF=nImJ^0*%#obYuuH7vBo4-}xbtijj{p`I1fBm+ves|M1 zcMhYo%&o(BK(cAq!>#G*J+~}ma;F&j!R*RfXuR_uBddI@I1k`QkGwU~{!qu*JN9It zbJ&T@oub$sL5s~*SBn*qHvQDTPYaj7&hfEA!T80WxAdUd)4~XzHibKnJUTp7ou-U7 zl~>6A<#U(;fMSaZXE z?A>A?_~~AiNjy8f>KW-pIJ>3owPt?zF3fcUlzsLd>m)*N$?*22GP-Qs%hF#mxaNhvumL%7>c!qkLGXwY zYtTB!i?IJn6OhB~Q=0(SyUF385m*>*B}>+4PGe4LzTrjI~$-pzD_SF^%owV?jWLwAQZJeopwOqwsv<>Ev#W z;;OFE8O7Cp1**qM?SiYLtoN?PLP18&T$LHlBmc=@jKcNmT&e5!$iqvYz2a^u%dU!r zqM^K3I`tIx-nCd{xV4z#He~oX^eI>7CKBx4E4?-C%Px!Xv0M<{y^^_fYY-4F>9mnlw`+4;u%Kse~`2% z%j^V=iUYlq>3FS!vtDV($-TD~t&fX!Xs*SfFQ8vd(wIXC@&{I#`f3QzM`85`VdtFx i2TfV-k;9IbGw?%7h!fRLRQ7ou+r1rDHLEN;n*IkTP;dkQ diff --git a/config/pyrightconfig.json b/pyrightconfig.json similarity index 82% rename from config/pyrightconfig.json rename to pyrightconfig.json index 5ac3e26..f7d08d7 100644 --- a/config/pyrightconfig.json +++ b/pyrightconfig.json @@ -8,8 +8,8 @@ "reportOptionalMemberAccess": false, "reportOptionalSubscript": false, "reportPrivateImportUsage": false, - "reportUnusedImport": "warning", - "reportUnusedVariable": "warning", + "reportUnusedImport": "none", + "reportUnusedVariable": "none", "reportUnusedArgument": "none", "reportUnknownArgumentType": false, "reportUnknownLambdaType": false, @@ -25,7 +25,10 @@ "reportUnusedClass": "none", "reportUnusedFunction": "none", "reportUnusedCoroutine": "none", - "reportDuplicateImport": "warning", + "reportDuplicateImport": "none", + "reportUnusedExpression": "none", + "reportUnreachable": "none", + "reportPossiblyUnboundVariable": "none", "reportWildcardImportFromLibrary": false, "reportAbstractUsage": false, "reportArgumentType": false, @@ -49,6 +52,15 @@ "reportTooBroadExceptionType": false, "typeCheckingMode": "basic", "stubPath": "./typings", - "include": ["."], - "exclude": ["**/node_modules", "**/__pycache__", "**/.*"] -} + "include": [ + "." + ], + "exclude": [ + "**/node_modules", + "**/__pycache__", + "**/.*", + "deleted_tests_backup/**", + "logs/**", + "pic/**" + ] +} \ No newline at end of file diff --git a/restore_screenshot_service.py b/restore_screenshot_service.py index b1bab9b..afd91ef 100644 --- a/restore_screenshot_service.py +++ b/restore_screenshot_service.py @@ -25,10 +25,10 @@ from operations.screenshot_operations import ScreenshotOperations class ScreenshotService: """后台截图服务:持续截图,避免主流程等待""" - + _instance: Optional['ScreenshotService'] = None _lock = threading.Lock() - + def __init__(self): self._running: bool = False self._thread: Optional[threading.Thread] = None @@ -40,7 +40,7 @@ class ScreenshotService: self._cache_valid_duration = 4.0 # 增加缓存有效期到4.0秒,避免频繁过期 self._screenshot_path: Optional[str] = None self._last_success = False # 最后一次截图是否成功 - + @classmethod def get_instance(cls) -> 'ScreenshotService': """获取单例实例""" @@ -49,10 +49,10 @@ class ScreenshotService: if cls._instance is None: cls._instance = cls() return cls._instance - + def start(self, device_id: str, interval: float = 1.5): """启动后台截图服务 - + 参数: device_id: 设备ID interval: 截图间隔(秒),默认1.5秒 @@ -62,17 +62,17 @@ class ScreenshotService: if self._current_device_id == device_id: return # 已经在运行,且设备ID相同 self.stop() # 设备ID不同,先停止 - + self._current_device_id = device_id self._screenshot_interval = max(0.5, interval) # 最小0.5秒 self._running = True - + # 初始化截图路径 try: self._screenshot_path = path_config.get_screenshot_path() except (ImportError, AttributeError, OSError): self._screenshot_path = os.path.join("pic", "screenshot.png") - + self._thread = threading.Thread( target=self._screenshot_loop, daemon=True, @@ -83,19 +83,19 @@ class ScreenshotService: self._last_screenshot_time = time.time() - self._cache_valid_duration - 1.0 # 确保缓存过期但不至于太旧 timetag = datetime.now().strftime("%H:%M:%S") print(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒") - + def stop(self): """停止后台截图服务""" with self._lock: if not self._running: return self._running = False - + if self._thread and self._thread.is_alive(): self._thread.join(timeout=2.0) timetag = datetime.now().strftime("%H:%M:%S") print(f"[{timetag}] [截图服务] 已停止后台截图服务") - + def _screenshot_loop(self): """后台截图循环""" loop_count = 0 @@ -105,14 +105,14 @@ class ScreenshotService: if not device_id: time.sleep(0.1) continue - + loop_count += 1 timetag = datetime.now().strftime("%H:%M:%S") screenshot_start = time.time() - + # 执行截图(禁用服务模式,避免递归) success = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type] - + screenshot_elapsed = (time.time() - screenshot_start) * 1000 if success: # 验证文件完整性后再更新时间戳(避免读取到不完整的文件) @@ -141,7 +141,7 @@ class ScreenshotService: else: self._last_success = False print(f"[{timetag}] [截图服务] 后台截图失败 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") - + # 等待间隔时间,确保不小于0.5秒 remaining_interval = max(0.5, self._screenshot_interval - screenshot_elapsed / 1000) time.sleep(remaining_interval) @@ -154,27 +154,27 @@ class ScreenshotService: except Exception: pass time.sleep(1.0) # 异常时等待1秒再继续 - + def get_screenshot(self, device_id: str, force: bool = False) -> bool: """获取截图(优先使用缓存) - + 参数: device_id: 设备ID force: 是否强制重新截图(忽略缓存) - + 返回: 是否成功获取截图 """ request_start = time.time() timetag = datetime.now().strftime("%H:%M:%S") - + # 如果设备ID不同,需要重新启动服务 if self._current_device_id != device_id: print(f"[{timetag}] [截图服务] 设备ID变更,重新启动服务: {device_id}") self.start(device_id) # 等待第一次截图完成 time.sleep(0.1) - + # 检查缓存是否有效 if not force: now = time.time() @@ -244,11 +244,11 @@ class ScreenshotService: print(f"[{timetag}] [截图服务] [WARN] 缓存文件不存在,等待后台截图") else: print(f"[{timetag}] [截图服务] [WARN] 缓存已过期 (距离上次: {time_since_last*1000:.0f}ms > {self._cache_valid_duration*1000:.0f}ms),等待后台截图") - + # 缓存无效或强制刷新 if force: print(f"[{timetag}] [截图服务] 强制刷新,忽略缓存") - + # 等待后台截图完成 if self._running: wait_start = time.time() @@ -259,7 +259,7 @@ class ScreenshotService: elif time_since_last_before_wait > 86400: time_since_last_before_wait = 10.0 print(f"[{timetag}] [截图服务] [WAIT] 缓存未命中,等待后台截图 (距离上次: {time_since_last_before_wait*1000:.0f}ms)") - + # 等待最多6秒,让后台线程完成截图(适应较慢的截图操作) max_wait_time = 6.0 while time.time() - wait_start < max_wait_time: @@ -288,11 +288,11 @@ class ScreenshotService: # 文件验证失败,继续等待 pass time.sleep(0.1) - + # 等待超时 wait_elapsed = (time.time() - wait_start) * 1000 print(f"[{timetag}] [截图服务] [TIMEOUT] 等待超时 ({wait_elapsed:.1f}ms),回退到直接截图") - + # 如果后台服务未运行或等待超时,直接执行截图(禁用服务模式,避免递归) direct_start = time.time() result = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type] @@ -301,15 +301,15 @@ class ScreenshotService: status = "[OK]" if result else "[FAIL]" print(f"[{timetag}] [截图服务] {status} 直接截图完成,耗时: {direct_elapsed:.0f}ms,总耗时: {total_elapsed:.1f}ms") return result - + def is_running(self) -> bool: """检查服务是否正在运行""" return self._running - + def get_last_screenshot_time(self) -> float: """获取最后一次截图的时间戳""" return self._last_screenshot_time - + def get_cache_info(self) -> dict: """获取缓存信息(用于调试)""" return { @@ -324,12 +324,12 @@ class ScreenshotService: def get_optimal_workers() -> int: """根据CPU核心数获取最优线程数 - + 返回: 推荐的线程数 """ cpu_count = os.cpu_count() or 4 - + # 针对12核CPU的优化配置 if cpu_count >= 12: return 10 # 12核:使用10个线程 @@ -348,7 +348,3 @@ with open('operations/screenshot_service.py', 'w', encoding='utf-8') as f: f.write(content) print('ScreenshotService file restored successfully') - - - - diff --git a/run_test.py b/run_test.py index a316d1f..8123b96 100644 --- a/run_test.py +++ b/run_test.py @@ -14,7 +14,7 @@ if os.path.exists(target_dir): if "152118" in f and "福袋倒计时_分钟" in f and "识别后" in f and "390,1110" in f: target_file = f break - + if target_file: # 使用绝对路径,避免编码问题 full_path = os.path.abspath(os.path.join(target_dir, target_file)) @@ -22,14 +22,14 @@ if os.path.exists(target_dir): print(f"完整路径: {full_path}") print(f"文件存在: {os.path.exists(full_path)}") print("\n开始运行测试...\n") - + # 运行测试脚本 cmd = [sys.executable, "-u", "test_real_parallel_ocr.py", full_path] env = os.environ.copy() env['PYTHONIOENCODING'] = 'utf-8' env['PYTHONUNBUFFERED'] = '1' # 实时显示输出 - process = subprocess.Popen(cmd, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + process = subprocess.Popen(cmd, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env, bufsize=1, universal_newlines=True) if process.stdout: for line in process.stdout: @@ -44,4 +44,3 @@ if os.path.exists(target_dir): print(f" {f}") else: print(f"目录不存在: {target_dir}") - diff --git a/scripts/annotate_image.py b/scripts/annotate_image.py index 8f81e8f..b9038d5 100644 --- a/scripts/annotate_image.py +++ b/scripts/annotate_image.py @@ -59,5 +59,3 @@ def main(): if __name__ == "__main__": main() - - diff --git a/tools/analyze_optimization_effect.py b/tools/analyze_optimization_effect.py index ae9baf3..53974d0 100644 --- a/tools/analyze_optimization_effect.py +++ b/tools/analyze_optimization_effect.py @@ -27,15 +27,15 @@ def main(): if not os.path.exists(log_file): print("日志文件不存在") return - + with open(log_file, 'r', encoding='utf-8', errors='replace') as f: lines = f.readlines() - + print("=" * 60) print("优化效果分析") print("=" * 60) print() - + # 1. 检查服务启动 service_started = False for line in lines: @@ -47,15 +47,15 @@ def main(): if time_match: print(f" 启动时间: {time_match.group(1)}") break - + if not service_started: print("❌ 服务未启动") return - + # 2. 分析服务启动后的截图性能 service_start_time = None screenshot_times_after_service = [] - + for i, line in enumerate(lines): if '截图服务' in line and '已启动' in line: time_match = re.search(r'(\d{2}:\d{2}:\d{2})', line) @@ -64,7 +64,7 @@ def main(): service_start_time = h * 3600 + m * 60 + s print(f" 服务启动时间戳: {service_start_time}") break - + if service_start_time: # 分析服务启动后的截图耗时 for line in lines: @@ -78,7 +78,7 @@ def main(): if elapsed_match: elapsed = float(elapsed_match.group(1)) screenshot_times_after_service.append(elapsed) - + if screenshot_times_after_service: print() print("服务启动后的截图性能:") @@ -86,7 +86,7 @@ def main(): print(f" 平均耗时: {sum(screenshot_times_after_service) / len(screenshot_times_after_service):.2f}秒") print(f" 最短耗时: {min(screenshot_times_after_service):.2f}秒") print(f" 最长耗时: {max(screenshot_times_after_service):.2f}秒") - + # 分析快速响应(可能是缓存命中) fast_responses = [t for t in screenshot_times_after_service if t < 0.5] if fast_responses: @@ -95,13 +95,13 @@ def main(): else: print(f"\n ⚠️ 未发现快速响应(< 0.5秒)") print(f" 可能原因:缓存未命中或服务未正常工作") - + # 3. 检查代码集成 print() print("=" * 60) print("代码集成检查") print("=" * 60) - + # 检查 Underlying_Operations.py if os.path.exists("Underlying_Operations.py"): with open("Underlying_Operations.py", 'r', encoding='utf-8') as f: @@ -110,12 +110,12 @@ def main(): print("✅ Underlying_Operations.py 已支持服务模式") else: print("❌ Underlying_Operations.py 未支持服务模式") - + print() print("=" * 60) print("结论") print("=" * 60) - + if service_started: if screenshot_times_after_service: avg = sum(screenshot_times_after_service) / len(screenshot_times_after_service) @@ -137,12 +137,3 @@ def main(): if __name__ == '__main__': main() - - - - - - - - - diff --git a/tools/analyze_screenshot_logs.py b/tools/analyze_screenshot_logs.py index 0816364..dc028fc 100644 --- a/tools/analyze_screenshot_logs.py +++ b/tools/analyze_screenshot_logs.py @@ -26,12 +26,12 @@ def analyze_log_file(log_path): if not os.path.exists(log_path): print(f"日志文件不存在: {log_path}") return - + print("=" * 60) print("截图性能分析") print("=" * 60) print() - + # 读取日志文件 try: with open(log_path, 'r', encoding='utf-8', errors='replace') as f: @@ -39,17 +39,17 @@ def analyze_log_file(log_path): except Exception as e: print(f"读取日志文件失败: {e}") return - + # 查找截图相关的日志 screenshot_times = [] service_started = False - + for line in lines: # 检查服务启动 if '截图服务' in line or 'ScreenshotService' in line or '后台截图' in line: service_started = True print(f"✅ 发现服务启动日志: {line.strip()[:100]}") - + # 查找截图耗时 if 'screenshot_elapsed_seconds' in line: # 提取耗时 @@ -57,25 +57,25 @@ def analyze_log_file(log_path): if match: elapsed = float(match.group(1)) screenshot_times.append(elapsed) - + # 查找截图成功日志 if '[截图]' in line and '成功' in line: # 尝试提取时间戳 timestamp_match = re.search(r'(\d{2}:\d{2}:\d{2})', line) if timestamp_match: pass # 可以用于分析时间间隔 - + # 分析结果 print(f"\n服务启动状态: {'✅ 已启动' if service_started else '❌ 未启动'}") print() - + if screenshot_times: print(f"截图耗时统计(共 {len(screenshot_times)} 次):") print(f" 平均耗时: {sum(screenshot_times) / len(screenshot_times):.2f} 秒") print(f" 最短耗时: {min(screenshot_times):.2f} 秒") print(f" 最长耗时: {max(screenshot_times):.2f} 秒") print() - + # 分析优化效果 avg_time = sum(screenshot_times) / len(screenshot_times) if service_started: @@ -92,7 +92,7 @@ def analyze_log_file(log_path): print(" 预期优化后: 缓存命中 < 0.01秒,缓存未命中 0.5-1秒") else: print("未找到截图耗时数据") - + # 查找最近的截图日志 print() print("最近的截图日志(最后5条):") @@ -107,27 +107,27 @@ def main(): if not os.path.exists(log_dir): print(f"日志目录不存在: {log_dir}") return - + # 查找最新的 unified_*.log 文件 log_files = [f for f in os.listdir(log_dir) if f.startswith('unified_') and f.endswith('.log')] if not log_files: print("未找到 unified_*.log 文件") return - + # 按修改时间排序 log_files.sort(key=lambda f: os.path.getmtime(os.path.join(log_dir, f)), reverse=True) latest_log = os.path.join(log_dir, log_files[0]) - + print(f"分析日志文件: {latest_log}") print() - + analyze_log_file(latest_log) - + print() print("=" * 60) print("分析完成") print("=" * 60) - + # 建议 print() print("建议:") @@ -137,12 +137,3 @@ def main(): if __name__ == '__main__': main() - - - - - - - - - diff --git a/tools/check_dependencies.py b/tools/check_dependencies.py index 93157ff..7d9f578 100644 --- a/tools/check_dependencies.py +++ b/tools/check_dependencies.py @@ -65,115 +65,3 @@ if missing: else: print("\n[SUCCESS] All required dependencies are installed!") sys.exit(0) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/check_gpu_available.py b/tools/check_gpu_available.py index f5bfd07..114e74b 100644 --- a/tools/check_gpu_available.py +++ b/tools/check_gpu_available.py @@ -19,7 +19,11 @@ if sys.platform == "win32": def check_torch_cuda(): """检查PyTorch是否支持CUDA""" try: - import torch # type: ignore + try: + import torch # type: ignore # pylint: disable=import-error + except ImportError: + print("[GPU检测] PyTorch未安装") + return False if torch.cuda.is_available(): print(f"[GPU检测] PyTorch CUDA可用") @@ -31,9 +35,6 @@ def check_torch_cuda(): else: print("[GPU检测] PyTorch CUDA不可用") return False - except ImportError: - print("[GPU检测] PyTorch未安装") - return False except Exception as e: print(f"[GPU检测] PyTorch CUDA检测失败: {e}") return False @@ -42,7 +43,11 @@ def check_torch_cuda(): def check_easyocr_gpu(): """检查EasyOCR是否可以使用GPU""" try: - import easyocr # type: ignore + try: + import easyocr # type: ignore # pylint: disable=import-error + except ImportError: + print("[GPU检测] EasyOCR未安装") + return False print("[GPU检测] EasyOCR已安装") # EasyOCR使用PyTorch,所以需要PyTorch支持CUDA @@ -69,12 +74,14 @@ def check_easyocr_gpu(): def check_paddleocr_gpu(): """检查PaddleOCR是否可以使用GPU""" try: - from paddleocr import PaddleOCR - print("[GPU检测] PaddleOCR已安装") # PaddleOCR需要paddlepaddle-gpu版本 try: - import paddle + try: + import paddle # type: ignore # pylint: disable=import-error + except ImportError: + print("[GPU检测] PaddleOCR未安装(paddle不可用)") + return False if paddle.device.is_compiled_with_cuda(): print("[GPU检测] PaddleOCR可以使用GPU(paddlepaddle-gpu已安装)") @@ -98,7 +105,10 @@ def check_paddleocr_gpu(): def check_integrated_graphics(): """检查是否是集成显卡(核显)""" try: - import torch # type: ignore + try: + import torch # type: ignore # pylint: disable=import-error + except ImportError: + return False if torch.cuda.is_available(): for i in range(torch.cuda.device_count()): diff --git a/tools/check_gui_params_conflicts.py b/tools/check_gui_params_conflicts.py index a8a1772..d860474 100644 --- a/tools/check_gui_params_conflicts.py +++ b/tools/check_gui_params_conflicts.py @@ -28,12 +28,12 @@ except Exception: def check_conflicts(cfg: dict) -> list: """检查配置参数冲突,返回冲突列表""" conflicts = [] - + # 1. 检查倒计时参数冲突 skip_gt = int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900) skip_lt = int(cfg.get("skip_if_countdown_lt_seconds", 5) or 5) join_ahead = int(cfg.get("high_value_fudai_join_ahead_seconds", 120) or 120) - + if skip_lt >= skip_gt: conflicts.append({ "type": "倒计时阈值冲突", @@ -43,7 +43,7 @@ def check_conflicts(cfg: dict) -> list: "skip_if_countdown_gt_seconds": skip_gt, } }) - + if join_ahead > skip_gt: conflicts.append({ "type": "预约参与阈值冲突", @@ -53,7 +53,7 @@ def check_conflicts(cfg: dict) -> list: "skip_if_countdown_gt_seconds": skip_gt, } }) - + if join_ahead < skip_lt: conflicts.append({ "type": "预约参与阈值冲突", @@ -63,11 +63,11 @@ def check_conflicts(cfg: dict) -> list: "skip_if_countdown_lt_seconds": skip_lt, } }) - + # 2. 检查参与人数参数冲突 min_participants = int(cfg.get("min_participants", 0) or 0) max_participants = int(cfg.get("max_participants", 0) or 0) - + if max_participants > 0 and min_participants > max_participants: conflicts.append({ "type": "参与人数阈值冲突", @@ -77,11 +77,11 @@ def check_conflicts(cfg: dict) -> list: "max_participants": max_participants, } }) - + # 3. 检查价值参数冲突 min_value = float(cfg.get("min_prize_value_yuan", 0) or 0) high_value_threshold = float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000) - + if high_value_threshold < min_value: conflicts.append({ "type": "价值阈值冲突", @@ -91,10 +91,10 @@ def check_conflicts(cfg: dict) -> list: "min_prize_value_yuan": min_value, } }) - + # 4. 检查高价值预约相关参数 high_value_enabled = bool(cfg.get("high_value_fudai_enabled", False)) - + if high_value_enabled and high_value_threshold <= 0: conflicts.append({ "type": "高价值预约配置错误", @@ -104,7 +104,7 @@ def check_conflicts(cfg: dict) -> list: "high_value_fudai_threshold_yuan": high_value_threshold, } }) - + # 5. 检查预约相关参数合理性 if high_value_enabled: max_reservations = int(cfg.get("high_value_fudai_max_reservations", 5) or 5) @@ -116,11 +116,11 @@ def check_conflicts(cfg: dict) -> list: "high_value_fudai_max_reservations": max_reservations, } }) - + # 6. 检查福袋查找相关参数 fudai_icon_max_wait = float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0) fudai_icon_retry_delay = float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6) - + if fudai_icon_max_wait < fudai_icon_retry_delay: conflicts.append({ "type": "福袋查找参数不合理", @@ -130,7 +130,7 @@ def check_conflicts(cfg: dict) -> list: "fudai_icon_retry_delay_seconds": fudai_icon_retry_delay, } }) - + return conflicts @@ -139,20 +139,20 @@ def main(): if not os.path.exists(CONFIG_PATH): print(f"配置文件不存在: {CONFIG_PATH}") return - + try: with open(CONFIG_PATH, "r", encoding="utf-8") as f: cfg = json.load(f) except Exception as e: print(f"读取配置文件失败: {e}") return - + conflicts = check_conflicts(cfg) - + if not conflicts: print("[OK] 未发现参数冲突") return - + print(f"发现 {len(conflicts)} 个参数冲突:\n") for i, conflict in enumerate(conflicts, 1): print(f"{i}. 【{conflict['type']}】") @@ -163,4 +163,3 @@ def main(): if __name__ == "__main__": main() - diff --git a/tools/check_screenshot_optimization.py b/tools/check_screenshot_optimization.py index 54df4bc..04e588d 100644 --- a/tools/check_screenshot_optimization.py +++ b/tools/check_screenshot_optimization.py @@ -29,26 +29,26 @@ def analyze_latest_log(): if not os.path.exists(log_dir): print("日志目录不存在") return None - + # 查找最新的 unified_*.log 文件 log_files = [f for f in os.listdir(log_dir) if f.startswith('unified_') and f.endswith('.log')] if not log_files: print("未找到日志文件") return None - + log_files.sort(key=lambda f: os.path.getmtime(os.path.join(log_dir, f)), reverse=True) latest_log = os.path.join(log_dir, log_files[0]) - + print(f"分析日志: {latest_log}") print() - + try: with open(latest_log, 'r', encoding='utf-8', errors='replace') as f: lines = f.readlines() except Exception as e: print(f"读取日志失败: {e}") return None - + return lines, latest_log def check_service_startup(lines): @@ -56,15 +56,15 @@ def check_service_startup(lines): print("=" * 60) print("1. 检查服务启动状态") print("=" * 60) - + service_started = False service_logs = [] - + for line in lines: if '截图服务' in line or 'ScreenshotService' in line or '后台截图' in line: service_started = True service_logs.append(line.strip()) - + if service_started: print("✅ 服务已启动") print("\n服务启动日志:") @@ -76,7 +76,7 @@ def check_service_startup(lines): print(" 可能原因:") print(" 1. 程序还未重新运行(需要运行新代码)") print(" 2. 服务启动时发生异常(被静默捕获)") - + return service_started def analyze_screenshot_performance(lines, service_started): @@ -84,11 +84,11 @@ def analyze_screenshot_performance(lines, service_started): print("\n" + "=" * 60) print("2. 分析截图性能") print("=" * 60) - + # 提取截图耗时 screenshot_times = [] screenshot_logs = [] - + for line in lines: # 查找截图耗时 if 'screenshot_elapsed_seconds' in line: @@ -97,24 +97,24 @@ def analyze_screenshot_performance(lines, service_started): elapsed = float(match.group(1)) screenshot_times.append(elapsed) screenshot_logs.append((elapsed, line.strip()[:100])) - + # 查找截图成功日志(用于分析时间间隔) if '[截图]' in line and ('成功' in line or '✓' in line): timestamp_match = re.search(r'(\d{2}:\d{2}:\d{2})', line) if timestamp_match: screenshot_logs.append(('log', line.strip()[:100])) - + if screenshot_times: avg_time = sum(screenshot_times) / len(screenshot_times) min_time = min(screenshot_times) max_time = max(screenshot_times) - + print(f"截图耗时统计(共 {len(screenshot_times)} 次):") print(f" 平均耗时: {avg_time:.2f} 秒") print(f" 最短耗时: {min_time:.2f} 秒") print(f" 最长耗时: {max_time:.2f} 秒") print() - + # 分析优化效果 if service_started: print("优化效果分析(服务已启动):") @@ -141,7 +141,7 @@ def analyze_screenshot_performance(lines, service_started): print(" - 缓存命中: < 0.01秒") print(" - 缓存未命中: 0.5-1秒") print(" - 平均耗时: 0.3-0.8秒") - + # 显示最近的截图耗时 print("\n最近的截图耗时(最后5次):") recent_times = [t for t, _ in screenshot_logs if isinstance(t, float)][-5:] @@ -157,10 +157,10 @@ def check_cache_effectiveness(lines): print("\n" + "=" * 60) print("3. 检查缓存效果") print("=" * 60) - + # 查找连续的截图操作,分析时间间隔 screenshot_timestamps = [] - + for line in lines: if '[截图]' in line and ('成功' in line or '✓' in line): # 提取时间戳 @@ -174,23 +174,23 @@ def check_cache_effectiveness(lines): screenshot_timestamps.append(timestamp) except Exception: pass - + if len(screenshot_timestamps) >= 2: intervals = [] for i in range(1, len(screenshot_timestamps)): interval = screenshot_timestamps[i] - screenshot_timestamps[i-1] if interval > 0: # 避免负数 intervals.append(interval) - + if intervals: avg_interval = sum(intervals) / len(intervals) min_interval = min(intervals) - + print(f"截图时间间隔分析(共 {len(intervals)} 个间隔):") print(f" 平均间隔: {avg_interval:.2f} 秒") print(f" 最短间隔: {min_interval:.2f} 秒") print() - + if min_interval < 1.0: print(" ✅ 发现快速连续截图(间隔 < 1秒)") print(" 说明缓存可能生效,响应速度很快") @@ -208,26 +208,26 @@ def check_code_integration(): print("\n" + "=" * 60) print("4. 检查代码集成") print("=" * 60) - + # 检查 douyin_fudai.py douyin_fudai_path = "douyin/core/douyin_fudai.py" if os.path.exists(douyin_fudai_path): with open(douyin_fudai_path, 'r', encoding='utf-8') as f: content = f.read() - + if 'ScreenshotService' in content and 'service.start' in content: print("✅ douyin_fudai.py 已包含服务启动代码") else: print("❌ douyin_fudai.py 未包含服务启动代码") else: print(f"❌ 文件不存在: {douyin_fudai_path}") - + # 检查 screenshot_operations.py screenshot_ops_path = "operations/screenshot_operations.py" if os.path.exists(screenshot_ops_path): with open(screenshot_ops_path, 'r', encoding='utf-8') as f: content = f.read() - + if 'use_service' in content: print("✅ screenshot_operations.py 已支持服务模式") else: @@ -241,31 +241,31 @@ def main(): print("截图优化效果检查") print("=" * 60) print() - + # 分析最新日志 result = analyze_latest_log() if not result: return 1 - + lines, log_file = result - + # 检查服务启动 service_started = check_service_startup(lines) - + # 分析性能 analyze_screenshot_performance(lines, service_started) - + # 检查缓存效果 check_cache_effectiveness(lines) - + # 检查代码集成 check_code_integration() - + # 总结 print("\n" + "=" * 60) print("检查总结") print("=" * 60) - + if service_started: print("✅ 服务已启动") print(" 如果截图耗时仍然较长,可能原因:") @@ -276,24 +276,15 @@ def main(): print("❌ 服务未启动") print(" 请重新运行程序,服务会在启动时自动启动") print(" 查看日志中是否有 '[截图服务] 已启动后台截图服务'") - + print() print("优化效果验证方法:") print("1. 重新运行程序") print("2. 观察首次截图后的后续截图速度") print("3. 如果缓存命中,响应时间应该 < 0.1秒") print("4. 运行: python tools/analyze_screenshot_logs.py") - + return 0 if __name__ == '__main__': sys.exit(main()) - - - - - - - - - diff --git a/tools/check_system_config.py b/tools/check_system_config.py index ac82559..68034ba 100644 --- a/tools/check_system_config.py +++ b/tools/check_system_config.py @@ -25,11 +25,11 @@ def check_cpu(): print("=" * 60) print("CPU 配置检查") print("=" * 60) - + cpu_count = os.cpu_count() if cpu_count: print(f"CPU核心数: {cpu_count}") - + # 评估 if cpu_count >= 8: print("✅ CPU配置: 优秀 (8核+)") @@ -48,7 +48,7 @@ def check_cpu(): print(" 不推荐使用多线程") else: print("❌ 无法检测CPU核心数") - + # 获取CPU信息(Windows) try: import subprocess @@ -66,7 +66,7 @@ def check_cpu(): print(f"CPU型号: {cpu_name}") except Exception: pass - + print() def check_memory(): @@ -74,18 +74,18 @@ def check_memory(): print("=" * 60) print("内存配置检查") print("=" * 60) - + try: import psutil mem = psutil.virtual_memory() total_gb = mem.total / (1024**3) available_gb = mem.available / (1024**3) used_percent = mem.percent - + print(f"总内存: {total_gb:.2f} GB") print(f"可用内存: {available_gb:.2f} GB") print(f"已用内存: {used_percent:.1f}%") - + # 评估 if total_gb >= 16: print("✅ 内存配置: 优秀 (16GB+)") @@ -99,18 +99,18 @@ def check_memory(): else: print("❌ 内存配置: 不足 (<4GB)") print(" 不推荐使用多线程") - + # 检查当前可用内存 if available_gb < 2: print("⚠️ 警告: 可用内存不足2GB,可能影响性能") - + except ImportError: print("⚠️ psutil未安装,无法检测内存") print(" 安装命令: pip install psutil") print(" 或手动检查: 任务管理器 -> 性能 -> 内存") except Exception as e: print(f"❌ 内存检测失败: {e}") - + print() def check_python(): @@ -118,10 +118,10 @@ def check_python(): print("=" * 60) print("Python 版本检查") print("=" * 60) - + version = sys.version_info print(f"Python版本: {version.major}.{version.minor}.{version.micro}") - + if version >= (3, 10): print("✅ Python版本: 优秀 (3.10+)") elif version >= (3, 8): @@ -129,7 +129,7 @@ def check_python(): else: print("❌ Python版本: 过低 (<3.8)") print(" 建议升级到 Python 3.8+") - + print() def check_system(): @@ -137,15 +137,15 @@ def check_system(): print("=" * 60) print("操作系统检查") print("=" * 60) - + system = platform.system() version = platform.version() arch = platform.machine() - + print(f"操作系统: {system}") print(f"系统版本: {version}") print(f"架构: {arch}") - + if system == 'Windows': if '64' in arch or 'AMD64' in arch: print("✅ 系统架构: 64位 (支持)") @@ -153,7 +153,7 @@ def check_system(): print("❌ 系统架构: 32位 (不支持)") else: print("⚠️ 非Windows系统,可能不兼容") - + print() def check_disk(): @@ -161,18 +161,18 @@ def check_disk(): print("=" * 60) print("磁盘空间检查") print("=" * 60) - + try: import shutil total, used, free = shutil.disk_usage('.') total_gb = total / (1024**3) free_gb = free / (1024**3) used_percent = (used / total) * 100 - + print(f"总空间: {total_gb:.2f} GB") print(f"可用空间: {free_gb:.2f} GB") print(f"已用空间: {used_percent:.1f}%") - + if free_gb >= 10: print("✅ 磁盘空间: 充足 (10GB+)") elif free_gb >= 5: @@ -182,10 +182,10 @@ def check_disk(): else: print("❌ 磁盘空间: 不足 (<2GB)") print(" 建议清理磁盘空间") - + except Exception as e: print(f"❌ 磁盘检测失败: {e}") - + print() def get_recommendation(): @@ -193,7 +193,7 @@ def get_recommendation(): print("=" * 60) print("综合评估与建议") print("=" * 60) - + try: cpu_count = os.cpu_count() or 4 try: @@ -202,11 +202,11 @@ def get_recommendation(): total_gb = mem.total / (1024**3) except ImportError: total_gb = 8 # 假设8GB - + # 综合评分 score = 0 recommendations = [] - + # CPU评分 if cpu_count >= 8: score += 30 @@ -219,7 +219,7 @@ def get_recommendation(): cpu_status = "基础" else: cpu_status = "不足" - + # 内存评分 if total_gb >= 16: score += 30 @@ -232,21 +232,21 @@ def get_recommendation(): mem_status = "基础" else: mem_status = "不足" - + # Python版本评分 if sys.version_info >= (3, 10): score += 20 elif sys.version_info >= (3, 8): score += 15 - + # 系统评分 if platform.system() == 'Windows' and ('64' in platform.machine() or 'AMD64' in platform.machine()): score += 20 - + # 给出建议 print(f"综合评分: {score}/100") print() - + if score >= 80: print("✅ 你的电脑非常适合多线程处理!") print(" 建议:") @@ -269,11 +269,11 @@ def get_recommendation(): print(" 建议:") print(" - 使用单线程或2线程") print(" - 考虑升级硬件") - + print() print(f"CPU状态: {cpu_status} ({cpu_count}核)") print(f"内存状态: {mem_status} ({total_gb:.1f}GB)") - + except Exception as e: print(f"评估失败: {e}") @@ -283,14 +283,14 @@ def main(): print("系统配置检查 - 多线程处理适配性分析") print("=" * 60) print() - + check_system() check_python() check_cpu() check_memory() check_disk() get_recommendation() - + print() print("=" * 60) print("检查完成") @@ -298,12 +298,3 @@ def main(): if __name__ == '__main__': main() - - - - - - - - - diff --git a/tools/cleanup_unused_files.py b/tools/cleanup_unused_files.py index cacf4f6..09f9ede 100644 --- a/tools/cleanup_unused_files.py +++ b/tools/cleanup_unused_files.py @@ -18,14 +18,14 @@ from datetime import datetime, timedelta class ProjectCleaner: """项目清理器""" - + def __init__(self, project_root: str = "."): self.project_root = Path(project_root).resolve() self.deleted_files: List[str] = [] self.deleted_dirs: List[str] = [] self.failed_deletes: List[Tuple[str, str]] = [] self.total_size_freed = 0 - + def get_file_size(self, path: Path) -> int: """获取文件或目录大小(字节)""" try: @@ -43,7 +43,7 @@ class ProjectCleaner: except (OSError, PermissionError): pass return 0 - + def safe_delete_file(self, file_path: Path) -> bool: """安全删除文件""" try: @@ -58,7 +58,7 @@ class ProjectCleaner: except Exception as e: self.failed_deletes.append((str(file_path), f"错误: {e}")) return False - + def safe_delete_dir(self, dir_path: Path) -> bool: """安全删除目录""" try: @@ -73,7 +73,7 @@ class ProjectCleaner: except Exception as e: self.failed_deletes.append((str(dir_path), f"错误: {e}")) return False - + def _should_exclude(self, path: Path) -> bool: """判断路径是否应该被排除""" # 排除虚拟环境目录 @@ -87,34 +87,34 @@ class ProjectCleaner: ".vscode", ".idea", ] - + path_str = str(path) for pattern in exclude_patterns: if pattern in path_str: return True return False - + def find_python_cache(self) -> List[Path]: """查找Python缓存文件""" cache_files = [] - + # __pycache__ 目录 for cache_dir in self.project_root.rglob("__pycache__"): if cache_dir.is_dir() and not self._should_exclude(cache_dir): cache_files.append(cache_dir) - + # .pyc 文件 for pyc_file in self.project_root.rglob("*.pyc"): if pyc_file.is_file() and not self._should_exclude(pyc_file): cache_files.append(pyc_file) - + # .pyo 文件 for pyo_file in self.project_root.rglob("*.pyo"): if pyo_file.is_file() and not self._should_exclude(pyo_file): cache_files.append(pyo_file) - + return cache_files - + def find_temp_files(self) -> List[Path]: """查找临时文件""" temp_patterns = [ @@ -128,20 +128,20 @@ class ProjectCleaner: "Thumbs.db", "desktop.ini", ] - + temp_files = [] for pattern in temp_patterns: for temp_file in self.project_root.rglob(pattern): if temp_file.is_file() and not self._should_exclude(temp_file): temp_files.append(temp_file) - + return temp_files - + def find_old_logs(self, keep_days: int = 7) -> List[Path]: """查找旧日志文件(保留最近N天)""" log_files = [] cutoff_time = time.time() - (keep_days * 24 * 60 * 60) - + for log_file in self.project_root.rglob("*.log"): if log_file.is_file() and not self._should_exclude(log_file): try: @@ -150,9 +150,9 @@ class ProjectCleaner: log_files.append(log_file) except (OSError, PermissionError): pass - + return log_files - + def find_report_files(self) -> List[Path]: """查找代码分析报告文件""" report_patterns = [ @@ -161,56 +161,56 @@ class ProjectCleaner: "*.report", "*.lint", ] - + report_files = [] for pattern in report_patterns: for report_file in self.project_root.rglob(pattern): if report_file.is_file() and not self._should_exclude(report_file): report_files.append(report_file) - + return report_files - + def find_unused_dirs(self) -> List[Path]: """查找可能无用的目录""" unused_dirs = [] - + # 检查原始代码目录(如果确认不再需要) legacy_dir = self.project_root / "原始代码" if legacy_dir.exists() and legacy_dir.is_dir(): # 检查是否被引用 unused_dirs.append(legacy_dir) - + # tools/legacy 目录(旧工具,可能不再使用) legacy_tools_dir = self.project_root / "tools" / "legacy" if legacy_tools_dir.exists() and legacy_tools_dir.is_dir(): unused_dirs.append(legacy_tools_dir) - + return unused_dirs - + def find_dummy_files(self) -> List[Path]: """查找测试/占位文件""" dummy_files = [] - + # 查找名为 dummy 的文件 dummy_file = self.project_root / "dummy" if dummy_file.exists(): dummy_files.append(dummy_file) - + return dummy_files - + def cleanup(self, dry_run: bool = True) -> Dict: """执行清理 - + 参数: dry_run: 是否只是预览(不实际删除) - + 返回: 清理报告 """ print(f"{'预览模式' if dry_run else '执行清理'}:扫描项目目录...") print(f"项目根目录: {self.project_root}") print("-" * 60) - + # 1. Python缓存 print("\n1. Python缓存文件:") cache_files = self.find_python_cache() @@ -222,7 +222,7 @@ class ProjectCleaner: self.safe_delete_file(cache_file) else: self.safe_delete_dir(cache_file) - + # 2. 临时文件 print("\n2. 临时文件:") temp_files = self.find_temp_files() @@ -231,7 +231,7 @@ class ProjectCleaner: print(f" - {temp_file.relative_to(self.project_root)} ({self._format_size(size)})") if not dry_run: self.safe_delete_file(temp_file) - + # 3. 旧日志文件(保留最近7天) print("\n3. 旧日志文件(保留最近7天):") old_logs = self.find_old_logs(keep_days=7) @@ -241,7 +241,7 @@ class ProjectCleaner: print(f" - {log_file.relative_to(self.project_root)} ({self._format_size(size)}, {mtime.strftime('%Y-%m-%d')})") if not dry_run: self.safe_delete_file(log_file) - + # 4. 代码分析报告 print("\n4. 代码分析报告文件:") report_files = self.find_report_files() @@ -250,7 +250,7 @@ class ProjectCleaner: print(f" - {report_file.relative_to(self.project_root)} ({self._format_size(size)})") if not dry_run: self.safe_delete_file(report_file) - + # 5. 可能无用的目录(需要确认) print("\n5. 可能无用的目录(需要确认):") unused_dirs = self.find_unused_dirs() @@ -261,7 +261,7 @@ class ProjectCleaner: if not dry_run: # 默认不删除,需要用户确认 pass - + # 6. 测试/占位文件 print("\n6. 测试/占位文件:") dummy_files = self.find_dummy_files() @@ -270,7 +270,7 @@ class ProjectCleaner: print(f" - {dummy_file.relative_to(self.project_root)} ({self._format_size(size)})") if not dry_run: self.safe_delete_file(dummy_file) - + # 生成报告 report = { "dry_run": dry_run, @@ -285,9 +285,9 @@ class ProjectCleaner: "unused_dirs": len(unused_dirs), "dummy_files": len(dummy_files), } - + return report - + def _format_size(self, size_bytes: int) -> str: """格式化文件大小""" size = float(size_bytes) @@ -296,7 +296,7 @@ class ProjectCleaner: return f"{size:.2f} {unit}" size /= 1024.0 return f"{size:.2f} TB" - + def print_report(self, report: Dict): """打印清理报告""" print("\n" + "=" * 60) @@ -310,14 +310,14 @@ class ProjectCleaner: print(f" - 代码分析报告: {report['report_files']} 个") print(f" - 可能无用目录: {report['unused_dirs']} 个") print(f" - 测试/占位文件: {report['dummy_files']} 个") - + if not report['dry_run']: print(f"\n删除结果:") print(f" - 已删除文件: {report['deleted_files']} 个") print(f" - 已删除目录: {report['deleted_dirs']} 个") print(f" - 释放空间: {self._format_size(report['total_size_freed'])}") print(f" - 删除失败: {report['failed_deletes']} 个") - + if self.failed_deletes: print(f"\n删除失败的文件:") for file_path, error in self.failed_deletes: @@ -328,7 +328,7 @@ def main(): """主函数""" import sys import argparse - + parser = argparse.ArgumentParser(description="项目无用文件清理工具") parser.add_argument( "--execute", @@ -341,65 +341,65 @@ def main(): help="仅预览,不执行清理" ) args = parser.parse_args() - + # 检查是否在项目根目录 if not Path("douyin_guaji.py").exists(): print("错误:请在项目根目录运行此脚本") sys.exit(1) - + cleaner = ProjectCleaner(".") - + # 先预览 print("=" * 60) print("第一步:预览模式(不实际删除)") print("=" * 60) preview_report = cleaner.cleanup(dry_run=True) cleaner.print_report(preview_report) - + # 如果只是预览,直接退出 if args.preview_only: print("\n预览完成,未执行清理操作") return - + # 如果指定了--execute,直接执行 if args.execute: print("\n" + "=" * 60) print("第二步:执行清理") print("=" * 60) - + # 重置统计 cleaner.deleted_files = [] cleaner.deleted_dirs = [] cleaner.failed_deletes = [] cleaner.total_size_freed = 0 - + # 执行清理 final_report = cleaner.cleanup(dry_run=False) cleaner.print_report(final_report) - + print("\n清理完成!") return - + # 否则询问用户(交互式模式) try: print("\n" + "=" * 60) response = input("是否执行清理?(yes/no): ").strip().lower() - + if response in ('yes', 'y', '是'): print("\n" + "=" * 60) print("第二步:执行清理") print("=" * 60) - + # 重置统计 cleaner.deleted_files = [] cleaner.deleted_dirs = [] cleaner.failed_deletes = [] cleaner.total_size_freed = 0 - + # 执行清理 final_report = cleaner.cleanup(dry_run=False) cleaner.print_report(final_report) - + print("\n清理完成!") else: print("已取消清理操作") @@ -411,4 +411,3 @@ def main(): if __name__ == "__main__": main() - diff --git a/tools/fix_trailing_whitespace.py b/tools/fix_trailing_whitespace.py new file mode 100644 index 0000000..ed1b3ea --- /dev/null +++ b/tools/fix_trailing_whitespace.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""批量移除 Python 文件尾随空白并确保文件以单一换行结束。""" +import os +import io + +def should_skip(path): + parts = path.split(os.sep) + return any(p.startswith('.') or p == '__pycache__' or p == '.venv' for p in parts) + +root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) +count = 0 +changed_files = [] +for dirpath, dirnames, filenames in os.walk(root): + # skip venv and hidden dirs + if should_skip(dirpath): + continue + for fname in filenames: + if not fname.endswith('.py'): + continue + fpath = os.path.join(dirpath, fname) + if should_skip(fpath): + continue + try: + with io.open(fpath, 'r', encoding='utf-8') as f: + lines = f.readlines() + except Exception: + continue + new_lines = [line.rstrip() + '\n' for line in lines] + # remove extra final newlines: ensure exactly one final newline + if new_lines: + # strip trailing empty lines + while len(new_lines) > 1 and new_lines[-1].strip() == '': + new_lines.pop() + if not new_lines[-1].endswith('\n'): + new_lines[-1] = new_lines[-1] + '\n' + new_text = ''.join(new_lines) + old_text = ''.join(lines) + if new_text != old_text: + with io.open(fpath, 'w', encoding='utf-8', newline='\n') as f: + f.write(new_text) + changed_files.append(fpath) + count += 1 + +print(f"Processed {count} files; modified: {len(changed_files)}") +for p in changed_files: + print(p) diff --git a/tools/install_dependencies.py b/tools/install_dependencies.py index eb40e22..550c733 100644 --- a/tools/install_dependencies.py +++ b/tools/install_dependencies.py @@ -19,37 +19,37 @@ def install_package(package): def main(): # 检查缺失的依赖 missing = [] - + try: import paddlepaddle # type: ignore[import-untyped] except ImportError: missing.append("paddlepaddle>=2.5.0,<3.0.0") - + try: import ttkbootstrap except ImportError: missing.append("ttkbootstrap>=1.10.0") - + if not missing: print("[SUCCESS] All dependencies are installed!") return 0 - + print(f"Missing dependencies: {', '.join(missing)}") print("\nDo you want to install them? (y/n): ", end='') - + # 在非交互环境中自动安装 response = 'y' try: response = input().strip().lower() except (EOFError, KeyboardInterrupt): response = 'y' # 默认安装 - + if response in ('y', 'yes', ''): success_count = 0 for pkg in missing: if install_package(pkg): success_count += 1 - + if success_count == len(missing): print("\n[SUCCESS] All dependencies installed successfully!") return 0 @@ -64,20 +64,3 @@ def main(): if __name__ == "__main__": sys.exit(main()) - - - - - - - - - - - - - - - - - diff --git a/tools/pick_coords.py b/tools/pick_coords.py index bb8a4ed..c74220c 100644 --- a/tools/pick_coords.py +++ b/tools/pick_coords.py @@ -62,7 +62,7 @@ class CoordPicker: file_menu.add_separator() file_menu.add_command(label="退出", command=self.root.destroy) menubar.add_cascade(label="文件", menu=file_menu) - + view_menu = tk.Menu(menubar, tearoff=0) view_menu.add_command(label="放大 (+)", command=self.zoom_in, accelerator="+ / Ctrl+滚轮上") view_menu.add_command(label="缩小 (-)", command=self.zoom_out, accelerator="- / Ctrl+滚轮下") @@ -70,7 +70,7 @@ class CoordPicker: view_menu.add_separator() view_menu.add_command(label="显示/隐藏放大镜", command=self.toggle_magnifier, accelerator="M") menubar.add_cascade(label="视图", menu=view_menu) - + self.root.config(menu=menubar) self.root.bind_all("", lambda e: self.open_dialog()) self.root.bind("", lambda e: self.prev_image()) @@ -95,7 +95,7 @@ class CoordPicker: self.status.set("移动鼠标查看坐标;单击复制坐标;滚轮缩放;右键显示放大镜;Ctrl+O 打开图片(提示:安装 tkinterdnd2 可支持拖放)") self.label = tk.Label(self.root, textvariable=self.status, anchor="w") self.label.pack(fill=tk.X) - + # 像素信息显示 self.pixel_info = tk.StringVar() self.pixel_info.set("") @@ -212,28 +212,28 @@ class CoordPicker: """更新显示""" if not self.img: return - + # 获取canvas实际大小 self.root.update_idletasks() canvas_w = max(1, self.canvas.winfo_width()) canvas_h = max(1, self.canvas.winfo_height()) - + # 计算显示尺寸 self.disp_w = int(self.w * self.scale) self.disp_h = int(self.h * self.scale) - + # 限制滚动偏移 max_offset_x = max(0, self.disp_w - canvas_w) max_offset_y = max(0, self.disp_h - canvas_h) self.scroll_offset_x = max(0, min(self.scroll_offset_x, max_offset_x)) self.scroll_offset_y = max(0, min(self.scroll_offset_y, max_offset_y)) - + # 生成显示图像 try: resample = Image.Resampling.BICUBIC if hasattr(Image, 'Resampling') else Image.BICUBIC except Exception: resample = Image.BICUBIC - + if self.scale != 1.0: # 如果放大,只显示可见区域以提高性能 if self.scale > 1.0 and canvas_w < self.disp_w and canvas_h < self.disp_h: @@ -242,7 +242,7 @@ class CoordPicker: src_y1 = max(0, int(self.scroll_offset_y / self.scale)) src_x2 = min(self.w, src_x1 + int(canvas_w / self.scale) + 2) src_y2 = min(self.h, src_y1 + int(canvas_h / self.scale) + 2) - + # 裁剪并放大 crop_img = self.img.crop((src_x1, src_y1, src_x2, src_y2)) crop_w, crop_h = crop_img.size @@ -252,20 +252,20 @@ class CoordPicker: disp_img = self.img.resize((self.disp_w, self.disp_h), resample) else: disp_img = self.img - + self.tk_img = ImageTk.PhotoImage(disp_img) - + # 更新canvas滚动区域 self.canvas.config(scrollregion=(0, 0, self.disp_w, self.disp_h)) - + # 更新图像位置 self.canvas.coords(self._canvas_image_id, -self.scroll_offset_x, -self.scroll_offset_y) self.canvas.itemconfig(self._canvas_image_id, image=self.tk_img) - + # 更新标题 if self.image_path: self.root.title(f"取坐标: {self.image_path.name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x") - + def on_move(self, event): """移动鼠标:显示坐标和像素信息(保留你原来的坐标逻辑)""" x, y = self._to_image_xy(event) @@ -299,17 +299,17 @@ class CoordPicker: self.status.set(f"已复制: {text}") except Exception: self.status.set(f"坐标: {text} (复制失败)") - + def on_right_click(self, event): """右键显示/隐藏放大镜""" self.toggle_magnifier() - + def on_drag_start(self, event): """开始拖拽""" self.drag_start_x = event.x self.drag_start_y = event.y self.is_dragging = False - + def on_drag(self, event): """拖拽平移""" if not self.img: @@ -323,26 +323,26 @@ class CoordPicker: self.drag_start_x = event.x self.drag_start_y = event.y self._update_display() - + def on_drag_end(self, event): """结束拖拽""" self.is_dragging = False - + def on_mousewheel(self, event): """鼠标滚轮缩放(无Ctrl)""" if event.state & 0x4: # Ctrl键按下 return # 交给on_mousewheel_ctrl处理 - + delta = 0 if event.num == 4 or event.delta > 0: # 向上滚动 delta = 1 elif event.num == 5 or event.delta < 0: # 向下滚动 delta = -1 - + if delta != 0: x, y = self._to_image_xy(event) self._zoom_at_point(x, y, delta * 0.1) - + def on_mousewheel_ctrl(self, event): """Ctrl+滚轮缩放""" delta = 0 @@ -350,31 +350,31 @@ class CoordPicker: delta = 1 elif event.num == 5 or event.delta < 0: # 向下滚动 delta = -1 - + if delta != 0: x, y = self._to_image_xy(event) self._zoom_at_point(x, y, delta * 0.1) - + def _zoom_at_point(self, img_x: int, img_y: int, delta: float): """在指定点缩放""" if not self.img: return - + old_scale = self.scale new_scale = clamp(old_scale + delta, self.min_scale, self.max_scale) - + if abs(new_scale - old_scale) < 0.01: return - + # 计算缩放中心点在图像中的位置 # 调整滚动偏移,使缩放点保持在屏幕上的同一位置 scale_ratio = new_scale / old_scale self.scroll_offset_x = img_x * new_scale - (img_x * old_scale - self.scroll_offset_x) * scale_ratio self.scroll_offset_y = img_y * new_scale - (img_y * old_scale - self.scroll_offset_y) * scale_ratio - + self.scale = new_scale self._update_display() - + def zoom_in(self): """放大""" if not self.img: @@ -382,7 +382,7 @@ class CoordPicker: center_x = self.w // 2 center_y = self.h // 2 self._zoom_at_point(center_x, center_y, 0.2) - + def zoom_out(self): """缩小""" if not self.img: @@ -390,7 +390,7 @@ class CoordPicker: center_x = self.w // 2 center_y = self.h // 2 self._zoom_at_point(center_x, center_y, -0.2) - + def reset_zoom(self): """重置缩放""" if not self.img: @@ -399,7 +399,7 @@ class CoordPicker: self.scroll_offset_x = 0 self.scroll_offset_y = 0 self._update_display() - + def toggle_magnifier(self): """切换放大镜显示""" if self.magnifier_window and self.magnifier_window.winfo_exists(): @@ -407,17 +407,17 @@ class CoordPicker: self.magnifier_window = None else: self._create_magnifier() - + def _create_magnifier(self): """创建放大镜窗口""" if not self.img: return - + self.magnifier_window = tk.Toplevel(self.root) self.magnifier_window.title("放大镜") self.magnifier_window.geometry(f"{self.magnifier_size}x{self.magnifier_size}") self.magnifier_window.resizable(False, False) - + self.magnifier_canvas = tk.Canvas( self.magnifier_window, width=self.magnifier_size, @@ -426,30 +426,30 @@ class CoordPicker: highlightbackground="black" ) self.magnifier_canvas.pack() - + # 绑定鼠标移动 self.root.bind("", self._on_magnifier_move) - + def _on_magnifier_move(self, event): """鼠标移动时更新放大镜""" if not self.magnifier_window or not self.magnifier_window.winfo_exists(): return - + x, y = self._to_image_xy(event) self._update_magnifier(x, y) - + def _update_magnifier(self, img_x: int, img_y: int): """更新放大镜显示""" if not self.magnifier_window or not self.magnifier_window.winfo_exists() or not self.img: return - + # 计算放大区域 half_size = self.magnifier_size // (2 * self.magnifier_zoom) x1 = max(0, img_x - half_size) y1 = max(0, img_y - half_size) x2 = min(self.w, img_x + half_size) y2 = min(self.h, img_y + half_size) - + # 裁剪并放大 crop_img = self.img.crop((x1, y1, x2, y2)) try: @@ -457,13 +457,13 @@ class CoordPicker: except Exception: resample = Image.NEAREST magnified = crop_img.resize((self.magnifier_size, self.magnifier_size), resample) - + # 显示 tk_mag_img = ImageTk.PhotoImage(magnified) self.magnifier_canvas.delete("all") self.magnifier_canvas.create_image(self.magnifier_size // 2, self.magnifier_size // 2, image=tk_mag_img) setattr(self.magnifier_canvas, 'image', tk_mag_img) # 保持引用 - + # 绘制十字线 center = self.magnifier_size // 2 self.magnifier_canvas.create_line(center, 0, center, self.magnifier_size, fill="red", width=1) @@ -495,29 +495,29 @@ class CoordPicker: """处理拖放事件""" if not HAS_DND: return - + try: # 获取拖放的文件路径 files = self.root.tk.splitlist(event.data) if not files: return - + # 取第一个文件 file_path = files[0] # 移除可能的花括号(Windows 拖放可能包含) file_path = file_path.strip('{}') - + path = Path(file_path) if not path.exists(): self.status.set(f"文件不存在: {path}") return - + # 检查是否为图片文件 exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp"} if path.suffix.lower() not in exts: self.status.set(f"不是支持的图片格式: {path.suffix}") return - + # 加载图片 self.set_image(path, update_list=True) self.status.set(f"已加载: {path.name}") @@ -546,4 +546,4 @@ def main(argv: list[str]) -> int: if __name__ == "__main__": - raise SystemExit(main(sys.argv)) \ No newline at end of file + raise SystemExit(main(sys.argv)) diff --git a/tools/region_selector.py b/tools/region_selector.py index ae4a1f9..92ece93 100644 --- a/tools/region_selector.py +++ b/tools/region_selector.py @@ -4,12 +4,18 @@ 用于选择图片区域,圈出边框,并统计区域内白色像素数量 """ +# 下面禁用部分 pylint 检查: +# - E1101: no-member(第三方 GUI / PIL 在静态检查下的误报) +# - E1102: not-callable(TkinterDnD 可调用性在类型检查器下常被误判) +# 这些抑制只影响静态检查,不改变运行时行为。 +# pylint: disable=E1101,E1102 + import sys from pathlib import Path -from typing import Optional, Tuple, Any +from typing import Optional, Any import json -from PIL import Image, ImageTk, ImageDraw +from PIL import Image, ImageTk try: import tkinter as tk diff --git a/tools/生成WPS流程图.py b/tools/生成WPS流程图.py index d16497d..9ee0823 100644 --- a/tools/生成WPS流程图.py +++ b/tools/生成WPS流程图.py @@ -12,8 +12,8 @@ import sys def check_mermaid_cli(): """检查是否安装了mermaid-cli""" try: - result = subprocess.run(['mmdc', '--version'], - capture_output=True, + result = subprocess.run(['mmdc', '--version'], + capture_output=True, text=True) return True except FileNotFoundError: @@ -42,18 +42,18 @@ def generate_svg_from_mermaid(mermaid_code, output_file): temp_file = "temp_flowchart.mmd" with open(temp_file, 'w', encoding='utf-8') as f: f.write(mermaid_code) - + # 使用mmdc生成SVG result = subprocess.run( ['mmdc', '-i', temp_file, '-o', output_file, '-b', 'transparent'], capture_output=True, text=True ) - + # 删除临时文件 if os.path.exists(temp_file): os.remove(temp_file) - + if result.returncode == 0: return True else: @@ -69,15 +69,15 @@ def read_mermaid_from_md(): if not os.path.exists(md_file): print(f"错误: 找不到文件 {md_file}") return None - + with open(md_file, 'r', encoding='utf-8') as f: content = f.read() - + # 提取所有mermaid代码块 mermaid_blocks = [] in_mermaid = False current_block = [] - + for line in content.split('\n'): if line.strip().startswith('```mermaid'): in_mermaid = True @@ -88,7 +88,7 @@ def read_mermaid_from_md(): mermaid_blocks.append('\n'.join(current_block)) elif in_mermaid: current_block.append(line) - + return mermaid_blocks def main(): @@ -96,22 +96,22 @@ def main(): print("=" * 60) print("WPS流程图生成工具") print("=" * 60) - + # 检查mermaid-cli if not check_mermaid_cli(): install_mermaid_cli() return - + # 读取mermaid代码 print("\n正在读取流程图.md...") mermaid_blocks = read_mermaid_from_md() - + if not mermaid_blocks: print("错误: 未找到mermaid代码块") return - + print(f"找到 {len(mermaid_blocks)} 个流程图") - + # 流程图名称 flowchart_names = [ "主流程图", @@ -122,24 +122,24 @@ def main(): "预约处理子流程图", "异常处理流程" ] - + # 生成SVG文件 output_dir = "WPS流程图" os.makedirs(output_dir, exist_ok=True) - + print(f"\n正在生成SVG文件到 {output_dir} 目录...") - + for i, mermaid_code in enumerate(mermaid_blocks): name = flowchart_names[i] if i < len(flowchart_names) else f"流程图{i+1}" output_file = os.path.join(output_dir, f"{name}.svg") - + print(f" 生成: {name}...", end=' ') - + if generate_svg_from_mermaid(mermaid_code, output_file): print("✓ 成功") else: print("✗ 失败") - + print("\n" + "=" * 60) print("生成完成!") print(f"SVG文件保存在: {output_dir}/") @@ -151,102 +151,3 @@ def main(): if __name__ == "__main__": main() - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/typings/__init__.py b/typings/__init__.py index 6426f36..a532841 100644 --- a/typings/__init__.py +++ b/typings/__init__.py @@ -1,2 +1 @@ # 类型存根包初始化文件 - diff --git a/webui/app.js b/webui/app.js index 93b6e6d..65b13d0 100644 --- a/webui/app.js +++ b/webui/app.js @@ -11,7 +11,7 @@ const DEFAULTS = { min_prize_value_yuan: 0, min_participants: 0, max_participants: 0, - skip_if_countdown_lt_seconds: 10, + skip_if_countdown_lt_seconds: 15, reset_after_swipes_enabled: false, reset_after_swipes: 10, auto_join_fansclub: false, @@ -55,19 +55,6 @@ const DEFAULTS = { fudai_quiet_hours_enabled: true, fudai_quiet_start_hour: 2, fudai_quiet_end_hour: 7, - - // 调试相关 - "debug_captures.enabled": false, - "debug_captures.auto_cleanup": true, - "debug_captures.keep_days": 7, - "debug_captures.max_files": 2000, - enable_ocr_mode1: false, - fudai_template_match_enabled: false, - fudai_template_match_threshold: 0.7, - lucky_draw_red_ratio_threshold: 0.8, - live_room_match_threshold: 0.7, - stage_diag_max_time: 15.0, - stage_diag_max_step_time: 4.0, }; function $(id) { return document.getElementById(id); } @@ -501,50 +488,13 @@ function coerceValue(type, raw, isCheckbox) { return String(raw ?? ""); } -function getNestedValue(obj, key) { - if (!obj || !key) return undefined; - // 支持嵌套键,如 "debug_captures.auto_cleanup" - if (key.includes(".")) { - const parts = key.split("."); - let current = obj; - for (const part of parts) { - if (current && typeof current === "object" && part in current) { - current = current[part]; - } else { - return undefined; - } - } - return current; - } - return obj[key]; -} - -function setNestedValue(obj, key, value) { - if (!obj || !key) return; - // 支持嵌套键,如 "debug_captures.auto_cleanup" - if (key.includes(".")) { - const parts = key.split("."); - let current = obj; - for (let i = 0; i < parts.length - 1; i++) { - const part = parts[i]; - if (!(part in current) || typeof current[part] !== "object" || current[part] === null) { - current[part] = {}; - } - current = current[part]; - } - current[parts[parts.length - 1]] = value; - } else { - obj[key] = value; - } -} - function applyConfigToUI(cfg) { for (const el of getConfigBoundElements()) { const key = el.dataset.key; const type = el.dataset.type || "str"; - const val = cfg ? getNestedValue(cfg, key) : undefined; + const val = cfg ? cfg[key] : undefined; - // undefined/null 都视为"未配置":保留页面默认值 + // undefined/null 都视为“未配置”:保留页面默认值 const hasVal = !(typeof val === "undefined" || val === null); const useVal = hasVal ? val : (Object.prototype.hasOwnProperty.call(DEFAULTS, key) ? DEFAULTS[key] : undefined); if (typeof useVal === "undefined") continue; @@ -568,12 +518,11 @@ function collectConfigFromUI() { const type = el.dataset.type || "str"; if (!key) continue; - const value = el.type === "checkbox" - ? coerceValue(type, el.checked, true) - : coerceValue(type, el.value, false); - - // 支持嵌套键,如 "debug_captures.auto_cleanup" - setNestedValue(out, key, value); + if (el.type === "checkbox") { + out[key] = coerceValue(type, el.checked, true); + } else { + out[key] = coerceValue(type, el.value, false); + } } return out; } @@ -677,13 +626,15 @@ async function startRun() { async function testYanghao() { const deviceId = $("device").value || ""; const seconds = parseInt($("yanghao_recommend_duration_seconds").value || "60", 10); - // 已移除测试养号功能 + await apiPost("/api/test-yanghao", { device_id: deviceId, seconds }); + appendLog([`[WEB] 已启动测试养号:device=${deviceId || '(auto)'} seconds=${seconds}`]); } async function testComment() { const deviceId = $("device").value || ""; const text = ""; - // 已移除测试评论功能 + await apiPost("/api/test-comment", { device_id: deviceId, text }); + appendLog([`[WEB] 已启动测试评论:device=${deviceId || '(auto)'}${text ? ' text=自定义' : ''}`]); } async function stopRun() { @@ -803,16 +754,16 @@ async function pollReservations() { const current_room_title_raw = data.current_room_title_raw || ""; const reason = data.reason || ""; - // 显示基本信息(中文) + // 显示基本信息 const info = document.createElement("div"); info.className = "reservationsInfo"; info.innerHTML = ` -
当前直播间位置:${room_pos}
+
当前位置:${room_pos}
当前直播间(清洗后):${escapeHtml(current_room_title || '-') }
当前直播间原文:${escapeHtml(current_room_title_raw || '-') }
-
预约总数量:${reservations.length}
-
更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleString() : '-'}
-
最近更新原因:${escapeHtml(reason || '-') }
+
预约数量:${reservations.length}
+
更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}
+
原因:${escapeHtml(reason || '-') }
`; container.appendChild(info); @@ -824,7 +775,7 @@ async function pollReservations() { return; } - // 显示预约列表(更详细中文) + // 显示预约列表 const list = document.createElement("div"); list.className = "reservationsList"; @@ -835,31 +786,20 @@ async function pollReservations() { const now = Date.now() / 1000; const future_ts = item.future_ts || 0; const remain = Math.max(0, Math.floor(future_ts - now)); - const remainStr = remain > 0 ? `${Math.floor(remain / 60)}分${remain % 60}秒后开奖` : "已到开奖时间"; - - const createdTs = item.created_ts || 0; - let createdStr = "-"; - if (createdTs > 0) { - try { - createdStr = new Date(createdTs * 1000).toLocaleString(); - } catch (e) { - createdStr = String(createdTs); - } - } + const remainStr = remain > 0 ? `${Math.floor(remain / 60)}分${remain % 60}秒后` : "已到开奖时间"; card.innerHTML = `
#${idx + 1} - ${item.prize_value_yuan || 0} 元 + ${item.prize_value_yuan || 0}元
内容:${escapeHtml(item.content || '-')}
开奖时间:${item.future_str || '-'}
剩余时间:${remainStr}
-
发现时直播间位置:${item.pos_seen || 0}
+
发现位置:${item.pos_seen || 0}
直播间(清洗后):${escapeHtml(item.room_title || '-')}
直播间原文:${escapeHtml(item.room_title_raw || '-')}
-
记录时间:${createdStr}
`; list.appendChild(card); @@ -1009,20 +949,6 @@ async function pollStats() { } setTextIfExists("statLastLog", fmtTime(s.last_log_ts)); setTextIfExists("statExitCode", (s.exit_code === null || typeof s.exit_code === "undefined") ? "-" : s.exit_code); - - // 显示traceId和MDC信息 - const traceId = s.trace_id || "-"; - setTextIfExists("statTraceId", traceId); - const mdcContext = s.mdc_context || {}; - if ($("statTraceIdHint")) { - const mdcKeys = Object.keys(mdcContext); - if (mdcKeys.length > 0) { - const mdcStr = mdcKeys.map(k => `${k}=${mdcContext[k]}`).join(", "); - $("statTraceIdHint").textContent = `MDC: ${mdcStr}`; - } else { - $("statTraceIdHint").textContent = ""; - } - } const c = s.counters || {}; const getC = (k) => Number.isFinite(Number(c[k])) ? Number(c[k]) : 0;