diff --git a/.specstory/history/2025-12-26_04-10Z-福袋确认流程中的额外步骤.md b/.specstory/history/2025-12-26_04-10Z-粉丝团点击位置与详情页关闭.md similarity index 57% rename from .specstory/history/2025-12-26_04-10Z-福袋确认流程中的额外步骤.md rename to .specstory/history/2025-12-26_04-10Z-粉丝团点击位置与详情页关闭.md index a05b389..e612a5d 100644 --- a/.specstory/history/2025-12-26_04-10Z-福袋确认流程中的额外步骤.md +++ b/.specstory/history/2025-12-26_04-10Z-粉丝团点击位置与详情页关闭.md @@ -2,7 +2,7 @@ -# 福袋确认流程中的额外步骤 (2025-12-26 04:10Z) +# 粉丝团点击位置与详情页关闭 (2025-12-26 04:10Z) _**User (2025-12-26 04:08Z)**_ @@ -14150,7 +14150,166 @@ _**Agent (model default, mode Agent)**_ --- + +
+Tool use: **grep** • Grep for "save_debug_image" in "." • 34 matches +Output mode: content + + +| File | Content | Line | +|------|------|------| +| `.\douyin_fudai_core.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L59 | +| `.\douyin_screenshot_manager.py` | `def save_debug_image(` | L547 | +| `.\Underlying_Operations.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L876 | +| `.\Underlying_Operations.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L966 | +| `.\Underlying_Operations.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L1067 | +| `.\Underlying_Operations.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L1191 | +| `.\douyin_fudai_detail.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L367 | +| `.\douyin_fudai_finder.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L682 | +| `.\douyin_fudai_finder.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L1187 | +| `.\douyin_fudai_finder.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L1477 | +| `.\douyin_fudai_finder.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L1543 | +| `.\douyin_detection.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L180 | +| `.\douyin_detection.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L424 | +| `.\douyin_detection.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L541 | +| `.\douyin_detection.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L708 | +| `.\douyin_detection.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L1329 | +| `.\douyin_detection.py` | `debug_path = douyin_screenshot_manager.save_debug_image_with_match_result(` | L1384 | +| `.\douyin_pixel.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L201 | +| `.\douyin_pixel.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L260 | +| `.\douyin_pixel.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L339 | +| `.\douyin_pixel.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L411 | +| `.\douyin_stage.py` | `debug_path = douyin_screenshot_manager.save_debug_image(` | L729 | +| `.\统一截图和分数记录说明.md` | `- **调试图像**:使用 `douyin_screenshot_manager.save_debug_image()` 保存` | L11 | +| `.\统一截图和分数记录说明.md` | `- **调试图像**:已使用 `save_debug_image()` 保存预处理和结果图像` | L16 | +| `.\统一截图和分数记录说明.md` | `- **调试图像**:已使用 `save_debug_image()` 保存` | L21 | +| `.\统一截图和分数记录说明.md` | `- **调试图像**:已使用 `save_debug_image()` 保存` | L26 | +| `.\统一截图和分数记录说明.md` | `- [ ] 统一使用 `douyin_screenshot_manager.save_debug_image()` 保存调试图像` | L38 | +| `.\统一截图和分数记录说明.md` | `- **调试图像**:使用 `douyin_screenshot_manager.save_debug_image()` 保存` | L80 | +| `.\统一截图和分数记录说明.md` | `- **调试图像**:已使用 `save_debug_image()` 保存预处理和结果图像` | L85 | +| `.\统一截图和分数记录说明.md` | `- **调试图像**:已使用 `save_debug_image()` 保存` | L90 | +| `.\统一截图和分数记录说明.md` | `- **调试图像**:已使用 `save_debug_image()` 保存` | L95 | +| `.\统一截图和分数记录说明.md` | `- [ ] 统一使用 `douyin_screenshot_manager.save_debug_image()` 保存调试图像` | L107 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `#### `save_debug_image()`` | L137 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `#### `save_debug_image_with_match_result()`` | L154 | + + +
+
+ +--- + + +
+Tool use: **grep** • Grep for "debug_ocr|debug_capture|调试截图" in "." • 89 matches + +Output mode: content + + +| File | Content | Line | +|------|------|------| +| `.\config.json` | `"debug_captures": \{` | L97 | +| `.\douyin_fudai_core.py` | `# 保存调试截图` | L122 | +| `.\douyin_fudai_core.py` | `# 保存任务列表区域的调试截图` | L396 | +| `.\douyin_fudai.py` | `# 裁剪区域用于OCR识别(通过cut_pic会自动保存到debug_captures)` | L2987 | +| `.\douyin_screenshot_manager.py` | `def get_debug_captures_dir() -> str:` | L269 | +| `.\douyin_screenshot_manager.py` | `debug_dir = os.path.join(pic_dir, "debug_captures")` | L272 | +| `.\douyin_screenshot_manager.py` | `def ensure_debug_captures_dir() -> None:` | L279 | +| `.\douyin_screenshot_manager.py` | `debug_dir = get_debug_captures_dir()` | L282 | +| `.\douyin_screenshot_manager.py` | `def get_debug_captures_base_dir() -> str:` | L297 | +| `.\douyin_screenshot_manager.py` | `return os.path.join(pic_dir, "debug_captures")` | L300 | +| `.\douyin_screenshot_manager.py` | `def count_debug_captures_files() -> int:` | L303 | +| `.\douyin_screenshot_manager.py` | `debug_base_dir = get_debug_captures_base_dir()` | L310 | +| `.\douyin_screenshot_manager.py` | `def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int:` | L339 | +| `.\douyin_screenshot_manager.py` | `debug_base_dir = get_debug_captures_base_dir()` | L350 | +| `.\douyin_screenshot_manager.py` | `def init_debug_captures_cleanup() -> None:` | L477 | +| `.\douyin_screenshot_manager.py` | `if 'debug_captures' in config and isinstance(config['debug_captures'], dict):` | L496 | +| `.\douyin_screenshot_manager.py` | `auto_cleanup = config['debug_captures'].get('auto_cleanup', True)` | L497 | +| `.\douyin_screenshot_manager.py` | `keep_days = int(config['debug_captures'].get('keep_days', 7))` | L498 | +| `.\douyin_screenshot_manager.py` | `max_files = int(config['debug_captures'].get('max_files', 2000))` | L499 | +| `.\douyin_screenshot_manager.py` | `cleanup_debug_captures(keep_days=keep_days, max_files=max_files)` | L502 | +| `.\douyin_screenshot_manager.py` | `debug_base_dir = get_debug_captures_base_dir()` | L579 | +| `.\douyin_screenshot_manager.py` | `if 'debug_captures' in config and isinstance(config['debug_captures'], dict):` | L606 | +| `.\douyin_screenshot_manager.py` | `cleanup_enabled = config['debug_captures'].get('auto_cleanup', True)` | L607 | +| `.\douyin_screenshot_manager.py` | `keep_days = int(config['debug_captures'].get('keep_days', 7))` | L608 | +| `.\douyin_screenshot_manager.py` | `max_files = int(config['debug_captures'].get('max_files', 2000))` | L609 | +| `.\douyin_screenshot_manager.py` | `cleanup_debug_captures(keep_days=keep_days, max_files=max_files)` | L615 | +| `.\douyin_screenshot_manager.py` | `if 'debug_captures' in config and isinstance(config['debug_captures'], dict):` | L633 | +| `.\douyin_screenshot_manager.py` | `max_files = int(config['debug_captures'].get('max_files', 2000))` | L634 | +| `.\douyin_screenshot_manager.py` | `current_count = count_debug_captures_files()` | L637 | +| `.\douyin_screenshot_manager.py` | `cleanup_debug_captures(keep_days=999, max_files=max_files) # keep_days设为999表示只按文件数量清理` | L644 | +| `.\douyin_screenshot_manager.py` | `ensure_debug_captures_dir()` | L651 | +| `.\douyin_screenshot_manager.py` | `debug_dir = get_debug_captures_dir()` | L652 | +| `.\douyin_screenshot_manager.py` | `ensure_debug_captures_dir()` | L722 | +| `.\douyin_screenshot_manager.py` | `ensure_debug_captures_dir()` | L737 | +| `.\web_gui.py` | `"""设置嵌套配置值,支持如 'debug_captures.auto_cleanup' 这样的键"""` | L1438 | +| `.\gui_app.py` | `debug_captures_auto_cleanup_var = tk.BooleanVar(` | L511 | +| `.\gui_app.py` | `cfg.get("debug_captures", \{}).get("auto_cleanup", True)` | L513 | +| `.\gui_app.py` | `if isinstance(cfg.get("debug_captures"), dict)` | L514 | +| `.\gui_app.py` | `debug_captures_keep_days_var = tk.IntVar(` | L518 | +| `.\gui_app.py` | `cfg.get("debug_captures", \{}).get("keep_days", 7)` | L520 | +| `.\gui_app.py` | `if isinstance(cfg.get("debug_captures"), dict)` | L521 | +| `.\gui_app.py` | `debug_captures_max_files_var = tk.IntVar(` | L525 | +| `.\gui_app.py` | `cfg.get("debug_captures", \{}).get("max_files", 2000)` | L527 | +| `.\gui_app.py` | `if isinstance(cfg.get("debug_captures"), dict)` | L528 | +| `.\gui_app.py` | `debug_captures_box = ttk.LabelFrame(debug_tab, text="调试图像清理")` | L882 | +| `.\gui_app.py` | `debug_captures_box.pack(fill=X, padx=10, pady=(10, 10))` | L883 | +| `.\gui_app.py` | `debug_r0 = ttk.Frame(debug_captures_box)` | L885 | +| `.\gui_app.py` | `debug_r0, text="启用自动清理调试图像", variable=debug_captures_auto_cleanup_var` | L888 | +| `.\gui_app.py` | `debug_r1 = ttk.Frame(debug_captures_box)` | L891 | +| `.\gui_app.py` | `textvariable=debug_captures_keep_days_var,` | L899 | +| `.\gui_app.py` | `textvariable=debug_captures_max_files_var,` | L908 | +| `.\gui_app.py` | `debug_captures_config = cfg.get("debug_captures", \{})` | L1249 | +| `.\gui_app.py` | `if isinstance(debug_captures_config, dict):` | L1250 | +| `.\gui_app.py` | `debug_captures_auto_cleanup_var.set(` | L1251 | +| `.\gui_app.py` | `bool(debug_captures_config.get("auto_cleanup", True))` | L1252 | +| `.\gui_app.py` | `debug_captures_keep_days_var.set(` | L1254 | +| `.\gui_app.py` | `int(debug_captures_config.get("keep_days", 7) or 7)` | L1255 | +| `.\gui_app.py` | `debug_captures_max_files_var.set(` | L1257 | +| `.\gui_app.py` | `int(debug_captures_config.get("max_files", 2000) or 2000)` | L1258 | +| `.\gui_app.py` | `debug_captures_auto_cleanup_var.set(True)` | L1261 | +| `.\gui_app.py` | `debug_captures_keep_days_var.set(7)` | L1262 | +| `.\gui_app.py` | `debug_captures_max_files_var.set(2000)` | L1263 | +| `.\gui_app.py` | `if "debug_captures" not in cfg2 or not isinstance(cfg2["debug_captures"], dict):` | L1438 | +| `.\gui_app.py` | `cfg2["debug_captures"] = \{}` | L1439 | +| `.\gui_app.py` | `cfg2["debug_captures"]["auto_cleanup"] = bool(` | L1440 | +| `.\gui_app.py` | `debug_captures_auto_cleanup_var.get()` | L1441 | +| `.\gui_app.py` | `cfg2["debug_captures"]["keep_days"] = int(` | L1443 | +| `.\gui_app.py` | `debug_captures_keep_days_var.get() or 7` | L1444 | +| `.\gui_app.py` | `cfg2["debug_captures"]["max_files"] = int(` | L1446 | +| `.\gui_app.py` | `debug_captures_max_files_var.get() or 2000` | L1447 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `├── debug_captures/ # 调试图像存档根目录` | L14 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `[调试图像] cut_pic保存: pic/debug_captures/2024-12-01/20241201_143022_cut_pic_福袋内容_before_ocr_(390,1240)-(980,1470).png` | L100 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `[调试图像] OCR预处理保存: pic/debug_captures/2024-12-01/20241201_143025_ocr_福袋内容_preprocessed_mode_0_size_590x230.png` | L101 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `[调试图像] OCR结果保存: pic/debug_captures/2024-12-01/20241201_143030_ocr_福袋内容_after_ocr_mode_0_text_len_25_text_preview_共1份1173人已参与.png, 文本: 共1份1173人已参与` | L102 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `[调试图像] 模板匹配前保存: pic/debug_captures/2024-12-01/20241201_143035_template_match_fudai_icon_before_match_(100,200)-(500,400).png` | L103 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `[调试图像] 模板匹配成功保存: pic/debug_captures/2024-12-01/20241201_143040_template_match_fudai_icon_matched_score_0.8523_loc_(45,120).png, score=0.8523, location=(45,120)` | L104 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `[调试图像] 像素检测前保存: pic/debug_captures/2024-12-01/20241201_143045_pixel_detect_lucky_draw_result_before_detect_(181,1261)-(890,1389).png` | L105 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `[调试图像] 像素检测成功保存: pic/debug_captures/2024-12-01/20241201_143050_pixel_detect_lucky_draw_result_detected_red_ratio_0.8523.png, red_ratio=0.8523` | L106 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `1. **按日期查看**:进入 `pic/debug_captures/YYYY-MM-DD/` 目录` | L113 | +| `.\DEBUG_IMAGE_SYSTEM.md` | `- `get_debug_captures_dir()`: 返回调试图像存档目录路径` | L176 | +| `.\webui\index.html` | `` | L651 | +| `.\webui\index.html` | `` | L659 | +| `.\webui\index.html` | `` | L664 | +| `.\webui\app.js` | `"debug_captures.auto_cleanup": true,` | L60 | +| `.\webui\app.js` | `"debug_captures.keep_days": 7,` | L61 | +| `.\webui\app.js` | `"debug_captures.max_files": 2000,` | L62 | +| `.\webui\app.js` | `// 支持嵌套键,如 "debug_captures.auto_cleanup"` | L505 | +| `.\webui\app.js` | `// 支持嵌套键,如 "debug_captures.auto_cleanup"` | L523 | +| `.\webui\app.js` | `// 支持嵌套键,如 "debug_captures.auto_cleanup"` | L574 | + + +
+
+ +--- + + +
Tool use: **read_file** • Read file: config.json + +
+
--- @@ -14158,11 +14317,1622 @@ _**Agent (model default, mode Agent)**_ --- + +
Tool use: **read_file** • Read file: douyin_screenshot_manager.py +
+
+ +--- + + +
Tool use: **read_file** • Read file: douyin_screenshot_manager.py + +
+
--- +--- + + +
Tool use: **read_file** • Read file: gui_app.py + +
+
+ +--- + + +
Tool use: **read_file** • Read file: gui_app.py + +
+
+ +--- + + +
Tool use: **read_file** • Read file: gui_app.py + +
+
+ +--- + + +
Tool use: **read_file** • Read file: gui_app.py + +
+
+ +--- + +
Thought Process +**Implementing Debug Captures** + +I'm planning to add a new boolean variable and checkbox for debug captures. First, I'll define `debug_captures_enabled_var` at the top, setting default to `False` for user compatibility. Then in `config.json`, I'll include `"enabled": false` to affect both GUI and CLI functions. + +For the GUI, I’ll set up the checkbox under the debug tab, probably above the auto_cleanup option. Lastly, I'll ensure the state is handled correctly when loading and saving the configuration. +**Integrating GUI Configurations** + +I see that the user uses both the desktop and web GUI, so it's important to align their configurations. To ensure we manage the saving of debug images correctly, I'll start by checking if the configuration path exists at the top of the function. If it doesn't exist or if the enabled flag is set to false, I'll return None. + +I’ll need to handle cases where the save_debug_image function is called before the GUI loads, ensuring compatibility throughout multiple modules. I'll also confirm that `os` is imported at the top of the file for necessary functionality.
+ +--- + + +
Tool use: **read_file** • Read file: douyin_screenshot_manager.py + +
+
+ +--- + + +
+Tool use: **apply_patch** + + +Parameters: + +```json +{ + "relativeWorkspacePath": "douyin_screenshot_manager.py" +} +``` +Additional data: + +```json +{ + "codeblockId": "49299c4e-569a-4fc1-97a1-236b81e36cf1" +} +``` +Result: + +```json +{ + "diff": { + "chunks": [ + { + "diffString": " \"\"\"\n try:\n+ # 从配置读取是否启用调试图像保存;默认关闭\n+ try:\n+ import json\n+ enabled = False\n+ config_path = path_config.get_config_path()\n+ if os.path.exists(config_path):\n+ with open(config_path, \"r\", encoding=\"utf-8\") as f:\n+ config = json.load(f)\n+ dbg_cfg = config.get(\"debug_captures\")\n+ if isinstance(dbg_cfg, dict):\n+ enabled = bool(dbg_cfg.get(\"enabled\", False))\n+ if not enabled:\n+ return None\n+ except Exception:\n+ # 配置读取异常时,为安全起见直接跳过保存调试图像\n+ return None\n+ \n # 自动清理旧目录(仅在每天第一次保存时执行)\n if auto_cleanup:", + "oldStart": 573, + "newStart": 573, + "oldLines": 4, + "newLines": 21, + "linesAdded": 17 + } + ], + "editor": "EDITOR_AI" + }, + "shouldAutoFixLints": true, + "resultForModel": "Success. Updated the following files:\nM douyin_screenshot_manager.py", + "contentsAfterEdit": "from __future__ import annotations\n\n\"\"\"\n截图管理模块:双截图记录机制\n============================\n\n功能:\n1. 实时操作截图(latest_attempt.png):每次识别操作都覆盖保存\n2. 成功识别存档截图(last_success.png):仅在成功时保存,不会被覆盖\n3. OCR文件夹清理:自动清理旧的OCR图片\n\"\"\"\n\nimport os\nimport shutil\nimport time\nfrom typing import Optional, Tuple\nfrom PIL import Image\nimport path_config\n\n\ndef get_ocr_dir() -> str:\n \"\"\"获取OCR目录路径\"\"\"\n return os.path.join(path_config.get_pic_dir(), \"ocr\")\n\n\ndef get_category_for_picname(picname: str) -> str:\n \"\"\"根据图片名称判断应该保存到哪个分类目录\n \n 参数:\n picname: 图片名称(不含扩展名)\n \n 返回:\n 分类目录名称,如 \"fudai\", \"live_room\", \"popups\", \"buttons\", \"stage_diag\", \"others\"\n \"\"\"\n picname_lower = picname.lower()\n \n # 福袋相关\n if any(keyword in picname_lower for keyword in [\"福袋\", \"fudai\"]):\n return \"fudai\"\n \n # 直播间相关\n if any(keyword in picname_lower for keyword in [\n \"live_room\", \"直播间\", \"直播列表\", \"直播广场\", \"直播状态\", \"直播验证\"\n ]):\n return \"live_room\"\n \n # 弹窗相关\n if any(keyword in picname_lower for keyword in [\n \"抽奖结果\", \"无奖励\", \"优惠券\", \"购物红包\", \"奖励通知\", \"订单确认\", \n \"lucky_draw\", \"coupon\", \"redpacket\", \"reward\", \"order\"\n ]):\n return \"popups\"\n \n # 按钮相关\n if any(keyword in picname_lower for keyword in [\n \"参与按钮\", \"粉丝团\", \"attend_button\", \"fans_club\"\n ]):\n return \"buttons\"\n \n # 阶段诊断相关\n if any(keyword in picname_lower for keyword in [\n \"推荐页\", \"关注列表\", \"直播列表标签\", \"recommend\", \"follow\", \"live_list\"\n ]):\n return \"stage_diag\"\n \n # 其他\n return \"others\"\n\n\ndef get_latest_attempt_path(operation_type: str = \"general\") -> str:\n \"\"\"获取实时操作截图路径\n \n 参数:\n operation_type: 操作类型,可选值:\n - \"pixel\" 或 \"pixel_detect\": 像素检测\n - \"ocr\": OCR识别\n - \"template\" 或 \"template_match\": 模板匹配\n - 其他: 通用操作\n \"\"\"\n # 规范化操作类型\n if operation_type.startswith(\"pixel\"):\n type_key = \"pixel\"\n elif operation_type.startswith(\"ocr\") or operation_type.startswith(\"cut_pic\"):\n type_key = \"ocr\"\n elif operation_type.startswith(\"template\"):\n type_key = \"template\"\n else:\n type_key = \"general\"\n \n return os.path.join(get_ocr_dir(), f\"latest_attempt_{type_key}.png\")\n\n\ndef get_last_success_path(operation_type: str = \"general\") -> str:\n \"\"\"获取成功识别存档截图路径\n \n 参数:\n operation_type: 操作类型,可选值:\n - \"pixel\" 或 \"pixel_detect\": 像素检测\n - \"ocr\": OCR识别\n - \"template\" 或 \"template_match\": 模板匹配\n - 其他: 通用操作\n \"\"\"\n # 规范化操作类型\n if operation_type.startswith(\"pixel\"):\n type_key = \"pixel\"\n elif operation_type.startswith(\"ocr\") or operation_type.startswith(\"cut_pic\"):\n type_key = \"ocr\"\n elif operation_type.startswith(\"template\"):\n type_key = \"template\"\n else:\n type_key = \"general\"\n \n return os.path.join(get_ocr_dir(), f\"last_success_{type_key}.png\")\n\n\ndef ensure_ocr_dir() -> None:\n \"\"\"确保OCR目录存在\"\"\"\n ocr_dir = get_ocr_dir()\n os.makedirs(ocr_dir, exist_ok=True)\n\n\ndef cleanup_ocr_dir(\n keep_latest_attempt: bool = True,\n keep_last_success: bool = True,\n keep_success_files: bool = True,\n max_files: int = 50,\n) -> int:\n \"\"\"清理OCR目录中的旧文件\n \n 参数:\n keep_latest_attempt: 是否保留所有 latest_attempt_*.png 文件\n keep_last_success: 是否保留所有 last_success_*.png 文件\n keep_success_files: 是否保留所有 _success.png 文件\n max_files: 最多保留的文件数(不包括特殊文件)\n \n 返回:\n 清理的文件数量\n \"\"\"\n try:\n ocr_dir = get_ocr_dir()\n if not os.path.exists(ocr_dir):\n return 0\n \n files = []\n for f in os.listdir(ocr_dir):\n file_path = os.path.join(ocr_dir, f)\n if os.path.isfile(file_path) and f.lower().endswith('.png'):\n # 检查是否为特殊文件\n is_special = False\n if f.startswith(\"latest_attempt_\") and keep_latest_attempt:\n is_special = True\n elif f.startswith(\"last_success_\") and keep_last_success:\n is_special = True\n elif f.endswith(\"_success.png\") and keep_success_files:\n is_special = True\n \n if not is_special:\n files.append((file_path, os.path.getmtime(file_path)))\n \n # 按修改时间排序,保留最新的\n files.sort(key=lambda x: x[1], reverse=True)\n \n # 删除超出限制的文件\n deleted_count = 0\n for file_path, _ in files[max_files:]:\n try:\n os.remove(file_path)\n deleted_count += 1\n except Exception:\n pass\n \n return deleted_count\n except Exception:\n return 0\n\n\ndef save_latest_attempt(image: Image.Image, operation_type: str = \"\") -> bool:\n \"\"\"保存实时操作截图(覆盖保存)\n \n 参数:\n image: PIL Image 对象\n operation_type: 操作类型(用于分类,如 \"template_match\", \"pixel_detect\", \"ocr\", \"cut_pic\")\n \n 返回:\n 是否保存成功\n \"\"\"\n try:\n ensure_ocr_dir()\n path = get_latest_attempt_path(operation_type)\n image.save(path, \"PNG\")\n return True\n except Exception as e:\n try:\n print(f\"[截图管理] 保存 latest_attempt_{operation_type}.png 失败: {e}\")\n except Exception:\n pass\n return False\n\n\ndef save_last_success(image: Image.Image, operation_type: str = \"\") -> bool:\n \"\"\"保存成功识别存档截图(不覆盖,仅成功时保存)\n \n 参数:\n image: PIL Image 对象\n operation_type: 操作类型(用于分类,如 \"template_match\", \"pixel_detect\", \"ocr\", \"cut_pic\")\n \n 返回:\n 是否保存成功\n \"\"\"\n try:\n ensure_ocr_dir()\n path = get_last_success_path(operation_type)\n image.save(path, \"PNG\")\n return True\n except Exception as e:\n try:\n print(f\"[截图管理] 保存 last_success_{operation_type}.png 失败: {e}\")\n except Exception:\n pass\n return False\n\n\ndef save_attempt_from_file(source_path: str, operation_type: str = \"\") -> bool:\n \"\"\"从文件保存实时操作截图\n \n 参数:\n source_path: 源图片文件路径\n operation_type: 操作类型\n \n 返回:\n 是否保存成功\n \"\"\"\n try:\n if not os.path.exists(source_path):\n return False\n image = Image.open(source_path)\n return save_latest_attempt(image, operation_type)\n except Exception as e:\n try:\n print(f\"[截图管理] 从文件保存 latest_attempt.png 失败: {e}\")\n except Exception:\n pass\n return False\n\n\ndef save_success_from_file(source_path: str, operation_type: str = \"\") -> bool:\n \"\"\"从文件保存成功识别存档截图\n \n 参数:\n source_path: 源图片文件路径\n operation_type: 操作类型\n \n 返回:\n 是否保存成功\n \"\"\"\n try:\n if not os.path.exists(source_path):\n return False\n image = Image.open(source_path)\n return save_last_success(image, operation_type)\n except Exception as e:\n try:\n print(f\"[截图管理] 从文件保存 last_success.png 失败: {e}\")\n except Exception:\n pass\n return False\n\n\ndef get_debug_captures_dir() -> str:\n \"\"\"获取调试图像存档目录路径\"\"\"\n pic_dir = path_config.get_pic_dir()\n debug_dir = os.path.join(pic_dir, \"debug_captures\")\n # 按日期分类:YYYY-MM-DD\n from datetime import datetime\n date_str = datetime.now().strftime(\"%Y-%m-%d\")\n return os.path.join(debug_dir, date_str)\n\n\ndef ensure_debug_captures_dir() -> None:\n \"\"\"确保调试图像存档目录存在\"\"\"\n try:\n debug_dir = get_debug_captures_dir()\n # 确保父目录也存在\n parent_dir = os.path.dirname(debug_dir)\n if parent_dir and not os.path.exists(parent_dir):\n os.makedirs(parent_dir, exist_ok=True)\n os.makedirs(debug_dir, exist_ok=True)\n except Exception as e:\n # 如果目录创建失败,记录错误但不抛出异常(让调用方处理)\n try:\n print(f\"[截图管理] 创建调试图像目录失败: {e}\")\n except Exception:\n pass\n raise\n\n\ndef get_debug_captures_base_dir() -> str:\n \"\"\"获取调试图像存档根目录路径(不包含日期)\"\"\"\n pic_dir = path_config.get_pic_dir()\n return os.path.join(pic_dir, \"debug_captures\")\n\n\ndef count_debug_captures_files() -> int:\n \"\"\"统计所有调试图像文件的总数量\n \n 返回:\n 文件总数\n \"\"\"\n try:\n debug_base_dir = get_debug_captures_base_dir()\n if not os.path.exists(debug_base_dir):\n return 0\n \n total_count = 0\n # 遍历所有日期目录\n for item in os.listdir(debug_base_dir):\n # 跳过隐藏文件和标记文件\n if item.startswith('.'):\n continue\n \n item_path = os.path.join(debug_base_dir, item)\n if not os.path.isdir(item_path):\n continue\n \n # 统计该目录下的所有PNG文件\n try:\n for root, dirs, files in os.walk(item_path):\n for f in files:\n if f.lower().endswith('.png'):\n total_count += 1\n except Exception:\n pass\n \n return total_count\n except Exception:\n return 0\n\n\ndef cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int:\n \"\"\"清理旧的调试图像存档目录\n \n 参数:\n keep_days: 保留天数,默认7天,超过此天数的目录将被删除\n max_files: 最大文件数量,默认2000,超过此数量时删除最旧的目录\n \n 返回:\n 清理的目录数量\n \"\"\"\n try:\n debug_base_dir = get_debug_captures_base_dir()\n if not os.path.exists(debug_base_dir):\n return 0\n \n from datetime import datetime, timedelta\n \n # 计算截止日期\n cutoff_date = datetime.now() - timedelta(days=keep_days)\n \n deleted_count = 0\n deleted_dirs = []\n total_size_freed = 0\n \n # 收集所有日期目录及其信息\n dirs_info = []\n for item in os.listdir(debug_base_dir):\n # 跳过隐藏文件和标记文件\n if item.startswith('.'):\n continue\n \n item_path = os.path.join(debug_base_dir, item)\n if not os.path.isdir(item_path):\n continue\n \n # 尝试解析目录名为日期(格式:YYYY-MM-DD)\n try:\n dir_date = datetime.strptime(item, \"%Y-%m-%d\")\n \n # 统计该目录下的文件数量和大小\n file_count = 0\n dir_size = 0\n try:\n for root, dirs, files in os.walk(item_path):\n for f in files:\n if f.lower().endswith('.png'):\n file_count += 1\n file_path = os.path.join(root, f)\n try:\n dir_size += os.path.getsize(file_path)\n except Exception:\n pass\n except Exception:\n pass\n \n dirs_info.append({\n 'name': item,\n 'path': item_path,\n 'date': dir_date,\n 'file_count': file_count,\n 'size': dir_size\n })\n except ValueError:\n # 如果目录名不是日期格式,跳过\n continue\n \n # 按日期排序(最旧的在前)\n dirs_info.sort(key=lambda x: x['date'])\n \n # 先按天数清理:删除超过保留天数的目录\n for dir_info in dirs_info[:]:\n if dir_info['date'] < cutoff_date:\n try:\n shutil.rmtree(dir_info['path'])\n deleted_count += 1\n deleted_dirs.append(dir_info['name'])\n total_size_freed += dir_info['size']\n dirs_info.remove(dir_info)\n except Exception as e:\n try:\n print(f\"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}\")\n except Exception:\n pass\n \n # 再按文件数量清理:如果文件总数超过max_files,删除最旧的目录\n total_files = sum(d['file_count'] for d in dirs_info)\n if total_files > max_files:\n # 计算需要删除的文件数量\n need_delete_count = total_files - max_files\n \n # 从最旧的目录开始删除,直到文件数量降到max_files以下\n deleted_files_count = 0\n for dir_info in dirs_info[:]:\n if deleted_files_count >= need_delete_count:\n break\n \n try:\n shutil.rmtree(dir_info['path'])\n deleted_count += 1\n deleted_dirs.append(dir_info['name'])\n total_size_freed += dir_info['size']\n deleted_files_count += dir_info['file_count']\n dirs_info.remove(dir_info)\n except Exception as e:\n try:\n print(f\"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}\")\n except Exception:\n pass\n \n if deleted_count > 0:\n try:\n size_mb = total_size_freed / (1024 * 1024)\n reason_parts = []\n if total_files > max_files:\n reason_parts.append(f\"文件数量超过{max_files}\")\n if any(d['date'] < cutoff_date for d in dirs_info if d not in [{'name': name} for name in deleted_dirs]):\n reason_parts.append(f\"超过{keep_days}天\")\n reason = \",\".join(reason_parts) if reason_parts else \"自动清理\"\n \n print(\n f\"[调试图像清理] 已删除 {deleted_count} 个调试图像目录: {', '.join(deleted_dirs)}\"\n )\n print(f\"[调试图像清理] 清理原因: {reason}\")\n if size_mb > 0.1: # 只显示大于0.1MB的清理\n print(f\"[调试图像清理] 释放空间: {size_mb:.2f} MB\")\n except Exception:\n pass\n \n return deleted_count\n except Exception as e:\n # 清理失败不应影响程序运行\n try:\n print(f\"[调试图像清理] 清理旧调试图像时出错: {e}\")\n except Exception:\n pass\n return 0\n\n\ndef init_debug_captures_cleanup() -> None:\n \"\"\"初始化调试图像清理(在程序启动时调用)\n \n 从 config.json 读取配置并执行清理\n \"\"\"\n try:\n import json\n config_path = path_config.get_config_path()\n if not os.path.exists(config_path):\n return\n \n with open(config_path, 'r', encoding='utf-8') as f:\n config = json.load(f)\n \n # 检查是否启用自动清理\n auto_cleanup = True\n keep_days = 7\n max_files = 2000\n \n if 'debug_captures' in config and isinstance(config['debug_captures'], dict):\n auto_cleanup = config['debug_captures'].get('auto_cleanup', True)\n keep_days = int(config['debug_captures'].get('keep_days', 7))\n max_files = int(config['debug_captures'].get('max_files', 2000))\n \n if auto_cleanup:\n cleanup_debug_captures(keep_days=keep_days, max_files=max_files)\n except Exception:\n # 初始化失败不影响程序运行\n pass\n\n\ndef _sanitize_filename_part(text: str) -> str:\n \"\"\"清理文件名部分,移除Windows不允许的字符\n \n 参数:\n text: 要清理的文本\n \n 返回:\n 清理后的文本\n \"\"\"\n if not text:\n return \"\"\n \n # Windows文件名不允许的字符: < > : \" / \\ | ? *\n # 同时移除路径分隔符和空格(用下划线替换)\n invalid_chars = '<>:\"/\\\\|?*'\n sanitized = str(text)\n \n # 如果是路径,只保留文件名部分\n if os.sep in sanitized or '/' in sanitized:\n sanitized = os.path.basename(sanitized)\n \n # 移除所有无效字符\n for char in invalid_chars:\n sanitized = sanitized.replace(char, '_')\n \n # 移除连续的下划线,替换为单个下划线\n while '__' in sanitized:\n sanitized = sanitized.replace('__', '_')\n \n # 移除首尾的下划线和空格\n sanitized = sanitized.strip('_').strip()\n \n # 如果清理后为空,返回默认值\n if not sanitized:\n sanitized = \"unknown\"\n \n return sanitized\n\n\ndef save_debug_image(\n image: Image.Image,\n operation_type: str = \"\",\n picname: str = \"\",\n step: str = \"\",\n coords: Optional[Tuple[int, int, int, int]] = None,\n extra_info: Optional[dict] = None,\n session_id: Optional[str] = None,\n annotate: bool = True,\n auto_cleanup: bool = True,\n) -> Optional[str]:\n \"\"\"保存调试图像到存档目录\n \n 参数:\n image: PIL Image 对象\n operation_type: 操作类型(\"pixel_detect\", \"ocr\", \"template_match\", \"cut_pic\")\n picname: 图片名称(可选)\n step: 步骤描述(可选,如 \"before_detect\", \"detected\")\n coords: 坐标信息 (x1, y1, x2, y2)(可选)\n extra_info: 额外信息字典(可选)\n session_id: 会话ID(可选,默认使用当前日期)\n annotate: 是否在图像上添加标注信息(默认True)\n auto_cleanup: 是否自动清理旧目录(默认True)\n \n 返回:\n 保存的文件路径,失败返回None\n \"\"\"\n try:\n # 从配置读取是否启用调试图像保存;默认关闭\n try:\n import json\n enabled = False\n config_path = path_config.get_config_path()\n if os.path.exists(config_path):\n with open(config_path, \"r\", encoding=\"utf-8\") as f:\n config = json.load(f)\n dbg_cfg = config.get(\"debug_captures\")\n if isinstance(dbg_cfg, dict):\n enabled = bool(dbg_cfg.get(\"enabled\", False))\n if not enabled:\n return None\n except Exception:\n # 配置读取异常时,为安全起见直接跳过保存调试图像\n return None\n\n # 自动清理旧目录(仅在每天第一次保存时执行)\n if auto_cleanup:\n try:\n # 检查今天是否已经清理过(使用简单的标记文件)\n debug_base_dir = get_debug_captures_base_dir()\n cleanup_marker = os.path.join(debug_base_dir, \".cleanup_marker\")\n from datetime import datetime\n today_str = datetime.now().strftime(\"%Y-%m-%d\")\n \n # 读取标记文件,检查今天是否已清理\n need_cleanup = True\n if os.path.exists(cleanup_marker):\n try:\n with open(cleanup_marker, 'r', encoding='utf-8') as f:\n last_cleanup_date = f.read().strip()\n if last_cleanup_date == today_str:\n need_cleanup = False\n except Exception:\n pass\n \n if need_cleanup:\n # 从配置读取保留天数、最大文件数和自动清理设置\n keep_days = 7 # 默认7天\n max_files = 2000 # 默认2000个文件\n cleanup_enabled = True\n try:\n import json\n config_path = path_config.get_config_path()\n if os.path.exists(config_path):\n with open(config_path, 'r', encoding='utf-8') as f:\n config = json.load(f)\n if 'debug_captures' in config and isinstance(config['debug_captures'], dict):\n cleanup_enabled = config['debug_captures'].get('auto_cleanup', True)\n keep_days = int(config['debug_captures'].get('keep_days', 7))\n max_files = int(config['debug_captures'].get('max_files', 2000))\n except Exception:\n pass\n \n # 如果启用自动清理,执行清理\n if cleanup_enabled:\n cleanup_debug_captures(keep_days=keep_days, max_files=max_files)\n \n # 更新标记文件(仅在执行清理后更新)\n try:\n with open(cleanup_marker, 'w', encoding='utf-8') as f:\n f.write(today_str)\n except Exception:\n pass\n else:\n # 即使今天已经清理过,也要检查文件数量是否超过限制\n # 如果超过,立即清理(不更新标记文件,避免频繁清理)\n try:\n import json\n config_path = path_config.get_config_path()\n max_files = 2000\n if os.path.exists(config_path):\n with open(config_path, 'r', encoding='utf-8') as f:\n config = json.load(f)\n if 'debug_captures' in config and isinstance(config['debug_captures'], dict):\n max_files = int(config['debug_captures'].get('max_files', 2000))\n \n # 检查当前文件数量\n current_count = count_debug_captures_files()\n if current_count > max_files:\n # 文件数量超过限制,立即清理\n try:\n print(f\"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理\")\n except Exception:\n pass\n cleanup_debug_captures(keep_days=999, max_files=max_files) # keep_days设为999表示只按文件数量清理\n except Exception:\n pass\n except Exception:\n # 清理失败不影响保存操作\n pass\n \n ensure_debug_captures_dir()\n debug_dir = get_debug_captures_dir()\n \n # 生成文件名\n from datetime import datetime\n timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n \n parts = []\n if operation_type:\n parts.append(_sanitize_filename_part(operation_type))\n if picname:\n parts.append(_sanitize_filename_part(picname))\n if step:\n parts.append(_sanitize_filename_part(step))\n if coords:\n parts.append(f\"({coords[0]},{coords[1]})-({coords[2]},{coords[3]})\")\n if extra_info:\n for key, value in extra_info.items():\n # 清理键名和值\n clean_key = _sanitize_filename_part(str(key))\n clean_value = _sanitize_filename_part(str(value))\n # 限制值的长度,避免文件名过长\n # 对于 text_preview 等长文本,限制更短(20字符)\n if key == \"text_preview\" or key == \"content\":\n if len(clean_value) > 20:\n clean_value = clean_value[:20]\n else:\n if len(clean_value) > 30:\n clean_value = clean_value[:30]\n parts.append(f\"{clean_key}_{clean_value}\")\n \n filename_parts = [timestamp] + parts\n filename = \"_\".join(str(p) for p in filename_parts if p) + \".png\"\n \n # Windows文件名长度限制(260字符),自动截断\n # 考虑完整路径长度,文件名部分限制更严格\n max_len = 180 # 留更多余量,考虑目录路径长度\n if len(filename) > max_len:\n # 保留时间戳和关键信息,截断其他部分\n # 优先保留:时间戳、操作类型、图片名、步骤\n base_parts = [timestamp]\n if operation_type:\n base_parts.append(_sanitize_filename_part(operation_type))\n if picname:\n base_parts.append(_sanitize_filename_part(picname))\n if step:\n base_parts.append(_sanitize_filename_part(step))\n \n base = \"_\".join(base_parts)\n \n # 如果还有空间,添加最重要的额外信息(排除长文本)\n remaining = max_len - len(base) - 10 # 留10字符余量\n if remaining > 20 and extra_info:\n important_keys = [\"mode\", \"size\", \"used_img2\", \"avg_confidence\"]\n for key in important_keys:\n if key in extra_info and remaining > 0:\n clean_key = _sanitize_filename_part(str(key))\n clean_value = _sanitize_filename_part(str(extra_info[key]))\n if len(clean_value) > 15:\n clean_value = clean_value[:15]\n part = f\"{clean_key}_{clean_value}\"\n if len(part) <= remaining:\n base += f\"_{part}\"\n remaining -= len(part) + 1\n \n filename = base[:max_len] + \".png\"\n \n file_path = os.path.join(debug_dir, filename)\n \n # 在保存文件前,再次确保目录存在(防止并发访问或权限问题导致目录不存在)\n try:\n ensure_debug_captures_dir()\n except Exception:\n pass # 如果目录创建失败,继续尝试保存,让保存时的异常处理来处理\n \n # 保存图像的辅助函数,带重试机制\n def save_image_with_retry(img_to_save: Image.Image, path: str, max_retries: int = 2) -> bool:\n \"\"\"保存图像,如果目录不存在则创建后重试\"\"\"\n for attempt in range(max_retries):\n try:\n img_to_save.save(path, \"PNG\")\n return True\n except FileNotFoundError:\n # 目录不存在,尝试创建后重试\n if attempt < max_retries - 1:\n try:\n ensure_debug_captures_dir()\n except Exception:\n pass\n else:\n # 最后一次尝试失败,抛出异常\n raise\n except Exception:\n # 其他异常直接抛出\n raise\n return False\n \n # 如果需要标注,在图像上添加信息\n if annotate and (coords or extra_info):\n try:\n from PIL import ImageDraw, ImageFont\n annotated_image = image.copy()\n draw = ImageDraw.Draw(annotated_image)\n \n # 尝试使用默认字体\n try:\n font = ImageFont.truetype(\"arial.ttf\", 12)\n except Exception:\n try:\n font = ImageFont.load_default()\n except Exception:\n font = None\n \n # 绘制坐标框\n if coords:\n x1, y1, x2, y2 = coords\n # 确保坐标在图像范围内\n img_w, img_h = annotated_image.size\n x1 = max(0, min(x1, img_w - 1))\n y1 = max(0, min(y1, img_h - 1))\n x2 = max(0, min(x2, img_w - 1))\n y2 = max(0, min(y2, img_h - 1))\n \n if x1 < x2 and y1 < y2:\n # 使用元组格式 (x1, y1, x2, y2)\n rect_coords: Tuple[float, float, float, float] = (float(x1), float(y1), float(x2), float(y2))\n draw.rectangle(rect_coords, outline=\"red\", width=2)\n \n # 添加文本信息\n if extra_info:\n text_lines = [f\"{k}: {v}\" for k, v in extra_info.items()]\n if text_lines:\n text = \"\\n\".join(text_lines)\n # 在图像左上角添加文本\n try:\n draw.text((5, 5), text, fill=\"yellow\", font=font)\n except Exception:\n pass\n \n save_image_with_retry(annotated_image, file_path)\n except Exception:\n # 如果标注失败,直接保存原图\n try:\n save_image_with_retry(image, file_path)\n except Exception:\n # 如果保存原图也失败,抛出异常让外层处理\n raise\n else:\n save_image_with_retry(image, file_path)\n \n return file_path\n except Exception as e:\n try:\n print(f\"[截图管理] 保存调试图像失败: {e}\")\n except Exception:\n pass\n return None\n\n" +} +``` +User decision: **accepted** + +Status: **completed** + + +
+
+ +--- + + +
+ Tool use: **read_lints** • Read lints for 1 file + +Lint paths: + +- `douyin_screenshot_manager.py` + +Lint results + +Lint errors for `douyin_screenshot_manager.py` + + +| Message | Range | Severity | +|-------|-------|----------| +| "time" 导入项未使用 | 15:8-15:12 | DIAGNOSTIC_SEVERITY_HINT | +| 变量 "root" 未使用 | 327:21-327:25 | DIAGNOSTIC_SEVERITY_HINT | +| 变量 "dirs" 未使用 | 327:27-327:31 | DIAGNOSTIC_SEVERITY_HINT | +| 变量 "dirs" 未使用 | 382:31-382:35 | DIAGNOSTIC_SEVERITY_HINT | +| "session_id" 未使用 | 554:5-554:15 | DIAGNOSTIC_SEVERITY_HINT | + + +
+
+ +--- + + +
Tool use: **read_file** • Read file: webui/app.js + +
+
+ +--- + + +
Tool use: **read_file** • Read file: webui/index.html + +
+
+ +--- + + +
+Tool use: **apply_patch** + + +Parameters: + +```json +{ + "relativeWorkspacePath": "webui/app.js" +} +``` +Additional data: + +```json +{ + "codeblockId": "e234992d-714c-43fe-a183-fdb3ebe6d100" +} +``` +Result: + +```json +{ + "diff": { + "chunks": [ + { + "diffString": " \r\n // 调试相关\r\n+ \"debug_captures.enabled\": false,\r\n \"debug_captures.auto_cleanup\": true,\r\n \"debug_captures.keep_days\": 7,\r", + "oldStart": 58, + "newStart": 58, + "oldLines": 4, + "newLines": 5, + "linesAdded": 1 + } + ], + "editor": "EDITOR_AI" + }, + "shouldAutoFixLints": true, + "resultForModel": "Success. Updated the following files:\nM webui/app.js", + "contentsAfterEdit": "let logIdx = 0;\r\nlet pollTimer = null;\r\nlet statsTimer = null;\r\nlet shotTimer = null;\r\nlet lastLogUpdateTime = 0; // 最后成功获取日志的时间\r\nlet logErrorCount = 0; // 连续错误计数\r\nlet emptyResponseCount = 0; // 连续空响应计数(用于检测索引卡住)\r\n\r\nconst DEFAULTS = {\r\n // 筛选\r\n min_prize_value_yuan: 0,\r\n min_participants: 0,\r\n max_participants: 0,\r\n skip_if_countdown_lt_seconds: 15,\r\n reset_after_swipes_enabled: false,\r\n reset_after_swipes: 10,\r\n auto_join_fansclub: false,\r\n fansclub_fail_action: \"stay\",\r\n\r\n // 养号\r\n yanghao_enabled: true,\r\n yanghao_enable_actions: true,\r\n yanghao_step_screenshot: false,\r\n yanghao_recommend_duration_seconds: 60,\r\n yanghao_recommend_interval_seconds: 0,\r\n yanghao_like_prob: 0.15,\r\n yanghao_fav_prob: 0.05,\r\n yanghao_comment_prob: 0,\r\n yanghao_icon_roi_size: 180,\r\n yanghao_icon_match_threshold: 0.72,\r\n yanghao_like_template_path: \"assets/like.png\",\r\n yanghao_fav_template_path: \"assets/fav.png\",\r\n yanghao_after_dwell_swipe_direction: \"up\",\r\n yanghao_after_dwell_swipe_distance_px: 900,\r\n\r\n // 高价值福袋预约\r\n high_value_fudai_enabled: false,\r\n high_value_fudai_threshold_yuan: 1000,\r\n high_value_fudai_join_ahead_seconds: 120,\r\n high_value_fudai_max_swipe_back: 60,\r\n high_value_fudai_max_reservations: 5,\r\n high_value_fudai_after_action: \"continue\",\r\n high_value_room_revisit_enabled: true,\r\n high_value_room_revisit_only_current_run: false,\r\n reservation_back_verify_enabled: true,\r\n // 找福袋图标相关\r\n fudai_find_max_attempts: 5,\r\n fudai_icon_retry_delay_seconds: 0.6,\r\n fudai_icon_max_wait_seconds: 5.0,\r\n live_room_match_threshold: 0.8,\r\n reservation_preempt_min_value: 0,\r\n reservation_back_swipe_delay: 0.6,\r\n\r\n // 定时禁抢福袋(默认 2-7 点)\r\n fudai_quiet_hours_enabled: true,\r\n fudai_quiet_start_hour: 2,\r\n fudai_quiet_end_hour: 7,\r\n\r\n // 调试相关\r\n \"debug_captures.enabled\": false,\r\n \"debug_captures.auto_cleanup\": true,\r\n \"debug_captures.keep_days\": 7,\r\n \"debug_captures.max_files\": 2000,\r\n enable_ocr_mode1: false,\r\n fudai_template_match_enabled: false,\r\n fudai_template_match_threshold: 0.7,\r\n lucky_draw_red_ratio_threshold: 0.8,\r\n live_room_match_threshold: 0.7,\r\n stage_diag_max_time: 15.0,\r\n stage_diag_max_step_time: 4.0,\r\n};\r\n\r\nfunction $(id) { return document.getElementById(id); }\r\n\r\nfunction initTabs() {\r\n const tabButtons = Array.from(document.querySelectorAll(\".tabBtn[data-target]\"));\r\n const panels = Array.from(document.querySelectorAll(\".panel[data-panel]\"));\r\n if (tabButtons.length === 0 || panels.length === 0) return;\r\n\r\n const setActive = (target) => {\r\n for (const btn of tabButtons) {\r\n const isActive = btn.dataset.target === target;\r\n btn.classList.toggle(\"active\", isActive);\r\n btn.setAttribute(\"aria-selected\", isActive ? \"true\" : \"false\");\r\n }\r\n for (const panel of panels) {\r\n const isActive = panel.dataset.panel === target;\r\n panel.toggleAttribute(\"hidden\", !isActive);\r\n panel.classList.toggle(\"active\", isActive);\r\n }\r\n };\r\n\r\n for (const btn of tabButtons) {\r\n btn.addEventListener(\"click\", () => setActive(btn.dataset.target));\r\n }\r\n\r\n const defaultTarget = tabButtons.find(b => b.classList.contains(\"active\"))?.dataset.target || tabButtons[0].dataset.target;\r\n setActive(defaultTarget);\r\n}\r\n\r\nfunction appendLog(lines) {\r\n const log = $(\"log\");\r\n if (!lines || lines.length === 0) return;\r\n \r\n // 检查是否在底部附近(用户可能在看最新日志)\r\n const wasNearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 100;\r\n \r\n // 性能优化:批量追加文本,减少重排次数\r\n const newText = lines.join(\"\\n\") + \"\\n\";\r\n log.textContent += newText;\r\n \r\n // 性能优化:限制日志长度,避免内存溢出(保留最近 50000 字符)\r\n const maxLength = 50000;\r\n if (log.textContent.length > maxLength) {\r\n log.textContent = log.textContent.slice(-maxLength);\r\n }\r\n \r\n // 只有在底部附近时才自动滚动,避免打断用户查看历史日志\r\n if (wasNearBottom) {\r\n log.scrollTop = log.scrollHeight;\r\n }\r\n}\r\n\r\nfunction fmtTime(ts) {\r\n if (!ts) return \"-\";\r\n try {\r\n return new Date(ts * 1000).toLocaleString();\r\n } catch {\r\n return \"-\";\r\n }\r\n}\r\n\r\nfunction fmtDuration(seconds) {\r\n const s = Math.max(0, parseInt(seconds || 0, 10));\r\n const h = Math.floor(s / 3600);\r\n const m = Math.floor((s % 3600) / 60);\r\n const sec = s % 60;\r\n if (h > 0) return `${h}小时${m}分${sec}秒`;\r\n if (m > 0) return `${m}分${sec}秒`;\r\n return `${sec}秒`;\r\n}\r\n\r\nfunction pollShot() {\r\n const img = $(\"liveShot\");\r\n if (!img) return;\r\n\r\n // 性能优化:避免重复加载相同的图片(如果正在加载中)\r\n if (img.dataset.loading === \"true\") return;\r\n \r\n const url = `/pic/screenshot.png?t=${Date.now()}`;\r\n img.dataset.loading = \"true\";\r\n img.src = url;\r\n\r\n const status = $(\"liveShotStatus\");\r\n if (status) status.textContent = `刷新中:${new Date().toLocaleTimeString()}`;\r\n}\r\n\r\nfunction startShotPolling() {\r\n if (shotTimer) clearInterval(shotTimer);\r\n\r\n const img = $(\"liveShot\");\r\n const status = $(\"liveShotStatus\");\r\n if (img) {\r\n img.addEventListener(\"load\", () => {\r\n img.dataset.loading = \"false\";\r\n if (status) status.textContent = `已更新:${new Date().toLocaleTimeString()}`;\r\n });\r\n img.addEventListener(\"error\", () => {\r\n img.dataset.loading = \"false\";\r\n if (status) status.textContent = \"暂无截图(等待脚本生成 pic/screenshot.png)\";\r\n });\r\n }\r\n\r\n // 性能优化:截图轮询间隔从 900ms 调整为 1500ms,减少服务器压力\r\n shotTimer = setInterval(pollShot, 1500);\r\n}\r\n\r\nfunction setTextIfExists(id, text) {\r\n const el = $(id);\r\n if (!el) return;\r\n el.textContent = String(text ?? \"-\");\r\n}\r\n\r\nfunction clearEl(el) {\r\n while (el && el.firstChild) el.removeChild(el.firstChild);\r\n}\r\n\r\n\r\nfunction renderBars(containerId, dataMap, labelMap) {\r\n const root = $(containerId);\r\n if (!root) return;\r\n clearEl(root);\r\n\r\n const m = (dataMap && typeof dataMap === \"object\") ? dataMap : {};\r\n const items = Object.keys(m).map(k => ({ key: k, count: Number(m[k]) || 0 }))\r\n .filter(x => x.count > 0);\r\n items.sort((a, b) => b.count - a.count);\r\n\r\n if (items.length === 0) {\r\n const d = document.createElement(\"div\");\r\n d.className = \"hint\";\r\n d.textContent = \"暂无数据\";\r\n root.appendChild(d);\r\n return;\r\n }\r\n\r\n const max = Math.max(...items.map(x => x.count));\r\n for (const it of items) {\r\n const row = document.createElement(\"div\");\r\n row.className = \"barRow\";\r\n\r\n const label = document.createElement(\"div\");\r\n label.className = \"barLabel\";\r\n label.textContent = (labelMap && labelMap[it.key]) ? labelMap[it.key] : it.key;\r\n\r\n const track = document.createElement(\"div\");\r\n track.className = \"barTrack\";\r\n const fill = document.createElement(\"div\");\r\n fill.className = \"barFill\";\r\n fill.style.width = `${max > 0 ? (it.count / max * 100) : 0}%`;\r\n track.appendChild(fill);\r\n\r\n const val = document.createElement(\"div\");\r\n val.className = \"barValue\";\r\n val.textContent = String(it.count);\r\n\r\n row.appendChild(label);\r\n row.appendChild(track);\r\n row.appendChild(val);\r\n root.appendChild(row);\r\n }\r\n}\r\n\r\nfunction renderTopContent(containerId, items) {\r\n const root = $(containerId);\r\n if (!root) return;\r\n clearEl(root);\r\n\r\n const list = Array.isArray(items) ? items : [];\r\n const head = document.createElement(\"div\");\r\n head.className = \"tableRow tableHead\";\r\n head.innerHTML = `<div>#</div><div>内容</div><div>次数</div>`;\r\n root.appendChild(head);\r\n\r\n if (list.length === 0) {\r\n const row = document.createElement(\"div\");\r\n row.className = \"tableRow\";\r\n row.innerHTML = `<div class=\"mono\">-</div><div class=\"hint\">暂无数据</div><div class=\"mono\">-</div>`;\r\n root.appendChild(row);\r\n return;\r\n }\r\n\r\n list.forEach((it, idx) => {\r\n const row = document.createElement(\"div\");\r\n row.className = \"tableRow\";\r\n const key = String(it.key ?? \"\");\r\n const cnt = Number(it.count) || 0;\r\n row.innerHTML = `<div class=\"mono\">#${idx + 1}</div><div>${escapeHtml(key)}</div><div class=\"mono\">${cnt}</div>`;\r\n root.appendChild(row);\r\n });\r\n}\r\n\r\nfunction escapeHtml(s) {\r\n return String(s ?? \"\")\r\n .replaceAll(\"&\", \"&amp;\")\r\n .replaceAll(\"<\", \"&lt;\")\r\n .replaceAll(\">\", \"&gt;\")\r\n .replaceAll('\"', \"&quot;\")\r\n .replaceAll(\"'\", \"&#39;\");\r\n}\r\n\r\nfunction renderWinsTable(containerId, wins) {\r\n const root = $(containerId);\r\n if (!root) return;\r\n clearEl(root);\r\n\r\n const list = Array.isArray(wins) ? wins : [];\r\n\r\n const head = document.createElement(\"div\");\r\n head.className = \"tableRow tableHead\";\r\n head.innerHTML = `<div>时间</div><div>内容</div><div>价值</div>`;\r\n root.appendChild(head);\r\n\r\n if (list.length === 0) {\r\n const row = document.createElement(\"div\");\r\n row.className = \"tableRow\";\r\n row.innerHTML = `<div class=\"mono\">-</div><div class=\"hint\">暂无中奖记录</div><div class=\"mono\">-</div>`;\r\n root.appendChild(row);\r\n return;\r\n }\r\n\r\n // 后端按时间顺序存储,这里倒序展示(最新在上)\r\n for (let i = list.length - 1; i >= 0; i--) {\r\n const it = list[i] || {};\r\n const ts = Number(it.ts) || 0;\r\n const content = String(it.content || \"-\");\r\n const value = (it.prize_value_yuan === null || typeof it.prize_value_yuan === \"undefined\") ? \"-\" : String(it.prize_value_yuan);\r\n\r\n const row = document.createElement(\"div\");\r\n row.className = \"tableRow\";\r\n row.innerHTML = `<div class=\"mono\">${escapeHtml(fmtTime(ts))}</div><div>${escapeHtml(content)}</div><div class=\"mono\">${escapeHtml(value)}</div>`;\r\n root.appendChild(row);\r\n }\r\n}\r\n\r\nfunction renderTimeline(containerId, timeline) {\r\n const root = $(containerId);\r\n if (!root) return;\r\n clearEl(root);\r\n\r\n const t = (timeline && typeof timeline === \"object\") ? timeline : null;\r\n const series = t && t.series && typeof t.series === \"object\" ? t.series : null;\r\n const bins = Number(t && t.bins) || 0;\r\n\r\n if (!series || bins <= 0) {\r\n const d = document.createElement(\"div\");\r\n d.className = \"hint\";\r\n d.textContent = \"暂无数据\";\r\n root.appendChild(d);\r\n return;\r\n }\r\n\r\n const keys = [\r\n \"fudai_open_detail\",\r\n \"fudai_attend_ok\",\r\n \"fudai_attend_fail\",\r\n \"fudai_result_win\",\r\n \"fudai_result_no_win\",\r\n \"fudai_skip\",\r\n \"switch_room\",\r\n ];\r\n\r\n let maxY = 0;\r\n for (const k of keys) {\r\n const arr = Array.isArray(series[k]) ? series[k] : [];\r\n for (const v of arr) maxY = Math.max(maxY, Number(v) || 0);\r\n }\r\n if (maxY <= 0) {\r\n const d = document.createElement(\"div\");\r\n d.className = \"hint\";\r\n d.textContent = \"暂无数据\";\r\n root.appendChild(d);\r\n return;\r\n }\r\n\r\n const W = 900;\r\n const H = 220;\r\n const padL = 36;\r\n const padR = 14;\r\n const padT = 10;\r\n const padB = 26;\r\n\r\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\r\n svg.setAttribute(\"viewBox\", `0 0 ${W} ${H}`);\r\n svg.setAttribute(\"width\", \"100%\");\r\n svg.setAttribute(\"height\", String(H));\r\n svg.style.display = \"block\";\r\n\r\n const axis = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\r\n axis.setAttribute(\"d\", `M ${padL} ${H - padB} L ${W - padR} ${H - padB}`);\r\n axis.setAttribute(\"stroke\", \"var(--border)\");\r\n axis.setAttribute(\"fill\", \"none\");\r\n svg.appendChild(axis);\r\n\r\n const mkText = (x, y, txt, anchor = \"start\") => {\r\n const el = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\r\n el.setAttribute(\"x\", String(x));\r\n el.setAttribute(\"y\", String(y));\r\n el.setAttribute(\"fill\", \"var(--muted)\");\r\n el.setAttribute(\"font-size\", \"11\");\r\n el.setAttribute(\"text-anchor\", anchor);\r\n el.textContent = txt;\r\n return el;\r\n };\r\n\r\n const startTs = Number(t.start_ts) || 0;\r\n const binSec = Number(t.bin_seconds) || 0;\r\n const xAt = (i) => {\r\n if (bins <= 1) return padL;\r\n return padL + (W - padL - padR) * (i / (bins - 1));\r\n };\r\n const yAt = (v) => {\r\n const vv = Number(v) || 0;\r\n const h = (H - padT - padB);\r\n return (H - padB) - (vv / maxY) * h;\r\n };\r\n\r\n // y 轴 max 标记\r\n svg.appendChild(mkText(padL, padT + 10, String(maxY), \"start\"));\r\n\r\n // x 轴 3 个时间刻度\r\n const fmtShort = (ts) => {\r\n if (!ts) return \"-\";\r\n try { return new Date(ts * 1000).toLocaleTimeString(); } catch { return \"-\"; }\r\n };\r\n svg.appendChild(mkText(padL, H - 8, fmtShort(startTs), \"start\"));\r\n svg.appendChild(mkText((padL + (W - padR)) / 2, H - 8, fmtShort(startTs + Math.floor(bins / 2) * binSec), \"middle\"));\r\n svg.appendChild(mkText(W - padR, H - 8, fmtShort(startTs + (bins - 1) * binSec), \"end\"));\r\n\r\n const strokes = {\r\n fudai_open_detail: { stroke: \"var(--primary)\", dash: \"\" },\r\n fudai_attend_ok: { stroke: \"var(--primary)\", dash: \"6 4\" },\r\n fudai_attend_fail: { stroke: \"var(--danger)\", dash: \"\" },\r\n fudai_result_win: { stroke: \"var(--danger)\", dash: \"6 4\" },\r\n fudai_result_no_win: { stroke: \"var(--muted)\", dash: \"\" },\r\n fudai_skip: { stroke: \"var(--muted)\", dash: \"6 4\" },\r\n switch_room: { stroke: \"var(--text)\", dash: \"2 4\" },\r\n };\r\n\r\n for (const k of keys) {\r\n const arr = Array.isArray(series[k]) ? series[k] : [];\r\n if (arr.length === 0) continue;\r\n let d = \"\";\r\n for (let i = 0; i < Math.min(bins, arr.length); i++) {\r\n const x = xAt(i);\r\n const y = yAt(arr[i]);\r\n d += (i === 0) ? `M ${x.toFixed(2)} ${y.toFixed(2)}` : ` L ${x.toFixed(2)} ${y.toFixed(2)}`;\r\n }\r\n const p = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\r\n p.setAttribute(\"d\", d);\r\n p.setAttribute(\"fill\", \"none\");\r\n p.setAttribute(\"stroke\", strokes[k]?.stroke || \"var(--primary)\");\r\n p.setAttribute(\"stroke-width\", \"2\");\r\n if (strokes[k]?.dash) p.setAttribute(\"stroke-dasharray\", strokes[k].dash);\r\n p.setAttribute(\"stroke-linecap\", \"round\");\r\n p.setAttribute(\"stroke-linejoin\", \"round\");\r\n svg.appendChild(p);\r\n }\r\n\r\n root.appendChild(svg);\r\n\r\n const legend = document.createElement(\"div\");\r\n legend.className = \"hint\";\r\n legend.textContent = \"图例:实线/虚线区分同色不同事件\";\r\n root.appendChild(legend);\r\n}\r\n\r\nasync function apiGet(path) {\r\n const res = await fetch(path, { cache: \"no-store\" });\r\n if (!res.ok) throw new Error(await res.text());\r\n return await res.json();\r\n}\r\n\r\nasync function apiPost(path, body) {\r\n const res = await fetch(path, {\r\n method: \"POST\",\r\n headers: { \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body || {}),\r\n });\r\n const data = await res.json();\r\n if (!res.ok) {\r\n const errorMsg = data.error || data.message || res.statusText;\r\n const error = new Error(errorMsg);\r\n error.status = res.status;\r\n error.data = data;\r\n throw error;\r\n }\r\n return data;\r\n}\r\n\r\nasync function refreshDevices() {\r\n const data = await apiGet(\"/api/devices\");\r\n const sel = $(\"device\");\r\n sel.innerHTML = \"\";\r\n const devices = data.devices || [];\r\n\r\n const optAuto = document.createElement(\"option\");\r\n optAuto.value = \"\";\r\n optAuto.textContent = \"(auto)\";\r\n sel.appendChild(optAuto);\r\n\r\n for (const d of devices) {\r\n const opt = document.createElement(\"option\");\r\n opt.value = d;\r\n opt.textContent = d;\r\n sel.appendChild(opt);\r\n }\r\n\r\n $(\"adbStatus\").textContent = data.adb ? `adb: ${data.adb}` : \"未找到 adb.exe(请安装 platform-tools)\";\r\n}\r\n\r\nfunction getConfigBoundElements() {\r\n return Array.from(document.querySelectorAll(\"[data-key]\"));\r\n}\r\n\r\nfunction coerceValue(type, raw, isCheckbox) {\r\n if (type === \"bool\") return !!raw;\r\n if (type === \"int\") {\r\n const n = parseInt(String(raw ?? \"0\"), 10);\r\n return Number.isFinite(n) ? n : 0;\r\n }\r\n if (type === \"float\") {\r\n const n = parseFloat(String(raw ?? \"0\"));\r\n return Number.isFinite(n) ? n : 0;\r\n }\r\n if (type === \"list_lines\") {\r\n if (Array.isArray(raw)) return raw.map(x => String(x).trim()).filter(Boolean);\r\n return String(raw ?? \"\").split(\"\\n\").map(x => x.trim()).filter(Boolean);\r\n }\r\n if (isCheckbox) return !!raw;\r\n return String(raw ?? \"\");\r\n}\r\n\r\nfunction getNestedValue(obj, key) {\r\n if (!obj || !key) return undefined;\r\n // 支持嵌套键,如 \"debug_captures.auto_cleanup\"\r\n if (key.includes(\".\")) {\r\n const parts = key.split(\".\");\r\n let current = obj;\r\n for (const part of parts) {\r\n if (current && typeof current === \"object\" && part in current) {\r\n current = current[part];\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n return current;\r\n }\r\n return obj[key];\r\n}\r\n\r\nfunction setNestedValue(obj, key, value) {\r\n if (!obj || !key) return;\r\n // 支持嵌套键,如 \"debug_captures.auto_cleanup\"\r\n if (key.includes(\".\")) {\r\n const parts = key.split(\".\");\r\n let current = obj;\r\n for (let i = 0; i < parts.length - 1; i++) {\r\n const part = parts[i];\r\n if (!(part in current) || typeof current[part] !== \"object\" || current[part] === null) {\r\n current[part] = {};\r\n }\r\n current = current[part];\r\n }\r\n current[parts[parts.length - 1]] = value;\r\n } else {\r\n obj[key] = value;\r\n }\r\n}\r\n\r\nfunction applyConfigToUI(cfg) {\r\n for (const el of getConfigBoundElements()) {\r\n const key = el.dataset.key;\r\n const type = el.dataset.type || \"str\";\r\n const val = cfg ? getNestedValue(cfg, key) : undefined;\r\n\r\n // undefined/null 都视为\"未配置\":保留页面默认值\r\n const hasVal = !(typeof val === \"undefined\" || val === null);\r\n const useVal = hasVal ? val : (Object.prototype.hasOwnProperty.call(DEFAULTS, key) ? DEFAULTS[key] : undefined);\r\n if (typeof useVal === \"undefined\") continue;\r\n\r\n if (el.type === \"checkbox\") {\r\n el.checked = !!useVal;\r\n continue;\r\n }\r\n if (type === \"list_lines\") {\r\n el.value = (Array.isArray(useVal) ? useVal : []).join(\"\\n\");\r\n continue;\r\n }\r\n el.value = String(useVal);\r\n }\r\n}\r\n\r\nfunction collectConfigFromUI() {\r\n const out = {};\r\n for (const el of getConfigBoundElements()) {\r\n const key = el.dataset.key;\r\n const type = el.dataset.type || \"str\";\r\n if (!key) continue;\r\n\r\n const value = el.type === \"checkbox\" \r\n ? coerceValue(type, el.checked, true)\r\n : coerceValue(type, el.value, false);\r\n \r\n // 支持嵌套键,如 \"debug_captures.auto_cleanup\"\r\n setNestedValue(out, key, value);\r\n }\r\n return out;\r\n}\r\n\r\nasync function loadConfig() {\r\n const cfg = await apiGet(\"/api/config\");\r\n applyConfigToUI(cfg);\r\n appendLog([\"[WEB] 配置已加载\"]);\r\n}\r\n\r\nasync function saveConfig() {\r\n const cfgUpdate = collectConfigFromUI();\r\n await apiPost(\"/api/config\", cfgUpdate);\r\n appendLog([\"[WEB] 配置已保存到 config.json\"]);\r\n}\r\n\r\nasync function startRun() {\r\n try {\r\n const deviceId = $(\"device\").value || \"\";\r\n const yPianyi = parseInt($(\"y_pianyi\").value || \"0\", 10);\r\n const waitMinutes = parseInt($(\"wait_minutes\").value || \"5\", 10);\r\n const needswitch = $(\"needswitch\").checked;\r\n const cfgPart = collectConfigFromUI();\r\n\r\n appendLog([`[WEB] 正在启动...`]);\r\n \r\n const result = await apiPost(\"/api/start-run\", {\r\n device_id: deviceId,\r\n y_pianyi: yPianyi,\r\n wait_minutes: waitMinutes,\r\n needswitch,\r\n reset_after_swipes_enabled: cfgPart.reset_after_swipes_enabled,\r\n min_prize_value_yuan: cfgPart.min_prize_value_yuan,\r\n min_participants: cfgPart.min_participants,\r\n max_participants: cfgPart.max_participants,\r\n skip_if_countdown_lt_seconds: cfgPart.skip_if_countdown_lt_seconds,\r\n reset_after_swipes: cfgPart.reset_after_swipes,\r\n auto_join_fansclub: cfgPart.auto_join_fansclub,\r\n fansclub_fail_action: cfgPart.fansclub_fail_action,\r\n high_value_room_revisit_enabled: cfgPart.high_value_room_revisit_enabled,\r\n high_value_room_revisit_only_current_run: cfgPart.high_value_room_revisit_only_current_run,\r\n reservation_back_verify_enabled: cfgPart.reservation_back_verify_enabled,\r\n reservation_back_swipe_delay: cfgPart.reservation_back_swipe_delay,\r\n fudai_find_max_attempts: cfgPart.fudai_find_max_attempts,\r\n reservation_preempt_min_value: cfgPart.reservation_preempt_min_value,\r\n });\r\n \r\n // 检查返回结果\r\n if (result && result.ok === false) {\r\n const errorMsg = result.error || \"未知错误\";\r\n appendLog([`[WEB] 启动失败: ${errorMsg}`]);\r\n if (errorMsg === \"running\") {\r\n appendLog([`[WEB] 提示:已有进程在运行中,请先点击\"停止\"按钮`]);\r\n }\r\n return;\r\n }\r\n \r\n appendLog([`[WEB] 已开始运行:device=${deviceId || '(auto)'}`]);\r\n \r\n // 启动时自动截图\r\n if (deviceId) {\r\n try {\r\n appendLog([\"[截图] 启动时自动截图...\"]);\r\n const screenshotResult = await apiPost(\"/api/screenshot\", { device_id: deviceId });\r\n if (screenshotResult.ok) {\r\n appendLog([\"[截图] 启动截图成功,已保存到 pic/screenshot.png\"]);\r\n // 刷新截图显示\r\n pollShot();\r\n } else {\r\n appendLog([`[截图] 启动截图失败: ${screenshotResult.error || \"未知错误\"}`]);\r\n }\r\n } catch (e) {\r\n appendLog([`[截图] 启动截图失败: ${e?.message || e}`]);\r\n }\r\n }\r\n \r\n // 重置本地日志索引并清空显示区域,然后立即拉取最新日志\r\n try {\r\n logIdx = 0;\r\n emptyResponseCount = 0; // 重置空响应计数\r\n // 清空日志显示区域,准备显示新进程的日志\r\n const logEl = $(\"log\");\r\n if (logEl) {\r\n logEl.textContent = \"\";\r\n }\r\n await pollLogs();\r\n } catch (e) {\r\n console.error(\"[WEB] pollLogs error after start:\", e);\r\n }\r\n } catch (e) {\r\n console.error(\"[WEB] startRun error:\", e);\r\n const errorMsg = e.message || String(e);\r\n appendLog([`[WEB] 启动失败: ${errorMsg}`]);\r\n // 如果是\"running\"错误,显示友好提示\r\n if (errorMsg === \"running\" || (e.status === 409)) {\r\n appendLog([`[WEB] 提示:已有进程在运行中,请先点击\"停止\"按钮`]);\r\n }\r\n }\r\n}\r\n\r\nasync function testYanghao() {\r\n const deviceId = $(\"device\").value || \"\";\r\n const seconds = parseInt($(\"yanghao_recommend_duration_seconds\").value || \"60\", 10);\r\n await apiPost(\"/api/test-yanghao\", { device_id: deviceId, seconds });\r\n appendLog([`[WEB] 已启动测试养号:device=${deviceId || '(auto)'} seconds=${seconds}`]);\r\n}\r\n\r\nasync function testComment() {\r\n const deviceId = $(\"device\").value || \"\";\r\n const text = \"\";\r\n await apiPost(\"/api/test-comment\", { device_id: deviceId, text });\r\n appendLog([`[WEB] 已启动测试评论:device=${deviceId || '(auto)'}${text ? ' text=自定义' : ''}`]);\r\n}\r\n\r\nasync function stopRun() {\r\n await apiPost(\"/api/stop\", {});\r\n appendLog([\"[WEB] 已发送停止\"]);\r\n // 重置并拉取日志,确保能看到后端的停止确认输出\r\n try {\r\n logIdx = 0;\r\n emptyResponseCount = 0; // 重置空响应计数\r\n await pollLogs();\r\n } catch (e) {\r\n // ignore\r\n }\r\n}\r\n\r\nasync function pollLogs() {\r\n try {\r\n const data = await apiGet(`/api/logs?since=${logIdx}`);\r\n \r\n // 检查返回数据是否有效\r\n if (!data || typeof data !== 'object') {\r\n console.error('[WEB_DBG] pollLogs: invalid response data', data);\r\n logErrorCount++;\r\n return;\r\n }\r\n \r\n // 重置错误计数(API调用成功)\r\n logErrorCount = 0;\r\n // 记录API调用成功的时间(即使没有新日志,也说明连接正常)\r\n const apiCallTime = Date.now();\r\n \r\n // 获取返回的索引\r\n const nextIdx = typeof data.next === 'number' ? data.next : 0;\r\n \r\n // 如果返回的索引小于当前索引,说明日志被截断了,需要重置\r\n // 或者如果返回了所有日志(lines数量很大),也可能是重置了索引\r\n if (nextIdx < logIdx && logIdx > 0) {\r\n console.warn('[WEB_DBG] pollLogs: 检测到日志截断,重置索引', { oldIdx: logIdx, newIdx: nextIdx });\r\n logIdx = 0;\r\n emptyResponseCount = 0; // 重置空响应计数\r\n // 清空日志显示区域,准备重新显示\r\n const log = document.getElementById('log');\r\n if (log) {\r\n log.textContent = '';\r\n }\r\n // 重新请求一次以获取所有日志\r\n const retryData = await apiGet(`/api/logs?since=0`);\r\n if (retryData && typeof retryData === 'object' && Array.isArray(retryData.lines)) {\r\n logIdx = typeof retryData.next === 'number' ? retryData.next : 0;\r\n if (retryData.lines.length > 0) {\r\n appendLog(retryData.lines);\r\n }\r\n }\r\n return;\r\n }\r\n \r\n // 更新日志索引\r\n logIdx = nextIdx;\r\n // API调用成功,更新最后更新时间(不管是否有新日志)\r\n lastLogUpdateTime = apiCallTime;\r\n \r\n // 追加日志\r\n if (Array.isArray(data.lines) && data.lines.length > 0) {\r\n appendLog(data.lines);\r\n emptyResponseCount = 0; // 重置空响应计数\r\n } else {\r\n // 没有新日志是正常的(比如脚本没有运行),不需要重置索引\r\n // 只有在检测到索引不同步时才重置(已在前面处理)\r\n emptyResponseCount++;\r\n // 移除自动重置逻辑,避免在没有新日志时频繁清空日志显示\r\n }\r\n \r\n // 容错:确保索引不为负数\r\n if (logIdx < 0) {\r\n console.warn('[WEB_DBG] pollLogs: logIdx为负数,重置为0');\r\n logIdx = 0;\r\n emptyResponseCount = 0;\r\n }\r\n } catch (e) {\r\n logErrorCount++;\r\n console.error('[WEB_DBG] pollLogs error:', e);\r\n // 如果连续10次出错,重置索引\r\n if (logErrorCount >= 10) {\r\n console.warn('[WEB_DBG] pollLogs: 连续10次错误,重置索引');\r\n logIdx = 0;\r\n logErrorCount = 0;\r\n emptyResponseCount = 0; // 重置空响应计数\r\n }\r\n // 错误时不追加日志到界面,避免刷屏,只在控制台输出\r\n // 如果是网络错误或超时,不重置索引;如果是其他错误,考虑重置\r\n if (e.message && !e.message.includes('NetworkError') && !e.message.includes('Failed to fetch') && !e.message.includes('timeout')) {\r\n console.error('[WEB_DBG] pollLogs failed:', e.message);\r\n // 非网络错误,可能是数据格式错误,重置索引尝试恢复\r\n if (e.message.includes('JSON') || e.message.includes('parse')) {\r\n console.warn('[WEB_DBG] pollLogs: 数据解析错误,重置索引');\r\n logIdx = 0;\r\n emptyResponseCount = 0; // 重置空响应计数\r\n }\r\n }\r\n }\r\n}\r\n\r\nasync function pollReservations() {\r\n try {\r\n const data = await apiGet(`/api/reservations?t=${Date.now()}`);\r\n const container = $(\"reservationsContent\");\r\n if (!container) return;\r\n // 保留上次滚动位置\r\n const prevList = container.querySelector('.reservationsList');\r\n const prevScroll = prevList ? prevList.scrollTop : 0;\r\n clearEl(container);\r\n \r\n const reservations = data.reservations || [];\r\n const room_pos = data.room_pos || 0;\r\n const updated_ts = data.updated_ts || 0;\r\n const current_room_title = data.current_room_title || \"\";\r\n const current_room_title_raw = data.current_room_title_raw || \"\";\r\n const reason = data.reason || \"\";\r\n \r\n // 显示基本信息\r\n const info = document.createElement(\"div\");\r\n info.className = \"reservationsInfo\";\r\n info.innerHTML = `\r\n <div><strong>当前位置:</strong>${room_pos}</div>\r\n <div><strong>当前直播间(清洗后):</strong>${escapeHtml(current_room_title || '-') }</div>\r\n <div><strong>当前直播间原文:</strong>${escapeHtml(current_room_title_raw || '-') }</div>\r\n <div><strong>预约数量:</strong>${reservations.length}</div>\r\n <div class=\"hint\">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}</div>\r\n <div class=\"hint\">原因:${escapeHtml(reason || '-') }</div>\r\n `;\r\n container.appendChild(info);\r\n\r\n if (reservations.length === 0) {\r\n const hint = document.createElement(\"div\");\r\n hint.className = \"hint\";\r\n hint.textContent = \"暂无预约信息\";\r\n container.appendChild(hint);\r\n return;\r\n }\r\n \r\n // 显示预约列表\r\n const list = document.createElement(\"div\");\r\n list.className = \"reservationsList\";\r\n \r\n reservations.forEach((item, idx) => {\r\n const card = document.createElement(\"div\");\r\n card.className = \"reservationItem\";\r\n \r\n const now = Date.now() / 1000;\r\n const future_ts = item.future_ts || 0;\r\n const remain = Math.max(0, Math.floor(future_ts - now));\r\n const remainStr = remain > 0 ? `${Math.floor(remain / 60)}分${remain % 60}秒后` : \"已到开奖时间\";\r\n \r\n card.innerHTML = `\r\n <div class=\"reservationHeader\">\r\n <span class=\"reservationIndex\">#${idx + 1}</span>\r\n <span class=\"reservationValue\">${item.prize_value_yuan || 0}元</span>\r\n </div>\r\n <div class=\"reservationBody\">\r\n <div><strong>内容:</strong>${escapeHtml(item.content || '-')}</div>\r\n <div><strong>开奖时间:</strong>${item.future_str || '-'}</div>\r\n <div><strong>剩余时间:</strong>${remainStr}</div>\r\n <div><strong>发现位置:</strong>${item.pos_seen || 0}</div>\r\n <div><strong>直播间(清洗后):</strong>${escapeHtml(item.room_title || '-')}</div>\r\n <div><strong>直播间原文:</strong>${escapeHtml(item.room_title_raw || '-')}</div>\r\n </div>\r\n `;\r\n list.appendChild(card);\r\n });\r\n \r\n container.appendChild(list);\r\n // 恢复滚动位置(若有)\r\n try { list.scrollTop = prevScroll; } catch (e) { /* ignore */ }\r\n } catch (e) {\r\n console.error(\"poll reservations failed:\", e);\r\n const container = $(\"reservationsContent\");\r\n if (!container) return;\r\n clearEl(container);\r\n const hint = document.createElement(\"div\");\r\n hint.className = \"hint\";\r\n hint.textContent = `预约信息获取失败:${e?.message || e}`;\r\n container.appendChild(hint);\r\n }\r\n}\r\n\r\nasync function pollHighValueRooms() {\r\n try {\r\n const data = await apiGet(`/api/high-value-rooms?t=${Date.now()}`);\r\n const container = $(\"highValueRoomsContent\");\r\n if (!container) return;\r\n // 保留上次滚动位置\r\n const prevList = container.querySelector('.reservationsList');\r\n const prevScroll = prevList ? prevList.scrollTop : 0;\r\n clearEl(container);\r\n\r\n const rooms = Array.isArray(data.rooms) ? data.rooms : [];\r\n const updated_ts = Number(data.updated_ts) || 0;\r\n const reason = String(data.reason || \"\");\r\n const total = Number(data.total) || rooms.length;\r\n\r\n const info = document.createElement(\"div\");\r\n info.className = \"reservationsInfo\";\r\n info.innerHTML = `\r\n <div><strong>记录数量:</strong>${total}</div>\r\n <div class=\"hint\">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}</div>\r\n <div class=\"hint\">原因:${escapeHtml(reason || '-') }</div>\r\n `;\r\n container.appendChild(info);\r\n\r\n if (rooms.length === 0) {\r\n const hint = document.createElement(\"div\");\r\n hint.className = \"hint\";\r\n hint.textContent = \"暂无记录\";\r\n container.appendChild(hint);\r\n return;\r\n }\r\n\r\n const list = document.createElement(\"div\");\r\n list.className = \"reservationsList\";\r\n\r\n rooms.forEach((item, idx) => {\r\n const card = document.createElement(\"div\");\r\n card.className = \"reservationItem\";\r\n\r\n const roomTitle = String(item.room_title || \"-\");\r\n const roomRaw = String(item.room_title_raw_last || \"-\");\r\n const posSeen = (typeof item.pos_seen === \"number\") ? item.pos_seen : ((item.pos_seen === null || typeof item.pos_seen === \"undefined\") ? \"-\" : String(item.pos_seen));\r\n const firstSeen = Number(item.first_seen_ts) || 0;\r\n const lastSeen = Number(item.last_seen_ts) || 0;\r\n const seenCount = Number(item.seen_count) || 0;\r\n const maxVal = (item.max_prize_value_yuan === null || typeof item.max_prize_value_yuan === \"undefined\") ? \"-\" : String(item.max_prize_value_yuan);\r\n const lastVal = (item.last_prize_value_yuan === null || typeof item.last_prize_value_yuan === \"undefined\") ? \"-\" : String(item.last_prize_value_yuan);\r\n\r\n card.innerHTML = `\r\n <div class=\"reservationHeader\">\r\n <span class=\"reservationIndex\">#${idx + 1}</span>\r\n <span class=\"reservationValue\">max ${escapeHtml(maxVal)}元</span>\r\n </div>\r\n <div class=\"reservationBody\">\r\n <div><strong>直播间(清洗后):</strong>${escapeHtml(roomTitle)}</div>\r\n <div><strong>直播间原文:</strong>${escapeHtml(roomRaw)}</div>\r\n <div><strong>最近位置:</strong>${escapeHtml(posSeen)}</div>\r\n <div><strong>首次记录:</strong>${escapeHtml(fmtTime(firstSeen))}</div>\r\n <div><strong>最近记录:</strong>${escapeHtml(fmtTime(lastSeen))}</div>\r\n <div><strong>记录次数:</strong>${escapeHtml(seenCount)}</div>\r\n <div><strong>最近价值:</strong>${escapeHtml(lastVal)}元</div>\r\n </div>\r\n `;\r\n // 让每条记录的 header 可点击以折叠/展开本条详情\r\n list.appendChild(card);\r\n try {\r\n const header = card.querySelector('.reservationHeader');\r\n const body = card.querySelector('.reservationBody');\r\n if (header && body) {\r\n header.style.cursor = 'pointer';\r\n header.addEventListener('click', () => {\r\n if (body.style.display === 'none') {\r\n body.style.display = '';\r\n } else {\r\n body.style.display = 'none';\r\n }\r\n });\r\n }\r\n } catch (e) {\r\n // ignore\r\n }\r\n \r\n });\r\n\r\n container.appendChild(list);\r\n // 恢复滚动位置(若有)\r\n try { list.scrollTop = prevScroll; } catch (e) { /* ignore */ }\r\n // 全局折叠/展开按钮绑定:折叠/展开整个列表(隐藏序号/条目),而不是仅隐藏每条的详情\r\n try {\r\n const btnExpand = $('hv_expand_all');\r\n const btnCollapse = $('hv_collapse_all');\r\n if (btnExpand) btnExpand.addEventListener('click', () => {\r\n const listEl = container.querySelector('.reservationsList');\r\n if (listEl) listEl.style.display = '';\r\n });\r\n if (btnCollapse) btnCollapse.addEventListener('click', () => {\r\n const listEl = container.querySelector('.reservationsList');\r\n if (listEl) listEl.style.display = 'none';\r\n });\r\n } catch (e) {\r\n // ignore\r\n }\r\n } catch (e) {\r\n console.error(\"poll high value rooms failed:\", e);\r\n const container = $(\"highValueRoomsContent\");\r\n if (!container) return;\r\n clearEl(container);\r\n const hint = document.createElement(\"div\");\r\n hint.className = \"hint\";\r\n hint.textContent = `直播间记录获取失败:${e?.message || e}`;\r\n container.appendChild(hint);\r\n }\r\n}\r\n\r\nasync function pollStats() {\r\n try {\r\n const s = await apiGet(`/api/stats?t=${Date.now()}`);\r\n const running = s.running ? \"运行中\" : \"未运行\";\r\n setTextIfExists(\"statRunning\", running);\r\n setTextIfExists(\"statPid\", s.pid ?? \"-\");\r\n setTextIfExists(\"statUptime\", fmtDuration(s.uptime_seconds));\r\n setTextIfExists(\"statLogLen\", s.log_len ?? \"-\");\r\n if ($(\"statLogCap\")) {\r\n const cap = s.log_capacity ?? 2000;\r\n const len = s.log_len ?? 0;\r\n $(\"statLogCap\").textContent = `缓存上限:${cap}(已用 ${len}/${cap})`;\r\n }\r\n setTextIfExists(\"statLastLog\", fmtTime(s.last_log_ts));\r\n setTextIfExists(\"statExitCode\", (s.exit_code === null || typeof s.exit_code === \"undefined\") ? \"-\" : s.exit_code);\r\n \r\n // 显示traceId和MDC信息\r\n const traceId = s.trace_id || \"-\";\r\n setTextIfExists(\"statTraceId\", traceId);\r\n const mdcContext = s.mdc_context || {};\r\n if ($(\"statTraceIdHint\")) {\r\n const mdcKeys = Object.keys(mdcContext);\r\n if (mdcKeys.length > 0) {\r\n const mdcStr = mdcKeys.map(k => `${k}=${mdcContext[k]}`).join(\", \");\r\n $(\"statTraceIdHint\").textContent = `MDC: ${mdcStr}`;\r\n } else {\r\n $(\"statTraceIdHint\").textContent = \"\";\r\n }\r\n }\r\n\r\n const c = s.counters || {};\r\n const getC = (k) => Number.isFinite(Number(c[k])) ? Number(c[k]) : 0;\r\n\r\n setTextIfExists(\"statFudaiSeen\", getC(\"fudai_seen\"));\r\n setTextIfExists(\"statFudaiOpen\", getC(\"fudai_open_detail\"));\r\n setTextIfExists(\"statFudaiAttendOk\", getC(\"fudai_attend_ok\"));\r\n setTextIfExists(\"statFudaiAttendFail\", getC(\"fudai_attend_fail\"));\r\n setTextIfExists(\"statFudaiNoWin\", getC(\"fudai_result_no_win\"));\r\n setTextIfExists(\"statFudaiWin\", getC(\"fudai_result_win\"));\r\n\r\n setTextIfExists(\"statSkipValueLow\", getC(\"fudai_skip_value_low\"));\r\n\r\n const pLow = getC(\"fudai_skip_participants_low\");\r\n const pHigh = getC(\"fudai_skip_participants_high\");\r\n setTextIfExists(\"statSkipParticipants\", pLow + pHigh);\r\n if ($(\"statSkipParticipantsHint\")) {\r\n $(\"statSkipParticipantsHint\").textContent = `低:${pLow} / 高:${pHigh}`;\r\n }\r\n\r\n setTextIfExists(\"statSkipContent\", getC(\"fudai_skip_content\"));\r\n\r\n const cdShort = getC(\"fudai_skip_countdown_short\");\r\n const cdLong = getC(\"fudai_skip_countdown_long\");\r\n setTextIfExists(\"statSkipCountdown\", cdShort + cdLong);\r\n if ($(\"statSkipCountdownHint\")) {\r\n $(\"statSkipCountdownHint\").textContent = `短:${cdShort} / 长:${cdLong}`;\r\n }\r\n\r\n const fcReq = getC(\"fansclub_required\");\r\n const fcManual = getC(\"fansclub_manual_needed\");\r\n const fcUn = getC(\"fansclub_unresolved\");\r\n setTextIfExists(\"statFansclub\", fcReq);\r\n if ($(\"statFansclubHint\")) {\r\n $(\"statFansclubHint\").textContent = `需手动:${fcManual} / 未解决:${fcUn}`;\r\n }\r\n\r\n const sw = getC(\"switch_room\");\r\n setTextIfExists(\"statSwitchRoom\", sw);\r\n if ($(\"statSwitchRoomHint\")) {\r\n const parts = [\r\n `无福袋:${getC(\"switch_room_no_fudai\")}`,\r\n `人数:${getC(\"switch_room_participants\")}`,\r\n `价值:${getC(\"switch_room_value\")}`,\r\n `内容:${getC(\"switch_room_content\")}`,\r\n `倒计时:${getC(\"switch_room_countdown\")}`,\r\n `参与失败:${getC(\"switch_room_attend_fail\")}`,\r\n ];\r\n $(\"statSwitchRoomHint\").textContent = parts.join(\" / \");\r\n }\r\n\r\n const last = s.fudai_last || {};\r\n setTextIfExists(\"statLastContent\", last.content || \"-\");\r\n setTextIfExists(\"statLastCountdown\", last.countdown || \"-\");\r\n const ppl = (typeof last.participants === \"number\") ? String(last.participants) : \"-\";\r\n const cop = (typeof last.copies === \"number\") ? String(last.copies) : \"-\";\r\n setTextIfExists(\"statLastPeople\", `${ppl} / ${cop}`);\r\n const val = (typeof last.prize_value_yuan === \"number\") ? String(last.prize_value_yuan) : \"-\";\r\n setTextIfExists(\"statLastValue\", val);\r\n if ($(\"statLastUpdated\")) {\r\n $(\"statLastUpdated\").textContent = last.updated_ts ? `更新时间:${fmtTime(last.updated_ts)}` : \"更新时间:-\";\r\n }\r\n\r\n // ====== 详细聚合渲染(趋势/分布/Top) ======\r\n const agg = s.agg || {};\r\n const reasonName = {\r\n value_low: \"价值过低\",\r\n participants_low: \"人数过少\",\r\n participants_high: \"人数过多\",\r\n content: \"内容不匹配\",\r\n countdown_short: \"倒计时太短\",\r\n countdown_long: \"倒计时太长\",\r\n unknown: \"未知\",\r\n };\r\n const switchName = {\r\n no_fudai: \"无福袋\",\r\n participants: \"人数不符合\",\r\n value: \"价值不符合\",\r\n content: \"内容不符合\",\r\n countdown: \"倒计时不符合\",\r\n attend_fail: \"参与失败\",\r\n unknown: \"未知\",\r\n };\r\n\r\n renderTimeline(\"chartTimeline\", agg.timeline);\r\n renderBars(\"chartSkipReason\", agg.skip_reason || {}, reasonName);\r\n renderBars(\"chartSwitchReason\", agg.switch_reason || {}, switchName);\r\n renderBars(\"chartValueBuckets\", agg.value_buckets || {});\r\n renderBars(\"chartParticipantsBuckets\", agg.participants_buckets || {});\r\n renderBars(\"chartCountdownBuckets\", agg.countdown_buckets || {});\r\n renderTopContent(\"tableTopContent\", agg.content_top || []);\r\n\r\n // ====== 中奖内容列表 ======\r\n renderWinsTable(\"tableWins\", s.wins || []);\r\n } catch (e) {\r\n // 统计失败不打断其他功能\r\n }\r\n}\r\n\r\nfunction startPolling() {\r\n if (pollTimer) clearInterval(pollTimer);\r\n // 性能优化:日志轮询间隔从 700ms 调整为 800ms,减少服务器压力同时保持实时性\r\n pollTimer = setInterval(pollLogs, 800);\r\n}\r\n\r\nfunction startStatsPolling() {\r\n if (statsTimer) clearInterval(statsTimer);\r\n statsTimer = setInterval(() => {\r\n pollStats();\r\n pollReservations();\r\n pollHighValueRooms();\r\n }, 1200);\r\n}\r\n\r\nwindow.addEventListener(\"DOMContentLoaded\", async () => {\r\n initTabs();\r\n $(\"btnRefresh\").addEventListener(\"click\", refreshDevices);\r\n $(\"btnLoad\").addEventListener(\"click\", async () => { await loadConfig(); });\r\n $(\"btnSave\").addEventListener(\"click\", async () => { await saveConfig(); });\r\n $(\"btnStart\").addEventListener(\"click\", async () => { await startRun(); });\r\n $(\"btnStop\").addEventListener(\"click\", async () => { await stopRun(); });\r\n \r\n // 截图按钮\r\n $(\"btnScreenshot\").addEventListener(\"click\", async () => {\r\n const deviceId = $(\"device\").value || \"\";\r\n if (!deviceId) {\r\n appendLog([\"[截图] 请先选择设备\"]);\r\n return;\r\n }\r\n try {\r\n appendLog([\"[截图] 正在截图...\"]);\r\n const result = await apiPost(\"/api/screenshot\", { device_id: deviceId });\r\n if (result.ok) {\r\n appendLog([\"[截图] 截图成功,已保存到 pic/screenshot.png\"]);\r\n // 刷新截图显示\r\n pollShot();\r\n } else {\r\n appendLog([`[截图] 截图失败: ${result.error || \"未知错误\"}`]);\r\n }\r\n } catch (e) {\r\n appendLog([`[截图] 截图失败: ${e?.message || e}`]);\r\n }\r\n });\r\n \r\n // 截图按钮\r\n $(\"btnScreenshot\").addEventListener(\"click\", async () => {\r\n const deviceId = $(\"device\").value || \"\";\r\n if (!deviceId) {\r\n appendLog([\"[截图] 请先选择设备\"]);\r\n return;\r\n }\r\n try {\r\n appendLog([\"[截图] 正在截图...\"]);\r\n const result = await apiPost(\"/api/screenshot\", { device_id: deviceId });\r\n if (result.ok) {\r\n appendLog([\"[截图] 截图成功,已保存到 pic/screenshot.png\"]);\r\n // 刷新截图显示\r\n pollShot();\r\n } else {\r\n appendLog([`[截图] 截图失败: ${result.error || \"未知错误\"}`]);\r\n }\r\n } catch (e) {\r\n appendLog([`[截图] 截图失败: ${e?.message || e}`]);\r\n }\r\n });\r\n\r\n await refreshDevices();\r\n await loadConfig();\r\n\r\n startPolling();\r\n startStatsPolling();\r\n startShotPolling();\r\n pollLogs();\r\n pollStats();\r\n pollShot();\r\n pollReservations();\r\n pollHighValueRooms();\r\n});" +} +``` +User decision: **accepted** + +Status: **completed** + + +
+
+ +--- + + +
+Tool use: **apply_patch** + + +Parameters: + +```json +{ + "relativeWorkspacePath": "webui/index.html" +} +``` +Additional data: + +```json +{ + "codeblockId": "34c25750-c6d1-4a2f-9650-2b13e82a1dcf" +} +``` +Result: + +```json +{ + "diff": { + "chunks": [ + { + "diffString": " 调试参数\r\n </div>\r\n+ \r\n+ <div class=\"sectionTitle\">调试图像</div>\r\n+ <div class=\"row\">\r\n+ <label class=\"label\">保存调试图像(OCR / 像素 / 模板等)</label>\r\n+ <label class=\"check\">\r\n+ <input id=\"debug_captures_enabled\" type=\"checkbox\" data-key=\"debug_captures.enabled\" data-type=\"bool\" />\r\n+ <span>启用</span>\r\n+ </label>\r\n+ <div class=\"hint\">关闭后不再保存调试截图,可显著减少磁盘占用和略微提升速度</div>\r\n+ </div>\r\n \r\n <div class=\"sectionTitle\">调试图像清理</div>\r", + "oldStart": 644, + "newStart": 644, + "oldLines": 4, + "newLines": 14, + "linesAdded": 10 + } + ], + "editor": "EDITOR_AI" + }, + "shouldAutoFixLints": true, + "resultForModel": "Success. Updated the following files:\nM webui/index.html", + "contentsAfterEdit": "<!doctype html>\r\n<html lang=\"zh-CN\">\r\n<head>\r\n <meta charset=\"utf-8\" />\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\r\n <title>抖音挂机 - Web GUI</title>\r\n <link rel=\"stylesheet\" href=\"styles.css\" />\r\n</head>\r\n<body>\r\n <div class=\"app\">\r\n <header class=\"header\">\r\n <div>\r\n <div class=\"title\">抖音挂机控制台</div>\r\n <div class=\"subtitle\">配置与运行(纯坐标点击)</div>\r\n </div>\r\n <div class=\"header-actions\">\r\n <button id=\"btnStart\" class=\"btn btnPrimary\">\r\n <span class=\"btnIcon\" aria-hidden=\"true\">\r\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M7 4v16l13-8z\"/></svg>\r\n </span>\r\n 开始运行\r\n </button>\r\n <button id=\"btnRefresh\" class=\"btn\">\r\n <span class=\"btnIcon\" aria-hidden=\"true\">\r\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M21 12a9 9 0 1 1-2.64-6.36\"/><path d=\"M21 3v6h-6\"/></svg>\r\n </span>\r\n 刷新设备\r\n </button>\r\n <button id=\"btnScreenshot\" class=\"btn\">\r\n <span class=\"btnIcon\" aria-hidden=\"true\">\r\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\" ry=\"2\"/><circle cx=\"8.5\" cy=\"8.5\" r=\"1.5\"/><polyline points=\"21 15 16 10 5 21\"/></svg>\r\n </span>\r\n 截图\r\n </button>\r\n <button id=\"btnLoad\" class=\"btn\">\r\n <span class=\"btnIcon\" aria-hidden=\"true\">\r\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\"/><path d=\"M7 10l5 5 5-5\"/><path d=\"M12 15V3\"/></svg>\r\n </span>\r\n 加载配置\r\n </button>\r\n <button id=\"btnSave\" class=\"btn btnPrimary\">\r\n <span class=\"btnIcon\" aria-hidden=\"true\">\r\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M19 21H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h11l5 5v9a2 2 0 0 1-2 2z\"/><path d=\"M17 21v-8H7v8\"/><path d=\"M7 3v5h8\"/></svg>\r\n </span>\r\n 保存配置\r\n </button>\r\n <button id=\"btnStop\" class=\"btn btnDanger\">\r\n <span class=\"btnIcon\" aria-hidden=\"true\">\r\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\"/></svg>\r\n </span>\r\n 停止\r\n </button>\r\n </div>\r\n </header>\r\n\r\n <main class=\"grid\">\r\n <section class=\"card cardScroll cardConfig\">\r\n <div class=\"cardTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\">\r\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"3\"/><path d=\"M19.4 15a1.7 1.7 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .31 1.7 1.7 0 0 0-.82 1.46V21a2 2 0 0 1-4 0v-.09a1.7 1.7 0 0 0-.82-1.46 1.7 1.7 0 0 0-1-.31 1.7 1.7 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.31-1 1.7 1.7 0 0 0-1.46-.82H2a2 2 0 0 1 0-4h.09a1.7 1.7 0 0 0 1.46-.82 1.7 1.7 0 0 0 .31-1 1.7 1.7 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.31 1.7 1.7 0 0 0 .82-1.46V2a2 2 0 0 1 4 0v.09a1.7 1.7 0 0 0 .82 1.46 1.7 1.7 0 0 0 1 .31 1.7 1.7 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.7 1.7 0 0 0 19.4 9a1.7 1.7 0 0 0 .31 1 1.7 1.7 0 0 0 1.46.82H22a2 2 0 0 1 0 4h-.09a1.7 1.7 0 0 0-1.46.82 1.7 1.7 0 0 0-.31 1z\"/></svg>\r\n </span>\r\n 配置\r\n </div>\r\n\r\n <div class=\"configLayout\">\r\n <nav class=\"sideNav\" role=\"tablist\" aria-label=\"配置分类\">\r\n <button class=\"tabBtn active\" type=\"button\" data-target=\"device\" role=\"tab\" aria-selected=\"true\">\r\n <span class=\"tabIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"7\" y=\"2\" width=\"10\" height=\"20\" rx=\"2\"/><path d=\"M11 19h2\"/></svg></span>\r\n <span class=\"tabText\">设备</span>\r\n </button>\r\n <button class=\"tabBtn\" type=\"button\" data-target=\"run\" role=\"tab\" aria-selected=\"false\">\r\n <span class=\"tabIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M12 20h9\"/><path d=\"M12 4h9\"/><path d=\"M4 9h16\"/><path d=\"M4 15h16\"/><circle cx=\"8\" cy=\"9\" r=\"2\"/><circle cx=\"8\" cy=\"15\" r=\"2\"/></svg></span>\r\n <span class=\"tabText\">运行</span>\r\n </button>\r\n <button class=\"tabBtn\" type=\"button\" data-target=\"filter\" role=\"tab\" aria-selected=\"false\">\r\n <span class=\"tabIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M22 3H2l8 9v7l4 2v-9z\"/></svg></span>\r\n <span class=\"tabText\">筛选</span>\r\n </button>\r\n <button class=\"tabBtn\" type=\"button\" data-target=\"stats\" role=\"tab\" aria-selected=\"false\">\r\n <span class=\"tabIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 19V5\"/><path d=\"M20 19V5\"/><path d=\"M8 17v-6\"/><path d=\"M12 17V9\"/><path d=\"M16 17V7\"/></svg></span>\r\n <span class=\"tabText\">统计</span>\r\n </button>\r\n <button class=\"tabBtn\" type=\"button\" data-target=\"yanghao\" role=\"tab\" aria-selected=\"false\">\r\n <span class=\"tabIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M20.8 4.6c-1.4-1.4-3.7-1.4-5.1 0L12 8.3 8.3 4.6c-1.4-1.4-3.7-1.4-5.1 0s-1.4 3.7 0 5.1L12 18.5l8.8-8.8c1.4-1.4 1.4-3.7 0-5.1z\"/></svg></span>\r\n <span class=\"tabText\">养号</span>\r\n </button>\r\n <button class=\"tabBtn\" type=\"button\" data-target=\"keywords\" role=\"tab\" aria-selected=\"false\">\r\n <span class=\"tabIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M21 10a7 7 0 1 1-14 0 7 7 0 0 1 14 0z\"/><path d=\"M21 21l-6-6\"/></svg></span>\r\n <span class=\"tabText\">关键词</span>\r\n </button>\r\n <button class=\"tabBtn\" type=\"button\" data-target=\"debug\" role=\"tab\" aria-selected=\"false\">\r\n <span class=\"tabIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 16v-4\"/><path d=\"M12 8h.01\"/></svg></span>\r\n <span class=\"tabText\">调试</span>\r\n </button>\r\n </nav>\r\n\r\n <div class=\"panels\">\r\n <div class=\"panel active\" data-panel=\"device\" role=\"tabpanel\">\r\n <div class=\"sectionTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"7\" y=\"2\" width=\"10\" height=\"20\" rx=\"2\"/><path d=\"M11 19h2\"/></svg></span>\r\n 设备\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">设备</label>\r\n <select id=\"device\" class=\"input\"></select>\r\n <div class=\"hint\" id=\"adbStatus\"></div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"panel\" data-panel=\"run\" role=\"tabpanel\" hidden>\r\n <div class=\"sectionTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M12 20h9\"/><path d=\"M12 4h9\"/><path d=\"M4 9h16\"/><path d=\"M4 15h16\"/><circle cx=\"8\" cy=\"9\" r=\"2\"/><circle cx=\"8\" cy=\"15\" r=\"2\"/></svg></span>\r\n 运行参数\r\n </div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">Y偏移</label>\r\n <input id=\"y_pianyi\" class=\"input\" type=\"number\" min=\"-200\" max=\"200\" step=\"1\" value=\"0\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">倒计时阈值(分钟)</label>\r\n <input id=\"wait_minutes\" class=\"input\" type=\"number\" min=\"1\" max=\"60\" step=\"1\" value=\"5\" />\r\n </div>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">允许切换直播间(needswitch)</label>\r\n <label class=\"check\">\r\n <input id=\"needswitch\" type=\"checkbox\" checked />\r\n <span>启用</span>\r\n </label>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">切换 N 次后回到第一个(开关)</label>\r\n <label class=\"check\">\r\n <input id=\"reset_after_swipes_enabled\" type=\"checkbox\" data-key=\"reset_after_swipes_enabled\" data-type=\"bool\" />\r\n <span>启用</span>\r\n </label>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">切换 N 次后回到第一个(次数)</label>\r\n <input id=\"reset_after_swipes\" class=\"input\" data-key=\"reset_after_swipes\" data-type=\"int\" type=\"number\" min=\"1\" step=\"1\" />\r\n <div class=\"hint\">用于需要循环切换时的回退阈值;配合上方开关启用</div>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">找福袋最大尝试次数</label>\r\n <input id=\"fudai_find_max_attempts\" class=\"input\" data-key=\"fudai_find_max_attempts\" data-type=\"int\" type=\"number\" min=\"1\" max=\"50\" step=\"1\" />\r\n <div class=\"hint\">找小福袋图标时的最大重试次数,默认 5</div>\r\n </div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">找福袋重试间隔(秒)</label>\r\n <input id=\"fudai_icon_retry_delay_seconds\" class=\"input\" data-key=\"fudai_icon_retry_delay_seconds\" data-type=\"float\" type=\"number\" min=\"0.1\" max=\"3.0\" step=\"0.1\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">找福袋最大等待时间(秒)</label>\r\n <input id=\"fudai_icon_max_wait_seconds\" class=\"input\" data-key=\"fudai_icon_max_wait_seconds\" data-type=\"float\" type=\"number\" min=\"0\" max=\"30\" step=\"0.5\" />\r\n <div class=\"hint\">识别到福袋一般 4–6 秒,可按设备/网络情况微调</div>\r\n </div>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">直播间检测阈值</label>\r\n <input id=\"live_room_match_threshold\" class=\"input\" data-key=\"live_room_match_threshold\" data-type=\"float\" type=\"number\" min=\"0.0\" max=\"1.0\" step=\"0.01\" />\r\n <div class=\"hint\">模板匹配阈值(0.0~1.0),默认0.8,值越高越严格,建议≥0.8</div>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">预约抢占最小价值(元)</label>\r\n <input id=\"reservation_preempt_min_value\" class=\"input\" data-key=\"reservation_preempt_min_value\" data-type=\"float\" type=\"number\" min=\"0\" step=\"1\" />\r\n <div class=\"hint\">低于该价值的预约不会抢占当前任务;0 表示任何预约可抢占</div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"panel\" data-panel=\"filter\" role=\"tabpanel\" hidden>\r\n <div class=\"sectionTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M22 3H2l8 9v7l4 2v-9z\"/></svg></span>\r\n 筛选设置\r\n </div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">最低价值(元)</label>\r\n <input id=\"min_prize_value_yuan\" class=\"input\" data-key=\"min_prize_value_yuan\" data-type=\"float\" type=\"number\" min=\"0\" step=\"0.1\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">倒计时小于(秒)时不参与(高价值可预约)</label>\r\n <input id=\"skip_if_countdown_lt_seconds\" class=\"input\" data-key=\"skip_if_countdown_lt_seconds\" data-type=\"int\" type=\"number\" min=\"0\" max=\"120\" step=\"1\" />\r\n </div>\r\n </div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">参与人数最小</label>\r\n <input id=\"min_participants\" class=\"input\" data-key=\"min_participants\" data-type=\"int\" type=\"number\" min=\"0\" step=\"1\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">参与人数最大</label>\r\n <input id=\"max_participants\" class=\"input\" data-key=\"max_participants\" data-type=\"int\" type=\"number\" min=\"0\" step=\"1\" />\r\n </div>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">自动加入粉丝团(谨慎)</label>\r\n <label class=\"check\">\r\n <input id=\"auto_join_fansclub\" type=\"checkbox\" data-key=\"auto_join_fansclub\" data-type=\"bool\" />\r\n <span>启用</span>\r\n </label>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">粉丝团失败策略</label>\r\n <select id=\"fansclub_fail_action\" class=\"input\" data-key=\"fansclub_fail_action\" data-type=\"str\">\r\n <option value=\"stay\">stay</option>\r\n <option value=\"switch\">switch</option>\r\n </select>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">高价值福袋预约参与</div>\r\n <div class=\"row\">\r\n <label class=\"label\">启用预约(价值≥阈值)</label>\r\n <label class=\"check\">\r\n <input id=\"high_value_fudai_enabled\" type=\"checkbox\" data-key=\"high_value_fudai_enabled\" data-type=\"bool\" />\r\n <span>启用</span>\r\n </label>\r\n </div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">价值阈值(元)</label>\r\n <input id=\"high_value_fudai_threshold_yuan\" class=\"input\" data-key=\"high_value_fudai_threshold_yuan\" data-type=\"float\" type=\"number\" min=\"0\" step=\"1\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">提前参与(秒)</label>\r\n <input id=\"high_value_fudai_join_ahead_seconds\" class=\"input\" data-key=\"high_value_fudai_join_ahead_seconds\" data-type=\"int\" type=\"number\" min=\"5\" max=\"900\" step=\"1\" />\r\n </div>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">最多回退直播间次数</label>\r\n <input id=\"high_value_fudai_max_swipe_back\" class=\"input\" data-key=\"high_value_fudai_max_swipe_back\" data-type=\"int\" type=\"number\" min=\"0\" max=\"300\" step=\"1\" />\r\n <div class=\"hint\">防止预约期间切换太远导致回退过慢/异常;0 表示不限制</div>\r\n </div>\r\n\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">最多记录数量</label>\r\n <input id=\"high_value_fudai_max_reservations\" class=\"input\" data-key=\"high_value_fudai_max_reservations\" data-type=\"int\" type=\"number\" min=\"1\" max=\"50\" step=\"1\" />\r\n <div class=\"hint\">超过后丢弃最晚开奖的预约</div>\r\n </div>\r\n <div>\r\n <label class=\"label\">完成后策略</label>\r\n <select id=\"high_value_fudai_after_action\" class=\"input\" data-key=\"high_value_fudai_after_action\" data-type=\"str\">\r\n <option value=\"continue\">continue</option>\r\n <option value=\"stay\">stay</option>\r\n </select>\r\n <div class=\"hint\">stay:停留当前直播间;continue:继续抢福袋</div>\r\n </div>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">启用高价值直播间定时回访</label>\r\n <label class=\"check\">\r\n <input id=\"high_value_room_revisit_enabled\" type=\"checkbox\" data-key=\"high_value_room_revisit_enabled\" data-type=\"bool\" />\r\n <span>启用</span>\r\n </label>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">仅回访本次运行记录的直播间</label>\r\n <label class=\"check\">\r\n <input id=\"high_value_room_revisit_only_current_run\" type=\"checkbox\" data-key=\"high_value_room_revisit_only_current_run\" data-type=\"bool\" />\r\n <span>仅本次运行</span>\r\n </label>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">预约回退后校验(回退校验开关)</label>\r\n <label class=\"check\">\r\n <input id=\"reservation_back_verify_enabled\" type=\"checkbox\" data-key=\"reservation_back_verify_enabled\" data-type=\"bool\" />\r\n <span>启用回退校验</span>\r\n </label>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">回退回滑快速延迟(秒,未启用回退校验时生效)</label>\r\n <input id=\"reservation_back_swipe_delay\" class=\"input\" data-key=\"reservation_back_swipe_delay\" data-type=\"float\" type=\"number\" min=\"0.2\" step=\"0.1\" />\r\n <div class=\"hint\">较小值能加快回退速度;当启用回退校验时仍使用兼容的较慢延迟。</div>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">定时禁抢(仅养号)</div>\r\n <div class=\"row\">\r\n <label class=\"label\">启用定时禁抢</label>\r\n <label class=\"check\">\r\n <input id=\"fudai_quiet_hours_enabled\" type=\"checkbox\" data-key=\"fudai_quiet_hours_enabled\" data-type=\"bool\" />\r\n <span>启用</span>\r\n </label>\r\n </div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">开始小时</label>\r\n <input id=\"fudai_quiet_start_hour\" class=\"input\" data-key=\"fudai_quiet_start_hour\" data-type=\"int\" type=\"number\" min=\"0\" max=\"23\" step=\"1\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">结束小时</label>\r\n <input id=\"fudai_quiet_end_hour\" class=\"input\" data-key=\"fudai_quiet_end_hour\" data-type=\"int\" type=\"number\" min=\"0\" max=\"23\" step=\"1\" />\r\n <div class=\"hint\">区间为 [开始, 结束),例如 2-7 表示 2:00~6:59</div>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"panel\" data-panel=\"stats\" role=\"tabpanel\" hidden>\r\n <div class=\"sectionTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 19V5\"/><path d=\"M20 19V5\"/><path d=\"M8 17v-6\"/><path d=\"M12 17V9\"/><path d=\"M16 17V7\"/></svg></span>\r\n 运行统计\r\n </div>\r\n\r\n <div class=\"sectionTitle\">福袋中奖内容(最近20条)</div>\r\n <div class=\"table\" id=\"tableWins\"></div>\r\n\r\n <div class=\"statsGrid\">\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">运行状态</div>\r\n <div id=\"statRunning\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">PID</div>\r\n <div id=\"statPid\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">运行时长</div>\r\n <div id=\"statUptime\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">日志行数</div>\r\n <div id=\"statLogLen\" class=\"statValue\">-</div>\r\n <div class=\"statHint\" id=\"statLogCap\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">最近日志时间</div>\r\n <div id=\"statLastLog\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">退出码</div>\r\n <div id=\"statExitCode\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">TraceId(请求追踪)</div>\r\n <div id=\"statTraceId\" class=\"statValue\" style=\"font-family: monospace; font-size: 0.9em;\">-</div>\r\n <div class=\"statHint\" id=\"statTraceIdHint\">-</div>\r\n </div>\r\n\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">福袋:识别次数</div>\r\n <div id=\"statFudaiSeen\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">福袋:打开详情</div>\r\n <div id=\"statFudaiOpen\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">福袋:参与成功/已参与</div>\r\n <div id=\"statFudaiAttendOk\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">福袋:参与失败</div>\r\n <div id=\"statFudaiAttendFail\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">福袋:未中奖次数</div>\r\n <div id=\"statFudaiNoWin\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">福袋:中奖次数</div>\r\n <div id=\"statFudaiWin\" class=\"statValue\">-</div>\r\n </div>\r\n\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">福袋:跳过(价值低)</div>\r\n <div id=\"statSkipValueLow\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">福袋:跳过(人数低/高)</div>\r\n <div id=\"statSkipParticipants\" class=\"statValue\">-</div>\r\n <div class=\"statHint\" id=\"statSkipParticipantsHint\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">福袋:跳过(内容不理想)</div>\r\n <div id=\"statSkipContent\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">福袋:跳过(倒计时短/长)</div>\r\n <div id=\"statSkipCountdown\" class=\"statValue\">-</div>\r\n <div class=\"statHint\" id=\"statSkipCountdownHint\">-</div>\r\n </div>\r\n\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">粉丝团门槛</div>\r\n <div id=\"statFansclub\" class=\"statValue\">-</div>\r\n <div class=\"statHint\" id=\"statFansclubHint\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">切换直播间次数</div>\r\n <div id=\"statSwitchRoom\" class=\"statValue\">-</div>\r\n <div class=\"statHint\" id=\"statSwitchRoomHint\">-</div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">最近识别到的福袋</div>\r\n <div class=\"statsGrid\">\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">内容</div>\r\n <div id=\"statLastContent\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">倒计时</div>\r\n <div id=\"statLastCountdown\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">参与人数 / 份数</div>\r\n <div id=\"statLastPeople\" class=\"statValue\">-</div>\r\n </div>\r\n <div class=\"stat\">\r\n <div class=\"statLabel\">奖品价值(元)</div>\r\n <div id=\"statLastValue\" class=\"statValue\">-</div>\r\n <div class=\"statHint\" id=\"statLastUpdated\">-</div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">趋势(最近2小时,5分钟粒度)</div>\r\n <div class=\"chartBlock\">\r\n <div class=\"chartTitle\">福袋关键动作趋势</div>\r\n <div id=\"chartTimeline\" class=\"chart\"></div>\r\n <div class=\"hint\">展示:打开详情 / 参与成功 / 参与失败 / 中奖 / 未中奖 / 跳过 / 切换直播间</div>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">分布</div>\r\n <div class=\"chartsGrid\">\r\n <div class=\"chartBlock\">\r\n <div class=\"chartTitle\">跳过原因</div>\r\n <div id=\"chartSkipReason\" class=\"chart\"></div>\r\n </div>\r\n <div class=\"chartBlock\">\r\n <div class=\"chartTitle\">切换直播间原因</div>\r\n <div id=\"chartSwitchReason\" class=\"chart\"></div>\r\n </div>\r\n <div class=\"chartBlock\">\r\n <div class=\"chartTitle\">奖品价值区间(元)</div>\r\n <div id=\"chartValueBuckets\" class=\"chart\"></div>\r\n </div>\r\n <div class=\"chartBlock\">\r\n <div class=\"chartTitle\">参与人数区间</div>\r\n <div id=\"chartParticipantsBuckets\" class=\"chart\"></div>\r\n </div>\r\n <div class=\"chartBlock\">\r\n <div class=\"chartTitle\">倒计时区间(秒)</div>\r\n <div id=\"chartCountdownBuckets\" class=\"chart\"></div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">Top 福袋内容</div>\r\n <div class=\"table\" id=\"tableTopContent\"></div>\r\n </div>\r\n\r\n <div class=\"panel\" data-panel=\"yanghao\" role=\"tabpanel\" hidden>\r\n <div class=\"sectionTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M20.8 4.6c-1.4-1.4-3.7-1.4-5.1 0L12 8.3 8.3 4.6c-1.4-1.4-3.7-1.4-5.1 0s-1.4 3.7 0 5.1L12 18.5l8.8-8.8c1.4-1.4 1.4-3.7 0-5.1z\"/></svg></span>\r\n 推荐页养号(爱心/收藏/评论)\r\n </div>\r\n\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">养号总开关(关闭=不跑推荐页养号)</label>\r\n <label class=\"check\">\r\n <input id=\"yanghao_enabled\" type=\"checkbox\" data-key=\"yanghao_enabled\" data-type=\"bool\" checked />\r\n <span>启用</span>\r\n </label>\r\n </div>\r\n <div>\r\n <label class=\"label\">养号动作开关(爱心/收藏/评论)</label>\r\n <label class=\"check\">\r\n <input id=\"yanghao_enable_actions\" type=\"checkbox\" data-key=\"yanghao_enable_actions\" data-type=\"bool\" checked />\r\n <span>启用</span>\r\n </label>\r\n </div>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">逐步截图(调试用)</label>\r\n <label class=\"check\">\r\n <input id=\"yanghao_step_screenshot\" type=\"checkbox\" data-key=\"yanghao_step_screenshot\" data-type=\"bool\" />\r\n <span>启用</span>\r\n </label>\r\n </div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">养号时长(秒)</label>\r\n <input id=\"yanghao_recommend_duration_seconds\" class=\"input\" data-key=\"yanghao_recommend_duration_seconds\" data-type=\"int\" type=\"number\" min=\"1\" max=\"3600\" step=\"5\" value=\"60\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">养号间隔(秒)</label>\r\n <input id=\"yanghao_recommend_interval_seconds\" class=\"input\" data-key=\"yanghao_recommend_interval_seconds\" data-type=\"int\" type=\"number\" min=\"0\" max=\"3600\" step=\"10\" value=\"0\" />\r\n <div class=\"hint\">0 表示每次触发都执行</div>\r\n </div>\r\n </div>\r\n <div class=\"row grid3\">\r\n <div>\r\n <label class=\"label\">爱心概率</label>\r\n <input id=\"yanghao_like_prob\" class=\"input\" data-key=\"yanghao_like_prob\" data-type=\"float\" type=\"number\" min=\"0\" max=\"1\" step=\"0.01\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">收藏概率</label>\r\n <input id=\"yanghao_fav_prob\" class=\"input\" data-key=\"yanghao_fav_prob\" data-type=\"float\" type=\"number\" min=\"0\" max=\"1\" step=\"0.01\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">评论概率</label>\r\n <input id=\"yanghao_comment_prob\" class=\"input\" data-key=\"yanghao_comment_prob\" data-type=\"float\" type=\"number\" min=\"0\" max=\"1\" step=\"0.01\" />\r\n </div>\r\n </div>\r\n\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">图标 ROI 大小(px)</label>\r\n <input id=\"yanghao_icon_roi_size\" class=\"input\" data-key=\"yanghao_icon_roi_size\" data-type=\"int\" type=\"number\" min=\"80\" max=\"600\" step=\"10\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">匹配阈值</label>\r\n <input id=\"yanghao_icon_match_threshold\" class=\"input\" data-key=\"yanghao_icon_match_threshold\" data-type=\"float\" type=\"number\" min=\"0\" max=\"1\" step=\"0.01\" />\r\n </div>\r\n </div>\r\n\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">爱心图标坐标(x,y)</label>\r\n <div class=\"inline2\">\r\n <input id=\"yanghao_like_icon_x\" class=\"input\" data-key=\"yanghao_like_icon_x\" data-type=\"int\" type=\"number\" />\r\n <input id=\"yanghao_like_icon_y\" class=\"input\" data-key=\"yanghao_like_icon_y\" data-type=\"int\" type=\"number\" />\r\n </div>\r\n </div>\r\n <div>\r\n <label class=\"label\">收藏图标坐标(x,y)</label>\r\n <div class=\"inline2\">\r\n <input id=\"yanghao_fav_icon_x\" class=\"input\" data-key=\"yanghao_fav_icon_x\" data-type=\"int\" type=\"number\" />\r\n <input id=\"yanghao_fav_icon_y\" class=\"input\" data-key=\"yanghao_fav_icon_y\" data-type=\"int\" type=\"number\" />\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">爱心 ROI 偏移(x,y)</label>\r\n <div class=\"inline2\">\r\n <input id=\"yanghao_like_roi_offset_x\" class=\"input\" data-key=\"yanghao_like_roi_offset_x\" data-type=\"int\" type=\"number\" />\r\n <input id=\"yanghao_like_roi_offset_y\" class=\"input\" data-key=\"yanghao_like_roi_offset_y\" data-type=\"int\" type=\"number\" />\r\n </div>\r\n </div>\r\n <div>\r\n <label class=\"label\">收藏 ROI 偏移(x,y)</label>\r\n <div class=\"inline2\">\r\n <input id=\"yanghao_fav_roi_offset_x\" class=\"input\" data-key=\"yanghao_fav_roi_offset_x\" data-type=\"int\" type=\"number\" />\r\n <input id=\"yanghao_fav_roi_offset_y\" class=\"input\" data-key=\"yanghao_fav_roi_offset_y\" data-type=\"int\" type=\"number\" />\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">爱心模板路径</label>\r\n <input id=\"yanghao_like_template_path\" class=\"input\" data-key=\"yanghao_like_template_path\" data-type=\"str\" type=\"text\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">收藏模板路径</label>\r\n <input id=\"yanghao_fav_template_path\" class=\"input\" data-key=\"yanghao_fav_template_path\" data-type=\"str\" type=\"text\" />\r\n </div>\r\n </div>\r\n\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">评论按钮坐标(x,y)</label>\r\n <div class=\"inline2\">\r\n <input id=\"yanghao_comment_btn_x\" class=\"input\" data-key=\"yanghao_comment_btn_x\" data-type=\"int\" type=\"number\" />\r\n <input id=\"yanghao_comment_btn_y\" class=\"input\" data-key=\"yanghao_comment_btn_y\" data-type=\"int\" type=\"number\" />\r\n </div>\r\n </div>\r\n <div>\r\n <label class=\"label\">评论输入框坐标(x,y)</label>\r\n <div class=\"inline2\">\r\n <input id=\"yanghao_comment_input_x\" class=\"input\" data-key=\"yanghao_comment_input_x\" data-type=\"int\" type=\"number\" />\r\n <input id=\"yanghao_comment_input_y\" class=\"input\" data-key=\"yanghao_comment_input_y\" data-type=\"int\" type=\"number\" />\r\n </div>\r\n </div>\r\n </div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">评论发送坐标(x,y)</label>\r\n <div class=\"inline2\">\r\n <input id=\"yanghao_comment_send_x\" class=\"input\" data-key=\"yanghao_comment_send_x\" data-type=\"int\" type=\"number\" />\r\n <input id=\"yanghao_comment_send_y\" class=\"input\" data-key=\"yanghao_comment_send_y\" data-type=\"int\" type=\"number\" />\r\n </div>\r\n </div>\r\n <div>\r\n <label class=\"label\">评论关闭坐标(x,y)</label>\r\n <div class=\"inline2\">\r\n <input id=\"yanghao_comment_close_x\" class=\"input\" data-key=\"yanghao_comment_close_x\" data-type=\"int\" type=\"number\" />\r\n <input id=\"yanghao_comment_close_y\" class=\"input\" data-key=\"yanghao_comment_close_y\" data-type=\"int\" type=\"number\" />\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">停留后滑动方向</label>\r\n <select id=\"yanghao_after_dwell_swipe_direction\" class=\"input\" data-key=\"yanghao_after_dwell_swipe_direction\" data-type=\"str\">\r\n <option value=\"up\">up</option>\r\n <option value=\"down\">down</option>\r\n </select>\r\n </div>\r\n <div>\r\n <label class=\"label\">停留后滑动距离(px)</label>\r\n <input id=\"yanghao_after_dwell_swipe_distance_px\" class=\"input\" data-key=\"yanghao_after_dwell_swipe_distance_px\" data-type=\"int\" type=\"number\" min=\"100\" max=\"2000\" step=\"10\" />\r\n </div>\r\n </div>\r\n\r\n <div class=\"row\">\r\n <label class=\"label\">评论文案库(每行一个)</label>\r\n <textarea id=\"yanghao_comment_texts\" class=\"input textarea\" data-key=\"yanghao_comment_texts\" data-type=\"list_lines\" rows=\"6\"></textarea>\r\n </div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">爱心关键词(每行一个)</label>\r\n <textarea id=\"yanghao_like_keywords\" class=\"input textarea\" data-key=\"yanghao_like_keywords\" data-type=\"list_lines\" rows=\"4\"></textarea>\r\n </div>\r\n <div>\r\n <label class=\"label\">收藏关键词(每行一个)</label>\r\n <textarea id=\"yanghao_fav_keywords\" class=\"input textarea\" data-key=\"yanghao_fav_keywords\" data-type=\"list_lines\" rows=\"4\"></textarea>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"panel\" data-panel=\"keywords\" role=\"tabpanel\" hidden>\r\n <div class=\"sectionTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M21 10a7 7 0 1 1-14 0 7 7 0 0 1 14 0z\"/><path d=\"M21 21l-6-6\"/></svg></span>\r\n 关键词(每行一个)\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">想要 contains_want</label>\r\n <textarea id=\"contains_want\" class=\"input textarea\" data-key=\"contains_want\" data-type=\"list_lines\" rows=\"5\"></textarea>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">不想要 contains_not_want</label>\r\n <textarea id=\"contains_not_want\" class=\"input textarea\" data-key=\"contains_not_want\" data-type=\"list_lines\" rows=\"5\"></textarea>\r\n </div>\r\n </div>\r\n\r\n <div class=\"panel\" data-panel=\"debug\" role=\"tabpanel\" hidden>\r\n <div class=\"sectionTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 16v-4\"/><path d=\"M12 8h.01\"/></svg></span>\r\n 调试参数\r\n </div>\r\n\r\n <div class=\"sectionTitle\">调试图像</div>\r\n <div class=\"row\">\r\n <label class=\"label\">保存调试图像(OCR / 像素 / 模板等)</label>\r\n <label class=\"check\">\r\n <input id=\"debug_captures_enabled\" type=\"checkbox\" data-key=\"debug_captures.enabled\" data-type=\"bool\" />\r\n <span>启用</span>\r\n </label>\r\n <div class=\"hint\">关闭后不再保存调试截图,可显著减少磁盘占用和略微提升速度</div>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">调试图像清理</div>\r\n <div class=\"row\">\r\n <label class=\"label\">启用自动清理调试图像</label>\r\n <label class=\"check\">\r\n <input id=\"debug_captures_auto_cleanup\" type=\"checkbox\" data-key=\"debug_captures.auto_cleanup\" data-type=\"bool\" checked />\r\n <span>启用</span>\r\n </label>\r\n <div class=\"hint\">每天第一次保存调试图像时自动清理旧目录</div>\r\n </div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">保留天数</label>\r\n <input id=\"debug_captures_keep_days\" class=\"input\" data-key=\"debug_captures.keep_days\" data-type=\"int\" type=\"number\" min=\"1\" max=\"30\" step=\"1\" value=\"7\" />\r\n <div class=\"hint\">超过此天数的调试图像目录将被自动删除</div>\r\n </div>\r\n <div>\r\n <label class=\"label\">最大文件数量</label>\r\n <input id=\"debug_captures_max_files\" class=\"input\" data-key=\"debug_captures.max_files\" data-type=\"int\" type=\"number\" min=\"100\" max=\"10000\" step=\"100\" value=\"2000\" />\r\n <div class=\"hint\">超过此数量的调试图像将被自动清理(优先删除最旧的)</div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">OCR 模式</div>\r\n <div class=\"row\">\r\n <label class=\"label\">启用 OCR 模式1(备用)</label>\r\n <label class=\"check\">\r\n <input id=\"enable_ocr_mode1\" type=\"checkbox\" data-key=\"enable_ocr_mode1\" data-type=\"bool\" />\r\n <span>启用</span>\r\n </label>\r\n <div class=\"hint\">当模式0识别失败时,自动尝试模式1</div>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">模板匹配</div>\r\n <div class=\"row\">\r\n <label class=\"label\">启用福袋模板匹配</label>\r\n <label class=\"check\">\r\n <input id=\"fudai_template_match_enabled\" type=\"checkbox\" data-key=\"fudai_template_match_enabled\" data-type=\"bool\" />\r\n <span>启用</span>\r\n </label>\r\n <div class=\"hint\">使用模板匹配辅助查找福袋图标</div>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">模板匹配阈值</label>\r\n <input id=\"fudai_template_match_threshold\" class=\"input\" data-key=\"fudai_template_match_threshold\" data-type=\"float\" type=\"number\" min=\"0\" max=\"1\" step=\"0.01\" value=\"0.7\" />\r\n <div class=\"hint\">匹配分数阈值,范围 0-1,默认 0.7</div>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">像素检测</div>\r\n <div class=\"row\">\r\n <label class=\"label\">抽奖结果红色比例阈值</label>\r\n <input id=\"lucky_draw_red_ratio_threshold\" class=\"input\" data-key=\"lucky_draw_red_ratio_threshold\" data-type=\"float\" type=\"number\" min=\"0\" max=\"1\" step=\"0.01\" value=\"0.8\" />\r\n <div class=\"hint\">用于检测抽奖结果弹窗,范围 0-1,默认 0.8</div>\r\n </div>\r\n <div class=\"row\">\r\n <label class=\"label\">直播间匹配阈值</label>\r\n <input id=\"live_room_match_threshold\" class=\"input\" data-key=\"live_room_match_threshold\" data-type=\"float\" type=\"number\" min=\"0\" max=\"1\" step=\"0.01\" value=\"0.7\" />\r\n <div class=\"hint\">用于判断是否在直播间,范围 0-1,默认 0.7</div>\r\n </div>\r\n\r\n <div class=\"sectionTitle\">阶段诊断</div>\r\n <div class=\"row grid2\">\r\n <div>\r\n <label class=\"label\">最大诊断时间(秒)</label>\r\n <input id=\"stage_diag_max_time\" class=\"input\" data-key=\"stage_diag_max_time\" data-type=\"float\" type=\"number\" min=\"1\" max=\"60\" step=\"1\" />\r\n </div>\r\n <div>\r\n <label class=\"label\">单步最大时间(秒)</label>\r\n <input id=\"stage_diag_max_step_time\" class=\"input\" data-key=\"stage_diag_max_step_time\" data-type=\"float\" type=\"number\" min=\"0.5\" max=\"10\" step=\"0.5\" />\r\n </div>\r\n </div>\r\n </div>\r\n\r\n </div>\r\n </div>\r\n </section>\r\n\r\n <section class=\"card cardShot\">\r\n <div class=\"cardTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\">\r\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\"/><path d=\"M7 15l3-3 3 3 5-5\"/></svg>\r\n </span>\r\n 实时截图\r\n </div>\r\n <div class=\"preview\">\r\n <img id=\"liveShot\" alt=\"实时截图预览\" src=\"/pic/screenshot.png\" />\r\n </div>\r\n <div class=\"hint\" id=\"liveShotStatus\">等待截图…</div>\r\n </section>\r\n\r\n <section class=\"card cardReservations\">\r\n <div class=\"cardTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\">\r\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M12 2L2 7l10 5 10-5-10-5z\"/><path d=\"M2 17l10 5 10-5\"/><path d=\"M2 12l10 5 10-5\"/></svg>\r\n </span>\r\n 预约队列\r\n </div>\r\n <div id=\"reservationsContent\" class=\"reservationsContent\">\r\n <div class=\"hint\">暂无预约信息</div>\r\n </div>\r\n\r\n <div class=\"divider\"></div>\r\n <details open>\r\n <summary class=\"sectionTitle\">已记录直播间(高价值)\r\n <span style=\"float:right; font-weight:normal; font-size:13px; margin-left:8px\">\r\n <button id=\"hv_expand_all\" class=\"btn small\">展开全部</button>\r\n <button id=\"hv_collapse_all\" class=\"btn small\">折叠全部</button>\r\n </span>\r\n </summary>\r\n <div id=\"highValueRoomsContent\" class=\"reservationsContent\">\r\n <div class=\"hint\">暂无记录</div>\r\n </div>\r\n </details>\r\n </section>\r\n\r\n <section class=\"card cardLog\">\r\n <div class=\"cardTitle\">\r\n <span class=\"sectionIcon\" aria-hidden=\"true\">\r\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 4h16v16H4z\"/><path d=\"M8 8h8\"/><path d=\"M8 12h8\"/><path d=\"M8 16h6\"/></svg>\r\n </span>\r\n 日志\r\n </div>\r\n <pre id=\"log\" class=\"log\"></pre>\r\n </section>\r\n </main>\r\n </div>\r\n\r\n <script src=\"app.js\"></script>\r\n</body>\r\n</html>" +} +``` +User decision: **accepted** + +Status: **completed** + + +
+
+ +--- + + +
+Tool use: **apply_patch** + + +Parameters: + +```json +{ + "relativeWorkspacePath": "gui_app.py" +} +``` +Additional data: + +```json +{ + "codeblockId": "a6095d87-6749-4c3a-bb07-c4149da032bd" +} +``` +Result: + +```json +{ + "diff": { + "chunks": [ + { + "diffString": " )\n \n+ # 调试图像开关 & 清理相关变量\n+ debug_captures_enabled_var = tk.BooleanVar(\n+ value=bool(\n+ cfg.get(\"debug_captures\", {}).get(\"enabled\", False)\n+ if isinstance(cfg.get(\"debug_captures\"), dict)\n+ else False\n+ )\n+ )\n # 调试图像清理相关变量\n debug_captures_auto_cleanup_var = tk.BooleanVar(", + "oldStart": 508, + "newStart": 508, + "oldLines": 4, + "newLines": 12, + "linesAdded": 8 + }, + { + "diffString": " left_notebook.add(debug_tab, text=\"调试参数\")\n \n- # 调试图像清理\n- debug_captures_box = ttk.LabelFrame(debug_tab, text=\"调试图像清理\")\n+ # 调试图像\n+ debug_captures_box = ttk.LabelFrame(debug_tab, text=\"调试图像\")\n debug_captures_box.pack(fill=X, padx=10, pady=(10, 10))\n \n debug_r0 = ttk.Frame(debug_captures_box)\n debug_r0.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Checkbutton(\n- debug_r0, text=\"启用自动清理调试图像\", variable=debug_captures_auto_cleanup_var\n+ debug_r0,\n+ text=\"保存调试图像(OCR / 像素 / 模板等)\",\n+ variable=debug_captures_enabled_var,\n ).pack(side=LEFT)\n \n- debug_r1 = ttk.Frame(debug_captures_box)\n- debug_r1.pack(fill=X, padx=10, pady=(0, 8))\n- ttk.Label(debug_r1, text=\"保留天数:\").pack(side=LEFT)\n+ debug_cleanup_box = ttk.LabelFrame(debug_tab, text=\"调试图像清理\")\n+ debug_cleanup_box.pack(fill=X, padx=10, pady=(0, 10))\n+ \n+ debug_r1 = ttk.Frame(debug_cleanup_box)\n+ debug_r1.pack(fill=X, padx=10, pady=(10, 8))\n+ ttk.Checkbutton(\n+ debug_r1, text=\"启用自动清理调试图像\", variable=debug_captures_auto_cleanup_var\n+ ).pack(side=LEFT)\n+ \n+ debug_r2 = ttk.Frame(debug_cleanup_box)\n+ debug_r2.pack(fill=X, padx=10, pady=(0, 8))\n+ ttk.Label(debug_r2, text=\"保留天数:\").pack(side=LEFT)\n ttk.Spinbox(\n- debug_r1,\n+ debug_r2,\n from_=1,\n to=30,", + "oldStart": 879, + "newStart": 887, + "oldLines": 19, + "newLines": 30, + "linesRemoved": 7, + "linesAdded": 18 + }, + { + "diffString": " width=6,\n ).pack(side=LEFT)\n- ttk.Label(debug_r1, text=\"最大文件数量:\").pack(side=LEFT, padx=(20, 0))\n+ ttk.Label(debug_r2, text=\"最大文件数量:\").pack(side=LEFT, padx=(20, 0))\n ttk.Spinbox(\n- debug_r1,\n+ debug_r2,\n from_=100,\n to=10000,", + "oldStart": 900, + "newStart": 919, + "oldLines": 7, + "newLines": 7, + "linesRemoved": 2, + "linesAdded": 2 + }, + { + "diffString": " width=8,\n ).pack(side=LEFT)\n- ttk.Label(debug_r1, text=\"(超过此数量自动清理)\").pack(side=LEFT, padx=(6, 0))\n+ ttk.Label(debug_r2, text=\"(超过此数量自动清理)\").pack(side=LEFT, padx=(6, 0))\n \n # 找福袋参数", + "oldStart": 909, + "newStart": 928, + "oldLines": 5, + "newLines": 5, + "linesRemoved": 1, + "linesAdded": 1 + } + ], + "editor": "EDITOR_AI" + }, + "shouldAutoFixLints": true, + "resultForModel": "Success. Updated the following files:\nM gui_app.py", + "contentsAfterEdit": "import json\nimport os\nimport queue\nimport re\nimport sys\nimport threading\nimport warnings\nfrom datetime import datetime\nfrom typing import Any, Callable\n\nfrom PIL import Image, ImageTk\n\n# 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化)\nfrom gui_core import (\n RunParams,\n Runner,\n find_adb_executable,\n list_adb_devices,\n read_config,\n write_config,\n)\nfrom path_config import get_logs_dir\n\n# 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告)\nwarnings.filterwarnings(\"ignore\", message=\".*pin_memory.*\", category=UserWarning)\nwarnings.filterwarnings(\"ignore\", message=\".*accelerator.*\", category=UserWarning)\n\n\ndef main():\n # ttkbootstrap 优先(更美观);没装则回退到原生 tkinter\n try:\n import ttkbootstrap as tb\n from ttkbootstrap.scrolled import ScrolledText\n\n import tkinter as tk\n from tkinter import ttk\n from ttkbootstrap.constants import LEFT, RIGHT, BOTH, X, Y\n\n root = tb.Window(themename=\"darkly\")\n except Exception:\n import tkinter as tk\n from tkinter import ttk\n from tkinter.constants import LEFT, RIGHT, BOTH, X, Y # type: ignore[assignment]\n from tkinter.scrolledtext import ScrolledText\n\n root = tk.Tk()\n\n root.title(\"抖音福袋挂机 - 可视化控制台\")\n root.geometry(\"1400x900\") # 增大窗口尺寸,提供更多空间\n\n q: queue.Queue[str] = queue.Queue()\n\n # ========== 线程安全的日志文件写入器 ==========\n class ThreadSafeLogWriter:\n \"\"\"线程安全的日志文件写入器,确保日志能稳定写入文件\"\"\"\n\n def __init__(self, log_dir: str | None = None):\n self._lock = threading.Lock()\n self._log_dir = log_dir or get_logs_dir()\n self._log_file_path: str = \"\"\n self._log_file_enabled: bool = True\n self._init_log_file()\n self._write_error_warned = False\n\n def _init_log_file(self) -> None:\n \"\"\"初始化日志文件路径(按日期)\"\"\"\n try:\n # 确保日志目录存在\n os.makedirs(self._log_dir, exist_ok=True)\n\n # 读取配置,检查是否启用日志文件\n cfg = read_config()\n self._log_file_enabled = bool(cfg.get(\"log_unified_enabled\", True))\n\n # 获取日志文件路径配置\n log_path = cfg.get(\"log_unified_path\") or \"logs/unified.log\"\n if not os.path.isabs(log_path):\n from path_config import PROJECT_ROOT\n\n log_path = os.path.join(PROJECT_ROOT, log_path)\n\n # 如果配置了按日期分割,使用日期后缀\n use_dated_logs = cfg.get(\"logging\", {}).get(\"use_dated_logs\", True)\n if use_dated_logs:\n # 提取基础文件名(移除扩展名)\n base_name = os.path.splitext(log_path)[0]\n today = datetime.now().strftime(\"%Y-%m-%d\")\n self._log_file_path = f\"{base_name}_{today}.log\"\n else:\n self._log_file_path = log_path\n except Exception as e:\n # 如果配置读取失败,使用默认路径\n today = datetime.now().strftime(\"%Y-%m-%d\")\n self._log_file_path = os.path.join(\n self._log_dir, f\"unified_{today}.log\"\n )\n if not self._write_error_warned:\n print(f\"[GUI日志] 配置读取失败,使用默认路径: {e}\", file=sys.stderr)\n\n def write(self, line: str) -> None:\n \"\"\"线程安全地写入日志行到文件\"\"\"\n if not self._log_file_enabled:\n return\n\n if not line or not line.strip():\n return\n\n with self._lock:\n try:\n # 检查日期是否变化(如果使用日期日志)\n cfg = read_config()\n use_dated_logs = cfg.get(\"logging\", {}).get(\"use_dated_logs\", True)\n if use_dated_logs:\n today = datetime.now().strftime(\"%Y-%m-%d\")\n current_base = os.path.splitext(self._log_file_path)[0]\n if not current_base.endswith(today):\n # 日期变化,更新文件路径\n base_name = (\n current_base.rsplit(\"_\", 1)[0]\n if \"_\" in os.path.basename(current_base)\n else current_base\n )\n self._log_file_path = f\"{base_name}_{today}.log\"\n\n # 确保目录存在\n log_dir = os.path.dirname(self._log_file_path)\n if log_dir:\n os.makedirs(log_dir, exist_ok=True)\n\n # 写入文件(追加模式,UTF-8编码,带BOM避免Windows乱码)\n with open(\n self._log_file_path, \"a\", encoding=\"utf-8-sig\", errors=\"replace\"\n ) as f:\n # 如果行已经包含时间戳(格式:YYYY-MM-DD HH:MM:SS),直接写入\n # 否则添加时间戳\n if line.strip() and not (line[0].isdigit() and \" - [\" in line):\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")[\n :-3\n ]\n formatted_line = f\"{timestamp} - [GUI] - {line}\\n\"\n else:\n formatted_line = f\"{line}\\n\"\n\n f.write(formatted_line)\n f.flush() # 立即刷新缓冲区,确保日志及时写入磁盘\n\n except PermissionError as e:\n if not self._write_error_warned:\n print(\n f\"[GUI日志] 权限错误,无法写入日志文件: {self._log_file_path}\",\n file=sys.stderr,\n )\n print(f\"[GUI日志] 错误详情: {e}\", file=sys.stderr)\n self._write_error_warned = True\n except Exception as e:\n if not self._write_error_warned:\n print(\n f\"[GUI日志] 写入日志文件失败: {self._log_file_path}\",\n file=sys.stderr,\n )\n print(f\"[GUI日志] 错误详情: {e}\", file=sys.stderr)\n self._write_error_warned = True\n\n # 创建日志写入器实例\n log_writer = ThreadSafeLogWriter()\n\n def _format_gui_log_line(line: str) -> str:\n \"\"\"\n 将“完整日志行”转换为 GUI 显示用的精简版本。\n\n 需求:\n - 文件中:仍然写入完整统一日志(含时间戳 / 级别 / 模块等信息);\n - GUI 中:保留【时间戳 + 业务日志】;\n - 如果该行包含识别/匹配的分数(如 `匹配度=0.87` / `相似度=0.95` / `score=0.83`),\n 需要在 GUI 文本中一并保留/补充出来。\n\n 精简规则(兼容统一日志格式):\n - 统一日志通常形如:\n YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - [线程] - [模块:函数:行号] - [traceId:xxx] - 业务内容\n - GUI 只展示:\n YYYY-MM-DD HH:MM:SS.xxx 业务内容(末尾可追加“(匹配度=..., 相似度=..., score=...)”)\n - 其他不符合该模式的行保持原样。\n \"\"\"\n s = (line or \"\").rstrip(\"\\n\")\n if not s:\n return s\n\n ts_part: str | None = None\n msg_part: str | None = None\n\n # 1)新统一日志格式:[YYYY-MM-DD HH:MM:SS.xxx] [LEVEL] ... 业务内容 字段_xxx=...\n m = re.match(r\"^\\[(\\d{4}-\\d{2}-\\d{2} [0-9:.]+)\\]\\s+\\[[A-Z]+\\]\\s+(.*)$\", s)\n if m:\n ts_part = m.group(1).strip()\n msg_part = m.group(2).strip()\n # 2)旧统一日志格式:YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - ... - 业务内容\n elif s[0].isdigit() and \" - \" in s:\n parts = s.split(\" - \")\n if len(parts) >= 3:\n ts_part = parts[0].strip()\n msg_part = parts[-1].strip()\n\n # 如果没解析出“时间戳 + 业务文案”,原样返回\n if not ts_part or msg_part is None:\n return s\n\n # 从业务文案中拆分出 字段_xxx=yyy,非 score 类字段在 GUI 中隐藏\n keep_tokens: list[str] = []\n\n def _is_score_field(k: str) -> bool:\n kl = k.lower()\n return (\n \"score\" in kl\n or \"match\" in kl\n or \"匹配\" in k\n or \"相似\" in k\n )\n\n for m2 in re.finditer(r\"字段_([^\\s=]+)=([^\\s]+)\", msg_part):\n key = m2.group(1)\n val = m2.group(2)\n if _is_score_field(key):\n keep_tokens.append(f\"{key}={val}\")\n\n # 先把所有 字段_xxx=yyy 从业务文案中移除\n clean_msg = re.sub(r\"\\s*字段_[^\\s=]+=[^\\s]+\", \"\", msg_part).strip()\n\n # 追加需要展示的分数字段\n if keep_tokens:\n clean_msg = f\"{clean_msg} ({', '.join(keep_tokens)})\"\n\n return f\"{ts_part} {clean_msg}\"\n\n # 不符合“完整格式”的行,原样返回\n return s\n\n def on_line(line: str):\n \"\"\"处理日志行:GUI 显示用精简版本,文件写入用完整版本\"\"\"\n # GUI 显示:使用精简后的版本\n try:\n display_line = _format_gui_log_line(line)\n except Exception:\n display_line = line\n q.put(display_line)\n\n # 文件:写入完整日志行(不做精简处理)\n try:\n log_writer.write(line)\n except Exception:\n pass # 文件写入失败不应影响GUI显示\n\n runner = Runner(on_line=on_line)\n\n # 顶部:设备选择 + Y偏移(其余运行参数放到左侧分组,避免重复)\n top = ttk.Frame(root)\n top.pack(fill=X, padx=12, pady=10)\n\n adb_exe = find_adb_executable()\n devices = list_adb_devices(adb_exe)\n device_var = tk.StringVar(value=(devices[0] if devices else \"\"))\n\n ttk.Label(top, text=\"设备:\").pack(side=LEFT)\n device_combo = ttk.Combobox(top, textvariable=device_var, values=devices, width=28)\n device_combo.pack(side=LEFT, padx=(0, 10))\n\n def refresh_devices():\n nonlocal adb_exe\n adb_exe = find_adb_executable()\n devs = list_adb_devices(adb_exe)\n device_combo[\"values\"] = devs\n if devs and not device_var.get():\n device_var.set(devs[0])\n if not adb_exe:\n on_line(\"[设备] 未找到 adb.exe(请确认已安装 platform-tools)\")\n elif not devs:\n on_line(\"[设备] adb 可用,但未发现 device 状态设备(可能未授权/未连接)\")\n\n ttk.Button(top, text=\"刷新设备\", command=refresh_devices).pack(\n side=LEFT, padx=(0, 20)\n )\n\n # 配置区(提前读取配置,供后续使用)\n cfg = read_config()\n\n y_var = tk.IntVar(value=int(cfg.get(\"y_pianyi\", 0) or 0))\n ttk.Label(top, text=\"Y偏移:\").pack(side=LEFT)\n ttk.Spinbox(top, from_=-200, to=200, textvariable=y_var, width=6).pack(\n side=LEFT, padx=(0, 12)\n )\n\n # 中部:左侧配置(使用Notebook标签页)+ 右侧日志/预览(支持拖拽调整宽度)\n mid = ttk.PanedWindow(root, orient=\"horizontal\")\n mid.pack(fill=BOTH, expand=True, padx=12, pady=(0, 12))\n\n left_wrap = ttk.Frame(mid)\n right = ttk.Frame(mid)\n mid.add(left_wrap, weight=0) # 左侧配置区域\n mid.add(right, weight=1) # 右侧日志/预览区域\n\n # 左侧使用Notebook标签页组织配置\n left_notebook = ttk.Notebook(left_wrap)\n left_notebook.pack(fill=BOTH, expand=True)\n needswitch_var = tk.BooleanVar(value=bool(cfg.get(\"needswitch\", True)))\n infinite_loop_var = tk.BooleanVar(\n value=bool(cfg.get(\"infinite_loop_enabled\", False))\n )\n wait_minutes_var = tk.IntVar(value=int(cfg.get(\"wait_minutes\", 5) or 5))\n\n min_value_var = tk.DoubleVar(value=float(cfg.get(\"min_prize_value_yuan\", 0) or 0))\n min_participants_var = tk.IntVar(value=int(cfg.get(\"min_participants\", 0) or 0))\n max_participants_var = tk.IntVar(value=int(cfg.get(\"max_participants\", 0) or 0))\n skip_gt_seconds_var = tk.IntVar(\n value=int(cfg.get(\"skip_if_countdown_gt_seconds\", 900) or 900)\n )\n reset_after_swipes_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"reset_after_swipes_enabled\", False))\n )\n reset_after_swipes_var = tk.IntVar(\n value=int(cfg.get(\"reset_after_swipes\", 10) or 10)\n )\n # 按需求:删除\"自动养号/随机等待/轻微扰动/定时休息\"等设置,仅保留\"推荐页养号(爱心/收藏/评论)\"配置。\n auto_join_var = tk.BooleanVar(value=bool(cfg.get(\"auto_join_fansclub\", False)))\n fansclub_action_var = tk.StringVar(\n value=str(cfg.get(\"fansclub_fail_action\", \"stay\") or \"stay\").lower()\n )\n\n # Web端新增配置变量 - 高价值预约相关\n high_value_fudai_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"high_value_fudai_enabled\", False))\n )\n high_value_fudai_threshold_yuan_var = tk.DoubleVar(\n value=float(cfg.get(\"high_value_fudai_threshold_yuan\", 1000) or 1000)\n )\n high_value_fudai_join_ahead_seconds_var = tk.IntVar(\n value=int(cfg.get(\"high_value_fudai_join_ahead_seconds\", 120) or 120)\n )\n high_value_fudai_max_swipe_back_var = tk.IntVar(\n value=int(cfg.get(\"high_value_fudai_max_swipe_back\", 60) or 60)\n )\n high_value_fudai_max_reservations_var = tk.IntVar(\n value=int(cfg.get(\"high_value_fudai_max_reservations\", 5) or 5)\n )\n high_value_fudai_after_action_var = tk.StringVar(\n value=str(cfg.get(\"high_value_fudai_after_action\", \"continue\") or \"continue\")\n )\n high_value_room_revisit_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"high_value_room_revisit_enabled\", True))\n )\n high_value_room_revisit_only_current_run_var = tk.BooleanVar(\n value=bool(cfg.get(\"high_value_room_revisit_only_current_run\", False))\n )\n reservation_back_verify_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"reservation_back_verify_enabled\", True))\n )\n reservation_back_swipe_delay_var = tk.DoubleVar(\n value=float(cfg.get(\"reservation_back_swipe_delay\", 0) or 0)\n )\n reservation_preempt_min_value_var = tk.DoubleVar(\n value=float(cfg.get(\"reservation_preempt_min_value\", 0) or 0)\n )\n fudai_find_max_attempts_var = tk.IntVar(\n value=int(cfg.get(\"fudai_find_max_attempts\", 0) or 0)\n )\n fudai_icon_retry_delay_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_icon_retry_delay_seconds\", 0.6) or 0.6)\n )\n fudai_icon_max_wait_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_icon_max_wait_seconds\", 5.0) or 5.0)\n )\n fudai_click_wait_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_click_wait_seconds\", 2.0) or 2.0)\n )\n switch_room_wait_after_stage_diag_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"switch_room_wait_after_stage_diag_seconds\", 7.0) or 7.0)\n )\n live_room_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"live_room_match_threshold\", 0.8) or 0.8)\n )\n\n # 推荐页养号:爱心/收藏/评论(基于图标模板匹配 + 坐标点击)\n yg_enabled_var = tk.BooleanVar(value=bool(cfg.get(\"yanghao_enabled\", True)))\n yg_actions_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"yanghao_enable_actions\", True))\n )\n yg_recommend_duration_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_recommend_duration_seconds\", 60) or 60)\n )\n yg_recommend_interval_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_recommend_interval_seconds\", 0) or 0)\n )\n yg_like_prob_var = tk.DoubleVar(\n value=float(cfg.get(\"yanghao_like_prob\", 0.0) or 0.0)\n )\n yg_fav_prob_var = tk.DoubleVar(value=float(cfg.get(\"yanghao_fav_prob\", 0.0) or 0.0))\n yg_comment_prob_var = tk.DoubleVar(\n value=float(cfg.get(\"yanghao_comment_prob\", 0.0) or 0.0)\n )\n yg_icon_roi_size_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_icon_roi_size\", 240) or 240)\n )\n yg_icon_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"yanghao_icon_match_threshold\", 0.72) or 0.72)\n )\n yg_step_screenshot_var = tk.BooleanVar(\n value=bool(cfg.get(\"yanghao_step_screenshot\", False))\n )\n yg_like_roi_offset_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_like_roi_offset_x\", 0) or 0)\n )\n yg_like_roi_offset_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_like_roi_offset_y\", 0) or 0)\n )\n yg_fav_roi_offset_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_fav_roi_offset_x\", 0) or 0)\n )\n yg_fav_roi_offset_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_fav_roi_offset_y\", 0) or 0)\n )\n yg_like_icon_x_var = tk.IntVar(value=int(cfg.get(\"yanghao_like_icon_x\", 0) or 0))\n yg_like_icon_y_var = tk.IntVar(value=int(cfg.get(\"yanghao_like_icon_y\", 0) or 0))\n yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get(\"yanghao_fav_icon_x\", 0) or 0))\n yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get(\"yanghao_fav_icon_y\", 0) or 0))\n yg_like_template_path_var = tk.StringVar(\n value=str(\n cfg.get(\"yanghao_like_template_path\", \"assets/like.png\")\n or \"assets/like.png\"\n )\n )\n yg_fav_template_path_var = tk.StringVar(\n value=str(\n cfg.get(\"yanghao_fav_template_path\", \"assets/fav.png\") or \"assets/fav.png\"\n )\n )\n yg_after_dwell_direction_var = tk.StringVar(\n value=str(cfg.get(\"yanghao_after_dwell_swipe_direction\", \"up\") or \"up\")\n )\n yg_after_dwell_distance_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_after_dwell_swipe_distance_px\", 900) or 900)\n )\n yg_comment_btn_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_btn_x\", 0) or 0)\n )\n yg_comment_btn_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_btn_y\", 0) or 0)\n )\n yg_comment_input_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_input_x\", 0) or 0)\n )\n yg_comment_input_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_input_y\", 0) or 0)\n )\n yg_comment_send_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_send_x\", 0) or 0)\n )\n yg_comment_send_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_send_y\", 0) or 0)\n )\n yg_comment_close_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_close_x\", 0) or 0)\n )\n yg_comment_close_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_close_y\", 0) or 0)\n )\n fudai_quiet_hours_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"fudai_quiet_hours_enabled\", True))\n )\n fudai_quiet_start_hour_var = tk.IntVar(\n value=int(cfg.get(\"fudai_quiet_start_hour\", 2) or 2)\n )\n fudai_quiet_end_hour_var = tk.IntVar(\n value=int(cfg.get(\"fudai_quiet_end_hour\", 7) or 7)\n )\n\n # 阶段诊断时间参数(用于调试)\n stage_diag_max_time_var = tk.DoubleVar(\n value=float(cfg.get(\"stage_diag_max_time\", 10.0) or 10.0)\n )\n stage_diag_max_step_time_var = tk.DoubleVar(\n value=float(cfg.get(\"stage_diag_max_step_time\", 2.0) or 2.0)\n )\n enable_ocr_mode1_var = tk.BooleanVar(value=bool(cfg.get(\"enable_ocr_mode1\", False)))\n # 福袋模板匹配开关和阈值\n fudai_template_match_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"fudai_template_match_enabled\", False))\n )\n fudai_template_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_template_match_threshold\", 0.7) or 0.7)\n )\n # 福袋详情页模板匹配阈值(0.0~1.0,默认0.7)\n fudai_detail_template_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_detail_template_threshold\", 0.7) or 0.7)\n )\n # 开奖页面红色占比阈值(0.0~1.0,默认0.9)\n lucky_draw_red_ratio_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"lucky_draw_red_ratio_threshold\", 0.9) or 0.9)\n )\n # 优惠券模板匹配阈值(0.0~1.0,默认0.75)\n coupon_template_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"coupon_template_match_threshold\", 0.75) or 0.75)\n )\n # 参与按钮红色占比阈值(0.0~1.0,默认0.25)\n attend_button_red_ratio_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"attend_button_red_ratio_threshold\", 0.25) or 0.25)\n )\n # 粉丝团加入红色占比阈值(0.0~1.0,默认0.25)\n fansclub_join_red_ratio_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"fansclub_join_red_ratio_threshold\", 0.25) or 0.25)\n )\n\n # 调试图像开关 & 清理相关变量\n debug_captures_enabled_var = tk.BooleanVar(\n value=bool(\n cfg.get(\"debug_captures\", {}).get(\"enabled\", False)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else False\n )\n )\n # 调试图像清理相关变量\n debug_captures_auto_cleanup_var = tk.BooleanVar(\n value=bool(\n cfg.get(\"debug_captures\", {}).get(\"auto_cleanup\", True)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else True\n )\n )\n debug_captures_keep_days_var = tk.IntVar(\n value=int(\n cfg.get(\"debug_captures\", {}).get(\"keep_days\", 7)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else 7\n )\n )\n debug_captures_max_files_var = tk.IntVar(\n value=int(\n cfg.get(\"debug_captures\", {}).get(\"max_files\", 2000)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else 2000\n )\n )\n\n # 倒计时小于阈值参数\n skip_lt_seconds_var = tk.IntVar(\n value=int(cfg.get(\"skip_if_countdown_lt_seconds\", 5) or 5)\n )\n\n # 创建左侧配置标签页\n # 标签页1:运行设置\n run_tab = ttk.Frame(left_notebook)\n left_notebook.add(run_tab, text=\"运行设置\")\n\n run_box = ttk.LabelFrame(run_tab, text=\"基本运行参数\")\n run_box.pack(fill=X, padx=10, pady=(10, 10))\n\n r0 = ttk.Frame(run_box)\n r0.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Checkbutton(r0, text=\"允许切换直播间\", variable=needswitch_var).pack(side=LEFT)\n\n r1 = ttk.Frame(run_box)\n r1.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Checkbutton(r1, text=\"无限循环模式\", variable=infinite_loop_var).pack(side=LEFT)\n ttk.Label(r1, text=\"运行时长(分钟):\").pack(side=LEFT, padx=(10, 0))\n wait_minutes_spinbox = ttk.Spinbox(\n r1, from_=1, to=60, textvariable=wait_minutes_var, width=6\n )\n wait_minutes_spinbox.pack(side=LEFT, padx=(0, 12))\n\n # 根据无限循环开关状态,启用/禁用运行时长输入框\n def update_wait_minutes_state(*args):\n if infinite_loop_var.get():\n wait_minutes_spinbox.config(state=\"disabled\")\n else:\n wait_minutes_spinbox.config(state=\"normal\")\n\n infinite_loop_var.trace(\"w\", update_wait_minutes_state)\n update_wait_minutes_state() # 初始化状态\n\n ttk.Label(r1, text=\"倒计时大于(秒)时不参与(高价值可预约):\").pack(side=LEFT)\n ttk.Spinbox(r1, from_=0, to=3600, textvariable=skip_gt_seconds_var, width=6).pack(\n side=LEFT\n )\n\n r2 = ttk.Frame(run_box)\n r2.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Checkbutton(\n r2, text=\"切换N次后回到第一个\", variable=reset_after_swipes_enabled_var\n ).pack(side=LEFT)\n ttk.Label(r2, text=\"次数:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n r2, from_=1, to=9999, textvariable=reset_after_swipes_var, width=6\n ).pack(side=LEFT)\n ttk.Label(r2, text=\"(触发后会向上回退)\").pack(side=LEFT, padx=(6, 0))\n\n # 标签页2:筛选设置\n filter_tab = ttk.Frame(left_notebook)\n left_notebook.add(filter_tab, text=\"筛选设置\")\n\n cfg_box = ttk.LabelFrame(filter_tab, text=\"福袋筛选条件\")\n cfg_box.pack(fill=X, padx=10, pady=(10, 10))\n\n row = ttk.Frame(cfg_box)\n row.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Label(row, text=\"最低价值(元):\").pack(side=LEFT)\n ttk.Spinbox(\n row, from_=0, to=99999, increment=1, textvariable=min_value_var, width=10\n ).pack(side=LEFT)\n\n rowp = ttk.Frame(cfg_box)\n rowp.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(rowp, text=\"参与人数范围:\").pack(side=LEFT)\n ttk.Spinbox(\n rowp,\n from_=0,\n to=99999999,\n increment=1,\n textvariable=min_participants_var,\n width=10,\n ).pack(side=LEFT)\n ttk.Label(rowp, text=\" ~ \").pack(side=LEFT)\n ttk.Spinbox(\n rowp,\n from_=0,\n to=99999999,\n increment=1,\n textvariable=max_participants_var,\n width=10,\n ).pack(side=LEFT)\n ttk.Label(rowp, text=\"(填0表示不限制)\").pack(side=LEFT)\n\n row2 = ttk.Frame(cfg_box)\n row2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row2, text=\"倒计时小于(秒)时不参与:\").pack(side=LEFT)\n ttk.Spinbox(\n row2, from_=0, to=300, increment=1, textvariable=skip_lt_seconds_var, width=6\n ).pack(side=LEFT)\n ttk.Label(row2, text=\"(剩余时间太短,不参与)\").pack(side=LEFT, padx=(6, 0))\n\n row3 = ttk.Frame(cfg_box)\n row3.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n row3, text=\"自动加入粉丝团(谨慎:可能消耗钻石)\", variable=auto_join_var\n ).pack(side=LEFT)\n\n row4 = ttk.Frame(cfg_box)\n row4.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(row4, text=\"粉丝团失败策略:\").pack(side=LEFT)\n ttk.Combobox(\n row4,\n textvariable=fansclub_action_var,\n values=[\"stay\", \"switch\"],\n width=10,\n state=\"readonly\",\n ).pack(side=LEFT)\n ttk.Label(row4, text=\"(stay=停留,switch=切换直播间)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 标签页3:高价值预约\n reservation_tab_left = ttk.Frame(left_notebook)\n left_notebook.add(reservation_tab_left, text=\"高价值预约\")\n\n reservation_box = ttk.LabelFrame(reservation_tab_left, text=\"高价值福袋预约参与\")\n reservation_box.pack(fill=X, padx=10, pady=(10, 10))\n\n # 预约启用开关\n res_r0 = ttk.Frame(reservation_box)\n res_r0.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Checkbutton(\n res_r0, text=\"启用预约(价值≥阈值)\", variable=high_value_fudai_enabled_var\n ).pack(side=LEFT)\n\n # 价值阈值和提前参与时间\n res_r1 = ttk.Frame(reservation_box)\n res_r1.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(res_r1, text=\"价值阈值(元):\").pack(side=LEFT)\n ttk.Spinbox(\n res_r1,\n from_=0,\n to=99999,\n increment=100,\n textvariable=high_value_fudai_threshold_yuan_var,\n width=10,\n ).pack(side=LEFT)\n ttk.Label(res_r1, text=\"提前参与(秒):\").pack(side=LEFT, padx=(20, 0))\n ttk.Spinbox(\n res_r1,\n from_=5,\n to=900,\n increment=10,\n textvariable=high_value_fudai_join_ahead_seconds_var,\n width=8,\n ).pack(side=LEFT)\n\n # 最多回退次数\n res_r2 = ttk.Frame(reservation_box)\n res_r2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(res_r2, text=\"最多回退直播间次数:\").pack(side=LEFT)\n ttk.Spinbox(\n res_r2,\n from_=0,\n to=300,\n increment=5,\n textvariable=high_value_fudai_max_swipe_back_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(res_r2, text=\"(0=不限制)\").pack(side=LEFT, padx=(6, 0))\n\n # 最多记录数量和完成后策略\n res_r3 = ttk.Frame(reservation_box)\n res_r3.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(res_r3, text=\"最多记录数量:\").pack(side=LEFT)\n ttk.Spinbox(\n res_r3,\n from_=1,\n to=50,\n increment=1,\n textvariable=high_value_fudai_max_reservations_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(res_r3, text=\"完成后策略:\").pack(side=LEFT, padx=(20, 0))\n ttk.Combobox(\n res_r3,\n textvariable=high_value_fudai_after_action_var,\n values=[\"continue\", \"stay\"],\n width=10,\n state=\"readonly\",\n ).pack(side=LEFT)\n ttk.Label(res_r3, text=\"(stay=停留,continue=继续)\").pack(side=LEFT, padx=(6, 0))\n\n # 高价值房间回访\n res_r4 = ttk.Frame(reservation_box)\n res_r4.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n res_r4, text=\"启用高价值房间回访\", variable=high_value_room_revisit_enabled_var\n ).pack(side=LEFT)\n ttk.Checkbutton(\n res_r4, text=\"仅当前运行\", variable=high_value_room_revisit_only_current_run_var\n ).pack(side=LEFT, padx=(20, 0))\n\n # 预约回退校验\n res_r5 = ttk.Frame(reservation_box)\n res_r5.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n res_r5, text=\"预约回退校验\", variable=reservation_back_verify_enabled_var\n ).pack(side=LEFT)\n\n # 回退滑延迟和预约抢占最小价值\n res_r6 = ttk.Frame(reservation_box)\n res_r6.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(res_r6, text=\"回退滑延迟(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n res_r6,\n from_=0.0,\n to=10.0,\n increment=0.1,\n textvariable=reservation_back_swipe_delay_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(res_r6, text=\"预约抢占最小价值(元):\").pack(side=LEFT, padx=(20, 0))\n ttk.Spinbox(\n res_r6,\n from_=0,\n to=99999,\n increment=100,\n textvariable=reservation_preempt_min_value_var,\n width=10,\n ).pack(side=LEFT)\n\n # 标签页4:养号设置\n yanghao_tab = ttk.Frame(left_notebook)\n left_notebook.add(yanghao_tab, text=\"养号设置\")\n\n yg_box = ttk.LabelFrame(yanghao_tab, text=\"推荐页养号(爱心/收藏/评论)\")\n yg_box.pack(fill=X, padx=10, pady=(10, 10))\n\n yg_switch = ttk.Frame(yg_box)\n yg_switch.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Checkbutton(\n yg_switch, text=\"养号总开关(关闭则跳过推荐页养号)\", variable=yg_enabled_var\n ).pack(side=LEFT)\n ttk.Checkbutton(\n yg_switch,\n text=\"启用养号动作(爱心/收藏/评论)\",\n variable=yg_actions_enabled_var,\n ).pack(side=LEFT, padx=(10, 0))\n\n yg0 = ttk.Frame(yg_box)\n yg0.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n yg0,\n text=\"逐步截图(调试用,生成 pic/*/latest.png)\",\n variable=yg_step_screenshot_var,\n ).pack(side=LEFT)\n\n yg_time = ttk.Frame(yg_box)\n yg_time.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(yg_time, text=\"养号时长(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n yg_time,\n from_=1,\n to=3600,\n increment=5,\n textvariable=yg_recommend_duration_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(yg_time, text=\"养号间隔(秒):\").pack(side=LEFT, padx=(12, 0))\n ttk.Spinbox(\n yg_time,\n from_=0,\n to=3600,\n increment=10,\n textvariable=yg_recommend_interval_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(yg_time, text=\"(0=每次触发都执行)\").pack(side=LEFT, padx=(6, 0))\n\n yg1 = ttk.Frame(yg_box)\n yg1.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(yg1, text=\"爱心概率:\").pack(side=LEFT)\n ttk.Spinbox(\n yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_like_prob_var, width=6\n ).pack(side=LEFT)\n ttk.Label(yg1, text=\"收藏概率:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_fav_prob_var, width=6\n ).pack(side=LEFT)\n ttk.Label(yg1, text=\"评论概率:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n yg1,\n from_=0.0,\n to=1.0,\n increment=0.05,\n textvariable=yg_comment_prob_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(yg1, text=\"(0~1)\").pack(side=LEFT, padx=(6, 0))\n\n yg2 = ttk.Frame(yg_box)\n yg2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(yg2, text=\"图标ROI大小(px):\").pack(side=LEFT)\n ttk.Spinbox(\n yg2, from_=80, to=600, increment=10, textvariable=yg_icon_roi_size_var, width=6\n ).pack(side=LEFT)\n ttk.Label(yg2, text=\"匹配阈值:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n yg2,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=yg_icon_match_threshold_var,\n width=6,\n ).pack(side=LEFT)\n\n yg_texts = ttk.Frame(yg_box)\n yg_texts.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))\n ttk.Label(yg_texts, text=\"评论文案库(每行一条):\").pack(anchor=\"w\")\n yg_comment_texts = ScrolledText(yg_texts, height=4)\n yg_comment_texts.pack(fill=X, pady=(0, 6))\n yg_kw = ttk.Frame(yg_texts)\n yg_kw.pack(fill=BOTH, expand=True)\n ttk.Label(yg_kw, text=\"爱心关键词(每行一条):\").pack(anchor=\"w\")\n yg_like_keywords_text = ScrolledText(yg_kw, height=3)\n yg_like_keywords_text.pack(fill=X, pady=(0, 6))\n ttk.Label(yg_kw, text=\"收藏关键词(每行一条):\").pack(anchor=\"w\")\n yg_fav_keywords_text = ScrolledText(yg_kw, height=3)\n yg_fav_keywords_text.pack(fill=X)\n\n quiet_box = ttk.LabelFrame(yanghao_tab, text=\"定时禁抢(仅养号)\")\n quiet_box.pack(fill=X, padx=10, pady=(0, 10))\n quiet_r0 = ttk.Frame(quiet_box)\n quiet_r0.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Checkbutton(\n quiet_r0, text=\"启用定时禁抢\", variable=fudai_quiet_hours_enabled_var\n ).pack(side=LEFT)\n quiet_r1 = ttk.Frame(quiet_box)\n quiet_r1.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(quiet_r1, text=\"开始小时:\").pack(side=LEFT)\n ttk.Spinbox(\n quiet_r1, from_=0, to=23, textvariable=fudai_quiet_start_hour_var, width=6\n ).pack(side=LEFT)\n ttk.Label(quiet_r1, text=\"结束小时:\").pack(side=LEFT, padx=(12, 0))\n ttk.Spinbox(\n quiet_r1, from_=0, to=23, textvariable=fudai_quiet_end_hour_var, width=6\n ).pack(side=LEFT)\n\n # 标签页5:调试参数\n debug_tab = ttk.Frame(left_notebook)\n left_notebook.add(debug_tab, text=\"调试参数\")\n\n # 调试图像\n debug_captures_box = ttk.LabelFrame(debug_tab, text=\"调试图像\")\n debug_captures_box.pack(fill=X, padx=10, pady=(10, 10))\n\n debug_r0 = ttk.Frame(debug_captures_box)\n debug_r0.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Checkbutton(\n debug_r0,\n text=\"保存调试图像(OCR / 像素 / 模板等)\",\n variable=debug_captures_enabled_var,\n ).pack(side=LEFT)\n\n debug_cleanup_box = ttk.LabelFrame(debug_tab, text=\"调试图像清理\")\n debug_cleanup_box.pack(fill=X, padx=10, pady=(0, 10))\n\n debug_r1 = ttk.Frame(debug_cleanup_box)\n debug_r1.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Checkbutton(\n debug_r1, text=\"启用自动清理调试图像\", variable=debug_captures_auto_cleanup_var\n ).pack(side=LEFT)\n\n debug_r2 = ttk.Frame(debug_cleanup_box)\n debug_r2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(debug_r2, text=\"保留天数:\").pack(side=LEFT)\n ttk.Spinbox(\n debug_r2,\n from_=1,\n to=30,\n increment=1,\n textvariable=debug_captures_keep_days_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(debug_r2, text=\"最大文件数量:\").pack(side=LEFT, padx=(20, 0))\n ttk.Spinbox(\n debug_r2,\n from_=100,\n to=10000,\n increment=100,\n textvariable=debug_captures_max_files_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(debug_r2, text=\"(超过此数量自动清理)\").pack(side=LEFT, padx=(6, 0))\n\n # 找福袋参数\n fudai_find_box = ttk.LabelFrame(debug_tab, text=\"找福袋参数\")\n fudai_find_box.pack(fill=X, padx=10, pady=(0, 10))\n\n row4 = ttk.Frame(fudai_find_box)\n row4.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Label(row4, text=\"找福袋最大尝试次数:\").pack(side=LEFT)\n ttk.Spinbox(\n row4,\n from_=0,\n to=50,\n increment=1,\n textvariable=fudai_find_max_attempts_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4, text=\"(0=使用默认值)\").pack(side=LEFT, padx=(6, 0))\n\n row4b = ttk.Frame(fudai_find_box)\n row4b.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row4b, text=\"找福袋重试间隔(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n row4b,\n from_=0.1,\n to=3.0,\n increment=0.1,\n textvariable=fudai_icon_retry_delay_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4b, text=\" 最大等待时间(秒):\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n row4b,\n from_=0.0,\n to=30.0,\n increment=0.5,\n textvariable=fudai_icon_max_wait_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4b, text=\"(实际识别常见 4-6 秒)\").pack(side=LEFT, padx=(6, 0))\n\n row4d = ttk.Frame(fudai_find_box)\n row4d.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row4d, text=\"点击福袋后等待时间(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n row4d,\n from_=0.5,\n to=10.0,\n increment=0.1,\n textvariable=fudai_click_wait_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4d, text=\"(等待福袋详情页加载,默认2.0秒)\").pack(side=LEFT, padx=(6, 0))\n\n row4e = ttk.Frame(fudai_find_box)\n row4e.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row4e, text=\"切换直播间后等待时间(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n row4e,\n from_=0.0,\n to=30.0,\n increment=0.5,\n textvariable=switch_room_wait_after_stage_diag_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4e, text=\"(阶段检测后等待福袋加载,默认7.0秒)\").pack(side=LEFT, padx=(6, 0))\n\n row4c = ttk.Frame(fudai_find_box)\n row4c.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(row4c, text=\"直播间检测阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n row4c,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=live_room_match_threshold_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4c, text=\"(0.0~1.0,默认0.7,值越高越严格)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 阶段诊断时间参数(用于调试)\n diag_time_box = ttk.LabelFrame(debug_tab, text=\"阶段诊断时间参数\")\n diag_time_box.pack(fill=X, padx=10, pady=(0, 10))\n diag_time_r1 = ttk.Frame(diag_time_box)\n diag_time_r1.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Label(diag_time_r1, text=\"最大诊断时间(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r1,\n from_=1.0,\n to=60.0,\n increment=1.0,\n textvariable=stage_diag_max_time_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r1, text=\"每步最大耗时(秒):\").pack(side=LEFT, padx=(12, 0))\n ttk.Spinbox(\n diag_time_r1,\n from_=0.5,\n to=30.0,\n increment=0.5,\n textvariable=stage_diag_max_step_time_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r1, text=\"(用于调试,延长检测时间)\").pack(\n side=LEFT, padx=(6, 0)\n )\n diag_time_r2 = ttk.Frame(diag_time_box)\n diag_time_r2.pack(fill=X, padx=10, pady=(0, 6))\n ttk.Checkbutton(\n diag_time_r2, text=\"启用OCR模式1(二值化)\", variable=enable_ocr_mode1_var\n ).pack(side=LEFT)\n diag_time_r2b = ttk.Frame(diag_time_box)\n diag_time_r2b.pack(fill=X, padx=10, pady=(0, 6))\n ttk.Checkbutton(\n diag_time_r2b,\n text=\"启用福袋模板匹配\",\n variable=fudai_template_match_enabled_var,\n ).pack(side=LEFT)\n diag_time_r3 = ttk.Frame(diag_time_box)\n diag_time_r3.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(diag_time_r3, text=\"福袋模板匹配阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r3,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=fudai_template_match_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r3, text=\"(0.0-1.0,彩色匹配)\").pack(side=LEFT, padx=(6, 0))\n\n diag_time_r3b = ttk.Frame(diag_time_box)\n diag_time_r3b.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(diag_time_r3b, text=\"福袋详情页模板匹配阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r3b,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=fudai_detail_template_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r3b, text=\"(0.0-1.0,默认0.7,区域(398,894)-(658,1179))\").pack(side=LEFT, padx=(6, 0))\n\n diag_time_r4 = ttk.Frame(diag_time_box)\n diag_time_r4.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(diag_time_r4, text=\"开奖页红色占比阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r4,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=lucky_draw_red_ratio_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r4, text=\"(默认0.90,≥此占比判定开奖页)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 更多模板匹配阈值\n diag_time_r5 = ttk.Frame(diag_time_box)\n diag_time_r5.pack(fill=X, padx=10, pady=(0, 6))\n ttk.Label(diag_time_r5, text=\"优惠券模板匹配阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r5,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=coupon_template_match_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r5, text=\"(默认0.75,用于检测优惠券弹窗)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 像素检测阈值\n pixel_detect_box = ttk.LabelFrame(debug_tab, text=\"像素检测阈值\")\n pixel_detect_box.pack(fill=X, padx=10, pady=(0, 10))\n\n pixel_r1 = ttk.Frame(pixel_detect_box)\n pixel_r1.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Label(pixel_r1, text=\"参与按钮红色占比阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n pixel_r1,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=attend_button_red_ratio_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(pixel_r1, text=\"(默认0.25,用于检测参与按钮)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n pixel_r2 = ttk.Frame(pixel_detect_box)\n pixel_r2.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(pixel_r2, text=\"粉丝团加入红色占比阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n pixel_r2,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=fansclub_join_red_ratio_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(pixel_r2, text=\"(默认0.25,用于检测粉丝团加入按钮)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 标签页6:关键词\n keywords_tab = ttk.Frame(left_notebook)\n left_notebook.add(keywords_tab, text=\"关键词\")\n\n kw_box = ttk.LabelFrame(keywords_tab, text=\"关键词(每行一个,仅黑名单)\")\n kw_box.pack(fill=BOTH, expand=True, padx=10, pady=(10, 10))\n\n ttk.Label(kw_box, text=\"不想要 contains_not_want(黑名单)\").pack(\n anchor=\"w\", padx=10, pady=(10, 4)\n )\n not_want_text = ScrolledText(kw_box, height=8)\n not_want_text.pack(fill=X, padx=10, pady=(0, 10))\n\n def load_config_to_ui():\n nonlocal cfg\n cfg = read_config()\n needswitch_var.set(bool(cfg.get(\"needswitch\", True)))\n infinite_loop_var.set(bool(cfg.get(\"infinite_loop_enabled\", False)))\n wait_minutes_var.set(int(cfg.get(\"wait_minutes\", 5) or 5))\n yg_enabled_var.set(bool(cfg.get(\"yanghao_enabled\", True)))\n yg_actions_enabled_var.set(bool(cfg.get(\"yanghao_enable_actions\", True)))\n yg_recommend_duration_var.set(\n int(cfg.get(\"yanghao_recommend_duration_seconds\", 60) or 60)\n )\n yg_recommend_interval_var.set(\n int(cfg.get(\"yanghao_recommend_interval_seconds\", 0) or 0)\n )\n min_value_var.set(float(cfg.get(\"min_prize_value_yuan\", 0) or 0))\n min_participants_var.set(int(cfg.get(\"min_participants\", 0) or 0))\n max_participants_var.set(int(cfg.get(\"max_participants\", 0) or 0))\n skip_gt_seconds_var.set(\n int(cfg.get(\"skip_if_countdown_gt_seconds\", 900) or 900)\n )\n reset_after_swipes_enabled_var.set(\n bool(cfg.get(\"reset_after_swipes_enabled\", False))\n )\n reset_after_swipes_var.set(int(cfg.get(\"reset_after_swipes\", 10) or 10))\n auto_join_var.set(bool(cfg.get(\"auto_join_fansclub\", False)))\n fansclub_action_var.set(\n str(cfg.get(\"fansclub_fail_action\", \"stay\") or \"stay\").lower()\n )\n lucky_draw_red_ratio_threshold_var.set(\n float(cfg.get(\"lucky_draw_red_ratio_threshold\", 0.9) or 0.9)\n )\n y_var.set(int(cfg.get(\"y_pianyi\", 0) or 0))\n\n # Web端新增配置 - 高价值预约相关\n high_value_fudai_enabled_var.set(\n bool(cfg.get(\"high_value_fudai_enabled\", False))\n )\n high_value_fudai_threshold_yuan_var.set(\n float(cfg.get(\"high_value_fudai_threshold_yuan\", 1000) or 1000)\n )\n high_value_fudai_join_ahead_seconds_var.set(\n int(cfg.get(\"high_value_fudai_join_ahead_seconds\", 120) or 120)\n )\n high_value_fudai_max_swipe_back_var.set(\n int(cfg.get(\"high_value_fudai_max_swipe_back\", 60) or 60)\n )\n high_value_fudai_max_reservations_var.set(\n int(cfg.get(\"high_value_fudai_max_reservations\", 5) or 5)\n )\n high_value_fudai_after_action_var.set(\n str(cfg.get(\"high_value_fudai_after_action\", \"continue\") or \"continue\")\n )\n high_value_room_revisit_enabled_var.set(\n bool(cfg.get(\"high_value_room_revisit_enabled\", True))\n )\n high_value_room_revisit_only_current_run_var.set(\n bool(cfg.get(\"high_value_room_revisit_only_current_run\", False))\n )\n reservation_back_verify_enabled_var.set(\n bool(cfg.get(\"reservation_back_verify_enabled\", True))\n )\n reservation_back_swipe_delay_var.set(\n float(cfg.get(\"reservation_back_swipe_delay\", 0) or 0)\n )\n reservation_preempt_min_value_var.set(\n float(cfg.get(\"reservation_preempt_min_value\", 0) or 0)\n )\n fudai_find_max_attempts_var.set(int(cfg.get(\"fudai_find_max_attempts\", 0) or 0))\n fudai_icon_retry_delay_seconds_var.set(\n float(cfg.get(\"fudai_icon_retry_delay_seconds\", 0.6) or 0.6)\n )\n fudai_icon_max_wait_seconds_var.set(\n float(cfg.get(\"fudai_icon_max_wait_seconds\", 5.0) or 5.0)\n )\n fudai_click_wait_seconds_var.set(\n float(cfg.get(\"fudai_click_wait_seconds\", 2.0) or 2.0)\n )\n switch_room_wait_after_stage_diag_seconds_var.set(\n float(cfg.get(\"switch_room_wait_after_stage_diag_seconds\", 7.0) or 7.0)\n )\n live_room_match_threshold_var.set(\n float(cfg.get(\"live_room_match_threshold\", 0.8) or 0.8)\n )\n fudai_quiet_hours_enabled_var.set(\n bool(cfg.get(\"fudai_quiet_hours_enabled\", True))\n )\n fudai_quiet_start_hour_var.set(int(cfg.get(\"fudai_quiet_start_hour\", 2) or 2))\n fudai_quiet_end_hour_var.set(int(cfg.get(\"fudai_quiet_end_hour\", 7) or 7))\n stage_diag_max_time_var.set(float(cfg.get(\"stage_diag_max_time\", 10.0) or 10.0))\n stage_diag_max_step_time_var.set(\n float(cfg.get(\"stage_diag_max_step_time\", 2.0) or 2.0)\n )\n enable_ocr_mode1_var.set(bool(cfg.get(\"enable_ocr_mode1\", False)))\n fudai_template_match_enabled_var.set(\n bool(cfg.get(\"fudai_template_match_enabled\", False))\n )\n fudai_template_match_threshold_var.set(\n float(cfg.get(\"fudai_template_match_threshold\", 0.7) or 0.7)\n )\n fudai_detail_template_threshold_var.set(\n float(cfg.get(\"fudai_detail_template_threshold\", 0.7) or 0.7)\n )\n coupon_template_match_threshold_var.set(\n float(cfg.get(\"coupon_template_match_threshold\", 0.75) or 0.75)\n )\n attend_button_red_ratio_threshold_var.set(\n float(cfg.get(\"attend_button_red_ratio_threshold\", 0.25) or 0.25)\n )\n fansclub_join_red_ratio_threshold_var.set(\n float(cfg.get(\"fansclub_join_red_ratio_threshold\", 0.25) or 0.25)\n )\n skip_lt_seconds_var.set(int(cfg.get(\"skip_if_countdown_lt_seconds\", 5) or 5))\n\n # 调试图像清理配置\n debug_captures_config = cfg.get(\"debug_captures\", {})\n if isinstance(debug_captures_config, dict):\n debug_captures_auto_cleanup_var.set(\n bool(debug_captures_config.get(\"auto_cleanup\", True))\n )\n debug_captures_keep_days_var.set(\n int(debug_captures_config.get(\"keep_days\", 7) or 7)\n )\n debug_captures_max_files_var.set(\n int(debug_captures_config.get(\"max_files\", 2000) or 2000)\n )\n else:\n debug_captures_auto_cleanup_var.set(True)\n debug_captures_keep_days_var.set(7)\n debug_captures_max_files_var.set(2000)\n\n yg_like_prob_var.set(float(cfg.get(\"yanghao_like_prob\", 0.0) or 0.0))\n yg_fav_prob_var.set(float(cfg.get(\"yanghao_fav_prob\", 0.0) or 0.0))\n yg_comment_prob_var.set(float(cfg.get(\"yanghao_comment_prob\", 0.0) or 0.0))\n yg_icon_roi_size_var.set(int(cfg.get(\"yanghao_icon_roi_size\", 240) or 240))\n yg_icon_match_threshold_var.set(\n float(cfg.get(\"yanghao_icon_match_threshold\", 0.72) or 0.72)\n )\n yg_step_screenshot_var.set(bool(cfg.get(\"yanghao_step_screenshot\", False)))\n yg_like_roi_offset_x_var.set(int(cfg.get(\"yanghao_like_roi_offset_x\", 0) or 0))\n yg_like_roi_offset_y_var.set(int(cfg.get(\"yanghao_like_roi_offset_y\", 0) or 0))\n yg_fav_roi_offset_x_var.set(int(cfg.get(\"yanghao_fav_roi_offset_x\", 0) or 0))\n yg_fav_roi_offset_y_var.set(int(cfg.get(\"yanghao_fav_roi_offset_y\", 0) or 0))\n yg_like_icon_x_var.set(int(cfg.get(\"yanghao_like_icon_x\", 0) or 0))\n yg_like_icon_y_var.set(int(cfg.get(\"yanghao_like_icon_y\", 0) or 0))\n yg_fav_icon_x_var.set(int(cfg.get(\"yanghao_fav_icon_x\", 0) or 0))\n yg_fav_icon_y_var.set(int(cfg.get(\"yanghao_fav_icon_y\", 0) or 0))\n yg_like_template_path_var.set(\n str(\n cfg.get(\"yanghao_like_template_path\", \"assets/like.png\")\n or \"assets/like.png\"\n )\n )\n yg_fav_template_path_var.set(\n str(\n cfg.get(\"yanghao_fav_template_path\", \"assets/fav.png\")\n or \"assets/fav.png\"\n )\n )\n yg_after_dwell_direction_var.set(\n str(cfg.get(\"yanghao_after_dwell_swipe_direction\", \"up\") or \"up\")\n )\n yg_after_dwell_distance_var.set(\n int(cfg.get(\"yanghao_after_dwell_swipe_distance_px\", 900) or 900)\n )\n yg_comment_btn_x_var.set(int(cfg.get(\"yanghao_comment_btn_x\", 0) or 0))\n yg_comment_btn_y_var.set(int(cfg.get(\"yanghao_comment_btn_y\", 0) or 0))\n yg_comment_input_x_var.set(int(cfg.get(\"yanghao_comment_input_x\", 0) or 0))\n yg_comment_input_y_var.set(int(cfg.get(\"yanghao_comment_input_y\", 0) or 0))\n yg_comment_send_x_var.set(int(cfg.get(\"yanghao_comment_send_x\", 0) or 0))\n yg_comment_send_y_var.set(int(cfg.get(\"yanghao_comment_send_y\", 0) or 0))\n yg_comment_close_x_var.set(int(cfg.get(\"yanghao_comment_close_x\", 0) or 0))\n yg_comment_close_y_var.set(int(cfg.get(\"yanghao_comment_close_y\", 0) or 0))\n\n # 仅保留黑名单 contains_not_want\n not_want = cfg.get(\"contains_not_want\", []) or []\n yg_comment_texts_list = cfg.get(\"yanghao_comment_texts\", []) or []\n yg_like_keywords_list = cfg.get(\"yanghao_like_keywords\", []) or []\n yg_fav_keywords_list = cfg.get(\"yanghao_fav_keywords\", []) or []\n not_want_text.delete(\"1.0\", \"end\")\n not_want_text.insert(\"1.0\", \"\\n\".join(not_want))\n yg_comment_texts.delete(\"1.0\", \"end\")\n yg_comment_texts.insert(\"1.0\", \"\\n\".join(yg_comment_texts_list))\n yg_like_keywords_text.delete(\"1.0\", \"end\")\n yg_like_keywords_text.insert(\"1.0\", \"\\n\".join(yg_like_keywords_list))\n yg_fav_keywords_text.delete(\"1.0\", \"end\")\n yg_fav_keywords_text.insert(\"1.0\", \"\\n\".join(yg_fav_keywords_list))\n\n def save_ui_to_config():\n # 仅保存黑名单 contains_not_want\n not_want_lines = [\n x.strip() for x in not_want_text.get(\"1.0\", \"end\").splitlines() if x.strip()\n ]\n yg_comment_text_lines = [\n x.strip()\n for x in yg_comment_texts.get(\"1.0\", \"end\").splitlines()\n if x.strip()\n ]\n yg_like_kw_lines = [\n x.strip()\n for x in yg_like_keywords_text.get(\"1.0\", \"end\").splitlines()\n if x.strip()\n ]\n yg_fav_kw_lines = [\n x.strip()\n for x in yg_fav_keywords_text.get(\"1.0\", \"end\").splitlines()\n if x.strip()\n ]\n\n cfg2 = read_config()\n cfg2[\"needswitch\"] = bool(needswitch_var.get())\n cfg2[\"infinite_loop_enabled\"] = bool(infinite_loop_var.get())\n cfg2[\"wait_minutes\"] = int(wait_minutes_var.get() or 5)\n cfg2[\"y_pianyi\"] = int(y_var.get() or 0)\n cfg2[\"contains_not_want\"] = not_want_lines\n cfg2[\"min_prize_value_yuan\"] = float(min_value_var.get() or 0)\n cfg2[\"min_participants\"] = int(min_participants_var.get() or 0)\n cfg2[\"max_participants\"] = int(max_participants_var.get() or 0)\n cfg2[\"skip_if_countdown_gt_seconds\"] = int(skip_gt_seconds_var.get() or 900)\n cfg2[\"reset_after_swipes_enabled\"] = bool(reset_after_swipes_enabled_var.get())\n cfg2[\"reset_after_swipes\"] = int(reset_after_swipes_var.get() or 10)\n cfg2[\"auto_join_fansclub\"] = bool(auto_join_var.get())\n cfg2[\"fansclub_fail_action\"] = str(fansclub_action_var.get() or \"stay\").lower()\n cfg2[\"lucky_draw_red_ratio_threshold\"] = float(\n lucky_draw_red_ratio_threshold_var.get() or 0.9\n )\n\n # Web端新增配置 - 高价值预约相关\n cfg2[\"high_value_fudai_enabled\"] = bool(high_value_fudai_enabled_var.get())\n cfg2[\"high_value_fudai_threshold_yuan\"] = float(\n high_value_fudai_threshold_yuan_var.get() or 1000\n )\n cfg2[\"high_value_fudai_join_ahead_seconds\"] = int(\n high_value_fudai_join_ahead_seconds_var.get() or 120\n )\n cfg2[\"high_value_fudai_max_swipe_back\"] = int(\n high_value_fudai_max_swipe_back_var.get() or 60\n )\n cfg2[\"high_value_fudai_max_reservations\"] = int(\n high_value_fudai_max_reservations_var.get() or 5\n )\n cfg2[\"high_value_fudai_after_action\"] = str(\n high_value_fudai_after_action_var.get() or \"continue\"\n ).lower()\n cfg2[\"high_value_room_revisit_enabled\"] = bool(\n high_value_room_revisit_enabled_var.get()\n )\n cfg2[\"high_value_room_revisit_only_current_run\"] = bool(\n high_value_room_revisit_only_current_run_var.get()\n )\n cfg2[\"reservation_back_verify_enabled\"] = bool(\n reservation_back_verify_enabled_var.get()\n )\n cfg2[\"reservation_back_swipe_delay\"] = float(\n reservation_back_swipe_delay_var.get() or 0\n )\n cfg2[\"reservation_preempt_min_value\"] = float(\n reservation_preempt_min_value_var.get() or 0\n )\n cfg2[\"fudai_find_max_attempts\"] = int(fudai_find_max_attempts_var.get() or 0)\n cfg2[\"fudai_icon_retry_delay_seconds\"] = float(\n fudai_icon_retry_delay_seconds_var.get() or 0.6\n )\n cfg2[\"fudai_icon_max_wait_seconds\"] = float(\n fudai_icon_max_wait_seconds_var.get() or 5.0\n )\n cfg2[\"fudai_click_wait_seconds\"] = float(\n fudai_click_wait_seconds_var.get() or 2.0\n )\n cfg2[\"switch_room_wait_after_stage_diag_seconds\"] = float(\n switch_room_wait_after_stage_diag_seconds_var.get() or 7.0\n )\n cfg2[\"live_room_match_threshold\"] = float(\n live_room_match_threshold_var.get() or 0.8\n )\n cfg2[\"fudai_quiet_hours_enabled\"] = bool(fudai_quiet_hours_enabled_var.get())\n cfg2[\"fudai_quiet_start_hour\"] = int(fudai_quiet_start_hour_var.get() or 0)\n cfg2[\"fudai_quiet_end_hour\"] = int(fudai_quiet_end_hour_var.get() or 0)\n cfg2[\"stage_diag_max_time\"] = float(stage_diag_max_time_var.get() or 10.0)\n cfg2[\"stage_diag_max_step_time\"] = float(\n stage_diag_max_step_time_var.get() or 2.0\n )\n cfg2[\"enable_ocr_mode1\"] = bool(enable_ocr_mode1_var.get())\n cfg2[\"fudai_template_match_enabled\"] = bool(\n fudai_template_match_enabled_var.get()\n )\n cfg2[\"fudai_template_match_threshold\"] = float(\n fudai_template_match_threshold_var.get() or 0.7\n )\n cfg2[\"fudai_detail_template_threshold\"] = float(\n fudai_detail_template_threshold_var.get() or 0.7\n )\n cfg2[\"coupon_template_match_threshold\"] = float(\n coupon_template_match_threshold_var.get() or 0.75\n )\n cfg2[\"attend_button_red_ratio_threshold\"] = float(\n attend_button_red_ratio_threshold_var.get() or 0.25\n )\n cfg2[\"fansclub_join_red_ratio_threshold\"] = float(\n fansclub_join_red_ratio_threshold_var.get() or 0.25\n )\n cfg2[\"skip_if_countdown_lt_seconds\"] = int(skip_lt_seconds_var.get() or 5)\n\n # 调试图像清理配置\n if \"debug_captures\" not in cfg2 or not isinstance(cfg2[\"debug_captures\"], dict):\n cfg2[\"debug_captures\"] = {}\n cfg2[\"debug_captures\"][\"auto_cleanup\"] = bool(\n debug_captures_auto_cleanup_var.get()\n )\n cfg2[\"debug_captures\"][\"keep_days\"] = int(\n debug_captures_keep_days_var.get() or 7\n )\n cfg2[\"debug_captures\"][\"max_files\"] = int(\n debug_captures_max_files_var.get() or 2000\n )\n\n cfg2[\"yanghao_enabled\"] = bool(yg_enabled_var.get())\n cfg2[\"yanghao_enable_actions\"] = bool(yg_actions_enabled_var.get())\n cfg2[\"yanghao_recommend_duration_seconds\"] = int(\n yg_recommend_duration_var.get() or 60\n )\n cfg2[\"yanghao_recommend_interval_seconds\"] = int(\n yg_recommend_interval_var.get() or 0\n )\n cfg2[\"yanghao_like_prob\"] = float(yg_like_prob_var.get() or 0.0)\n cfg2[\"yanghao_fav_prob\"] = float(yg_fav_prob_var.get() or 0.0)\n cfg2[\"yanghao_comment_prob\"] = float(yg_comment_prob_var.get() or 0.0)\n cfg2[\"yanghao_icon_roi_size\"] = int(yg_icon_roi_size_var.get() or 240)\n cfg2[\"yanghao_icon_match_threshold\"] = float(\n yg_icon_match_threshold_var.get() or 0.72\n )\n cfg2[\"yanghao_step_screenshot\"] = bool(yg_step_screenshot_var.get())\n cfg2[\"yanghao_like_roi_offset_x\"] = int(yg_like_roi_offset_x_var.get() or 0)\n cfg2[\"yanghao_like_roi_offset_y\"] = int(yg_like_roi_offset_y_var.get() or 0)\n cfg2[\"yanghao_fav_roi_offset_x\"] = int(yg_fav_roi_offset_x_var.get() or 0)\n cfg2[\"yanghao_fav_roi_offset_y\"] = int(yg_fav_roi_offset_y_var.get() or 0)\n cfg2[\"yanghao_like_icon_x\"] = int(yg_like_icon_x_var.get() or 0)\n cfg2[\"yanghao_like_icon_y\"] = int(yg_like_icon_y_var.get() or 0)\n cfg2[\"yanghao_fav_icon_x\"] = int(yg_fav_icon_x_var.get() or 0)\n cfg2[\"yanghao_fav_icon_y\"] = int(yg_fav_icon_y_var.get() or 0)\n cfg2[\"yanghao_like_template_path\"] = str(\n yg_like_template_path_var.get() or \"assets/like.png\"\n )\n cfg2[\"yanghao_fav_template_path\"] = str(\n yg_fav_template_path_var.get() or \"assets/fav.png\"\n )\n cfg2[\"yanghao_after_dwell_swipe_direction\"] = str(\n yg_after_dwell_direction_var.get() or \"up\"\n )\n cfg2[\"yanghao_after_dwell_swipe_distance_px\"] = int(\n yg_after_dwell_distance_var.get() or 900\n )\n cfg2[\"yanghao_comment_btn_x\"] = int(yg_comment_btn_x_var.get() or 0)\n cfg2[\"yanghao_comment_btn_y\"] = int(yg_comment_btn_y_var.get() or 0)\n cfg2[\"yanghao_comment_input_x\"] = int(yg_comment_input_x_var.get() or 0)\n cfg2[\"yanghao_comment_input_y\"] = int(yg_comment_input_y_var.get() or 0)\n cfg2[\"yanghao_comment_send_x\"] = int(yg_comment_send_x_var.get() or 0)\n cfg2[\"yanghao_comment_send_y\"] = int(yg_comment_send_y_var.get() or 0)\n cfg2[\"yanghao_comment_close_x\"] = int(yg_comment_close_x_var.get() or 0)\n cfg2[\"yanghao_comment_close_y\"] = int(yg_comment_close_y_var.get() or 0)\n cfg2[\"yanghao_comment_texts\"] = yg_comment_text_lines\n cfg2[\"yanghao_like_keywords\"] = yg_like_kw_lines\n cfg2[\"yanghao_fav_keywords\"] = yg_fav_kw_lines\n write_config(cfg2)\n on_line(\"[配置] 已保存到 config.json\")\n\n load_config_to_ui()\n\n # 顶部常驻按钮区域(与设备选择同一行,不随左侧滚动)\n top_btns = ttk.Frame(top)\n top_btns.pack(side=RIGHT, padx=(20, 0))\n ttk.Button(top_btns, text=\"保存配置\", command=save_ui_to_config).pack(\n side=LEFT, padx=(0, 8)\n )\n # 截图+OCR 按钮也放在顶部,方便随时使用\n # 具体回调在后文定义,这里先占位,通过 lambda 延迟绑定\n screenshot_button_var = {\"command\": None}\n\n def _bind_screenshot_button(btn):\n # 在 do_screenshot 定义后调用,将真正的 command 绑定到按钮\n screenshot_button_var[\"button\"] = btn\n\n screenshot_btn = ttk.Button(top_btns, text=\"截图+OCR\")\n screenshot_btn.pack(side=LEFT, padx=(0, 8))\n _bind_screenshot_button(screenshot_btn)\n\n # OCR区域配置:定义所有需要识别的区域(坐标基于1080x2400基准)\n OCR_REGIONS = [\n # (区域名称, (x1, y1, x2, y2), 描述)\n (\"福袋内容\", (390, 1240, 980, 1470), \"福袋内容详情\"),\n (\"福袋倒计时\", (390, 1470, 980, 1580), \"福袋倒计时\"),\n (\"福袋价值\", (390, 1460, 1000, 1580), \"奖品价值/价格\"),\n (\"抽奖结果\", (380, 660, 720, 755), \"抽奖结果弹窗\"),\n (\"推荐页标签栏\", (400, 140, 900, 200), \"推荐/关注/直播标签\"),\n (\"推荐页标签栏快速检测\", (400, 140, 900, 200), \"推荐页快速检测\"),\n (\"参与按钮\", (306, 2030, 780, 2110), \"参与福袋抽奖按钮\"),\n (\"无奖励确认\", (340, 1195, 740, 1355), \"无奖励确认弹窗\"),\n (\"奖励通知确认\", (370, 1350, 680, 1440), \"奖励通知确认\"),\n (\"订单确认\", (370, 120, 700, 220), \"订单确认页面\"),\n (\"关注列表标签\", (658, 147, 765, 194), \"关注列表标签\"),\n (\"直播列表标签\", (400, 140, 900, 200), \"直播列表标签\"),\n (\"直播广场\", (400, 140, 900, 200), \"直播广场标题\"),\n (\"直播间标题_中\", (400, 140, 900, 200), \"直播间标题中部\"),\n (\"诊断优惠券标题\", (60, 1260, 1020, 1480), \"优惠券弹窗标题\"),\n (\"诊断优惠券按钮\", (400, 1600, 680, 1700), \"优惠券按钮\"),\n (\"诊断购物红包\", (400, 1400, 900, 1600), \"购物红包弹窗\"),\n ]\n\n # 截图按钮\n def do_screenshot():\n device_id = device_var.get().strip()\n if not device_id:\n on_line(\"[截图] 请先选择设备\")\n return\n\n # 在后台线程中执行截图和OCR识别,避免阻塞GUI\n def screenshot_thread():\n try:\n from Underlying_Operations import underlying_operations\n from PIL import Image\n import os\n\n # 使用 root.after 在主线程中更新日志\n def log_msg(msg: str) -> Callable[[], None]:\n def wrapper() -> None:\n on_line(msg)\n\n return wrapper\n\n root.after(0, log_msg(\"[截图] 正在截图...\")) # type: ignore[arg-type]\n ops = underlying_operations()\n result = ops.get_screenshot(device_id)\n if not result:\n root.after(0, log_msg(\"[截图] 截图失败\")) # type: ignore[arg-type]\n return\n\n root.after(0, log_msg(\"[截图] 截图成功,已保存到 pic/screenshot.png\")) # type: ignore[arg-type]\n\n # 读取截图以获取实际尺寸\n screenshot_path = os.path.join(\n os.path.dirname(__file__), \"pic\", \"screenshot.png\"\n )\n if not os.path.exists(screenshot_path):\n root.after(0, log_msg(\"[OCR] 截图文件不存在\")) # type: ignore[arg-type]\n return\n\n try:\n img = Image.open(screenshot_path)\n img.load() # Force load to catch truncated files early\n img_width, img_height = img.size\n # 计算缩放比例(基于1080x2400基准)\n scale_x = img_width / 1080.0\n scale_y = img_height / 2400.0\n except (OSError, IOError, SyntaxError) as e:\n # Handle truncated image files\n root.after(0, log_msg(f\"图片文件损坏或截断: {e}\")) # type: ignore[arg-type]\n return\n except Exception as e:\n root.after(0, log_msg(f\"[OCR] 读取截图失败: {e}\")) # type: ignore[arg-type]\n return\n\n # 获取Y偏移\n y_offset = int(y_var.get() or 0)\n\n # 执行所有OCR区域的识别\n ocr_results = []\n total_regions = len(OCR_REGIONS)\n root.after(0, log_msg(f\"[OCR] 开始识别 {total_regions} 个区域...\")) # type: ignore[arg-type]\n\n for idx, (region_name, (x1, y1, x2, y2), desc) in enumerate(\n OCR_REGIONS, 1\n ):\n try:\n # 缩放坐标到实际截图尺寸\n actual_x1 = int(x1 * scale_x)\n actual_y1 = int(y1 * scale_y) + y_offset\n actual_x2 = int(x2 * scale_x)\n actual_y2 = int(y2 * scale_y) + y_offset\n\n # 确保坐标在图片范围内\n actual_x1 = max(0, min(actual_x1, img_width))\n actual_y1 = max(0, min(actual_y1, img_height))\n actual_x2 = max(0, min(actual_x2, img_width))\n actual_y2 = max(0, min(actual_y2, img_height))\n\n if actual_x1 >= actual_x2 or actual_y1 >= actual_y2:\n root.after(0, log_msg(f\"[OCR] {region_name}: 坐标无效,跳过\")) # type: ignore[arg-type]\n continue\n\n # 截取区域\n cut_result = ops.cut_pic(\n (actual_x1, actual_y1),\n (actual_x2, actual_y2),\n \"\",\n region_name,\n )\n if not cut_result:\n root.after(0, log_msg(f\"[OCR] {region_name}: 截图失败\")) # type: ignore[arg-type]\n ocr_results.append((region_name, desc, \"\", \"截图失败\"))\n continue\n\n # OCR识别(先尝试模式0,如果为空再尝试模式1)\n text_result = \"\"\n ocr_mode = 0\n for mode in [0, 1]:\n try:\n text = str(\n ops.analyse_pic_word(region_name, mode) or \"\"\n ).strip()\n if text:\n text_result = text\n ocr_mode = mode\n break\n except Exception:\n continue\n\n ocr_results.append(\n (region_name, desc, text_result, f\"模式{ocr_mode}\")\n )\n status_msg = f\"[OCR] ({idx}/{total_regions}) {region_name}: {text_result[:50] if text_result else '(空)'}\"\n root.after(0, log_msg(status_msg)) # type: ignore[arg-type]\n\n except Exception as e:\n error_msg = f\"[OCR] {region_name}: 异常 - {e}\"\n root.after(0, log_msg(error_msg)) # type: ignore[arg-type]\n ocr_results.append((region_name, desc, \"\", f\"异常: {e}\"))\n\n # 更新OCR结果标签页\n def update_ocr_wrapper() -> None:\n update_ocr_results(ocr_results)\n\n root.after(0, update_ocr_wrapper) # type: ignore[arg-type]\n root.after(0, log_msg(f\"[OCR] 完成!共识别 {len(ocr_results)} 个区域\")) # type: ignore[arg-type]\n\n # 刷新截图预览(如果当前显示的是 screenshot.png)\n def refresh_if_screenshot() -> None:\n if image_var.get() == \"screenshot.png\":\n refresh_preview()\n\n root.after(0, refresh_if_screenshot) # type: ignore[arg-type]\n\n except Exception as e:\n import traceback\n\n error_detail = traceback.format_exc()\n root.after(0, log_msg(f\"[截图] 截图异常: {e}\\n{error_detail}\")) # type: ignore[arg-type]\n\n thread = threading.Thread(target=screenshot_thread, daemon=True)\n thread.start()\n\n # 将顶部“截图+OCR”按钮的回调绑定到 do_screenshot\n try:\n btn = screenshot_button_var.get(\"button\")\n if btn is not None:\n btn.configure(command=do_screenshot)\n except Exception:\n pass\n\n # 右侧:操作按钮区域(先创建,放在底部)\n actions = ttk.Frame(right)\n\n # 右侧:Notebook(日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间)\n notebook = ttk.Notebook(right)\n\n log_tab = ttk.Frame(notebook)\n preview_tab = ttk.Frame(notebook)\n stats_tab = ttk.Frame(notebook)\n reservation_tab = ttk.Frame(notebook)\n high_value_tab = ttk.Frame(notebook)\n actions_log_tab = ttk.Frame(notebook)\n ocr_results_tab = ttk.Frame(notebook)\n notebook.add(log_tab, text=\"运行日志\")\n notebook.add(preview_tab, text=\"截图预览\")\n notebook.add(stats_tab, text=\"统计信息\")\n notebook.add(reservation_tab, text=\"预约队列\")\n notebook.add(high_value_tab, text=\"高价值房间\")\n notebook.add(actions_log_tab, text=\"行为日志\")\n notebook.add(ocr_results_tab, text=\"OCR结果\")\n\n # 日志区\n log_box = ttk.Frame(log_tab)\n log_box.pack(fill=BOTH, expand=True)\n \n # 搜索工具栏\n log_search_frame = ttk.Frame(log_box)\n log_search_frame.pack(fill=X, padx=10, pady=(10, 5))\n \n log_search_var = tk.StringVar(value=\"\")\n log_search_entry = ttk.Entry(log_search_frame, textvariable=log_search_var, width=20)\n log_search_entry.pack(side=LEFT, padx=(0, 5))\n \n log_search_matches = [] # 存储所有匹配的位置\n log_current_match_index = -1 # 当前匹配的索引\n \n def search_in_log_text(direction=1):\n \"\"\"在运行日志中搜索文本\"\"\"\n nonlocal log_search_matches, log_current_match_index\n \n search_text = log_search_var.get().strip()\n if not search_text:\n # 清除高亮\n log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n log_search_matches = []\n log_current_match_index = -1\n return\n \n # 获取所有文本\n content = log_text.get(\"1.0\", \"end-1c\")\n if not content:\n return\n \n # 清除之前的高亮\n log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n \n # 配置高亮样式\n log_text.tag_config(\"search_highlight\", background=\"yellow\")\n log_text.tag_config(\"search_current\", background=\"orange\")\n \n # 查找所有匹配项(不区分大小写)\n log_search_matches = []\n start_pos = 0 # 使用整数索引\n search_text_lower = search_text.lower()\n content_lower = content.lower()\n \n while True:\n # 在内容中查找\n pos = content_lower.find(search_text_lower, start_pos)\n if pos == -1:\n break\n \n # 计算行号和列号\n line_start = content[:pos].rfind(\"\\n\") + 1\n line_num = content[:pos].count(\"\\n\") + 1\n col_num = pos - line_start\n \n # 转换为 tkinter 索引格式\n start_index = f\"{line_num}.{col_num}\"\n end_index = f\"{line_num}.{col_num + len(search_text)}\"\n \n log_search_matches.append((start_index, end_index))\n start_pos = pos + 1\n \n if not log_search_matches:\n # 没有找到匹配项\n log_current_match_index = -1\n return\n \n # 高亮所有匹配项\n for start_idx, end_idx in log_search_matches:\n log_text.tag_add(\"search_highlight\", start_idx, end_idx)\n \n # 根据方向更新当前匹配索引\n if direction == 1: # 下一个\n log_current_match_index = (log_current_match_index + 1) % len(log_search_matches)\n else: # 上一个\n log_current_match_index = (log_current_match_index - 1) % len(log_search_matches)\n \n # 高亮当前匹配项并滚动到该位置\n if log_current_match_index >= 0:\n start_idx, end_idx = log_search_matches[log_current_match_index]\n log_text.tag_add(\"search_current\", start_idx, end_idx)\n log_text.see(start_idx)\n log_text.mark_set(\"insert\", start_idx)\n \n def search_next_in_log():\n \"\"\"搜索下一个\"\"\"\n search_in_log_text(1)\n \n def search_prev_in_log():\n \"\"\"搜索上一个\"\"\"\n search_in_log_text(-1)\n \n def clear_search_in_log():\n \"\"\"清除搜索高亮\"\"\"\n nonlocal log_search_matches, log_current_match_index\n log_search_var.set(\"\")\n log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n log_search_matches = []\n log_current_match_index = -1\n \n # 绑定回车键搜索\n def on_log_search_entry_key(event):\n if event.keysym == \"Return\":\n search_next_in_log()\n \n log_search_entry.bind(\"<KeyPress>\", on_log_search_entry_key)\n \n ttk.Button(log_search_frame, text=\"搜索\", command=search_next_in_log).pack(side=LEFT, padx=(0, 2))\n ttk.Button(log_search_frame, text=\"上一个\", command=search_prev_in_log).pack(side=LEFT, padx=(0, 2))\n ttk.Button(log_search_frame, text=\"下一个\", command=search_next_in_log).pack(side=LEFT, padx=(0, 2))\n ttk.Button(log_search_frame, text=\"清除\", command=clear_search_in_log).pack(side=LEFT, padx=(0, 5))\n \n log_text = ScrolledText(log_box)\n try:\n log_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n log_text.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))\n\n # 截图预览\n preview_top = ttk.Frame(preview_tab)\n preview_top.pack(fill=X, padx=10, pady=10)\n\n images_dir = os.path.join(os.path.dirname(__file__), \"pic\")\n\n def scan_image_files():\n \"\"\"扫描pic文件夹及其子文件夹中的所有图片文件\"\"\"\n image_files = []\n if os.path.exists(images_dir):\n for root, dirs, files in os.walk(images_dir):\n for file in files:\n if file.lower().endswith(\n (\".png\", \".jpg\", \".jpeg\", \".bmp\", \".webp\", \".gif\")\n ):\n # 获取相对路径\n rel_path = os.path.relpath(os.path.join(root, file), images_dir)\n # 统一使用正斜杠(Windows和Unix都支持)\n rel_path = rel_path.replace(\"\\\\\", \"/\")\n image_files.append(rel_path)\n # 按文件名排序\n image_files.sort(key=lambda x: x.lower())\n return image_files\n\n image_var = tk.StringVar(value=\"\")\n\n ttk.Label(preview_top, text=\"选择图片:\").pack(side=LEFT)\n # 允许手工输入子路径(例如 start/latest.png),方便查看逐步截图\n image_combo = ttk.Combobox(\n preview_top, textvariable=image_var, width=30, state=\"normal\"\n )\n image_combo.pack(side=LEFT, padx=(0, 10))\n\n def update_image_list(refresh_after=True):\n \"\"\"更新图片列表\"\"\"\n new_list = scan_image_files()\n image_combo[\"values\"] = new_list\n current_value = image_var.get()\n # 如果当前值不在新列表中,或列表为空,选择第一个\n if new_list:\n if not current_value or current_value not in new_list:\n image_var.set(new_list[0])\n else:\n image_var.set(\"\")\n on_line(f\"[预览] 扫描到 {len(new_list)} 个图片文件\")\n # 如果当前有选择的图片,刷新预览(如果refresh_after为True且refresh_preview已定义)\n if refresh_after and image_var.get():\n try:\n refresh_preview()\n except NameError:\n # refresh_preview还没定义,忽略\n pass\n\n # 先定义refresh_preview函数(即使它引用了后面的变量,函数定义本身是延迟执行的)\n def refresh_preview():\n name = image_var.get().strip()\n if not name:\n preview_status.set(\"请选择图片\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n # 处理相对路径(将正斜杠转换为系统路径分隔符)\n name_normalized = name.replace(\"/\", os.sep)\n path = os.path.join(images_dir, name_normalized)\n _load_and_fit_image(path)\n\n update_image_list(refresh_after=False) # 初始化时扫描一次,但不刷新预览\n\n preview_status = tk.StringVar(value=\"\")\n ttk.Label(preview_top, textvariable=preview_status).pack(side=RIGHT)\n\n preview_body = ttk.Frame(preview_tab)\n preview_body.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))\n\n image_label = ttk.Label(preview_body)\n image_label.pack(fill=BOTH, expand=True)\n _img_ref: dict[str, Any] = {\"photo\": None} # 防止 PhotoImage 被回收\n\n def _load_and_fit_image(img_path: str) -> None:\n if not os.path.exists(img_path):\n preview_status.set(f\"未找到:{os.path.basename(img_path)}\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n\n try:\n img = Image.open(img_path)\n img.load() # Force load to catch truncated files early\n img = img.convert(\"RGB\")\n except (OSError, IOError, SyntaxError) as e:\n # Handle truncated image files\n preview_status.set(f\"图片加载失败:{str(e)[:50]}\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n except Exception as e:\n preview_status.set(f\"图片加载错误:{str(e)[:50]}\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n\n # 获取预览区域的实际尺寸(如果窗口还未初始化,使用默认值)\n try:\n preview_body.update_idletasks() # 强制更新布局\n w = preview_body.winfo_width()\n h = preview_body.winfo_height()\n # 如果尺寸无效(窗口未初始化),使用默认值\n if w <= 1 or h <= 1:\n w, h = 900, 520\n except Exception:\n w, h = 900, 520\n\n max_w = max(300, w - 20)\n max_h = max(200, h - 20)\n try:\n resample = Image.Resampling.LANCZOS\n except AttributeError:\n # Fallback for older Pillow versions: LANCZOS constant value is 1\n resample = 1 # type: ignore[assignment]\n img.thumbnail((max_w, max_h), resample)\n photo: ImageTk.PhotoImage = ImageTk.PhotoImage(img)\n _img_ref[\"photo\"] = photo # type: ignore[assignment]\n image_label.configure(image=photo)\n preview_status.set(f\"{os.path.basename(img_path)} {img.width}x{img.height}\")\n\n ttk.Button(\n preview_top,\n text=\"刷新列表\",\n command=lambda: update_image_list(refresh_after=True),\n ).pack(side=LEFT, padx=(0, 5))\n ttk.Button(preview_top, text=\"刷新预览\", command=refresh_preview).pack(side=LEFT)\n\n # 绑定选择变化事件,自动刷新预览(在 refresh_preview 函数定义之后)\n def on_image_selected(*args):\n \"\"\"当用户选择图片时自动刷新预览\"\"\"\n try:\n refresh_preview()\n except Exception:\n pass # 忽略错误,避免影响其他功能\n\n image_var.trace(\"w\", on_image_selected) # 监听变量变化\n image_combo.bind(\n \"<<ComboboxSelected>>\", lambda e: refresh_preview()\n ) # 监听下拉选择\n\n def open_pic_folder():\n try:\n os.makedirs(images_dir, exist_ok=True)\n os.startfile(images_dir) # type: ignore[attr-defined]\n except Exception as e:\n on_line(f\"[预览] 打开图片目录失败:{e}\")\n\n ttk.Button(preview_top, text=\"打开pic目录\", command=open_pic_folder).pack(\n side=LEFT, padx=(10, 0)\n )\n\n status_var = tk.StringVar(value=\"就绪\")\n\n def get_params() -> RunParams:\n # 如果启用无限循环,设置 wait_minutes=0\n wait_minutes_value = (\n 0 if infinite_loop_var.get() else int(wait_minutes_var.get() or 5)\n )\n return RunParams(\n enable_ocr_mode1=bool(enable_ocr_mode1_var.get()),\n device_id=device_var.get().strip(),\n y_pianyi=int(y_var.get()),\n needswitch=bool(needswitch_var.get()),\n wait_minutes=wait_minutes_value,\n skip_if_countdown_gt_seconds=int(skip_gt_seconds_var.get() or 900),\n reset_after_swipes_enabled=bool(reset_after_swipes_enabled_var.get()),\n reset_after_swipes=int(reset_after_swipes_var.get() or 10),\n min_prize_value_yuan=float(min_value_var.get() or 0),\n min_participants=int(min_participants_var.get() or 0),\n max_participants=int(max_participants_var.get() or 0),\n auto_join_fansclub=bool(auto_join_var.get()),\n fansclub_fail_action=str(fansclub_action_var.get() or \"stay\").lower(),\n # Web端新增参数\n high_value_room_revisit_enabled=bool(\n high_value_room_revisit_enabled_var.get()\n ),\n high_value_room_revisit_only_current_run=bool(\n high_value_room_revisit_only_current_run_var.get()\n ),\n reservation_back_verify_enabled=bool(\n reservation_back_verify_enabled_var.get()\n ),\n reservation_back_swipe_delay=float(\n reservation_back_swipe_delay_var.get() or 0\n ),\n reservation_preempt_min_value=float(\n reservation_preempt_min_value_var.get() or 0\n ),\n fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 0),\n fudai_template_match_enabled=bool(fudai_template_match_enabled_var.get()),\n fudai_template_match_threshold=float(\n fudai_template_match_threshold_var.get() or 0.7\n ),\n )\n\n def start_run():\n if runner.is_running():\n on_line(\"[运行] 已在运行中\")\n return\n save_ui_to_config()\n params = get_params()\n\n wait_display = \"∞\" if params.wait_minutes == 0 else f\"{params.wait_minutes}m\"\n on_line(\n f\"[运行] 启动:device={params.device_id or '(auto)'} y={params.y_pianyi} \"\n f\"needswitch={params.needswitch} wait={wait_display} \"\n f\"skip_gt={params.skip_if_countdown_gt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} \"\n f\"value>={params.min_prize_value_yuan} participants=[{params.min_participants},{params.max_participants}] \"\n f\"high_value_revisit={params.high_value_room_revisit_enabled} reservation_verify={params.reservation_back_verify_enabled} \"\n f\"fudai_find_max={params.fudai_find_max_attempts} yanghao=recommend_flow_only\"\n )\n status_var.set(\"运行中\")\n try:\n runner.start(params)\n except Exception as e:\n status_var.set(\"启动失败\")\n on_line(f\"[错误] {e}\")\n\n def stop_run():\n runner.stop()\n status_var.set(\"已停止\")\n\n # 先打包 actions 到底部(不 expand,固定在底部)\n actions.pack(fill=X, pady=(10, 0), padx=12, side=\"bottom\")\n\n # 然后打包 notebook 填充剩余空间(在 actions 之上)\n notebook.pack(fill=BOTH, expand=True)\n\n ttk.Button(actions, text=\"开始运行\", command=start_run).pack(side=LEFT, padx=(0, 8))\n ttk.Button(actions, text=\"停止\", command=stop_run).pack(side=LEFT, padx=(0, 4))\n\n def force_stop_run():\n \"\"\"强制终止后台进程(包括可能残留的子进程)。\"\"\"\n runner.force_stop()\n status_var.set(\"已停止(强制)\")\n\n ttk.Button(actions, text=\"强制停止\", command=force_stop_run).pack(\n side=LEFT, padx=(0, 8)\n )\n\n ttk.Separator(actions, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=10, pady=3)\n test_seconds_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_recommend_duration_seconds\", 60) or 60)\n )\n ttk.Label(actions, text=\"测试养号(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n actions, from_=10, to=3600, increment=10, textvariable=test_seconds_var, width=8\n ).pack(side=LEFT, padx=(0, 8))\n\n def start_test_yanghao():\n if runner.is_running():\n on_line(\"[运行] 已在运行中\")\n return\n save_ui_to_config()\n secs = int(test_seconds_var.get() or 90)\n dev = device_var.get().strip()\n on_line(f\"[测试] 启动养号流程:device={dev or '(auto)'} seconds={secs}\")\n status_var.set(\"运行中\")\n try:\n runner.start_test_yanghao_flow(dev, secs)\n except Exception as e:\n status_var.set(\"启动失败\")\n on_line(f\"[错误] {e}\")\n\n ttk.Button(actions, text=\"测试养号流程\", command=start_test_yanghao).pack(side=LEFT)\n\n ttk.Separator(actions, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=10, pady=3)\n test_comment_var = tk.StringVar(value=\"测试评论\")\n ttk.Label(actions, text=\"测试评论:\").pack(side=LEFT)\n ttk.Entry(actions, textvariable=test_comment_var, width=12).pack(\n side=LEFT, padx=(0, 8)\n )\n\n def start_test_comment():\n if runner.is_running():\n on_line(\"[运行] 已在运行中\")\n return\n save_ui_to_config()\n text = test_comment_var.get().strip()\n dev = device_var.get().strip()\n on_line(f\"[测试] 启动评论测试:device={dev or '(auto)'} text={text}\")\n status_var.set(\"运行中\")\n try:\n runner.start_test_comment(dev, text)\n except Exception as e:\n status_var.set(\"启动失败\")\n on_line(f\"[错误] {e}\")\n\n ttk.Button(actions, text=\"测试评论\", command=start_test_comment).pack(side=LEFT)\n\n ttk.Separator(actions, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=10, pady=3)\n\n def send_back_key():\n dev = device_var.get().strip()\n try:\n runner.send_back_key(dev)\n except Exception as e:\n on_line(f\"[错误] 发送返回键失败: {e}\")\n\n ttk.Button(actions, text=\"发送返回键\", command=send_back_key).pack(\n side=LEFT, padx=(0, 8)\n )\n\n ttk.Label(actions, textvariable=status_var).pack(side=RIGHT)\n\n def pump_logs():\n changed = False\n try:\n while True:\n line = q.get_nowait()\n try:\n log_text.insert(\"end\", line + \"\\n\")\n # 不再自动滚动到底部,让用户自由控制滚动位置\n changed = True\n except Exception as e:\n # 如果插入日志失败,至少打印到控制台(调试用)\n print(f\"[GUI日志错误] 无法插入日志: {e}\", file=sys.stderr)\n except queue.Empty:\n pass\n except Exception as e:\n # 捕获其他异常,确保日志循环不会中断\n print(f\"[GUI日志错误] pump_logs异常: {e}\", file=sys.stderr)\n\n try:\n if changed and not runner.is_running() and status_var.get() == \"运行中\":\n status_var.set(\"已结束\")\n except Exception:\n pass\n\n # 确保递归调用始终执行,即使前面出现异常\n try:\n root.after(100, pump_logs) # type: ignore[arg-type]\n except Exception as e:\n # 如果 root 已被销毁,停止日志循环\n print(f\"[GUI日志错误] 无法调度下次日志更新: {e}\", file=sys.stderr)\n\n # 统计信息显示\n stats_top = ttk.Frame(stats_tab)\n stats_top.pack(fill=X, padx=10, pady=(10, 0))\n stats_text = ScrolledText(stats_tab)\n stats_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n stats_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def refresh_stats():\n try:\n stats = runner.get_stats()\n lines = []\n\n # 基本信息\n lines.append(\"=\" * 60)\n lines.append(\"运行状态信息\")\n lines.append(\"=\" * 60)\n lines.append(f\"运行状态: {'运行中' if stats.get('running') else '未运行'}\")\n lines.append(f\"PID: {stats.get('pid') or '-'}\")\n\n uptime_seconds = stats.get(\"uptime_seconds\", 0)\n if uptime_seconds > 0:\n hours = uptime_seconds // 3600\n minutes = (uptime_seconds % 3600) // 60\n seconds = uptime_seconds % 60\n lines.append(f\"运行时长: {hours:02d}:{minutes:02d}:{seconds:02d}\")\n else:\n lines.append(f\"运行时长: -\")\n\n last_log_ts = stats.get(\"last_log_ts\")\n if last_log_ts:\n import datetime\n\n dt = datetime.datetime.fromtimestamp(last_log_ts)\n lines.append(f\"最近日志时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}\")\n else:\n lines.append(f\"最近日志时间: -\")\n\n exit_code = stats.get(\"exit_code\")\n lines.append(f\"退出码: {exit_code if exit_code is not None else '-'}\")\n lines.append(\"\")\n\n # 计数器统计\n counters = stats.get(\"counters\", {})\n\n # 快速汇总(关键指标)\n fudai_seen = counters.get(\"fudai_seen\", 0)\n fudai_attend_ok = counters.get(\"fudai_attend_ok\", 0)\n fudai_result_win = counters.get(\"fudai_result_win\", 0)\n fudai_order_success = counters.get(\"fudai_order_success\", 0)\n\n if fudai_seen > 0 or fudai_attend_ok > 0 or fudai_result_win > 0:\n lines.append(\"=\" * 60)\n lines.append(\"快速汇总\")\n lines.append(\"=\" * 60)\n lines.append(f\"识别福袋: {fudai_seen} 个\")\n lines.append(f\"参与成功: {fudai_attend_ok} 次\")\n lines.append(f\"中奖次数: {fudai_result_win} 次\")\n lines.append(f\"下单成功: {fudai_order_success} 次\")\n if uptime_seconds > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(\n f\"运行效率: {fudai_attend_ok / hours:.1f} 次参与/小时\"\n )\n lines.append(\"\")\n\n # 核心统计(总是显示,即使数据为0)\n lines.append(\"=\" * 60)\n lines.append(\"核心统计\")\n lines.append(\"=\" * 60)\n\n # 福袋相关核心指标(重新获取,避免重复定义)\n fudai_open_detail = counters.get(\"fudai_open_detail\", 0)\n fudai_click_attend = counters.get(\"fudai_click_attend\", 0)\n fudai_attend_ok = counters.get(\"fudai_attend_ok\", 0)\n fudai_attend_fail = counters.get(\"fudai_attend_fail\", 0)\n fudai_result_win = counters.get(\"fudai_result_win\", 0)\n fudai_result_no_win = counters.get(\"fudai_result_no_win\", 0)\n fudai_order_success = counters.get(\"fudai_order_success\", 0)\n\n lines.append(f\"福袋识别次数: {fudai_seen}\")\n lines.append(f\"打开详情: {fudai_open_detail}\")\n if fudai_seen > 0:\n open_rate = (fudai_open_detail / fudai_seen) * 100\n lines.append(f\" 打开成功率: {open_rate:.1f}%\")\n\n lines.append(f\"点击参与: {fudai_click_attend}\")\n if fudai_open_detail > 0:\n click_rate = (fudai_click_attend / fudai_open_detail) * 100\n lines.append(f\" 点击率: {click_rate:.1f}%\")\n\n lines.append(f\"参与成功: {fudai_attend_ok}\")\n lines.append(f\"参与失败: {fudai_attend_fail}\")\n total_attend = fudai_attend_ok + fudai_attend_fail\n if total_attend > 0:\n success_rate = (fudai_attend_ok / total_attend) * 100\n lines.append(f\" 参与成功率: {success_rate:.1f}%\")\n\n lines.append(f\"中奖次数: {fudai_result_win}\")\n lines.append(f\"未中奖次数: {fudai_result_no_win}\")\n total_results = fudai_result_win + fudai_result_no_win\n if total_results > 0:\n win_rate = (fudai_result_win / total_results) * 100\n lines.append(f\" 中奖率: {win_rate:.1f}%\")\n\n lines.append(f\"下单成功: {fudai_order_success}\")\n\n # 效率统计\n if uptime_seconds > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(\"\")\n lines.append(\"效率统计(每小时):\")\n if fudai_seen > 0:\n lines.append(f\" 识别福袋: {fudai_seen / hours:.1f} 个/小时\")\n if fudai_attend_ok > 0:\n lines.append(\n f\" 参与成功: {fudai_attend_ok / hours:.1f} 次/小时\"\n )\n if total_results > 0:\n lines.append(f\" 开奖次数: {total_results / hours:.1f} 次/小时\")\n if fudai_result_win > 0:\n lines.append(\n f\" 中奖次数: {fudai_result_win / hours:.2f} 次/小时\"\n )\n\n lines.append(\"\")\n\n # 跳过原因统计\n skip_stats = [\n (\"fudai_skip_value_low\", \"跳过-价值过低\"),\n (\"fudai_skip_participants_low\", \"跳过-人数过少\"),\n (\"fudai_skip_participants_high\", \"跳过-人数过多\"),\n (\"fudai_skip_content\", \"跳过-内容不理想\"),\n (\"fudai_skip_countdown_short\", \"跳过-倒计时太短\"),\n (\"fudai_skip_countdown_long\", \"跳过-倒计时太长\"),\n (\"fudai_skip_watch_required\", \"跳过-需要看播\"),\n ]\n skip_total = sum(counters.get(key, 0) for key, _ in skip_stats)\n if skip_total > 0:\n lines.append(\"=\" * 60)\n lines.append(\"跳过原因统计\")\n lines.append(\"=\" * 60)\n lines.append(f\"总跳过次数: {skip_total}\")\n if fudai_seen > 0:\n skip_rate = (skip_total / fudai_seen) * 100\n lines.append(f\"跳过率: {skip_rate:.1f}%\")\n lines.append(\"\")\n for key, label in skip_stats:\n val = counters.get(key, 0)\n if val > 0:\n percentage = (val / skip_total) * 100 if skip_total > 0 else 0\n lines.append(f\" {label}: {val} ({percentage:.1f}%)\")\n lines.append(\"\")\n\n # 粉丝团统计\n fansclub_stats = [\n (\"fansclub_required\", \"需要粉丝团\"),\n (\"fansclub_manual_needed\", \"需手动加入\"),\n (\"fansclub_unresolved\", \"未解决\"),\n ]\n fansclub_total = sum(counters.get(key, 0) for key, _ in fansclub_stats)\n if fansclub_total > 0:\n lines.append(\"=\" * 60)\n lines.append(\"粉丝团相关统计\")\n lines.append(\"=\" * 60)\n for key, label in fansclub_stats:\n val = counters.get(key, 0)\n if val > 0:\n percentage = (\n (val / fansclub_total) * 100 if fansclub_total > 0 else 0\n )\n lines.append(f\" {label}: {val} ({percentage:.1f}%)\")\n lines.append(\"\")\n\n # 直播间切换统计\n switch_val = counters.get(\"switch_room\", 0)\n if switch_val > 0:\n lines.append(\"=\" * 60)\n lines.append(\"直播间切换统计\")\n lines.append(\"=\" * 60)\n lines.append(f\"总切换次数: {switch_val}\")\n if uptime_seconds > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(f\"切换频率: {switch_val / hours:.1f} 次/小时\")\n lines.append(\"\")\n switch_reasons = [\n (\"switch_room_no_fudai\", \"无福袋\"),\n (\"switch_room_participants\", \"人数不符合\"),\n (\"switch_room_value\", \"价值不符合\"),\n (\"switch_room_content\", \"内容不符合\"),\n (\"switch_room_countdown\", \"倒计时不符合\"),\n (\"switch_room_attend_fail\", \"参与失败\"),\n ]\n for key, label in switch_reasons:\n val = counters.get(key, 0)\n if val > 0:\n percentage = (val / switch_val) * 100 if switch_val > 0 else 0\n lines.append(f\" {label}: {val} ({percentage:.1f}%)\")\n lines.append(\"\")\n\n # 预约相关统计(详细版)\n reservation_recorded = counters.get(\"reservation_recorded\", 0)\n reservation_window_entered = counters.get(\"reservation_window_entered\", 0)\n reservation_back_success = counters.get(\"reservation_back_success\", 0)\n reservation_back_verify_ok = counters.get(\"reservation_back_verify_ok\", 0)\n reservation_back_verify_fail = counters.get(\"reservation_back_verify_fail\", 0)\n reservation_window_not_reached = counters.get(\"reservation_window_not_reached\", 0)\n reservation_expired = counters.get(\"reservation_expired\", 0)\n reservation_queue_empty = counters.get(\"reservation_queue_empty\", 0)\n reservation_locked = counters.get(\"reservation_locked\", 0)\n reservation_back_to_first = counters.get(\"reservation_back_to_first\", 0)\n reservation_queue_full_wait = counters.get(\"reservation_queue_full_wait\", 0)\n reservation_drop_low_value = counters.get(\"reservation_drop_low_value\", 0)\n reservation_clear = counters.get(\"reservation_clear\", 0)\n \n reservation_total = (\n reservation_recorded\n + reservation_window_entered\n + reservation_back_success\n + reservation_back_verify_ok\n + reservation_back_verify_fail\n + reservation_window_not_reached\n + reservation_expired\n + reservation_queue_empty\n + reservation_locked\n + reservation_back_to_first\n + reservation_queue_full_wait\n + reservation_drop_low_value\n + reservation_clear\n )\n \n if reservation_total > 0 or reservation_recorded > 0:\n lines.append(\"=\" * 60)\n lines.append(\"预约相关统计(详细)\")\n lines.append(\"=\" * 60)\n \n # 预约记录统计\n if reservation_recorded > 0:\n lines.append(f\"记录预约总数: {reservation_recorded}\")\n \n # 预约回退统计\n if reservation_back_success > 0:\n lines.append(f\"成功回退到预约直播间: {reservation_back_success}\")\n \n # 回退校验统计\n verify_total = reservation_back_verify_ok + reservation_back_verify_fail\n if verify_total > 0:\n verify_rate = (reservation_back_verify_ok / verify_total) * 100\n lines.append(\n f\"回退校验: {reservation_back_verify_ok} 成功 / {reservation_back_verify_fail} 失败 (成功率: {verify_rate:.1f}%)\"\n )\n \n # 预约窗口统计\n if reservation_window_entered > 0:\n lines.append(f\"进入预约参与窗口: {reservation_window_entered}\")\n if reservation_window_not_reached > 0:\n lines.append(f\"时间窗口未到(跳过): {reservation_window_not_reached}\")\n \n # 预约状态统计\n if reservation_expired > 0:\n lines.append(f\"过期预约(已清理): {reservation_expired}\")\n if reservation_locked > 0:\n lines.append(f\"锁定期未结束(跳过): {reservation_locked}\")\n if reservation_queue_empty > 0:\n lines.append(f\"预约队列为空(检查次数): {reservation_queue_empty}\")\n if reservation_queue_full_wait > 0:\n lines.append(f\"队列已满等待: {reservation_queue_full_wait}\")\n if reservation_back_to_first > 0:\n lines.append(f\"回退到第一个直播间: {reservation_back_to_first}\")\n \n # 预约管理统计\n if reservation_drop_low_value > 0:\n lines.append(f\"丢弃低价值预约: {reservation_drop_low_value}\")\n if reservation_clear > 0:\n lines.append(f\"清空预约队列: {reservation_clear}\")\n \n # 预约成功率\n if reservation_recorded > 0 and reservation_back_success > 0:\n back_rate = (reservation_back_success / reservation_recorded) * 100\n lines.append(f\"预约回退成功率: {back_rate:.1f}% ({reservation_back_success}/{reservation_recorded})\")\n \n lines.append(\"\")\n\n # 错误统计(详细版)\n error_total = counters.get(\"error_total\", 0)\n error_unbound_local = counters.get(\"error_unbound_local\", 0)\n error_attribute = counters.get(\"error_attribute\", 0)\n error_key = counters.get(\"error_key\", 0)\n error_value = counters.get(\"error_value\", 0)\n error_type = counters.get(\"error_type\", 0)\n error_timeout = counters.get(\"error_timeout\", 0)\n error_connection = counters.get(\"error_connection\", 0)\n error_ocr = counters.get(\"error_ocr\", 0)\n error_screenshot = counters.get(\"error_screenshot\", 0)\n error_detection = counters.get(\"error_detection\", 0)\n error_stage_diagnosis = counters.get(\"error_stage_diagnosis\", 0)\n error_read_detail = counters.get(\"error_read_detail\", 0)\n error_config_load = counters.get(\"error_config_load\", 0)\n error_state_file = counters.get(\"error_state_file\", 0)\n error_live_room_detect = counters.get(\"error_live_room_detect\", 0)\n error_fudai_find = counters.get(\"error_fudai_find\", 0)\n fudai_open_error = counters.get(\"fudai_open_error\", 0)\n fudai_open_error_too_many = counters.get(\"fudai_open_error_too_many\", 0)\n \n error_all = (\n error_total\n + error_unbound_local\n + error_attribute\n + error_key\n + error_value\n + error_type\n + error_timeout\n + error_connection\n + error_ocr\n + error_screenshot\n + error_detection\n + error_stage_diagnosis\n + error_read_detail\n + error_config_load\n + error_state_file\n + error_live_room_detect\n + error_fudai_find\n + fudai_open_error\n + fudai_open_error_too_many\n )\n \n if error_all > 0:\n lines.append(\"=\" * 60)\n lines.append(\"错误统计(详细)\")\n lines.append(\"=\" * 60)\n \n # 总错误数\n if error_total > 0:\n lines.append(f\"总错误数: {error_total}\")\n \n # 福袋相关错误\n fudai_errors = fudai_open_error + fudai_open_error_too_many\n if fudai_errors > 0:\n lines.append(\"\")\n lines.append(\"福袋相关错误:\")\n if fudai_open_error > 0:\n lines.append(f\" 打开福袋异常: {fudai_open_error}\")\n if fudai_open_error_too_many > 0:\n lines.append(f\" 打开失败次数过多: {fudai_open_error_too_many}\")\n \n # Python异常类型\n python_errors = (\n error_unbound_local\n + error_attribute\n + error_key\n + error_value\n + error_type\n )\n if python_errors > 0:\n lines.append(\"\")\n lines.append(\"Python异常类型:\")\n if error_unbound_local > 0:\n lines.append(f\" UnboundLocalError: {error_unbound_local}\")\n if error_attribute > 0:\n lines.append(f\" AttributeError: {error_attribute}\")\n if error_key > 0:\n lines.append(f\" KeyError: {error_key}\")\n if error_value > 0:\n lines.append(f\" ValueError: {error_value}\")\n if error_type > 0:\n lines.append(f\" TypeError: {error_type}\")\n \n # 功能模块错误\n module_errors = (\n error_ocr\n + error_screenshot\n + error_detection\n + error_stage_diagnosis\n + error_read_detail\n + error_config_load\n + error_state_file\n + error_live_room_detect\n + error_fudai_find\n )\n if module_errors > 0:\n lines.append(\"\")\n lines.append(\"功能模块错误:\")\n if error_ocr > 0:\n lines.append(f\" OCR识别错误: {error_ocr}\")\n if error_screenshot > 0:\n lines.append(f\" 截图错误: {error_screenshot}\")\n if error_detection > 0:\n lines.append(f\" 识别错误: {error_detection}\")\n if error_stage_diagnosis > 0:\n lines.append(f\" 阶段诊断错误: {error_stage_diagnosis}\")\n if error_read_detail > 0:\n lines.append(f\" 读取详情错误: {error_read_detail}\")\n if error_config_load > 0:\n lines.append(f\" 配置加载错误: {error_config_load}\")\n if error_state_file > 0:\n lines.append(f\" 状态文件错误: {error_state_file}\")\n if error_live_room_detect > 0:\n lines.append(f\" 直播间检测错误: {error_live_room_detect}\")\n if error_fudai_find > 0:\n lines.append(f\" 福袋查找错误: {error_fudai_find}\")\n \n # 网络和超时错误\n network_errors = error_timeout + error_connection\n if network_errors > 0:\n lines.append(\"\")\n lines.append(\"网络和超时错误:\")\n if error_timeout > 0:\n lines.append(f\" 超时错误: {error_timeout}\")\n if error_connection > 0:\n lines.append(f\" 连接错误: {error_connection}\")\n \n # 错误率统计\n if uptime_seconds > 0 and error_all > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(\"\")\n lines.append(f\"错误频率: {error_all / hours:.2f} 次/小时\")\n \n lines.append(\"\")\n\n # 价值统计(从事件中提取)\n events = stats.get(\"events\", [])\n prize_values = []\n for event in events:\n meta = event.get(\"meta\", {})\n if \"prize_value_yuan\" in meta and meta[\"prize_value_yuan\"] is not None:\n try:\n prize_values.append(float(meta[\"prize_value_yuan\"]))\n except (ValueError, TypeError):\n pass\n\n if prize_values:\n lines.append(\"=\" * 60)\n lines.append(\"价值统计\")\n lines.append(\"=\" * 60)\n total_value = sum(prize_values)\n avg_value = total_value / len(prize_values)\n max_value = max(prize_values)\n min_value = min(prize_values)\n lines.append(f\"识别到的福袋总数: {len(prize_values)}\")\n lines.append(f\"总价值: {total_value:.2f} 元\")\n lines.append(f\"平均价值: {avg_value:.2f} 元\")\n lines.append(f\"最高价值: {max_value:.2f} 元\")\n lines.append(f\"最低价值: {min_value:.2f} 元\")\n\n # 价值分布\n high_value_count = sum(1 for v in prize_values if v >= 500)\n medium_value_count = sum(1 for v in prize_values if 100 <= v < 500)\n low_value_count = sum(1 for v in prize_values if v < 100)\n lines.append(\"\")\n lines.append(\"价值分布:\")\n lines.append(\n f\" 高价值(≥500元): {high_value_count} ({high_value_count/len(prize_values)*100:.1f}%)\"\n )\n lines.append(\n f\" 中价值(100-500元): {medium_value_count} ({medium_value_count/len(prize_values)*100:.1f}%)\"\n )\n lines.append(\n f\" 低价值(<100元): {low_value_count} ({low_value_count/len(prize_values)*100:.1f}%)\"\n )\n lines.append(\"\")\n\n # 最近一次福袋信息\n fudai_last = stats.get(\"fudai_last\", {})\n if fudai_last.get(\"content\") or fudai_last.get(\"countdown\"):\n lines.append(\"=\" * 60)\n lines.append(\"最近一次福袋信息\")\n lines.append(\"=\" * 60)\n lines.append(f\"内容: {fudai_last.get('content') or '-'}\")\n lines.append(f\"倒计时: {fudai_last.get('countdown') or '-'}\")\n participants = fudai_last.get(\"participants\")\n copies = fudai_last.get(\"copies\")\n if participants is not None and copies is not None:\n lines.append(f\"参与人数/份数: {participants} / {copies}\")\n if participants > 0 and copies > 0:\n ratio = participants / copies\n lines.append(f\" 中奖概率: {1/ratio*100:.2f}% (1/{ratio:.1f})\")\n prize_value = fudai_last.get(\"prize_value_yuan\")\n if prize_value is not None:\n lines.append(f\"奖品价值: {prize_value} 元\")\n updated_ts = fudai_last.get(\"updated_ts\")\n if updated_ts:\n import datetime\n\n dt = datetime.datetime.fromtimestamp(updated_ts)\n lines.append(f\"更新时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}\")\n lines.append(\"\")\n\n # 中奖记录\n wins = stats.get(\"wins\", [])\n if wins:\n lines.append(\"=\" * 60)\n lines.append(f\"最近中奖记录(显示最近 {len(wins)} 条)\")\n lines.append(\"=\" * 60)\n for i, win in enumerate(wins[-10:], 1): # 只显示最近10条\n import datetime\n\n ts = win.get(\"ts\", 0)\n dt_str = (\n datetime.datetime.fromtimestamp(ts).strftime(\n \"%Y-%m-%d %H:%M:%S\"\n )\n if ts\n else \"-\"\n )\n lines.append(f\"\\n[{i}] 时间: {dt_str}\")\n if win.get(\"content\"):\n lines.append(f\" 内容: {win.get('content')}\")\n if win.get(\"prize_value_yuan\"):\n lines.append(f\" 价值: {win.get('prize_value_yuan')} 元\")\n if win.get(\"participants\") and win.get(\"copies\"):\n lines.append(\n f\" 人数/份数: {win.get('participants')} / {win.get('copies')}\"\n )\n\n # 确保至少显示基本信息\n if not lines:\n lines.append(\"=\" * 60)\n lines.append(\"统计信息\")\n lines.append(\"=\" * 60)\n lines.append(\"暂无统计数据\")\n lines.append(\"\")\n lines.append(\"提示:请先运行程序以收集统计数据\")\n\n stats_text.delete(\"1.0\", \"end\")\n stats_text.insert(\"1.0\", \"\\n\".join(lines))\n except Exception as e:\n import traceback\n\n stats_text.delete(\"1.0\", \"end\")\n error_detail = traceback.format_exc()\n stats_text.insert(\n \"1.0\", f\"刷新统计信息失败:{e}\\n\\n详细信息:\\n{error_detail}\"\n )\n\n ttk.Button(stats_top, text=\"刷新\", command=refresh_stats).pack(side=LEFT)\n\n # 预约队列显示\n reservation_top = ttk.Frame(reservation_tab)\n reservation_top.pack(fill=X, padx=10, pady=(10, 0))\n reservation_text = ScrolledText(reservation_tab)\n reservation_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n reservation_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def refresh_reservations():\n path = os.path.join(os.path.dirname(__file__), \"state\", \"reservations.json\")\n try:\n if os.path.exists(path):\n with open(path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n reservation_text.delete(\"1.0\", \"end\")\n reservation_text.insert(\n \"1.0\", json.dumps(data, ensure_ascii=False, indent=2)\n )\n else:\n reservation_text.delete(\"1.0\", \"end\")\n reservation_text.insert(\"1.0\", \"暂无预约队列数据\")\n except Exception as e:\n reservation_text.delete(\"1.0\", \"end\")\n reservation_text.insert(\"1.0\", f\"读取预约队列失败:{e}\")\n\n ttk.Button(reservation_top, text=\"刷新\", command=refresh_reservations).pack(\n side=LEFT\n )\n\n # 高价值房间显示\n high_value_top = ttk.Frame(high_value_tab)\n high_value_top.pack(fill=X, padx=10, pady=(10, 0))\n high_value_text = ScrolledText(high_value_tab)\n high_value_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n high_value_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def refresh_high_value_rooms():\n path = os.path.join(os.path.dirname(__file__), \"state\", \"high_value_rooms.json\")\n try:\n if os.path.exists(path):\n with open(path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n high_value_text.delete(\"1.0\", \"end\")\n high_value_text.insert(\n \"1.0\", json.dumps(data, ensure_ascii=False, indent=2)\n )\n else:\n high_value_text.delete(\"1.0\", \"end\")\n high_value_text.insert(\"1.0\", \"暂无高价值房间数据\")\n except Exception as e:\n high_value_text.delete(\"1.0\", \"end\")\n high_value_text.insert(\"1.0\", f\"读取高价值房间失败:{e}\")\n\n ttk.Button(high_value_top, text=\"刷新\", command=refresh_high_value_rooms).pack(\n side=LEFT\n )\n\n # 行为日志显示(点击/识别/耗时)\n actions_log_top = ttk.Frame(actions_log_tab)\n actions_log_top.pack(fill=X, padx=10, pady=(10, 0))\n actions_log_text = ScrolledText(actions_log_tab)\n actions_log_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n actions_log_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n actions_filter_var = tk.StringVar(value=\"\")\n\n def refresh_actions_log():\n \"\"\"读取 logs/actions.log 的尾部若干行,在 GUI 中展示关键行为日志(支持简单关键字筛选)。\"\"\"\n path = os.path.join(os.path.dirname(__file__), \"logs\", \"actions.log\")\n try:\n if os.path.exists(path):\n # 仿照 web_gui 的实现:只读最后一小段,避免文件巨大\n size = os.path.getsize(path)\n if size == 0:\n actions_log_text.delete(\"1.0\", \"end\")\n actions_log_text.insert(\"1.0\", \"行为日志文件为空\")\n return\n \n read_bytes = min(size, 65536)\n with open(path, \"rb\") as f:\n if read_bytes < size:\n f.seek(-read_bytes, os.SEEK_END)\n data = f.read()\n # 尝试多种编码方式\n try:\n # 先尝试 utf-8-sig(带BOM)\n text = data.decode(\"utf-8-sig\", errors=\"replace\")\n except Exception:\n try:\n # 再尝试 utf-8\n text = data.decode(\"utf-8\", errors=\"replace\")\n except Exception:\n # 最后尝试 gbk(Windows常见编码)\n text = data.decode(\"gbk\", errors=\"replace\")\n lines = text.splitlines()\n # 只取最近 300 行\n tail = lines[-300:]\n\n # 关键字筛选:若填写了筛选词,只保留包含该关键字的行\n kw = actions_filter_var.get().strip()\n if kw:\n tail = [ln for ln in tail if kw in ln]\n\n # 保存当前滚动位置,避免刷新时自动置顶\n try:\n scroll_position = actions_log_text.yview()[0] # 获取当前滚动位置(顶部可见位置的比例)\n except Exception:\n scroll_position = 0.0\n\n actions_log_text.delete(\"1.0\", \"end\")\n if tail:\n actions_log_text.insert(\"1.0\", \"\\n\".join(tail))\n else:\n actions_log_text.insert(\"1.0\", \"暂无匹配的行为日志\")\n \n # 恢复之前的滚动位置,避免自动置顶\n try:\n actions_log_text.yview_moveto(scroll_position)\n except Exception:\n pass\n else:\n actions_log_text.delete(\"1.0\", \"end\")\n actions_log_text.insert(\n \"1.0\", \"暂无行为日志(logs/actions.log 不存在)\"\n )\n except Exception as e:\n actions_log_text.delete(\"1.0\", \"end\")\n actions_log_text.insert(\"1.0\", f\"读取行为日志失败:{e}\")\n\n ttk.Label(actions_log_top, text=\"关键字筛选:\").pack(side=LEFT)\n ttk.Entry(actions_log_top, textvariable=actions_filter_var, width=16).pack(\n side=LEFT, padx=(0, 8)\n )\n ttk.Button(actions_log_top, text=\"刷新\", command=refresh_actions_log).pack(\n side=LEFT, padx=(0, 10)\n )\n \n # 行为日志搜索功能\n ttk.Separator(actions_log_top, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=5, pady=3)\n ttk.Label(actions_log_top, text=\"搜索:\").pack(side=LEFT)\n \n actions_search_var = tk.StringVar(value=\"\")\n actions_search_entry = ttk.Entry(actions_log_top, textvariable=actions_search_var, width=20)\n actions_search_entry.pack(side=LEFT, padx=(0, 5))\n \n actions_search_matches = []\n actions_current_match_index = -1\n \n def search_in_actions_log(direction=1):\n \"\"\"在行为日志中搜索文本\"\"\"\n nonlocal actions_search_matches, actions_current_match_index\n \n search_text = actions_search_var.get().strip()\n if not search_text:\n actions_log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n actions_log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n actions_search_matches = []\n actions_current_match_index = -1\n return\n \n content = actions_log_text.get(\"1.0\", \"end-1c\")\n if not content:\n return\n \n actions_log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n actions_log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n \n actions_log_text.tag_config(\"search_highlight\", background=\"yellow\")\n actions_log_text.tag_config(\"search_current\", background=\"orange\")\n \n actions_search_matches = []\n start_pos = 0 # 使用整数索引\n search_text_lower = search_text.lower()\n content_lower = content.lower()\n \n while True:\n pos = content_lower.find(search_text_lower, start_pos)\n if pos == -1:\n break\n \n line_start = content[:pos].rfind(\"\\n\") + 1\n line_num = content[:pos].count(\"\\n\") + 1\n col_num = pos - line_start\n \n start_index = f\"{line_num}.{col_num}\"\n end_index = f\"{line_num}.{col_num + len(search_text)}\"\n \n actions_search_matches.append((start_index, end_index))\n start_pos = pos + 1\n \n if not actions_search_matches:\n actions_current_match_index = -1\n return\n \n for start_idx, end_idx in actions_search_matches:\n actions_log_text.tag_add(\"search_highlight\", start_idx, end_idx)\n \n if direction == 1:\n actions_current_match_index = (actions_current_match_index + 1) % len(actions_search_matches)\n else:\n actions_current_match_index = (actions_current_match_index - 1) % len(actions_search_matches)\n \n if actions_current_match_index >= 0:\n start_idx, end_idx = actions_search_matches[actions_current_match_index]\n actions_log_text.tag_add(\"search_current\", start_idx, end_idx)\n actions_log_text.see(start_idx)\n actions_log_text.mark_set(\"insert\", start_idx)\n \n def search_next_in_actions():\n search_in_actions_log(1)\n \n def search_prev_in_actions():\n search_in_actions_log(-1)\n \n def clear_search_in_actions():\n nonlocal actions_search_matches, actions_current_match_index\n actions_search_var.set(\"\")\n actions_log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n actions_log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n actions_search_matches = []\n actions_current_match_index = -1\n \n def on_actions_search_entry_key(event):\n if event.keysym == \"Return\":\n search_next_in_actions()\n \n actions_search_entry.bind(\"<KeyPress>\", on_actions_search_entry_key)\n \n ttk.Button(actions_log_top, text=\"搜索\", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2))\n ttk.Button(actions_log_top, text=\"上一个\", command=search_prev_in_actions).pack(side=LEFT, padx=(0, 2))\n ttk.Button(actions_log_top, text=\"下一个\", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2))\n ttk.Button(actions_log_top, text=\"清除\", command=clear_search_in_actions).pack(side=LEFT)\n\n # OCR结果显示\n ocr_results_top = ttk.Frame(ocr_results_tab)\n ocr_results_top.pack(fill=X, padx=10, pady=(10, 0))\n ocr_results_text = ScrolledText(ocr_results_tab)\n ocr_results_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n ocr_results_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def update_ocr_results(results):\n \"\"\"更新OCR结果标签页的显示\"\"\"\n try:\n lines = []\n lines.append(\"=\" * 80)\n lines.append(\"OCR识别结果(基于最新截图)\")\n lines.append(\"=\" * 80)\n lines.append(\"\")\n\n if not results:\n lines.append('暂无OCR结果,请先点击\"截图+OCR\"按钮')\n else:\n # 按区域名称分组显示\n for region_name, desc, text_result, status in results:\n lines.append(f\"【{region_name}】{desc}\")\n lines.append(f\" 状态: {status}\")\n if text_result:\n # 如果文本较长,分行显示\n if len(text_result) > 100:\n lines.append(f\" 识别文本: {text_result[:100]}...\")\n lines.append(f\" (完整文本: {text_result})\")\n else:\n lines.append(f\" 识别文本: {text_result}\")\n else:\n lines.append(\" 识别文本: (空)\")\n lines.append(\"\")\n\n ocr_results_text.delete(\"1.0\", \"end\")\n ocr_results_text.insert(\"1.0\", \"\\n\".join(lines))\n ocr_results_text.see(\"1.0\")\n except Exception as e:\n ocr_results_text.delete(\"1.0\", \"end\")\n ocr_results_text.insert(\"1.0\", f\"更新OCR结果失败:{e}\")\n\n ttk.Button(\n ocr_results_top, text=\"刷新\", command=lambda: update_ocr_results([])\n ).pack(side=LEFT)\n ttk.Label(ocr_results_top, text='(点击\"截图+OCR\"按钮自动更新)').pack(\n side=LEFT, padx=(10, 0)\n )\n\n pump_logs()\n\n def delayed_refresh_preview() -> None:\n if image_var.get():\n refresh_preview()\n\n root.after(300, delayed_refresh_preview) # type: ignore[arg-type]\n root.after(500, refresh_stats) # type: ignore[arg-type]\n root.after(500, refresh_reservations) # type: ignore[arg-type]\n root.after(500, refresh_high_value_rooms) # type: ignore[arg-type]\n root.after(500, refresh_actions_log) # type: ignore[arg-type]\n\n # 定期刷新行为日志(每2秒)\n def auto_refresh_actions_log() -> None:\n refresh_actions_log()\n root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]\n \n root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]\n\n # 定期刷新统计信息(每3秒)\n def auto_refresh_stats() -> None:\n if runner.is_running():\n refresh_stats()\n root.after(3000, auto_refresh_stats) # type: ignore[arg-type]\n\n auto_refresh_stats()\n\n def on_close():\n try:\n runner.stop()\n except Exception:\n pass\n root.destroy()\n\n root.protocol(\"WM_DELETE_WINDOW\", on_close)\n refresh_devices()\n root.mainloop()\n\n\nif __name__ == \"__main__\":\n try:\n from version import print_version_banner\n\n print_version_banner(\"gui_app\")\n except Exception:\n pass\n main()\n" +} +``` +User decision: **accepted** + +Status: **completed** + + +
+
+ +--- + + +
+Tool use: **apply_patch** + + +Parameters: + +```json +{ + "relativeWorkspacePath": "gui_app.py" +} +``` +Additional data: + +```json +{ + "codeblockId": "962c5073-192e-4717-9dde-7cd0c0d931f0" +} +``` +Result: + +```json +{ + "diff": { + "chunks": [ + { + "diffString": " debug_captures_config = cfg.get(\"debug_captures\", {})\n if isinstance(debug_captures_config, dict):\n+ debug_captures_enabled_var.set(\n+ bool(debug_captures_config.get(\"enabled\", False))\n+ )\n debug_captures_auto_cleanup_var.set(\n bool(debug_captures_config.get(\"auto_cleanup\", True))", + "oldStart": 1268, + "newStart": 1268, + "oldLines": 4, + "newLines": 7, + "linesAdded": 3 + }, + { + "diffString": " if \"debug_captures\" not in cfg2 or not isinstance(cfg2[\"debug_captures\"], dict):\n cfg2[\"debug_captures\"] = {}\n+ cfg2[\"debug_captures\"][\"enabled\"] = bool(\n+ debug_captures_enabled_var.get()\n+ )\n cfg2[\"debug_captures\"][\"auto_cleanup\"] = bool(\n debug_captures_auto_cleanup_var.get()", + "oldStart": 1457, + "newStart": 1460, + "oldLines": 4, + "newLines": 7, + "linesAdded": 3 + } + ], + "editor": "EDITOR_AI" + }, + "shouldAutoFixLints": true, + "resultForModel": "Success. Updated the following files:\nM gui_app.py", + "contentsAfterEdit": "import json\nimport os\nimport queue\nimport re\nimport sys\nimport threading\nimport warnings\nfrom datetime import datetime\nfrom typing import Any, Callable\n\nfrom PIL import Image, ImageTk\n\n# 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化)\nfrom gui_core import (\n RunParams,\n Runner,\n find_adb_executable,\n list_adb_devices,\n read_config,\n write_config,\n)\nfrom path_config import get_logs_dir\n\n# 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告)\nwarnings.filterwarnings(\"ignore\", message=\".*pin_memory.*\", category=UserWarning)\nwarnings.filterwarnings(\"ignore\", message=\".*accelerator.*\", category=UserWarning)\n\n\ndef main():\n # ttkbootstrap 优先(更美观);没装则回退到原生 tkinter\n try:\n import ttkbootstrap as tb\n from ttkbootstrap.scrolled import ScrolledText\n\n import tkinter as tk\n from tkinter import ttk\n from ttkbootstrap.constants import LEFT, RIGHT, BOTH, X, Y\n\n root = tb.Window(themename=\"darkly\")\n except Exception:\n import tkinter as tk\n from tkinter import ttk\n from tkinter.constants import LEFT, RIGHT, BOTH, X, Y # type: ignore[assignment]\n from tkinter.scrolledtext import ScrolledText\n\n root = tk.Tk()\n\n root.title(\"抖音福袋挂机 - 可视化控制台\")\n root.geometry(\"1400x900\") # 增大窗口尺寸,提供更多空间\n\n q: queue.Queue[str] = queue.Queue()\n\n # ========== 线程安全的日志文件写入器 ==========\n class ThreadSafeLogWriter:\n \"\"\"线程安全的日志文件写入器,确保日志能稳定写入文件\"\"\"\n\n def __init__(self, log_dir: str | None = None):\n self._lock = threading.Lock()\n self._log_dir = log_dir or get_logs_dir()\n self._log_file_path: str = \"\"\n self._log_file_enabled: bool = True\n self._init_log_file()\n self._write_error_warned = False\n\n def _init_log_file(self) -> None:\n \"\"\"初始化日志文件路径(按日期)\"\"\"\n try:\n # 确保日志目录存在\n os.makedirs(self._log_dir, exist_ok=True)\n\n # 读取配置,检查是否启用日志文件\n cfg = read_config()\n self._log_file_enabled = bool(cfg.get(\"log_unified_enabled\", True))\n\n # 获取日志文件路径配置\n log_path = cfg.get(\"log_unified_path\") or \"logs/unified.log\"\n if not os.path.isabs(log_path):\n from path_config import PROJECT_ROOT\n\n log_path = os.path.join(PROJECT_ROOT, log_path)\n\n # 如果配置了按日期分割,使用日期后缀\n use_dated_logs = cfg.get(\"logging\", {}).get(\"use_dated_logs\", True)\n if use_dated_logs:\n # 提取基础文件名(移除扩展名)\n base_name = os.path.splitext(log_path)[0]\n today = datetime.now().strftime(\"%Y-%m-%d\")\n self._log_file_path = f\"{base_name}_{today}.log\"\n else:\n self._log_file_path = log_path\n except Exception as e:\n # 如果配置读取失败,使用默认路径\n today = datetime.now().strftime(\"%Y-%m-%d\")\n self._log_file_path = os.path.join(\n self._log_dir, f\"unified_{today}.log\"\n )\n if not self._write_error_warned:\n print(f\"[GUI日志] 配置读取失败,使用默认路径: {e}\", file=sys.stderr)\n\n def write(self, line: str) -> None:\n \"\"\"线程安全地写入日志行到文件\"\"\"\n if not self._log_file_enabled:\n return\n\n if not line or not line.strip():\n return\n\n with self._lock:\n try:\n # 检查日期是否变化(如果使用日期日志)\n cfg = read_config()\n use_dated_logs = cfg.get(\"logging\", {}).get(\"use_dated_logs\", True)\n if use_dated_logs:\n today = datetime.now().strftime(\"%Y-%m-%d\")\n current_base = os.path.splitext(self._log_file_path)[0]\n if not current_base.endswith(today):\n # 日期变化,更新文件路径\n base_name = (\n current_base.rsplit(\"_\", 1)[0]\n if \"_\" in os.path.basename(current_base)\n else current_base\n )\n self._log_file_path = f\"{base_name}_{today}.log\"\n\n # 确保目录存在\n log_dir = os.path.dirname(self._log_file_path)\n if log_dir:\n os.makedirs(log_dir, exist_ok=True)\n\n # 写入文件(追加模式,UTF-8编码,带BOM避免Windows乱码)\n with open(\n self._log_file_path, \"a\", encoding=\"utf-8-sig\", errors=\"replace\"\n ) as f:\n # 如果行已经包含时间戳(格式:YYYY-MM-DD HH:MM:SS),直接写入\n # 否则添加时间戳\n if line.strip() and not (line[0].isdigit() and \" - [\" in line):\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")[\n :-3\n ]\n formatted_line = f\"{timestamp} - [GUI] - {line}\\n\"\n else:\n formatted_line = f\"{line}\\n\"\n\n f.write(formatted_line)\n f.flush() # 立即刷新缓冲区,确保日志及时写入磁盘\n\n except PermissionError as e:\n if not self._write_error_warned:\n print(\n f\"[GUI日志] 权限错误,无法写入日志文件: {self._log_file_path}\",\n file=sys.stderr,\n )\n print(f\"[GUI日志] 错误详情: {e}\", file=sys.stderr)\n self._write_error_warned = True\n except Exception as e:\n if not self._write_error_warned:\n print(\n f\"[GUI日志] 写入日志文件失败: {self._log_file_path}\",\n file=sys.stderr,\n )\n print(f\"[GUI日志] 错误详情: {e}\", file=sys.stderr)\n self._write_error_warned = True\n\n # 创建日志写入器实例\n log_writer = ThreadSafeLogWriter()\n\n def _format_gui_log_line(line: str) -> str:\n \"\"\"\n 将“完整日志行”转换为 GUI 显示用的精简版本。\n\n 需求:\n - 文件中:仍然写入完整统一日志(含时间戳 / 级别 / 模块等信息);\n - GUI 中:保留【时间戳 + 业务日志】;\n - 如果该行包含识别/匹配的分数(如 `匹配度=0.87` / `相似度=0.95` / `score=0.83`),\n 需要在 GUI 文本中一并保留/补充出来。\n\n 精简规则(兼容统一日志格式):\n - 统一日志通常形如:\n YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - [线程] - [模块:函数:行号] - [traceId:xxx] - 业务内容\n - GUI 只展示:\n YYYY-MM-DD HH:MM:SS.xxx 业务内容(末尾可追加“(匹配度=..., 相似度=..., score=...)”)\n - 其他不符合该模式的行保持原样。\n \"\"\"\n s = (line or \"\").rstrip(\"\\n\")\n if not s:\n return s\n\n ts_part: str | None = None\n msg_part: str | None = None\n\n # 1)新统一日志格式:[YYYY-MM-DD HH:MM:SS.xxx] [LEVEL] ... 业务内容 字段_xxx=...\n m = re.match(r\"^\\[(\\d{4}-\\d{2}-\\d{2} [0-9:.]+)\\]\\s+\\[[A-Z]+\\]\\s+(.*)$\", s)\n if m:\n ts_part = m.group(1).strip()\n msg_part = m.group(2).strip()\n # 2)旧统一日志格式:YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - ... - 业务内容\n elif s[0].isdigit() and \" - \" in s:\n parts = s.split(\" - \")\n if len(parts) >= 3:\n ts_part = parts[0].strip()\n msg_part = parts[-1].strip()\n\n # 如果没解析出“时间戳 + 业务文案”,原样返回\n if not ts_part or msg_part is None:\n return s\n\n # 从业务文案中拆分出 字段_xxx=yyy,非 score 类字段在 GUI 中隐藏\n keep_tokens: list[str] = []\n\n def _is_score_field(k: str) -> bool:\n kl = k.lower()\n return (\n \"score\" in kl\n or \"match\" in kl\n or \"匹配\" in k\n or \"相似\" in k\n )\n\n for m2 in re.finditer(r\"字段_([^\\s=]+)=([^\\s]+)\", msg_part):\n key = m2.group(1)\n val = m2.group(2)\n if _is_score_field(key):\n keep_tokens.append(f\"{key}={val}\")\n\n # 先把所有 字段_xxx=yyy 从业务文案中移除\n clean_msg = re.sub(r\"\\s*字段_[^\\s=]+=[^\\s]+\", \"\", msg_part).strip()\n\n # 追加需要展示的分数字段\n if keep_tokens:\n clean_msg = f\"{clean_msg} ({', '.join(keep_tokens)})\"\n\n return f\"{ts_part} {clean_msg}\"\n\n # 不符合“完整格式”的行,原样返回\n return s\n\n def on_line(line: str):\n \"\"\"处理日志行:GUI 显示用精简版本,文件写入用完整版本\"\"\"\n # GUI 显示:使用精简后的版本\n try:\n display_line = _format_gui_log_line(line)\n except Exception:\n display_line = line\n q.put(display_line)\n\n # 文件:写入完整日志行(不做精简处理)\n try:\n log_writer.write(line)\n except Exception:\n pass # 文件写入失败不应影响GUI显示\n\n runner = Runner(on_line=on_line)\n\n # 顶部:设备选择 + Y偏移(其余运行参数放到左侧分组,避免重复)\n top = ttk.Frame(root)\n top.pack(fill=X, padx=12, pady=10)\n\n adb_exe = find_adb_executable()\n devices = list_adb_devices(adb_exe)\n device_var = tk.StringVar(value=(devices[0] if devices else \"\"))\n\n ttk.Label(top, text=\"设备:\").pack(side=LEFT)\n device_combo = ttk.Combobox(top, textvariable=device_var, values=devices, width=28)\n device_combo.pack(side=LEFT, padx=(0, 10))\n\n def refresh_devices():\n nonlocal adb_exe\n adb_exe = find_adb_executable()\n devs = list_adb_devices(adb_exe)\n device_combo[\"values\"] = devs\n if devs and not device_var.get():\n device_var.set(devs[0])\n if not adb_exe:\n on_line(\"[设备] 未找到 adb.exe(请确认已安装 platform-tools)\")\n elif not devs:\n on_line(\"[设备] adb 可用,但未发现 device 状态设备(可能未授权/未连接)\")\n\n ttk.Button(top, text=\"刷新设备\", command=refresh_devices).pack(\n side=LEFT, padx=(0, 20)\n )\n\n # 配置区(提前读取配置,供后续使用)\n cfg = read_config()\n\n y_var = tk.IntVar(value=int(cfg.get(\"y_pianyi\", 0) or 0))\n ttk.Label(top, text=\"Y偏移:\").pack(side=LEFT)\n ttk.Spinbox(top, from_=-200, to=200, textvariable=y_var, width=6).pack(\n side=LEFT, padx=(0, 12)\n )\n\n # 中部:左侧配置(使用Notebook标签页)+ 右侧日志/预览(支持拖拽调整宽度)\n mid = ttk.PanedWindow(root, orient=\"horizontal\")\n mid.pack(fill=BOTH, expand=True, padx=12, pady=(0, 12))\n\n left_wrap = ttk.Frame(mid)\n right = ttk.Frame(mid)\n mid.add(left_wrap, weight=0) # 左侧配置区域\n mid.add(right, weight=1) # 右侧日志/预览区域\n\n # 左侧使用Notebook标签页组织配置\n left_notebook = ttk.Notebook(left_wrap)\n left_notebook.pack(fill=BOTH, expand=True)\n needswitch_var = tk.BooleanVar(value=bool(cfg.get(\"needswitch\", True)))\n infinite_loop_var = tk.BooleanVar(\n value=bool(cfg.get(\"infinite_loop_enabled\", False))\n )\n wait_minutes_var = tk.IntVar(value=int(cfg.get(\"wait_minutes\", 5) or 5))\n\n min_value_var = tk.DoubleVar(value=float(cfg.get(\"min_prize_value_yuan\", 0) or 0))\n min_participants_var = tk.IntVar(value=int(cfg.get(\"min_participants\", 0) or 0))\n max_participants_var = tk.IntVar(value=int(cfg.get(\"max_participants\", 0) or 0))\n skip_gt_seconds_var = tk.IntVar(\n value=int(cfg.get(\"skip_if_countdown_gt_seconds\", 900) or 900)\n )\n reset_after_swipes_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"reset_after_swipes_enabled\", False))\n )\n reset_after_swipes_var = tk.IntVar(\n value=int(cfg.get(\"reset_after_swipes\", 10) or 10)\n )\n # 按需求:删除\"自动养号/随机等待/轻微扰动/定时休息\"等设置,仅保留\"推荐页养号(爱心/收藏/评论)\"配置。\n auto_join_var = tk.BooleanVar(value=bool(cfg.get(\"auto_join_fansclub\", False)))\n fansclub_action_var = tk.StringVar(\n value=str(cfg.get(\"fansclub_fail_action\", \"stay\") or \"stay\").lower()\n )\n\n # Web端新增配置变量 - 高价值预约相关\n high_value_fudai_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"high_value_fudai_enabled\", False))\n )\n high_value_fudai_threshold_yuan_var = tk.DoubleVar(\n value=float(cfg.get(\"high_value_fudai_threshold_yuan\", 1000) or 1000)\n )\n high_value_fudai_join_ahead_seconds_var = tk.IntVar(\n value=int(cfg.get(\"high_value_fudai_join_ahead_seconds\", 120) or 120)\n )\n high_value_fudai_max_swipe_back_var = tk.IntVar(\n value=int(cfg.get(\"high_value_fudai_max_swipe_back\", 60) or 60)\n )\n high_value_fudai_max_reservations_var = tk.IntVar(\n value=int(cfg.get(\"high_value_fudai_max_reservations\", 5) or 5)\n )\n high_value_fudai_after_action_var = tk.StringVar(\n value=str(cfg.get(\"high_value_fudai_after_action\", \"continue\") or \"continue\")\n )\n high_value_room_revisit_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"high_value_room_revisit_enabled\", True))\n )\n high_value_room_revisit_only_current_run_var = tk.BooleanVar(\n value=bool(cfg.get(\"high_value_room_revisit_only_current_run\", False))\n )\n reservation_back_verify_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"reservation_back_verify_enabled\", True))\n )\n reservation_back_swipe_delay_var = tk.DoubleVar(\n value=float(cfg.get(\"reservation_back_swipe_delay\", 0) or 0)\n )\n reservation_preempt_min_value_var = tk.DoubleVar(\n value=float(cfg.get(\"reservation_preempt_min_value\", 0) or 0)\n )\n fudai_find_max_attempts_var = tk.IntVar(\n value=int(cfg.get(\"fudai_find_max_attempts\", 0) or 0)\n )\n fudai_icon_retry_delay_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_icon_retry_delay_seconds\", 0.6) or 0.6)\n )\n fudai_icon_max_wait_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_icon_max_wait_seconds\", 5.0) or 5.0)\n )\n fudai_click_wait_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_click_wait_seconds\", 2.0) or 2.0)\n )\n switch_room_wait_after_stage_diag_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"switch_room_wait_after_stage_diag_seconds\", 7.0) or 7.0)\n )\n live_room_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"live_room_match_threshold\", 0.8) or 0.8)\n )\n\n # 推荐页养号:爱心/收藏/评论(基于图标模板匹配 + 坐标点击)\n yg_enabled_var = tk.BooleanVar(value=bool(cfg.get(\"yanghao_enabled\", True)))\n yg_actions_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"yanghao_enable_actions\", True))\n )\n yg_recommend_duration_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_recommend_duration_seconds\", 60) or 60)\n )\n yg_recommend_interval_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_recommend_interval_seconds\", 0) or 0)\n )\n yg_like_prob_var = tk.DoubleVar(\n value=float(cfg.get(\"yanghao_like_prob\", 0.0) or 0.0)\n )\n yg_fav_prob_var = tk.DoubleVar(value=float(cfg.get(\"yanghao_fav_prob\", 0.0) or 0.0))\n yg_comment_prob_var = tk.DoubleVar(\n value=float(cfg.get(\"yanghao_comment_prob\", 0.0) or 0.0)\n )\n yg_icon_roi_size_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_icon_roi_size\", 240) or 240)\n )\n yg_icon_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"yanghao_icon_match_threshold\", 0.72) or 0.72)\n )\n yg_step_screenshot_var = tk.BooleanVar(\n value=bool(cfg.get(\"yanghao_step_screenshot\", False))\n )\n yg_like_roi_offset_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_like_roi_offset_x\", 0) or 0)\n )\n yg_like_roi_offset_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_like_roi_offset_y\", 0) or 0)\n )\n yg_fav_roi_offset_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_fav_roi_offset_x\", 0) or 0)\n )\n yg_fav_roi_offset_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_fav_roi_offset_y\", 0) or 0)\n )\n yg_like_icon_x_var = tk.IntVar(value=int(cfg.get(\"yanghao_like_icon_x\", 0) or 0))\n yg_like_icon_y_var = tk.IntVar(value=int(cfg.get(\"yanghao_like_icon_y\", 0) or 0))\n yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get(\"yanghao_fav_icon_x\", 0) or 0))\n yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get(\"yanghao_fav_icon_y\", 0) or 0))\n yg_like_template_path_var = tk.StringVar(\n value=str(\n cfg.get(\"yanghao_like_template_path\", \"assets/like.png\")\n or \"assets/like.png\"\n )\n )\n yg_fav_template_path_var = tk.StringVar(\n value=str(\n cfg.get(\"yanghao_fav_template_path\", \"assets/fav.png\") or \"assets/fav.png\"\n )\n )\n yg_after_dwell_direction_var = tk.StringVar(\n value=str(cfg.get(\"yanghao_after_dwell_swipe_direction\", \"up\") or \"up\")\n )\n yg_after_dwell_distance_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_after_dwell_swipe_distance_px\", 900) or 900)\n )\n yg_comment_btn_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_btn_x\", 0) or 0)\n )\n yg_comment_btn_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_btn_y\", 0) or 0)\n )\n yg_comment_input_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_input_x\", 0) or 0)\n )\n yg_comment_input_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_input_y\", 0) or 0)\n )\n yg_comment_send_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_send_x\", 0) or 0)\n )\n yg_comment_send_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_send_y\", 0) or 0)\n )\n yg_comment_close_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_close_x\", 0) or 0)\n )\n yg_comment_close_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_close_y\", 0) or 0)\n )\n fudai_quiet_hours_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"fudai_quiet_hours_enabled\", True))\n )\n fudai_quiet_start_hour_var = tk.IntVar(\n value=int(cfg.get(\"fudai_quiet_start_hour\", 2) or 2)\n )\n fudai_quiet_end_hour_var = tk.IntVar(\n value=int(cfg.get(\"fudai_quiet_end_hour\", 7) or 7)\n )\n\n # 阶段诊断时间参数(用于调试)\n stage_diag_max_time_var = tk.DoubleVar(\n value=float(cfg.get(\"stage_diag_max_time\", 10.0) or 10.0)\n )\n stage_diag_max_step_time_var = tk.DoubleVar(\n value=float(cfg.get(\"stage_diag_max_step_time\", 2.0) or 2.0)\n )\n enable_ocr_mode1_var = tk.BooleanVar(value=bool(cfg.get(\"enable_ocr_mode1\", False)))\n # 福袋模板匹配开关和阈值\n fudai_template_match_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"fudai_template_match_enabled\", False))\n )\n fudai_template_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_template_match_threshold\", 0.7) or 0.7)\n )\n # 福袋详情页模板匹配阈值(0.0~1.0,默认0.7)\n fudai_detail_template_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_detail_template_threshold\", 0.7) or 0.7)\n )\n # 开奖页面红色占比阈值(0.0~1.0,默认0.9)\n lucky_draw_red_ratio_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"lucky_draw_red_ratio_threshold\", 0.9) or 0.9)\n )\n # 优惠券模板匹配阈值(0.0~1.0,默认0.75)\n coupon_template_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"coupon_template_match_threshold\", 0.75) or 0.75)\n )\n # 参与按钮红色占比阈值(0.0~1.0,默认0.25)\n attend_button_red_ratio_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"attend_button_red_ratio_threshold\", 0.25) or 0.25)\n )\n # 粉丝团加入红色占比阈值(0.0~1.0,默认0.25)\n fansclub_join_red_ratio_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"fansclub_join_red_ratio_threshold\", 0.25) or 0.25)\n )\n\n # 调试图像开关 & 清理相关变量\n debug_captures_enabled_var = tk.BooleanVar(\n value=bool(\n cfg.get(\"debug_captures\", {}).get(\"enabled\", False)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else False\n )\n )\n # 调试图像清理相关变量\n debug_captures_auto_cleanup_var = tk.BooleanVar(\n value=bool(\n cfg.get(\"debug_captures\", {}).get(\"auto_cleanup\", True)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else True\n )\n )\n debug_captures_keep_days_var = tk.IntVar(\n value=int(\n cfg.get(\"debug_captures\", {}).get(\"keep_days\", 7)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else 7\n )\n )\n debug_captures_max_files_var = tk.IntVar(\n value=int(\n cfg.get(\"debug_captures\", {}).get(\"max_files\", 2000)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else 2000\n )\n )\n\n # 倒计时小于阈值参数\n skip_lt_seconds_var = tk.IntVar(\n value=int(cfg.get(\"skip_if_countdown_lt_seconds\", 5) or 5)\n )\n\n # 创建左侧配置标签页\n # 标签页1:运行设置\n run_tab = ttk.Frame(left_notebook)\n left_notebook.add(run_tab, text=\"运行设置\")\n\n run_box = ttk.LabelFrame(run_tab, text=\"基本运行参数\")\n run_box.pack(fill=X, padx=10, pady=(10, 10))\n\n r0 = ttk.Frame(run_box)\n r0.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Checkbutton(r0, text=\"允许切换直播间\", variable=needswitch_var).pack(side=LEFT)\n\n r1 = ttk.Frame(run_box)\n r1.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Checkbutton(r1, text=\"无限循环模式\", variable=infinite_loop_var).pack(side=LEFT)\n ttk.Label(r1, text=\"运行时长(分钟):\").pack(side=LEFT, padx=(10, 0))\n wait_minutes_spinbox = ttk.Spinbox(\n r1, from_=1, to=60, textvariable=wait_minutes_var, width=6\n )\n wait_minutes_spinbox.pack(side=LEFT, padx=(0, 12))\n\n # 根据无限循环开关状态,启用/禁用运行时长输入框\n def update_wait_minutes_state(*args):\n if infinite_loop_var.get():\n wait_minutes_spinbox.config(state=\"disabled\")\n else:\n wait_minutes_spinbox.config(state=\"normal\")\n\n infinite_loop_var.trace(\"w\", update_wait_minutes_state)\n update_wait_minutes_state() # 初始化状态\n\n ttk.Label(r1, text=\"倒计时大于(秒)时不参与(高价值可预约):\").pack(side=LEFT)\n ttk.Spinbox(r1, from_=0, to=3600, textvariable=skip_gt_seconds_var, width=6).pack(\n side=LEFT\n )\n\n r2 = ttk.Frame(run_box)\n r2.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Checkbutton(\n r2, text=\"切换N次后回到第一个\", variable=reset_after_swipes_enabled_var\n ).pack(side=LEFT)\n ttk.Label(r2, text=\"次数:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n r2, from_=1, to=9999, textvariable=reset_after_swipes_var, width=6\n ).pack(side=LEFT)\n ttk.Label(r2, text=\"(触发后会向上回退)\").pack(side=LEFT, padx=(6, 0))\n\n # 标签页2:筛选设置\n filter_tab = ttk.Frame(left_notebook)\n left_notebook.add(filter_tab, text=\"筛选设置\")\n\n cfg_box = ttk.LabelFrame(filter_tab, text=\"福袋筛选条件\")\n cfg_box.pack(fill=X, padx=10, pady=(10, 10))\n\n row = ttk.Frame(cfg_box)\n row.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Label(row, text=\"最低价值(元):\").pack(side=LEFT)\n ttk.Spinbox(\n row, from_=0, to=99999, increment=1, textvariable=min_value_var, width=10\n ).pack(side=LEFT)\n\n rowp = ttk.Frame(cfg_box)\n rowp.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(rowp, text=\"参与人数范围:\").pack(side=LEFT)\n ttk.Spinbox(\n rowp,\n from_=0,\n to=99999999,\n increment=1,\n textvariable=min_participants_var,\n width=10,\n ).pack(side=LEFT)\n ttk.Label(rowp, text=\" ~ \").pack(side=LEFT)\n ttk.Spinbox(\n rowp,\n from_=0,\n to=99999999,\n increment=1,\n textvariable=max_participants_var,\n width=10,\n ).pack(side=LEFT)\n ttk.Label(rowp, text=\"(填0表示不限制)\").pack(side=LEFT)\n\n row2 = ttk.Frame(cfg_box)\n row2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row2, text=\"倒计时小于(秒)时不参与:\").pack(side=LEFT)\n ttk.Spinbox(\n row2, from_=0, to=300, increment=1, textvariable=skip_lt_seconds_var, width=6\n ).pack(side=LEFT)\n ttk.Label(row2, text=\"(剩余时间太短,不参与)\").pack(side=LEFT, padx=(6, 0))\n\n row3 = ttk.Frame(cfg_box)\n row3.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n row3, text=\"自动加入粉丝团(谨慎:可能消耗钻石)\", variable=auto_join_var\n ).pack(side=LEFT)\n\n row4 = ttk.Frame(cfg_box)\n row4.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(row4, text=\"粉丝团失败策略:\").pack(side=LEFT)\n ttk.Combobox(\n row4,\n textvariable=fansclub_action_var,\n values=[\"stay\", \"switch\"],\n width=10,\n state=\"readonly\",\n ).pack(side=LEFT)\n ttk.Label(row4, text=\"(stay=停留,switch=切换直播间)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 标签页3:高价值预约\n reservation_tab_left = ttk.Frame(left_notebook)\n left_notebook.add(reservation_tab_left, text=\"高价值预约\")\n\n reservation_box = ttk.LabelFrame(reservation_tab_left, text=\"高价值福袋预约参与\")\n reservation_box.pack(fill=X, padx=10, pady=(10, 10))\n\n # 预约启用开关\n res_r0 = ttk.Frame(reservation_box)\n res_r0.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Checkbutton(\n res_r0, text=\"启用预约(价值≥阈值)\", variable=high_value_fudai_enabled_var\n ).pack(side=LEFT)\n\n # 价值阈值和提前参与时间\n res_r1 = ttk.Frame(reservation_box)\n res_r1.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(res_r1, text=\"价值阈值(元):\").pack(side=LEFT)\n ttk.Spinbox(\n res_r1,\n from_=0,\n to=99999,\n increment=100,\n textvariable=high_value_fudai_threshold_yuan_var,\n width=10,\n ).pack(side=LEFT)\n ttk.Label(res_r1, text=\"提前参与(秒):\").pack(side=LEFT, padx=(20, 0))\n ttk.Spinbox(\n res_r1,\n from_=5,\n to=900,\n increment=10,\n textvariable=high_value_fudai_join_ahead_seconds_var,\n width=8,\n ).pack(side=LEFT)\n\n # 最多回退次数\n res_r2 = ttk.Frame(reservation_box)\n res_r2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(res_r2, text=\"最多回退直播间次数:\").pack(side=LEFT)\n ttk.Spinbox(\n res_r2,\n from_=0,\n to=300,\n increment=5,\n textvariable=high_value_fudai_max_swipe_back_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(res_r2, text=\"(0=不限制)\").pack(side=LEFT, padx=(6, 0))\n\n # 最多记录数量和完成后策略\n res_r3 = ttk.Frame(reservation_box)\n res_r3.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(res_r3, text=\"最多记录数量:\").pack(side=LEFT)\n ttk.Spinbox(\n res_r3,\n from_=1,\n to=50,\n increment=1,\n textvariable=high_value_fudai_max_reservations_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(res_r3, text=\"完成后策略:\").pack(side=LEFT, padx=(20, 0))\n ttk.Combobox(\n res_r3,\n textvariable=high_value_fudai_after_action_var,\n values=[\"continue\", \"stay\"],\n width=10,\n state=\"readonly\",\n ).pack(side=LEFT)\n ttk.Label(res_r3, text=\"(stay=停留,continue=继续)\").pack(side=LEFT, padx=(6, 0))\n\n # 高价值房间回访\n res_r4 = ttk.Frame(reservation_box)\n res_r4.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n res_r4, text=\"启用高价值房间回访\", variable=high_value_room_revisit_enabled_var\n ).pack(side=LEFT)\n ttk.Checkbutton(\n res_r4, text=\"仅当前运行\", variable=high_value_room_revisit_only_current_run_var\n ).pack(side=LEFT, padx=(20, 0))\n\n # 预约回退校验\n res_r5 = ttk.Frame(reservation_box)\n res_r5.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n res_r5, text=\"预约回退校验\", variable=reservation_back_verify_enabled_var\n ).pack(side=LEFT)\n\n # 回退滑延迟和预约抢占最小价值\n res_r6 = ttk.Frame(reservation_box)\n res_r6.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(res_r6, text=\"回退滑延迟(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n res_r6,\n from_=0.0,\n to=10.0,\n increment=0.1,\n textvariable=reservation_back_swipe_delay_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(res_r6, text=\"预约抢占最小价值(元):\").pack(side=LEFT, padx=(20, 0))\n ttk.Spinbox(\n res_r6,\n from_=0,\n to=99999,\n increment=100,\n textvariable=reservation_preempt_min_value_var,\n width=10,\n ).pack(side=LEFT)\n\n # 标签页4:养号设置\n yanghao_tab = ttk.Frame(left_notebook)\n left_notebook.add(yanghao_tab, text=\"养号设置\")\n\n yg_box = ttk.LabelFrame(yanghao_tab, text=\"推荐页养号(爱心/收藏/评论)\")\n yg_box.pack(fill=X, padx=10, pady=(10, 10))\n\n yg_switch = ttk.Frame(yg_box)\n yg_switch.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Checkbutton(\n yg_switch, text=\"养号总开关(关闭则跳过推荐页养号)\", variable=yg_enabled_var\n ).pack(side=LEFT)\n ttk.Checkbutton(\n yg_switch,\n text=\"启用养号动作(爱心/收藏/评论)\",\n variable=yg_actions_enabled_var,\n ).pack(side=LEFT, padx=(10, 0))\n\n yg0 = ttk.Frame(yg_box)\n yg0.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n yg0,\n text=\"逐步截图(调试用,生成 pic/*/latest.png)\",\n variable=yg_step_screenshot_var,\n ).pack(side=LEFT)\n\n yg_time = ttk.Frame(yg_box)\n yg_time.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(yg_time, text=\"养号时长(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n yg_time,\n from_=1,\n to=3600,\n increment=5,\n textvariable=yg_recommend_duration_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(yg_time, text=\"养号间隔(秒):\").pack(side=LEFT, padx=(12, 0))\n ttk.Spinbox(\n yg_time,\n from_=0,\n to=3600,\n increment=10,\n textvariable=yg_recommend_interval_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(yg_time, text=\"(0=每次触发都执行)\").pack(side=LEFT, padx=(6, 0))\n\n yg1 = ttk.Frame(yg_box)\n yg1.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(yg1, text=\"爱心概率:\").pack(side=LEFT)\n ttk.Spinbox(\n yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_like_prob_var, width=6\n ).pack(side=LEFT)\n ttk.Label(yg1, text=\"收藏概率:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_fav_prob_var, width=6\n ).pack(side=LEFT)\n ttk.Label(yg1, text=\"评论概率:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n yg1,\n from_=0.0,\n to=1.0,\n increment=0.05,\n textvariable=yg_comment_prob_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(yg1, text=\"(0~1)\").pack(side=LEFT, padx=(6, 0))\n\n yg2 = ttk.Frame(yg_box)\n yg2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(yg2, text=\"图标ROI大小(px):\").pack(side=LEFT)\n ttk.Spinbox(\n yg2, from_=80, to=600, increment=10, textvariable=yg_icon_roi_size_var, width=6\n ).pack(side=LEFT)\n ttk.Label(yg2, text=\"匹配阈值:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n yg2,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=yg_icon_match_threshold_var,\n width=6,\n ).pack(side=LEFT)\n\n yg_texts = ttk.Frame(yg_box)\n yg_texts.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))\n ttk.Label(yg_texts, text=\"评论文案库(每行一条):\").pack(anchor=\"w\")\n yg_comment_texts = ScrolledText(yg_texts, height=4)\n yg_comment_texts.pack(fill=X, pady=(0, 6))\n yg_kw = ttk.Frame(yg_texts)\n yg_kw.pack(fill=BOTH, expand=True)\n ttk.Label(yg_kw, text=\"爱心关键词(每行一条):\").pack(anchor=\"w\")\n yg_like_keywords_text = ScrolledText(yg_kw, height=3)\n yg_like_keywords_text.pack(fill=X, pady=(0, 6))\n ttk.Label(yg_kw, text=\"收藏关键词(每行一条):\").pack(anchor=\"w\")\n yg_fav_keywords_text = ScrolledText(yg_kw, height=3)\n yg_fav_keywords_text.pack(fill=X)\n\n quiet_box = ttk.LabelFrame(yanghao_tab, text=\"定时禁抢(仅养号)\")\n quiet_box.pack(fill=X, padx=10, pady=(0, 10))\n quiet_r0 = ttk.Frame(quiet_box)\n quiet_r0.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Checkbutton(\n quiet_r0, text=\"启用定时禁抢\", variable=fudai_quiet_hours_enabled_var\n ).pack(side=LEFT)\n quiet_r1 = ttk.Frame(quiet_box)\n quiet_r1.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(quiet_r1, text=\"开始小时:\").pack(side=LEFT)\n ttk.Spinbox(\n quiet_r1, from_=0, to=23, textvariable=fudai_quiet_start_hour_var, width=6\n ).pack(side=LEFT)\n ttk.Label(quiet_r1, text=\"结束小时:\").pack(side=LEFT, padx=(12, 0))\n ttk.Spinbox(\n quiet_r1, from_=0, to=23, textvariable=fudai_quiet_end_hour_var, width=6\n ).pack(side=LEFT)\n\n # 标签页5:调试参数\n debug_tab = ttk.Frame(left_notebook)\n left_notebook.add(debug_tab, text=\"调试参数\")\n\n # 调试图像\n debug_captures_box = ttk.LabelFrame(debug_tab, text=\"调试图像\")\n debug_captures_box.pack(fill=X, padx=10, pady=(10, 10))\n\n debug_r0 = ttk.Frame(debug_captures_box)\n debug_r0.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Checkbutton(\n debug_r0,\n text=\"保存调试图像(OCR / 像素 / 模板等)\",\n variable=debug_captures_enabled_var,\n ).pack(side=LEFT)\n\n debug_cleanup_box = ttk.LabelFrame(debug_tab, text=\"调试图像清理\")\n debug_cleanup_box.pack(fill=X, padx=10, pady=(0, 10))\n\n debug_r1 = ttk.Frame(debug_cleanup_box)\n debug_r1.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Checkbutton(\n debug_r1, text=\"启用自动清理调试图像\", variable=debug_captures_auto_cleanup_var\n ).pack(side=LEFT)\n\n debug_r2 = ttk.Frame(debug_cleanup_box)\n debug_r2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(debug_r2, text=\"保留天数:\").pack(side=LEFT)\n ttk.Spinbox(\n debug_r2,\n from_=1,\n to=30,\n increment=1,\n textvariable=debug_captures_keep_days_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(debug_r2, text=\"最大文件数量:\").pack(side=LEFT, padx=(20, 0))\n ttk.Spinbox(\n debug_r2,\n from_=100,\n to=10000,\n increment=100,\n textvariable=debug_captures_max_files_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(debug_r2, text=\"(超过此数量自动清理)\").pack(side=LEFT, padx=(6, 0))\n\n # 找福袋参数\n fudai_find_box = ttk.LabelFrame(debug_tab, text=\"找福袋参数\")\n fudai_find_box.pack(fill=X, padx=10, pady=(0, 10))\n\n row4 = ttk.Frame(fudai_find_box)\n row4.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Label(row4, text=\"找福袋最大尝试次数:\").pack(side=LEFT)\n ttk.Spinbox(\n row4,\n from_=0,\n to=50,\n increment=1,\n textvariable=fudai_find_max_attempts_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4, text=\"(0=使用默认值)\").pack(side=LEFT, padx=(6, 0))\n\n row4b = ttk.Frame(fudai_find_box)\n row4b.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row4b, text=\"找福袋重试间隔(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n row4b,\n from_=0.1,\n to=3.0,\n increment=0.1,\n textvariable=fudai_icon_retry_delay_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4b, text=\" 最大等待时间(秒):\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n row4b,\n from_=0.0,\n to=30.0,\n increment=0.5,\n textvariable=fudai_icon_max_wait_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4b, text=\"(实际识别常见 4-6 秒)\").pack(side=LEFT, padx=(6, 0))\n\n row4d = ttk.Frame(fudai_find_box)\n row4d.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row4d, text=\"点击福袋后等待时间(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n row4d,\n from_=0.5,\n to=10.0,\n increment=0.1,\n textvariable=fudai_click_wait_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4d, text=\"(等待福袋详情页加载,默认2.0秒)\").pack(side=LEFT, padx=(6, 0))\n\n row4e = ttk.Frame(fudai_find_box)\n row4e.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row4e, text=\"切换直播间后等待时间(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n row4e,\n from_=0.0,\n to=30.0,\n increment=0.5,\n textvariable=switch_room_wait_after_stage_diag_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4e, text=\"(阶段检测后等待福袋加载,默认7.0秒)\").pack(side=LEFT, padx=(6, 0))\n\n row4c = ttk.Frame(fudai_find_box)\n row4c.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(row4c, text=\"直播间检测阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n row4c,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=live_room_match_threshold_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4c, text=\"(0.0~1.0,默认0.7,值越高越严格)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 阶段诊断时间参数(用于调试)\n diag_time_box = ttk.LabelFrame(debug_tab, text=\"阶段诊断时间参数\")\n diag_time_box.pack(fill=X, padx=10, pady=(0, 10))\n diag_time_r1 = ttk.Frame(diag_time_box)\n diag_time_r1.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Label(diag_time_r1, text=\"最大诊断时间(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r1,\n from_=1.0,\n to=60.0,\n increment=1.0,\n textvariable=stage_diag_max_time_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r1, text=\"每步最大耗时(秒):\").pack(side=LEFT, padx=(12, 0))\n ttk.Spinbox(\n diag_time_r1,\n from_=0.5,\n to=30.0,\n increment=0.5,\n textvariable=stage_diag_max_step_time_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r1, text=\"(用于调试,延长检测时间)\").pack(\n side=LEFT, padx=(6, 0)\n )\n diag_time_r2 = ttk.Frame(diag_time_box)\n diag_time_r2.pack(fill=X, padx=10, pady=(0, 6))\n ttk.Checkbutton(\n diag_time_r2, text=\"启用OCR模式1(二值化)\", variable=enable_ocr_mode1_var\n ).pack(side=LEFT)\n diag_time_r2b = ttk.Frame(diag_time_box)\n diag_time_r2b.pack(fill=X, padx=10, pady=(0, 6))\n ttk.Checkbutton(\n diag_time_r2b,\n text=\"启用福袋模板匹配\",\n variable=fudai_template_match_enabled_var,\n ).pack(side=LEFT)\n diag_time_r3 = ttk.Frame(diag_time_box)\n diag_time_r3.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(diag_time_r3, text=\"福袋模板匹配阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r3,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=fudai_template_match_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r3, text=\"(0.0-1.0,彩色匹配)\").pack(side=LEFT, padx=(6, 0))\n\n diag_time_r3b = ttk.Frame(diag_time_box)\n diag_time_r3b.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(diag_time_r3b, text=\"福袋详情页模板匹配阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r3b,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=fudai_detail_template_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r3b, text=\"(0.0-1.0,默认0.7,区域(398,894)-(658,1179))\").pack(side=LEFT, padx=(6, 0))\n\n diag_time_r4 = ttk.Frame(diag_time_box)\n diag_time_r4.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(diag_time_r4, text=\"开奖页红色占比阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r4,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=lucky_draw_red_ratio_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r4, text=\"(默认0.90,≥此占比判定开奖页)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 更多模板匹配阈值\n diag_time_r5 = ttk.Frame(diag_time_box)\n diag_time_r5.pack(fill=X, padx=10, pady=(0, 6))\n ttk.Label(diag_time_r5, text=\"优惠券模板匹配阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r5,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=coupon_template_match_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r5, text=\"(默认0.75,用于检测优惠券弹窗)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 像素检测阈值\n pixel_detect_box = ttk.LabelFrame(debug_tab, text=\"像素检测阈值\")\n pixel_detect_box.pack(fill=X, padx=10, pady=(0, 10))\n\n pixel_r1 = ttk.Frame(pixel_detect_box)\n pixel_r1.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Label(pixel_r1, text=\"参与按钮红色占比阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n pixel_r1,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=attend_button_red_ratio_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(pixel_r1, text=\"(默认0.25,用于检测参与按钮)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n pixel_r2 = ttk.Frame(pixel_detect_box)\n pixel_r2.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(pixel_r2, text=\"粉丝团加入红色占比阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n pixel_r2,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=fansclub_join_red_ratio_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(pixel_r2, text=\"(默认0.25,用于检测粉丝团加入按钮)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 标签页6:关键词\n keywords_tab = ttk.Frame(left_notebook)\n left_notebook.add(keywords_tab, text=\"关键词\")\n\n kw_box = ttk.LabelFrame(keywords_tab, text=\"关键词(每行一个,仅黑名单)\")\n kw_box.pack(fill=BOTH, expand=True, padx=10, pady=(10, 10))\n\n ttk.Label(kw_box, text=\"不想要 contains_not_want(黑名单)\").pack(\n anchor=\"w\", padx=10, pady=(10, 4)\n )\n not_want_text = ScrolledText(kw_box, height=8)\n not_want_text.pack(fill=X, padx=10, pady=(0, 10))\n\n def load_config_to_ui():\n nonlocal cfg\n cfg = read_config()\n needswitch_var.set(bool(cfg.get(\"needswitch\", True)))\n infinite_loop_var.set(bool(cfg.get(\"infinite_loop_enabled\", False)))\n wait_minutes_var.set(int(cfg.get(\"wait_minutes\", 5) or 5))\n yg_enabled_var.set(bool(cfg.get(\"yanghao_enabled\", True)))\n yg_actions_enabled_var.set(bool(cfg.get(\"yanghao_enable_actions\", True)))\n yg_recommend_duration_var.set(\n int(cfg.get(\"yanghao_recommend_duration_seconds\", 60) or 60)\n )\n yg_recommend_interval_var.set(\n int(cfg.get(\"yanghao_recommend_interval_seconds\", 0) or 0)\n )\n min_value_var.set(float(cfg.get(\"min_prize_value_yuan\", 0) or 0))\n min_participants_var.set(int(cfg.get(\"min_participants\", 0) or 0))\n max_participants_var.set(int(cfg.get(\"max_participants\", 0) or 0))\n skip_gt_seconds_var.set(\n int(cfg.get(\"skip_if_countdown_gt_seconds\", 900) or 900)\n )\n reset_after_swipes_enabled_var.set(\n bool(cfg.get(\"reset_after_swipes_enabled\", False))\n )\n reset_after_swipes_var.set(int(cfg.get(\"reset_after_swipes\", 10) or 10))\n auto_join_var.set(bool(cfg.get(\"auto_join_fansclub\", False)))\n fansclub_action_var.set(\n str(cfg.get(\"fansclub_fail_action\", \"stay\") or \"stay\").lower()\n )\n lucky_draw_red_ratio_threshold_var.set(\n float(cfg.get(\"lucky_draw_red_ratio_threshold\", 0.9) or 0.9)\n )\n y_var.set(int(cfg.get(\"y_pianyi\", 0) or 0))\n\n # Web端新增配置 - 高价值预约相关\n high_value_fudai_enabled_var.set(\n bool(cfg.get(\"high_value_fudai_enabled\", False))\n )\n high_value_fudai_threshold_yuan_var.set(\n float(cfg.get(\"high_value_fudai_threshold_yuan\", 1000) or 1000)\n )\n high_value_fudai_join_ahead_seconds_var.set(\n int(cfg.get(\"high_value_fudai_join_ahead_seconds\", 120) or 120)\n )\n high_value_fudai_max_swipe_back_var.set(\n int(cfg.get(\"high_value_fudai_max_swipe_back\", 60) or 60)\n )\n high_value_fudai_max_reservations_var.set(\n int(cfg.get(\"high_value_fudai_max_reservations\", 5) or 5)\n )\n high_value_fudai_after_action_var.set(\n str(cfg.get(\"high_value_fudai_after_action\", \"continue\") or \"continue\")\n )\n high_value_room_revisit_enabled_var.set(\n bool(cfg.get(\"high_value_room_revisit_enabled\", True))\n )\n high_value_room_revisit_only_current_run_var.set(\n bool(cfg.get(\"high_value_room_revisit_only_current_run\", False))\n )\n reservation_back_verify_enabled_var.set(\n bool(cfg.get(\"reservation_back_verify_enabled\", True))\n )\n reservation_back_swipe_delay_var.set(\n float(cfg.get(\"reservation_back_swipe_delay\", 0) or 0)\n )\n reservation_preempt_min_value_var.set(\n float(cfg.get(\"reservation_preempt_min_value\", 0) or 0)\n )\n fudai_find_max_attempts_var.set(int(cfg.get(\"fudai_find_max_attempts\", 0) or 0))\n fudai_icon_retry_delay_seconds_var.set(\n float(cfg.get(\"fudai_icon_retry_delay_seconds\", 0.6) or 0.6)\n )\n fudai_icon_max_wait_seconds_var.set(\n float(cfg.get(\"fudai_icon_max_wait_seconds\", 5.0) or 5.0)\n )\n fudai_click_wait_seconds_var.set(\n float(cfg.get(\"fudai_click_wait_seconds\", 2.0) or 2.0)\n )\n switch_room_wait_after_stage_diag_seconds_var.set(\n float(cfg.get(\"switch_room_wait_after_stage_diag_seconds\", 7.0) or 7.0)\n )\n live_room_match_threshold_var.set(\n float(cfg.get(\"live_room_match_threshold\", 0.8) or 0.8)\n )\n fudai_quiet_hours_enabled_var.set(\n bool(cfg.get(\"fudai_quiet_hours_enabled\", True))\n )\n fudai_quiet_start_hour_var.set(int(cfg.get(\"fudai_quiet_start_hour\", 2) or 2))\n fudai_quiet_end_hour_var.set(int(cfg.get(\"fudai_quiet_end_hour\", 7) or 7))\n stage_diag_max_time_var.set(float(cfg.get(\"stage_diag_max_time\", 10.0) or 10.0))\n stage_diag_max_step_time_var.set(\n float(cfg.get(\"stage_diag_max_step_time\", 2.0) or 2.0)\n )\n enable_ocr_mode1_var.set(bool(cfg.get(\"enable_ocr_mode1\", False)))\n fudai_template_match_enabled_var.set(\n bool(cfg.get(\"fudai_template_match_enabled\", False))\n )\n fudai_template_match_threshold_var.set(\n float(cfg.get(\"fudai_template_match_threshold\", 0.7) or 0.7)\n )\n fudai_detail_template_threshold_var.set(\n float(cfg.get(\"fudai_detail_template_threshold\", 0.7) or 0.7)\n )\n coupon_template_match_threshold_var.set(\n float(cfg.get(\"coupon_template_match_threshold\", 0.75) or 0.75)\n )\n attend_button_red_ratio_threshold_var.set(\n float(cfg.get(\"attend_button_red_ratio_threshold\", 0.25) or 0.25)\n )\n fansclub_join_red_ratio_threshold_var.set(\n float(cfg.get(\"fansclub_join_red_ratio_threshold\", 0.25) or 0.25)\n )\n skip_lt_seconds_var.set(int(cfg.get(\"skip_if_countdown_lt_seconds\", 5) or 5))\n\n # 调试图像清理配置\n debug_captures_config = cfg.get(\"debug_captures\", {})\n if isinstance(debug_captures_config, dict):\n debug_captures_enabled_var.set(\n bool(debug_captures_config.get(\"enabled\", False))\n )\n debug_captures_auto_cleanup_var.set(\n bool(debug_captures_config.get(\"auto_cleanup\", True))\n )\n debug_captures_keep_days_var.set(\n int(debug_captures_config.get(\"keep_days\", 7) or 7)\n )\n debug_captures_max_files_var.set(\n int(debug_captures_config.get(\"max_files\", 2000) or 2000)\n )\n else:\n debug_captures_auto_cleanup_var.set(True)\n debug_captures_keep_days_var.set(7)\n debug_captures_max_files_var.set(2000)\n\n yg_like_prob_var.set(float(cfg.get(\"yanghao_like_prob\", 0.0) or 0.0))\n yg_fav_prob_var.set(float(cfg.get(\"yanghao_fav_prob\", 0.0) or 0.0))\n yg_comment_prob_var.set(float(cfg.get(\"yanghao_comment_prob\", 0.0) or 0.0))\n yg_icon_roi_size_var.set(int(cfg.get(\"yanghao_icon_roi_size\", 240) or 240))\n yg_icon_match_threshold_var.set(\n float(cfg.get(\"yanghao_icon_match_threshold\", 0.72) or 0.72)\n )\n yg_step_screenshot_var.set(bool(cfg.get(\"yanghao_step_screenshot\", False)))\n yg_like_roi_offset_x_var.set(int(cfg.get(\"yanghao_like_roi_offset_x\", 0) or 0))\n yg_like_roi_offset_y_var.set(int(cfg.get(\"yanghao_like_roi_offset_y\", 0) or 0))\n yg_fav_roi_offset_x_var.set(int(cfg.get(\"yanghao_fav_roi_offset_x\", 0) or 0))\n yg_fav_roi_offset_y_var.set(int(cfg.get(\"yanghao_fav_roi_offset_y\", 0) or 0))\n yg_like_icon_x_var.set(int(cfg.get(\"yanghao_like_icon_x\", 0) or 0))\n yg_like_icon_y_var.set(int(cfg.get(\"yanghao_like_icon_y\", 0) or 0))\n yg_fav_icon_x_var.set(int(cfg.get(\"yanghao_fav_icon_x\", 0) or 0))\n yg_fav_icon_y_var.set(int(cfg.get(\"yanghao_fav_icon_y\", 0) or 0))\n yg_like_template_path_var.set(\n str(\n cfg.get(\"yanghao_like_template_path\", \"assets/like.png\")\n or \"assets/like.png\"\n )\n )\n yg_fav_template_path_var.set(\n str(\n cfg.get(\"yanghao_fav_template_path\", \"assets/fav.png\")\n or \"assets/fav.png\"\n )\n )\n yg_after_dwell_direction_var.set(\n str(cfg.get(\"yanghao_after_dwell_swipe_direction\", \"up\") or \"up\")\n )\n yg_after_dwell_distance_var.set(\n int(cfg.get(\"yanghao_after_dwell_swipe_distance_px\", 900) or 900)\n )\n yg_comment_btn_x_var.set(int(cfg.get(\"yanghao_comment_btn_x\", 0) or 0))\n yg_comment_btn_y_var.set(int(cfg.get(\"yanghao_comment_btn_y\", 0) or 0))\n yg_comment_input_x_var.set(int(cfg.get(\"yanghao_comment_input_x\", 0) or 0))\n yg_comment_input_y_var.set(int(cfg.get(\"yanghao_comment_input_y\", 0) or 0))\n yg_comment_send_x_var.set(int(cfg.get(\"yanghao_comment_send_x\", 0) or 0))\n yg_comment_send_y_var.set(int(cfg.get(\"yanghao_comment_send_y\", 0) or 0))\n yg_comment_close_x_var.set(int(cfg.get(\"yanghao_comment_close_x\", 0) or 0))\n yg_comment_close_y_var.set(int(cfg.get(\"yanghao_comment_close_y\", 0) or 0))\n\n # 仅保留黑名单 contains_not_want\n not_want = cfg.get(\"contains_not_want\", []) or []\n yg_comment_texts_list = cfg.get(\"yanghao_comment_texts\", []) or []\n yg_like_keywords_list = cfg.get(\"yanghao_like_keywords\", []) or []\n yg_fav_keywords_list = cfg.get(\"yanghao_fav_keywords\", []) or []\n not_want_text.delete(\"1.0\", \"end\")\n not_want_text.insert(\"1.0\", \"\\n\".join(not_want))\n yg_comment_texts.delete(\"1.0\", \"end\")\n yg_comment_texts.insert(\"1.0\", \"\\n\".join(yg_comment_texts_list))\n yg_like_keywords_text.delete(\"1.0\", \"end\")\n yg_like_keywords_text.insert(\"1.0\", \"\\n\".join(yg_like_keywords_list))\n yg_fav_keywords_text.delete(\"1.0\", \"end\")\n yg_fav_keywords_text.insert(\"1.0\", \"\\n\".join(yg_fav_keywords_list))\n\n def save_ui_to_config():\n # 仅保存黑名单 contains_not_want\n not_want_lines = [\n x.strip() for x in not_want_text.get(\"1.0\", \"end\").splitlines() if x.strip()\n ]\n yg_comment_text_lines = [\n x.strip()\n for x in yg_comment_texts.get(\"1.0\", \"end\").splitlines()\n if x.strip()\n ]\n yg_like_kw_lines = [\n x.strip()\n for x in yg_like_keywords_text.get(\"1.0\", \"end\").splitlines()\n if x.strip()\n ]\n yg_fav_kw_lines = [\n x.strip()\n for x in yg_fav_keywords_text.get(\"1.0\", \"end\").splitlines()\n if x.strip()\n ]\n\n cfg2 = read_config()\n cfg2[\"needswitch\"] = bool(needswitch_var.get())\n cfg2[\"infinite_loop_enabled\"] = bool(infinite_loop_var.get())\n cfg2[\"wait_minutes\"] = int(wait_minutes_var.get() or 5)\n cfg2[\"y_pianyi\"] = int(y_var.get() or 0)\n cfg2[\"contains_not_want\"] = not_want_lines\n cfg2[\"min_prize_value_yuan\"] = float(min_value_var.get() or 0)\n cfg2[\"min_participants\"] = int(min_participants_var.get() or 0)\n cfg2[\"max_participants\"] = int(max_participants_var.get() or 0)\n cfg2[\"skip_if_countdown_gt_seconds\"] = int(skip_gt_seconds_var.get() or 900)\n cfg2[\"reset_after_swipes_enabled\"] = bool(reset_after_swipes_enabled_var.get())\n cfg2[\"reset_after_swipes\"] = int(reset_after_swipes_var.get() or 10)\n cfg2[\"auto_join_fansclub\"] = bool(auto_join_var.get())\n cfg2[\"fansclub_fail_action\"] = str(fansclub_action_var.get() or \"stay\").lower()\n cfg2[\"lucky_draw_red_ratio_threshold\"] = float(\n lucky_draw_red_ratio_threshold_var.get() or 0.9\n )\n\n # Web端新增配置 - 高价值预约相关\n cfg2[\"high_value_fudai_enabled\"] = bool(high_value_fudai_enabled_var.get())\n cfg2[\"high_value_fudai_threshold_yuan\"] = float(\n high_value_fudai_threshold_yuan_var.get() or 1000\n )\n cfg2[\"high_value_fudai_join_ahead_seconds\"] = int(\n high_value_fudai_join_ahead_seconds_var.get() or 120\n )\n cfg2[\"high_value_fudai_max_swipe_back\"] = int(\n high_value_fudai_max_swipe_back_var.get() or 60\n )\n cfg2[\"high_value_fudai_max_reservations\"] = int(\n high_value_fudai_max_reservations_var.get() or 5\n )\n cfg2[\"high_value_fudai_after_action\"] = str(\n high_value_fudai_after_action_var.get() or \"continue\"\n ).lower()\n cfg2[\"high_value_room_revisit_enabled\"] = bool(\n high_value_room_revisit_enabled_var.get()\n )\n cfg2[\"high_value_room_revisit_only_current_run\"] = bool(\n high_value_room_revisit_only_current_run_var.get()\n )\n cfg2[\"reservation_back_verify_enabled\"] = bool(\n reservation_back_verify_enabled_var.get()\n )\n cfg2[\"reservation_back_swipe_delay\"] = float(\n reservation_back_swipe_delay_var.get() or 0\n )\n cfg2[\"reservation_preempt_min_value\"] = float(\n reservation_preempt_min_value_var.get() or 0\n )\n cfg2[\"fudai_find_max_attempts\"] = int(fudai_find_max_attempts_var.get() or 0)\n cfg2[\"fudai_icon_retry_delay_seconds\"] = float(\n fudai_icon_retry_delay_seconds_var.get() or 0.6\n )\n cfg2[\"fudai_icon_max_wait_seconds\"] = float(\n fudai_icon_max_wait_seconds_var.get() or 5.0\n )\n cfg2[\"fudai_click_wait_seconds\"] = float(\n fudai_click_wait_seconds_var.get() or 2.0\n )\n cfg2[\"switch_room_wait_after_stage_diag_seconds\"] = float(\n switch_room_wait_after_stage_diag_seconds_var.get() or 7.0\n )\n cfg2[\"live_room_match_threshold\"] = float(\n live_room_match_threshold_var.get() or 0.8\n )\n cfg2[\"fudai_quiet_hours_enabled\"] = bool(fudai_quiet_hours_enabled_var.get())\n cfg2[\"fudai_quiet_start_hour\"] = int(fudai_quiet_start_hour_var.get() or 0)\n cfg2[\"fudai_quiet_end_hour\"] = int(fudai_quiet_end_hour_var.get() or 0)\n cfg2[\"stage_diag_max_time\"] = float(stage_diag_max_time_var.get() or 10.0)\n cfg2[\"stage_diag_max_step_time\"] = float(\n stage_diag_max_step_time_var.get() or 2.0\n )\n cfg2[\"enable_ocr_mode1\"] = bool(enable_ocr_mode1_var.get())\n cfg2[\"fudai_template_match_enabled\"] = bool(\n fudai_template_match_enabled_var.get()\n )\n cfg2[\"fudai_template_match_threshold\"] = float(\n fudai_template_match_threshold_var.get() or 0.7\n )\n cfg2[\"fudai_detail_template_threshold\"] = float(\n fudai_detail_template_threshold_var.get() or 0.7\n )\n cfg2[\"coupon_template_match_threshold\"] = float(\n coupon_template_match_threshold_var.get() or 0.75\n )\n cfg2[\"attend_button_red_ratio_threshold\"] = float(\n attend_button_red_ratio_threshold_var.get() or 0.25\n )\n cfg2[\"fansclub_join_red_ratio_threshold\"] = float(\n fansclub_join_red_ratio_threshold_var.get() or 0.25\n )\n cfg2[\"skip_if_countdown_lt_seconds\"] = int(skip_lt_seconds_var.get() or 5)\n\n # 调试图像清理配置\n if \"debug_captures\" not in cfg2 or not isinstance(cfg2[\"debug_captures\"], dict):\n cfg2[\"debug_captures\"] = {}\n cfg2[\"debug_captures\"][\"enabled\"] = bool(\n debug_captures_enabled_var.get()\n )\n cfg2[\"debug_captures\"][\"auto_cleanup\"] = bool(\n debug_captures_auto_cleanup_var.get()\n )\n cfg2[\"debug_captures\"][\"keep_days\"] = int(\n debug_captures_keep_days_var.get() or 7\n )\n cfg2[\"debug_captures\"][\"max_files\"] = int(\n debug_captures_max_files_var.get() or 2000\n )\n\n cfg2[\"yanghao_enabled\"] = bool(yg_enabled_var.get())\n cfg2[\"yanghao_enable_actions\"] = bool(yg_actions_enabled_var.get())\n cfg2[\"yanghao_recommend_duration_seconds\"] = int(\n yg_recommend_duration_var.get() or 60\n )\n cfg2[\"yanghao_recommend_interval_seconds\"] = int(\n yg_recommend_interval_var.get() or 0\n )\n cfg2[\"yanghao_like_prob\"] = float(yg_like_prob_var.get() or 0.0)\n cfg2[\"yanghao_fav_prob\"] = float(yg_fav_prob_var.get() or 0.0)\n cfg2[\"yanghao_comment_prob\"] = float(yg_comment_prob_var.get() or 0.0)\n cfg2[\"yanghao_icon_roi_size\"] = int(yg_icon_roi_size_var.get() or 240)\n cfg2[\"yanghao_icon_match_threshold\"] = float(\n yg_icon_match_threshold_var.get() or 0.72\n )\n cfg2[\"yanghao_step_screenshot\"] = bool(yg_step_screenshot_var.get())\n cfg2[\"yanghao_like_roi_offset_x\"] = int(yg_like_roi_offset_x_var.get() or 0)\n cfg2[\"yanghao_like_roi_offset_y\"] = int(yg_like_roi_offset_y_var.get() or 0)\n cfg2[\"yanghao_fav_roi_offset_x\"] = int(yg_fav_roi_offset_x_var.get() or 0)\n cfg2[\"yanghao_fav_roi_offset_y\"] = int(yg_fav_roi_offset_y_var.get() or 0)\n cfg2[\"yanghao_like_icon_x\"] = int(yg_like_icon_x_var.get() or 0)\n cfg2[\"yanghao_like_icon_y\"] = int(yg_like_icon_y_var.get() or 0)\n cfg2[\"yanghao_fav_icon_x\"] = int(yg_fav_icon_x_var.get() or 0)\n cfg2[\"yanghao_fav_icon_y\"] = int(yg_fav_icon_y_var.get() or 0)\n cfg2[\"yanghao_like_template_path\"] = str(\n yg_like_template_path_var.get() or \"assets/like.png\"\n )\n cfg2[\"yanghao_fav_template_path\"] = str(\n yg_fav_template_path_var.get() or \"assets/fav.png\"\n )\n cfg2[\"yanghao_after_dwell_swipe_direction\"] = str(\n yg_after_dwell_direction_var.get() or \"up\"\n )\n cfg2[\"yanghao_after_dwell_swipe_distance_px\"] = int(\n yg_after_dwell_distance_var.get() or 900\n )\n cfg2[\"yanghao_comment_btn_x\"] = int(yg_comment_btn_x_var.get() or 0)\n cfg2[\"yanghao_comment_btn_y\"] = int(yg_comment_btn_y_var.get() or 0)\n cfg2[\"yanghao_comment_input_x\"] = int(yg_comment_input_x_var.get() or 0)\n cfg2[\"yanghao_comment_input_y\"] = int(yg_comment_input_y_var.get() or 0)\n cfg2[\"yanghao_comment_send_x\"] = int(yg_comment_send_x_var.get() or 0)\n cfg2[\"yanghao_comment_send_y\"] = int(yg_comment_send_y_var.get() or 0)\n cfg2[\"yanghao_comment_close_x\"] = int(yg_comment_close_x_var.get() or 0)\n cfg2[\"yanghao_comment_close_y\"] = int(yg_comment_close_y_var.get() or 0)\n cfg2[\"yanghao_comment_texts\"] = yg_comment_text_lines\n cfg2[\"yanghao_like_keywords\"] = yg_like_kw_lines\n cfg2[\"yanghao_fav_keywords\"] = yg_fav_kw_lines\n write_config(cfg2)\n on_line(\"[配置] 已保存到 config.json\")\n\n load_config_to_ui()\n\n # 顶部常驻按钮区域(与设备选择同一行,不随左侧滚动)\n top_btns = ttk.Frame(top)\n top_btns.pack(side=RIGHT, padx=(20, 0))\n ttk.Button(top_btns, text=\"保存配置\", command=save_ui_to_config).pack(\n side=LEFT, padx=(0, 8)\n )\n # 截图+OCR 按钮也放在顶部,方便随时使用\n # 具体回调在后文定义,这里先占位,通过 lambda 延迟绑定\n screenshot_button_var = {\"command\": None}\n\n def _bind_screenshot_button(btn):\n # 在 do_screenshot 定义后调用,将真正的 command 绑定到按钮\n screenshot_button_var[\"button\"] = btn\n\n screenshot_btn = ttk.Button(top_btns, text=\"截图+OCR\")\n screenshot_btn.pack(side=LEFT, padx=(0, 8))\n _bind_screenshot_button(screenshot_btn)\n\n # OCR区域配置:定义所有需要识别的区域(坐标基于1080x2400基准)\n OCR_REGIONS = [\n # (区域名称, (x1, y1, x2, y2), 描述)\n (\"福袋内容\", (390, 1240, 980, 1470), \"福袋内容详情\"),\n (\"福袋倒计时\", (390, 1470, 980, 1580), \"福袋倒计时\"),\n (\"福袋价值\", (390, 1460, 1000, 1580), \"奖品价值/价格\"),\n (\"抽奖结果\", (380, 660, 720, 755), \"抽奖结果弹窗\"),\n (\"推荐页标签栏\", (400, 140, 900, 200), \"推荐/关注/直播标签\"),\n (\"推荐页标签栏快速检测\", (400, 140, 900, 200), \"推荐页快速检测\"),\n (\"参与按钮\", (306, 2030, 780, 2110), \"参与福袋抽奖按钮\"),\n (\"无奖励确认\", (340, 1195, 740, 1355), \"无奖励确认弹窗\"),\n (\"奖励通知确认\", (370, 1350, 680, 1440), \"奖励通知确认\"),\n (\"订单确认\", (370, 120, 700, 220), \"订单确认页面\"),\n (\"关注列表标签\", (658, 147, 765, 194), \"关注列表标签\"),\n (\"直播列表标签\", (400, 140, 900, 200), \"直播列表标签\"),\n (\"直播广场\", (400, 140, 900, 200), \"直播广场标题\"),\n (\"直播间标题_中\", (400, 140, 900, 200), \"直播间标题中部\"),\n (\"诊断优惠券标题\", (60, 1260, 1020, 1480), \"优惠券弹窗标题\"),\n (\"诊断优惠券按钮\", (400, 1600, 680, 1700), \"优惠券按钮\"),\n (\"诊断购物红包\", (400, 1400, 900, 1600), \"购物红包弹窗\"),\n ]\n\n # 截图按钮\n def do_screenshot():\n device_id = device_var.get().strip()\n if not device_id:\n on_line(\"[截图] 请先选择设备\")\n return\n\n # 在后台线程中执行截图和OCR识别,避免阻塞GUI\n def screenshot_thread():\n try:\n from Underlying_Operations import underlying_operations\n from PIL import Image\n import os\n\n # 使用 root.after 在主线程中更新日志\n def log_msg(msg: str) -> Callable[[], None]:\n def wrapper() -> None:\n on_line(msg)\n\n return wrapper\n\n root.after(0, log_msg(\"[截图] 正在截图...\")) # type: ignore[arg-type]\n ops = underlying_operations()\n result = ops.get_screenshot(device_id)\n if not result:\n root.after(0, log_msg(\"[截图] 截图失败\")) # type: ignore[arg-type]\n return\n\n root.after(0, log_msg(\"[截图] 截图成功,已保存到 pic/screenshot.png\")) # type: ignore[arg-type]\n\n # 读取截图以获取实际尺寸\n screenshot_path = os.path.join(\n os.path.dirname(__file__), \"pic\", \"screenshot.png\"\n )\n if not os.path.exists(screenshot_path):\n root.after(0, log_msg(\"[OCR] 截图文件不存在\")) # type: ignore[arg-type]\n return\n\n try:\n img = Image.open(screenshot_path)\n img.load() # Force load to catch truncated files early\n img_width, img_height = img.size\n # 计算缩放比例(基于1080x2400基准)\n scale_x = img_width / 1080.0\n scale_y = img_height / 2400.0\n except (OSError, IOError, SyntaxError) as e:\n # Handle truncated image files\n root.after(0, log_msg(f\"图片文件损坏或截断: {e}\")) # type: ignore[arg-type]\n return\n except Exception as e:\n root.after(0, log_msg(f\"[OCR] 读取截图失败: {e}\")) # type: ignore[arg-type]\n return\n\n # 获取Y偏移\n y_offset = int(y_var.get() or 0)\n\n # 执行所有OCR区域的识别\n ocr_results = []\n total_regions = len(OCR_REGIONS)\n root.after(0, log_msg(f\"[OCR] 开始识别 {total_regions} 个区域...\")) # type: ignore[arg-type]\n\n for idx, (region_name, (x1, y1, x2, y2), desc) in enumerate(\n OCR_REGIONS, 1\n ):\n try:\n # 缩放坐标到实际截图尺寸\n actual_x1 = int(x1 * scale_x)\n actual_y1 = int(y1 * scale_y) + y_offset\n actual_x2 = int(x2 * scale_x)\n actual_y2 = int(y2 * scale_y) + y_offset\n\n # 确保坐标在图片范围内\n actual_x1 = max(0, min(actual_x1, img_width))\n actual_y1 = max(0, min(actual_y1, img_height))\n actual_x2 = max(0, min(actual_x2, img_width))\n actual_y2 = max(0, min(actual_y2, img_height))\n\n if actual_x1 >= actual_x2 or actual_y1 >= actual_y2:\n root.after(0, log_msg(f\"[OCR] {region_name}: 坐标无效,跳过\")) # type: ignore[arg-type]\n continue\n\n # 截取区域\n cut_result = ops.cut_pic(\n (actual_x1, actual_y1),\n (actual_x2, actual_y2),\n \"\",\n region_name,\n )\n if not cut_result:\n root.after(0, log_msg(f\"[OCR] {region_name}: 截图失败\")) # type: ignore[arg-type]\n ocr_results.append((region_name, desc, \"\", \"截图失败\"))\n continue\n\n # OCR识别(先尝试模式0,如果为空再尝试模式1)\n text_result = \"\"\n ocr_mode = 0\n for mode in [0, 1]:\n try:\n text = str(\n ops.analyse_pic_word(region_name, mode) or \"\"\n ).strip()\n if text:\n text_result = text\n ocr_mode = mode\n break\n except Exception:\n continue\n\n ocr_results.append(\n (region_name, desc, text_result, f\"模式{ocr_mode}\")\n )\n status_msg = f\"[OCR] ({idx}/{total_regions}) {region_name}: {text_result[:50] if text_result else '(空)'}\"\n root.after(0, log_msg(status_msg)) # type: ignore[arg-type]\n\n except Exception as e:\n error_msg = f\"[OCR] {region_name}: 异常 - {e}\"\n root.after(0, log_msg(error_msg)) # type: ignore[arg-type]\n ocr_results.append((region_name, desc, \"\", f\"异常: {e}\"))\n\n # 更新OCR结果标签页\n def update_ocr_wrapper() -> None:\n update_ocr_results(ocr_results)\n\n root.after(0, update_ocr_wrapper) # type: ignore[arg-type]\n root.after(0, log_msg(f\"[OCR] 完成!共识别 {len(ocr_results)} 个区域\")) # type: ignore[arg-type]\n\n # 刷新截图预览(如果当前显示的是 screenshot.png)\n def refresh_if_screenshot() -> None:\n if image_var.get() == \"screenshot.png\":\n refresh_preview()\n\n root.after(0, refresh_if_screenshot) # type: ignore[arg-type]\n\n except Exception as e:\n import traceback\n\n error_detail = traceback.format_exc()\n root.after(0, log_msg(f\"[截图] 截图异常: {e}\\n{error_detail}\")) # type: ignore[arg-type]\n\n thread = threading.Thread(target=screenshot_thread, daemon=True)\n thread.start()\n\n # 将顶部“截图+OCR”按钮的回调绑定到 do_screenshot\n try:\n btn = screenshot_button_var.get(\"button\")\n if btn is not None:\n btn.configure(command=do_screenshot)\n except Exception:\n pass\n\n # 右侧:操作按钮区域(先创建,放在底部)\n actions = ttk.Frame(right)\n\n # 右侧:Notebook(日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间)\n notebook = ttk.Notebook(right)\n\n log_tab = ttk.Frame(notebook)\n preview_tab = ttk.Frame(notebook)\n stats_tab = ttk.Frame(notebook)\n reservation_tab = ttk.Frame(notebook)\n high_value_tab = ttk.Frame(notebook)\n actions_log_tab = ttk.Frame(notebook)\n ocr_results_tab = ttk.Frame(notebook)\n notebook.add(log_tab, text=\"运行日志\")\n notebook.add(preview_tab, text=\"截图预览\")\n notebook.add(stats_tab, text=\"统计信息\")\n notebook.add(reservation_tab, text=\"预约队列\")\n notebook.add(high_value_tab, text=\"高价值房间\")\n notebook.add(actions_log_tab, text=\"行为日志\")\n notebook.add(ocr_results_tab, text=\"OCR结果\")\n\n # 日志区\n log_box = ttk.Frame(log_tab)\n log_box.pack(fill=BOTH, expand=True)\n \n # 搜索工具栏\n log_search_frame = ttk.Frame(log_box)\n log_search_frame.pack(fill=X, padx=10, pady=(10, 5))\n \n log_search_var = tk.StringVar(value=\"\")\n log_search_entry = ttk.Entry(log_search_frame, textvariable=log_search_var, width=20)\n log_search_entry.pack(side=LEFT, padx=(0, 5))\n \n log_search_matches = [] # 存储所有匹配的位置\n log_current_match_index = -1 # 当前匹配的索引\n \n def search_in_log_text(direction=1):\n \"\"\"在运行日志中搜索文本\"\"\"\n nonlocal log_search_matches, log_current_match_index\n \n search_text = log_search_var.get().strip()\n if not search_text:\n # 清除高亮\n log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n log_search_matches = []\n log_current_match_index = -1\n return\n \n # 获取所有文本\n content = log_text.get(\"1.0\", \"end-1c\")\n if not content:\n return\n \n # 清除之前的高亮\n log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n \n # 配置高亮样式\n log_text.tag_config(\"search_highlight\", background=\"yellow\")\n log_text.tag_config(\"search_current\", background=\"orange\")\n \n # 查找所有匹配项(不区分大小写)\n log_search_matches = []\n start_pos = 0 # 使用整数索引\n search_text_lower = search_text.lower()\n content_lower = content.lower()\n \n while True:\n # 在内容中查找\n pos = content_lower.find(search_text_lower, start_pos)\n if pos == -1:\n break\n \n # 计算行号和列号\n line_start = content[:pos].rfind(\"\\n\") + 1\n line_num = content[:pos].count(\"\\n\") + 1\n col_num = pos - line_start\n \n # 转换为 tkinter 索引格式\n start_index = f\"{line_num}.{col_num}\"\n end_index = f\"{line_num}.{col_num + len(search_text)}\"\n \n log_search_matches.append((start_index, end_index))\n start_pos = pos + 1\n \n if not log_search_matches:\n # 没有找到匹配项\n log_current_match_index = -1\n return\n \n # 高亮所有匹配项\n for start_idx, end_idx in log_search_matches:\n log_text.tag_add(\"search_highlight\", start_idx, end_idx)\n \n # 根据方向更新当前匹配索引\n if direction == 1: # 下一个\n log_current_match_index = (log_current_match_index + 1) % len(log_search_matches)\n else: # 上一个\n log_current_match_index = (log_current_match_index - 1) % len(log_search_matches)\n \n # 高亮当前匹配项并滚动到该位置\n if log_current_match_index >= 0:\n start_idx, end_idx = log_search_matches[log_current_match_index]\n log_text.tag_add(\"search_current\", start_idx, end_idx)\n log_text.see(start_idx)\n log_text.mark_set(\"insert\", start_idx)\n \n def search_next_in_log():\n \"\"\"搜索下一个\"\"\"\n search_in_log_text(1)\n \n def search_prev_in_log():\n \"\"\"搜索上一个\"\"\"\n search_in_log_text(-1)\n \n def clear_search_in_log():\n \"\"\"清除搜索高亮\"\"\"\n nonlocal log_search_matches, log_current_match_index\n log_search_var.set(\"\")\n log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n log_search_matches = []\n log_current_match_index = -1\n \n # 绑定回车键搜索\n def on_log_search_entry_key(event):\n if event.keysym == \"Return\":\n search_next_in_log()\n \n log_search_entry.bind(\"<KeyPress>\", on_log_search_entry_key)\n \n ttk.Button(log_search_frame, text=\"搜索\", command=search_next_in_log).pack(side=LEFT, padx=(0, 2))\n ttk.Button(log_search_frame, text=\"上一个\", command=search_prev_in_log).pack(side=LEFT, padx=(0, 2))\n ttk.Button(log_search_frame, text=\"下一个\", command=search_next_in_log).pack(side=LEFT, padx=(0, 2))\n ttk.Button(log_search_frame, text=\"清除\", command=clear_search_in_log).pack(side=LEFT, padx=(0, 5))\n \n log_text = ScrolledText(log_box)\n try:\n log_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n log_text.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))\n\n # 截图预览\n preview_top = ttk.Frame(preview_tab)\n preview_top.pack(fill=X, padx=10, pady=10)\n\n images_dir = os.path.join(os.path.dirname(__file__), \"pic\")\n\n def scan_image_files():\n \"\"\"扫描pic文件夹及其子文件夹中的所有图片文件\"\"\"\n image_files = []\n if os.path.exists(images_dir):\n for root, dirs, files in os.walk(images_dir):\n for file in files:\n if file.lower().endswith(\n (\".png\", \".jpg\", \".jpeg\", \".bmp\", \".webp\", \".gif\")\n ):\n # 获取相对路径\n rel_path = os.path.relpath(os.path.join(root, file), images_dir)\n # 统一使用正斜杠(Windows和Unix都支持)\n rel_path = rel_path.replace(\"\\\\\", \"/\")\n image_files.append(rel_path)\n # 按文件名排序\n image_files.sort(key=lambda x: x.lower())\n return image_files\n\n image_var = tk.StringVar(value=\"\")\n\n ttk.Label(preview_top, text=\"选择图片:\").pack(side=LEFT)\n # 允许手工输入子路径(例如 start/latest.png),方便查看逐步截图\n image_combo = ttk.Combobox(\n preview_top, textvariable=image_var, width=30, state=\"normal\"\n )\n image_combo.pack(side=LEFT, padx=(0, 10))\n\n def update_image_list(refresh_after=True):\n \"\"\"更新图片列表\"\"\"\n new_list = scan_image_files()\n image_combo[\"values\"] = new_list\n current_value = image_var.get()\n # 如果当前值不在新列表中,或列表为空,选择第一个\n if new_list:\n if not current_value or current_value not in new_list:\n image_var.set(new_list[0])\n else:\n image_var.set(\"\")\n on_line(f\"[预览] 扫描到 {len(new_list)} 个图片文件\")\n # 如果当前有选择的图片,刷新预览(如果refresh_after为True且refresh_preview已定义)\n if refresh_after and image_var.get():\n try:\n refresh_preview()\n except NameError:\n # refresh_preview还没定义,忽略\n pass\n\n # 先定义refresh_preview函数(即使它引用了后面的变量,函数定义本身是延迟执行的)\n def refresh_preview():\n name = image_var.get().strip()\n if not name:\n preview_status.set(\"请选择图片\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n # 处理相对路径(将正斜杠转换为系统路径分隔符)\n name_normalized = name.replace(\"/\", os.sep)\n path = os.path.join(images_dir, name_normalized)\n _load_and_fit_image(path)\n\n update_image_list(refresh_after=False) # 初始化时扫描一次,但不刷新预览\n\n preview_status = tk.StringVar(value=\"\")\n ttk.Label(preview_top, textvariable=preview_status).pack(side=RIGHT)\n\n preview_body = ttk.Frame(preview_tab)\n preview_body.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))\n\n image_label = ttk.Label(preview_body)\n image_label.pack(fill=BOTH, expand=True)\n _img_ref: dict[str, Any] = {\"photo\": None} # 防止 PhotoImage 被回收\n\n def _load_and_fit_image(img_path: str) -> None:\n if not os.path.exists(img_path):\n preview_status.set(f\"未找到:{os.path.basename(img_path)}\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n\n try:\n img = Image.open(img_path)\n img.load() # Force load to catch truncated files early\n img = img.convert(\"RGB\")\n except (OSError, IOError, SyntaxError) as e:\n # Handle truncated image files\n preview_status.set(f\"图片加载失败:{str(e)[:50]}\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n except Exception as e:\n preview_status.set(f\"图片加载错误:{str(e)[:50]}\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n\n # 获取预览区域的实际尺寸(如果窗口还未初始化,使用默认值)\n try:\n preview_body.update_idletasks() # 强制更新布局\n w = preview_body.winfo_width()\n h = preview_body.winfo_height()\n # 如果尺寸无效(窗口未初始化),使用默认值\n if w <= 1 or h <= 1:\n w, h = 900, 520\n except Exception:\n w, h = 900, 520\n\n max_w = max(300, w - 20)\n max_h = max(200, h - 20)\n try:\n resample = Image.Resampling.LANCZOS\n except AttributeError:\n # Fallback for older Pillow versions: LANCZOS constant value is 1\n resample = 1 # type: ignore[assignment]\n img.thumbnail((max_w, max_h), resample)\n photo: ImageTk.PhotoImage = ImageTk.PhotoImage(img)\n _img_ref[\"photo\"] = photo # type: ignore[assignment]\n image_label.configure(image=photo)\n preview_status.set(f\"{os.path.basename(img_path)} {img.width}x{img.height}\")\n\n ttk.Button(\n preview_top,\n text=\"刷新列表\",\n command=lambda: update_image_list(refresh_after=True),\n ).pack(side=LEFT, padx=(0, 5))\n ttk.Button(preview_top, text=\"刷新预览\", command=refresh_preview).pack(side=LEFT)\n\n # 绑定选择变化事件,自动刷新预览(在 refresh_preview 函数定义之后)\n def on_image_selected(*args):\n \"\"\"当用户选择图片时自动刷新预览\"\"\"\n try:\n refresh_preview()\n except Exception:\n pass # 忽略错误,避免影响其他功能\n\n image_var.trace(\"w\", on_image_selected) # 监听变量变化\n image_combo.bind(\n \"<<ComboboxSelected>>\", lambda e: refresh_preview()\n ) # 监听下拉选择\n\n def open_pic_folder():\n try:\n os.makedirs(images_dir, exist_ok=True)\n os.startfile(images_dir) # type: ignore[attr-defined]\n except Exception as e:\n on_line(f\"[预览] 打开图片目录失败:{e}\")\n\n ttk.Button(preview_top, text=\"打开pic目录\", command=open_pic_folder).pack(\n side=LEFT, padx=(10, 0)\n )\n\n status_var = tk.StringVar(value=\"就绪\")\n\n def get_params() -> RunParams:\n # 如果启用无限循环,设置 wait_minutes=0\n wait_minutes_value = (\n 0 if infinite_loop_var.get() else int(wait_minutes_var.get() or 5)\n )\n return RunParams(\n enable_ocr_mode1=bool(enable_ocr_mode1_var.get()),\n device_id=device_var.get().strip(),\n y_pianyi=int(y_var.get()),\n needswitch=bool(needswitch_var.get()),\n wait_minutes=wait_minutes_value,\n skip_if_countdown_gt_seconds=int(skip_gt_seconds_var.get() or 900),\n reset_after_swipes_enabled=bool(reset_after_swipes_enabled_var.get()),\n reset_after_swipes=int(reset_after_swipes_var.get() or 10),\n min_prize_value_yuan=float(min_value_var.get() or 0),\n min_participants=int(min_participants_var.get() or 0),\n max_participants=int(max_participants_var.get() or 0),\n auto_join_fansclub=bool(auto_join_var.get()),\n fansclub_fail_action=str(fansclub_action_var.get() or \"stay\").lower(),\n # Web端新增参数\n high_value_room_revisit_enabled=bool(\n high_value_room_revisit_enabled_var.get()\n ),\n high_value_room_revisit_only_current_run=bool(\n high_value_room_revisit_only_current_run_var.get()\n ),\n reservation_back_verify_enabled=bool(\n reservation_back_verify_enabled_var.get()\n ),\n reservation_back_swipe_delay=float(\n reservation_back_swipe_delay_var.get() or 0\n ),\n reservation_preempt_min_value=float(\n reservation_preempt_min_value_var.get() or 0\n ),\n fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 0),\n fudai_template_match_enabled=bool(fudai_template_match_enabled_var.get()),\n fudai_template_match_threshold=float(\n fudai_template_match_threshold_var.get() or 0.7\n ),\n )\n\n def start_run():\n if runner.is_running():\n on_line(\"[运行] 已在运行中\")\n return\n save_ui_to_config()\n params = get_params()\n\n wait_display = \"∞\" if params.wait_minutes == 0 else f\"{params.wait_minutes}m\"\n on_line(\n f\"[运行] 启动:device={params.device_id or '(auto)'} y={params.y_pianyi} \"\n f\"needswitch={params.needswitch} wait={wait_display} \"\n f\"skip_gt={params.skip_if_countdown_gt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} \"\n f\"value>={params.min_prize_value_yuan} participants=[{params.min_participants},{params.max_participants}] \"\n f\"high_value_revisit={params.high_value_room_revisit_enabled} reservation_verify={params.reservation_back_verify_enabled} \"\n f\"fudai_find_max={params.fudai_find_max_attempts} yanghao=recommend_flow_only\"\n )\n status_var.set(\"运行中\")\n try:\n runner.start(params)\n except Exception as e:\n status_var.set(\"启动失败\")\n on_line(f\"[错误] {e}\")\n\n def stop_run():\n runner.stop()\n status_var.set(\"已停止\")\n\n # 先打包 actions 到底部(不 expand,固定在底部)\n actions.pack(fill=X, pady=(10, 0), padx=12, side=\"bottom\")\n\n # 然后打包 notebook 填充剩余空间(在 actions 之上)\n notebook.pack(fill=BOTH, expand=True)\n\n ttk.Button(actions, text=\"开始运行\", command=start_run).pack(side=LEFT, padx=(0, 8))\n ttk.Button(actions, text=\"停止\", command=stop_run).pack(side=LEFT, padx=(0, 4))\n\n def force_stop_run():\n \"\"\"强制终止后台进程(包括可能残留的子进程)。\"\"\"\n runner.force_stop()\n status_var.set(\"已停止(强制)\")\n\n ttk.Button(actions, text=\"强制停止\", command=force_stop_run).pack(\n side=LEFT, padx=(0, 8)\n )\n\n ttk.Separator(actions, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=10, pady=3)\n test_seconds_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_recommend_duration_seconds\", 60) or 60)\n )\n ttk.Label(actions, text=\"测试养号(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n actions, from_=10, to=3600, increment=10, textvariable=test_seconds_var, width=8\n ).pack(side=LEFT, padx=(0, 8))\n\n def start_test_yanghao():\n if runner.is_running():\n on_line(\"[运行] 已在运行中\")\n return\n save_ui_to_config()\n secs = int(test_seconds_var.get() or 90)\n dev = device_var.get().strip()\n on_line(f\"[测试] 启动养号流程:device={dev or '(auto)'} seconds={secs}\")\n status_var.set(\"运行中\")\n try:\n runner.start_test_yanghao_flow(dev, secs)\n except Exception as e:\n status_var.set(\"启动失败\")\n on_line(f\"[错误] {e}\")\n\n ttk.Button(actions, text=\"测试养号流程\", command=start_test_yanghao).pack(side=LEFT)\n\n ttk.Separator(actions, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=10, pady=3)\n test_comment_var = tk.StringVar(value=\"测试评论\")\n ttk.Label(actions, text=\"测试评论:\").pack(side=LEFT)\n ttk.Entry(actions, textvariable=test_comment_var, width=12).pack(\n side=LEFT, padx=(0, 8)\n )\n\n def start_test_comment():\n if runner.is_running():\n on_line(\"[运行] 已在运行中\")\n return\n save_ui_to_config()\n text = test_comment_var.get().strip()\n dev = device_var.get().strip()\n on_line(f\"[测试] 启动评论测试:device={dev or '(auto)'} text={text}\")\n status_var.set(\"运行中\")\n try:\n runner.start_test_comment(dev, text)\n except Exception as e:\n status_var.set(\"启动失败\")\n on_line(f\"[错误] {e}\")\n\n ttk.Button(actions, text=\"测试评论\", command=start_test_comment).pack(side=LEFT)\n\n ttk.Separator(actions, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=10, pady=3)\n\n def send_back_key():\n dev = device_var.get().strip()\n try:\n runner.send_back_key(dev)\n except Exception as e:\n on_line(f\"[错误] 发送返回键失败: {e}\")\n\n ttk.Button(actions, text=\"发送返回键\", command=send_back_key).pack(\n side=LEFT, padx=(0, 8)\n )\n\n ttk.Label(actions, textvariable=status_var).pack(side=RIGHT)\n\n def pump_logs():\n changed = False\n try:\n while True:\n line = q.get_nowait()\n try:\n log_text.insert(\"end\", line + \"\\n\")\n # 不再自动滚动到底部,让用户自由控制滚动位置\n changed = True\n except Exception as e:\n # 如果插入日志失败,至少打印到控制台(调试用)\n print(f\"[GUI日志错误] 无法插入日志: {e}\", file=sys.stderr)\n except queue.Empty:\n pass\n except Exception as e:\n # 捕获其他异常,确保日志循环不会中断\n print(f\"[GUI日志错误] pump_logs异常: {e}\", file=sys.stderr)\n\n try:\n if changed and not runner.is_running() and status_var.get() == \"运行中\":\n status_var.set(\"已结束\")\n except Exception:\n pass\n\n # 确保递归调用始终执行,即使前面出现异常\n try:\n root.after(100, pump_logs) # type: ignore[arg-type]\n except Exception as e:\n # 如果 root 已被销毁,停止日志循环\n print(f\"[GUI日志错误] 无法调度下次日志更新: {e}\", file=sys.stderr)\n\n # 统计信息显示\n stats_top = ttk.Frame(stats_tab)\n stats_top.pack(fill=X, padx=10, pady=(10, 0))\n stats_text = ScrolledText(stats_tab)\n stats_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n stats_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def refresh_stats():\n try:\n stats = runner.get_stats()\n lines = []\n\n # 基本信息\n lines.append(\"=\" * 60)\n lines.append(\"运行状态信息\")\n lines.append(\"=\" * 60)\n lines.append(f\"运行状态: {'运行中' if stats.get('running') else '未运行'}\")\n lines.append(f\"PID: {stats.get('pid') or '-'}\")\n\n uptime_seconds = stats.get(\"uptime_seconds\", 0)\n if uptime_seconds > 0:\n hours = uptime_seconds // 3600\n minutes = (uptime_seconds % 3600) // 60\n seconds = uptime_seconds % 60\n lines.append(f\"运行时长: {hours:02d}:{minutes:02d}:{seconds:02d}\")\n else:\n lines.append(f\"运行时长: -\")\n\n last_log_ts = stats.get(\"last_log_ts\")\n if last_log_ts:\n import datetime\n\n dt = datetime.datetime.fromtimestamp(last_log_ts)\n lines.append(f\"最近日志时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}\")\n else:\n lines.append(f\"最近日志时间: -\")\n\n exit_code = stats.get(\"exit_code\")\n lines.append(f\"退出码: {exit_code if exit_code is not None else '-'}\")\n lines.append(\"\")\n\n # 计数器统计\n counters = stats.get(\"counters\", {})\n\n # 快速汇总(关键指标)\n fudai_seen = counters.get(\"fudai_seen\", 0)\n fudai_attend_ok = counters.get(\"fudai_attend_ok\", 0)\n fudai_result_win = counters.get(\"fudai_result_win\", 0)\n fudai_order_success = counters.get(\"fudai_order_success\", 0)\n\n if fudai_seen > 0 or fudai_attend_ok > 0 or fudai_result_win > 0:\n lines.append(\"=\" * 60)\n lines.append(\"快速汇总\")\n lines.append(\"=\" * 60)\n lines.append(f\"识别福袋: {fudai_seen} 个\")\n lines.append(f\"参与成功: {fudai_attend_ok} 次\")\n lines.append(f\"中奖次数: {fudai_result_win} 次\")\n lines.append(f\"下单成功: {fudai_order_success} 次\")\n if uptime_seconds > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(\n f\"运行效率: {fudai_attend_ok / hours:.1f} 次参与/小时\"\n )\n lines.append(\"\")\n\n # 核心统计(总是显示,即使数据为0)\n lines.append(\"=\" * 60)\n lines.append(\"核心统计\")\n lines.append(\"=\" * 60)\n\n # 福袋相关核心指标(重新获取,避免重复定义)\n fudai_open_detail = counters.get(\"fudai_open_detail\", 0)\n fudai_click_attend = counters.get(\"fudai_click_attend\", 0)\n fudai_attend_ok = counters.get(\"fudai_attend_ok\", 0)\n fudai_attend_fail = counters.get(\"fudai_attend_fail\", 0)\n fudai_result_win = counters.get(\"fudai_result_win\", 0)\n fudai_result_no_win = counters.get(\"fudai_result_no_win\", 0)\n fudai_order_success = counters.get(\"fudai_order_success\", 0)\n\n lines.append(f\"福袋识别次数: {fudai_seen}\")\n lines.append(f\"打开详情: {fudai_open_detail}\")\n if fudai_seen > 0:\n open_rate = (fudai_open_detail / fudai_seen) * 100\n lines.append(f\" 打开成功率: {open_rate:.1f}%\")\n\n lines.append(f\"点击参与: {fudai_click_attend}\")\n if fudai_open_detail > 0:\n click_rate = (fudai_click_attend / fudai_open_detail) * 100\n lines.append(f\" 点击率: {click_rate:.1f}%\")\n\n lines.append(f\"参与成功: {fudai_attend_ok}\")\n lines.append(f\"参与失败: {fudai_attend_fail}\")\n total_attend = fudai_attend_ok + fudai_attend_fail\n if total_attend > 0:\n success_rate = (fudai_attend_ok / total_attend) * 100\n lines.append(f\" 参与成功率: {success_rate:.1f}%\")\n\n lines.append(f\"中奖次数: {fudai_result_win}\")\n lines.append(f\"未中奖次数: {fudai_result_no_win}\")\n total_results = fudai_result_win + fudai_result_no_win\n if total_results > 0:\n win_rate = (fudai_result_win / total_results) * 100\n lines.append(f\" 中奖率: {win_rate:.1f}%\")\n\n lines.append(f\"下单成功: {fudai_order_success}\")\n\n # 效率统计\n if uptime_seconds > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(\"\")\n lines.append(\"效率统计(每小时):\")\n if fudai_seen > 0:\n lines.append(f\" 识别福袋: {fudai_seen / hours:.1f} 个/小时\")\n if fudai_attend_ok > 0:\n lines.append(\n f\" 参与成功: {fudai_attend_ok / hours:.1f} 次/小时\"\n )\n if total_results > 0:\n lines.append(f\" 开奖次数: {total_results / hours:.1f} 次/小时\")\n if fudai_result_win > 0:\n lines.append(\n f\" 中奖次数: {fudai_result_win / hours:.2f} 次/小时\"\n )\n\n lines.append(\"\")\n\n # 跳过原因统计\n skip_stats = [\n (\"fudai_skip_value_low\", \"跳过-价值过低\"),\n (\"fudai_skip_participants_low\", \"跳过-人数过少\"),\n (\"fudai_skip_participants_high\", \"跳过-人数过多\"),\n (\"fudai_skip_content\", \"跳过-内容不理想\"),\n (\"fudai_skip_countdown_short\", \"跳过-倒计时太短\"),\n (\"fudai_skip_countdown_long\", \"跳过-倒计时太长\"),\n (\"fudai_skip_watch_required\", \"跳过-需要看播\"),\n ]\n skip_total = sum(counters.get(key, 0) for key, _ in skip_stats)\n if skip_total > 0:\n lines.append(\"=\" * 60)\n lines.append(\"跳过原因统计\")\n lines.append(\"=\" * 60)\n lines.append(f\"总跳过次数: {skip_total}\")\n if fudai_seen > 0:\n skip_rate = (skip_total / fudai_seen) * 100\n lines.append(f\"跳过率: {skip_rate:.1f}%\")\n lines.append(\"\")\n for key, label in skip_stats:\n val = counters.get(key, 0)\n if val > 0:\n percentage = (val / skip_total) * 100 if skip_total > 0 else 0\n lines.append(f\" {label}: {val} ({percentage:.1f}%)\")\n lines.append(\"\")\n\n # 粉丝团统计\n fansclub_stats = [\n (\"fansclub_required\", \"需要粉丝团\"),\n (\"fansclub_manual_needed\", \"需手动加入\"),\n (\"fansclub_unresolved\", \"未解决\"),\n ]\n fansclub_total = sum(counters.get(key, 0) for key, _ in fansclub_stats)\n if fansclub_total > 0:\n lines.append(\"=\" * 60)\n lines.append(\"粉丝团相关统计\")\n lines.append(\"=\" * 60)\n for key, label in fansclub_stats:\n val = counters.get(key, 0)\n if val > 0:\n percentage = (\n (val / fansclub_total) * 100 if fansclub_total > 0 else 0\n )\n lines.append(f\" {label}: {val} ({percentage:.1f}%)\")\n lines.append(\"\")\n\n # 直播间切换统计\n switch_val = counters.get(\"switch_room\", 0)\n if switch_val > 0:\n lines.append(\"=\" * 60)\n lines.append(\"直播间切换统计\")\n lines.append(\"=\" * 60)\n lines.append(f\"总切换次数: {switch_val}\")\n if uptime_seconds > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(f\"切换频率: {switch_val / hours:.1f} 次/小时\")\n lines.append(\"\")\n switch_reasons = [\n (\"switch_room_no_fudai\", \"无福袋\"),\n (\"switch_room_participants\", \"人数不符合\"),\n (\"switch_room_value\", \"价值不符合\"),\n (\"switch_room_content\", \"内容不符合\"),\n (\"switch_room_countdown\", \"倒计时不符合\"),\n (\"switch_room_attend_fail\", \"参与失败\"),\n ]\n for key, label in switch_reasons:\n val = counters.get(key, 0)\n if val > 0:\n percentage = (val / switch_val) * 100 if switch_val > 0 else 0\n lines.append(f\" {label}: {val} ({percentage:.1f}%)\")\n lines.append(\"\")\n\n # 预约相关统计(详细版)\n reservation_recorded = counters.get(\"reservation_recorded\", 0)\n reservation_window_entered = counters.get(\"reservation_window_entered\", 0)\n reservation_back_success = counters.get(\"reservation_back_success\", 0)\n reservation_back_verify_ok = counters.get(\"reservation_back_verify_ok\", 0)\n reservation_back_verify_fail = counters.get(\"reservation_back_verify_fail\", 0)\n reservation_window_not_reached = counters.get(\"reservation_window_not_reached\", 0)\n reservation_expired = counters.get(\"reservation_expired\", 0)\n reservation_queue_empty = counters.get(\"reservation_queue_empty\", 0)\n reservation_locked = counters.get(\"reservation_locked\", 0)\n reservation_back_to_first = counters.get(\"reservation_back_to_first\", 0)\n reservation_queue_full_wait = counters.get(\"reservation_queue_full_wait\", 0)\n reservation_drop_low_value = counters.get(\"reservation_drop_low_value\", 0)\n reservation_clear = counters.get(\"reservation_clear\", 0)\n \n reservation_total = (\n reservation_recorded\n + reservation_window_entered\n + reservation_back_success\n + reservation_back_verify_ok\n + reservation_back_verify_fail\n + reservation_window_not_reached\n + reservation_expired\n + reservation_queue_empty\n + reservation_locked\n + reservation_back_to_first\n + reservation_queue_full_wait\n + reservation_drop_low_value\n + reservation_clear\n )\n \n if reservation_total > 0 or reservation_recorded > 0:\n lines.append(\"=\" * 60)\n lines.append(\"预约相关统计(详细)\")\n lines.append(\"=\" * 60)\n \n # 预约记录统计\n if reservation_recorded > 0:\n lines.append(f\"记录预约总数: {reservation_recorded}\")\n \n # 预约回退统计\n if reservation_back_success > 0:\n lines.append(f\"成功回退到预约直播间: {reservation_back_success}\")\n \n # 回退校验统计\n verify_total = reservation_back_verify_ok + reservation_back_verify_fail\n if verify_total > 0:\n verify_rate = (reservation_back_verify_ok / verify_total) * 100\n lines.append(\n f\"回退校验: {reservation_back_verify_ok} 成功 / {reservation_back_verify_fail} 失败 (成功率: {verify_rate:.1f}%)\"\n )\n \n # 预约窗口统计\n if reservation_window_entered > 0:\n lines.append(f\"进入预约参与窗口: {reservation_window_entered}\")\n if reservation_window_not_reached > 0:\n lines.append(f\"时间窗口未到(跳过): {reservation_window_not_reached}\")\n \n # 预约状态统计\n if reservation_expired > 0:\n lines.append(f\"过期预约(已清理): {reservation_expired}\")\n if reservation_locked > 0:\n lines.append(f\"锁定期未结束(跳过): {reservation_locked}\")\n if reservation_queue_empty > 0:\n lines.append(f\"预约队列为空(检查次数): {reservation_queue_empty}\")\n if reservation_queue_full_wait > 0:\n lines.append(f\"队列已满等待: {reservation_queue_full_wait}\")\n if reservation_back_to_first > 0:\n lines.append(f\"回退到第一个直播间: {reservation_back_to_first}\")\n \n # 预约管理统计\n if reservation_drop_low_value > 0:\n lines.append(f\"丢弃低价值预约: {reservation_drop_low_value}\")\n if reservation_clear > 0:\n lines.append(f\"清空预约队列: {reservation_clear}\")\n \n # 预约成功率\n if reservation_recorded > 0 and reservation_back_success > 0:\n back_rate = (reservation_back_success / reservation_recorded) * 100\n lines.append(f\"预约回退成功率: {back_rate:.1f}% ({reservation_back_success}/{reservation_recorded})\")\n \n lines.append(\"\")\n\n # 错误统计(详细版)\n error_total = counters.get(\"error_total\", 0)\n error_unbound_local = counters.get(\"error_unbound_local\", 0)\n error_attribute = counters.get(\"error_attribute\", 0)\n error_key = counters.get(\"error_key\", 0)\n error_value = counters.get(\"error_value\", 0)\n error_type = counters.get(\"error_type\", 0)\n error_timeout = counters.get(\"error_timeout\", 0)\n error_connection = counters.get(\"error_connection\", 0)\n error_ocr = counters.get(\"error_ocr\", 0)\n error_screenshot = counters.get(\"error_screenshot\", 0)\n error_detection = counters.get(\"error_detection\", 0)\n error_stage_diagnosis = counters.get(\"error_stage_diagnosis\", 0)\n error_read_detail = counters.get(\"error_read_detail\", 0)\n error_config_load = counters.get(\"error_config_load\", 0)\n error_state_file = counters.get(\"error_state_file\", 0)\n error_live_room_detect = counters.get(\"error_live_room_detect\", 0)\n error_fudai_find = counters.get(\"error_fudai_find\", 0)\n fudai_open_error = counters.get(\"fudai_open_error\", 0)\n fudai_open_error_too_many = counters.get(\"fudai_open_error_too_many\", 0)\n \n error_all = (\n error_total\n + error_unbound_local\n + error_attribute\n + error_key\n + error_value\n + error_type\n + error_timeout\n + error_connection\n + error_ocr\n + error_screenshot\n + error_detection\n + error_stage_diagnosis\n + error_read_detail\n + error_config_load\n + error_state_file\n + error_live_room_detect\n + error_fudai_find\n + fudai_open_error\n + fudai_open_error_too_many\n )\n \n if error_all > 0:\n lines.append(\"=\" * 60)\n lines.append(\"错误统计(详细)\")\n lines.append(\"=\" * 60)\n \n # 总错误数\n if error_total > 0:\n lines.append(f\"总错误数: {error_total}\")\n \n # 福袋相关错误\n fudai_errors = fudai_open_error + fudai_open_error_too_many\n if fudai_errors > 0:\n lines.append(\"\")\n lines.append(\"福袋相关错误:\")\n if fudai_open_error > 0:\n lines.append(f\" 打开福袋异常: {fudai_open_error}\")\n if fudai_open_error_too_many > 0:\n lines.append(f\" 打开失败次数过多: {fudai_open_error_too_many}\")\n \n # Python异常类型\n python_errors = (\n error_unbound_local\n + error_attribute\n + error_key\n + error_value\n + error_type\n )\n if python_errors > 0:\n lines.append(\"\")\n lines.append(\"Python异常类型:\")\n if error_unbound_local > 0:\n lines.append(f\" UnboundLocalError: {error_unbound_local}\")\n if error_attribute > 0:\n lines.append(f\" AttributeError: {error_attribute}\")\n if error_key > 0:\n lines.append(f\" KeyError: {error_key}\")\n if error_value > 0:\n lines.append(f\" ValueError: {error_value}\")\n if error_type > 0:\n lines.append(f\" TypeError: {error_type}\")\n \n # 功能模块错误\n module_errors = (\n error_ocr\n + error_screenshot\n + error_detection\n + error_stage_diagnosis\n + error_read_detail\n + error_config_load\n + error_state_file\n + error_live_room_detect\n + error_fudai_find\n )\n if module_errors > 0:\n lines.append(\"\")\n lines.append(\"功能模块错误:\")\n if error_ocr > 0:\n lines.append(f\" OCR识别错误: {error_ocr}\")\n if error_screenshot > 0:\n lines.append(f\" 截图错误: {error_screenshot}\")\n if error_detection > 0:\n lines.append(f\" 识别错误: {error_detection}\")\n if error_stage_diagnosis > 0:\n lines.append(f\" 阶段诊断错误: {error_stage_diagnosis}\")\n if error_read_detail > 0:\n lines.append(f\" 读取详情错误: {error_read_detail}\")\n if error_config_load > 0:\n lines.append(f\" 配置加载错误: {error_config_load}\")\n if error_state_file > 0:\n lines.append(f\" 状态文件错误: {error_state_file}\")\n if error_live_room_detect > 0:\n lines.append(f\" 直播间检测错误: {error_live_room_detect}\")\n if error_fudai_find > 0:\n lines.append(f\" 福袋查找错误: {error_fudai_find}\")\n \n # 网络和超时错误\n network_errors = error_timeout + error_connection\n if network_errors > 0:\n lines.append(\"\")\n lines.append(\"网络和超时错误:\")\n if error_timeout > 0:\n lines.append(f\" 超时错误: {error_timeout}\")\n if error_connection > 0:\n lines.append(f\" 连接错误: {error_connection}\")\n \n # 错误率统计\n if uptime_seconds > 0 and error_all > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(\"\")\n lines.append(f\"错误频率: {error_all / hours:.2f} 次/小时\")\n \n lines.append(\"\")\n\n # 价值统计(从事件中提取)\n events = stats.get(\"events\", [])\n prize_values = []\n for event in events:\n meta = event.get(\"meta\", {})\n if \"prize_value_yuan\" in meta and meta[\"prize_value_yuan\"] is not None:\n try:\n prize_values.append(float(meta[\"prize_value_yuan\"]))\n except (ValueError, TypeError):\n pass\n\n if prize_values:\n lines.append(\"=\" * 60)\n lines.append(\"价值统计\")\n lines.append(\"=\" * 60)\n total_value = sum(prize_values)\n avg_value = total_value / len(prize_values)\n max_value = max(prize_values)\n min_value = min(prize_values)\n lines.append(f\"识别到的福袋总数: {len(prize_values)}\")\n lines.append(f\"总价值: {total_value:.2f} 元\")\n lines.append(f\"平均价值: {avg_value:.2f} 元\")\n lines.append(f\"最高价值: {max_value:.2f} 元\")\n lines.append(f\"最低价值: {min_value:.2f} 元\")\n\n # 价值分布\n high_value_count = sum(1 for v in prize_values if v >= 500)\n medium_value_count = sum(1 for v in prize_values if 100 <= v < 500)\n low_value_count = sum(1 for v in prize_values if v < 100)\n lines.append(\"\")\n lines.append(\"价值分布:\")\n lines.append(\n f\" 高价值(≥500元): {high_value_count} ({high_value_count/len(prize_values)*100:.1f}%)\"\n )\n lines.append(\n f\" 中价值(100-500元): {medium_value_count} ({medium_value_count/len(prize_values)*100:.1f}%)\"\n )\n lines.append(\n f\" 低价值(<100元): {low_value_count} ({low_value_count/len(prize_values)*100:.1f}%)\"\n )\n lines.append(\"\")\n\n # 最近一次福袋信息\n fudai_last = stats.get(\"fudai_last\", {})\n if fudai_last.get(\"content\") or fudai_last.get(\"countdown\"):\n lines.append(\"=\" * 60)\n lines.append(\"最近一次福袋信息\")\n lines.append(\"=\" * 60)\n lines.append(f\"内容: {fudai_last.get('content') or '-'}\")\n lines.append(f\"倒计时: {fudai_last.get('countdown') or '-'}\")\n participants = fudai_last.get(\"participants\")\n copies = fudai_last.get(\"copies\")\n if participants is not None and copies is not None:\n lines.append(f\"参与人数/份数: {participants} / {copies}\")\n if participants > 0 and copies > 0:\n ratio = participants / copies\n lines.append(f\" 中奖概率: {1/ratio*100:.2f}% (1/{ratio:.1f})\")\n prize_value = fudai_last.get(\"prize_value_yuan\")\n if prize_value is not None:\n lines.append(f\"奖品价值: {prize_value} 元\")\n updated_ts = fudai_last.get(\"updated_ts\")\n if updated_ts:\n import datetime\n\n dt = datetime.datetime.fromtimestamp(updated_ts)\n lines.append(f\"更新时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}\")\n lines.append(\"\")\n\n # 中奖记录\n wins = stats.get(\"wins\", [])\n if wins:\n lines.append(\"=\" * 60)\n lines.append(f\"最近中奖记录(显示最近 {len(wins)} 条)\")\n lines.append(\"=\" * 60)\n for i, win in enumerate(wins[-10:], 1): # 只显示最近10条\n import datetime\n\n ts = win.get(\"ts\", 0)\n dt_str = (\n datetime.datetime.fromtimestamp(ts).strftime(\n \"%Y-%m-%d %H:%M:%S\"\n )\n if ts\n else \"-\"\n )\n lines.append(f\"\\n[{i}] 时间: {dt_str}\")\n if win.get(\"content\"):\n lines.append(f\" 内容: {win.get('content')}\")\n if win.get(\"prize_value_yuan\"):\n lines.append(f\" 价值: {win.get('prize_value_yuan')} 元\")\n if win.get(\"participants\") and win.get(\"copies\"):\n lines.append(\n f\" 人数/份数: {win.get('participants')} / {win.get('copies')}\"\n )\n\n # 确保至少显示基本信息\n if not lines:\n lines.append(\"=\" * 60)\n lines.append(\"统计信息\")\n lines.append(\"=\" * 60)\n lines.append(\"暂无统计数据\")\n lines.append(\"\")\n lines.append(\"提示:请先运行程序以收集统计数据\")\n\n stats_text.delete(\"1.0\", \"end\")\n stats_text.insert(\"1.0\", \"\\n\".join(lines))\n except Exception as e:\n import traceback\n\n stats_text.delete(\"1.0\", \"end\")\n error_detail = traceback.format_exc()\n stats_text.insert(\n \"1.0\", f\"刷新统计信息失败:{e}\\n\\n详细信息:\\n{error_detail}\"\n )\n\n ttk.Button(stats_top, text=\"刷新\", command=refresh_stats).pack(side=LEFT)\n\n # 预约队列显示\n reservation_top = ttk.Frame(reservation_tab)\n reservation_top.pack(fill=X, padx=10, pady=(10, 0))\n reservation_text = ScrolledText(reservation_tab)\n reservation_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n reservation_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def refresh_reservations():\n path = os.path.join(os.path.dirname(__file__), \"state\", \"reservations.json\")\n try:\n if os.path.exists(path):\n with open(path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n reservation_text.delete(\"1.0\", \"end\")\n reservation_text.insert(\n \"1.0\", json.dumps(data, ensure_ascii=False, indent=2)\n )\n else:\n reservation_text.delete(\"1.0\", \"end\")\n reservation_text.insert(\"1.0\", \"暂无预约队列数据\")\n except Exception as e:\n reservation_text.delete(\"1.0\", \"end\")\n reservation_text.insert(\"1.0\", f\"读取预约队列失败:{e}\")\n\n ttk.Button(reservation_top, text=\"刷新\", command=refresh_reservations).pack(\n side=LEFT\n )\n\n # 高价值房间显示\n high_value_top = ttk.Frame(high_value_tab)\n high_value_top.pack(fill=X, padx=10, pady=(10, 0))\n high_value_text = ScrolledText(high_value_tab)\n high_value_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n high_value_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def refresh_high_value_rooms():\n path = os.path.join(os.path.dirname(__file__), \"state\", \"high_value_rooms.json\")\n try:\n if os.path.exists(path):\n with open(path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n high_value_text.delete(\"1.0\", \"end\")\n high_value_text.insert(\n \"1.0\", json.dumps(data, ensure_ascii=False, indent=2)\n )\n else:\n high_value_text.delete(\"1.0\", \"end\")\n high_value_text.insert(\"1.0\", \"暂无高价值房间数据\")\n except Exception as e:\n high_value_text.delete(\"1.0\", \"end\")\n high_value_text.insert(\"1.0\", f\"读取高价值房间失败:{e}\")\n\n ttk.Button(high_value_top, text=\"刷新\", command=refresh_high_value_rooms).pack(\n side=LEFT\n )\n\n # 行为日志显示(点击/识别/耗时)\n actions_log_top = ttk.Frame(actions_log_tab)\n actions_log_top.pack(fill=X, padx=10, pady=(10, 0))\n actions_log_text = ScrolledText(actions_log_tab)\n actions_log_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n actions_log_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n actions_filter_var = tk.StringVar(value=\"\")\n\n def refresh_actions_log():\n \"\"\"读取 logs/actions.log 的尾部若干行,在 GUI 中展示关键行为日志(支持简单关键字筛选)。\"\"\"\n path = os.path.join(os.path.dirname(__file__), \"logs\", \"actions.log\")\n try:\n if os.path.exists(path):\n # 仿照 web_gui 的实现:只读最后一小段,避免文件巨大\n size = os.path.getsize(path)\n if size == 0:\n actions_log_text.delete(\"1.0\", \"end\")\n actions_log_text.insert(\"1.0\", \"行为日志文件为空\")\n return\n \n read_bytes = min(size, 65536)\n with open(path, \"rb\") as f:\n if read_bytes < size:\n f.seek(-read_bytes, os.SEEK_END)\n data = f.read()\n # 尝试多种编码方式\n try:\n # 先尝试 utf-8-sig(带BOM)\n text = data.decode(\"utf-8-sig\", errors=\"replace\")\n except Exception:\n try:\n # 再尝试 utf-8\n text = data.decode(\"utf-8\", errors=\"replace\")\n except Exception:\n # 最后尝试 gbk(Windows常见编码)\n text = data.decode(\"gbk\", errors=\"replace\")\n lines = text.splitlines()\n # 只取最近 300 行\n tail = lines[-300:]\n\n # 关键字筛选:若填写了筛选词,只保留包含该关键字的行\n kw = actions_filter_var.get().strip()\n if kw:\n tail = [ln for ln in tail if kw in ln]\n\n # 保存当前滚动位置,避免刷新时自动置顶\n try:\n scroll_position = actions_log_text.yview()[0] # 获取当前滚动位置(顶部可见位置的比例)\n except Exception:\n scroll_position = 0.0\n\n actions_log_text.delete(\"1.0\", \"end\")\n if tail:\n actions_log_text.insert(\"1.0\", \"\\n\".join(tail))\n else:\n actions_log_text.insert(\"1.0\", \"暂无匹配的行为日志\")\n \n # 恢复之前的滚动位置,避免自动置顶\n try:\n actions_log_text.yview_moveto(scroll_position)\n except Exception:\n pass\n else:\n actions_log_text.delete(\"1.0\", \"end\")\n actions_log_text.insert(\n \"1.0\", \"暂无行为日志(logs/actions.log 不存在)\"\n )\n except Exception as e:\n actions_log_text.delete(\"1.0\", \"end\")\n actions_log_text.insert(\"1.0\", f\"读取行为日志失败:{e}\")\n\n ttk.Label(actions_log_top, text=\"关键字筛选:\").pack(side=LEFT)\n ttk.Entry(actions_log_top, textvariable=actions_filter_var, width=16).pack(\n side=LEFT, padx=(0, 8)\n )\n ttk.Button(actions_log_top, text=\"刷新\", command=refresh_actions_log).pack(\n side=LEFT, padx=(0, 10)\n )\n \n # 行为日志搜索功能\n ttk.Separator(actions_log_top, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=5, pady=3)\n ttk.Label(actions_log_top, text=\"搜索:\").pack(side=LEFT)\n \n actions_search_var = tk.StringVar(value=\"\")\n actions_search_entry = ttk.Entry(actions_log_top, textvariable=actions_search_var, width=20)\n actions_search_entry.pack(side=LEFT, padx=(0, 5))\n \n actions_search_matches = []\n actions_current_match_index = -1\n \n def search_in_actions_log(direction=1):\n \"\"\"在行为日志中搜索文本\"\"\"\n nonlocal actions_search_matches, actions_current_match_index\n \n search_text = actions_search_var.get().strip()\n if not search_text:\n actions_log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n actions_log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n actions_search_matches = []\n actions_current_match_index = -1\n return\n \n content = actions_log_text.get(\"1.0\", \"end-1c\")\n if not content:\n return\n \n actions_log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n actions_log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n \n actions_log_text.tag_config(\"search_highlight\", background=\"yellow\")\n actions_log_text.tag_config(\"search_current\", background=\"orange\")\n \n actions_search_matches = []\n start_pos = 0 # 使用整数索引\n search_text_lower = search_text.lower()\n content_lower = content.lower()\n \n while True:\n pos = content_lower.find(search_text_lower, start_pos)\n if pos == -1:\n break\n \n line_start = content[:pos].rfind(\"\\n\") + 1\n line_num = content[:pos].count(\"\\n\") + 1\n col_num = pos - line_start\n \n start_index = f\"{line_num}.{col_num}\"\n end_index = f\"{line_num}.{col_num + len(search_text)}\"\n \n actions_search_matches.append((start_index, end_index))\n start_pos = pos + 1\n \n if not actions_search_matches:\n actions_current_match_index = -1\n return\n \n for start_idx, end_idx in actions_search_matches:\n actions_log_text.tag_add(\"search_highlight\", start_idx, end_idx)\n \n if direction == 1:\n actions_current_match_index = (actions_current_match_index + 1) % len(actions_search_matches)\n else:\n actions_current_match_index = (actions_current_match_index - 1) % len(actions_search_matches)\n \n if actions_current_match_index >= 0:\n start_idx, end_idx = actions_search_matches[actions_current_match_index]\n actions_log_text.tag_add(\"search_current\", start_idx, end_idx)\n actions_log_text.see(start_idx)\n actions_log_text.mark_set(\"insert\", start_idx)\n \n def search_next_in_actions():\n search_in_actions_log(1)\n \n def search_prev_in_actions():\n search_in_actions_log(-1)\n \n def clear_search_in_actions():\n nonlocal actions_search_matches, actions_current_match_index\n actions_search_var.set(\"\")\n actions_log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n actions_log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n actions_search_matches = []\n actions_current_match_index = -1\n \n def on_actions_search_entry_key(event):\n if event.keysym == \"Return\":\n search_next_in_actions()\n \n actions_search_entry.bind(\"<KeyPress>\", on_actions_search_entry_key)\n \n ttk.Button(actions_log_top, text=\"搜索\", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2))\n ttk.Button(actions_log_top, text=\"上一个\", command=search_prev_in_actions).pack(side=LEFT, padx=(0, 2))\n ttk.Button(actions_log_top, text=\"下一个\", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2))\n ttk.Button(actions_log_top, text=\"清除\", command=clear_search_in_actions).pack(side=LEFT)\n\n # OCR结果显示\n ocr_results_top = ttk.Frame(ocr_results_tab)\n ocr_results_top.pack(fill=X, padx=10, pady=(10, 0))\n ocr_results_text = ScrolledText(ocr_results_tab)\n ocr_results_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n ocr_results_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def update_ocr_results(results):\n \"\"\"更新OCR结果标签页的显示\"\"\"\n try:\n lines = []\n lines.append(\"=\" * 80)\n lines.append(\"OCR识别结果(基于最新截图)\")\n lines.append(\"=\" * 80)\n lines.append(\"\")\n\n if not results:\n lines.append('暂无OCR结果,请先点击\"截图+OCR\"按钮')\n else:\n # 按区域名称分组显示\n for region_name, desc, text_result, status in results:\n lines.append(f\"【{region_name}】{desc}\")\n lines.append(f\" 状态: {status}\")\n if text_result:\n # 如果文本较长,分行显示\n if len(text_result) > 100:\n lines.append(f\" 识别文本: {text_result[:100]}...\")\n lines.append(f\" (完整文本: {text_result})\")\n else:\n lines.append(f\" 识别文本: {text_result}\")\n else:\n lines.append(\" 识别文本: (空)\")\n lines.append(\"\")\n\n ocr_results_text.delete(\"1.0\", \"end\")\n ocr_results_text.insert(\"1.0\", \"\\n\".join(lines))\n ocr_results_text.see(\"1.0\")\n except Exception as e:\n ocr_results_text.delete(\"1.0\", \"end\")\n ocr_results_text.insert(\"1.0\", f\"更新OCR结果失败:{e}\")\n\n ttk.Button(\n ocr_results_top, text=\"刷新\", command=lambda: update_ocr_results([])\n ).pack(side=LEFT)\n ttk.Label(ocr_results_top, text='(点击\"截图+OCR\"按钮自动更新)').pack(\n side=LEFT, padx=(10, 0)\n )\n\n pump_logs()\n\n def delayed_refresh_preview() -> None:\n if image_var.get():\n refresh_preview()\n\n root.after(300, delayed_refresh_preview) # type: ignore[arg-type]\n root.after(500, refresh_stats) # type: ignore[arg-type]\n root.after(500, refresh_reservations) # type: ignore[arg-type]\n root.after(500, refresh_high_value_rooms) # type: ignore[arg-type]\n root.after(500, refresh_actions_log) # type: ignore[arg-type]\n\n # 定期刷新行为日志(每2秒)\n def auto_refresh_actions_log() -> None:\n refresh_actions_log()\n root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]\n \n root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]\n\n # 定期刷新统计信息(每3秒)\n def auto_refresh_stats() -> None:\n if runner.is_running():\n refresh_stats()\n root.after(3000, auto_refresh_stats) # type: ignore[arg-type]\n\n auto_refresh_stats()\n\n def on_close():\n try:\n runner.stop()\n except Exception:\n pass\n root.destroy()\n\n root.protocol(\"WM_DELETE_WINDOW\", on_close)\n refresh_devices()\n root.mainloop()\n\n\nif __name__ == \"__main__\":\n try:\n from version import print_version_banner\n\n print_version_banner(\"gui_app\")\n except Exception:\n pass\n main()\n" +} +``` +User decision: **accepted** + +Status: **completed** + + +
+
+ +--- + + +
+ Tool use: **read_lints** • Read lints for 1 file + +Lint paths: + +- `gui_app.py` + +Lint results + +Lint errors for `gui_app.py` + + +| Message | Range | Severity | +|-------|-------|----------| +| 代码不会被执行 | 235:9-235:17 | DIAGNOSTIC_SEVERITY_HINT | +| "args" 未使用 | 568:36-568:40 | DIAGNOSTIC_SEVERITY_HINT | +| 变量 "dirs" 未使用 | 1870:23-1870:27 | DIAGNOSTIC_SEVERITY_HINT | +| "args" 未使用 | 1993:28-1993:32 | DIAGNOSTIC_SEVERITY_HINT | + + +
+
+ +--- + + +
+ Tool use: **read_lints** • Read lints for 1 file + +Lint paths: + +- `webui/app.js` + +Lint results + + +**No lint errors found** +
+
+ +--- + + +
+Tool use: **apply_patch** + + +Parameters: + +```json +{ + "relativeWorkspacePath": "config.json" +} +``` +Additional data: + +```json +{ + "codeblockId": "3c62296f-1b22-4b7a-af15-b505b78a5120" +} +``` +Result: + +```json +{ + "diff": { + "chunks": [ + { + "diffString": " },\r\n \"debug_captures\": {\r\n+ \"enabled\": false,\r\n \"keep_days\": 3,\r\n \"max_files\": 2000,\r", + "oldStart": 96, + "newStart": 96, + "oldLines": 4, + "newLines": 5, + "linesAdded": 1 + } + ], + "editor": "EDITOR_AI" + }, + "shouldAutoFixLints": true, + "resultForModel": "Success. Updated the following files:\nM config.json", + "contentsAfterEdit": "{\r\n \"needswitch\": true,\r\n \"infinite_loop_enabled\": true,\r\n \"wait_minutes\": 5,\r\n \"min_prize_value_yuan\": 200.0,\r\n \"min_participants\": 0,\r\n \"max_participants\": 0,\r\n \"skip_if_countdown_gt_seconds\": 120,\r\n \"reset_after_swipes_enabled\": true,\r\n \"reset_after_swipes\": 50,\r\n \"auto_join_fansclub\": true,\r\n \"fansclub_fail_action\": \"switch\",\r\n \"high_value_fudai_enabled\": true,\r\n \"high_value_fudai_threshold_yuan\": 500.0,\r\n \"high_value_fudai_join_ahead_seconds\": 120,\r\n \"high_value_fudai_max_swipe_back\": 50,\r\n \"high_value_fudai_max_reservations\": 9999,\r\n \"high_value_fudai_after_action\": \"continue\",\r\n \"high_value_room_revisit_enabled\": true,\r\n \"high_value_room_revisit_only_current_run\": true,\r\n \"reservation_back_verify_enabled\": false,\r\n \"reservation_back_swipe_delay\": 0.5,\r\n \"reservation_preempt_min_value\": 0.0,\r\n \"desktop_icon_x\": 153,\r\n \"desktop_icon_y\": 260,\r\n \"yanghao_fallback_live_x\": 540,\r\n \"yanghao_fallback_live_y\": 2000,\r\n \"yanghao_fallback_enter_live_x\": 540,\r\n \"yanghao_fallback_enter_live_y\": 1200,\r\n \"fudai_find_max_attempts\": 99999,\r\n \"fudai_icon_retry_delay_seconds\": 0.1,\r\n \"fudai_icon_max_wait_seconds\": 8.0,\r\n \"fudai_click_wait_seconds\": 1.7,\r\n \"yanghao_recommend_duration_seconds\": 206,\r\n \"yanghao_recommend_interval_seconds\": 570,\r\n \"yanghao_like_prob\": 1.0,\r\n \"yanghao_fav_prob\": 0.85,\r\n \"yanghao_comment_prob\": 1.0,\r\n \"yanghao_icon_roi_size\": 240,\r\n \"yanghao_icon_match_threshold\": 0.77,\r\n \"yanghao_step_screenshot\": false,\r\n \"yanghao_like_roi_offset_x\": 0,\r\n \"yanghao_like_roi_offset_y\": -50,\r\n \"yanghao_fav_roi_offset_x\": 40,\r\n \"yanghao_fav_roi_offset_y\": 0,\r\n \"contains_want\": [],\r\n \"contains_not_want\": [\r\n \"首饰盒\"\r\n ],\r\n \"fudai_quiet_hours_enabled\": true,\r\n \"fudai_quiet_start_hour\": 2,\r\n \"fudai_quiet_end_hour\": 9,\r\n \"yanghao_enabled\": false,\r\n \"yanghao_enable_actions\": false,\r\n \"yanghao_like_icon_x\": 0,\r\n \"yanghao_like_icon_y\": -1,\r\n \"yanghao_fav_icon_x\": -1,\r\n \"yanghao_fav_icon_y\": 0,\r\n \"yanghao_like_template_path\": \"assets/like.png\",\r\n \"yanghao_fav_template_path\": \"assets/fav.png\",\r\n \"yanghao_after_dwell_swipe_direction\": \"up\",\r\n \"yanghao_after_dwell_swipe_distance_px\": 900,\r\n \"yanghao_comment_btn_x\": 0,\r\n \"yanghao_comment_btn_y\": -1,\r\n \"yanghao_comment_input_x\": 0,\r\n \"yanghao_comment_input_y\": 0,\r\n \"yanghao_comment_send_x\": 0,\r\n \"yanghao_comment_send_y\": -1,\r\n \"yanghao_comment_close_x\": 0,\r\n \"yanghao_comment_close_y\": 0,\r\n \"yanghao_comment_texts\": [],\r\n \"yanghao_like_keywords\": [],\r\n \"yanghao_fav_keywords\": [],\r\n \"stage_diag_max_time\": 5.0,\r\n \"stage_diag_max_step_time\": 2.0,\r\n \"live_room_match_threshold\": 0.6,\r\n \"enable_ocr_mode1\": false,\r\n \"fudai_template_match_enabled\": false,\r\n \"fudai_template_match_threshold\": 0.7,\r\n \"lucky_draw_red_ratio_threshold\": 0.8,\r\n \"y_pianyi\": 0,\r\n \"skip_if_countdown_lt_seconds\": 5,\r\n \"no_attend_timeout_minutes\": 30.0,\r\n \"logging\": {\r\n \"level\": \"INFO\",\r\n \"file_path\": \"logs/unified.log\",\r\n \"keep_days\": 30,\r\n \"use_dated_logs\": true,\r\n \"rotation\": {\r\n \"enabled\": true,\r\n \"max_bytes\": 10485760,\r\n \"backup_count\": 5,\r\n \"when\": \"midnight\",\r\n \"interval\": 1\r\n }\r\n },\r\n \"debug_captures\": {\r\n \"enabled\": false,\r\n \"keep_days\": 3,\r\n \"max_files\": 2000,\r\n \"auto_cleanup\": true\r\n },\r\n \"fudai_detail_template_threshold\": 0.54,\r\n \"switch_room_wait_after_stage_diag_seconds\": 4.0,\r\n \"coupon_template_match_threshold\": 0.4,\r\n \"attend_button_red_ratio_threshold\": 0.25,\r\n \"fansclub_join_red_ratio_threshold\": 0.25,\r\n \"reservation_test_mode\": false\r\n}\r\n" +} +``` +User decision: **accepted** + +Status: **completed** + + +
+
+ +--- + +### 已实现的功能 + +- **关闭调试截图(默认)** + - 在 `douyin_screenshot_manager.save_debug_image` 里增加了总开关: + - 读取 `config.json` 中 `debug_captures.enabled`,默认为 `false`。 + - 若为 `false` 或读取配置出错,则直接 `return None`,**不再创建目录、不再保存任何调试 PNG**。 + - 当前你的 `config.json` 已设置:`"debug_captures": { "enabled": false, ... }`,所以现在所有 OCR / 像素 / 模板的调试截图都已关闭。 + +- **在 GUI 中增加开关** + - **桌面 GUI (`gui_app.py`)**: + - 调试页新增一个勾选项:`保存调试图像(OCR / 像素 / 模板等)`,绑定 `debug_captures.enabled`。 + - 读取配置时会同步这个勾选状态;保存配置时会把当前勾选写回 `config.json`。 + - **网页 GUI (`webui`)**: + - 在“调试参数”页新增一个开关: + - 文本:`保存调试图像(OCR / 像素 / 模板等)` + - 对应键:`debug_captures.enabled` + - `app.js` 默认值为 `false`,与本地 `config.json` 一致。 + +### 使用方式 + +- 现在**默认不保存任何调试截图**,OCR 会少一次磁盘写入,整体会稍微快一点、也不再爆 debug_captures 目录。 +- 需要排查问题时,只要在桌面 GUI 或 Web GUI 里勾上“保存调试图像(OCR / 像素 / 模板等)”,保存配置后重新启动脚本即可恢复保存调试截图。 + +--- + +_**User (2025-12-26 05:50Z)**_ + +过期的预约队列要立即丢弃 + +--- + +_**Agent (model default, mode Agent)**_ + +
Thought Process +**Looking into reservation logic** + +I need to modify the reservation logic to ensure that expired reservations are dropped immediately. It's crucial for maintaining an effective system. So, I'll inspect the reservation logic module to pinpoint exactly what changes are necessary. This should help streamline the process and improve user experience. I'm curious to see what adjustments I can make that will lead to better functionality. Let's get to work on this!
+ +--- + + +
+ Tool use: **codebase_search** • Searched codebase "ReservationItem dataclass expire_time or countdown_seconds" • **10** results + +| File | Lines | +|------|-------| +| `douyin_reservation_logic.py` | L46 | +| `douyin_reservation_logic.py` | L808-896 | +| `douyin_reservation_logic.py` | L27-183 | +| `douyin_reservation_logic.py` | L186-430 | +| `douyin_reservation_logic.py` | L430-808 | +| `douyin_reservation_logic.py` | L49-183 | +| `douyin_reservation_logic.py` | L59-183 | +| `douyin_reservation_logic.py` | L240-808 | +| `douyin_reservation_logic.py` | L205-430 | +| `douyin_reservation_logic.py` | L62-237 | + +
+
+ +--- + + +
Tool use: **read_file** • Read file: douyin_reservation_logic.py + +
+
+ +--- + + +
+Tool use: **grep** • Grep for "reservations" in "douyin_fudai_core.py" • 16 matches + +Output mode: content + + +| File | Content | Line | +|------|------|------| +| `douyin_fudai_core.py` | `reservations = getattr(analyser, "reservations", None)` | L2733 | +| `douyin_fudai_core.py` | `if reservations is None:` | L2734 | +| `douyin_fudai_core.py` | `reservations = []` | L2735 | +| `douyin_fudai_core.py` | `analyser.reservations = reservations # type: ignore[attr-defined]` | L2737 | +| `douyin_fudai_core.py` | `# 定义写入状态文件的回调函数(格式与 douyin_reservation.py 中的 write_reservations_state 一致)` | L2792 | +| `douyin_fudai_core.py` | `analyser, "_reservations_state_path", None` | L2800 | +| `douyin_fudai_core.py` | `"reservations.json",` | L2807 | +| `douyin_fudai_core.py` | `for r in reservations or []:` | L2814 | +| `douyin_fudai_core.py` | `"reservations": items,` | L2866 | +| `douyin_fudai_core.py` | `queue_len=len(reservations),` | L2876 | +| `douyin_fudai_core.py` | `max_reservations=int(` | L2916 | +| `douyin_fudai_core.py` | `analyser, "high_value_fudai_max_reservations", 3` | L2918 | +| `douyin_fudai_core.py` | `reservations=reservations,` | L2937 | +| `douyin_fudai_core.py` | `sort_reservations_callback=lambda: rl._sort_reservations_inplace( # type: ignore[attr-defined]` | L2948 | +| `douyin_fudai_core.py` | `reservations` | L2949 | +| `douyin_fudai_core.py` | `queue_len=len(reservations),` | L2973 | + + +
+
+ +--- + + +
Tool use: **read_file** • Read file: douyin_fudai_core.py + +
+
+ +--- + + +
Tool use: **read_file** • Read file: douyin_fudai_core.py + +
+
+ +--- + + + +--- + + +
+Tool use: **grep** • Grep for "cleanup_expired_reservations" in "." • 4 matches + +Output mode: content + + +| File | Content | Line | +|------|------|------| +| `.\douyin_fudai.py` | `douyin_reservation_logic.cleanup_expired_reservations(` | L2386 | +| `.\douyin_reservation_logic.py` | `def cleanup_expired_reservations(` | L206 | +| `.\douyin_reservation_logic.py` | `"[预约] cleanup_expired_reservations",` | L224 | +| `.\douyin_reservation_logic.py` | `cleanup_expired_reservations(analyser, reservations, write_state_callback)` | L685 | + + +
+
+ +--- + + +
Tool use: **read_file** • Read file: douyin_fudai.py + +
+
+ +--- + + +
Tool use: **read_file** • Read file: douyin_reservation_logic.py + +
+
+ +--- + +
Thought Process +**Locating idempotent processing** + +I’m trying to track down where reservations are loaded and processed in the `douyin_fudai.py` file, specifically within the `run_once_basic` section. This seems to be an idempotent process, so I need to carefully look at the earlier lines to understand how it's working. I’ll focus on that part to ensure everything is functioning as intended. Let's keep going with this focus!
+ +--- + + +
+Tool use: **grep** • Grep for "process_reservation_attend_window" in "douyin_fudai.py" • 4 matches + +Output mode: content + + +| File | Content | Line | +|------|------|------| +| `douyin_fudai.py` | `preempted = douyin_reservation_logic.process_reservation_attend_window(` | L1747 | +| `douyin_fudai.py` | `"[预约] 多间模式:开始调用 process_reservation_attend_window",` | L2311 | +| `douyin_fudai.py` | `douyin_reservation_logic.process_reservation_attend_window(` | L2319 | +| `douyin_fudai.py` | `"[预约] process_reservation_attend_window 返回结果",` | L2338 | + + +
+
+ +--- + + +
Tool use: **read_file** • Read file: douyin_fudai.py + +
+
+ +--- + + +
+Tool use: **grep** • Grep for "cleanup_expired_reservations" in "douyin_fudai_core.py" • 0 matches + +Output mode: content + + +_No matches found_ + +
+
+ +--- + + +
+Tool use: **apply_patch** + + +Parameters: + +```json +{ + "relativeWorkspacePath": "douyin_fudai_core.py" +} +``` +Additional data: + +```json +{ + "codeblockId": "4bbc2595-a947-4ff7-930d-171615a07705" +} +``` +Result: + +```json +{ + "diff": { + "chunks": [ + { + "diffString": " except Exception:\n pass\n+ else:\n+ # 在已有预约队列的情况下,先立即清理已过期的预约,保证队列始终是“未过期”的\n+ try:\n+ import douyin_reservation_logic as rl_cleanup\n+ \n+ rl_cleanup.cleanup_expired_reservations(\n+ analyser,\n+ reservations,\n+ write_state_callback=None,\n+ )\n+ except Exception:\n+ pass\n \n # room_pos:当前直播间位置计数", + "oldStart": 2738, + "newStart": 2738, + "oldLines": 4, + "newLines": 16, + "linesAdded": 12 + } + ], + "editor": "EDITOR_AI" + }, + "shouldAutoFixLints": true, + "resultForModel": "Success. Updated the following files:\nM douyin_fudai_core.py", + "contentsAfterEdit": "from __future__ import annotations\n\nimport re\nimport time\nimport os\nfrom typing import Tuple, Any\nfrom PIL import Image\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\nfrom douyin_utils import normalize_countdown_text, extract_prize_value_yuan\nimport douyin_reservation_logic\nimport path_config\n\n\ndef _save_full_screenshot_with_ocr_region(\n analyser: Any, picname: str, coords: Tuple[int, int, int, int], y_pianyi: int = 0\n) -> None:\n \"\"\"保存完整截图并标注OCR区域(用于调试)。\n\n 参数:\n analyser: 分析器对象\n picname: 图片名称(如\"福袋内容\")\n coords: OCR区域坐标 (x1, y1, x2, y2) - 基准坐标(1080x2400)\n y_pianyi: Y轴偏移\n \"\"\"\n try:\n import douyin_screenshot_manager\n\n # 读取完整截图\n pic_path = path_config.get_screenshot_path()\n if not os.path.exists(pic_path):\n return\n\n pic = Image.open(pic_path)\n pic.load()\n pic_rgb = pic.convert(\"RGB\")\n\n # 缩放坐标到实际分辨率\n width, height = pic_rgb.size\n rx = int(getattr(analyser, \"resolution_ratio_x\", 1080) or 1080)\n ry = int(getattr(analyser, \"resolution_ratio_y\", 2400) or 2400)\n\n x1_base, y1_base, x2_base, y2_base = coords\n x1 = int(x1_base * width / rx)\n y1 = int((y1_base + y_pianyi) * height / ry)\n x2 = int(x2_base * width / rx)\n y2 = int((y2_base + y_pianyi) * height / ry)\n\n # 边界检查\n x1 = max(0, min(x1, width - 1))\n y1 = max(0, min(y1, height - 1))\n x2 = max(0, min(x2, width - 1))\n y2 = max(0, min(y2, height - 1))\n\n if x1 >= x2 or y1 >= y2:\n return\n\n # 保存调试图片\n debug_path = douyin_screenshot_manager.save_debug_image(\n pic_rgb,\n operation_type=\"ocr\",\n picname=picname,\n step=\"before_ocr\",\n coords=(x1, y1, x2, y2),\n extra_info={\n \"region\": f\"({x1_base},{y1_base})-({x2_base},{y2_base})\",\n \"size\": f\"{x2_base-x1_base}x{y2_base-y1_base}\",\n \"y_offset\": y_pianyi,\n },\n )\n if debug_path:\n try:\n analyser._log_kv(\n \"[调试图像]\",\n f\"OCR识别前保存完整截图({picname})\",\n path=debug_path,\n region=f\"({x1_base},{y1_base})-({x2_base},{y2_base})\",\n )\n except Exception:\n pass\n except Exception:\n pass\n\n\ndef get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]:\n \"\"\"获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。\"\"\"\n\n def _parse_mm_ss(text: str):\n m = re.search(r\"(\\d{1,2})[::](\\d{2})\", str(text or \"\"))\n if not m:\n return None\n try:\n return int(m.group(1)), int(m.group(2))\n except Exception:\n return None\n\n def _extract_2digits(text: str) -> str:\n digits = \"\".join(ch for ch in str(text or \"\") if ch.isdigit())\n if len(digits) >= 2:\n return digits[:2]\n if len(digits) == 1:\n return \"0\" + digits\n return \"\"\n\n def _read_countdown_split(box: tuple[int, int, int, int]) -> str:\n \"\"\"将倒计时区域分割成\"分钟段\"和\"秒段\",分别OCR识别,然后组合为 mm:ss。\n\n 优化:更精确的分割方式,避免识别顺序错误。\n 倒计时格式通常是:XX:XX后开奖,其中前两位是分钟,中间两位是秒。\n \"\"\"\n try:\n x1, y1, x2, y2 = box\n w = max(1, int(x2 - x1))\n h = max(1, int(y2 - y1))\n\n # 优化:根据实际布局,倒计时通常是:分钟(2位数字框) + 冒号 + 秒(2位数字框) + 后开奖\n # 更精确的分割:前30%为分钟数字框,中间30%为秒数字框(剩余40%包含冒号和\"后开奖\")\n # 这样可以更精确地定位到数字区域,避免识别到冒号或\"后开奖\"文字\n seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框\n seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框\n\n # 保存调试截图\n try:\n _save_full_screenshot_with_ocr_region(\n analyser,\n \"福袋倒计时_分钟\",\n (x1, y1, x1 + seg1, y2),\n analyser.y_pianyi,\n )\n _save_full_screenshot_with_ocr_region(\n analyser,\n \"福袋倒计时_秒\",\n (x1 + seg1, y1, x1 + seg1 + seg2, y2),\n analyser.y_pianyi,\n )\n except Exception:\n pass\n\n # 切割分钟区域(左侧)\n analyser.cut_pic(\n x1, y1, x1 + seg1, y2, \"\", \"福袋倒计时_分钟\", analyser.y_pianyi\n )\n # 切割秒区域(中间,跳过冒号)\n analyser.cut_pic(\n x1 + seg1,\n y1,\n x1 + seg1 + seg2,\n y2,\n \"\",\n \"福袋倒计时_秒\",\n analyser.y_pianyi,\n )\n\n # 并行执行两个OCR识别\n with ThreadPoolExecutor(max_workers=2) as executor:\n future_mm = executor.submit(\n analyser.operation.analyse_pic_word, \"福袋倒计时_分钟\", 0\n )\n future_ss = executor.submit(\n analyser.operation.analyse_pic_word, \"福袋倒计时_秒\", 0\n )\n mm_raw = future_mm.result()\n ss_raw = future_ss.result()\n\n # 提取数字:分钟和秒都应该是1-2位数字\n def _extract_digits(text: str, max_digits: int = 2) -> str:\n \"\"\"提取数字,最多max_digits位\"\"\"\n digits = \"\".join(ch for ch in str(text or \"\") if ch.isdigit())\n if len(digits) > max_digits:\n return digits[:max_digits]\n if len(digits) == 1:\n return \"0\" + digits\n return digits\n\n mm = _extract_digits(mm_raw, max_digits=2)\n ss = _extract_digits(ss_raw, max_digits=2)\n\n # 分割识别已经分别识别了分钟和秒,顺序是正确的,不需要交换纠正\n # 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果)\n try:\n mm_int = int(mm) if mm else 0\n ss_int = int(ss) if ss else 0\n if ss_int >= 60:\n try:\n analyser._log_kv(\n \"福袋倒计时\",\n \"分割识别:检测到秒数>=60(可能是识别错误)\",\n mm=mm_int,\n ss=ss_int,\n mm_raw=mm_raw,\n ss_raw=ss_raw,\n )\n except Exception:\n pass\n except Exception:\n pass\n\n if mm and ss:\n result = f\"{mm}:{ss}\"\n try:\n analyser._log_kv(\n \"福袋倒计时\",\n \"分割识别成功\",\n mm_raw=mm_raw,\n ss_raw=ss_raw,\n result=result,\n )\n except Exception:\n pass\n return result\n except Exception as e:\n try:\n analyser._log_kv(\n \"福袋倒计时\",\n \"分割识别失败\",\n error=str(e),\n error_type=type(e).__name__,\n )\n except Exception:\n pass\n return \"\"\n\n def _extract_participants_and_clean(text: str):\n if not text:\n return 0, 0, \"\"\n compact = re.sub(r\"\\s+\", \"\", str(text))\n # 例如:共1份1173人已参与\n copies = 0\n participants = 0\n m = re.search(r\"共(\\d+)份\", compact)\n if m:\n copies = int(m.group(1))\n m = re.search(r\"(\\d+)人已参与\", compact)\n if m:\n participants = int(m.group(1))\n\n # 清理掉份数/参与人数等尾巴,避免干扰关键词匹配\n cleaned = re.sub(r\"共\\d+份\", \"\", compact)\n cleaned = re.sub(r\"\\d+人已参与\", \"\", cleaned)\n return participants, copies, cleaned\n\n countdown_box = None\n if renwu == 2: # 如果是2个任务的\n # 优化:扩大Y范围向上,确保包含任务描述(如\"观看X分钟\"等)\n # 从1240向上扩展到1100,确保包含任务描述区域\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋内容\", (390, 1100, 980, 1470), analyser.y_pianyi\n )\n analyser.cut_pic(\n 390, 1100, 980, 1470, \"\", \"福袋内容\", analyser.y_pianyi\n ) # 福袋内容详情(包含任务描述)\n # 优化:稍微扩大高度(1220->1230),确保包含完整的\"后开奖\"文字\n countdown_box = (390, 1110, 690, 1230)\n # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域\n x1, y1, x2, y2 = countdown_box\n w = max(1, int(x2 - x1))\n seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框\n seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋倒计时_分钟\", (x1, y1, x1 + seg1, y2), analyser.y_pianyi\n )\n analyser.cut_pic(\n x1, y1, x1 + seg1, y2, \"\", \"福袋倒计时_分钟\", analyser.y_pianyi\n )\n _save_full_screenshot_with_ocr_region(\n analyser,\n \"福袋倒计时_秒\",\n (x1 + seg1, y1, x1 + seg1 + seg2, y2),\n analyser.y_pianyi,\n )\n analyser.cut_pic(\n x1 + seg1, y1, x1 + seg1 + seg2, y2, \"\", \"福袋倒计时_秒\", analyser.y_pianyi\n )\n # 优化:增加高度(1560->1580),确保包含\"元\"等单位文字\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋价值\", (390, 1460, 1000, 1580), analyser.y_pianyi\n )\n analyser.cut_pic(\n 390, 1460, 1000, 1580, \"\", \"福袋价值\", analyser.y_pianyi\n ) # 奖品价值/价格\n elif renwu == 1: # 如果是1个任务的\n # 优化:扩大Y范围向上,确保包含任务描述\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋内容\", (390, 1160, 980, 1530), analyser.y_pianyi\n )\n analyser.cut_pic(\n 390, 1160, 980, 1530, \"\", \"福袋内容\", analyser.y_pianyi\n ) # 福袋内容详情(包含任务描述)\n # 优化:稍微扩大高度,确保完整\n countdown_box = (390, 1180, 690, 1300)\n # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域\n x1, y1, x2, y2 = countdown_box\n w = max(1, int(x2 - x1))\n seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框\n seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋倒计时_分钟\", (x1, y1, x1 + seg1, y2), analyser.y_pianyi\n )\n analyser.cut_pic(\n x1, y1, x1 + seg1, y2, \"\", \"福袋倒计时_分钟\", analyser.y_pianyi\n )\n _save_full_screenshot_with_ocr_region(\n analyser,\n \"福袋倒计时_秒\",\n (x1 + seg1, y1, x1 + seg1 + seg2, y2),\n analyser.y_pianyi,\n )\n analyser.cut_pic(\n x1 + seg1, y1, x1 + seg1 + seg2, y2, \"\", \"福袋倒计时_秒\", analyser.y_pianyi\n )\n # 优化:增加高度,包含单位\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋价值\", (390, 1520, 1000, 1630), analyser.y_pianyi\n )\n analyser.cut_pic(\n 390, 1520, 1000, 1630, \"\", \"福袋价值\", analyser.y_pianyi\n ) # 奖品价值/价格\n elif renwu == 3: # 如果是3个任务的\n # 优化:扩大Y范围向上,确保包含任务描述\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋内容\", (390, 1020, 980, 1390), analyser.y_pianyi\n )\n analyser.cut_pic(\n 390, 1020, 980, 1390, \"\", \"福袋内容\", analyser.y_pianyi\n ) # 福袋内容详情(包含任务描述)\n # 优化:稍微扩大高度\n countdown_box = (390, 1010, 690, 1130)\n # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域\n x1, y1, x2, y2 = countdown_box\n w = max(1, int(x2 - x1))\n seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框\n seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋倒计时_分钟\", (x1, y1, x1 + seg1, y2), analyser.y_pianyi\n )\n analyser.cut_pic(\n x1, y1, x1 + seg1, y2, \"\", \"福袋倒计时_分钟\", analyser.y_pianyi\n )\n _save_full_screenshot_with_ocr_region(\n analyser,\n \"福袋倒计时_秒\",\n (x1 + seg1, y1, x1 + seg1 + seg2, y2),\n analyser.y_pianyi,\n )\n analyser.cut_pic(\n x1 + seg1, y1, x1 + seg1 + seg2, y2, \"\", \"福袋倒计时_秒\", analyser.y_pianyi\n )\n # 优化:增加高度\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋价值\", (390, 1380, 1000, 1490), analyser.y_pianyi\n )\n analyser.cut_pic(\n 390, 1380, 1000, 1490, \"\", \"福袋价值\", analyser.y_pianyi\n ) # 奖品价值/价格\n else:\n # 优化:稍微缩小宽度,增加高度\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋内容\", (390, 1600, 980, 1830), analyser.y_pianyi\n )\n analyser.cut_pic(\n 390, 1600, 980, 1830, \"\", \"福袋内容\", analyser.y_pianyi\n ) # 福袋内容详情\n # 优化:稍微扩大高度\n countdown_box = (390, 1460, 690, 1580)\n # 直接进行分割裁剪(分钟和秒),不再裁剪完整倒计时区域\n x1, y1, x2, y2 = countdown_box\n w = max(1, int(x2 - x1))\n seg1 = max(1, int(w * 0.3)) # 前30%:分钟数字框\n seg2 = max(1, int(w * 0.3)) # 中间30%:秒数字框\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋倒计时_分钟\", (x1, y1, x1 + seg1, y2), analyser.y_pianyi\n )\n analyser.cut_pic(\n x1, y1, x1 + seg1, y2, \"\", \"福袋倒计时_分钟\", analyser.y_pianyi\n )\n _save_full_screenshot_with_ocr_region(\n analyser,\n \"福袋倒计时_秒\",\n (x1 + seg1, y1, x1 + seg1 + seg2, y2),\n analyser.y_pianyi,\n )\n analyser.cut_pic(\n x1 + seg1, y1, x1 + seg1 + seg2, y2, \"\", \"福袋倒计时_秒\", analyser.y_pianyi\n )\n # 优化:增加高度\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋价值\", (390, 1820, 1000, 1930), analyser.y_pianyi\n )\n analyser.cut_pic(\n 390, 1820, 1000, 1930, \"\", \"福袋价值\", analyser.y_pianyi\n ) # 奖品价值/价格\n\n # 准备任务列表区域的截图(用于并行OCR)\n # 任务列表区域(任务位置:50,1621到1032,1960),用于检测\"观看X分钟\"任务\n try:\n # 保存任务列表区域的调试截图\n _save_full_screenshot_with_ocr_region(\n analyser, \"福袋任务列表\", (50, 1621, 1032, 1960), analyser.y_pianyi\n )\n analyser.cut_pic(50, 1621, 1032, 1960, \"\", \"福袋任务列表\", analyser.y_pianyi)\n except Exception as e:\n # 任务列表截图失败不影响后续流程,记录日志即可\n try:\n analyser._log_kv(\n \"福袋\",\n \"任务列表截图失败,继续后续流程\",\n error=str(e),\n )\n except Exception:\n pass\n\n # 并行执行五个操作:OCR识别任务列表/内容/倒计时分钟/倒计时秒/价值\n # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数\n ocr_start_time = time.time()\n task_list_raw = None\n fudai_content_raw = None\n countdown_mm_raw = None\n countdown_ss_raw = None\n value_raw = None\n\n def ocr_task_list():\n \"\"\"OCR识别任务列表(用于检测观看任务)\"\"\"\n try:\n return analyser.operation.analyse_pic_word(\"福袋任务列表\", 0)\n except Exception:\n return None\n\n def ocr_content():\n \"\"\"OCR识别福袋内容\"\"\"\n try:\n return analyser.operation.analyse_pic_word(\"福袋内容\", 0)\n except Exception:\n return None\n\n def ocr_countdown_mm():\n \"\"\"OCR识别福袋倒计时分钟\"\"\"\n try:\n return analyser.operation.analyse_pic_word(\"福袋倒计时_分钟\", 0)\n except Exception:\n return None\n\n def ocr_countdown_ss():\n \"\"\"OCR识别福袋倒计时秒\"\"\"\n try:\n return analyser.operation.analyse_pic_word(\"福袋倒计时_秒\", 0)\n except Exception:\n return None\n\n def ocr_value():\n \"\"\"OCR识别福袋价值\"\"\"\n try:\n return analyser.operation.analyse_pic_word(\"福袋价值\", 0)\n except Exception:\n return None\n\n # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行)\n # 任务数量已在 detect_fudai_detail_page 中检测,直接使用传入的 renwu 参数\n try:\n with ThreadPoolExecutor(max_workers=5) as executor:\n future_task_list = executor.submit(ocr_task_list)\n future_content = executor.submit(ocr_content)\n future_countdown_mm = executor.submit(ocr_countdown_mm)\n future_countdown_ss = executor.submit(ocr_countdown_ss)\n future_value = executor.submit(ocr_value)\n\n # 等待所有操作完成\n task_list_raw = future_task_list.result()\n fudai_content_raw = future_content.result()\n countdown_mm_raw = future_countdown_mm.result()\n countdown_ss_raw = future_countdown_ss.result()\n value_raw = future_value.result()\n\n # 检查任务列表中是否包含\"观看X分钟\"任务(在并行OCR完成后检查)\n if task_list_raw:\n try:\n analyser._log_kv(\n \"福袋\",\n \"OCR识别任务列表区域\",\n task_list_text=task_list_raw[:200] if task_list_raw else \"\",\n )\n except Exception:\n pass\n # 检查任务列表中是否包含\"观看X分钟\"任务\n is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw))\n if is_watch_task_in_list:\n try:\n analyser._log_kv(\n \"福袋\",\n \"任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理\",\n task_list_text=task_list_raw[:200] if task_list_raw else \"\",\n )\n except Exception:\n pass\n # 设置标志,让调用方知道这是观看任务\n try:\n analyser._is_watch_task_detected = True\n except Exception:\n pass\n # 直接返回空内容,后续流程会跳过\n return \"\", \"\", 0, 0, 0.0\n\n ocr_elapsed = time.time() - ocr_start_time\n try:\n analyser._log_kv(\n \"性能\",\n \"并行OCR识别完成(任务数量已在前置检测中获取)\",\n elapsed_seconds=round(ocr_elapsed, 3),\n task_count=renwu,\n )\n except Exception:\n pass\n except Exception as e:\n # 如果并行执行失败,回退到备用并行执行(使用新的线程池)\n try:\n analyser._log_kv(\n \"性能\",\n \"并行OCR失败,使用备用并行执行\",\n error=str(e),\n )\n except Exception:\n pass\n # 使用线程池并行执行OCR(包括任务列表OCR,与其他OCR一起并行执行)\n try:\n\n def ocr_task_list_fallback():\n try:\n return analyser.operation.analyse_pic_word(\"福袋任务列表\", 0)\n except Exception:\n return None\n\n def ocr_content_fallback():\n try:\n return analyser.operation.analyse_pic_word(\"福袋内容\", 0)\n except Exception:\n return None\n\n def ocr_countdown_mm_fallback():\n try:\n return analyser.operation.analyse_pic_word(\"福袋倒计时_分钟\", 0)\n except Exception:\n return None\n\n def ocr_countdown_ss_fallback():\n try:\n return analyser.operation.analyse_pic_word(\"福袋倒计时_秒\", 0)\n except Exception:\n return None\n\n def ocr_value_fallback():\n try:\n return analyser.operation.analyse_pic_word(\"福袋价值\", 0)\n except Exception:\n return None\n\n with ThreadPoolExecutor(max_workers=5) as executor:\n future_task_list = executor.submit(ocr_task_list_fallback)\n future_content = executor.submit(ocr_content_fallback)\n future_countdown_mm = executor.submit(ocr_countdown_mm_fallback)\n future_countdown_ss = executor.submit(ocr_countdown_ss_fallback)\n future_value = executor.submit(ocr_value_fallback)\n\n # 等待所有操作完成\n task_list_raw = future_task_list.result()\n fudai_content_raw = future_content.result()\n countdown_mm_raw = future_countdown_mm.result()\n countdown_ss_raw = future_countdown_ss.result()\n value_raw = future_value.result()\n\n # 检查任务列表中是否包含\"观看X分钟\"任务(在并行OCR完成后检查)\n if task_list_raw:\n try:\n analyser._log_kv(\n \"福袋\",\n \"OCR识别任务列表区域(备用并行)\",\n task_list_text=task_list_raw[:200] if task_list_raw else \"\",\n )\n except Exception:\n pass\n # 检查任务列表中是否包含\"观看X分钟\"任务\n is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw))\n if is_watch_task_in_list:\n try:\n analyser._log_kv(\n \"福袋\",\n \"任务列表OCR识别到'观看X分钟'类任务,直接跳过后续处理\",\n task_list_text=task_list_raw[:200] if task_list_raw else \"\",\n )\n except Exception:\n pass\n # 设置标志,让调用方知道这是观看任务\n try:\n analyser._is_watch_task_detected = True\n except Exception:\n pass\n # 直接返回空内容,后续流程会跳过\n return \"\", \"\", 0, 0, 0.0\n except Exception as fallback_error:\n # 如果备用并行执行也失败,使用串行执行作为最后兜底\n try:\n analyser._log_kv(\n \"性能\",\n \"备用并行OCR也失败,使用串行执行作为最后兜底\",\n error=str(fallback_error),\n )\n except Exception:\n pass\n # 串行执行所有OCR(包括任务列表OCR)\n try:\n task_list_raw = analyser.operation.analyse_pic_word(\"福袋任务列表\", 0)\n # 检查任务列表中是否包含\"观看X分钟\"任务\n if task_list_raw:\n is_watch_task_in_list = is_watch_task_fudai(str(task_list_raw))\n if is_watch_task_in_list:\n try:\n analyser._is_watch_task_detected = True\n except Exception:\n pass\n return \"\", \"\", 0, 0, 0.0\n except Exception:\n pass\n fudai_content_raw = analyser.operation.analyse_pic_word(\"福袋内容\", 0)\n countdown_mm_raw = analyser.operation.analyse_pic_word(\"福袋倒计时_分钟\", 0)\n countdown_ss_raw = analyser.operation.analyse_pic_word(\"福袋倒计时_秒\", 0)\n value_raw = analyser.operation.analyse_pic_word(\"福袋价值\", 0)\n\n # 先检查原始OCR内容是否是\"观看X分钟\"任务(在清理之前检查,避免丢失关键信息)\n is_watch_task = False\n if fudai_content_raw:\n try:\n is_watch_task = is_watch_task_fudai(str(fudai_content_raw))\n if is_watch_task:\n try:\n analyser._log_kv(\n \"福袋\",\n \"OCR识别到'观看X分钟'类任务,直接跳过后续处理\",\n raw_content=(\n fudai_content_raw[:100] if fudai_content_raw else \"\"\n ),\n )\n except Exception:\n pass\n # 设置标志,让调用方知道这是观看任务\n try:\n analyser._is_watch_task_detected = True\n except Exception:\n pass\n # 直接返回空内容,后续流程会跳过\n return \"\", \"\", 0, 0, 0.0\n except Exception:\n pass\n\n participants, copies, fudai_content_text = _extract_participants_and_clean(\n fudai_content_raw\n )\n\n # 如果清理后的内容中没有检测到,但原始内容中检测到了,使用原始内容再次确认\n if not is_watch_task and fudai_content_text:\n try:\n is_watch_task = is_watch_task_fudai(fudai_content_text)\n if is_watch_task:\n try:\n analyser._log_kv(\n \"福袋\",\n \"OCR识别到'观看X分钟'类任务(清理后检测),直接跳过后续处理\",\n content=fudai_content_text[:100] if fudai_content_text else \"\",\n )\n except Exception:\n pass\n # 设置标志\n try:\n analyser._is_watch_task_detected = True\n except Exception:\n pass\n # 直接返回空内容,后续流程会跳过\n return \"\", \"\", 0, 0, 0.0\n except Exception:\n pass\n\n analyser._log_kv(\n \"福袋\",\n \"识别福袋内容\",\n level=\"INFO\",\n content=fudai_content_text[:60] if fudai_content_text else \"未识别到\",\n )\n\n # 记录进入直播间到识别到福袋的耗时(仅记录一次)\n try:\n if getattr(analyser, \"_enter_live_ts\", 0.0) and not getattr(\n analyser, \"_enter_live_fudai_logged\", False\n ):\n try:\n secs = float(time.time() - float(analyser._enter_live_ts or 0.0))\n except Exception:\n secs = -1.0\n reason = str(getattr(analyser, \"_enter_live_reason\", \"\") or \"\")\n analyser._log_kv(\n \"性能\",\n \"进入直播间到识别福袋耗时\",\n seconds=round(secs, 2),\n enter_reason=reason,\n )\n try:\n analyser._enter_live_fudai_logged = True\n except Exception:\n pass\n if copies:\n analyser._log_kv(\n \"福袋\",\n \"识别福袋信息\",\n copies=copies,\n participants=participants if participants else 0,\n )\n except Exception:\n pass\n\n # 倒计时:直接使用分割OCR结果(分钟+秒),不再使用完整OCR\n time_text = \"\" # 初始化为空字符串,确保类型为 str\n try:\n # 提取数字:分钟和秒都应该是1-2位数字\n def _extract_digits(text: str, max_digits: int = 2) -> str:\n \"\"\"提取数字,最多max_digits位\"\"\"\n digits = \"\".join(ch for ch in str(text or \"\") if ch.isdigit())\n if len(digits) > max_digits:\n return digits[:max_digits]\n if len(digits) == 1:\n return \"0\" + digits\n return digits\n\n mm = _extract_digits(countdown_mm_raw, max_digits=2) if countdown_mm_raw else \"\"\n ss = _extract_digits(countdown_ss_raw, max_digits=2) if countdown_ss_raw else \"\"\n\n # 如果秒数 >= 60,可能是识别错误,记录日志但不交换(保持原始识别结果)\n try:\n mm_int = int(mm) if mm else 0\n ss_int = int(ss) if ss else 0\n if ss_int >= 60:\n try:\n analyser._log_kv(\n \"福袋倒计时\",\n \"分割识别:检测到秒数>=60(可能是识别错误)\",\n mm=mm_int,\n ss=ss_int,\n mm_raw=countdown_mm_raw,\n ss_raw=countdown_ss_raw,\n )\n except Exception:\n pass\n except Exception:\n pass\n\n if mm and ss:\n time_text = f\"{mm}:{ss}\"\n try:\n analyser._log_kv(\n \"福袋倒计时\",\n \"分割识别成功\",\n mm_raw=countdown_mm_raw,\n ss_raw=countdown_ss_raw,\n result=time_text,\n )\n except Exception:\n pass\n else:\n # 识别失败,time_text 保持为空字符串\n try:\n analyser._log_kv(\n \"福袋倒计时\",\n \"分割识别失败(分钟或秒为空)\",\n mm_raw=countdown_mm_raw,\n ss_raw=countdown_ss_raw,\n )\n except Exception:\n pass\n except Exception as e:\n # 异常时,time_text 保持为空字符串\n try:\n analyser._log_kv(\n \"福袋倒计时\",\n \"分割识别异常\",\n error=str(e),\n error_type=type(e).__name__,\n )\n except Exception:\n pass\n analyser._log_kv(\n \"福袋\", \"识别倒计时\", countdown=time_text if time_text else \"未识别到\"\n )\n\n prize_value_yuan = extract_prize_value_yuan(value_raw)\n if prize_value_yuan:\n if float(prize_value_yuan).is_integer():\n show_value = int(prize_value_yuan)\n else:\n show_value = prize_value_yuan\n analyser._log_kv(\"福袋\", \"识别奖品价值\", value_yuan=show_value)\n\n return fudai_content_text, time_text, participants, copies, prize_value_yuan\n\n\ndef check_contain(analyser, contains: str = \"\") -> bool:\n \"\"\"检查福袋内容是否命中“黑名单”关键词(只保留黑名单逻辑,不再使用白名单)。\n\n 返回值语义(调整后):\n - True : “建议丢弃”(内容命中黑名单 contains_not_want)\n - False : “可以保留”(未命中黑名单,或凌晨时段不做内容过滤)\n \"\"\"\n try:\n hour = int(analyser.operation.get_current_hour())\n except Exception:\n hour = -1\n\n # 凌晨:不对内容做要求(不过滤)\n if 0 < hour < 7:\n try:\n analyser._log_kv(\n \"筛选\",\n \"凌晨不过滤福袋内容\",\n hour=hour,\n contains=contains[:50] if contains else \"\",\n )\n except Exception:\n pass\n return False\n\n try:\n for contain in getattr(analyser, \"contains_not_want\", []) or []:\n if contain and contain in (contains or \"\"):\n try:\n analyser._log_kv(\n \"筛选\",\n \"福袋内容命中黑名单,将丢弃\",\n keyword=contain,\n contains=contains[:80] if contains else \"\",\n )\n except Exception:\n pass\n return True\n\n try:\n analyser._log_kv(\n \"筛选\",\n \"福袋内容未命中黑名单,保留\",\n contains=contains[:80] if contains else \"\",\n )\n except Exception:\n pass\n return False\n except Exception:\n # 容错:异常时不过滤\n try:\n analyser._log_kv(\n \"筛选\",\n \"check_contain 异常,默认保留\",\n contains=contains[:80] if contains else \"\",\n )\n except Exception:\n pass\n return False\n\n\ndef attend_choujiang(analyser) -> bool:\n \"\"\"点击参与抽奖。\"\"\"\n analyser.last_attend_fail_reason = \"\"\n click_times = 0\n while click_times < 2:\n analyser.cut_pic(306, 2030, 780, 2110, \"\", \"参与按钮\") # 参与福袋抽奖的文字\n # 优化:尝试多种OCR模式提高精准度(优先保证精准)\n attend_button_text = str(\n analyser.operation.analyse_pic_word(\"参与按钮\", 0) or \"\"\n )\n if not attend_button_text or not any(\n k in attend_button_text\n for k in (\n \"参与成功\",\n \"还需看播\",\n \"评论\",\n \"参与抽奖\",\n \"开始观看\",\n \"参与\",\n \"加入粉丝团\",\n \"粉丝团\",\n )\n ):\n attend_button_text = str(\n analyser.operation.analyse_pic_word(\"参与按钮\", 1) or \"\"\n )\n analyser._log_kv(\"参与\", \"识别参与按钮\", text=attend_button_text)\n if \"参与成功\" in attend_button_text: # 如果识别到已经参与抽奖\n analyser._log_kv(\"参与\", \"已参与,等待开奖\", result=\"已参与\")\n # 记录最后一次成功参与的时间\n try:\n analyser._last_successful_attend_ts = time.time()\n except Exception:\n pass\n\n # 记录已参与的福袋(通过 future_ts 标识),避免重复参与\n try:\n # 从 detail 中获取 future_ts(如果可用)\n future_ts = getattr(analyser, \"_current_fudai_future_ts\", 0.0) or 0.0\n if future_ts > 0:\n participated_fudai_ts = getattr(\n analyser, \"_participated_fudai_future_ts\", set()\n )\n if not isinstance(participated_fudai_ts, set):\n participated_fudai_ts = set()\n participated_fudai_ts.add(future_ts)\n analyser._participated_fudai_future_ts = participated_fudai_ts\n analyser._log_kv(\n \"参与\",\n \"记录已参与福袋\",\n future_ts=future_ts,\n total_participated=len(participated_fudai_ts),\n )\n except Exception:\n pass\n\n # 设置标志:已经关闭了详情,避免后续再次点击返回键\n try:\n analyser._detail_closed_by_attend = True\n except Exception:\n pass\n\n analyser.click(500, 470) # 点击刚才打开福袋的旁边位置\n analyser._log_kv(\"参与\", \"关闭福袋详情\", action=\"关闭详情\")\n return True\n elif (\"活动已结束\" in attend_button_text) or (\n \"活动己结束\" in attend_button_text\n ):\n # 活动结束:按一次返回键退出详情\n analyser.last_attend_fail_reason = \"activity_ended\"\n try:\n analyser._log_kv(\n \"参与\", \"活动已结束:按返回键退出详情\", result=\"activity_ended\"\n )\n except Exception:\n pass\n try:\n analyser.operation.click_back(analyser.device_id)\n analyser.operation.delay(0.5)\n except Exception:\n try:\n analyser.click(500, 470)\n except Exception:\n pass\n return False\n elif \"还需看播\" in attend_button_text: # 如果识别到需要看播\n analyser.last_attend_fail_reason = \"watch_required\"\n analyser._log_kv(\"参与\", \"需要看播时长:默认不参与\", result=\"看播门槛\")\n analyser.click(500, 470)\n analyser._log_kv(\"参与\", \"关闭福袋详情\", action=\"关闭详情\")\n return False\n elif \"无法参与\" in attend_button_text:\n analyser._log_kv(\"参与\", \"无法参与(条件不满足)\", result=\"无法参与\")\n analyser.click(500, 470)\n analyser._log_kv(\"参与\", \"关闭福袋详情\", action=\"关闭详情\")\n return False\n elif \"时长不足\" in attend_button_text:\n analyser._log_kv(\"参与\", \"无法参与(看播时长不足)\", result=\"时长不足\")\n analyser.click(500, 470)\n analyser._log_kv(\"参与\", \"关闭福袋详情\", action=\"关闭详情\")\n return False\n elif \"评论\" in attend_button_text:\n # 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80\n # 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070\n analyser.click(543, 2070)\n analyser._log_kv(\n \"参与\",\n \"点击参与抽奖(基于截图优化坐标)\",\n action=\"点击参与\",\n mode=\"评论\",\n base_x=543,\n base_y=2070,\n region=\"(306,2030)-(780,2110)\",\n )\n return True\n elif \"参与抽奖\" in attend_button_text:\n # 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80\n # 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070\n analyser.click(543, 2070)\n analyser._log_kv(\n \"参与\",\n \"点击参与抽奖(基于截图优化坐标)\",\n action=\"点击参与\",\n mode=\"普通\",\n base_x=543,\n base_y=2070,\n region=\"(306,2030)-(780,2110)\",\n )\n\n # 设置标志:点击参与抽奖后直接查找福袋,跳过阶段检测\n # 注意:点击参与按钮后会自动关闭详情页,返回直播间\n try:\n analyser._skip_stage_diagnosis_and_find_fudai = True\n except Exception:\n pass\n\n analyser._log_kv(\n \"参与\",\n \"点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测\",\n )\n return True\n elif \"加入粉丝团\" in attend_button_text or \"粉丝团\" in attend_button_text:\n # 需要粉丝团门槛:先点击参与按钮,再点击一次预设位置,最后关闭详情页\n analyser.last_attend_fail_reason = \"fansclub_required\"\n # 第一步:先点击参与按钮(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070))\n analyser.click(543, 2070)\n analyser._log_kv(\n \"参与\",\n \"粉丝团门槛:先点击参与按钮\",\n result=\"需要粉丝团\",\n base_x=543,\n base_y=2070,\n region=\"(306,2030)-(780,2110)\",\n )\n analyser.operation.delay(1.0) # 等待参与按钮响应稍长一些,避免过快\n\n # 第二步:点击一次预设位置(527, 567)\n try:\n rx = int(getattr(analyser, \"resolution_ratio_x\", 1080) or 1080)\n ry = int(getattr(analyser, \"resolution_ratio_y\", 2400) or 2400)\n preset_x = int(527 * rx // 1080)\n preset_y = int(567 * ry // 2400)\n\n # 点击预设位置\n analyser.operation.click(analyser.device_id, preset_x, preset_y)\n analyser._log_kv(\n \"参与\",\n \"粉丝团门槛:点击预设位置\",\n x=preset_x,\n y=preset_y,\n base_x=527,\n base_y=567,\n )\n analyser.operation.delay(1.2) # 等待点击完成(适当延长)\n except Exception as e:\n analyser._log_kv(\"参与\", \"点击预设位置失败\", error=str(e))\n\n # 第三步:关闭详情页\n analyser.click(500, 470) # 点击详情页旁边位置关闭详情页\n analyser._log_kv(\"参与\", \"关闭福袋详情\", action=\"关闭详情\")\n\n if not analyser.auto_join_fansclub:\n analyser._log_kv(\n \"参与\", \"未启用自动加粉丝团:等待手动确认\", wait_seconds=15\n )\n analyser.operation.delay(15)\n\n # 点击粉丝团按钮后,可能进入“加入粉丝团”独立页面:需要在该页再次点击“加入粉丝团”才能成功。\n def _recover_to_fudai_detail_after_fansclub(max_steps: int = 4) -> bool:\n for i in range(int(max_steps or 4)):\n try:\n analyser._shot_and_diagnose(\n \"粉丝团\",\n \"粉丝团后定位福袋详情({}/{})\".format(i + 1, max_steps),\n analyser.device_id,\n )\n except Exception:\n pass\n try:\n st, seen = analyser._diagnose_stage_from_current_screen()\n except Exception:\n st, seen = \"\", \"\"\n\n if st == \"FUDai_DETAIL\":\n return True\n\n if st == \"FANSCLUB_JOIN\":\n # 在加入页点击底部\"加入粉丝团\"按钮(与详情页按钮同位置)\n analyser._log_kv(\n \"参与\",\n \"粉丝团加入页:点击加入粉丝团\",\n stage=st,\n seen=seen,\n attempt=i + 1,\n )\n try:\n # 点击加入粉丝团按钮\n # 基于实际截图分析:OCR区域 (200, 1940, 880, 2140),尺寸680x200\n # 按钮上部66%是红色区域(文字\"加入粉丝团\"所在),高度约132像素\n # 红色区域Y范围:1940 到 2072,中心Y = 1940 + 132/2 = 2006\n # 使用区域中心X = (200+880)/2 = 540,Y = 2006(红色区域中心)\n rx = int(\n getattr(analyser, \"resolution_ratio_x\", 1080) or 1080\n )\n ry = int(\n getattr(analyser, \"resolution_ratio_y\", 2400) or 2400\n )\n # 点击红色文字区域的中心(基于截图分析优化)\n click_x = int(540 * rx // 1080) # 区域中心X\n click_y = int(\n 2006 * ry // 2400\n ) # 红色区域中心Y(基于截图:1940+132/2=2006)\n # 第一次点击\n analyser.operation.click(\n analyser.device_id, click_x, click_y\n )\n analyser._log_kv(\n \"参与\",\n \"恢复流程:第一次点击加入粉丝团按钮(基于截图优化坐标)\",\n x=click_x,\n y=click_y,\n base_x=540,\n base_y=2006,\n region=\"(200,1940)-(880,2140)\",\n red_area_center_y=2006,\n )\n analyser.operation.delay(0.5) # 短暂等待后立即第二次点击\n # 第二次点击(连续点击两次确保成功)\n analyser.operation.click(\n analyser.device_id, click_x, click_y\n )\n analyser._log_kv(\n \"参与\",\n \"恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)\",\n x=click_x,\n y=click_y,\n )\n # 两次点击后,立即点击 (527, 567) 返回直播间\n analyser.operation.delay(0.5) # 短暂等待\n try:\n rx = int(\n getattr(analyser, \"resolution_ratio_x\", 1080)\n or 1080\n )\n ry = int(\n getattr(analyser, \"resolution_ratio_y\", 2400)\n or 2400\n )\n return_x = int(527 * rx // 1080)\n return_y = int(567 * ry // 2400)\n analyser.operation.click(\n analyser.device_id, return_x, return_y\n )\n analyser._log_kv(\n \"参与\",\n \"恢复流程:两次点击后,点击返回直播间\",\n x=return_x,\n y=return_y,\n base_x=527,\n base_y=567,\n )\n analyser.operation.delay(1.0) # 等待返回完成\n except Exception as e:\n analyser._log_kv(\n \"参与\", \"恢复流程:点击返回直播间失败\", error=str(e)\n )\n except Exception:\n # 如果新坐标失败,回退到优化后的坐标(粉丝团加入按钮)\n try:\n analyser.click(540, 2006) # 粉丝团加入按钮优化坐标\n except Exception:\n # 最后回退到旧坐标\n try:\n analyser.click(500, 2060)\n except Exception:\n pass\n\n # 等待加入流程完成(根据是否启用自动加入决定等待时间)\n auto_join_enabled = getattr(\n analyser, \"auto_join_fansclub\", False\n )\n if auto_join_enabled:\n # 启用自动加入:等待更长时间,让加入流程完成\n analyser.operation.delay(5.0)\n analyser._log_kv(\n \"参与\",\n \"已启用自动加入粉丝团,等待加入流程完成\",\n wait_seconds=5.0,\n )\n else:\n # 未启用自动加入:等待较短时间后返回\n analyser.operation.delay(3.0)\n analyser._log_kv(\n \"参与\",\n \"未启用自动加入粉丝团,等待后返回\",\n wait_seconds=3.0,\n )\n\n # 加入粉丝团成功后,点击 (527, 567) 返回直播间\n try:\n rx = int(\n getattr(analyser, \"resolution_ratio_x\", 1080) or 1080\n )\n ry = int(\n getattr(analyser, \"resolution_ratio_y\", 2400) or 2400\n )\n return_x = int(527 * rx // 1080)\n return_y = int(567 * ry // 2400)\n analyser.operation.click(\n analyser.device_id, return_x, return_y\n )\n analyser._log_kv(\n \"参与\",\n \"加入粉丝团成功后,点击返回直播间\",\n x=return_x,\n y=return_y,\n base_x=527,\n base_y=567,\n )\n analyser.operation.delay(1.0) # 等待返回完成\n except Exception as e:\n analyser._log_kv(\"参与\", \"点击返回直播间失败\", error=str(e))\n\n # 重新诊断阶段,确认是否还在粉丝团加入页\n try:\n analyser.operation.get_screenshot(analyser.device_id)\n st_after, seen_after = (\n analyser._diagnose_stage_from_current_screen()\n )\n analyser._log_kv(\n \"参与\",\n \"点击加入粉丝团后重新诊断阶段\",\n stage_before=st,\n stage_after=st_after,\n seen_after=seen_after,\n )\n\n if st_after == \"FANSCLUB_JOIN\":\n # 仍在粉丝团加入页,说明可能需要再次点击或等待更长时间\n if auto_join_enabled:\n # 如果启用了自动加入,尝试再次点击\n analyser._log_kv(\n \"参与\", \"仍在粉丝团加入页,尝试再次点击\"\n )\n try:\n # 基于截图优化坐标:红色区域中心Y=2006\n rx = int(\n getattr(\n analyser, \"resolution_ratio_x\", 1080\n )\n or 1080\n )\n ry = int(\n getattr(\n analyser, \"resolution_ratio_y\", 2400\n )\n or 2400\n )\n click_x = int(540 * rx // 1080)\n click_y = int(\n 2006 * ry // 2400\n ) # 红色区域中心Y=2006\n # 第一次点击\n analyser.operation.click(\n analyser.device_id, click_x, click_y\n )\n analyser._log_kv(\n \"参与\",\n \"恢复流程:再次第一次点击加入粉丝团按钮(基于截图优化坐标)\",\n x=click_x,\n y=click_y,\n base_y=2006,\n )\n analyser.operation.delay(\n 0.5\n ) # 短暂等待后立即第二次点击\n # 第二次点击(连续点击两次确保成功)\n analyser.operation.click(\n analyser.device_id, click_x, click_y\n )\n analyser._log_kv(\n \"参与\",\n \"恢复流程:再次第二次点击加入粉丝团按钮(基于截图优化坐标)\",\n x=click_x,\n y=click_y,\n )\n # 两次点击后,立即点击 (527, 567) 返回直播间\n analyser.operation.delay(0.5) # 短暂等待\n try:\n return_x = int(527 * rx // 1080)\n return_y = int(567 * ry // 2400)\n analyser.operation.click(\n analyser.device_id, return_x, return_y\n )\n analyser._log_kv(\n \"参与\",\n \"恢复流程:再次两次点击后,点击返回直播间\",\n x=return_x,\n y=return_y,\n base_x=527,\n base_y=567,\n )\n analyser.operation.delay(\n 1.0\n ) # 等待返回完成\n except Exception as e:\n analyser._log_kv(\n \"参与\",\n \"恢复流程:再次点击返回直播间失败\",\n error=str(e),\n )\n analyser.operation.delay(3.0)\n except Exception:\n # 回退到优化后的坐标(粉丝团加入按钮)\n try:\n analyser.click(540, 2006) # 第一次点击\n analyser.operation.delay(0.5)\n analyser.click(\n 540, 2006\n ) # 第二次点击(连续点击两次确保成功)\n # 两次点击后,立即点击 (527, 567) 返回直播间\n analyser.operation.delay(0.5) # 短暂等待\n try:\n rx = int(\n getattr(\n analyser,\n \"resolution_ratio_x\",\n 1080,\n )\n or 1080\n )\n ry = int(\n getattr(\n analyser,\n \"resolution_ratio_y\",\n 2400,\n )\n or 2400\n )\n return_x = int(527 * rx // 1080)\n return_y = int(567 * ry // 2400)\n analyser.operation.click(\n analyser.device_id,\n return_x,\n return_y,\n )\n analyser._log_kv(\n \"参与\",\n \"恢复流程:回退逻辑两次点击后,点击返回直播间\",\n x=return_x,\n y=return_y,\n base_x=527,\n base_y=567,\n )\n analyser.operation.delay(\n 1.0\n ) # 等待返回完成\n except Exception as e:\n analyser._log_kv(\n \"参与\",\n \"恢复流程:回退逻辑点击返回直播间失败\",\n error=str(e),\n )\n analyser.operation.delay(3.0)\n except Exception:\n # 最后回退到旧坐标\n try:\n analyser.click(500, 2060)\n analyser.operation.delay(3.0)\n except Exception:\n pass\n else:\n # 未启用自动加入,直接返回\n analyser._log_kv(\n \"参与\", \"仍在粉丝团加入页,未启用自动加入,返回\"\n )\n try:\n analyser.operation.click_back(\n analyser.device_id\n )\n analyser.operation.delay(1)\n except Exception:\n pass\n elif st_after == \"FUDai_DETAIL\":\n # 已经回到福袋详情页,说明加入成功\n analyser._log_kv(\n \"参与\", \"已回到福袋详情页,加入流程可能已完成\"\n )\n return True\n elif st_after in (\n \"IN_LIVE_ROOM\",\n \"FOLLOW_LIST\",\n \"LIVE_LIST\",\n ):\n # 如果之前是在粉丝团加入页,现在显示在直播间,可能是误判\n # 实际上可能还在加入成功的页面,需要点击返回键\n analyser._log_kv(\n \"参与\",\n \"点击加入粉丝团后显示在直播间(可能误判),尝试点击返回键\",\n stage_before=\"FANSCLUB_JOIN\",\n stage_after=st_after,\n )\n try:\n analyser.operation.click_back(analyser.device_id)\n analyser.operation.delay(1.0)\n # 点击返回后再次诊断,看是否回到福袋详情页\n try:\n analyser.operation.get_screenshot(\n analyser.device_id\n )\n st_after_back, seen_after_back = (\n analyser._diagnose_stage_from_current_screen()\n )\n analyser._log_kv(\n \"参与\",\n \"点击返回后重新诊断阶段\",\n stage_after_back=st_after_back,\n seen_after_back=seen_after_back,\n )\n if st_after_back == \"FUDai_DETAIL\":\n analyser._log_kv(\n \"参与\", \"点击返回后已回到福袋详情页\"\n )\n return True\n elif st_after_back in (\n \"IN_LIVE_ROOM\",\n \"FOLLOW_LIST\",\n \"LIVE_LIST\",\n ):\n analyser._log_kv(\n \"参与\",\n \"点击返回后确实回到直播间,停止继续返回\",\n stage=st_after_back,\n )\n return False\n except Exception:\n pass\n except Exception:\n pass\n return False\n else:\n # 其他阶段,尝试返回\n analyser._log_kv(\n \"参与\",\n \"点击后进入其他阶段,尝试返回\",\n stage=st_after,\n )\n try:\n analyser.operation.click_back(analyser.device_id)\n analyser.operation.delay(1)\n except Exception:\n pass\n except Exception as e:\n # 诊断失败,保守处理:如果启用了自动加入,不返回;否则返回\n analyser._log_kv(\"参与\", \"重新诊断阶段失败\", error=str(e))\n if not auto_join_enabled:\n try:\n analyser.operation.click_back(analyser.device_id)\n analyser.operation.delay(1)\n except Exception:\n pass\n continue\n\n # 已经回到直播间/列表时:尝试重新打开福袋详情页\n if st in (\"IN_LIVE_ROOM\", \"FOLLOW_LIST\", \"LIVE_LIST\"):\n analyser._log_kv(\n \"参与\",\n \"已离开福袋详情:尝试重新打开福袋详情页\",\n stage=st,\n seen=seen,\n )\n # 尝试重新打开福袋详情页\n try:\n # 延迟导入避免循环导入\n import douyin_flow_control\n\n room_pos_ref = [0]\n opened = douyin_flow_control.find_and_open_fudai_detail(\n analyser, room_pos_ref\n )\n if opened:\n # 验证是否成功打开福袋详情页\n analyser.operation.delay(0.5)\n try:\n analyser.operation.get_screenshot(\n analyser.device_id\n )\n st_after, seen_after = (\n analyser._diagnose_stage_from_current_screen()\n )\n if st_after == \"FUDai_DETAIL\":\n analyser._log_kv(\n \"参与\",\n \"重新打开福袋详情页成功\",\n stage=st_after,\n )\n return True\n else:\n analyser._log_kv(\n \"参与\",\n \"重新打开福袋详情页后未在详情页\",\n stage=st_after,\n seen=seen_after,\n )\n except Exception as e:\n analyser._log_kv(\n \"参与\",\n \"重新打开后验证阶段失败\",\n error=str(e),\n )\n except Exception as e:\n analyser._log_kv(\n \"参与\", \"重新打开福袋详情页失败\", error=str(e)\n )\n # 如果重新打开失败,返回 False\n return False\n\n # 其它未知弹窗:尝试一次返回\n analyser._log_kv(\n \"参与\", \"粉丝团流程:尝试返回\", stage=st, seen=seen\n )\n try:\n analyser.operation.click_back(analyser.device_id)\n except Exception:\n pass\n analyser.operation.delay(1)\n return False\n\n ok = _recover_to_fudai_detail_after_fansclub()\n if ok:\n analyser._log_kv(\n \"参与\", \"粉丝团流程结束:已回到福袋详情\", result=\"回到详情\"\n )\n return attend_choujiang(analyser)\n\n analyser._log_kv(\n \"参与\", \"粉丝团流程失败:未回到福袋详情\", result=\"粉丝团门槛仍未解决\"\n )\n analyser.operation.delay(1.2)\n try:\n analyser.operation.get_screenshot(analyser.device_id)\n except Exception:\n pass\n if analyser.check_in_fudai_detail():\n analyser._log_kv(\n \"参与\", \"粉丝团流程失败:仍在详情页,执行关闭\", stage=\"FUDai_DETAIL\"\n )\n try:\n analyser.click(500, 470)\n except Exception:\n pass\n analyser.operation.delay(0.8)\n else:\n analyser._log_kv(\n \"参与\", \"粉丝团流程失败:已不在详情页,视为已退出\", stage=\"UNKNOWN\"\n )\n try:\n analyser._log_kv(\n \"参与\", \"粉丝团门槛仍未解决\", result=\"粉丝团门槛仍未解决\"\n )\n except Exception:\n pass\n return False\n else:\n # 未识别到任何可用文案:再尝试一次\n analyser._log_kv(\n \"参与\", \"未识别到可用参与按钮文案\", text=attend_button_text or \"\"\n )\n click_times += 1\n analyser.operation.delay(1)\n continue\n analyser._log_kv(\"参与\", \"参与抽奖多次点击失败\", result=\"多次失败\")\n return False\n\n\ndef check_lucky_draw_result(analyser):\n \"\"\"判定福袋抽奖的结果。\"\"\"\n # 速度优化:只在需要时截图(如果有最近截图且缓存有效,可跳过)\n cache_key = (\"lucky_draw_result\", 0)\n now = time.time()\n need_screenshot = True\n\n # 检查缓存是否有效\n if cache_key in analyser._ocr_cache:\n cached_ts, cached_result = analyser._ocr_cache[cache_key]\n if (\n (now - cached_ts) < 0.5\n and cached_result\n and (\"没有抽中\" in cached_result or \"抽中福袋\" in cached_result)\n ):\n need_screenshot = False\n\n if need_screenshot:\n analyser._shot_and_diagnose(\n \"开奖结果\", \"识别是否中奖/未中奖\", analyser.device_id\n )\n # 优化:扩大区域(300-800, 600-800),确保包含完整的开奖结果文字\"没有抽中福袋\"\n analyser.cut_pic(300, 600, 800, 800, \"\", \"抽奖结果\") # 没有抽中福袋位置\n\n # 诊断开始时间\n t0 = time.time()\n\n # 检查缓存\n if cache_key in analyser._ocr_cache:\n cached_ts, cached_result = analyser._ocr_cache[cache_key]\n if (now - cached_ts) < analyser._ocr_cache_ttl:\n lucky_draw_result = cached_result\n else:\n lucky_draw_result = str(\n analyser.operation.analyse_pic_word(\"抽奖结果\", 0) or \"\"\n )\n if not lucky_draw_result or (\n \"没有抽中\" not in lucky_draw_result\n and \"抽中福袋\" not in lucky_draw_result\n ):\n lucky_draw_result = str(\n analyser.operation.analyse_pic_word(\"抽奖结果\", 1) or \"\"\n )\n analyser._ocr_cache[cache_key] = (now, lucky_draw_result)\n else:\n lucky_draw_result = str(\n analyser.operation.analyse_pic_word(\"抽奖结果\", 0) or \"\"\n )\n if not lucky_draw_result or (\n \"没有抽中\" not in lucky_draw_result and \"抽中福袋\" not in lucky_draw_result\n ):\n lucky_draw_result = str(\n analyser.operation.analyse_pic_word(\"抽奖结果\", 1) or \"\"\n )\n analyser._ocr_cache[cache_key] = (now, lucky_draw_result)\n\n dur = time.time() - t0\n try:\n brief = (lucky_draw_result or \"\").replace(\"\\n\", \" \")[:140]\n except Exception:\n brief = \"\"\n try:\n analyser._log_kv(\n \"开奖诊断\",\n \"lucky_draw_result\",\n brief=brief,\n ocr_dur=round(dur, 2),\n )\n except Exception:\n pass\n\n if \"没有抽中\" in (lucky_draw_result or \"\"):\n # 速度优化:使用缓存避免重复OCR\n cache_key2 = (\"no_award_confirm\", 0)\n dur2 = 0.0 # Initialize dur2 to avoid unbound variable\n if cache_key2 in analyser._ocr_cache:\n cached_ts2, cached_result2 = analyser._ocr_cache[cache_key2]\n if (now - cached_ts2) < analyser._ocr_cache_ttl:\n no_award_confirm = cached_result2\n else:\n t1 = time.time()\n analyser.cut_pic(181, 1261, 890, 1389, \"\", \"无奖励确认\")\n no_award_confirm = analyser.operation.analyse_pic_word(\"无奖励确认\")\n analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm)\n dur2 = time.time() - t1\n else:\n t1 = time.time()\n analyser.cut_pic(181, 1261, 890, 1389, \"\", \"无奖励确认\")\n no_award_confirm = analyser.operation.analyse_pic_word(\"无奖励确认\")\n analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm)\n dur2 = time.time() - t1\n try:\n brief2 = (no_award_confirm or \"\").replace(\"\\n\", \" \")[:140]\n except Exception:\n brief2 = \"\"\n try:\n analyser._log_kv(\n \"开奖诊断\",\n \"no_award_confirm\",\n brief=brief2,\n ocr_dur=round(dur2, 2),\n )\n except Exception:\n pass\n if \"我知道了\" in (no_award_confirm or \"\"):\n return 1\n elif \"领取并使用\" in (no_award_confirm or \"\"):\n return 2\n return 3\n elif \"抽中福袋\" in (lucky_draw_result or \"\"):\n try:\n analyser._log_kv(\"开奖诊断\", \"恭喜中奖了\", result_text=brief)\n except Exception:\n pass\n # 速度优化:优先检测第一个常见位置,命中即返回\n y_value = [1438, 1490]\n for y in y_value:\n cache_key3 = (f\"have_read_user_agreement_{y}\", 0)\n have_read_user_agreement = None\n dur3 = 0.0\n\n if cache_key3 in analyser._ocr_cache:\n cached_ts3, cached_result3 = analyser._ocr_cache[cache_key3]\n if (now - cached_ts3) < analyser._ocr_cache_ttl:\n have_read_user_agreement = cached_result3\n\n if not have_read_user_agreement:\n t2 = time.time()\n analyser.cut_pic(280, y - 35, 670, y + 35, \"\", f\"已阅读用户协议_{y}\")\n have_read_user_agreement = analyser.operation.analyse_pic_word(\n f\"已阅读用户协议_{y}\"\n )\n analyser._ocr_cache[cache_key3] = (\n time.time(),\n have_read_user_agreement,\n )\n dur3 = time.time() - t2\n try:\n brief3 = (have_read_user_agreement or \"\").replace(\"\\n\", \" \")[:140]\n except Exception:\n brief3 = \"\"\n try:\n analyser._log_kv(\n \"开奖诊断\",\n \"have_read_user_agreement\",\n brief=brief3,\n ocr_dur=round(dur3, 2),\n y=y,\n )\n except Exception:\n pass\n\n if \"已阅读\" in (have_read_user_agreement or \"\"):\n return y\n return False\n\n\ndef check_have_reward_notice_confirm(analyser) -> bool:\n \"\"\"判断是否有领奖的二次确认提醒。\"\"\"\n analyser._shot_and_diagnose(\"领奖确认\", \"识别是否有我知道了\", analyser.device_id)\n analyser.cut_pic(370, 1350, 680, 1440, \"\", \"奖励通知确认\")\n reward_notice_confirm = analyser.operation.analyse_pic_word(\"奖励通知确认\", 1)\n if \"我知道了\" in (reward_notice_confirm or \"\"):\n try:\n analyser._log_kv(\n \"开奖诊断\",\n \"存在奖品领取提醒\",\n text=(reward_notice_confirm or \"\")[:80],\n )\n except Exception:\n pass\n return True\n return False\n\n\ndef check_in_order_confirm_page(analyser) -> bool:\n \"\"\"判断是否在中奖下单后的购买成功的页面。\"\"\"\n analyser._shot_and_diagnose(\"下单结果\", \"识别是否购买成功页\", analyser.device_id)\n analyser.cut_pic(370, 120, 700, 220, \"\", \"订单确认\")\n order_confirm = analyser.operation.analyse_pic_word(\"订单确认\")\n if \"购买成功\" in (order_confirm or \"\"):\n try:\n analyser._log_kv(\n \"开奖诊断\",\n \"订单确认页面:购买成功\",\n text=(order_confirm or \"\")[:80],\n )\n except Exception:\n pass\n return True\n return False\n\n\ndef get_reward(analyser, reward_y: int = 0) -> None:\n \"\"\"中奖后领奖然后返回。\"\"\"\n analyser.operation.save_reward_pic(analyser.device_id)\n try:\n analyser._log_kv(\"领奖\", \"保存中奖截图\", step=\"save_reward_pic\")\n except Exception:\n pass\n\n analyser.click(243, reward_y) # 勾选协议\n analyser.operation.delay(1)\n analyser.click(540, reward_y - 140) # 点击领取\n try:\n analyser._log_kv(\"领奖\", \"勾选协议并点击领取\", reward_y=reward_y)\n except Exception:\n pass\n\n analyser.operation.delay(5)\n analyser.click(886, 2170) # 点击下单\n try:\n analyser._log_kv(\"领奖\", \"点击下单\")\n except Exception:\n pass\n analyser.operation.delay(10)\n\n # 循环检查下单结果,增加保护避免极端死循环\n max_checks = 5\n checks = 0\n while checks < max_checks and check_in_order_confirm_page(analyser):\n checks += 1\n analyser.operation.click_back(analyser.device_id)\n try:\n analyser._log_kv(\"领奖\", \"点击回退按钮\", check_round=checks)\n except Exception:\n pass\n analyser.operation.delay(4)\n\n try:\n analyser._log_kv(\"领奖\", \"下完单返回到直播间\", checks=checks)\n except Exception:\n pass\n analyser.operation.delay(4)\n\n if check_lucky_draw_result(analyser):\n try:\n analyser._log_kv(\"领奖\", \"领奖弹窗未关闭,准备关闭\")\n except Exception:\n pass\n analyser.click(540, reward_y + 180)\n try:\n analyser._log_kv(\n \"领奖\",\n \"点击关闭领奖弹窗\",\n x=540,\n y=(reward_y + 180) * analyser.resolution_ratio_y // 2400,\n )\n except Exception:\n pass\n analyser.operation.delay(2)\n analyser.operation.save_reward_pic(analyser.device_id)\n try:\n analyser._log_kv(\"领奖\", \"保存关闭领奖弹窗后的截图\")\n except Exception:\n pass\n analyser.operation.click_back(analyser.device_id)\n analyser.operation.delay(2)\n\n if check_have_reward_notice_confirm(analyser):\n try:\n analyser._log_kv(\"领奖\", \"提醒领奖弹窗未关闭,点击我知道了\")\n except Exception:\n pass\n analyser.click(540, 1400)\n analyser.operation.delay(2)\n\n try:\n analyser._log_kv(\"领奖\", \"关闭中奖提醒后等待\", wait_seconds=30)\n except Exception:\n pass\n analyser.operation.delay(30)\n\n\ndef is_watch_task_fudai(content: str) -> bool:\n \"\"\"检测是否为\"观看X分钟\"类任务福袋。\n\n 参数:\n content: 福袋内容文本\n\n 返回:\n True 表示是\"观看X分钟\"类任务,应放弃\n False 表示不是此类任务\n \"\"\"\n if not content:\n return False\n\n try:\n import re\n\n # 将内容转换为字符串并去除空白\n content_str = re.sub(r\"\\s+\", \"\", str(content))\n\n # 中文数字字符\n chinese_num_chars = \"零一二三四五六七八九十百千两\"\n\n # 匹配模式1:观看/看 + (可选\"直播\") + 数字或中文数字 + 分钟\n patt1 = rf\"(?:观看|看)(?:直播)?(?:.*?)?(?:\\d+|[{chinese_num_chars}]+)\\s*分钟\"\n\n # 匹配模式2:需要观看/需要看 + 数字或中文数字 + 分钟\n patt2 = rf\"需要(?:观看|看)(?:.*?)?(?:\\d+|[{chinese_num_chars}]+)\\s*分钟\"\n\n # 匹配模式3:观看时长 + 数字或中文数字 + 分钟\n patt3 = rf\"观看时长(?:.*?)?(?:\\d+|[{chinese_num_chars}]+)\\s*分钟\"\n\n # 匹配模式4:看播 + 数字或中文数字 + 分钟\n patt4 = rf\"看播(?:.*?)?(?:\\d+|[{chinese_num_chars}]+)\\s*分钟\"\n\n # 检查是否匹配任一模式\n patterns = [patt1, patt2, patt3, patt4]\n for patt in patterns:\n if re.search(patt, content_str):\n return True\n\n return False\n except Exception:\n return False\n\n\ndef should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str]:\n \"\"\"根据 config.json 中的阈值与关键词,判断是否应丢弃当前福袋。\n\n 返回:\n (skip, reason) 其中 reason 为简单文字原因,便于日志查看。\n \"\"\"\n start_time = time.time()\n # 单间模式(needswitch=False):忽略所有福袋阈值配置,永远不因为配置而跳过\n try:\n needswitch = bool(getattr(analyser, \"needswitch\", True))\n except Exception:\n needswitch = True\n if not needswitch:\n try:\n analyser._log_kv(\n \"筛选\",\n \"单间模式:忽略所有福袋阈值配置,直接参与\",\n needswitch=0,\n )\n except Exception:\n pass\n return False, \"single_room_mode\"\n\n if not isinstance(detail, tuple) or len(detail) < 6:\n return False, \"detail_tuple_invalid\"\n\n content = str(detail[0] or \"\")\n\n # 优先检查是否为\"观看X分钟\"类任务:若是,直接放弃\n if is_watch_task_fudai(content):\n try:\n analyser._log_kv(\n \"筛选\",\n \"检测到'观看X分钟'类任务,自动放弃\",\n content=content[:80] if content else \"\",\n reason=\"watch_task_detected\",\n )\n except Exception:\n pass\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"筛选\",\n \"should_skip_fudai_by_config完成(观看任务)\",\n elapsed_seconds=round(elapsed, 2),\n )\n return True, \"watch_task_detected\"\n time_text = str(detail[1] or \"\")\n try:\n participants = int(detail[2] or 0)\n except Exception:\n participants = 0\n try:\n copies = int(detail[3] or 0)\n except Exception:\n copies = 0\n try:\n prize_value_yuan = float(detail[4] or 0.0)\n except Exception:\n prize_value_yuan = 0.0\n\n cd_start, cd_end = None, None\n if isinstance(detail[5], (tuple, list)) and len(detail[5]) >= 2:\n cd_start, cd_end = detail[5][0], detail[5][1]\n now = time.time()\n remain_seconds = None\n try:\n if isinstance(cd_end, (int, float)) and cd_end > now:\n remain_seconds = float(cd_end - now)\n try:\n analyser._log_kv(\n \"筛选\",\n \"倒计时计算成功\",\n cd_end=cd_end,\n now=now,\n 剩余秒数=remain_seconds,\n )\n except Exception:\n pass\n else:\n try:\n analyser._log_kv(\n \"筛选\",\n \"倒计时计算失败或已过期\",\n cd_end=cd_end,\n now=now,\n cd_end类型=type(cd_end).__name__,\n cd_end大于now=(\n bool(isinstance(cd_end, (int, float)) and cd_end > now)\n if isinstance(cd_end, (int, float))\n else False\n ),\n )\n except Exception:\n pass\n except Exception as e:\n remain_seconds = None\n try:\n analyser._log_kv(\n \"筛选\",\n \"倒计时计算异常\",\n 异常=str(e),\n 异常类型=type(e).__name__,\n )\n except Exception:\n pass\n\n # 读取配置阈值\n try:\n min_value = float(getattr(analyser, \"min_prize_value_yuan\", 0.0) or 0.0)\n except Exception:\n min_value = 0.0\n try:\n min_participants = int(getattr(analyser, \"min_participants\", 0) or 0)\n except Exception:\n min_participants = 0\n try:\n max_participants = int(getattr(analyser, \"max_participants\", 0) or 0)\n except Exception:\n max_participants = 0\n skip_if_gt = 0 # Initialize before try block\n try:\n skip_if_gt = int(getattr(analyser, \"skip_if_countdown_gt_seconds\", 0) or 0)\n except Exception:\n skip_if_gt = 0\n skip_if_lt = 0 # Initialize before try block\n try:\n skip_if_lt = int(getattr(analyser, \"skip_if_countdown_lt_seconds\", 0) or 0)\n except Exception:\n skip_if_lt = 0\n\n # 记录所有配置值和实际值,便于调试\n try:\n analyser._log_kv(\n \"筛选\",\n \"should_skip_fudai_by_config 开始检查\",\n 配置_最小价值=min_value,\n 配置_最小参与人数=min_participants,\n 配置_最大参与人数=max_participants,\n 配置_倒计时大于秒数=skip_if_gt,\n 配置_倒计时小于秒数=skip_if_lt,\n 实际_价值=prize_value_yuan,\n 实际_参与人数=participants,\n 实际_份数=copies,\n 实际_剩余秒数=int(remain_seconds) if remain_seconds is not None else None,\n 实际_内容=content[:60] if content else \"\",\n )\n except Exception:\n pass\n\n # 1) 价值过滤\n if min_value > 0:\n if prize_value_yuan > 0:\n if prize_value_yuan < min_value:\n try:\n analyser._log_kv(\n \"筛选\",\n \"价值过滤:丢弃\",\n 原因=f\"value_lt_{min_value}\",\n 实际价值=prize_value_yuan,\n 配置最小价值=min_value,\n )\n except Exception:\n pass\n return True, f\"value_lt_{min_value}\"\n else:\n try:\n analyser._log_kv(\n \"筛选\",\n \"价值过滤:通过\",\n 实际价值=prize_value_yuan,\n 配置最小价值=min_value,\n )\n except Exception:\n pass\n else:\n try:\n analyser._log_kv(\n \"筛选\",\n \"价值过滤:跳过(未识别到价值)\",\n 实际价值=prize_value_yuan,\n )\n except Exception:\n pass\n\n # 2) 参与人数过滤\n if min_participants > 0:\n if participants > 0:\n if participants < min_participants:\n try:\n analyser._log_kv(\n \"筛选\",\n \"参与人数过滤:丢弃(小于最小值)\",\n 原因=f\"participants_lt_{min_participants}\",\n 实际参与人数=participants,\n 配置最小参与人数=min_participants,\n )\n except Exception:\n pass\n return True, f\"participants_lt_{min_participants}\"\n else:\n try:\n analyser._log_kv(\n \"筛选\",\n \"参与人数过滤:通过(最小值检查)\",\n 实际参与人数=participants,\n 配置最小参与人数=min_participants,\n )\n except Exception:\n pass\n else:\n try:\n analyser._log_kv(\n \"筛选\",\n \"参与人数过滤:跳过(未识别到参与人数)\",\n 实际参与人数=participants,\n )\n except Exception:\n pass\n\n if max_participants > 0:\n if participants > 0:\n if participants > max_participants:\n try:\n analyser._log_kv(\n \"筛选\",\n \"参与人数过滤:丢弃(大于最大值)\",\n 原因=f\"participants_gt_{max_participants}\",\n 实际参与人数=participants,\n 配置最大参与人数=max_participants,\n )\n except Exception:\n pass\n return True, f\"participants_gt_{max_participants}\"\n else:\n try:\n analyser._log_kv(\n \"筛选\",\n \"参与人数过滤:通过(最大值检查)\",\n 实际参与人数=participants,\n 配置最大参与人数=max_participants,\n )\n except Exception:\n pass\n\n # 3) 倒计时过滤\n # 3.1) 倒计时小于阈值:直接丢弃(不参与)\n if skip_if_lt > 0:\n if remain_seconds is not None:\n if remain_seconds < skip_if_lt:\n try:\n analyser._log_kv(\n \"筛选\",\n \"倒计时过滤:丢弃(剩余秒数小于阈值,不参与)\",\n 原因=f\"countdown_lt_{skip_if_lt}\",\n 实际剩余秒数=int(remain_seconds),\n 配置阈值秒数=skip_if_lt,\n 判断条件=f\"{remain_seconds} < {skip_if_lt} = True\",\n )\n except Exception:\n pass\n return True, f\"countdown_lt_{skip_if_lt}\"\n\n # 3.2) 倒计时大于阈值:不参与(但如果价值达到高价值阈值,可以预约)\n # 注意:这个过滤在 basic_join_decision 中会被特殊处理,如果价值达到高价值阈值,即使倒计时大于阈值也会记录预约\n if skip_if_gt > 0:\n try:\n analyser._log_kv(\n \"筛选\",\n \"倒计时过滤:开始检查\",\n 配置阈值秒数=skip_if_gt,\n 实际剩余秒数=(\n int(remain_seconds) if remain_seconds is not None else None\n ),\n 是否有倒计时数据=remain_seconds is not None,\n 说明=\"如果剩余秒数大于阈值,则不参与(但高价值福袋可预约)\",\n )\n except Exception:\n pass\n\n if remain_seconds is not None:\n # 如果剩余秒数 > 阈值,就丢弃(不参与)\n if remain_seconds > skip_if_gt:\n try:\n analyser._log_kv(\n \"筛选\",\n \"倒计时过滤:丢弃(剩余秒数大于阈值,不参与)\",\n 原因=f\"countdown_gt_{skip_if_gt}\",\n 实际剩余秒数=int(remain_seconds),\n 配置阈值秒数=skip_if_gt,\n 判断条件=f\"{remain_seconds} > {skip_if_gt} = True\",\n 说明=\"如果价值达到高价值阈值,basic_join_decision 会记录预约\",\n )\n except Exception:\n pass\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"筛选\",\n \"should_skip_fudai_by_config完成(倒计时大于阈值)\",\n elapsed_seconds=round(elapsed, 2),\n )\n return True, f\"countdown_gt_{skip_if_gt}\"\n else:\n try:\n analyser._log_kv(\n \"筛选\",\n \"倒计时过滤:通过(剩余秒数小于等于阈值,可以参与)\",\n 实际剩余秒数=int(remain_seconds),\n 配置阈值秒数=skip_if_gt,\n 判断条件=f\"{remain_seconds} > {skip_if_gt} = False\",\n )\n except Exception:\n pass\n else:\n try:\n analyser._log_kv(\n \"筛选\",\n \"倒计时过滤:跳过(未识别到倒计时或倒计时已过期)\",\n 剩余秒数=remain_seconds,\n cd_start=cd_start,\n cd_end=cd_end,\n now=now,\n )\n except Exception:\n pass\n else:\n try:\n analyser._log_kv(\n \"筛选\",\n \"倒计时过滤:跳过(配置阈值为0,不启用倒计时过滤)\",\n 配置阈值秒数=skip_if_gt,\n )\n except Exception:\n pass\n\n # 4) 内容关键词过滤(复用 check_contain 逻辑)\n content_check_result = check_contain(analyser, content)\n if content_check_result:\n try:\n analyser._log_kv(\n \"筛选\",\n \"内容关键词过滤:丢弃\",\n 原因=\"content_not_wanted\",\n 内容=content[:60] if content else \"\",\n )\n except Exception:\n pass\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"筛选\",\n \"should_skip_fudai_by_config完成(内容关键词过滤)\",\n elapsed_seconds=round(elapsed, 2),\n )\n return True, \"content_not_wanted\"\n else:\n try:\n analyser._log_kv(\n \"筛选\",\n \"内容关键词过滤:通过\",\n 内容=content[:60] if content else \"\",\n )\n except Exception:\n pass\n\n try:\n analyser._log_kv(\n \"筛选\",\n \"should_skip_fudai_by_config 通过(所有检查项均通过)\",\n content=content[:60] if content else \"\",\n participants=participants,\n copies=copies,\n value_yuan=prize_value_yuan,\n remain_seconds=int(remain_seconds) if remain_seconds is not None else None,\n )\n except Exception:\n pass\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"筛选\",\n \"should_skip_fudai_by_config完成(通过)\",\n elapsed_seconds=round(elapsed, 2),\n )\n return False, \"ok\"\n\n\ndef basic_join_decision(analyser: Any, detail: Tuple) -> bool:\n \"\"\"基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。\n\n 返回:\n True 表示已经参与或已处理完成;\n False 表示未参与(例如被配置筛掉或参与失败)。\n \"\"\"\n # time 模块在文件开头已导入\n start_time = time.time()\n # 解析 detail 字段:先提取价值信息,用于判断是否达到高价值阈值\n content = \"\"\n prize_value_yuan = 0.0\n countdown_tuple = None\n try:\n if isinstance(detail, tuple) and len(detail) >= 6:\n content = str(detail[0] or \"\")\n prize_value_yuan = float(detail[4] or 0.0)\n countdown_tuple = detail[5]\n except Exception:\n pass\n\n # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理\n try:\n last_status = getattr(analyser, \"_last_fudai_detail_status\", \"\")\n if last_status == \"coupon_popup\":\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理\",\n )\n except Exception:\n pass\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision完成(优惠券弹窗)\",\n elapsed_seconds=round(elapsed, 2),\n )\n return False\n elif last_status == \"validation_failed\":\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理\",\n )\n except Exception:\n pass\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision完成(验证失败)\",\n elapsed_seconds=round(elapsed, 2),\n )\n return False\n except Exception:\n pass\n\n # 额外验证:使用验证函数检查数据合理性\n try:\n # 在函数开头导入,避免作用域问题\n import douyin_fudai_detail as dfd_module\n\n is_valid, reason = dfd_module.validate_fudai_detail(detail, analyser)\n if not is_valid:\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:福袋详情数据验证失败,识别出错\",\n validation_reason=reason,\n content=content[:50] if content else \"\",\n prize_value_yuan=prize_value_yuan,\n )\n except Exception:\n pass\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision完成(验证失败)\",\n elapsed_seconds=round(elapsed, 2),\n )\n return False\n except Exception:\n pass\n\n # 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误\n if not content and prize_value_yuan == 0.0:\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理\",\n content=content,\n prize_value_yuan=prize_value_yuan,\n )\n except Exception:\n pass\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision完成(无效详情)\",\n elapsed_seconds=round(elapsed, 2),\n )\n return False\n\n # 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋\n try:\n needswitch = bool(getattr(analyser, \"needswitch\", True))\n except Exception:\n needswitch = True\n if not needswitch:\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:单间模式,忽略阈值与预约逻辑,直接参与当前福袋\",\n )\n except Exception:\n pass\n result = attend_choujiang(analyser)\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision完成(单间模式参与)\",\n elapsed_seconds=round(elapsed, 2),\n result=result,\n )\n return result\n\n # 检查是否启用高价值预约,以及价值是否达到阈值\n try:\n high_value_enabled = bool(getattr(analyser, \"high_value_fudai_enabled\", False))\n except Exception:\n high_value_enabled = False\n\n try:\n high_value_threshold = float(\n getattr(analyser, \"high_value_fudai_threshold_yuan\", 500.0) or 500.0\n )\n except Exception:\n high_value_threshold = 500.0\n\n # 计算 future_timestamp(预计开奖时间戳)\n future_ts = 0.0\n if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:\n try:\n future_ts = float(countdown_tuple[1] or 0.0)\n except Exception:\n future_ts = 0.0\n\n # 检查是否已经参与过这个福袋(通过 future_ts 匹配,避免重复参与)\n if future_ts > 0:\n try:\n participated_fudai_ts = getattr(\n analyser, \"_participated_fudai_future_ts\", set()\n )\n if not isinstance(participated_fudai_ts, set):\n participated_fudai_ts = set()\n\n # 检查是否已经参与过(允许5秒误差,因为倒计时可能略有变化)\n for participated_ts in participated_fudai_ts:\n if abs(future_ts - participated_ts) < 5.0:\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:已参与过此福袋,跳过重复参与\",\n future_ts=future_ts,\n participated_ts=participated_ts,\n )\n except Exception:\n pass\n # 已参与过,直接返回 True(表示已处理完成)\n return True\n except Exception:\n pass\n\n # 检查价值是否达到高价值阈值\n is_high_value = (\n high_value_enabled\n and prize_value_yuan > 0\n and prize_value_yuan >= high_value_threshold\n and future_ts > 0.0\n )\n\n # 执行筛选检查\n skip, reason = should_skip_fudai_by_config(analyser, detail)\n\n # 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值\n # 需要检查剩余秒数是否在\"预约参与阈值\"内,如果在阈值内则立即参与,否则记录预约\n if skip and reason.startswith(\"countdown_gt_\") and is_high_value:\n # 计算剩余秒数\n remain_seconds = None\n if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:\n try:\n now = time.time()\n cd_start = float(countdown_tuple[0] or 0.0)\n cd_end = float(countdown_tuple[1] or 0.0)\n if cd_start > 0 and cd_end > cd_start:\n remain_seconds = float(cd_end - now)\n except Exception:\n pass\n\n # 获取\"预约参与阈值\"配置\n try:\n join_ahead_seconds = int(\n getattr(analyser, \"high_value_fudai_join_ahead_seconds\", 120) or 120\n )\n except Exception:\n join_ahead_seconds = 120\n\n # 如果剩余秒数在\"预约参与阈值\"内,立即参与而不是预约\n if remain_seconds is not None and remain_seconds <= join_ahead_seconds:\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:倒计时大于阈值,但剩余秒数在预约参与阈值内,立即参与\",\n reason=reason,\n value_yuan=prize_value_yuan,\n threshold=high_value_threshold,\n remain_seconds=int(remain_seconds),\n join_ahead_threshold=join_ahead_seconds,\n )\n except Exception:\n pass\n # 不关闭详情,继续走立即参与逻辑\n skip = False\n reason = \"high_value_immediate_join\"\n else:\n # 剩余秒数大于\"预约参与阈值\",记录预约\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:倒计时大于阈值,但价值达到高价值阈值,记录预约\",\n reason=reason,\n value_yuan=prize_value_yuan,\n threshold=high_value_threshold,\n remain_seconds=(\n int(remain_seconds) if remain_seconds is not None else None\n ),\n join_ahead_threshold=join_ahead_seconds,\n )\n except Exception:\n pass\n # 不关闭详情,继续走预约逻辑\n skip = False\n reason = \"high_value_reservation\"\n\n if skip:\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:按配置丢弃福袋\",\n reason=reason,\n )\n except Exception:\n pass\n # 丢弃时,尽量关闭详情,避免停留在详情页\n try:\n analyser.click(500, 470)\n except Exception:\n try:\n analyser.operation.click_back(analyser.device_id)\n except Exception:\n pass\n try:\n analyser._log_kv(\n \"参与\", \"basic_join_decision:已关闭详情\", action=\"close_detail\"\n )\n except Exception:\n pass\n\n # 如果允许切换直播间,筛选不通过直接切换直播间\n try:\n needswitch = bool(getattr(analyser, \"needswitch\", True))\n except Exception:\n needswitch = True\n if needswitch:\n try:\n analyser._log_kv(\n \"参与\", \"basic_join_decision:丢弃后切换直播间\", reason=reason\n )\n except Exception:\n pass\n try:\n # 优先使用封装好的上滑切房方法\n if hasattr(analyser, \"swipe_up_to_next_live\"):\n analyser.swipe_up_to_next_live()\n else:\n # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)\n try:\n rx = int(getattr(analyser, \"resolution_ratio_x\", 1080) or 1080)\n ry = int(getattr(analyser, \"resolution_ratio_y\", 2400) or 2400)\n except Exception:\n rx, ry = 1080, 2400\n start_x = 540 * rx // 1080\n start_y = 1700 * ry // 2400\n end_x = 540 * rx // 1080\n end_y = 700 * ry // 2400\n analyser.operation.swipe(\n analyser.device_id, start_x, start_y, end_x, end_y, 300\n )\n except Exception:\n # 切房失败不影响主流程,直接返回\n pass\n\n return False\n\n # 未被筛掉:根据配置决定\"直接参与\"或\"记录为高价值预约\"\n # 注意:content, prize_value_yuan, countdown_tuple, future_ts, high_value_enabled, high_value_threshold, is_high_value 已在前面提取\n # 仅当启用高价值预约、识别到价值且未来时间合理时,才考虑记入预约队列\n if is_high_value:\n # 价值达到高价值阈值:检查剩余秒数,如果在\"预约参与阈值\"内则立即参与,否则记录预约\n # 计算剩余秒数\n remain_seconds = None\n if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:\n try:\n now = time.time()\n cd_start = float(countdown_tuple[0] or 0.0)\n cd_end = float(countdown_tuple[1] or 0.0)\n if cd_start > 0 and cd_end > cd_start:\n remain_seconds = float(cd_end - now)\n except Exception:\n pass\n\n # 获取\"预约参与阈值\"配置(high_value_fudai_join_ahead_seconds)\n # 如果剩余秒数 <= 这个阈值,立即参与;否则记录预约\n try:\n join_ahead_seconds = int(\n getattr(analyser, \"high_value_fudai_join_ahead_seconds\", 120) or 120\n )\n except Exception:\n join_ahead_seconds = 120\n\n # 如果剩余秒数在\"预约参与阈值\"内(<= 阈值),立即参与而不是记录预约\n if remain_seconds is not None and remain_seconds <= join_ahead_seconds:\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:价值达到高价值阈值,剩余秒数在预约参与阈值内,立即参与\",\n value_yuan=prize_value_yuan,\n threshold=high_value_threshold,\n remain_seconds=int(remain_seconds),\n join_ahead_threshold=join_ahead_seconds,\n )\n except Exception:\n pass\n # 不记录预约,继续执行后续的立即参与逻辑\n is_high_value = False\n else:\n # 剩余秒数大于\"预约参与阈值\",记录预约\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:价值达到高价值阈值,但剩余秒数大于预约参与阈值,记录预约\",\n value_yuan=prize_value_yuan,\n threshold=high_value_threshold,\n remain_seconds=(\n int(remain_seconds) if remain_seconds is not None else None\n ),\n join_ahead_threshold=join_ahead_seconds,\n )\n except Exception:\n pass\n\n if is_high_value:\n # 价值达到高价值阈值且剩余秒数大于阈值:记录预约而不是立即参与\n # 在记录预约之前,先检查福袋内容是否在黑名单中\n try:\n # 检查内容是否命中黑名单\n content_hit_blacklist = check_contain(analyser, content)\n if content_hit_blacklist:\n # 命中黑名单,不记录预约,直接关闭详情页并返回\n try:\n analyser._log_kv(\n \"预约\",\n \"[预约] 福袋内容命中黑名单,不记录预约,直接丢弃\",\n content=content[:80] if content else \"\",\n value_yuan=prize_value_yuan,\n threshold=high_value_threshold,\n )\n except Exception:\n pass\n # 关闭详情页\n try:\n analyser.click(500, 470)\n except Exception:\n try:\n analyser.operation.click_back(analyser.device_id)\n except Exception:\n pass\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:已关闭详情(命中黑名单)\",\n action=\"close_detail\",\n )\n except Exception:\n pass\n # 如果允许切换直播间,切换直播间\n try:\n needswitch = bool(getattr(analyser, \"needswitch\", True))\n except Exception:\n needswitch = True\n if needswitch:\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:命中黑名单后切换直播间\",\n reason=\"content_blacklist\",\n )\n except Exception:\n pass\n try:\n # 优先使用封装好的上滑切房方法\n if hasattr(analyser, \"swipe_up_to_next_live\"):\n analyser.swipe_up_to_next_live()\n else:\n # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)\n try:\n rx = int(\n getattr(analyser, \"resolution_ratio_x\", 1080)\n or 1080\n )\n ry = int(\n getattr(analyser, \"resolution_ratio_y\", 2400)\n or 2400\n )\n except Exception:\n rx, ry = 1080, 2400\n start_x = 540 * rx // 1080\n start_y = 1700 * ry // 2400\n end_x = 540 * rx // 1080\n end_y = 700 * ry // 2400\n analyser.operation.swipe(\n analyser.device_id,\n start_x,\n start_y,\n end_x,\n end_y,\n 300,\n )\n except Exception:\n # 切房失败不影响主流程,直接返回\n pass\n # 直接返回 False,不参与抽奖\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision完成(命中黑名单,已丢弃)\",\n elapsed_seconds=round(elapsed, 2),\n )\n return False\n except Exception as e:\n # 如果检查黑名单时出错,记录日志但继续记录预约(容错处理)\n try:\n analyser._log_kv(\n \"预约\",\n \"[预约] 检查黑名单时出错,继续记录预约\",\n error=str(e),\n error_type=type(e).__name__,\n )\n except Exception:\n pass\n\n if is_high_value:\n # 未命中黑名单,继续记录预约\n try:\n # 预约抢占最小价值(若配置了,则低于该值的预约不会抢占当前任务)\n try:\n preempt_min = float(\n getattr(analyser, \"reservation_preempt_min_value_yuan\", 0.0)\n or 0.0\n )\n except Exception:\n preempt_min = 0.0\n\n # 初始化预约队列容器\n reservations = getattr(analyser, \"reservations\", None)\n if reservations is None:\n reservations = []\n try:\n analyser.reservations = reservations # type: ignore[attr-defined]\n except Exception:\n pass\n else:\n # 在已有预约队列的情况下,先立即清理已过期的预约,保证队列始终是“未过期”的\n try:\n import douyin_reservation_logic as rl_cleanup\n\n rl_cleanup.cleanup_expired_reservations(\n analyser,\n reservations,\n write_state_callback=None,\n )\n except Exception:\n pass\n\n # room_pos:当前直播间位置计数\n try:\n room_pos = int(getattr(analyser, \"room_pos\", 0) or 0)\n except Exception:\n room_pos = 0\n\n # 获取当前直播间标题(如果可用)\n room_title = \"\"\n room_title_raw = \"\"\n try:\n # 每次记录预约时,都重新读取直播间标题,不使用缓存\n # 这样可以确保每个预约记录的是当时的真实直播间标题\n try:\n # 在函数开头导入,避免作用域问题\n import douyin_fudai_detail as dfd_module\n\n y_pianyi_val = int(getattr(analyser, \"y_pianyi\", 0) or 0)\n room_title, room_title_raw = (\n dfd_module.read_live_room_title_core(\n analyser, y_pianyi_val\n )\n )\n # 更新 analyser 的属性,用于状态文件显示当前直播间\n try:\n analyser.current_room_title = room_title\n analyser.current_room_title_raw = room_title_raw\n except Exception:\n pass\n except Exception as e:\n try:\n analyser._log_kv(\n \"预约\",\n \"读取直播间标题失败,尝试使用缓存\",\n error=str(e),\n error_type=type(e).__name__,\n )\n except Exception:\n pass\n # 如果读取失败,尝试使用缓存(作为兜底)\n room_title = str(\n getattr(analyser, \"current_room_title\", \"\") or \"\"\n )\n room_title_raw = str(\n getattr(analyser, \"current_room_title_raw\", \"\") or \"\"\n )\n except Exception:\n pass\n\n # 记录高价值预约(仅负责入队和写状态,不立即改变当前直播间)\n rl = douyin_reservation_logic\n\n # 定义写入状态文件的回调函数(格式与 douyin_reservation.py 中的 write_reservations_state 一致)\n def _write_reservation_state() -> None:\n try:\n import os\n import json\n from datetime import datetime\n\n state_path = getattr(\n analyser, \"_reservations_state_path\", None\n )\n if not state_path:\n # 使用与 douyin_fudai.py 相同的路径逻辑\n state_path = os.path.join(\n os.path.dirname(__file__),\n \"state\",\n \"reservations.json\",\n )\n # 确保目录存在\n os.makedirs(os.path.dirname(state_path), exist_ok=True)\n\n # 格式化预约队列数据(与 douyin_reservation.py 格式一致)\n items = []\n for r in reservations or []:\n try:\n ft = float(r.get(\"future_ts\") or 0)\n except Exception:\n ft = 0.0\n try:\n ft_str = (\n datetime.fromtimestamp(ft).strftime(\n \"%Y-%m-%d %H:%M:%S\"\n )\n if ft\n else \"\"\n )\n except Exception:\n ft_str = str(r.get(\"future_str\", \"\"))\n\n items.append(\n {\n \"prize_value_yuan\": float(\n r.get(\"prize_value_yuan\") or 0\n ),\n \"content\": str(r.get(\"content\") or \"\"),\n \"future_ts\": ft,\n \"future_str\": ft_str,\n \"pos_seen\": int(r.get(\"pos_seen\") or 0),\n \"room_title\": str(r.get(\"room_title\") or \"\"),\n \"room_title_raw\": str(\n r.get(\"room_title_raw\") or \"\"\n ),\n \"created_ts\": float(r.get(\"created_ts\") or 0),\n }\n )\n\n # 获取当前直播间标题(用于状态文件)\n current_title = str(\n getattr(analyser, \"current_room_title\", \"\")\n or room_title\n or \"\"\n )\n current_title_raw = str(\n getattr(analyser, \"current_room_title_raw\", \"\")\n or room_title_raw\n or \"\"\n )\n\n # 写入完整的状态数据\n data = {\n \"updated_ts\": time.time(),\n \"reason\": \"record_reservation\",\n \"room_pos\": int(room_pos),\n \"current_room_title\": current_title,\n \"current_room_title_raw\": current_title_raw,\n \"reservations\": items,\n }\n\n with open(state_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(data, f, ensure_ascii=False, indent=2)\n try:\n analyser._log_kv(\n \"预约\",\n \"已写入预约队列状态文件\",\n path=state_path,\n queue_len=len(reservations),\n )\n except Exception:\n pass\n except Exception as e:\n try:\n analyser._log_kv(\n \"预约\",\n \"写入预约队列状态文件失败\",\n error=str(e),\n error_type=type(e).__name__,\n )\n except Exception:\n pass\n\n # 记录高价值直播间(在记录预约之前)\n try:\n import douyin_high_value_room\n\n if hasattr(douyin_high_value_room, \"touch_high_value_room\"):\n douyin_high_value_room.touch_high_value_room( # type: ignore[attr-defined]\n analyser=analyser,\n title_norm=room_title,\n title_raw=room_title_raw,\n prize_value_yuan=prize_value_yuan,\n reason=\"reservation\",\n increment=True,\n content=content,\n pos_seen=room_pos,\n )\n except Exception:\n pass\n\n # 记录预约,并检查队列是否已满\n queue_full_flag = [False]\n\n def _add_reservation_with_flag(q, item):\n queue_full_flag[0] = rl.add_reservation_core_logic( # type: ignore[attr-defined]\n q,\n item,\n max_reservations=int(\n getattr(\n analyser, \"high_value_fudai_max_reservations\", 3\n )\n or 3\n ),\n analyser=analyser,\n write_state_callback=_write_reservation_state,\n )\n\n rl.record_high_value_reservation( # type: ignore[attr-defined]\n analyser=analyser,\n fudai_content_text=content,\n prize_value_yuan=prize_value_yuan,\n lastsecond=0,\n future_timestamp=future_ts,\n x=0,\n needswitch=True,\n wait_minutes=0,\n post_switch_delay_s=0.0,\n room_pos=room_pos,\n reservations=reservations,\n reservation_focus_until_ts_ref=[\n float(\n getattr(analyser, \"reservation_focus_until_ts\", 0.0)\n or 0.0\n )\n ],\n close_detail_callback=lambda: None,\n swipe_up_switch_callback=lambda: None,\n swipe_down_back_callback=lambda: None,\n add_reservation_callback=_add_reservation_with_flag,\n sort_reservations_callback=lambda: rl._sort_reservations_inplace( # type: ignore[attr-defined]\n reservations\n ),\n write_state_callback=_write_reservation_state,\n room_title=room_title,\n room_title_raw=room_title_raw,\n )\n\n # 如果队列已满,设置标志以便主循环处理\n if queue_full_flag[0]:\n try:\n analyser.queue_full_waiting_at_earliest = (\n False # 重置标志,让主循环处理\n )\n except Exception:\n pass\n\n try:\n analyser._log_kv(\n \"预约\",\n \"basic_join_decision:命中高价值阈值,已记录为预约,不立即参与\",\n value_yuan=prize_value_yuan,\n threshold=high_value_threshold,\n future_ts=int(future_ts),\n room_pos=room_pos,\n queue_len=len(reservations),\n preempt_min_value=preempt_min,\n )\n except Exception:\n pass\n\n # 关闭当前详情,避免长时间停留\n try:\n analyser.click(500, 470)\n except Exception:\n try:\n analyser.operation.click_back(analyser.device_id)\n except Exception:\n pass\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:已关闭详情\",\n action=\"close_detail\",\n )\n except Exception:\n pass\n\n # 记录预约后,切换直播间继续找别的福袋\n # 注意:如果已经在锁定期内(已回退到预约直播间),不应该切换直播间\n try:\n needswitch = bool(getattr(analyser, \"needswitch\", True))\n except Exception:\n needswitch = True\n\n # 检查是否在锁定期内\n in_lock_period = False\n try:\n focus_until = float(\n getattr(analyser, \"reservation_focus_until_ts\", 0.0) or 0.0\n )\n now_ts = time.time()\n if focus_until > 0 and now_ts < focus_until:\n in_lock_period = True\n try:\n analyser._log_kv(\n \"预约\",\n \"[预约] 记录预约后:在锁定期内,不切换直播间\",\n focus_until=int(focus_until),\n remain_seconds=int(focus_until - now_ts),\n )\n except Exception:\n pass\n except Exception:\n pass\n\n if needswitch and not in_lock_period:\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:记录预约后切换直播间\",\n reason=\"high_value_reservation\",\n )\n except Exception:\n pass\n try:\n # 优先使用封装好的上滑切房方法\n if hasattr(analyser, \"swipe_up_to_next_live\"):\n analyser.swipe_up_to_next_live()\n else:\n # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)\n try:\n rx = int(\n getattr(analyser, \"resolution_ratio_x\", 1080)\n or 1080\n )\n ry = int(\n getattr(analyser, \"resolution_ratio_y\", 2400)\n or 2400\n )\n except Exception:\n rx, ry = 1080, 2400\n start_x = 540 * rx // 1080\n start_y = 1700 * ry // 2400\n end_x = 540 * rx // 1080\n end_y = 700 * ry // 2400\n analyser.operation.swipe(\n analyser.device_id,\n start_x,\n start_y,\n end_x,\n end_y,\n 300,\n )\n except Exception:\n # 切房失败不影响主流程,直接返回\n pass\n elif in_lock_period:\n # 在锁定期内,不切换直播间,但记录日志说明原因\n try:\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision:记录预约后不切换直播间(锁定期内)\",\n reason=\"lock_period_active\",\n )\n except Exception:\n pass\n\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision完成(记录预约)\",\n elapsed_seconds=round(elapsed, 2),\n )\n return True\n except Exception:\n # 若预约逻辑异常,退化为直接参与抽奖\n try:\n analyser._log_kv(\n \"预约\",\n \"basic_join_decision:记录预约时异常,退化为直接参与\",\n )\n except Exception:\n pass\n\n # 默认分支:未进入预约路径或预约失败,直接参与抽奖\n try:\n analyser._log_kv(\"参与\", \"basic_join_decision:尝试参与抽奖\")\n except Exception:\n pass\n result = attend_choujiang(analyser)\n elapsed = time.time() - start_time\n analyser._log_kv(\n \"参与\",\n \"basic_join_decision完成(参与抽奖)\",\n elapsed_seconds=round(elapsed, 2),\n result=result,\n )\n return result\n" +} +``` +User decision: **accepted** + +Status: **completed** + + +
+
+ +--- + + +
+ Tool use: **read_lints** • Read lints for 1 file + +Lint paths: + +- `douyin_fudai_core.py` + +Lint results + +Lint errors for `douyin_fudai_core.py` + + +| Message | Range | Severity | +|-------|-------|----------| +| "as_completed" 导入项未使用 | 8:52-8:64 | DIAGNOSTIC_SEVERITY_HINT | +| "normalize_countdown_text" 导入项未使用 | 10:26-10:50 | DIAGNOSTIC_SEVERITY_HINT | +| "_parse_mm_ss" 函数未使用 | 88:9-88:21 | DIAGNOSTIC_SEVERITY_HINT | +| "_extract_2digits" 函数未使用 | 97:9-97:25 | DIAGNOSTIC_SEVERITY_HINT | +| "_read_countdown_split" 函数未使用 | 105:9-105:30 | DIAGNOSTIC_SEVERITY_HINT | +| 变量 "h" 未使用 | 114:13-114:14 | DIAGNOSTIC_SEVERITY_HINT | +| 变量 "time_text" 未使用 | 1921:5-1921:14 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“as_completed” | 8:52-8:64 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“normalize_countdown_text” | 10:26-10:50 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“h” | 114:13-114:14 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“_parse_mm_ss” | 88:9-88:21 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“_extract_2digits” | 97:9-97:25 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“_read_countdown_split” | 105:9-105:30 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“time_text” | 1921:5-1921:14 | DIAGNOSTIC_SEVERITY_HINT | +| Line too long (126/100) | 2564:1-2564:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Line too long (103/100) | 2896:1-2896:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Line too long (105/100) | 2913:1-2913:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Line too long (119/100) | 2948:1-2948:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Too many lines in module (3106/1000) | 1:1-1:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Missing module docstring | 1:1-1:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Too many local variables (21/15) | 15:1-15:42 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 81:12-81:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_screenshot_manager) | 27:9-27:41 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 79:20-79:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 73:17-73:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many local variables (54/15) | 85:1-85:22 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 94:16-94:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many local variables (21/15) | 105:5-105:30 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 211:16-211:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 136:20-136:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 195:20-195:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 193:28-193:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 185:25-185:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 208:24-208:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 201:21-201:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 219:20-219:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 213:17-213:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Unused variable 'h' | 114:13-114:14 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 401:12-401:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 409:16-409:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 404:13-404:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 425:16-425:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 432:16-432:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 439:16-439:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 446:16-446:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 453:16-453:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 512:12-512:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 481:20-481:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 476:17-476:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 492:24-492:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 487:21-487:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 497:24-497:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _is_watch_task_detected of a client class | 496:21-496:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 510:16-510:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 504:13-504:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 520:16-520:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 515:13-515:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 597:16-597:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 528:24-528:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 534:24-534:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 540:24-540:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 546:24-546:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 552:24-552:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 577:24-577:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 572:21-572:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 588:28-588:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 583:25-583:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 593:28-593:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _is_watch_task_detected of a client class | 592:25-592:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 605:20-605:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 600:17-600:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 619:20-619:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 616:32-616:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _is_watch_task_detected of a client class | 615:29-615:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 649:16-649:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 640:24-640:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 633:21-633:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 645:24-645:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _is_watch_task_detected of a client class | 644:21-644:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 676:16-676:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 667:24-667:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 662:21-662:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 672:24-672:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _is_watch_task_detected of a client class | 671:21-671:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 679:5-679:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 713:12-713:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 693:20-693:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _enter_live_ts of a client class | 692:50-692:73 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 696:13-696:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 704:20-704:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _enter_live_fudai_logged of a client class | 703:17-703:50 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 707:17-707:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 774:12-774:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 748:16-748:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 746:24-746:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 738:21-738:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 761:20-761:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 754:17-754:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 772:20-772:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 766:17-766:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 783:16-783:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 777:13-777:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 785:5-785:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 795:9-795:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many branches (52/12) | 85:1-85:22 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (327/50) | 85:1-85:22 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 809:12-809:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 821:16-821:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 815:13-815:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 848:12-848:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 835:24-835:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 829:21-829:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 845:16-845:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 840:13-840:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 856:16-856:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 851:13-851:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 887:9-887:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "elif" after "return", remove the leading "el" from "elif" | 888:9-1551:21 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _log_kv of a client class | 889:13-889:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 893:20-893:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _last_successful_attend_ts of a client class | 892:17-892:52 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 914:20-914:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _participated_fudai_future_ts of a client class | 907:21-907:59 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 908:21-908:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 920:20-920:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _detail_closed_by_attend of a client class | 919:17-919:50 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 924:13-924:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 935:20-935:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 932:17-932:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 940:20-940:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 943:24-943:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 948:13-948:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 950:13-950:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 953:13-953:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 955:13-955:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 958:13-958:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 960:13-960:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 966:13-966:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 980:13-980:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 994:20-994:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _skip_stage_diagnosis_and_find_fudai of a client class | 993:17-993:62 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 997:13-997:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1007:13-1007:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1035:20-1035:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1026:17-1026:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1036:17-1036:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1040:13-1040:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1043:17-1043:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many local variables (19/15) | 1049:13-1049:56 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 1057:28-1057:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _shot_and_diagnose of a client class | 1052:25-1052:52 | DIAGNOSTIC_SEVERITY_WARNING | +| Formatting a regular string which could be an f-string | 1054:29-1054:68 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 1061:28-1061:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _diagnose_stage_from_current_screen of a client class | 1060:36-1060:80 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1069:25-1069:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1147:32-1147:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1097:29-1097:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1112:29-1112:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1143:36-1143:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1134:33-1134:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1144:33-1144:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1151:36-1151:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1155:40-1155:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1165:29-1165:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1173:29-1173:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1201:32-1201:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1192:29-1192:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1202:29-1202:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1433:32-1433:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _diagnose_stage_from_current_screen of a client class | 1208:33-1208:77 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1210:29-1210:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1222:37-1222:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1293:44-1293:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1247:41-1247:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1261:41-1261:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1286:48-1286:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1275:45-1275:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1287:45-1287:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1345:48-1345:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1338:52-1338:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1327:49-1327:65 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1339:49-1339:65 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1350:52-1350:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1354:37-1354:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1362:44-1362:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1366:33-1366:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1377:33-1377:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1418:40-1418:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1416:44-1416:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _diagnose_stage_from_current_screen of a client class | 1392:45-1392:89 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1394:41-1394:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "elif" after "return", remove the leading "el" from "elif" | 1400:41-1415:57 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _log_kv of a client class | 1401:45-1401:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1410:45-1410:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1423:33-1423:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1431:40-1431:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1435:29-1435:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1440:40-1440:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1446:25-1446:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1491:32-1491:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_flow_control) | 1455:29-1455:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 1485:40-1485:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _diagnose_stage_from_current_screen of a client class | 1469:41-1469:85 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 1471:37-1484:42 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _log_kv of a client class | 1472:41-1472:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1479:41-1479:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1486:37-1486:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1492:29-1492:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1499:21-1499:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1504:28-1504:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many return statements (8/6) | 1049:13-1049:56 | DIAGNOSTIC_SEVERITY_HINT | +| Too many branches (39/12) | 1049:13-1049:56 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (175/50) | 1049:13-1049:56 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _log_kv of a client class | 1511:17-1511:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1516:13-1516:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1522:20-1522:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1525:17-1525:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1530:24-1530:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1534:17-1534:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1541:20-1541:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1538:17-1538:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1546:13-1546:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1552:5-1552:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many return statements (10/6) | 861:1-861:21 | DIAGNOSTIC_SEVERITY_HINT | +| Too many branches (28/12) | 861:1-861:21 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (291/50) | 861:1-861:21 | DIAGNOSTIC_SEVERITY_HINT | +| Too many local variables (26/15) | 1556:1-1556:28 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _ocr_cache of a client class | 1564:21-1564:40 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1565:36-1565:55 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _shot_and_diagnose of a client class | 1574:9-1574:36 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1584:21-1584:40 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1585:36-1585:55 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache_ttl of a client class | 1586:32-1586:55 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1599:13-1599:32 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1610:9-1610:28 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1615:12-1615:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1624:12-1624:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1618:9-1618:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "elif" after "return", remove the leading "el" from "elif" | 1627:5-1709:25 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _ocr_cache of a client class | 1631:26-1631:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1632:42-1632:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache_ttl of a client class | 1633:37-1633:60 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1639:17-1639:36 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1645:13-1645:32 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1649:16-1649:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1658:16-1658:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1652:13-1652:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "elif" after "return", remove the leading "el" from "elif" | 1660:9-1663:21 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 1668:16-1668:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1667:13-1667:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1677:30-1677:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1678:46-1678:65 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache_ttl of a client class | 1679:41-1679:64 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1688:17-1688:36 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1695:20-1695:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1705:20-1705:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1698:17-1698:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many branches (29/12) | 1556:1-1556:28 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (92/50) | 1556:1-1556:28 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _shot_and_diagnose of a client class | 1715:5-1715:32 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1725:16-1725:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1720:13-1720:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _shot_and_diagnose of a client class | 1733:5-1733:32 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1743:16-1743:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1738:13-1738:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1754:12-1754:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1753:9-1753:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1762:12-1762:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1761:9-1761:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1769:12-1769:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1768:9-1768:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1781:16-1781:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1780:13-1780:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1787:12-1787:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1786:9-1786:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1794:16-1794:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1793:13-1793:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1804:16-1804:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1798:13-1798:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1810:16-1810:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1809:13-1809:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1818:16-1818:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1817:13-1817:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1825:12-1825:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1824:9-1824:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many branches (13/12) | 1749:1-1749:15 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (64/50) | 1749:1-1749:15 | DIAGNOSTIC_SEVERITY_HINT | +| Redefining name 're' from outer scope (line 3) | 1844:9-1844:18 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1871:12-1871:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Reimport 're' (imported line 3) | 1844:9-1844:18 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (re) | 1844:9-1844:18 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Too many local variables (21/15) | 1875:1-1875:32 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 1885:12-1885:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1894:16-1894:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1889:13-1889:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1912:16-1912:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1906:13-1906:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1915:9-1915:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1924:12-1924:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1928:12-1928:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1932:12-1932:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1969:12-1969:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1951:20-1951:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "剩余秒数" contains a non-ASCII character, consider renaming it. | 1949:21-1949:48 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 1944:17-1944:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1967:20-1967:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "cd_end类型" contains a non-ASCII character, consider renaming it. | 1960:21-1960:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "cd_end大于now" contains a non-ASCII character, consider renaming it. | 1961:21-1965:22 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 1955:17-1955:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1978:16-1978:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "异常" contains a non-ASCII character, consider renaming it. | 1975:17-1975:30 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "异常类型" contains a non-ASCII character, consider renaming it. | 1976:17-1976:46 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 1972:13-1972:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1984:12-1984:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1988:12-1988:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1992:12-1992:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1997:12-1997:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2002:12-2002:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2021:12-2021:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "配置_最小价值" contains a non-ASCII character, consider renaming it. | 2010:13-2010:42 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置_最小参与人数" contains a non-ASCII character, consider renaming it. | 2011:13-2011:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置_最大参与人数" contains a non-ASCII character, consider renaming it. | 2012:13-2012:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置_倒计时大于秒数" contains a non-ASCII character, consider renaming it. | 2013:13-2013:52 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置_倒计时小于秒数" contains a non-ASCII character, consider renaming it. | 2014:13-2014:52 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际_价值" contains a non-ASCII character, consider renaming it. | 2015:13-2015:43 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际_参与人数" contains a non-ASCII character, consider renaming it. | 2016:13-2016:45 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际_份数" contains a non-ASCII character, consider renaming it. | 2017:13-2017:33 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际_剩余秒数" contains a non-ASCII character, consider renaming it. | 2018:13-2018:92 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际_内容" contains a non-ASCII character, consider renaming it. | 2019:13-2019:58 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2007:9-2007:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 2027:13-2048:25 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2036:24-2036:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2032:25-2032:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际价值" contains a non-ASCII character, consider renaming it. | 2033:25-2033:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最小价值" contains a non-ASCII character, consider renaming it. | 2034:25-2034:53 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2029:21-2029:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2047:24-2047:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际价值" contains a non-ASCII character, consider renaming it. | 2044:25-2044:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最小价值" contains a non-ASCII character, consider renaming it. | 2045:25-2045:53 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2041:21-2041:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2056:20-2056:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际价值" contains a non-ASCII character, consider renaming it. | 2054:21-2054:50 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2051:17-2051:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 2062:13-2083:25 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2071:24-2071:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2067:25-2067:69 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际参与人数" contains a non-ASCII character, consider renaming it. | 2068:25-2068:56 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最小参与人数" contains a non-ASCII character, consider renaming it. | 2069:25-2069:66 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2064:21-2064:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2082:24-2082:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际参与人数" contains a non-ASCII character, consider renaming it. | 2079:25-2079:56 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最小参与人数" contains a non-ASCII character, consider renaming it. | 2080:25-2080:66 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2076:21-2076:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2091:20-2091:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际参与人数" contains a non-ASCII character, consider renaming it. | 2089:21-2089:52 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2086:17-2086:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 2096:13-2117:25 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2105:24-2105:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2101:25-2101:69 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际参与人数" contains a non-ASCII character, consider renaming it. | 2102:25-2102:56 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最大参与人数" contains a non-ASCII character, consider renaming it. | 2103:25-2103:66 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2098:21-2098:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2116:24-2116:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际参与人数" contains a non-ASCII character, consider renaming it. | 2113:25-2113:56 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最大参与人数" contains a non-ASCII character, consider renaming it. | 2114:25-2114:66 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2110:21-2110:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2133:24-2133:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2128:25-2128:60 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际剩余秒数" contains a non-ASCII character, consider renaming it. | 2129:25-2129:63 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置阈值秒数" contains a non-ASCII character, consider renaming it. | 2130:25-2130:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "判断条件" contains a non-ASCII character, consider renaming it. | 2131:25-2131:79 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2125:21-2125:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2151:16-2151:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "配置阈值秒数" contains a non-ASCII character, consider renaming it. | 2144:17-2144:46 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际剩余秒数" contains a non-ASCII character, consider renaming it. | 2145:17-2147:18 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "是否有倒计时数据" contains a non-ASCII character, consider renaming it. | 2148:17-2148:68 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "说明" contains a non-ASCII character, consider renaming it. | 2149:17-2149:104 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2141:13-2141:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 2156:13-2186:25 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2167:24-2167:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2161:25-2161:60 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际剩余秒数" contains a non-ASCII character, consider renaming it. | 2162:25-2162:63 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置阈值秒数" contains a non-ASCII character, consider renaming it. | 2163:25-2163:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "判断条件" contains a non-ASCII character, consider renaming it. | 2164:25-2164:79 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "说明" contains a non-ASCII character, consider renaming it. | 2165:25-2165:105 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2158:21-2158:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2170:17-2170:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2185:24-2185:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际剩余秒数" contains a non-ASCII character, consider renaming it. | 2181:25-2181:63 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置阈值秒数" contains a non-ASCII character, consider renaming it. | 2182:25-2182:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "判断条件" contains a non-ASCII character, consider renaming it. | 2183:25-2183:80 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2178:21-2178:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2197:20-2197:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "剩余秒数" contains a non-ASCII character, consider renaming it. | 2192:21-2192:48 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2189:17-2189:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2206:16-2206:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "配置阈值秒数" contains a non-ASCII character, consider renaming it. | 2204:17-2204:46 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2201:13-2201:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 2211:5-2236:17 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2219:16-2219:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2216:17-2216:44 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "内容" contains a non-ASCII character, consider renaming it. | 2217:17-2217:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2213:13-2213:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2222:9-2222:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2235:16-2235:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "内容" contains a non-ASCII character, consider renaming it. | 2233:17-2233:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2230:13-2230:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2248:12-2248:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2239:9-2239:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2251:5-2251:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many return statements (10/6) | 1875:1-1875:32 | DIAGNOSTIC_SEVERITY_HINT | +| Too many branches (64/12) | 1875:1-1875:32 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (182/50) | 1875:1-1875:32 | DIAGNOSTIC_SEVERITY_HINT | +| Unused variable 'time_text' | 1921:5-1921:14 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many local variables (47/15) | 2259:1-2259:24 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2277:12-2277:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2313:12-2313:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "elif" after "return", remove the leading "el" from "elif" | 2283:9-2312:25 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2289:20-2289:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2285:17-2285:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2292:13-2292:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2304:20-2304:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2300:17-2300:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2307:13-2307:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2340:12-2340:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_fudai_detail) | 2319:9-2319:49 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 2331:20-2331:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2324:17-2324:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2334:13-2334:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2352:16-2352:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2346:13-2346:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2355:9-2355:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2365:12-2365:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2373:16-2373:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2369:13-2369:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2377:9-2377:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2388:12-2388:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2395:12-2395:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2403:16-2403:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2429:16-2429:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2425:28-2425:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2419:25-2419:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2455:20-2455:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Simplify chained comparison between the operands | 2453:20-2453:54 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2463:16-2463:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2478:20-2478:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2469:17-2469:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2497:20-2497:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2486:17-2486:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2510:16-2510:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2505:13-2505:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2515:16-2515:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2518:20-2518:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2524:16-2524:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2521:13-2521:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2530:16-2530:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2537:20-2537:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2534:17-2534:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2557:20-2557:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2548:28-2548:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2577:20-2577:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Simplify chained comparison between the operands | 2575:20-2575:54 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2586:16-2586:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2600:20-2600:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2592:17-2592:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2617:20-2617:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2607:17-2607:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2708:20-2708:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2636:28-2636:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2629:25-2629:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2641:28-2641:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2644:32-2644:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2652:28-2652:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2647:25-2647:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2657:28-2657:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2666:32-2666:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2661:29-2661:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2697:32-2697:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2683:40-2683:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2702:21-2702:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2717:24-2717:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2711:21-2711:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3083:24-3083:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2729:28-2729:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2738:32-2738:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2744:28-2744:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2786:28-2786:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2769:32-2769:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_fudai_detail) | 2755:29-2755:69 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 2767:36-2767:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2777:36-2777:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2771:33-2771:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Redefining name 'os' from outer scope (line 5) | 2795:29-2795:38 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2880:32-2880:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Reimport 'os' (imported line 5) | 2795:29-2795:38 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (os) | 2795:29-2795:38 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Import outside toplevel (json) | 2796:29-2796:40 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Import outside toplevel (datetime.datetime) | 2797:29-2797:58 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 2817:40-2817:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2827:40-2827:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2878:36-2878:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2872:33-2872:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2888:36-2888:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2882:33-2882:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2906:28-2906:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_high_value_room) | 2893:25-2893:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _sort_reservations_inplace of a client class | 2948:60-2948:89 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2962:32-2962:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2976:28-2976:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2966:25-2966:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2982:28-2982:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2985:32-2985:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2993:28-2993:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2988:25-2988:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3000:28-3000:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3021:28-3021:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3019:36-3019:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3013:33-3013:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3031:32-3031:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3026:29-3026:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3062:32-3062:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3048:40-3048:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3073:32-3073:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3068:29-3068:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3077:21-3077:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3090:28-3090:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3086:25-3086:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3096:12-3096:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3095:9-3095:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3100:5-3100:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many return statements (10/6) | 2259:1-2259:24 | DIAGNOSTIC_SEVERITY_HINT | +| Too many branches (102/12) | 2259:1-2259:24 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (392/50) | 2259:1-2259:24 | DIAGNOSTIC_SEVERITY_HINT | +| standard import "concurrent.futures.ThreadPoolExecutor" should be placed before third party import "PIL.Image" | 8:1-8:64 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Unused as_completed imported from concurrent.futures | 8:1-8:64 | DIAGNOSTIC_SEVERITY_WARNING | +| Unused normalize_countdown_text imported from douyin_utils | 10:1-10:76 | DIAGNOSTIC_SEVERITY_WARNING | + + +
+
+ +--- + +**过期预约现在会被立即丢弃了。** + +- 在 `basic_join_decision` 里,每次准备**记录新的高价值预约**时,如果 `analyser` 上已经有 `reservations`,我会先调用: + `douyin_reservation_logic.cleanup_expired_reservations(analyser, reservations, write_state_callback=None)`。 +- 这样一来,**队列中所有 `future_ts <= 当前时间` 的预约会在入队前被立刻清理掉**,内存中的预约队列始终只保留“未过期”的记录;后续 `process_reservation_attend_window` 和单间模式里的清理逻辑会继续保持。 + +--- + +_**User (2025-12-26 05:50Z)**_ + +把显示的预约队列改成中文,并且更详细 + +--- + +_**Agent (model default, mode Agent)**_ + +
Thought Process +I need to adjust how the reservation queue is displayed, and I think that might involve changes in the state file or in the GUI list. I'll definitely need to search for instructions or examples on how to do this effectively. It’s important to ensure that the display is clear and user-friendly. So, I’ll look into the best practices for managing reservation queues in the interface! This should help improve functionality for everyone using it.
+ +--- + + +
Tool use: **read_file** • Read file: douyin_fudai_core.py + +
+
+ +--- + + +
+Tool use: **grep** • Grep for "reservations_state|"reservations"" in "." • 24 matches + +Output mode: content + + +| File | Content | Line | +|------|------|------| +| `.\state\reservations.json` | `"reservations": [` | L7 | +| `.\douyin_fudai_core.py` | `reservations = getattr(analyser, "reservations", None)` | L2733 | +| `.\douyin_fudai_core.py` | `# 定义写入状态文件的回调函数(格式与 douyin_reservation.py 中的 write_reservations_state 一致)` | L2804 | +| `.\douyin_fudai_core.py` | `analyser, "_reservations_state_path", None` | L2812 | +| `.\douyin_fudai_core.py` | `"reservations": items,` | L2878 | +| `.\douyin_fudai.py` | `self._reservations_state_path: str = os.path.join(` | L231 | +| `.\douyin_fudai.py` | `self, "reservations", None` | L1735 | +| `.\douyin_fudai.py` | `old_reservations_count = len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0` | L1935 | +| `.\douyin_fudai.py` | `before_clear = len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0` | L1951 | +| `.\douyin_fudai.py` | `after_clear = len(self.reservations) if hasattr(self, "reservations") else 0` | L1953 | +| `.\douyin_fudai.py` | `state_path = getattr(self, "_reservations_state_path", None)` | L1958 | +| `.\douyin_fudai.py` | `from douyin_reservation import write_reservations_state` | L1961 | +| `.\douyin_fudai.py` | `write_reservations_state(` | L1962 | +| `.\douyin_fudai.py` | `if hasattr(self, "reservations"):` | L1992 | +| `.\douyin_fudai.py` | `current_count = len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0` | L2010 | +| `.\douyin_fudai.py` | `reservations_list = getattr(self, "reservations", None)` | L2034 | +| `.\douyin_fudai.py` | `os.path.dirname(self._reservations_state_path),` | L2106 | +| `.\douyin_fudai.py` | `"reservations": items,` | L2160 | +| `.\douyin_fudai.py` | `self._reservations_state_path, "w", encoding="utf-8"` | L2164 | +| `.\douyin_fudai.py` | `if hasattr(self, "reservations") and self.reservations:` | L4445 | +| `.\web_gui.py` | `"reservations": [],` | L577 | +| `.\web_gui.py` | `"reservations": [],` | L583 | +| `.\douyin_reservation.py` | `def write_reservations_state(` | L18 | +| `.\douyin_reservation.py` | `"reservations": items,` | L57 | + + +
+
+ +--- + + +
+ Tool use: **codebase_search** • Searched codebase "显示预约队列" • **14** results + +| File | Lines | +|------|-------| +| `gui_app.py` | L25-3070 | +| `webui/app.js` | L703-871 | +| `webui/app.js` | L788-985 | +| `webui/index.html` | L713-758 | +| `douyin_reservation_logic.py` | L240-808 | +| `webui/styles.css` | L355-469 | +| `douyin_reservation_logic.py` | L205-430 | +| `douyin_reservation_logic.py` | L59-183 | +| `web_gui.py` | L1115-1540 | +| `流程图.md` | L443-490 | +| `webui/app.js` | L790-985 | +| `webui/app.js` | L871-985 | +| `web_gui.py` | L75-1115 | +| `douyin_reservation.py` | L8-92 | + +
+
+ +--- + + +
Tool use: **read_file** • Read file: state/reservations.json + +
+
+ +--- + + +
Tool use: **read_file** • Read file: web_gui.py + +
+
+ +--- + + + +--- + + +
Tool use: **read_file** • Read file: gui_app.py + +
+
+ +--- + + +
+Tool use: **apply_patch** + + +Parameters: + +```json +{ + "relativeWorkspacePath": "gui_app.py" +} +``` +Additional data: + +```json +{ + "codeblockId": "59b4d680-f6cd-4790-a257-e1a3e1662287" +} +``` +Result: + +```json +{ + "diff": { + "chunks": [ + { + "diffString": " data = json.load(f)\n reservation_text.delete(\"1.0\", \"end\")\n- reservation_text.insert(\n- \"1.0\", json.dumps(data, ensure_ascii=False, indent=2)\n- )\n+ \n+ from datetime import datetime\n+ updated_ts = float(data.get(\"updated_ts\", 0.0) or 0.0) if isinstance(data, dict) else 0.0\n+ room_pos = int(data.get(\"room_pos\", 0) or 0) if isinstance(data, dict) else 0\n+ reason = str(data.get(\"reason\", \"\") or \"\") if isinstance(data, dict) else \"\"\n+ current_title = str(data.get(\"current_room_title\", \"\") or \"\") if isinstance(data, dict) else \"\"\n+ current_title_raw = str(data.get(\"current_room_title_raw\", \"\") or \"\") if isinstance(data, dict) else \"\"\n+ reservations = data.get(\"reservations\", []) if isinstance(data, dict) else []\n+ \n+ # 基本信息(中文)\n+ lines = []\n+ lines.append(\"=== 预约队列总览 ===\")\n+ if updated_ts > 0:\n+ try:\n+ updated_str = datetime.fromtimestamp(updated_ts).strftime(\"%Y-%m-%d %H:%M:%S\")\n+ except Exception:\n+ updated_str = str(updated_ts)\n+ else:\n+ updated_str = \"-\"\n+ lines.append(f\"更新时间:{updated_str}\")\n+ lines.append(f\"当前直播间位置:{room_pos}\")\n+ lines.append(f\"当前直播间(清洗后):{current_title or '-'}\")\n+ lines.append(f\"当前直播间原文:{current_title_raw or '-'}\")\n+ lines.append(f\"预约总数量:{len(reservations)}\")\n+ if reason:\n+ lines.append(f\"最近更新原因:{reason}\")\n+ lines.append(\"\")\n+ \n+ if not reservations:\n+ lines.append(\"暂无预约记录。\")\n+ else:\n+ lines.append(\"=== 预约明细列表(按预计开奖时间排序) ===\")\n+ now_ts = datetime.now().timestamp()\n+ for idx, item in enumerate(reservations, start=1):\n+ try:\n+ val = float(item.get(\"prize_value_yuan\") or 0.0)\n+ except Exception:\n+ val = 0.0\n+ content = str(item.get(\"content\") or \"\")\n+ ft = float(item.get(\"future_ts\") or 0.0)\n+ ft_str = str(item.get(\"future_str\") or \"\")\n+ pos_seen = int(item.get(\"pos_seen\") or 0)\n+ room_title = str(item.get(\"room_title\") or \"\")\n+ room_title_raw = str(item.get(\"room_title_raw\") or \"\")\n+ created_ts = float(item.get(\"created_ts\") or 0.0)\n+ \n+ # 计算剩余时间\n+ remain_sec = max(0, int(ft - now_ts)) if ft > 0 else 0\n+ if remain_sec > 0:\n+ remain_str = f\"{remain_sec // 60}分{remain_sec % 60}秒后开奖\"\n+ elif ft > 0:\n+ remain_str = \"已到开奖时间\"\n+ else:\n+ remain_str = \"未知(future_ts 无效)\"\n+ \n+ # 记录时间\n+ if created_ts > 0:\n+ try:\n+ created_str = datetime.fromtimestamp(created_ts).strftime(\"%Y-%m-%d %H:%M:%S\")\n+ except Exception:\n+ created_str = str(created_ts)\n+ else:\n+ created_str = \"-\"\n+ \n+ lines.append(f\"[#{idx}] 价值:{val:.2f} 元\")\n+ lines.append(f\" 奖品内容:{content}\")\n+ lines.append(f\" 预计开奖时间:{ft_str or '-'}\")\n+ lines.append(f\" 剩余时间:{remain_str}\")\n+ lines.append(f\" 发现时直播间位置:{pos_seen}\")\n+ lines.append(f\" 直播间(清洗后):{room_title or '-'}\")\n+ lines.append(f\" 直播间原文:{room_title_raw or '-'}\")\n+ lines.append(f\" 记录时间:{created_str}\")\n+ lines.append(\"-\" * 40)\n+ \n+ reservation_text.insert(\"1.0\", \"\\n\".join(lines))\n else:\n reservation_text.delete(\"1.0\", \"end\")", + "oldStart": 2758, + "newStart": 2758, + "oldLines": 7, + "newLines": 79, + "linesRemoved": 3, + "linesAdded": 75 + } + ], + "editor": "EDITOR_AI" + }, + "shouldAutoFixLints": true, + "resultForModel": "Success. Updated the following files:\nM gui_app.py", + "contentsAfterEdit": "import json\nimport os\nimport queue\nimport re\nimport sys\nimport threading\nimport warnings\nfrom datetime import datetime\nfrom typing import Any, Callable\n\nfrom PIL import Image, ImageTk\n\n# 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化)\nfrom gui_core import (\n RunParams,\n Runner,\n find_adb_executable,\n list_adb_devices,\n read_config,\n write_config,\n)\nfrom path_config import get_logs_dir\n\n# 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告)\nwarnings.filterwarnings(\"ignore\", message=\".*pin_memory.*\", category=UserWarning)\nwarnings.filterwarnings(\"ignore\", message=\".*accelerator.*\", category=UserWarning)\n\n\ndef main():\n # ttkbootstrap 优先(更美观);没装则回退到原生 tkinter\n try:\n import ttkbootstrap as tb\n from ttkbootstrap.scrolled import ScrolledText\n\n import tkinter as tk\n from tkinter import ttk\n from ttkbootstrap.constants import LEFT, RIGHT, BOTH, X, Y\n\n root = tb.Window(themename=\"darkly\")\n except Exception:\n import tkinter as tk\n from tkinter import ttk\n from tkinter.constants import LEFT, RIGHT, BOTH, X, Y # type: ignore[assignment]\n from tkinter.scrolledtext import ScrolledText\n\n root = tk.Tk()\n\n root.title(\"抖音福袋挂机 - 可视化控制台\")\n root.geometry(\"1400x900\") # 增大窗口尺寸,提供更多空间\n\n q: queue.Queue[str] = queue.Queue()\n\n # ========== 线程安全的日志文件写入器 ==========\n class ThreadSafeLogWriter:\n \"\"\"线程安全的日志文件写入器,确保日志能稳定写入文件\"\"\"\n\n def __init__(self, log_dir: str | None = None):\n self._lock = threading.Lock()\n self._log_dir = log_dir or get_logs_dir()\n self._log_file_path: str = \"\"\n self._log_file_enabled: bool = True\n self._init_log_file()\n self._write_error_warned = False\n\n def _init_log_file(self) -> None:\n \"\"\"初始化日志文件路径(按日期)\"\"\"\n try:\n # 确保日志目录存在\n os.makedirs(self._log_dir, exist_ok=True)\n\n # 读取配置,检查是否启用日志文件\n cfg = read_config()\n self._log_file_enabled = bool(cfg.get(\"log_unified_enabled\", True))\n\n # 获取日志文件路径配置\n log_path = cfg.get(\"log_unified_path\") or \"logs/unified.log\"\n if not os.path.isabs(log_path):\n from path_config import PROJECT_ROOT\n\n log_path = os.path.join(PROJECT_ROOT, log_path)\n\n # 如果配置了按日期分割,使用日期后缀\n use_dated_logs = cfg.get(\"logging\", {}).get(\"use_dated_logs\", True)\n if use_dated_logs:\n # 提取基础文件名(移除扩展名)\n base_name = os.path.splitext(log_path)[0]\n today = datetime.now().strftime(\"%Y-%m-%d\")\n self._log_file_path = f\"{base_name}_{today}.log\"\n else:\n self._log_file_path = log_path\n except Exception as e:\n # 如果配置读取失败,使用默认路径\n today = datetime.now().strftime(\"%Y-%m-%d\")\n self._log_file_path = os.path.join(\n self._log_dir, f\"unified_{today}.log\"\n )\n if not self._write_error_warned:\n print(f\"[GUI日志] 配置读取失败,使用默认路径: {e}\", file=sys.stderr)\n\n def write(self, line: str) -> None:\n \"\"\"线程安全地写入日志行到文件\"\"\"\n if not self._log_file_enabled:\n return\n\n if not line or not line.strip():\n return\n\n with self._lock:\n try:\n # 检查日期是否变化(如果使用日期日志)\n cfg = read_config()\n use_dated_logs = cfg.get(\"logging\", {}).get(\"use_dated_logs\", True)\n if use_dated_logs:\n today = datetime.now().strftime(\"%Y-%m-%d\")\n current_base = os.path.splitext(self._log_file_path)[0]\n if not current_base.endswith(today):\n # 日期变化,更新文件路径\n base_name = (\n current_base.rsplit(\"_\", 1)[0]\n if \"_\" in os.path.basename(current_base)\n else current_base\n )\n self._log_file_path = f\"{base_name}_{today}.log\"\n\n # 确保目录存在\n log_dir = os.path.dirname(self._log_file_path)\n if log_dir:\n os.makedirs(log_dir, exist_ok=True)\n\n # 写入文件(追加模式,UTF-8编码,带BOM避免Windows乱码)\n with open(\n self._log_file_path, \"a\", encoding=\"utf-8-sig\", errors=\"replace\"\n ) as f:\n # 如果行已经包含时间戳(格式:YYYY-MM-DD HH:MM:SS),直接写入\n # 否则添加时间戳\n if line.strip() and not (line[0].isdigit() and \" - [\" in line):\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")[\n :-3\n ]\n formatted_line = f\"{timestamp} - [GUI] - {line}\\n\"\n else:\n formatted_line = f\"{line}\\n\"\n\n f.write(formatted_line)\n f.flush() # 立即刷新缓冲区,确保日志及时写入磁盘\n\n except PermissionError as e:\n if not self._write_error_warned:\n print(\n f\"[GUI日志] 权限错误,无法写入日志文件: {self._log_file_path}\",\n file=sys.stderr,\n )\n print(f\"[GUI日志] 错误详情: {e}\", file=sys.stderr)\n self._write_error_warned = True\n except Exception as e:\n if not self._write_error_warned:\n print(\n f\"[GUI日志] 写入日志文件失败: {self._log_file_path}\",\n file=sys.stderr,\n )\n print(f\"[GUI日志] 错误详情: {e}\", file=sys.stderr)\n self._write_error_warned = True\n\n # 创建日志写入器实例\n log_writer = ThreadSafeLogWriter()\n\n def _format_gui_log_line(line: str) -> str:\n \"\"\"\n 将“完整日志行”转换为 GUI 显示用的精简版本。\n\n 需求:\n - 文件中:仍然写入完整统一日志(含时间戳 / 级别 / 模块等信息);\n - GUI 中:保留【时间戳 + 业务日志】;\n - 如果该行包含识别/匹配的分数(如 `匹配度=0.87` / `相似度=0.95` / `score=0.83`),\n 需要在 GUI 文本中一并保留/补充出来。\n\n 精简规则(兼容统一日志格式):\n - 统一日志通常形如:\n YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - [线程] - [模块:函数:行号] - [traceId:xxx] - 业务内容\n - GUI 只展示:\n YYYY-MM-DD HH:MM:SS.xxx 业务内容(末尾可追加“(匹配度=..., 相似度=..., score=...)”)\n - 其他不符合该模式的行保持原样。\n \"\"\"\n s = (line or \"\").rstrip(\"\\n\")\n if not s:\n return s\n\n ts_part: str | None = None\n msg_part: str | None = None\n\n # 1)新统一日志格式:[YYYY-MM-DD HH:MM:SS.xxx] [LEVEL] ... 业务内容 字段_xxx=...\n m = re.match(r\"^\\[(\\d{4}-\\d{2}-\\d{2} [0-9:.]+)\\]\\s+\\[[A-Z]+\\]\\s+(.*)$\", s)\n if m:\n ts_part = m.group(1).strip()\n msg_part = m.group(2).strip()\n # 2)旧统一日志格式:YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - ... - 业务内容\n elif s[0].isdigit() and \" - \" in s:\n parts = s.split(\" - \")\n if len(parts) >= 3:\n ts_part = parts[0].strip()\n msg_part = parts[-1].strip()\n\n # 如果没解析出“时间戳 + 业务文案”,原样返回\n if not ts_part or msg_part is None:\n return s\n\n # 从业务文案中拆分出 字段_xxx=yyy,非 score 类字段在 GUI 中隐藏\n keep_tokens: list[str] = []\n\n def _is_score_field(k: str) -> bool:\n kl = k.lower()\n return (\n \"score\" in kl\n or \"match\" in kl\n or \"匹配\" in k\n or \"相似\" in k\n )\n\n for m2 in re.finditer(r\"字段_([^\\s=]+)=([^\\s]+)\", msg_part):\n key = m2.group(1)\n val = m2.group(2)\n if _is_score_field(key):\n keep_tokens.append(f\"{key}={val}\")\n\n # 先把所有 字段_xxx=yyy 从业务文案中移除\n clean_msg = re.sub(r\"\\s*字段_[^\\s=]+=[^\\s]+\", \"\", msg_part).strip()\n\n # 追加需要展示的分数字段\n if keep_tokens:\n clean_msg = f\"{clean_msg} ({', '.join(keep_tokens)})\"\n\n return f\"{ts_part} {clean_msg}\"\n\n # 不符合“完整格式”的行,原样返回\n return s\n\n def on_line(line: str):\n \"\"\"处理日志行:GUI 显示用精简版本,文件写入用完整版本\"\"\"\n # GUI 显示:使用精简后的版本\n try:\n display_line = _format_gui_log_line(line)\n except Exception:\n display_line = line\n q.put(display_line)\n\n # 文件:写入完整日志行(不做精简处理)\n try:\n log_writer.write(line)\n except Exception:\n pass # 文件写入失败不应影响GUI显示\n\n runner = Runner(on_line=on_line)\n\n # 顶部:设备选择 + Y偏移(其余运行参数放到左侧分组,避免重复)\n top = ttk.Frame(root)\n top.pack(fill=X, padx=12, pady=10)\n\n adb_exe = find_adb_executable()\n devices = list_adb_devices(adb_exe)\n device_var = tk.StringVar(value=(devices[0] if devices else \"\"))\n\n ttk.Label(top, text=\"设备:\").pack(side=LEFT)\n device_combo = ttk.Combobox(top, textvariable=device_var, values=devices, width=28)\n device_combo.pack(side=LEFT, padx=(0, 10))\n\n def refresh_devices():\n nonlocal adb_exe\n adb_exe = find_adb_executable()\n devs = list_adb_devices(adb_exe)\n device_combo[\"values\"] = devs\n if devs and not device_var.get():\n device_var.set(devs[0])\n if not adb_exe:\n on_line(\"[设备] 未找到 adb.exe(请确认已安装 platform-tools)\")\n elif not devs:\n on_line(\"[设备] adb 可用,但未发现 device 状态设备(可能未授权/未连接)\")\n\n ttk.Button(top, text=\"刷新设备\", command=refresh_devices).pack(\n side=LEFT, padx=(0, 20)\n )\n\n # 配置区(提前读取配置,供后续使用)\n cfg = read_config()\n\n y_var = tk.IntVar(value=int(cfg.get(\"y_pianyi\", 0) or 0))\n ttk.Label(top, text=\"Y偏移:\").pack(side=LEFT)\n ttk.Spinbox(top, from_=-200, to=200, textvariable=y_var, width=6).pack(\n side=LEFT, padx=(0, 12)\n )\n\n # 中部:左侧配置(使用Notebook标签页)+ 右侧日志/预览(支持拖拽调整宽度)\n mid = ttk.PanedWindow(root, orient=\"horizontal\")\n mid.pack(fill=BOTH, expand=True, padx=12, pady=(0, 12))\n\n left_wrap = ttk.Frame(mid)\n right = ttk.Frame(mid)\n mid.add(left_wrap, weight=0) # 左侧配置区域\n mid.add(right, weight=1) # 右侧日志/预览区域\n\n # 左侧使用Notebook标签页组织配置\n left_notebook = ttk.Notebook(left_wrap)\n left_notebook.pack(fill=BOTH, expand=True)\n needswitch_var = tk.BooleanVar(value=bool(cfg.get(\"needswitch\", True)))\n infinite_loop_var = tk.BooleanVar(\n value=bool(cfg.get(\"infinite_loop_enabled\", False))\n )\n wait_minutes_var = tk.IntVar(value=int(cfg.get(\"wait_minutes\", 5) or 5))\n\n min_value_var = tk.DoubleVar(value=float(cfg.get(\"min_prize_value_yuan\", 0) or 0))\n min_participants_var = tk.IntVar(value=int(cfg.get(\"min_participants\", 0) or 0))\n max_participants_var = tk.IntVar(value=int(cfg.get(\"max_participants\", 0) or 0))\n skip_gt_seconds_var = tk.IntVar(\n value=int(cfg.get(\"skip_if_countdown_gt_seconds\", 900) or 900)\n )\n reset_after_swipes_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"reset_after_swipes_enabled\", False))\n )\n reset_after_swipes_var = tk.IntVar(\n value=int(cfg.get(\"reset_after_swipes\", 10) or 10)\n )\n # 按需求:删除\"自动养号/随机等待/轻微扰动/定时休息\"等设置,仅保留\"推荐页养号(爱心/收藏/评论)\"配置。\n auto_join_var = tk.BooleanVar(value=bool(cfg.get(\"auto_join_fansclub\", False)))\n fansclub_action_var = tk.StringVar(\n value=str(cfg.get(\"fansclub_fail_action\", \"stay\") or \"stay\").lower()\n )\n\n # Web端新增配置变量 - 高价值预约相关\n high_value_fudai_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"high_value_fudai_enabled\", False))\n )\n high_value_fudai_threshold_yuan_var = tk.DoubleVar(\n value=float(cfg.get(\"high_value_fudai_threshold_yuan\", 1000) or 1000)\n )\n high_value_fudai_join_ahead_seconds_var = tk.IntVar(\n value=int(cfg.get(\"high_value_fudai_join_ahead_seconds\", 120) or 120)\n )\n high_value_fudai_max_swipe_back_var = tk.IntVar(\n value=int(cfg.get(\"high_value_fudai_max_swipe_back\", 60) or 60)\n )\n high_value_fudai_max_reservations_var = tk.IntVar(\n value=int(cfg.get(\"high_value_fudai_max_reservations\", 5) or 5)\n )\n high_value_fudai_after_action_var = tk.StringVar(\n value=str(cfg.get(\"high_value_fudai_after_action\", \"continue\") or \"continue\")\n )\n high_value_room_revisit_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"high_value_room_revisit_enabled\", True))\n )\n high_value_room_revisit_only_current_run_var = tk.BooleanVar(\n value=bool(cfg.get(\"high_value_room_revisit_only_current_run\", False))\n )\n reservation_back_verify_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"reservation_back_verify_enabled\", True))\n )\n reservation_back_swipe_delay_var = tk.DoubleVar(\n value=float(cfg.get(\"reservation_back_swipe_delay\", 0) or 0)\n )\n reservation_preempt_min_value_var = tk.DoubleVar(\n value=float(cfg.get(\"reservation_preempt_min_value\", 0) or 0)\n )\n fudai_find_max_attempts_var = tk.IntVar(\n value=int(cfg.get(\"fudai_find_max_attempts\", 0) or 0)\n )\n fudai_icon_retry_delay_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_icon_retry_delay_seconds\", 0.6) or 0.6)\n )\n fudai_icon_max_wait_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_icon_max_wait_seconds\", 5.0) or 5.0)\n )\n fudai_click_wait_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_click_wait_seconds\", 2.0) or 2.0)\n )\n switch_room_wait_after_stage_diag_seconds_var = tk.DoubleVar(\n value=float(cfg.get(\"switch_room_wait_after_stage_diag_seconds\", 7.0) or 7.0)\n )\n live_room_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"live_room_match_threshold\", 0.8) or 0.8)\n )\n\n # 推荐页养号:爱心/收藏/评论(基于图标模板匹配 + 坐标点击)\n yg_enabled_var = tk.BooleanVar(value=bool(cfg.get(\"yanghao_enabled\", True)))\n yg_actions_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"yanghao_enable_actions\", True))\n )\n yg_recommend_duration_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_recommend_duration_seconds\", 60) or 60)\n )\n yg_recommend_interval_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_recommend_interval_seconds\", 0) or 0)\n )\n yg_like_prob_var = tk.DoubleVar(\n value=float(cfg.get(\"yanghao_like_prob\", 0.0) or 0.0)\n )\n yg_fav_prob_var = tk.DoubleVar(value=float(cfg.get(\"yanghao_fav_prob\", 0.0) or 0.0))\n yg_comment_prob_var = tk.DoubleVar(\n value=float(cfg.get(\"yanghao_comment_prob\", 0.0) or 0.0)\n )\n yg_icon_roi_size_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_icon_roi_size\", 240) or 240)\n )\n yg_icon_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"yanghao_icon_match_threshold\", 0.72) or 0.72)\n )\n yg_step_screenshot_var = tk.BooleanVar(\n value=bool(cfg.get(\"yanghao_step_screenshot\", False))\n )\n yg_like_roi_offset_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_like_roi_offset_x\", 0) or 0)\n )\n yg_like_roi_offset_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_like_roi_offset_y\", 0) or 0)\n )\n yg_fav_roi_offset_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_fav_roi_offset_x\", 0) or 0)\n )\n yg_fav_roi_offset_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_fav_roi_offset_y\", 0) or 0)\n )\n yg_like_icon_x_var = tk.IntVar(value=int(cfg.get(\"yanghao_like_icon_x\", 0) or 0))\n yg_like_icon_y_var = tk.IntVar(value=int(cfg.get(\"yanghao_like_icon_y\", 0) or 0))\n yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get(\"yanghao_fav_icon_x\", 0) or 0))\n yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get(\"yanghao_fav_icon_y\", 0) or 0))\n yg_like_template_path_var = tk.StringVar(\n value=str(\n cfg.get(\"yanghao_like_template_path\", \"assets/like.png\")\n or \"assets/like.png\"\n )\n )\n yg_fav_template_path_var = tk.StringVar(\n value=str(\n cfg.get(\"yanghao_fav_template_path\", \"assets/fav.png\") or \"assets/fav.png\"\n )\n )\n yg_after_dwell_direction_var = tk.StringVar(\n value=str(cfg.get(\"yanghao_after_dwell_swipe_direction\", \"up\") or \"up\")\n )\n yg_after_dwell_distance_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_after_dwell_swipe_distance_px\", 900) or 900)\n )\n yg_comment_btn_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_btn_x\", 0) or 0)\n )\n yg_comment_btn_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_btn_y\", 0) or 0)\n )\n yg_comment_input_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_input_x\", 0) or 0)\n )\n yg_comment_input_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_input_y\", 0) or 0)\n )\n yg_comment_send_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_send_x\", 0) or 0)\n )\n yg_comment_send_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_send_y\", 0) or 0)\n )\n yg_comment_close_x_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_close_x\", 0) or 0)\n )\n yg_comment_close_y_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_comment_close_y\", 0) or 0)\n )\n fudai_quiet_hours_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"fudai_quiet_hours_enabled\", True))\n )\n fudai_quiet_start_hour_var = tk.IntVar(\n value=int(cfg.get(\"fudai_quiet_start_hour\", 2) or 2)\n )\n fudai_quiet_end_hour_var = tk.IntVar(\n value=int(cfg.get(\"fudai_quiet_end_hour\", 7) or 7)\n )\n\n # 阶段诊断时间参数(用于调试)\n stage_diag_max_time_var = tk.DoubleVar(\n value=float(cfg.get(\"stage_diag_max_time\", 10.0) or 10.0)\n )\n stage_diag_max_step_time_var = tk.DoubleVar(\n value=float(cfg.get(\"stage_diag_max_step_time\", 2.0) or 2.0)\n )\n enable_ocr_mode1_var = tk.BooleanVar(value=bool(cfg.get(\"enable_ocr_mode1\", False)))\n # 福袋模板匹配开关和阈值\n fudai_template_match_enabled_var = tk.BooleanVar(\n value=bool(cfg.get(\"fudai_template_match_enabled\", False))\n )\n fudai_template_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_template_match_threshold\", 0.7) or 0.7)\n )\n # 福袋详情页模板匹配阈值(0.0~1.0,默认0.7)\n fudai_detail_template_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"fudai_detail_template_threshold\", 0.7) or 0.7)\n )\n # 开奖页面红色占比阈值(0.0~1.0,默认0.9)\n lucky_draw_red_ratio_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"lucky_draw_red_ratio_threshold\", 0.9) or 0.9)\n )\n # 优惠券模板匹配阈值(0.0~1.0,默认0.75)\n coupon_template_match_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"coupon_template_match_threshold\", 0.75) or 0.75)\n )\n # 参与按钮红色占比阈值(0.0~1.0,默认0.25)\n attend_button_red_ratio_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"attend_button_red_ratio_threshold\", 0.25) or 0.25)\n )\n # 粉丝团加入红色占比阈值(0.0~1.0,默认0.25)\n fansclub_join_red_ratio_threshold_var = tk.DoubleVar(\n value=float(cfg.get(\"fansclub_join_red_ratio_threshold\", 0.25) or 0.25)\n )\n\n # 调试图像开关 & 清理相关变量\n debug_captures_enabled_var = tk.BooleanVar(\n value=bool(\n cfg.get(\"debug_captures\", {}).get(\"enabled\", False)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else False\n )\n )\n # 调试图像清理相关变量\n debug_captures_auto_cleanup_var = tk.BooleanVar(\n value=bool(\n cfg.get(\"debug_captures\", {}).get(\"auto_cleanup\", True)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else True\n )\n )\n debug_captures_keep_days_var = tk.IntVar(\n value=int(\n cfg.get(\"debug_captures\", {}).get(\"keep_days\", 7)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else 7\n )\n )\n debug_captures_max_files_var = tk.IntVar(\n value=int(\n cfg.get(\"debug_captures\", {}).get(\"max_files\", 2000)\n if isinstance(cfg.get(\"debug_captures\"), dict)\n else 2000\n )\n )\n\n # 倒计时小于阈值参数\n skip_lt_seconds_var = tk.IntVar(\n value=int(cfg.get(\"skip_if_countdown_lt_seconds\", 5) or 5)\n )\n\n # 创建左侧配置标签页\n # 标签页1:运行设置\n run_tab = ttk.Frame(left_notebook)\n left_notebook.add(run_tab, text=\"运行设置\")\n\n run_box = ttk.LabelFrame(run_tab, text=\"基本运行参数\")\n run_box.pack(fill=X, padx=10, pady=(10, 10))\n\n r0 = ttk.Frame(run_box)\n r0.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Checkbutton(r0, text=\"允许切换直播间\", variable=needswitch_var).pack(side=LEFT)\n\n r1 = ttk.Frame(run_box)\n r1.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Checkbutton(r1, text=\"无限循环模式\", variable=infinite_loop_var).pack(side=LEFT)\n ttk.Label(r1, text=\"运行时长(分钟):\").pack(side=LEFT, padx=(10, 0))\n wait_minutes_spinbox = ttk.Spinbox(\n r1, from_=1, to=60, textvariable=wait_minutes_var, width=6\n )\n wait_minutes_spinbox.pack(side=LEFT, padx=(0, 12))\n\n # 根据无限循环开关状态,启用/禁用运行时长输入框\n def update_wait_minutes_state(*args):\n if infinite_loop_var.get():\n wait_minutes_spinbox.config(state=\"disabled\")\n else:\n wait_minutes_spinbox.config(state=\"normal\")\n\n infinite_loop_var.trace(\"w\", update_wait_minutes_state)\n update_wait_minutes_state() # 初始化状态\n\n ttk.Label(r1, text=\"倒计时大于(秒)时不参与(高价值可预约):\").pack(side=LEFT)\n ttk.Spinbox(r1, from_=0, to=3600, textvariable=skip_gt_seconds_var, width=6).pack(\n side=LEFT\n )\n\n r2 = ttk.Frame(run_box)\n r2.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Checkbutton(\n r2, text=\"切换N次后回到第一个\", variable=reset_after_swipes_enabled_var\n ).pack(side=LEFT)\n ttk.Label(r2, text=\"次数:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n r2, from_=1, to=9999, textvariable=reset_after_swipes_var, width=6\n ).pack(side=LEFT)\n ttk.Label(r2, text=\"(触发后会向上回退)\").pack(side=LEFT, padx=(6, 0))\n\n # 标签页2:筛选设置\n filter_tab = ttk.Frame(left_notebook)\n left_notebook.add(filter_tab, text=\"筛选设置\")\n\n cfg_box = ttk.LabelFrame(filter_tab, text=\"福袋筛选条件\")\n cfg_box.pack(fill=X, padx=10, pady=(10, 10))\n\n row = ttk.Frame(cfg_box)\n row.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Label(row, text=\"最低价值(元):\").pack(side=LEFT)\n ttk.Spinbox(\n row, from_=0, to=99999, increment=1, textvariable=min_value_var, width=10\n ).pack(side=LEFT)\n\n rowp = ttk.Frame(cfg_box)\n rowp.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(rowp, text=\"参与人数范围:\").pack(side=LEFT)\n ttk.Spinbox(\n rowp,\n from_=0,\n to=99999999,\n increment=1,\n textvariable=min_participants_var,\n width=10,\n ).pack(side=LEFT)\n ttk.Label(rowp, text=\" ~ \").pack(side=LEFT)\n ttk.Spinbox(\n rowp,\n from_=0,\n to=99999999,\n increment=1,\n textvariable=max_participants_var,\n width=10,\n ).pack(side=LEFT)\n ttk.Label(rowp, text=\"(填0表示不限制)\").pack(side=LEFT)\n\n row2 = ttk.Frame(cfg_box)\n row2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row2, text=\"倒计时小于(秒)时不参与:\").pack(side=LEFT)\n ttk.Spinbox(\n row2, from_=0, to=300, increment=1, textvariable=skip_lt_seconds_var, width=6\n ).pack(side=LEFT)\n ttk.Label(row2, text=\"(剩余时间太短,不参与)\").pack(side=LEFT, padx=(6, 0))\n\n row3 = ttk.Frame(cfg_box)\n row3.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n row3, text=\"自动加入粉丝团(谨慎:可能消耗钻石)\", variable=auto_join_var\n ).pack(side=LEFT)\n\n row4 = ttk.Frame(cfg_box)\n row4.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(row4, text=\"粉丝团失败策略:\").pack(side=LEFT)\n ttk.Combobox(\n row4,\n textvariable=fansclub_action_var,\n values=[\"stay\", \"switch\"],\n width=10,\n state=\"readonly\",\n ).pack(side=LEFT)\n ttk.Label(row4, text=\"(stay=停留,switch=切换直播间)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 标签页3:高价值预约\n reservation_tab_left = ttk.Frame(left_notebook)\n left_notebook.add(reservation_tab_left, text=\"高价值预约\")\n\n reservation_box = ttk.LabelFrame(reservation_tab_left, text=\"高价值福袋预约参与\")\n reservation_box.pack(fill=X, padx=10, pady=(10, 10))\n\n # 预约启用开关\n res_r0 = ttk.Frame(reservation_box)\n res_r0.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Checkbutton(\n res_r0, text=\"启用预约(价值≥阈值)\", variable=high_value_fudai_enabled_var\n ).pack(side=LEFT)\n\n # 价值阈值和提前参与时间\n res_r1 = ttk.Frame(reservation_box)\n res_r1.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(res_r1, text=\"价值阈值(元):\").pack(side=LEFT)\n ttk.Spinbox(\n res_r1,\n from_=0,\n to=99999,\n increment=100,\n textvariable=high_value_fudai_threshold_yuan_var,\n width=10,\n ).pack(side=LEFT)\n ttk.Label(res_r1, text=\"提前参与(秒):\").pack(side=LEFT, padx=(20, 0))\n ttk.Spinbox(\n res_r1,\n from_=5,\n to=900,\n increment=10,\n textvariable=high_value_fudai_join_ahead_seconds_var,\n width=8,\n ).pack(side=LEFT)\n\n # 最多回退次数\n res_r2 = ttk.Frame(reservation_box)\n res_r2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(res_r2, text=\"最多回退直播间次数:\").pack(side=LEFT)\n ttk.Spinbox(\n res_r2,\n from_=0,\n to=300,\n increment=5,\n textvariable=high_value_fudai_max_swipe_back_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(res_r2, text=\"(0=不限制)\").pack(side=LEFT, padx=(6, 0))\n\n # 最多记录数量和完成后策略\n res_r3 = ttk.Frame(reservation_box)\n res_r3.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(res_r3, text=\"最多记录数量:\").pack(side=LEFT)\n ttk.Spinbox(\n res_r3,\n from_=1,\n to=50,\n increment=1,\n textvariable=high_value_fudai_max_reservations_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(res_r3, text=\"完成后策略:\").pack(side=LEFT, padx=(20, 0))\n ttk.Combobox(\n res_r3,\n textvariable=high_value_fudai_after_action_var,\n values=[\"continue\", \"stay\"],\n width=10,\n state=\"readonly\",\n ).pack(side=LEFT)\n ttk.Label(res_r3, text=\"(stay=停留,continue=继续)\").pack(side=LEFT, padx=(6, 0))\n\n # 高价值房间回访\n res_r4 = ttk.Frame(reservation_box)\n res_r4.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n res_r4, text=\"启用高价值房间回访\", variable=high_value_room_revisit_enabled_var\n ).pack(side=LEFT)\n ttk.Checkbutton(\n res_r4, text=\"仅当前运行\", variable=high_value_room_revisit_only_current_run_var\n ).pack(side=LEFT, padx=(20, 0))\n\n # 预约回退校验\n res_r5 = ttk.Frame(reservation_box)\n res_r5.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n res_r5, text=\"预约回退校验\", variable=reservation_back_verify_enabled_var\n ).pack(side=LEFT)\n\n # 回退滑延迟和预约抢占最小价值\n res_r6 = ttk.Frame(reservation_box)\n res_r6.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(res_r6, text=\"回退滑延迟(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n res_r6,\n from_=0.0,\n to=10.0,\n increment=0.1,\n textvariable=reservation_back_swipe_delay_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(res_r6, text=\"预约抢占最小价值(元):\").pack(side=LEFT, padx=(20, 0))\n ttk.Spinbox(\n res_r6,\n from_=0,\n to=99999,\n increment=100,\n textvariable=reservation_preempt_min_value_var,\n width=10,\n ).pack(side=LEFT)\n\n # 标签页4:养号设置\n yanghao_tab = ttk.Frame(left_notebook)\n left_notebook.add(yanghao_tab, text=\"养号设置\")\n\n yg_box = ttk.LabelFrame(yanghao_tab, text=\"推荐页养号(爱心/收藏/评论)\")\n yg_box.pack(fill=X, padx=10, pady=(10, 10))\n\n yg_switch = ttk.Frame(yg_box)\n yg_switch.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Checkbutton(\n yg_switch, text=\"养号总开关(关闭则跳过推荐页养号)\", variable=yg_enabled_var\n ).pack(side=LEFT)\n ttk.Checkbutton(\n yg_switch,\n text=\"启用养号动作(爱心/收藏/评论)\",\n variable=yg_actions_enabled_var,\n ).pack(side=LEFT, padx=(10, 0))\n\n yg0 = ttk.Frame(yg_box)\n yg0.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Checkbutton(\n yg0,\n text=\"逐步截图(调试用,生成 pic/*/latest.png)\",\n variable=yg_step_screenshot_var,\n ).pack(side=LEFT)\n\n yg_time = ttk.Frame(yg_box)\n yg_time.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(yg_time, text=\"养号时长(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n yg_time,\n from_=1,\n to=3600,\n increment=5,\n textvariable=yg_recommend_duration_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(yg_time, text=\"养号间隔(秒):\").pack(side=LEFT, padx=(12, 0))\n ttk.Spinbox(\n yg_time,\n from_=0,\n to=3600,\n increment=10,\n textvariable=yg_recommend_interval_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(yg_time, text=\"(0=每次触发都执行)\").pack(side=LEFT, padx=(6, 0))\n\n yg1 = ttk.Frame(yg_box)\n yg1.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(yg1, text=\"爱心概率:\").pack(side=LEFT)\n ttk.Spinbox(\n yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_like_prob_var, width=6\n ).pack(side=LEFT)\n ttk.Label(yg1, text=\"收藏概率:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n yg1, from_=0.0, to=1.0, increment=0.05, textvariable=yg_fav_prob_var, width=6\n ).pack(side=LEFT)\n ttk.Label(yg1, text=\"评论概率:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n yg1,\n from_=0.0,\n to=1.0,\n increment=0.05,\n textvariable=yg_comment_prob_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(yg1, text=\"(0~1)\").pack(side=LEFT, padx=(6, 0))\n\n yg2 = ttk.Frame(yg_box)\n yg2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(yg2, text=\"图标ROI大小(px):\").pack(side=LEFT)\n ttk.Spinbox(\n yg2, from_=80, to=600, increment=10, textvariable=yg_icon_roi_size_var, width=6\n ).pack(side=LEFT)\n ttk.Label(yg2, text=\"匹配阈值:\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n yg2,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=yg_icon_match_threshold_var,\n width=6,\n ).pack(side=LEFT)\n\n yg_texts = ttk.Frame(yg_box)\n yg_texts.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))\n ttk.Label(yg_texts, text=\"评论文案库(每行一条):\").pack(anchor=\"w\")\n yg_comment_texts = ScrolledText(yg_texts, height=4)\n yg_comment_texts.pack(fill=X, pady=(0, 6))\n yg_kw = ttk.Frame(yg_texts)\n yg_kw.pack(fill=BOTH, expand=True)\n ttk.Label(yg_kw, text=\"爱心关键词(每行一条):\").pack(anchor=\"w\")\n yg_like_keywords_text = ScrolledText(yg_kw, height=3)\n yg_like_keywords_text.pack(fill=X, pady=(0, 6))\n ttk.Label(yg_kw, text=\"收藏关键词(每行一条):\").pack(anchor=\"w\")\n yg_fav_keywords_text = ScrolledText(yg_kw, height=3)\n yg_fav_keywords_text.pack(fill=X)\n\n quiet_box = ttk.LabelFrame(yanghao_tab, text=\"定时禁抢(仅养号)\")\n quiet_box.pack(fill=X, padx=10, pady=(0, 10))\n quiet_r0 = ttk.Frame(quiet_box)\n quiet_r0.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Checkbutton(\n quiet_r0, text=\"启用定时禁抢\", variable=fudai_quiet_hours_enabled_var\n ).pack(side=LEFT)\n quiet_r1 = ttk.Frame(quiet_box)\n quiet_r1.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(quiet_r1, text=\"开始小时:\").pack(side=LEFT)\n ttk.Spinbox(\n quiet_r1, from_=0, to=23, textvariable=fudai_quiet_start_hour_var, width=6\n ).pack(side=LEFT)\n ttk.Label(quiet_r1, text=\"结束小时:\").pack(side=LEFT, padx=(12, 0))\n ttk.Spinbox(\n quiet_r1, from_=0, to=23, textvariable=fudai_quiet_end_hour_var, width=6\n ).pack(side=LEFT)\n\n # 标签页5:调试参数\n debug_tab = ttk.Frame(left_notebook)\n left_notebook.add(debug_tab, text=\"调试参数\")\n\n # 调试图像\n debug_captures_box = ttk.LabelFrame(debug_tab, text=\"调试图像\")\n debug_captures_box.pack(fill=X, padx=10, pady=(10, 10))\n\n debug_r0 = ttk.Frame(debug_captures_box)\n debug_r0.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Checkbutton(\n debug_r0,\n text=\"保存调试图像(OCR / 像素 / 模板等)\",\n variable=debug_captures_enabled_var,\n ).pack(side=LEFT)\n\n debug_cleanup_box = ttk.LabelFrame(debug_tab, text=\"调试图像清理\")\n debug_cleanup_box.pack(fill=X, padx=10, pady=(0, 10))\n\n debug_r1 = ttk.Frame(debug_cleanup_box)\n debug_r1.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Checkbutton(\n debug_r1, text=\"启用自动清理调试图像\", variable=debug_captures_auto_cleanup_var\n ).pack(side=LEFT)\n\n debug_r2 = ttk.Frame(debug_cleanup_box)\n debug_r2.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(debug_r2, text=\"保留天数:\").pack(side=LEFT)\n ttk.Spinbox(\n debug_r2,\n from_=1,\n to=30,\n increment=1,\n textvariable=debug_captures_keep_days_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(debug_r2, text=\"最大文件数量:\").pack(side=LEFT, padx=(20, 0))\n ttk.Spinbox(\n debug_r2,\n from_=100,\n to=10000,\n increment=100,\n textvariable=debug_captures_max_files_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(debug_r2, text=\"(超过此数量自动清理)\").pack(side=LEFT, padx=(6, 0))\n\n # 找福袋参数\n fudai_find_box = ttk.LabelFrame(debug_tab, text=\"找福袋参数\")\n fudai_find_box.pack(fill=X, padx=10, pady=(0, 10))\n\n row4 = ttk.Frame(fudai_find_box)\n row4.pack(fill=X, padx=10, pady=(10, 8))\n ttk.Label(row4, text=\"找福袋最大尝试次数:\").pack(side=LEFT)\n ttk.Spinbox(\n row4,\n from_=0,\n to=50,\n increment=1,\n textvariable=fudai_find_max_attempts_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4, text=\"(0=使用默认值)\").pack(side=LEFT, padx=(6, 0))\n\n row4b = ttk.Frame(fudai_find_box)\n row4b.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row4b, text=\"找福袋重试间隔(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n row4b,\n from_=0.1,\n to=3.0,\n increment=0.1,\n textvariable=fudai_icon_retry_delay_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4b, text=\" 最大等待时间(秒):\").pack(side=LEFT, padx=(10, 0))\n ttk.Spinbox(\n row4b,\n from_=0.0,\n to=30.0,\n increment=0.5,\n textvariable=fudai_icon_max_wait_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4b, text=\"(实际识别常见 4-6 秒)\").pack(side=LEFT, padx=(6, 0))\n\n row4d = ttk.Frame(fudai_find_box)\n row4d.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row4d, text=\"点击福袋后等待时间(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n row4d,\n from_=0.5,\n to=10.0,\n increment=0.1,\n textvariable=fudai_click_wait_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4d, text=\"(等待福袋详情页加载,默认2.0秒)\").pack(side=LEFT, padx=(6, 0))\n\n row4e = ttk.Frame(fudai_find_box)\n row4e.pack(fill=X, padx=10, pady=(0, 8))\n ttk.Label(row4e, text=\"切换直播间后等待时间(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n row4e,\n from_=0.0,\n to=30.0,\n increment=0.5,\n textvariable=switch_room_wait_after_stage_diag_seconds_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4e, text=\"(阶段检测后等待福袋加载,默认7.0秒)\").pack(side=LEFT, padx=(6, 0))\n\n row4c = ttk.Frame(fudai_find_box)\n row4c.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(row4c, text=\"直播间检测阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n row4c,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=live_room_match_threshold_var,\n width=6,\n ).pack(side=LEFT)\n ttk.Label(row4c, text=\"(0.0~1.0,默认0.7,值越高越严格)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 阶段诊断时间参数(用于调试)\n diag_time_box = ttk.LabelFrame(debug_tab, text=\"阶段诊断时间参数\")\n diag_time_box.pack(fill=X, padx=10, pady=(0, 10))\n diag_time_r1 = ttk.Frame(diag_time_box)\n diag_time_r1.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Label(diag_time_r1, text=\"最大诊断时间(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r1,\n from_=1.0,\n to=60.0,\n increment=1.0,\n textvariable=stage_diag_max_time_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r1, text=\"每步最大耗时(秒):\").pack(side=LEFT, padx=(12, 0))\n ttk.Spinbox(\n diag_time_r1,\n from_=0.5,\n to=30.0,\n increment=0.5,\n textvariable=stage_diag_max_step_time_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r1, text=\"(用于调试,延长检测时间)\").pack(\n side=LEFT, padx=(6, 0)\n )\n diag_time_r2 = ttk.Frame(diag_time_box)\n diag_time_r2.pack(fill=X, padx=10, pady=(0, 6))\n ttk.Checkbutton(\n diag_time_r2, text=\"启用OCR模式1(二值化)\", variable=enable_ocr_mode1_var\n ).pack(side=LEFT)\n diag_time_r2b = ttk.Frame(diag_time_box)\n diag_time_r2b.pack(fill=X, padx=10, pady=(0, 6))\n ttk.Checkbutton(\n diag_time_r2b,\n text=\"启用福袋模板匹配\",\n variable=fudai_template_match_enabled_var,\n ).pack(side=LEFT)\n diag_time_r3 = ttk.Frame(diag_time_box)\n diag_time_r3.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(diag_time_r3, text=\"福袋模板匹配阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r3,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=fudai_template_match_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r3, text=\"(0.0-1.0,彩色匹配)\").pack(side=LEFT, padx=(6, 0))\n\n diag_time_r3b = ttk.Frame(diag_time_box)\n diag_time_r3b.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(diag_time_r3b, text=\"福袋详情页模板匹配阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r3b,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=fudai_detail_template_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r3b, text=\"(0.0-1.0,默认0.7,区域(398,894)-(658,1179))\").pack(side=LEFT, padx=(6, 0))\n\n diag_time_r4 = ttk.Frame(diag_time_box)\n diag_time_r4.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(diag_time_r4, text=\"开奖页红色占比阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r4,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=lucky_draw_red_ratio_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r4, text=\"(默认0.90,≥此占比判定开奖页)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 更多模板匹配阈值\n diag_time_r5 = ttk.Frame(diag_time_box)\n diag_time_r5.pack(fill=X, padx=10, pady=(0, 6))\n ttk.Label(diag_time_r5, text=\"优惠券模板匹配阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n diag_time_r5,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=coupon_template_match_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(diag_time_r5, text=\"(默认0.75,用于检测优惠券弹窗)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 像素检测阈值\n pixel_detect_box = ttk.LabelFrame(debug_tab, text=\"像素检测阈值\")\n pixel_detect_box.pack(fill=X, padx=10, pady=(0, 10))\n\n pixel_r1 = ttk.Frame(pixel_detect_box)\n pixel_r1.pack(fill=X, padx=10, pady=(10, 6))\n ttk.Label(pixel_r1, text=\"参与按钮红色占比阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n pixel_r1,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=attend_button_red_ratio_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(pixel_r1, text=\"(默认0.25,用于检测参与按钮)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n pixel_r2 = ttk.Frame(pixel_detect_box)\n pixel_r2.pack(fill=X, padx=10, pady=(0, 10))\n ttk.Label(pixel_r2, text=\"粉丝团加入红色占比阈值:\").pack(side=LEFT)\n ttk.Spinbox(\n pixel_r2,\n from_=0.0,\n to=1.0,\n increment=0.01,\n textvariable=fansclub_join_red_ratio_threshold_var,\n width=8,\n ).pack(side=LEFT)\n ttk.Label(pixel_r2, text=\"(默认0.25,用于检测粉丝团加入按钮)\").pack(\n side=LEFT, padx=(6, 0)\n )\n\n # 标签页6:关键词\n keywords_tab = ttk.Frame(left_notebook)\n left_notebook.add(keywords_tab, text=\"关键词\")\n\n kw_box = ttk.LabelFrame(keywords_tab, text=\"关键词(每行一个,仅黑名单)\")\n kw_box.pack(fill=BOTH, expand=True, padx=10, pady=(10, 10))\n\n ttk.Label(kw_box, text=\"不想要 contains_not_want(黑名单)\").pack(\n anchor=\"w\", padx=10, pady=(10, 4)\n )\n not_want_text = ScrolledText(kw_box, height=8)\n not_want_text.pack(fill=X, padx=10, pady=(0, 10))\n\n def load_config_to_ui():\n nonlocal cfg\n cfg = read_config()\n needswitch_var.set(bool(cfg.get(\"needswitch\", True)))\n infinite_loop_var.set(bool(cfg.get(\"infinite_loop_enabled\", False)))\n wait_minutes_var.set(int(cfg.get(\"wait_minutes\", 5) or 5))\n yg_enabled_var.set(bool(cfg.get(\"yanghao_enabled\", True)))\n yg_actions_enabled_var.set(bool(cfg.get(\"yanghao_enable_actions\", True)))\n yg_recommend_duration_var.set(\n int(cfg.get(\"yanghao_recommend_duration_seconds\", 60) or 60)\n )\n yg_recommend_interval_var.set(\n int(cfg.get(\"yanghao_recommend_interval_seconds\", 0) or 0)\n )\n min_value_var.set(float(cfg.get(\"min_prize_value_yuan\", 0) or 0))\n min_participants_var.set(int(cfg.get(\"min_participants\", 0) or 0))\n max_participants_var.set(int(cfg.get(\"max_participants\", 0) or 0))\n skip_gt_seconds_var.set(\n int(cfg.get(\"skip_if_countdown_gt_seconds\", 900) or 900)\n )\n reset_after_swipes_enabled_var.set(\n bool(cfg.get(\"reset_after_swipes_enabled\", False))\n )\n reset_after_swipes_var.set(int(cfg.get(\"reset_after_swipes\", 10) or 10))\n auto_join_var.set(bool(cfg.get(\"auto_join_fansclub\", False)))\n fansclub_action_var.set(\n str(cfg.get(\"fansclub_fail_action\", \"stay\") or \"stay\").lower()\n )\n lucky_draw_red_ratio_threshold_var.set(\n float(cfg.get(\"lucky_draw_red_ratio_threshold\", 0.9) or 0.9)\n )\n y_var.set(int(cfg.get(\"y_pianyi\", 0) or 0))\n\n # Web端新增配置 - 高价值预约相关\n high_value_fudai_enabled_var.set(\n bool(cfg.get(\"high_value_fudai_enabled\", False))\n )\n high_value_fudai_threshold_yuan_var.set(\n float(cfg.get(\"high_value_fudai_threshold_yuan\", 1000) or 1000)\n )\n high_value_fudai_join_ahead_seconds_var.set(\n int(cfg.get(\"high_value_fudai_join_ahead_seconds\", 120) or 120)\n )\n high_value_fudai_max_swipe_back_var.set(\n int(cfg.get(\"high_value_fudai_max_swipe_back\", 60) or 60)\n )\n high_value_fudai_max_reservations_var.set(\n int(cfg.get(\"high_value_fudai_max_reservations\", 5) or 5)\n )\n high_value_fudai_after_action_var.set(\n str(cfg.get(\"high_value_fudai_after_action\", \"continue\") or \"continue\")\n )\n high_value_room_revisit_enabled_var.set(\n bool(cfg.get(\"high_value_room_revisit_enabled\", True))\n )\n high_value_room_revisit_only_current_run_var.set(\n bool(cfg.get(\"high_value_room_revisit_only_current_run\", False))\n )\n reservation_back_verify_enabled_var.set(\n bool(cfg.get(\"reservation_back_verify_enabled\", True))\n )\n reservation_back_swipe_delay_var.set(\n float(cfg.get(\"reservation_back_swipe_delay\", 0) or 0)\n )\n reservation_preempt_min_value_var.set(\n float(cfg.get(\"reservation_preempt_min_value\", 0) or 0)\n )\n fudai_find_max_attempts_var.set(int(cfg.get(\"fudai_find_max_attempts\", 0) or 0))\n fudai_icon_retry_delay_seconds_var.set(\n float(cfg.get(\"fudai_icon_retry_delay_seconds\", 0.6) or 0.6)\n )\n fudai_icon_max_wait_seconds_var.set(\n float(cfg.get(\"fudai_icon_max_wait_seconds\", 5.0) or 5.0)\n )\n fudai_click_wait_seconds_var.set(\n float(cfg.get(\"fudai_click_wait_seconds\", 2.0) or 2.0)\n )\n switch_room_wait_after_stage_diag_seconds_var.set(\n float(cfg.get(\"switch_room_wait_after_stage_diag_seconds\", 7.0) or 7.0)\n )\n live_room_match_threshold_var.set(\n float(cfg.get(\"live_room_match_threshold\", 0.8) or 0.8)\n )\n fudai_quiet_hours_enabled_var.set(\n bool(cfg.get(\"fudai_quiet_hours_enabled\", True))\n )\n fudai_quiet_start_hour_var.set(int(cfg.get(\"fudai_quiet_start_hour\", 2) or 2))\n fudai_quiet_end_hour_var.set(int(cfg.get(\"fudai_quiet_end_hour\", 7) or 7))\n stage_diag_max_time_var.set(float(cfg.get(\"stage_diag_max_time\", 10.0) or 10.0))\n stage_diag_max_step_time_var.set(\n float(cfg.get(\"stage_diag_max_step_time\", 2.0) or 2.0)\n )\n enable_ocr_mode1_var.set(bool(cfg.get(\"enable_ocr_mode1\", False)))\n fudai_template_match_enabled_var.set(\n bool(cfg.get(\"fudai_template_match_enabled\", False))\n )\n fudai_template_match_threshold_var.set(\n float(cfg.get(\"fudai_template_match_threshold\", 0.7) or 0.7)\n )\n fudai_detail_template_threshold_var.set(\n float(cfg.get(\"fudai_detail_template_threshold\", 0.7) or 0.7)\n )\n coupon_template_match_threshold_var.set(\n float(cfg.get(\"coupon_template_match_threshold\", 0.75) or 0.75)\n )\n attend_button_red_ratio_threshold_var.set(\n float(cfg.get(\"attend_button_red_ratio_threshold\", 0.25) or 0.25)\n )\n fansclub_join_red_ratio_threshold_var.set(\n float(cfg.get(\"fansclub_join_red_ratio_threshold\", 0.25) or 0.25)\n )\n skip_lt_seconds_var.set(int(cfg.get(\"skip_if_countdown_lt_seconds\", 5) or 5))\n\n # 调试图像清理配置\n debug_captures_config = cfg.get(\"debug_captures\", {})\n if isinstance(debug_captures_config, dict):\n debug_captures_enabled_var.set(\n bool(debug_captures_config.get(\"enabled\", False))\n )\n debug_captures_auto_cleanup_var.set(\n bool(debug_captures_config.get(\"auto_cleanup\", True))\n )\n debug_captures_keep_days_var.set(\n int(debug_captures_config.get(\"keep_days\", 7) or 7)\n )\n debug_captures_max_files_var.set(\n int(debug_captures_config.get(\"max_files\", 2000) or 2000)\n )\n else:\n debug_captures_auto_cleanup_var.set(True)\n debug_captures_keep_days_var.set(7)\n debug_captures_max_files_var.set(2000)\n\n yg_like_prob_var.set(float(cfg.get(\"yanghao_like_prob\", 0.0) or 0.0))\n yg_fav_prob_var.set(float(cfg.get(\"yanghao_fav_prob\", 0.0) or 0.0))\n yg_comment_prob_var.set(float(cfg.get(\"yanghao_comment_prob\", 0.0) or 0.0))\n yg_icon_roi_size_var.set(int(cfg.get(\"yanghao_icon_roi_size\", 240) or 240))\n yg_icon_match_threshold_var.set(\n float(cfg.get(\"yanghao_icon_match_threshold\", 0.72) or 0.72)\n )\n yg_step_screenshot_var.set(bool(cfg.get(\"yanghao_step_screenshot\", False)))\n yg_like_roi_offset_x_var.set(int(cfg.get(\"yanghao_like_roi_offset_x\", 0) or 0))\n yg_like_roi_offset_y_var.set(int(cfg.get(\"yanghao_like_roi_offset_y\", 0) or 0))\n yg_fav_roi_offset_x_var.set(int(cfg.get(\"yanghao_fav_roi_offset_x\", 0) or 0))\n yg_fav_roi_offset_y_var.set(int(cfg.get(\"yanghao_fav_roi_offset_y\", 0) or 0))\n yg_like_icon_x_var.set(int(cfg.get(\"yanghao_like_icon_x\", 0) or 0))\n yg_like_icon_y_var.set(int(cfg.get(\"yanghao_like_icon_y\", 0) or 0))\n yg_fav_icon_x_var.set(int(cfg.get(\"yanghao_fav_icon_x\", 0) or 0))\n yg_fav_icon_y_var.set(int(cfg.get(\"yanghao_fav_icon_y\", 0) or 0))\n yg_like_template_path_var.set(\n str(\n cfg.get(\"yanghao_like_template_path\", \"assets/like.png\")\n or \"assets/like.png\"\n )\n )\n yg_fav_template_path_var.set(\n str(\n cfg.get(\"yanghao_fav_template_path\", \"assets/fav.png\")\n or \"assets/fav.png\"\n )\n )\n yg_after_dwell_direction_var.set(\n str(cfg.get(\"yanghao_after_dwell_swipe_direction\", \"up\") or \"up\")\n )\n yg_after_dwell_distance_var.set(\n int(cfg.get(\"yanghao_after_dwell_swipe_distance_px\", 900) or 900)\n )\n yg_comment_btn_x_var.set(int(cfg.get(\"yanghao_comment_btn_x\", 0) or 0))\n yg_comment_btn_y_var.set(int(cfg.get(\"yanghao_comment_btn_y\", 0) or 0))\n yg_comment_input_x_var.set(int(cfg.get(\"yanghao_comment_input_x\", 0) or 0))\n yg_comment_input_y_var.set(int(cfg.get(\"yanghao_comment_input_y\", 0) or 0))\n yg_comment_send_x_var.set(int(cfg.get(\"yanghao_comment_send_x\", 0) or 0))\n yg_comment_send_y_var.set(int(cfg.get(\"yanghao_comment_send_y\", 0) or 0))\n yg_comment_close_x_var.set(int(cfg.get(\"yanghao_comment_close_x\", 0) or 0))\n yg_comment_close_y_var.set(int(cfg.get(\"yanghao_comment_close_y\", 0) or 0))\n\n # 仅保留黑名单 contains_not_want\n not_want = cfg.get(\"contains_not_want\", []) or []\n yg_comment_texts_list = cfg.get(\"yanghao_comment_texts\", []) or []\n yg_like_keywords_list = cfg.get(\"yanghao_like_keywords\", []) or []\n yg_fav_keywords_list = cfg.get(\"yanghao_fav_keywords\", []) or []\n not_want_text.delete(\"1.0\", \"end\")\n not_want_text.insert(\"1.0\", \"\\n\".join(not_want))\n yg_comment_texts.delete(\"1.0\", \"end\")\n yg_comment_texts.insert(\"1.0\", \"\\n\".join(yg_comment_texts_list))\n yg_like_keywords_text.delete(\"1.0\", \"end\")\n yg_like_keywords_text.insert(\"1.0\", \"\\n\".join(yg_like_keywords_list))\n yg_fav_keywords_text.delete(\"1.0\", \"end\")\n yg_fav_keywords_text.insert(\"1.0\", \"\\n\".join(yg_fav_keywords_list))\n\n def save_ui_to_config():\n # 仅保存黑名单 contains_not_want\n not_want_lines = [\n x.strip() for x in not_want_text.get(\"1.0\", \"end\").splitlines() if x.strip()\n ]\n yg_comment_text_lines = [\n x.strip()\n for x in yg_comment_texts.get(\"1.0\", \"end\").splitlines()\n if x.strip()\n ]\n yg_like_kw_lines = [\n x.strip()\n for x in yg_like_keywords_text.get(\"1.0\", \"end\").splitlines()\n if x.strip()\n ]\n yg_fav_kw_lines = [\n x.strip()\n for x in yg_fav_keywords_text.get(\"1.0\", \"end\").splitlines()\n if x.strip()\n ]\n\n cfg2 = read_config()\n cfg2[\"needswitch\"] = bool(needswitch_var.get())\n cfg2[\"infinite_loop_enabled\"] = bool(infinite_loop_var.get())\n cfg2[\"wait_minutes\"] = int(wait_minutes_var.get() or 5)\n cfg2[\"y_pianyi\"] = int(y_var.get() or 0)\n cfg2[\"contains_not_want\"] = not_want_lines\n cfg2[\"min_prize_value_yuan\"] = float(min_value_var.get() or 0)\n cfg2[\"min_participants\"] = int(min_participants_var.get() or 0)\n cfg2[\"max_participants\"] = int(max_participants_var.get() or 0)\n cfg2[\"skip_if_countdown_gt_seconds\"] = int(skip_gt_seconds_var.get() or 900)\n cfg2[\"reset_after_swipes_enabled\"] = bool(reset_after_swipes_enabled_var.get())\n cfg2[\"reset_after_swipes\"] = int(reset_after_swipes_var.get() or 10)\n cfg2[\"auto_join_fansclub\"] = bool(auto_join_var.get())\n cfg2[\"fansclub_fail_action\"] = str(fansclub_action_var.get() or \"stay\").lower()\n cfg2[\"lucky_draw_red_ratio_threshold\"] = float(\n lucky_draw_red_ratio_threshold_var.get() or 0.9\n )\n\n # Web端新增配置 - 高价值预约相关\n cfg2[\"high_value_fudai_enabled\"] = bool(high_value_fudai_enabled_var.get())\n cfg2[\"high_value_fudai_threshold_yuan\"] = float(\n high_value_fudai_threshold_yuan_var.get() or 1000\n )\n cfg2[\"high_value_fudai_join_ahead_seconds\"] = int(\n high_value_fudai_join_ahead_seconds_var.get() or 120\n )\n cfg2[\"high_value_fudai_max_swipe_back\"] = int(\n high_value_fudai_max_swipe_back_var.get() or 60\n )\n cfg2[\"high_value_fudai_max_reservations\"] = int(\n high_value_fudai_max_reservations_var.get() or 5\n )\n cfg2[\"high_value_fudai_after_action\"] = str(\n high_value_fudai_after_action_var.get() or \"continue\"\n ).lower()\n cfg2[\"high_value_room_revisit_enabled\"] = bool(\n high_value_room_revisit_enabled_var.get()\n )\n cfg2[\"high_value_room_revisit_only_current_run\"] = bool(\n high_value_room_revisit_only_current_run_var.get()\n )\n cfg2[\"reservation_back_verify_enabled\"] = bool(\n reservation_back_verify_enabled_var.get()\n )\n cfg2[\"reservation_back_swipe_delay\"] = float(\n reservation_back_swipe_delay_var.get() or 0\n )\n cfg2[\"reservation_preempt_min_value\"] = float(\n reservation_preempt_min_value_var.get() or 0\n )\n cfg2[\"fudai_find_max_attempts\"] = int(fudai_find_max_attempts_var.get() or 0)\n cfg2[\"fudai_icon_retry_delay_seconds\"] = float(\n fudai_icon_retry_delay_seconds_var.get() or 0.6\n )\n cfg2[\"fudai_icon_max_wait_seconds\"] = float(\n fudai_icon_max_wait_seconds_var.get() or 5.0\n )\n cfg2[\"fudai_click_wait_seconds\"] = float(\n fudai_click_wait_seconds_var.get() or 2.0\n )\n cfg2[\"switch_room_wait_after_stage_diag_seconds\"] = float(\n switch_room_wait_after_stage_diag_seconds_var.get() or 7.0\n )\n cfg2[\"live_room_match_threshold\"] = float(\n live_room_match_threshold_var.get() or 0.8\n )\n cfg2[\"fudai_quiet_hours_enabled\"] = bool(fudai_quiet_hours_enabled_var.get())\n cfg2[\"fudai_quiet_start_hour\"] = int(fudai_quiet_start_hour_var.get() or 0)\n cfg2[\"fudai_quiet_end_hour\"] = int(fudai_quiet_end_hour_var.get() or 0)\n cfg2[\"stage_diag_max_time\"] = float(stage_diag_max_time_var.get() or 10.0)\n cfg2[\"stage_diag_max_step_time\"] = float(\n stage_diag_max_step_time_var.get() or 2.0\n )\n cfg2[\"enable_ocr_mode1\"] = bool(enable_ocr_mode1_var.get())\n cfg2[\"fudai_template_match_enabled\"] = bool(\n fudai_template_match_enabled_var.get()\n )\n cfg2[\"fudai_template_match_threshold\"] = float(\n fudai_template_match_threshold_var.get() or 0.7\n )\n cfg2[\"fudai_detail_template_threshold\"] = float(\n fudai_detail_template_threshold_var.get() or 0.7\n )\n cfg2[\"coupon_template_match_threshold\"] = float(\n coupon_template_match_threshold_var.get() or 0.75\n )\n cfg2[\"attend_button_red_ratio_threshold\"] = float(\n attend_button_red_ratio_threshold_var.get() or 0.25\n )\n cfg2[\"fansclub_join_red_ratio_threshold\"] = float(\n fansclub_join_red_ratio_threshold_var.get() or 0.25\n )\n cfg2[\"skip_if_countdown_lt_seconds\"] = int(skip_lt_seconds_var.get() or 5)\n\n # 调试图像清理配置\n if \"debug_captures\" not in cfg2 or not isinstance(cfg2[\"debug_captures\"], dict):\n cfg2[\"debug_captures\"] = {}\n cfg2[\"debug_captures\"][\"enabled\"] = bool(\n debug_captures_enabled_var.get()\n )\n cfg2[\"debug_captures\"][\"auto_cleanup\"] = bool(\n debug_captures_auto_cleanup_var.get()\n )\n cfg2[\"debug_captures\"][\"keep_days\"] = int(\n debug_captures_keep_days_var.get() or 7\n )\n cfg2[\"debug_captures\"][\"max_files\"] = int(\n debug_captures_max_files_var.get() or 2000\n )\n\n cfg2[\"yanghao_enabled\"] = bool(yg_enabled_var.get())\n cfg2[\"yanghao_enable_actions\"] = bool(yg_actions_enabled_var.get())\n cfg2[\"yanghao_recommend_duration_seconds\"] = int(\n yg_recommend_duration_var.get() or 60\n )\n cfg2[\"yanghao_recommend_interval_seconds\"] = int(\n yg_recommend_interval_var.get() or 0\n )\n cfg2[\"yanghao_like_prob\"] = float(yg_like_prob_var.get() or 0.0)\n cfg2[\"yanghao_fav_prob\"] = float(yg_fav_prob_var.get() or 0.0)\n cfg2[\"yanghao_comment_prob\"] = float(yg_comment_prob_var.get() or 0.0)\n cfg2[\"yanghao_icon_roi_size\"] = int(yg_icon_roi_size_var.get() or 240)\n cfg2[\"yanghao_icon_match_threshold\"] = float(\n yg_icon_match_threshold_var.get() or 0.72\n )\n cfg2[\"yanghao_step_screenshot\"] = bool(yg_step_screenshot_var.get())\n cfg2[\"yanghao_like_roi_offset_x\"] = int(yg_like_roi_offset_x_var.get() or 0)\n cfg2[\"yanghao_like_roi_offset_y\"] = int(yg_like_roi_offset_y_var.get() or 0)\n cfg2[\"yanghao_fav_roi_offset_x\"] = int(yg_fav_roi_offset_x_var.get() or 0)\n cfg2[\"yanghao_fav_roi_offset_y\"] = int(yg_fav_roi_offset_y_var.get() or 0)\n cfg2[\"yanghao_like_icon_x\"] = int(yg_like_icon_x_var.get() or 0)\n cfg2[\"yanghao_like_icon_y\"] = int(yg_like_icon_y_var.get() or 0)\n cfg2[\"yanghao_fav_icon_x\"] = int(yg_fav_icon_x_var.get() or 0)\n cfg2[\"yanghao_fav_icon_y\"] = int(yg_fav_icon_y_var.get() or 0)\n cfg2[\"yanghao_like_template_path\"] = str(\n yg_like_template_path_var.get() or \"assets/like.png\"\n )\n cfg2[\"yanghao_fav_template_path\"] = str(\n yg_fav_template_path_var.get() or \"assets/fav.png\"\n )\n cfg2[\"yanghao_after_dwell_swipe_direction\"] = str(\n yg_after_dwell_direction_var.get() or \"up\"\n )\n cfg2[\"yanghao_after_dwell_swipe_distance_px\"] = int(\n yg_after_dwell_distance_var.get() or 900\n )\n cfg2[\"yanghao_comment_btn_x\"] = int(yg_comment_btn_x_var.get() or 0)\n cfg2[\"yanghao_comment_btn_y\"] = int(yg_comment_btn_y_var.get() or 0)\n cfg2[\"yanghao_comment_input_x\"] = int(yg_comment_input_x_var.get() or 0)\n cfg2[\"yanghao_comment_input_y\"] = int(yg_comment_input_y_var.get() or 0)\n cfg2[\"yanghao_comment_send_x\"] = int(yg_comment_send_x_var.get() or 0)\n cfg2[\"yanghao_comment_send_y\"] = int(yg_comment_send_y_var.get() or 0)\n cfg2[\"yanghao_comment_close_x\"] = int(yg_comment_close_x_var.get() or 0)\n cfg2[\"yanghao_comment_close_y\"] = int(yg_comment_close_y_var.get() or 0)\n cfg2[\"yanghao_comment_texts\"] = yg_comment_text_lines\n cfg2[\"yanghao_like_keywords\"] = yg_like_kw_lines\n cfg2[\"yanghao_fav_keywords\"] = yg_fav_kw_lines\n write_config(cfg2)\n on_line(\"[配置] 已保存到 config.json\")\n\n load_config_to_ui()\n\n # 顶部常驻按钮区域(与设备选择同一行,不随左侧滚动)\n top_btns = ttk.Frame(top)\n top_btns.pack(side=RIGHT, padx=(20, 0))\n ttk.Button(top_btns, text=\"保存配置\", command=save_ui_to_config).pack(\n side=LEFT, padx=(0, 8)\n )\n # 截图+OCR 按钮也放在顶部,方便随时使用\n # 具体回调在后文定义,这里先占位,通过 lambda 延迟绑定\n screenshot_button_var = {\"command\": None}\n\n def _bind_screenshot_button(btn):\n # 在 do_screenshot 定义后调用,将真正的 command 绑定到按钮\n screenshot_button_var[\"button\"] = btn\n\n screenshot_btn = ttk.Button(top_btns, text=\"截图+OCR\")\n screenshot_btn.pack(side=LEFT, padx=(0, 8))\n _bind_screenshot_button(screenshot_btn)\n\n # OCR区域配置:定义所有需要识别的区域(坐标基于1080x2400基准)\n OCR_REGIONS = [\n # (区域名称, (x1, y1, x2, y2), 描述)\n (\"福袋内容\", (390, 1240, 980, 1470), \"福袋内容详情\"),\n (\"福袋倒计时\", (390, 1470, 980, 1580), \"福袋倒计时\"),\n (\"福袋价值\", (390, 1460, 1000, 1580), \"奖品价值/价格\"),\n (\"抽奖结果\", (380, 660, 720, 755), \"抽奖结果弹窗\"),\n (\"推荐页标签栏\", (400, 140, 900, 200), \"推荐/关注/直播标签\"),\n (\"推荐页标签栏快速检测\", (400, 140, 900, 200), \"推荐页快速检测\"),\n (\"参与按钮\", (306, 2030, 780, 2110), \"参与福袋抽奖按钮\"),\n (\"无奖励确认\", (340, 1195, 740, 1355), \"无奖励确认弹窗\"),\n (\"奖励通知确认\", (370, 1350, 680, 1440), \"奖励通知确认\"),\n (\"订单确认\", (370, 120, 700, 220), \"订单确认页面\"),\n (\"关注列表标签\", (658, 147, 765, 194), \"关注列表标签\"),\n (\"直播列表标签\", (400, 140, 900, 200), \"直播列表标签\"),\n (\"直播广场\", (400, 140, 900, 200), \"直播广场标题\"),\n (\"直播间标题_中\", (400, 140, 900, 200), \"直播间标题中部\"),\n (\"诊断优惠券标题\", (60, 1260, 1020, 1480), \"优惠券弹窗标题\"),\n (\"诊断优惠券按钮\", (400, 1600, 680, 1700), \"优惠券按钮\"),\n (\"诊断购物红包\", (400, 1400, 900, 1600), \"购物红包弹窗\"),\n ]\n\n # 截图按钮\n def do_screenshot():\n device_id = device_var.get().strip()\n if not device_id:\n on_line(\"[截图] 请先选择设备\")\n return\n\n # 在后台线程中执行截图和OCR识别,避免阻塞GUI\n def screenshot_thread():\n try:\n from Underlying_Operations import underlying_operations\n from PIL import Image\n import os\n\n # 使用 root.after 在主线程中更新日志\n def log_msg(msg: str) -> Callable[[], None]:\n def wrapper() -> None:\n on_line(msg)\n\n return wrapper\n\n root.after(0, log_msg(\"[截图] 正在截图...\")) # type: ignore[arg-type]\n ops = underlying_operations()\n result = ops.get_screenshot(device_id)\n if not result:\n root.after(0, log_msg(\"[截图] 截图失败\")) # type: ignore[arg-type]\n return\n\n root.after(0, log_msg(\"[截图] 截图成功,已保存到 pic/screenshot.png\")) # type: ignore[arg-type]\n\n # 读取截图以获取实际尺寸\n screenshot_path = os.path.join(\n os.path.dirname(__file__), \"pic\", \"screenshot.png\"\n )\n if not os.path.exists(screenshot_path):\n root.after(0, log_msg(\"[OCR] 截图文件不存在\")) # type: ignore[arg-type]\n return\n\n try:\n img = Image.open(screenshot_path)\n img.load() # Force load to catch truncated files early\n img_width, img_height = img.size\n # 计算缩放比例(基于1080x2400基准)\n scale_x = img_width / 1080.0\n scale_y = img_height / 2400.0\n except (OSError, IOError, SyntaxError) as e:\n # Handle truncated image files\n root.after(0, log_msg(f\"图片文件损坏或截断: {e}\")) # type: ignore[arg-type]\n return\n except Exception as e:\n root.after(0, log_msg(f\"[OCR] 读取截图失败: {e}\")) # type: ignore[arg-type]\n return\n\n # 获取Y偏移\n y_offset = int(y_var.get() or 0)\n\n # 执行所有OCR区域的识别\n ocr_results = []\n total_regions = len(OCR_REGIONS)\n root.after(0, log_msg(f\"[OCR] 开始识别 {total_regions} 个区域...\")) # type: ignore[arg-type]\n\n for idx, (region_name, (x1, y1, x2, y2), desc) in enumerate(\n OCR_REGIONS, 1\n ):\n try:\n # 缩放坐标到实际截图尺寸\n actual_x1 = int(x1 * scale_x)\n actual_y1 = int(y1 * scale_y) + y_offset\n actual_x2 = int(x2 * scale_x)\n actual_y2 = int(y2 * scale_y) + y_offset\n\n # 确保坐标在图片范围内\n actual_x1 = max(0, min(actual_x1, img_width))\n actual_y1 = max(0, min(actual_y1, img_height))\n actual_x2 = max(0, min(actual_x2, img_width))\n actual_y2 = max(0, min(actual_y2, img_height))\n\n if actual_x1 >= actual_x2 or actual_y1 >= actual_y2:\n root.after(0, log_msg(f\"[OCR] {region_name}: 坐标无效,跳过\")) # type: ignore[arg-type]\n continue\n\n # 截取区域\n cut_result = ops.cut_pic(\n (actual_x1, actual_y1),\n (actual_x2, actual_y2),\n \"\",\n region_name,\n )\n if not cut_result:\n root.after(0, log_msg(f\"[OCR] {region_name}: 截图失败\")) # type: ignore[arg-type]\n ocr_results.append((region_name, desc, \"\", \"截图失败\"))\n continue\n\n # OCR识别(先尝试模式0,如果为空再尝试模式1)\n text_result = \"\"\n ocr_mode = 0\n for mode in [0, 1]:\n try:\n text = str(\n ops.analyse_pic_word(region_name, mode) or \"\"\n ).strip()\n if text:\n text_result = text\n ocr_mode = mode\n break\n except Exception:\n continue\n\n ocr_results.append(\n (region_name, desc, text_result, f\"模式{ocr_mode}\")\n )\n status_msg = f\"[OCR] ({idx}/{total_regions}) {region_name}: {text_result[:50] if text_result else '(空)'}\"\n root.after(0, log_msg(status_msg)) # type: ignore[arg-type]\n\n except Exception as e:\n error_msg = f\"[OCR] {region_name}: 异常 - {e}\"\n root.after(0, log_msg(error_msg)) # type: ignore[arg-type]\n ocr_results.append((region_name, desc, \"\", f\"异常: {e}\"))\n\n # 更新OCR结果标签页\n def update_ocr_wrapper() -> None:\n update_ocr_results(ocr_results)\n\n root.after(0, update_ocr_wrapper) # type: ignore[arg-type]\n root.after(0, log_msg(f\"[OCR] 完成!共识别 {len(ocr_results)} 个区域\")) # type: ignore[arg-type]\n\n # 刷新截图预览(如果当前显示的是 screenshot.png)\n def refresh_if_screenshot() -> None:\n if image_var.get() == \"screenshot.png\":\n refresh_preview()\n\n root.after(0, refresh_if_screenshot) # type: ignore[arg-type]\n\n except Exception as e:\n import traceback\n\n error_detail = traceback.format_exc()\n root.after(0, log_msg(f\"[截图] 截图异常: {e}\\n{error_detail}\")) # type: ignore[arg-type]\n\n thread = threading.Thread(target=screenshot_thread, daemon=True)\n thread.start()\n\n # 将顶部“截图+OCR”按钮的回调绑定到 do_screenshot\n try:\n btn = screenshot_button_var.get(\"button\")\n if btn is not None:\n btn.configure(command=do_screenshot)\n except Exception:\n pass\n\n # 右侧:操作按钮区域(先创建,放在底部)\n actions = ttk.Frame(right)\n\n # 右侧:Notebook(日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间)\n notebook = ttk.Notebook(right)\n\n log_tab = ttk.Frame(notebook)\n preview_tab = ttk.Frame(notebook)\n stats_tab = ttk.Frame(notebook)\n reservation_tab = ttk.Frame(notebook)\n high_value_tab = ttk.Frame(notebook)\n actions_log_tab = ttk.Frame(notebook)\n ocr_results_tab = ttk.Frame(notebook)\n notebook.add(log_tab, text=\"运行日志\")\n notebook.add(preview_tab, text=\"截图预览\")\n notebook.add(stats_tab, text=\"统计信息\")\n notebook.add(reservation_tab, text=\"预约队列\")\n notebook.add(high_value_tab, text=\"高价值房间\")\n notebook.add(actions_log_tab, text=\"行为日志\")\n notebook.add(ocr_results_tab, text=\"OCR结果\")\n\n # 日志区\n log_box = ttk.Frame(log_tab)\n log_box.pack(fill=BOTH, expand=True)\n \n # 搜索工具栏\n log_search_frame = ttk.Frame(log_box)\n log_search_frame.pack(fill=X, padx=10, pady=(10, 5))\n \n log_search_var = tk.StringVar(value=\"\")\n log_search_entry = ttk.Entry(log_search_frame, textvariable=log_search_var, width=20)\n log_search_entry.pack(side=LEFT, padx=(0, 5))\n \n log_search_matches = [] # 存储所有匹配的位置\n log_current_match_index = -1 # 当前匹配的索引\n \n def search_in_log_text(direction=1):\n \"\"\"在运行日志中搜索文本\"\"\"\n nonlocal log_search_matches, log_current_match_index\n \n search_text = log_search_var.get().strip()\n if not search_text:\n # 清除高亮\n log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n log_search_matches = []\n log_current_match_index = -1\n return\n \n # 获取所有文本\n content = log_text.get(\"1.0\", \"end-1c\")\n if not content:\n return\n \n # 清除之前的高亮\n log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n \n # 配置高亮样式\n log_text.tag_config(\"search_highlight\", background=\"yellow\")\n log_text.tag_config(\"search_current\", background=\"orange\")\n \n # 查找所有匹配项(不区分大小写)\n log_search_matches = []\n start_pos = 0 # 使用整数索引\n search_text_lower = search_text.lower()\n content_lower = content.lower()\n \n while True:\n # 在内容中查找\n pos = content_lower.find(search_text_lower, start_pos)\n if pos == -1:\n break\n \n # 计算行号和列号\n line_start = content[:pos].rfind(\"\\n\") + 1\n line_num = content[:pos].count(\"\\n\") + 1\n col_num = pos - line_start\n \n # 转换为 tkinter 索引格式\n start_index = f\"{line_num}.{col_num}\"\n end_index = f\"{line_num}.{col_num + len(search_text)}\"\n \n log_search_matches.append((start_index, end_index))\n start_pos = pos + 1\n \n if not log_search_matches:\n # 没有找到匹配项\n log_current_match_index = -1\n return\n \n # 高亮所有匹配项\n for start_idx, end_idx in log_search_matches:\n log_text.tag_add(\"search_highlight\", start_idx, end_idx)\n \n # 根据方向更新当前匹配索引\n if direction == 1: # 下一个\n log_current_match_index = (log_current_match_index + 1) % len(log_search_matches)\n else: # 上一个\n log_current_match_index = (log_current_match_index - 1) % len(log_search_matches)\n \n # 高亮当前匹配项并滚动到该位置\n if log_current_match_index >= 0:\n start_idx, end_idx = log_search_matches[log_current_match_index]\n log_text.tag_add(\"search_current\", start_idx, end_idx)\n log_text.see(start_idx)\n log_text.mark_set(\"insert\", start_idx)\n \n def search_next_in_log():\n \"\"\"搜索下一个\"\"\"\n search_in_log_text(1)\n \n def search_prev_in_log():\n \"\"\"搜索上一个\"\"\"\n search_in_log_text(-1)\n \n def clear_search_in_log():\n \"\"\"清除搜索高亮\"\"\"\n nonlocal log_search_matches, log_current_match_index\n log_search_var.set(\"\")\n log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n log_search_matches = []\n log_current_match_index = -1\n \n # 绑定回车键搜索\n def on_log_search_entry_key(event):\n if event.keysym == \"Return\":\n search_next_in_log()\n \n log_search_entry.bind(\"<KeyPress>\", on_log_search_entry_key)\n \n ttk.Button(log_search_frame, text=\"搜索\", command=search_next_in_log).pack(side=LEFT, padx=(0, 2))\n ttk.Button(log_search_frame, text=\"上一个\", command=search_prev_in_log).pack(side=LEFT, padx=(0, 2))\n ttk.Button(log_search_frame, text=\"下一个\", command=search_next_in_log).pack(side=LEFT, padx=(0, 2))\n ttk.Button(log_search_frame, text=\"清除\", command=clear_search_in_log).pack(side=LEFT, padx=(0, 5))\n \n log_text = ScrolledText(log_box)\n try:\n log_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n log_text.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))\n\n # 截图预览\n preview_top = ttk.Frame(preview_tab)\n preview_top.pack(fill=X, padx=10, pady=10)\n\n images_dir = os.path.join(os.path.dirname(__file__), \"pic\")\n\n def scan_image_files():\n \"\"\"扫描pic文件夹及其子文件夹中的所有图片文件\"\"\"\n image_files = []\n if os.path.exists(images_dir):\n for root, dirs, files in os.walk(images_dir):\n for file in files:\n if file.lower().endswith(\n (\".png\", \".jpg\", \".jpeg\", \".bmp\", \".webp\", \".gif\")\n ):\n # 获取相对路径\n rel_path = os.path.relpath(os.path.join(root, file), images_dir)\n # 统一使用正斜杠(Windows和Unix都支持)\n rel_path = rel_path.replace(\"\\\\\", \"/\")\n image_files.append(rel_path)\n # 按文件名排序\n image_files.sort(key=lambda x: x.lower())\n return image_files\n\n image_var = tk.StringVar(value=\"\")\n\n ttk.Label(preview_top, text=\"选择图片:\").pack(side=LEFT)\n # 允许手工输入子路径(例如 start/latest.png),方便查看逐步截图\n image_combo = ttk.Combobox(\n preview_top, textvariable=image_var, width=30, state=\"normal\"\n )\n image_combo.pack(side=LEFT, padx=(0, 10))\n\n def update_image_list(refresh_after=True):\n \"\"\"更新图片列表\"\"\"\n new_list = scan_image_files()\n image_combo[\"values\"] = new_list\n current_value = image_var.get()\n # 如果当前值不在新列表中,或列表为空,选择第一个\n if new_list:\n if not current_value or current_value not in new_list:\n image_var.set(new_list[0])\n else:\n image_var.set(\"\")\n on_line(f\"[预览] 扫描到 {len(new_list)} 个图片文件\")\n # 如果当前有选择的图片,刷新预览(如果refresh_after为True且refresh_preview已定义)\n if refresh_after and image_var.get():\n try:\n refresh_preview()\n except NameError:\n # refresh_preview还没定义,忽略\n pass\n\n # 先定义refresh_preview函数(即使它引用了后面的变量,函数定义本身是延迟执行的)\n def refresh_preview():\n name = image_var.get().strip()\n if not name:\n preview_status.set(\"请选择图片\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n # 处理相对路径(将正斜杠转换为系统路径分隔符)\n name_normalized = name.replace(\"/\", os.sep)\n path = os.path.join(images_dir, name_normalized)\n _load_and_fit_image(path)\n\n update_image_list(refresh_after=False) # 初始化时扫描一次,但不刷新预览\n\n preview_status = tk.StringVar(value=\"\")\n ttk.Label(preview_top, textvariable=preview_status).pack(side=RIGHT)\n\n preview_body = ttk.Frame(preview_tab)\n preview_body.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))\n\n image_label = ttk.Label(preview_body)\n image_label.pack(fill=BOTH, expand=True)\n _img_ref: dict[str, Any] = {\"photo\": None} # 防止 PhotoImage 被回收\n\n def _load_and_fit_image(img_path: str) -> None:\n if not os.path.exists(img_path):\n preview_status.set(f\"未找到:{os.path.basename(img_path)}\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n\n try:\n img = Image.open(img_path)\n img.load() # Force load to catch truncated files early\n img = img.convert(\"RGB\")\n except (OSError, IOError, SyntaxError) as e:\n # Handle truncated image files\n preview_status.set(f\"图片加载失败:{str(e)[:50]}\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n except Exception as e:\n preview_status.set(f\"图片加载错误:{str(e)[:50]}\")\n image_label.configure(image=\"\")\n _img_ref[\"photo\"] = None\n return\n\n # 获取预览区域的实际尺寸(如果窗口还未初始化,使用默认值)\n try:\n preview_body.update_idletasks() # 强制更新布局\n w = preview_body.winfo_width()\n h = preview_body.winfo_height()\n # 如果尺寸无效(窗口未初始化),使用默认值\n if w <= 1 or h <= 1:\n w, h = 900, 520\n except Exception:\n w, h = 900, 520\n\n max_w = max(300, w - 20)\n max_h = max(200, h - 20)\n try:\n resample = Image.Resampling.LANCZOS\n except AttributeError:\n # Fallback for older Pillow versions: LANCZOS constant value is 1\n resample = 1 # type: ignore[assignment]\n img.thumbnail((max_w, max_h), resample)\n photo: ImageTk.PhotoImage = ImageTk.PhotoImage(img)\n _img_ref[\"photo\"] = photo # type: ignore[assignment]\n image_label.configure(image=photo)\n preview_status.set(f\"{os.path.basename(img_path)} {img.width}x{img.height}\")\n\n ttk.Button(\n preview_top,\n text=\"刷新列表\",\n command=lambda: update_image_list(refresh_after=True),\n ).pack(side=LEFT, padx=(0, 5))\n ttk.Button(preview_top, text=\"刷新预览\", command=refresh_preview).pack(side=LEFT)\n\n # 绑定选择变化事件,自动刷新预览(在 refresh_preview 函数定义之后)\n def on_image_selected(*args):\n \"\"\"当用户选择图片时自动刷新预览\"\"\"\n try:\n refresh_preview()\n except Exception:\n pass # 忽略错误,避免影响其他功能\n\n image_var.trace(\"w\", on_image_selected) # 监听变量变化\n image_combo.bind(\n \"<<ComboboxSelected>>\", lambda e: refresh_preview()\n ) # 监听下拉选择\n\n def open_pic_folder():\n try:\n os.makedirs(images_dir, exist_ok=True)\n os.startfile(images_dir) # type: ignore[attr-defined]\n except Exception as e:\n on_line(f\"[预览] 打开图片目录失败:{e}\")\n\n ttk.Button(preview_top, text=\"打开pic目录\", command=open_pic_folder).pack(\n side=LEFT, padx=(10, 0)\n )\n\n status_var = tk.StringVar(value=\"就绪\")\n\n def get_params() -> RunParams:\n # 如果启用无限循环,设置 wait_minutes=0\n wait_minutes_value = (\n 0 if infinite_loop_var.get() else int(wait_minutes_var.get() or 5)\n )\n return RunParams(\n enable_ocr_mode1=bool(enable_ocr_mode1_var.get()),\n device_id=device_var.get().strip(),\n y_pianyi=int(y_var.get()),\n needswitch=bool(needswitch_var.get()),\n wait_minutes=wait_minutes_value,\n skip_if_countdown_gt_seconds=int(skip_gt_seconds_var.get() or 900),\n reset_after_swipes_enabled=bool(reset_after_swipes_enabled_var.get()),\n reset_after_swipes=int(reset_after_swipes_var.get() or 10),\n min_prize_value_yuan=float(min_value_var.get() or 0),\n min_participants=int(min_participants_var.get() or 0),\n max_participants=int(max_participants_var.get() or 0),\n auto_join_fansclub=bool(auto_join_var.get()),\n fansclub_fail_action=str(fansclub_action_var.get() or \"stay\").lower(),\n # Web端新增参数\n high_value_room_revisit_enabled=bool(\n high_value_room_revisit_enabled_var.get()\n ),\n high_value_room_revisit_only_current_run=bool(\n high_value_room_revisit_only_current_run_var.get()\n ),\n reservation_back_verify_enabled=bool(\n reservation_back_verify_enabled_var.get()\n ),\n reservation_back_swipe_delay=float(\n reservation_back_swipe_delay_var.get() or 0\n ),\n reservation_preempt_min_value=float(\n reservation_preempt_min_value_var.get() or 0\n ),\n fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 0),\n fudai_template_match_enabled=bool(fudai_template_match_enabled_var.get()),\n fudai_template_match_threshold=float(\n fudai_template_match_threshold_var.get() or 0.7\n ),\n )\n\n def start_run():\n if runner.is_running():\n on_line(\"[运行] 已在运行中\")\n return\n save_ui_to_config()\n params = get_params()\n\n wait_display = \"∞\" if params.wait_minutes == 0 else f\"{params.wait_minutes}m\"\n on_line(\n f\"[运行] 启动:device={params.device_id or '(auto)'} y={params.y_pianyi} \"\n f\"needswitch={params.needswitch} wait={wait_display} \"\n f\"skip_gt={params.skip_if_countdown_gt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} \"\n f\"value>={params.min_prize_value_yuan} participants=[{params.min_participants},{params.max_participants}] \"\n f\"high_value_revisit={params.high_value_room_revisit_enabled} reservation_verify={params.reservation_back_verify_enabled} \"\n f\"fudai_find_max={params.fudai_find_max_attempts} yanghao=recommend_flow_only\"\n )\n status_var.set(\"运行中\")\n try:\n runner.start(params)\n except Exception as e:\n status_var.set(\"启动失败\")\n on_line(f\"[错误] {e}\")\n\n def stop_run():\n runner.stop()\n status_var.set(\"已停止\")\n\n # 先打包 actions 到底部(不 expand,固定在底部)\n actions.pack(fill=X, pady=(10, 0), padx=12, side=\"bottom\")\n\n # 然后打包 notebook 填充剩余空间(在 actions 之上)\n notebook.pack(fill=BOTH, expand=True)\n\n ttk.Button(actions, text=\"开始运行\", command=start_run).pack(side=LEFT, padx=(0, 8))\n ttk.Button(actions, text=\"停止\", command=stop_run).pack(side=LEFT, padx=(0, 4))\n\n def force_stop_run():\n \"\"\"强制终止后台进程(包括可能残留的子进程)。\"\"\"\n runner.force_stop()\n status_var.set(\"已停止(强制)\")\n\n ttk.Button(actions, text=\"强制停止\", command=force_stop_run).pack(\n side=LEFT, padx=(0, 8)\n )\n\n ttk.Separator(actions, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=10, pady=3)\n test_seconds_var = tk.IntVar(\n value=int(cfg.get(\"yanghao_recommend_duration_seconds\", 60) or 60)\n )\n ttk.Label(actions, text=\"测试养号(秒):\").pack(side=LEFT)\n ttk.Spinbox(\n actions, from_=10, to=3600, increment=10, textvariable=test_seconds_var, width=8\n ).pack(side=LEFT, padx=(0, 8))\n\n def start_test_yanghao():\n if runner.is_running():\n on_line(\"[运行] 已在运行中\")\n return\n save_ui_to_config()\n secs = int(test_seconds_var.get() or 90)\n dev = device_var.get().strip()\n on_line(f\"[测试] 启动养号流程:device={dev or '(auto)'} seconds={secs}\")\n status_var.set(\"运行中\")\n try:\n runner.start_test_yanghao_flow(dev, secs)\n except Exception as e:\n status_var.set(\"启动失败\")\n on_line(f\"[错误] {e}\")\n\n ttk.Button(actions, text=\"测试养号流程\", command=start_test_yanghao).pack(side=LEFT)\n\n ttk.Separator(actions, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=10, pady=3)\n test_comment_var = tk.StringVar(value=\"测试评论\")\n ttk.Label(actions, text=\"测试评论:\").pack(side=LEFT)\n ttk.Entry(actions, textvariable=test_comment_var, width=12).pack(\n side=LEFT, padx=(0, 8)\n )\n\n def start_test_comment():\n if runner.is_running():\n on_line(\"[运行] 已在运行中\")\n return\n save_ui_to_config()\n text = test_comment_var.get().strip()\n dev = device_var.get().strip()\n on_line(f\"[测试] 启动评论测试:device={dev or '(auto)'} text={text}\")\n status_var.set(\"运行中\")\n try:\n runner.start_test_comment(dev, text)\n except Exception as e:\n status_var.set(\"启动失败\")\n on_line(f\"[错误] {e}\")\n\n ttk.Button(actions, text=\"测试评论\", command=start_test_comment).pack(side=LEFT)\n\n ttk.Separator(actions, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=10, pady=3)\n\n def send_back_key():\n dev = device_var.get().strip()\n try:\n runner.send_back_key(dev)\n except Exception as e:\n on_line(f\"[错误] 发送返回键失败: {e}\")\n\n ttk.Button(actions, text=\"发送返回键\", command=send_back_key).pack(\n side=LEFT, padx=(0, 8)\n )\n\n ttk.Label(actions, textvariable=status_var).pack(side=RIGHT)\n\n def pump_logs():\n changed = False\n try:\n while True:\n line = q.get_nowait()\n try:\n log_text.insert(\"end\", line + \"\\n\")\n # 不再自动滚动到底部,让用户自由控制滚动位置\n changed = True\n except Exception as e:\n # 如果插入日志失败,至少打印到控制台(调试用)\n print(f\"[GUI日志错误] 无法插入日志: {e}\", file=sys.stderr)\n except queue.Empty:\n pass\n except Exception as e:\n # 捕获其他异常,确保日志循环不会中断\n print(f\"[GUI日志错误] pump_logs异常: {e}\", file=sys.stderr)\n\n try:\n if changed and not runner.is_running() and status_var.get() == \"运行中\":\n status_var.set(\"已结束\")\n except Exception:\n pass\n\n # 确保递归调用始终执行,即使前面出现异常\n try:\n root.after(100, pump_logs) # type: ignore[arg-type]\n except Exception as e:\n # 如果 root 已被销毁,停止日志循环\n print(f\"[GUI日志错误] 无法调度下次日志更新: {e}\", file=sys.stderr)\n\n # 统计信息显示\n stats_top = ttk.Frame(stats_tab)\n stats_top.pack(fill=X, padx=10, pady=(10, 0))\n stats_text = ScrolledText(stats_tab)\n stats_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n stats_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def refresh_stats():\n try:\n stats = runner.get_stats()\n lines = []\n\n # 基本信息\n lines.append(\"=\" * 60)\n lines.append(\"运行状态信息\")\n lines.append(\"=\" * 60)\n lines.append(f\"运行状态: {'运行中' if stats.get('running') else '未运行'}\")\n lines.append(f\"PID: {stats.get('pid') or '-'}\")\n\n uptime_seconds = stats.get(\"uptime_seconds\", 0)\n if uptime_seconds > 0:\n hours = uptime_seconds // 3600\n minutes = (uptime_seconds % 3600) // 60\n seconds = uptime_seconds % 60\n lines.append(f\"运行时长: {hours:02d}:{minutes:02d}:{seconds:02d}\")\n else:\n lines.append(f\"运行时长: -\")\n\n last_log_ts = stats.get(\"last_log_ts\")\n if last_log_ts:\n import datetime\n\n dt = datetime.datetime.fromtimestamp(last_log_ts)\n lines.append(f\"最近日志时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}\")\n else:\n lines.append(f\"最近日志时间: -\")\n\n exit_code = stats.get(\"exit_code\")\n lines.append(f\"退出码: {exit_code if exit_code is not None else '-'}\")\n lines.append(\"\")\n\n # 计数器统计\n counters = stats.get(\"counters\", {})\n\n # 快速汇总(关键指标)\n fudai_seen = counters.get(\"fudai_seen\", 0)\n fudai_attend_ok = counters.get(\"fudai_attend_ok\", 0)\n fudai_result_win = counters.get(\"fudai_result_win\", 0)\n fudai_order_success = counters.get(\"fudai_order_success\", 0)\n\n if fudai_seen > 0 or fudai_attend_ok > 0 or fudai_result_win > 0:\n lines.append(\"=\" * 60)\n lines.append(\"快速汇总\")\n lines.append(\"=\" * 60)\n lines.append(f\"识别福袋: {fudai_seen} 个\")\n lines.append(f\"参与成功: {fudai_attend_ok} 次\")\n lines.append(f\"中奖次数: {fudai_result_win} 次\")\n lines.append(f\"下单成功: {fudai_order_success} 次\")\n if uptime_seconds > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(\n f\"运行效率: {fudai_attend_ok / hours:.1f} 次参与/小时\"\n )\n lines.append(\"\")\n\n # 核心统计(总是显示,即使数据为0)\n lines.append(\"=\" * 60)\n lines.append(\"核心统计\")\n lines.append(\"=\" * 60)\n\n # 福袋相关核心指标(重新获取,避免重复定义)\n fudai_open_detail = counters.get(\"fudai_open_detail\", 0)\n fudai_click_attend = counters.get(\"fudai_click_attend\", 0)\n fudai_attend_ok = counters.get(\"fudai_attend_ok\", 0)\n fudai_attend_fail = counters.get(\"fudai_attend_fail\", 0)\n fudai_result_win = counters.get(\"fudai_result_win\", 0)\n fudai_result_no_win = counters.get(\"fudai_result_no_win\", 0)\n fudai_order_success = counters.get(\"fudai_order_success\", 0)\n\n lines.append(f\"福袋识别次数: {fudai_seen}\")\n lines.append(f\"打开详情: {fudai_open_detail}\")\n if fudai_seen > 0:\n open_rate = (fudai_open_detail / fudai_seen) * 100\n lines.append(f\" 打开成功率: {open_rate:.1f}%\")\n\n lines.append(f\"点击参与: {fudai_click_attend}\")\n if fudai_open_detail > 0:\n click_rate = (fudai_click_attend / fudai_open_detail) * 100\n lines.append(f\" 点击率: {click_rate:.1f}%\")\n\n lines.append(f\"参与成功: {fudai_attend_ok}\")\n lines.append(f\"参与失败: {fudai_attend_fail}\")\n total_attend = fudai_attend_ok + fudai_attend_fail\n if total_attend > 0:\n success_rate = (fudai_attend_ok / total_attend) * 100\n lines.append(f\" 参与成功率: {success_rate:.1f}%\")\n\n lines.append(f\"中奖次数: {fudai_result_win}\")\n lines.append(f\"未中奖次数: {fudai_result_no_win}\")\n total_results = fudai_result_win + fudai_result_no_win\n if total_results > 0:\n win_rate = (fudai_result_win / total_results) * 100\n lines.append(f\" 中奖率: {win_rate:.1f}%\")\n\n lines.append(f\"下单成功: {fudai_order_success}\")\n\n # 效率统计\n if uptime_seconds > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(\"\")\n lines.append(\"效率统计(每小时):\")\n if fudai_seen > 0:\n lines.append(f\" 识别福袋: {fudai_seen / hours:.1f} 个/小时\")\n if fudai_attend_ok > 0:\n lines.append(\n f\" 参与成功: {fudai_attend_ok / hours:.1f} 次/小时\"\n )\n if total_results > 0:\n lines.append(f\" 开奖次数: {total_results / hours:.1f} 次/小时\")\n if fudai_result_win > 0:\n lines.append(\n f\" 中奖次数: {fudai_result_win / hours:.2f} 次/小时\"\n )\n\n lines.append(\"\")\n\n # 跳过原因统计\n skip_stats = [\n (\"fudai_skip_value_low\", \"跳过-价值过低\"),\n (\"fudai_skip_participants_low\", \"跳过-人数过少\"),\n (\"fudai_skip_participants_high\", \"跳过-人数过多\"),\n (\"fudai_skip_content\", \"跳过-内容不理想\"),\n (\"fudai_skip_countdown_short\", \"跳过-倒计时太短\"),\n (\"fudai_skip_countdown_long\", \"跳过-倒计时太长\"),\n (\"fudai_skip_watch_required\", \"跳过-需要看播\"),\n ]\n skip_total = sum(counters.get(key, 0) for key, _ in skip_stats)\n if skip_total > 0:\n lines.append(\"=\" * 60)\n lines.append(\"跳过原因统计\")\n lines.append(\"=\" * 60)\n lines.append(f\"总跳过次数: {skip_total}\")\n if fudai_seen > 0:\n skip_rate = (skip_total / fudai_seen) * 100\n lines.append(f\"跳过率: {skip_rate:.1f}%\")\n lines.append(\"\")\n for key, label in skip_stats:\n val = counters.get(key, 0)\n if val > 0:\n percentage = (val / skip_total) * 100 if skip_total > 0 else 0\n lines.append(f\" {label}: {val} ({percentage:.1f}%)\")\n lines.append(\"\")\n\n # 粉丝团统计\n fansclub_stats = [\n (\"fansclub_required\", \"需要粉丝团\"),\n (\"fansclub_manual_needed\", \"需手动加入\"),\n (\"fansclub_unresolved\", \"未解决\"),\n ]\n fansclub_total = sum(counters.get(key, 0) for key, _ in fansclub_stats)\n if fansclub_total > 0:\n lines.append(\"=\" * 60)\n lines.append(\"粉丝团相关统计\")\n lines.append(\"=\" * 60)\n for key, label in fansclub_stats:\n val = counters.get(key, 0)\n if val > 0:\n percentage = (\n (val / fansclub_total) * 100 if fansclub_total > 0 else 0\n )\n lines.append(f\" {label}: {val} ({percentage:.1f}%)\")\n lines.append(\"\")\n\n # 直播间切换统计\n switch_val = counters.get(\"switch_room\", 0)\n if switch_val > 0:\n lines.append(\"=\" * 60)\n lines.append(\"直播间切换统计\")\n lines.append(\"=\" * 60)\n lines.append(f\"总切换次数: {switch_val}\")\n if uptime_seconds > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(f\"切换频率: {switch_val / hours:.1f} 次/小时\")\n lines.append(\"\")\n switch_reasons = [\n (\"switch_room_no_fudai\", \"无福袋\"),\n (\"switch_room_participants\", \"人数不符合\"),\n (\"switch_room_value\", \"价值不符合\"),\n (\"switch_room_content\", \"内容不符合\"),\n (\"switch_room_countdown\", \"倒计时不符合\"),\n (\"switch_room_attend_fail\", \"参与失败\"),\n ]\n for key, label in switch_reasons:\n val = counters.get(key, 0)\n if val > 0:\n percentage = (val / switch_val) * 100 if switch_val > 0 else 0\n lines.append(f\" {label}: {val} ({percentage:.1f}%)\")\n lines.append(\"\")\n\n # 预约相关统计(详细版)\n reservation_recorded = counters.get(\"reservation_recorded\", 0)\n reservation_window_entered = counters.get(\"reservation_window_entered\", 0)\n reservation_back_success = counters.get(\"reservation_back_success\", 0)\n reservation_back_verify_ok = counters.get(\"reservation_back_verify_ok\", 0)\n reservation_back_verify_fail = counters.get(\"reservation_back_verify_fail\", 0)\n reservation_window_not_reached = counters.get(\"reservation_window_not_reached\", 0)\n reservation_expired = counters.get(\"reservation_expired\", 0)\n reservation_queue_empty = counters.get(\"reservation_queue_empty\", 0)\n reservation_locked = counters.get(\"reservation_locked\", 0)\n reservation_back_to_first = counters.get(\"reservation_back_to_first\", 0)\n reservation_queue_full_wait = counters.get(\"reservation_queue_full_wait\", 0)\n reservation_drop_low_value = counters.get(\"reservation_drop_low_value\", 0)\n reservation_clear = counters.get(\"reservation_clear\", 0)\n \n reservation_total = (\n reservation_recorded\n + reservation_window_entered\n + reservation_back_success\n + reservation_back_verify_ok\n + reservation_back_verify_fail\n + reservation_window_not_reached\n + reservation_expired\n + reservation_queue_empty\n + reservation_locked\n + reservation_back_to_first\n + reservation_queue_full_wait\n + reservation_drop_low_value\n + reservation_clear\n )\n \n if reservation_total > 0 or reservation_recorded > 0:\n lines.append(\"=\" * 60)\n lines.append(\"预约相关统计(详细)\")\n lines.append(\"=\" * 60)\n \n # 预约记录统计\n if reservation_recorded > 0:\n lines.append(f\"记录预约总数: {reservation_recorded}\")\n \n # 预约回退统计\n if reservation_back_success > 0:\n lines.append(f\"成功回退到预约直播间: {reservation_back_success}\")\n \n # 回退校验统计\n verify_total = reservation_back_verify_ok + reservation_back_verify_fail\n if verify_total > 0:\n verify_rate = (reservation_back_verify_ok / verify_total) * 100\n lines.append(\n f\"回退校验: {reservation_back_verify_ok} 成功 / {reservation_back_verify_fail} 失败 (成功率: {verify_rate:.1f}%)\"\n )\n \n # 预约窗口统计\n if reservation_window_entered > 0:\n lines.append(f\"进入预约参与窗口: {reservation_window_entered}\")\n if reservation_window_not_reached > 0:\n lines.append(f\"时间窗口未到(跳过): {reservation_window_not_reached}\")\n \n # 预约状态统计\n if reservation_expired > 0:\n lines.append(f\"过期预约(已清理): {reservation_expired}\")\n if reservation_locked > 0:\n lines.append(f\"锁定期未结束(跳过): {reservation_locked}\")\n if reservation_queue_empty > 0:\n lines.append(f\"预约队列为空(检查次数): {reservation_queue_empty}\")\n if reservation_queue_full_wait > 0:\n lines.append(f\"队列已满等待: {reservation_queue_full_wait}\")\n if reservation_back_to_first > 0:\n lines.append(f\"回退到第一个直播间: {reservation_back_to_first}\")\n \n # 预约管理统计\n if reservation_drop_low_value > 0:\n lines.append(f\"丢弃低价值预约: {reservation_drop_low_value}\")\n if reservation_clear > 0:\n lines.append(f\"清空预约队列: {reservation_clear}\")\n \n # 预约成功率\n if reservation_recorded > 0 and reservation_back_success > 0:\n back_rate = (reservation_back_success / reservation_recorded) * 100\n lines.append(f\"预约回退成功率: {back_rate:.1f}% ({reservation_back_success}/{reservation_recorded})\")\n \n lines.append(\"\")\n\n # 错误统计(详细版)\n error_total = counters.get(\"error_total\", 0)\n error_unbound_local = counters.get(\"error_unbound_local\", 0)\n error_attribute = counters.get(\"error_attribute\", 0)\n error_key = counters.get(\"error_key\", 0)\n error_value = counters.get(\"error_value\", 0)\n error_type = counters.get(\"error_type\", 0)\n error_timeout = counters.get(\"error_timeout\", 0)\n error_connection = counters.get(\"error_connection\", 0)\n error_ocr = counters.get(\"error_ocr\", 0)\n error_screenshot = counters.get(\"error_screenshot\", 0)\n error_detection = counters.get(\"error_detection\", 0)\n error_stage_diagnosis = counters.get(\"error_stage_diagnosis\", 0)\n error_read_detail = counters.get(\"error_read_detail\", 0)\n error_config_load = counters.get(\"error_config_load\", 0)\n error_state_file = counters.get(\"error_state_file\", 0)\n error_live_room_detect = counters.get(\"error_live_room_detect\", 0)\n error_fudai_find = counters.get(\"error_fudai_find\", 0)\n fudai_open_error = counters.get(\"fudai_open_error\", 0)\n fudai_open_error_too_many = counters.get(\"fudai_open_error_too_many\", 0)\n \n error_all = (\n error_total\n + error_unbound_local\n + error_attribute\n + error_key\n + error_value\n + error_type\n + error_timeout\n + error_connection\n + error_ocr\n + error_screenshot\n + error_detection\n + error_stage_diagnosis\n + error_read_detail\n + error_config_load\n + error_state_file\n + error_live_room_detect\n + error_fudai_find\n + fudai_open_error\n + fudai_open_error_too_many\n )\n \n if error_all > 0:\n lines.append(\"=\" * 60)\n lines.append(\"错误统计(详细)\")\n lines.append(\"=\" * 60)\n \n # 总错误数\n if error_total > 0:\n lines.append(f\"总错误数: {error_total}\")\n \n # 福袋相关错误\n fudai_errors = fudai_open_error + fudai_open_error_too_many\n if fudai_errors > 0:\n lines.append(\"\")\n lines.append(\"福袋相关错误:\")\n if fudai_open_error > 0:\n lines.append(f\" 打开福袋异常: {fudai_open_error}\")\n if fudai_open_error_too_many > 0:\n lines.append(f\" 打开失败次数过多: {fudai_open_error_too_many}\")\n \n # Python异常类型\n python_errors = (\n error_unbound_local\n + error_attribute\n + error_key\n + error_value\n + error_type\n )\n if python_errors > 0:\n lines.append(\"\")\n lines.append(\"Python异常类型:\")\n if error_unbound_local > 0:\n lines.append(f\" UnboundLocalError: {error_unbound_local}\")\n if error_attribute > 0:\n lines.append(f\" AttributeError: {error_attribute}\")\n if error_key > 0:\n lines.append(f\" KeyError: {error_key}\")\n if error_value > 0:\n lines.append(f\" ValueError: {error_value}\")\n if error_type > 0:\n lines.append(f\" TypeError: {error_type}\")\n \n # 功能模块错误\n module_errors = (\n error_ocr\n + error_screenshot\n + error_detection\n + error_stage_diagnosis\n + error_read_detail\n + error_config_load\n + error_state_file\n + error_live_room_detect\n + error_fudai_find\n )\n if module_errors > 0:\n lines.append(\"\")\n lines.append(\"功能模块错误:\")\n if error_ocr > 0:\n lines.append(f\" OCR识别错误: {error_ocr}\")\n if error_screenshot > 0:\n lines.append(f\" 截图错误: {error_screenshot}\")\n if error_detection > 0:\n lines.append(f\" 识别错误: {error_detection}\")\n if error_stage_diagnosis > 0:\n lines.append(f\" 阶段诊断错误: {error_stage_diagnosis}\")\n if error_read_detail > 0:\n lines.append(f\" 读取详情错误: {error_read_detail}\")\n if error_config_load > 0:\n lines.append(f\" 配置加载错误: {error_config_load}\")\n if error_state_file > 0:\n lines.append(f\" 状态文件错误: {error_state_file}\")\n if error_live_room_detect > 0:\n lines.append(f\" 直播间检测错误: {error_live_room_detect}\")\n if error_fudai_find > 0:\n lines.append(f\" 福袋查找错误: {error_fudai_find}\")\n \n # 网络和超时错误\n network_errors = error_timeout + error_connection\n if network_errors > 0:\n lines.append(\"\")\n lines.append(\"网络和超时错误:\")\n if error_timeout > 0:\n lines.append(f\" 超时错误: {error_timeout}\")\n if error_connection > 0:\n lines.append(f\" 连接错误: {error_connection}\")\n \n # 错误率统计\n if uptime_seconds > 0 and error_all > 0:\n hours = uptime_seconds / 3600.0\n if hours > 0:\n lines.append(\"\")\n lines.append(f\"错误频率: {error_all / hours:.2f} 次/小时\")\n \n lines.append(\"\")\n\n # 价值统计(从事件中提取)\n events = stats.get(\"events\", [])\n prize_values = []\n for event in events:\n meta = event.get(\"meta\", {})\n if \"prize_value_yuan\" in meta and meta[\"prize_value_yuan\"] is not None:\n try:\n prize_values.append(float(meta[\"prize_value_yuan\"]))\n except (ValueError, TypeError):\n pass\n\n if prize_values:\n lines.append(\"=\" * 60)\n lines.append(\"价值统计\")\n lines.append(\"=\" * 60)\n total_value = sum(prize_values)\n avg_value = total_value / len(prize_values)\n max_value = max(prize_values)\n min_value = min(prize_values)\n lines.append(f\"识别到的福袋总数: {len(prize_values)}\")\n lines.append(f\"总价值: {total_value:.2f} 元\")\n lines.append(f\"平均价值: {avg_value:.2f} 元\")\n lines.append(f\"最高价值: {max_value:.2f} 元\")\n lines.append(f\"最低价值: {min_value:.2f} 元\")\n\n # 价值分布\n high_value_count = sum(1 for v in prize_values if v >= 500)\n medium_value_count = sum(1 for v in prize_values if 100 <= v < 500)\n low_value_count = sum(1 for v in prize_values if v < 100)\n lines.append(\"\")\n lines.append(\"价值分布:\")\n lines.append(\n f\" 高价值(≥500元): {high_value_count} ({high_value_count/len(prize_values)*100:.1f}%)\"\n )\n lines.append(\n f\" 中价值(100-500元): {medium_value_count} ({medium_value_count/len(prize_values)*100:.1f}%)\"\n )\n lines.append(\n f\" 低价值(<100元): {low_value_count} ({low_value_count/len(prize_values)*100:.1f}%)\"\n )\n lines.append(\"\")\n\n # 最近一次福袋信息\n fudai_last = stats.get(\"fudai_last\", {})\n if fudai_last.get(\"content\") or fudai_last.get(\"countdown\"):\n lines.append(\"=\" * 60)\n lines.append(\"最近一次福袋信息\")\n lines.append(\"=\" * 60)\n lines.append(f\"内容: {fudai_last.get('content') or '-'}\")\n lines.append(f\"倒计时: {fudai_last.get('countdown') or '-'}\")\n participants = fudai_last.get(\"participants\")\n copies = fudai_last.get(\"copies\")\n if participants is not None and copies is not None:\n lines.append(f\"参与人数/份数: {participants} / {copies}\")\n if participants > 0 and copies > 0:\n ratio = participants / copies\n lines.append(f\" 中奖概率: {1/ratio*100:.2f}% (1/{ratio:.1f})\")\n prize_value = fudai_last.get(\"prize_value_yuan\")\n if prize_value is not None:\n lines.append(f\"奖品价值: {prize_value} 元\")\n updated_ts = fudai_last.get(\"updated_ts\")\n if updated_ts:\n import datetime\n\n dt = datetime.datetime.fromtimestamp(updated_ts)\n lines.append(f\"更新时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}\")\n lines.append(\"\")\n\n # 中奖记录\n wins = stats.get(\"wins\", [])\n if wins:\n lines.append(\"=\" * 60)\n lines.append(f\"最近中奖记录(显示最近 {len(wins)} 条)\")\n lines.append(\"=\" * 60)\n for i, win in enumerate(wins[-10:], 1): # 只显示最近10条\n import datetime\n\n ts = win.get(\"ts\", 0)\n dt_str = (\n datetime.datetime.fromtimestamp(ts).strftime(\n \"%Y-%m-%d %H:%M:%S\"\n )\n if ts\n else \"-\"\n )\n lines.append(f\"\\n[{i}] 时间: {dt_str}\")\n if win.get(\"content\"):\n lines.append(f\" 内容: {win.get('content')}\")\n if win.get(\"prize_value_yuan\"):\n lines.append(f\" 价值: {win.get('prize_value_yuan')} 元\")\n if win.get(\"participants\") and win.get(\"copies\"):\n lines.append(\n f\" 人数/份数: {win.get('participants')} / {win.get('copies')}\"\n )\n\n # 确保至少显示基本信息\n if not lines:\n lines.append(\"=\" * 60)\n lines.append(\"统计信息\")\n lines.append(\"=\" * 60)\n lines.append(\"暂无统计数据\")\n lines.append(\"\")\n lines.append(\"提示:请先运行程序以收集统计数据\")\n\n stats_text.delete(\"1.0\", \"end\")\n stats_text.insert(\"1.0\", \"\\n\".join(lines))\n except Exception as e:\n import traceback\n\n stats_text.delete(\"1.0\", \"end\")\n error_detail = traceback.format_exc()\n stats_text.insert(\n \"1.0\", f\"刷新统计信息失败:{e}\\n\\n详细信息:\\n{error_detail}\"\n )\n\n ttk.Button(stats_top, text=\"刷新\", command=refresh_stats).pack(side=LEFT)\n\n # 预约队列显示\n reservation_top = ttk.Frame(reservation_tab)\n reservation_top.pack(fill=X, padx=10, pady=(10, 0))\n reservation_text = ScrolledText(reservation_tab)\n reservation_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n reservation_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def refresh_reservations():\n path = os.path.join(os.path.dirname(__file__), \"state\", \"reservations.json\")\n try:\n if os.path.exists(path):\n with open(path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n reservation_text.delete(\"1.0\", \"end\")\n\n from datetime import datetime\n updated_ts = float(data.get(\"updated_ts\", 0.0) or 0.0) if isinstance(data, dict) else 0.0\n room_pos = int(data.get(\"room_pos\", 0) or 0) if isinstance(data, dict) else 0\n reason = str(data.get(\"reason\", \"\") or \"\") if isinstance(data, dict) else \"\"\n current_title = str(data.get(\"current_room_title\", \"\") or \"\") if isinstance(data, dict) else \"\"\n current_title_raw = str(data.get(\"current_room_title_raw\", \"\") or \"\") if isinstance(data, dict) else \"\"\n reservations = data.get(\"reservations\", []) if isinstance(data, dict) else []\n\n # 基本信息(中文)\n lines = []\n lines.append(\"=== 预约队列总览 ===\")\n if updated_ts > 0:\n try:\n updated_str = datetime.fromtimestamp(updated_ts).strftime(\"%Y-%m-%d %H:%M:%S\")\n except Exception:\n updated_str = str(updated_ts)\n else:\n updated_str = \"-\"\n lines.append(f\"更新时间:{updated_str}\")\n lines.append(f\"当前直播间位置:{room_pos}\")\n lines.append(f\"当前直播间(清洗后):{current_title or '-'}\")\n lines.append(f\"当前直播间原文:{current_title_raw or '-'}\")\n lines.append(f\"预约总数量:{len(reservations)}\")\n if reason:\n lines.append(f\"最近更新原因:{reason}\")\n lines.append(\"\")\n\n if not reservations:\n lines.append(\"暂无预约记录。\")\n else:\n lines.append(\"=== 预约明细列表(按预计开奖时间排序) ===\")\n now_ts = datetime.now().timestamp()\n for idx, item in enumerate(reservations, start=1):\n try:\n val = float(item.get(\"prize_value_yuan\") or 0.0)\n except Exception:\n val = 0.0\n content = str(item.get(\"content\") or \"\")\n ft = float(item.get(\"future_ts\") or 0.0)\n ft_str = str(item.get(\"future_str\") or \"\")\n pos_seen = int(item.get(\"pos_seen\") or 0)\n room_title = str(item.get(\"room_title\") or \"\")\n room_title_raw = str(item.get(\"room_title_raw\") or \"\")\n created_ts = float(item.get(\"created_ts\") or 0.0)\n\n # 计算剩余时间\n remain_sec = max(0, int(ft - now_ts)) if ft > 0 else 0\n if remain_sec > 0:\n remain_str = f\"{remain_sec // 60}分{remain_sec % 60}秒后开奖\"\n elif ft > 0:\n remain_str = \"已到开奖时间\"\n else:\n remain_str = \"未知(future_ts 无效)\"\n\n # 记录时间\n if created_ts > 0:\n try:\n created_str = datetime.fromtimestamp(created_ts).strftime(\"%Y-%m-%d %H:%M:%S\")\n except Exception:\n created_str = str(created_ts)\n else:\n created_str = \"-\"\n\n lines.append(f\"[#{idx}] 价值:{val:.2f} 元\")\n lines.append(f\" 奖品内容:{content}\")\n lines.append(f\" 预计开奖时间:{ft_str or '-'}\")\n lines.append(f\" 剩余时间:{remain_str}\")\n lines.append(f\" 发现时直播间位置:{pos_seen}\")\n lines.append(f\" 直播间(清洗后):{room_title or '-'}\")\n lines.append(f\" 直播间原文:{room_title_raw or '-'}\")\n lines.append(f\" 记录时间:{created_str}\")\n lines.append(\"-\" * 40)\n\n reservation_text.insert(\"1.0\", \"\\n\".join(lines))\n else:\n reservation_text.delete(\"1.0\", \"end\")\n reservation_text.insert(\"1.0\", \"暂无预约队列数据\")\n except Exception as e:\n reservation_text.delete(\"1.0\", \"end\")\n reservation_text.insert(\"1.0\", f\"读取预约队列失败:{e}\")\n\n ttk.Button(reservation_top, text=\"刷新\", command=refresh_reservations).pack(\n side=LEFT\n )\n\n # 高价值房间显示\n high_value_top = ttk.Frame(high_value_tab)\n high_value_top.pack(fill=X, padx=10, pady=(10, 0))\n high_value_text = ScrolledText(high_value_tab)\n high_value_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n high_value_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def refresh_high_value_rooms():\n path = os.path.join(os.path.dirname(__file__), \"state\", \"high_value_rooms.json\")\n try:\n if os.path.exists(path):\n with open(path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n high_value_text.delete(\"1.0\", \"end\")\n high_value_text.insert(\n \"1.0\", json.dumps(data, ensure_ascii=False, indent=2)\n )\n else:\n high_value_text.delete(\"1.0\", \"end\")\n high_value_text.insert(\"1.0\", \"暂无高价值房间数据\")\n except Exception as e:\n high_value_text.delete(\"1.0\", \"end\")\n high_value_text.insert(\"1.0\", f\"读取高价值房间失败:{e}\")\n\n ttk.Button(high_value_top, text=\"刷新\", command=refresh_high_value_rooms).pack(\n side=LEFT\n )\n\n # 行为日志显示(点击/识别/耗时)\n actions_log_top = ttk.Frame(actions_log_tab)\n actions_log_top.pack(fill=X, padx=10, pady=(10, 0))\n actions_log_text = ScrolledText(actions_log_tab)\n actions_log_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n actions_log_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n actions_filter_var = tk.StringVar(value=\"\")\n\n def refresh_actions_log():\n \"\"\"读取 logs/actions.log 的尾部若干行,在 GUI 中展示关键行为日志(支持简单关键字筛选)。\"\"\"\n path = os.path.join(os.path.dirname(__file__), \"logs\", \"actions.log\")\n try:\n if os.path.exists(path):\n # 仿照 web_gui 的实现:只读最后一小段,避免文件巨大\n size = os.path.getsize(path)\n if size == 0:\n actions_log_text.delete(\"1.0\", \"end\")\n actions_log_text.insert(\"1.0\", \"行为日志文件为空\")\n return\n \n read_bytes = min(size, 65536)\n with open(path, \"rb\") as f:\n if read_bytes < size:\n f.seek(-read_bytes, os.SEEK_END)\n data = f.read()\n # 尝试多种编码方式\n try:\n # 先尝试 utf-8-sig(带BOM)\n text = data.decode(\"utf-8-sig\", errors=\"replace\")\n except Exception:\n try:\n # 再尝试 utf-8\n text = data.decode(\"utf-8\", errors=\"replace\")\n except Exception:\n # 最后尝试 gbk(Windows常见编码)\n text = data.decode(\"gbk\", errors=\"replace\")\n lines = text.splitlines()\n # 只取最近 300 行\n tail = lines[-300:]\n\n # 关键字筛选:若填写了筛选词,只保留包含该关键字的行\n kw = actions_filter_var.get().strip()\n if kw:\n tail = [ln for ln in tail if kw in ln]\n\n # 保存当前滚动位置,避免刷新时自动置顶\n try:\n scroll_position = actions_log_text.yview()[0] # 获取当前滚动位置(顶部可见位置的比例)\n except Exception:\n scroll_position = 0.0\n\n actions_log_text.delete(\"1.0\", \"end\")\n if tail:\n actions_log_text.insert(\"1.0\", \"\\n\".join(tail))\n else:\n actions_log_text.insert(\"1.0\", \"暂无匹配的行为日志\")\n \n # 恢复之前的滚动位置,避免自动置顶\n try:\n actions_log_text.yview_moveto(scroll_position)\n except Exception:\n pass\n else:\n actions_log_text.delete(\"1.0\", \"end\")\n actions_log_text.insert(\n \"1.0\", \"暂无行为日志(logs/actions.log 不存在)\"\n )\n except Exception as e:\n actions_log_text.delete(\"1.0\", \"end\")\n actions_log_text.insert(\"1.0\", f\"读取行为日志失败:{e}\")\n\n ttk.Label(actions_log_top, text=\"关键字筛选:\").pack(side=LEFT)\n ttk.Entry(actions_log_top, textvariable=actions_filter_var, width=16).pack(\n side=LEFT, padx=(0, 8)\n )\n ttk.Button(actions_log_top, text=\"刷新\", command=refresh_actions_log).pack(\n side=LEFT, padx=(0, 10)\n )\n \n # 行为日志搜索功能\n ttk.Separator(actions_log_top, orient=\"vertical\").pack(side=LEFT, fill=Y, padx=5, pady=3)\n ttk.Label(actions_log_top, text=\"搜索:\").pack(side=LEFT)\n \n actions_search_var = tk.StringVar(value=\"\")\n actions_search_entry = ttk.Entry(actions_log_top, textvariable=actions_search_var, width=20)\n actions_search_entry.pack(side=LEFT, padx=(0, 5))\n \n actions_search_matches = []\n actions_current_match_index = -1\n \n def search_in_actions_log(direction=1):\n \"\"\"在行为日志中搜索文本\"\"\"\n nonlocal actions_search_matches, actions_current_match_index\n \n search_text = actions_search_var.get().strip()\n if not search_text:\n actions_log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n actions_log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n actions_search_matches = []\n actions_current_match_index = -1\n return\n \n content = actions_log_text.get(\"1.0\", \"end-1c\")\n if not content:\n return\n \n actions_log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n actions_log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n \n actions_log_text.tag_config(\"search_highlight\", background=\"yellow\")\n actions_log_text.tag_config(\"search_current\", background=\"orange\")\n \n actions_search_matches = []\n start_pos = 0 # 使用整数索引\n search_text_lower = search_text.lower()\n content_lower = content.lower()\n \n while True:\n pos = content_lower.find(search_text_lower, start_pos)\n if pos == -1:\n break\n \n line_start = content[:pos].rfind(\"\\n\") + 1\n line_num = content[:pos].count(\"\\n\") + 1\n col_num = pos - line_start\n \n start_index = f\"{line_num}.{col_num}\"\n end_index = f\"{line_num}.{col_num + len(search_text)}\"\n \n actions_search_matches.append((start_index, end_index))\n start_pos = pos + 1\n \n if not actions_search_matches:\n actions_current_match_index = -1\n return\n \n for start_idx, end_idx in actions_search_matches:\n actions_log_text.tag_add(\"search_highlight\", start_idx, end_idx)\n \n if direction == 1:\n actions_current_match_index = (actions_current_match_index + 1) % len(actions_search_matches)\n else:\n actions_current_match_index = (actions_current_match_index - 1) % len(actions_search_matches)\n \n if actions_current_match_index >= 0:\n start_idx, end_idx = actions_search_matches[actions_current_match_index]\n actions_log_text.tag_add(\"search_current\", start_idx, end_idx)\n actions_log_text.see(start_idx)\n actions_log_text.mark_set(\"insert\", start_idx)\n \n def search_next_in_actions():\n search_in_actions_log(1)\n \n def search_prev_in_actions():\n search_in_actions_log(-1)\n \n def clear_search_in_actions():\n nonlocal actions_search_matches, actions_current_match_index\n actions_search_var.set(\"\")\n actions_log_text.tag_remove(\"search_highlight\", \"1.0\", \"end\")\n actions_log_text.tag_remove(\"search_current\", \"1.0\", \"end\")\n actions_search_matches = []\n actions_current_match_index = -1\n \n def on_actions_search_entry_key(event):\n if event.keysym == \"Return\":\n search_next_in_actions()\n \n actions_search_entry.bind(\"<KeyPress>\", on_actions_search_entry_key)\n \n ttk.Button(actions_log_top, text=\"搜索\", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2))\n ttk.Button(actions_log_top, text=\"上一个\", command=search_prev_in_actions).pack(side=LEFT, padx=(0, 2))\n ttk.Button(actions_log_top, text=\"下一个\", command=search_next_in_actions).pack(side=LEFT, padx=(0, 2))\n ttk.Button(actions_log_top, text=\"清除\", command=clear_search_in_actions).pack(side=LEFT)\n\n # OCR结果显示\n ocr_results_top = ttk.Frame(ocr_results_tab)\n ocr_results_top.pack(fill=X, padx=10, pady=(10, 0))\n ocr_results_text = ScrolledText(ocr_results_tab)\n ocr_results_text.pack(fill=BOTH, expand=True, padx=10, pady=10)\n try:\n ocr_results_text.configure(font=(\"Consolas\", 10))\n except Exception:\n pass\n\n def update_ocr_results(results):\n \"\"\"更新OCR结果标签页的显示\"\"\"\n try:\n lines = []\n lines.append(\"=\" * 80)\n lines.append(\"OCR识别结果(基于最新截图)\")\n lines.append(\"=\" * 80)\n lines.append(\"\")\n\n if not results:\n lines.append('暂无OCR结果,请先点击\"截图+OCR\"按钮')\n else:\n # 按区域名称分组显示\n for region_name, desc, text_result, status in results:\n lines.append(f\"【{region_name}】{desc}\")\n lines.append(f\" 状态: {status}\")\n if text_result:\n # 如果文本较长,分行显示\n if len(text_result) > 100:\n lines.append(f\" 识别文本: {text_result[:100]}...\")\n lines.append(f\" (完整文本: {text_result})\")\n else:\n lines.append(f\" 识别文本: {text_result}\")\n else:\n lines.append(\" 识别文本: (空)\")\n lines.append(\"\")\n\n ocr_results_text.delete(\"1.0\", \"end\")\n ocr_results_text.insert(\"1.0\", \"\\n\".join(lines))\n ocr_results_text.see(\"1.0\")\n except Exception as e:\n ocr_results_text.delete(\"1.0\", \"end\")\n ocr_results_text.insert(\"1.0\", f\"更新OCR结果失败:{e}\")\n\n ttk.Button(\n ocr_results_top, text=\"刷新\", command=lambda: update_ocr_results([])\n ).pack(side=LEFT)\n ttk.Label(ocr_results_top, text='(点击\"截图+OCR\"按钮自动更新)').pack(\n side=LEFT, padx=(10, 0)\n )\n\n pump_logs()\n\n def delayed_refresh_preview() -> None:\n if image_var.get():\n refresh_preview()\n\n root.after(300, delayed_refresh_preview) # type: ignore[arg-type]\n root.after(500, refresh_stats) # type: ignore[arg-type]\n root.after(500, refresh_reservations) # type: ignore[arg-type]\n root.after(500, refresh_high_value_rooms) # type: ignore[arg-type]\n root.after(500, refresh_actions_log) # type: ignore[arg-type]\n\n # 定期刷新行为日志(每2秒)\n def auto_refresh_actions_log() -> None:\n refresh_actions_log()\n root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]\n \n root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]\n\n # 定期刷新统计信息(每3秒)\n def auto_refresh_stats() -> None:\n if runner.is_running():\n refresh_stats()\n root.after(3000, auto_refresh_stats) # type: ignore[arg-type]\n\n auto_refresh_stats()\n\n def on_close():\n try:\n runner.stop()\n except Exception:\n pass\n root.destroy()\n\n root.protocol(\"WM_DELETE_WINDOW\", on_close)\n refresh_devices()\n root.mainloop()\n\n\nif __name__ == \"__main__\":\n try:\n from version import print_version_banner\n\n print_version_banner(\"gui_app\")\n except Exception:\n pass\n main()\n" +} +``` +User decision: **accepted** + +Status: **completed** + + +
+
+ +--- + + +
+Tool use: **apply_patch** + + +Parameters: + +```json +{ + "relativeWorkspacePath": "webui/app.js" +} +``` +Additional data: + +```json +{ + "codeblockId": "c9b5570c-6d12-4300-bf68-d75f84e6285e" +} +``` +Result: + +```json +{ + "diff": { + "chunks": [ + { + "diffString": " const reason = data.reason || \"\";\r\n \r\n- // 显示基本信息\r\n+ // 显示基本信息(中文)\r\n const info = document.createElement(\"div\");\r\n info.className = \"reservationsInfo\";\r\n info.innerHTML = `\r\n- <div><strong>当前位置:</strong>${room_pos}</div>\r\n+ <div><strong>当前直播间位置:</strong>${room_pos}</div>\r\n <div><strong>当前直播间(清洗后):</strong>${escapeHtml(current_room_title || '-') }</div>\r\n <div><strong>当前直播间原文:</strong>${escapeHtml(current_room_title_raw || '-') }</div>\r\n- <div><strong>预约数量:</strong>${reservations.length}</div>\r\n- <div class=\"hint\">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}</div>\r\n- <div class=\"hint\">原因:${escapeHtml(reason || '-') }</div>\r\n+ <div><strong>预约总数量:</strong>${reservations.length}</div>\r\n+ <div class=\"hint\">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleString() : '-'}</div>\r\n+ <div class=\"hint\">最近更新原因:${escapeHtml(reason || '-') }</div>\r\n `;\r\n container.appendChild(info);\r", + "oldStart": 806, + "newStart": 806, + "oldLines": 14, + "newLines": 14, + "linesRemoved": 5, + "linesAdded": 5 + }, + { + "diffString": " }\r\n \r\n- // 显示预约列表\r\n+ // 显示预约列表(更详细中文)\r\n const list = document.createElement(\"div\");\r\n list.className = \"reservationsList\";\r", + "oldStart": 827, + "newStart": 827, + "oldLines": 5, + "newLines": 5, + "linesRemoved": 1, + "linesAdded": 1 + }, + { + "diffString": " const future_ts = item.future_ts || 0;\r\n const remain = Math.max(0, Math.floor(future_ts - now));\r\n- const remainStr = remain > 0 ? `${Math.floor(remain / 60)}分${remain % 60}秒后` : \"已到开奖时间\";\r\n+ const remainStr = remain > 0 ? `${Math.floor(remain / 60)}分${remain % 60}秒后开奖` : \"已到开奖时间\";\r\n+ \r\n+ const createdTs = item.created_ts || 0;\r\n+ let createdStr = \"-\";\r\n+ if (createdTs > 0) {\r\n+ try {\r\n+ createdStr = new Date(createdTs * 1000).toLocaleString();\r\n+ } catch (e) {\r\n+ createdStr = String(createdTs);\r\n+ }\r\n+ }\r\n \r\n card.innerHTML = `\r\n <div class=\"reservationHeader\">\r\n <span class=\"reservationIndex\">#${idx + 1}</span>\r\n- <span class=\"reservationValue\">${item.prize_value_yuan || 0}元</span>\r\n+ <span class=\"reservationValue\">${item.prize_value_yuan || 0} 元</span>\r\n </div>\r\n <div class=\"reservationBody\">\r\n <div><strong>内容:</strong>${escapeHtml(item.content || '-')}</div>\r\n <div><strong>开奖时间:</strong>${item.future_str || '-'}</div>\r\n <div><strong>剩余时间:</strong>${remainStr}</div>\r\n- <div><strong>发现位置:</strong>${item.pos_seen || 0}</div>\r\n+ <div><strong>发现时直播间位置:</strong>${item.pos_seen || 0}</div>\r\n <div><strong>直播间(清洗后):</strong>${escapeHtml(item.room_title || '-')}</div>\r\n <div><strong>直播间原文:</strong>${escapeHtml(item.room_title_raw || '-')}</div>\r\n+ <div><strong>记录时间:</strong>${createdStr}</div>\r\n </div>\r\n `;\r", + "oldStart": 838, + "newStart": 838, + "oldLines": 18, + "newLines": 29, + "linesRemoved": 3, + "linesAdded": 14 + } + ], + "editor": "EDITOR_AI" + }, + "shouldAutoFixLints": true, + "resultForModel": "Success. Updated the following files:\nM webui/app.js", + "contentsAfterEdit": "let logIdx = 0;\r\nlet pollTimer = null;\r\nlet statsTimer = null;\r\nlet shotTimer = null;\r\nlet lastLogUpdateTime = 0; // 最后成功获取日志的时间\r\nlet logErrorCount = 0; // 连续错误计数\r\nlet emptyResponseCount = 0; // 连续空响应计数(用于检测索引卡住)\r\n\r\nconst DEFAULTS = {\r\n // 筛选\r\n min_prize_value_yuan: 0,\r\n min_participants: 0,\r\n max_participants: 0,\r\n skip_if_countdown_lt_seconds: 15,\r\n reset_after_swipes_enabled: false,\r\n reset_after_swipes: 10,\r\n auto_join_fansclub: false,\r\n fansclub_fail_action: \"stay\",\r\n\r\n // 养号\r\n yanghao_enabled: true,\r\n yanghao_enable_actions: true,\r\n yanghao_step_screenshot: false,\r\n yanghao_recommend_duration_seconds: 60,\r\n yanghao_recommend_interval_seconds: 0,\r\n yanghao_like_prob: 0.15,\r\n yanghao_fav_prob: 0.05,\r\n yanghao_comment_prob: 0,\r\n yanghao_icon_roi_size: 180,\r\n yanghao_icon_match_threshold: 0.72,\r\n yanghao_like_template_path: \"assets/like.png\",\r\n yanghao_fav_template_path: \"assets/fav.png\",\r\n yanghao_after_dwell_swipe_direction: \"up\",\r\n yanghao_after_dwell_swipe_distance_px: 900,\r\n\r\n // 高价值福袋预约\r\n high_value_fudai_enabled: false,\r\n high_value_fudai_threshold_yuan: 1000,\r\n high_value_fudai_join_ahead_seconds: 120,\r\n high_value_fudai_max_swipe_back: 60,\r\n high_value_fudai_max_reservations: 5,\r\n high_value_fudai_after_action: \"continue\",\r\n high_value_room_revisit_enabled: true,\r\n high_value_room_revisit_only_current_run: false,\r\n reservation_back_verify_enabled: true,\r\n // 找福袋图标相关\r\n fudai_find_max_attempts: 5,\r\n fudai_icon_retry_delay_seconds: 0.6,\r\n fudai_icon_max_wait_seconds: 5.0,\r\n live_room_match_threshold: 0.8,\r\n reservation_preempt_min_value: 0,\r\n reservation_back_swipe_delay: 0.6,\r\n\r\n // 定时禁抢福袋(默认 2-7 点)\r\n fudai_quiet_hours_enabled: true,\r\n fudai_quiet_start_hour: 2,\r\n fudai_quiet_end_hour: 7,\r\n\r\n // 调试相关\r\n \"debug_captures.enabled\": false,\r\n \"debug_captures.auto_cleanup\": true,\r\n \"debug_captures.keep_days\": 7,\r\n \"debug_captures.max_files\": 2000,\r\n enable_ocr_mode1: false,\r\n fudai_template_match_enabled: false,\r\n fudai_template_match_threshold: 0.7,\r\n lucky_draw_red_ratio_threshold: 0.8,\r\n live_room_match_threshold: 0.7,\r\n stage_diag_max_time: 15.0,\r\n stage_diag_max_step_time: 4.0,\r\n};\r\n\r\nfunction $(id) { return document.getElementById(id); }\r\n\r\nfunction initTabs() {\r\n const tabButtons = Array.from(document.querySelectorAll(\".tabBtn[data-target]\"));\r\n const panels = Array.from(document.querySelectorAll(\".panel[data-panel]\"));\r\n if (tabButtons.length === 0 || panels.length === 0) return;\r\n\r\n const setActive = (target) => {\r\n for (const btn of tabButtons) {\r\n const isActive = btn.dataset.target === target;\r\n btn.classList.toggle(\"active\", isActive);\r\n btn.setAttribute(\"aria-selected\", isActive ? \"true\" : \"false\");\r\n }\r\n for (const panel of panels) {\r\n const isActive = panel.dataset.panel === target;\r\n panel.toggleAttribute(\"hidden\", !isActive);\r\n panel.classList.toggle(\"active\", isActive);\r\n }\r\n };\r\n\r\n for (const btn of tabButtons) {\r\n btn.addEventListener(\"click\", () => setActive(btn.dataset.target));\r\n }\r\n\r\n const defaultTarget = tabButtons.find(b => b.classList.contains(\"active\"))?.dataset.target || tabButtons[0].dataset.target;\r\n setActive(defaultTarget);\r\n}\r\n\r\nfunction appendLog(lines) {\r\n const log = $(\"log\");\r\n if (!lines || lines.length === 0) return;\r\n \r\n // 检查是否在底部附近(用户可能在看最新日志)\r\n const wasNearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 100;\r\n \r\n // 性能优化:批量追加文本,减少重排次数\r\n const newText = lines.join(\"\\n\") + \"\\n\";\r\n log.textContent += newText;\r\n \r\n // 性能优化:限制日志长度,避免内存溢出(保留最近 50000 字符)\r\n const maxLength = 50000;\r\n if (log.textContent.length > maxLength) {\r\n log.textContent = log.textContent.slice(-maxLength);\r\n }\r\n \r\n // 只有在底部附近时才自动滚动,避免打断用户查看历史日志\r\n if (wasNearBottom) {\r\n log.scrollTop = log.scrollHeight;\r\n }\r\n}\r\n\r\nfunction fmtTime(ts) {\r\n if (!ts) return \"-\";\r\n try {\r\n return new Date(ts * 1000).toLocaleString();\r\n } catch {\r\n return \"-\";\r\n }\r\n}\r\n\r\nfunction fmtDuration(seconds) {\r\n const s = Math.max(0, parseInt(seconds || 0, 10));\r\n const h = Math.floor(s / 3600);\r\n const m = Math.floor((s % 3600) / 60);\r\n const sec = s % 60;\r\n if (h > 0) return `${h}小时${m}分${sec}秒`;\r\n if (m > 0) return `${m}分${sec}秒`;\r\n return `${sec}秒`;\r\n}\r\n\r\nfunction pollShot() {\r\n const img = $(\"liveShot\");\r\n if (!img) return;\r\n\r\n // 性能优化:避免重复加载相同的图片(如果正在加载中)\r\n if (img.dataset.loading === \"true\") return;\r\n \r\n const url = `/pic/screenshot.png?t=${Date.now()}`;\r\n img.dataset.loading = \"true\";\r\n img.src = url;\r\n\r\n const status = $(\"liveShotStatus\");\r\n if (status) status.textContent = `刷新中:${new Date().toLocaleTimeString()}`;\r\n}\r\n\r\nfunction startShotPolling() {\r\n if (shotTimer) clearInterval(shotTimer);\r\n\r\n const img = $(\"liveShot\");\r\n const status = $(\"liveShotStatus\");\r\n if (img) {\r\n img.addEventListener(\"load\", () => {\r\n img.dataset.loading = \"false\";\r\n if (status) status.textContent = `已更新:${new Date().toLocaleTimeString()}`;\r\n });\r\n img.addEventListener(\"error\", () => {\r\n img.dataset.loading = \"false\";\r\n if (status) status.textContent = \"暂无截图(等待脚本生成 pic/screenshot.png)\";\r\n });\r\n }\r\n\r\n // 性能优化:截图轮询间隔从 900ms 调整为 1500ms,减少服务器压力\r\n shotTimer = setInterval(pollShot, 1500);\r\n}\r\n\r\nfunction setTextIfExists(id, text) {\r\n const el = $(id);\r\n if (!el) return;\r\n el.textContent = String(text ?? \"-\");\r\n}\r\n\r\nfunction clearEl(el) {\r\n while (el && el.firstChild) el.removeChild(el.firstChild);\r\n}\r\n\r\n\r\nfunction renderBars(containerId, dataMap, labelMap) {\r\n const root = $(containerId);\r\n if (!root) return;\r\n clearEl(root);\r\n\r\n const m = (dataMap && typeof dataMap === \"object\") ? dataMap : {};\r\n const items = Object.keys(m).map(k => ({ key: k, count: Number(m[k]) || 0 }))\r\n .filter(x => x.count > 0);\r\n items.sort((a, b) => b.count - a.count);\r\n\r\n if (items.length === 0) {\r\n const d = document.createElement(\"div\");\r\n d.className = \"hint\";\r\n d.textContent = \"暂无数据\";\r\n root.appendChild(d);\r\n return;\r\n }\r\n\r\n const max = Math.max(...items.map(x => x.count));\r\n for (const it of items) {\r\n const row = document.createElement(\"div\");\r\n row.className = \"barRow\";\r\n\r\n const label = document.createElement(\"div\");\r\n label.className = \"barLabel\";\r\n label.textContent = (labelMap && labelMap[it.key]) ? labelMap[it.key] : it.key;\r\n\r\n const track = document.createElement(\"div\");\r\n track.className = \"barTrack\";\r\n const fill = document.createElement(\"div\");\r\n fill.className = \"barFill\";\r\n fill.style.width = `${max > 0 ? (it.count / max * 100) : 0}%`;\r\n track.appendChild(fill);\r\n\r\n const val = document.createElement(\"div\");\r\n val.className = \"barValue\";\r\n val.textContent = String(it.count);\r\n\r\n row.appendChild(label);\r\n row.appendChild(track);\r\n row.appendChild(val);\r\n root.appendChild(row);\r\n }\r\n}\r\n\r\nfunction renderTopContent(containerId, items) {\r\n const root = $(containerId);\r\n if (!root) return;\r\n clearEl(root);\r\n\r\n const list = Array.isArray(items) ? items : [];\r\n const head = document.createElement(\"div\");\r\n head.className = \"tableRow tableHead\";\r\n head.innerHTML = `<div>#</div><div>内容</div><div>次数</div>`;\r\n root.appendChild(head);\r\n\r\n if (list.length === 0) {\r\n const row = document.createElement(\"div\");\r\n row.className = \"tableRow\";\r\n row.innerHTML = `<div class=\"mono\">-</div><div class=\"hint\">暂无数据</div><div class=\"mono\">-</div>`;\r\n root.appendChild(row);\r\n return;\r\n }\r\n\r\n list.forEach((it, idx) => {\r\n const row = document.createElement(\"div\");\r\n row.className = \"tableRow\";\r\n const key = String(it.key ?? \"\");\r\n const cnt = Number(it.count) || 0;\r\n row.innerHTML = `<div class=\"mono\">#${idx + 1}</div><div>${escapeHtml(key)}</div><div class=\"mono\">${cnt}</div>`;\r\n root.appendChild(row);\r\n });\r\n}\r\n\r\nfunction escapeHtml(s) {\r\n return String(s ?? \"\")\r\n .replaceAll(\"&\", \"&amp;\")\r\n .replaceAll(\"<\", \"&lt;\")\r\n .replaceAll(\">\", \"&gt;\")\r\n .replaceAll('\"', \"&quot;\")\r\n .replaceAll(\"'\", \"&#39;\");\r\n}\r\n\r\nfunction renderWinsTable(containerId, wins) {\r\n const root = $(containerId);\r\n if (!root) return;\r\n clearEl(root);\r\n\r\n const list = Array.isArray(wins) ? wins : [];\r\n\r\n const head = document.createElement(\"div\");\r\n head.className = \"tableRow tableHead\";\r\n head.innerHTML = `<div>时间</div><div>内容</div><div>价值</div>`;\r\n root.appendChild(head);\r\n\r\n if (list.length === 0) {\r\n const row = document.createElement(\"div\");\r\n row.className = \"tableRow\";\r\n row.innerHTML = `<div class=\"mono\">-</div><div class=\"hint\">暂无中奖记录</div><div class=\"mono\">-</div>`;\r\n root.appendChild(row);\r\n return;\r\n }\r\n\r\n // 后端按时间顺序存储,这里倒序展示(最新在上)\r\n for (let i = list.length - 1; i >= 0; i--) {\r\n const it = list[i] || {};\r\n const ts = Number(it.ts) || 0;\r\n const content = String(it.content || \"-\");\r\n const value = (it.prize_value_yuan === null || typeof it.prize_value_yuan === \"undefined\") ? \"-\" : String(it.prize_value_yuan);\r\n\r\n const row = document.createElement(\"div\");\r\n row.className = \"tableRow\";\r\n row.innerHTML = `<div class=\"mono\">${escapeHtml(fmtTime(ts))}</div><div>${escapeHtml(content)}</div><div class=\"mono\">${escapeHtml(value)}</div>`;\r\n root.appendChild(row);\r\n }\r\n}\r\n\r\nfunction renderTimeline(containerId, timeline) {\r\n const root = $(containerId);\r\n if (!root) return;\r\n clearEl(root);\r\n\r\n const t = (timeline && typeof timeline === \"object\") ? timeline : null;\r\n const series = t && t.series && typeof t.series === \"object\" ? t.series : null;\r\n const bins = Number(t && t.bins) || 0;\r\n\r\n if (!series || bins <= 0) {\r\n const d = document.createElement(\"div\");\r\n d.className = \"hint\";\r\n d.textContent = \"暂无数据\";\r\n root.appendChild(d);\r\n return;\r\n }\r\n\r\n const keys = [\r\n \"fudai_open_detail\",\r\n \"fudai_attend_ok\",\r\n \"fudai_attend_fail\",\r\n \"fudai_result_win\",\r\n \"fudai_result_no_win\",\r\n \"fudai_skip\",\r\n \"switch_room\",\r\n ];\r\n\r\n let maxY = 0;\r\n for (const k of keys) {\r\n const arr = Array.isArray(series[k]) ? series[k] : [];\r\n for (const v of arr) maxY = Math.max(maxY, Number(v) || 0);\r\n }\r\n if (maxY <= 0) {\r\n const d = document.createElement(\"div\");\r\n d.className = \"hint\";\r\n d.textContent = \"暂无数据\";\r\n root.appendChild(d);\r\n return;\r\n }\r\n\r\n const W = 900;\r\n const H = 220;\r\n const padL = 36;\r\n const padR = 14;\r\n const padT = 10;\r\n const padB = 26;\r\n\r\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\r\n svg.setAttribute(\"viewBox\", `0 0 ${W} ${H}`);\r\n svg.setAttribute(\"width\", \"100%\");\r\n svg.setAttribute(\"height\", String(H));\r\n svg.style.display = \"block\";\r\n\r\n const axis = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\r\n axis.setAttribute(\"d\", `M ${padL} ${H - padB} L ${W - padR} ${H - padB}`);\r\n axis.setAttribute(\"stroke\", \"var(--border)\");\r\n axis.setAttribute(\"fill\", \"none\");\r\n svg.appendChild(axis);\r\n\r\n const mkText = (x, y, txt, anchor = \"start\") => {\r\n const el = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\r\n el.setAttribute(\"x\", String(x));\r\n el.setAttribute(\"y\", String(y));\r\n el.setAttribute(\"fill\", \"var(--muted)\");\r\n el.setAttribute(\"font-size\", \"11\");\r\n el.setAttribute(\"text-anchor\", anchor);\r\n el.textContent = txt;\r\n return el;\r\n };\r\n\r\n const startTs = Number(t.start_ts) || 0;\r\n const binSec = Number(t.bin_seconds) || 0;\r\n const xAt = (i) => {\r\n if (bins <= 1) return padL;\r\n return padL + (W - padL - padR) * (i / (bins - 1));\r\n };\r\n const yAt = (v) => {\r\n const vv = Number(v) || 0;\r\n const h = (H - padT - padB);\r\n return (H - padB) - (vv / maxY) * h;\r\n };\r\n\r\n // y 轴 max 标记\r\n svg.appendChild(mkText(padL, padT + 10, String(maxY), \"start\"));\r\n\r\n // x 轴 3 个时间刻度\r\n const fmtShort = (ts) => {\r\n if (!ts) return \"-\";\r\n try { return new Date(ts * 1000).toLocaleTimeString(); } catch { return \"-\"; }\r\n };\r\n svg.appendChild(mkText(padL, H - 8, fmtShort(startTs), \"start\"));\r\n svg.appendChild(mkText((padL + (W - padR)) / 2, H - 8, fmtShort(startTs + Math.floor(bins / 2) * binSec), \"middle\"));\r\n svg.appendChild(mkText(W - padR, H - 8, fmtShort(startTs + (bins - 1) * binSec), \"end\"));\r\n\r\n const strokes = {\r\n fudai_open_detail: { stroke: \"var(--primary)\", dash: \"\" },\r\n fudai_attend_ok: { stroke: \"var(--primary)\", dash: \"6 4\" },\r\n fudai_attend_fail: { stroke: \"var(--danger)\", dash: \"\" },\r\n fudai_result_win: { stroke: \"var(--danger)\", dash: \"6 4\" },\r\n fudai_result_no_win: { stroke: \"var(--muted)\", dash: \"\" },\r\n fudai_skip: { stroke: \"var(--muted)\", dash: \"6 4\" },\r\n switch_room: { stroke: \"var(--text)\", dash: \"2 4\" },\r\n };\r\n\r\n for (const k of keys) {\r\n const arr = Array.isArray(series[k]) ? series[k] : [];\r\n if (arr.length === 0) continue;\r\n let d = \"\";\r\n for (let i = 0; i < Math.min(bins, arr.length); i++) {\r\n const x = xAt(i);\r\n const y = yAt(arr[i]);\r\n d += (i === 0) ? `M ${x.toFixed(2)} ${y.toFixed(2)}` : ` L ${x.toFixed(2)} ${y.toFixed(2)}`;\r\n }\r\n const p = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\r\n p.setAttribute(\"d\", d);\r\n p.setAttribute(\"fill\", \"none\");\r\n p.setAttribute(\"stroke\", strokes[k]?.stroke || \"var(--primary)\");\r\n p.setAttribute(\"stroke-width\", \"2\");\r\n if (strokes[k]?.dash) p.setAttribute(\"stroke-dasharray\", strokes[k].dash);\r\n p.setAttribute(\"stroke-linecap\", \"round\");\r\n p.setAttribute(\"stroke-linejoin\", \"round\");\r\n svg.appendChild(p);\r\n }\r\n\r\n root.appendChild(svg);\r\n\r\n const legend = document.createElement(\"div\");\r\n legend.className = \"hint\";\r\n legend.textContent = \"图例:实线/虚线区分同色不同事件\";\r\n root.appendChild(legend);\r\n}\r\n\r\nasync function apiGet(path) {\r\n const res = await fetch(path, { cache: \"no-store\" });\r\n if (!res.ok) throw new Error(await res.text());\r\n return await res.json();\r\n}\r\n\r\nasync function apiPost(path, body) {\r\n const res = await fetch(path, {\r\n method: \"POST\",\r\n headers: { \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body || {}),\r\n });\r\n const data = await res.json();\r\n if (!res.ok) {\r\n const errorMsg = data.error || data.message || res.statusText;\r\n const error = new Error(errorMsg);\r\n error.status = res.status;\r\n error.data = data;\r\n throw error;\r\n }\r\n return data;\r\n}\r\n\r\nasync function refreshDevices() {\r\n const data = await apiGet(\"/api/devices\");\r\n const sel = $(\"device\");\r\n sel.innerHTML = \"\";\r\n const devices = data.devices || [];\r\n\r\n const optAuto = document.createElement(\"option\");\r\n optAuto.value = \"\";\r\n optAuto.textContent = \"(auto)\";\r\n sel.appendChild(optAuto);\r\n\r\n for (const d of devices) {\r\n const opt = document.createElement(\"option\");\r\n opt.value = d;\r\n opt.textContent = d;\r\n sel.appendChild(opt);\r\n }\r\n\r\n $(\"adbStatus\").textContent = data.adb ? `adb: ${data.adb}` : \"未找到 adb.exe(请安装 platform-tools)\";\r\n}\r\n\r\nfunction getConfigBoundElements() {\r\n return Array.from(document.querySelectorAll(\"[data-key]\"));\r\n}\r\n\r\nfunction coerceValue(type, raw, isCheckbox) {\r\n if (type === \"bool\") return !!raw;\r\n if (type === \"int\") {\r\n const n = parseInt(String(raw ?? \"0\"), 10);\r\n return Number.isFinite(n) ? n : 0;\r\n }\r\n if (type === \"float\") {\r\n const n = parseFloat(String(raw ?? \"0\"));\r\n return Number.isFinite(n) ? n : 0;\r\n }\r\n if (type === \"list_lines\") {\r\n if (Array.isArray(raw)) return raw.map(x => String(x).trim()).filter(Boolean);\r\n return String(raw ?? \"\").split(\"\\n\").map(x => x.trim()).filter(Boolean);\r\n }\r\n if (isCheckbox) return !!raw;\r\n return String(raw ?? \"\");\r\n}\r\n\r\nfunction getNestedValue(obj, key) {\r\n if (!obj || !key) return undefined;\r\n // 支持嵌套键,如 \"debug_captures.auto_cleanup\"\r\n if (key.includes(\".\")) {\r\n const parts = key.split(\".\");\r\n let current = obj;\r\n for (const part of parts) {\r\n if (current && typeof current === \"object\" && part in current) {\r\n current = current[part];\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n return current;\r\n }\r\n return obj[key];\r\n}\r\n\r\nfunction setNestedValue(obj, key, value) {\r\n if (!obj || !key) return;\r\n // 支持嵌套键,如 \"debug_captures.auto_cleanup\"\r\n if (key.includes(\".\")) {\r\n const parts = key.split(\".\");\r\n let current = obj;\r\n for (let i = 0; i < parts.length - 1; i++) {\r\n const part = parts[i];\r\n if (!(part in current) || typeof current[part] !== \"object\" || current[part] === null) {\r\n current[part] = {};\r\n }\r\n current = current[part];\r\n }\r\n current[parts[parts.length - 1]] = value;\r\n } else {\r\n obj[key] = value;\r\n }\r\n}\r\n\r\nfunction applyConfigToUI(cfg) {\r\n for (const el of getConfigBoundElements()) {\r\n const key = el.dataset.key;\r\n const type = el.dataset.type || \"str\";\r\n const val = cfg ? getNestedValue(cfg, key) : undefined;\r\n\r\n // undefined/null 都视为\"未配置\":保留页面默认值\r\n const hasVal = !(typeof val === \"undefined\" || val === null);\r\n const useVal = hasVal ? val : (Object.prototype.hasOwnProperty.call(DEFAULTS, key) ? DEFAULTS[key] : undefined);\r\n if (typeof useVal === \"undefined\") continue;\r\n\r\n if (el.type === \"checkbox\") {\r\n el.checked = !!useVal;\r\n continue;\r\n }\r\n if (type === \"list_lines\") {\r\n el.value = (Array.isArray(useVal) ? useVal : []).join(\"\\n\");\r\n continue;\r\n }\r\n el.value = String(useVal);\r\n }\r\n}\r\n\r\nfunction collectConfigFromUI() {\r\n const out = {};\r\n for (const el of getConfigBoundElements()) {\r\n const key = el.dataset.key;\r\n const type = el.dataset.type || \"str\";\r\n if (!key) continue;\r\n\r\n const value = el.type === \"checkbox\" \r\n ? coerceValue(type, el.checked, true)\r\n : coerceValue(type, el.value, false);\r\n \r\n // 支持嵌套键,如 \"debug_captures.auto_cleanup\"\r\n setNestedValue(out, key, value);\r\n }\r\n return out;\r\n}\r\n\r\nasync function loadConfig() {\r\n const cfg = await apiGet(\"/api/config\");\r\n applyConfigToUI(cfg);\r\n appendLog([\"[WEB] 配置已加载\"]);\r\n}\r\n\r\nasync function saveConfig() {\r\n const cfgUpdate = collectConfigFromUI();\r\n await apiPost(\"/api/config\", cfgUpdate);\r\n appendLog([\"[WEB] 配置已保存到 config.json\"]);\r\n}\r\n\r\nasync function startRun() {\r\n try {\r\n const deviceId = $(\"device\").value || \"\";\r\n const yPianyi = parseInt($(\"y_pianyi\").value || \"0\", 10);\r\n const waitMinutes = parseInt($(\"wait_minutes\").value || \"5\", 10);\r\n const needswitch = $(\"needswitch\").checked;\r\n const cfgPart = collectConfigFromUI();\r\n\r\n appendLog([`[WEB] 正在启动...`]);\r\n \r\n const result = await apiPost(\"/api/start-run\", {\r\n device_id: deviceId,\r\n y_pianyi: yPianyi,\r\n wait_minutes: waitMinutes,\r\n needswitch,\r\n reset_after_swipes_enabled: cfgPart.reset_after_swipes_enabled,\r\n min_prize_value_yuan: cfgPart.min_prize_value_yuan,\r\n min_participants: cfgPart.min_participants,\r\n max_participants: cfgPart.max_participants,\r\n skip_if_countdown_lt_seconds: cfgPart.skip_if_countdown_lt_seconds,\r\n reset_after_swipes: cfgPart.reset_after_swipes,\r\n auto_join_fansclub: cfgPart.auto_join_fansclub,\r\n fansclub_fail_action: cfgPart.fansclub_fail_action,\r\n high_value_room_revisit_enabled: cfgPart.high_value_room_revisit_enabled,\r\n high_value_room_revisit_only_current_run: cfgPart.high_value_room_revisit_only_current_run,\r\n reservation_back_verify_enabled: cfgPart.reservation_back_verify_enabled,\r\n reservation_back_swipe_delay: cfgPart.reservation_back_swipe_delay,\r\n fudai_find_max_attempts: cfgPart.fudai_find_max_attempts,\r\n reservation_preempt_min_value: cfgPart.reservation_preempt_min_value,\r\n });\r\n \r\n // 检查返回结果\r\n if (result && result.ok === false) {\r\n const errorMsg = result.error || \"未知错误\";\r\n appendLog([`[WEB] 启动失败: ${errorMsg}`]);\r\n if (errorMsg === \"running\") {\r\n appendLog([`[WEB] 提示:已有进程在运行中,请先点击\"停止\"按钮`]);\r\n }\r\n return;\r\n }\r\n \r\n appendLog([`[WEB] 已开始运行:device=${deviceId || '(auto)'}`]);\r\n \r\n // 启动时自动截图\r\n if (deviceId) {\r\n try {\r\n appendLog([\"[截图] 启动时自动截图...\"]);\r\n const screenshotResult = await apiPost(\"/api/screenshot\", { device_id: deviceId });\r\n if (screenshotResult.ok) {\r\n appendLog([\"[截图] 启动截图成功,已保存到 pic/screenshot.png\"]);\r\n // 刷新截图显示\r\n pollShot();\r\n } else {\r\n appendLog([`[截图] 启动截图失败: ${screenshotResult.error || \"未知错误\"}`]);\r\n }\r\n } catch (e) {\r\n appendLog([`[截图] 启动截图失败: ${e?.message || e}`]);\r\n }\r\n }\r\n \r\n // 重置本地日志索引并清空显示区域,然后立即拉取最新日志\r\n try {\r\n logIdx = 0;\r\n emptyResponseCount = 0; // 重置空响应计数\r\n // 清空日志显示区域,准备显示新进程的日志\r\n const logEl = $(\"log\");\r\n if (logEl) {\r\n logEl.textContent = \"\";\r\n }\r\n await pollLogs();\r\n } catch (e) {\r\n console.error(\"[WEB] pollLogs error after start:\", e);\r\n }\r\n } catch (e) {\r\n console.error(\"[WEB] startRun error:\", e);\r\n const errorMsg = e.message || String(e);\r\n appendLog([`[WEB] 启动失败: ${errorMsg}`]);\r\n // 如果是\"running\"错误,显示友好提示\r\n if (errorMsg === \"running\" || (e.status === 409)) {\r\n appendLog([`[WEB] 提示:已有进程在运行中,请先点击\"停止\"按钮`]);\r\n }\r\n }\r\n}\r\n\r\nasync function testYanghao() {\r\n const deviceId = $(\"device\").value || \"\";\r\n const seconds = parseInt($(\"yanghao_recommend_duration_seconds\").value || \"60\", 10);\r\n await apiPost(\"/api/test-yanghao\", { device_id: deviceId, seconds });\r\n appendLog([`[WEB] 已启动测试养号:device=${deviceId || '(auto)'} seconds=${seconds}`]);\r\n}\r\n\r\nasync function testComment() {\r\n const deviceId = $(\"device\").value || \"\";\r\n const text = \"\";\r\n await apiPost(\"/api/test-comment\", { device_id: deviceId, text });\r\n appendLog([`[WEB] 已启动测试评论:device=${deviceId || '(auto)'}${text ? ' text=自定义' : ''}`]);\r\n}\r\n\r\nasync function stopRun() {\r\n await apiPost(\"/api/stop\", {});\r\n appendLog([\"[WEB] 已发送停止\"]);\r\n // 重置并拉取日志,确保能看到后端的停止确认输出\r\n try {\r\n logIdx = 0;\r\n emptyResponseCount = 0; // 重置空响应计数\r\n await pollLogs();\r\n } catch (e) {\r\n // ignore\r\n }\r\n}\r\n\r\nasync function pollLogs() {\r\n try {\r\n const data = await apiGet(`/api/logs?since=${logIdx}`);\r\n \r\n // 检查返回数据是否有效\r\n if (!data || typeof data !== 'object') {\r\n console.error('[WEB_DBG] pollLogs: invalid response data', data);\r\n logErrorCount++;\r\n return;\r\n }\r\n \r\n // 重置错误计数(API调用成功)\r\n logErrorCount = 0;\r\n // 记录API调用成功的时间(即使没有新日志,也说明连接正常)\r\n const apiCallTime = Date.now();\r\n \r\n // 获取返回的索引\r\n const nextIdx = typeof data.next === 'number' ? data.next : 0;\r\n \r\n // 如果返回的索引小于当前索引,说明日志被截断了,需要重置\r\n // 或者如果返回了所有日志(lines数量很大),也可能是重置了索引\r\n if (nextIdx < logIdx && logIdx > 0) {\r\n console.warn('[WEB_DBG] pollLogs: 检测到日志截断,重置索引', { oldIdx: logIdx, newIdx: nextIdx });\r\n logIdx = 0;\r\n emptyResponseCount = 0; // 重置空响应计数\r\n // 清空日志显示区域,准备重新显示\r\n const log = document.getElementById('log');\r\n if (log) {\r\n log.textContent = '';\r\n }\r\n // 重新请求一次以获取所有日志\r\n const retryData = await apiGet(`/api/logs?since=0`);\r\n if (retryData && typeof retryData === 'object' && Array.isArray(retryData.lines)) {\r\n logIdx = typeof retryData.next === 'number' ? retryData.next : 0;\r\n if (retryData.lines.length > 0) {\r\n appendLog(retryData.lines);\r\n }\r\n }\r\n return;\r\n }\r\n \r\n // 更新日志索引\r\n logIdx = nextIdx;\r\n // API调用成功,更新最后更新时间(不管是否有新日志)\r\n lastLogUpdateTime = apiCallTime;\r\n \r\n // 追加日志\r\n if (Array.isArray(data.lines) && data.lines.length > 0) {\r\n appendLog(data.lines);\r\n emptyResponseCount = 0; // 重置空响应计数\r\n } else {\r\n // 没有新日志是正常的(比如脚本没有运行),不需要重置索引\r\n // 只有在检测到索引不同步时才重置(已在前面处理)\r\n emptyResponseCount++;\r\n // 移除自动重置逻辑,避免在没有新日志时频繁清空日志显示\r\n }\r\n \r\n // 容错:确保索引不为负数\r\n if (logIdx < 0) {\r\n console.warn('[WEB_DBG] pollLogs: logIdx为负数,重置为0');\r\n logIdx = 0;\r\n emptyResponseCount = 0;\r\n }\r\n } catch (e) {\r\n logErrorCount++;\r\n console.error('[WEB_DBG] pollLogs error:', e);\r\n // 如果连续10次出错,重置索引\r\n if (logErrorCount >= 10) {\r\n console.warn('[WEB_DBG] pollLogs: 连续10次错误,重置索引');\r\n logIdx = 0;\r\n logErrorCount = 0;\r\n emptyResponseCount = 0; // 重置空响应计数\r\n }\r\n // 错误时不追加日志到界面,避免刷屏,只在控制台输出\r\n // 如果是网络错误或超时,不重置索引;如果是其他错误,考虑重置\r\n if (e.message && !e.message.includes('NetworkError') && !e.message.includes('Failed to fetch') && !e.message.includes('timeout')) {\r\n console.error('[WEB_DBG] pollLogs failed:', e.message);\r\n // 非网络错误,可能是数据格式错误,重置索引尝试恢复\r\n if (e.message.includes('JSON') || e.message.includes('parse')) {\r\n console.warn('[WEB_DBG] pollLogs: 数据解析错误,重置索引');\r\n logIdx = 0;\r\n emptyResponseCount = 0; // 重置空响应计数\r\n }\r\n }\r\n }\r\n}\r\n\r\nasync function pollReservations() {\r\n try {\r\n const data = await apiGet(`/api/reservations?t=${Date.now()}`);\r\n const container = $(\"reservationsContent\");\r\n if (!container) return;\r\n // 保留上次滚动位置\r\n const prevList = container.querySelector('.reservationsList');\r\n const prevScroll = prevList ? prevList.scrollTop : 0;\r\n clearEl(container);\r\n \r\n const reservations = data.reservations || [];\r\n const room_pos = data.room_pos || 0;\r\n const updated_ts = data.updated_ts || 0;\r\n const current_room_title = data.current_room_title || \"\";\r\n const current_room_title_raw = data.current_room_title_raw || \"\";\r\n const reason = data.reason || \"\";\r\n \r\n // 显示基本信息(中文)\r\n const info = document.createElement(\"div\");\r\n info.className = \"reservationsInfo\";\r\n info.innerHTML = `\r\n <div><strong>当前直播间位置:</strong>${room_pos}</div>\r\n <div><strong>当前直播间(清洗后):</strong>${escapeHtml(current_room_title || '-') }</div>\r\n <div><strong>当前直播间原文:</strong>${escapeHtml(current_room_title_raw || '-') }</div>\r\n <div><strong>预约总数量:</strong>${reservations.length}</div>\r\n <div class=\"hint\">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleString() : '-'}</div>\r\n <div class=\"hint\">最近更新原因:${escapeHtml(reason || '-') }</div>\r\n `;\r\n container.appendChild(info);\r\n\r\n if (reservations.length === 0) {\r\n const hint = document.createElement(\"div\");\r\n hint.className = \"hint\";\r\n hint.textContent = \"暂无预约信息\";\r\n container.appendChild(hint);\r\n return;\r\n }\r\n \r\n // 显示预约列表(更详细中文)\r\n const list = document.createElement(\"div\");\r\n list.className = \"reservationsList\";\r\n \r\n reservations.forEach((item, idx) => {\r\n const card = document.createElement(\"div\");\r\n card.className = \"reservationItem\";\r\n \r\n const now = Date.now() / 1000;\r\n const future_ts = item.future_ts || 0;\r\n const remain = Math.max(0, Math.floor(future_ts - now));\r\n const remainStr = remain > 0 ? `${Math.floor(remain / 60)}分${remain % 60}秒后开奖` : \"已到开奖时间\";\r\n\r\n const createdTs = item.created_ts || 0;\r\n let createdStr = \"-\";\r\n if (createdTs > 0) {\r\n try {\r\n createdStr = new Date(createdTs * 1000).toLocaleString();\r\n } catch (e) {\r\n createdStr = String(createdTs);\r\n }\r\n }\r\n \r\n card.innerHTML = `\r\n <div class=\"reservationHeader\">\r\n <span class=\"reservationIndex\">#${idx + 1}</span>\r\n <span class=\"reservationValue\">${item.prize_value_yuan || 0} 元</span>\r\n </div>\r\n <div class=\"reservationBody\">\r\n <div><strong>内容:</strong>${escapeHtml(item.content || '-')}</div>\r\n <div><strong>开奖时间:</strong>${item.future_str || '-'}</div>\r\n <div><strong>剩余时间:</strong>${remainStr}</div>\r\n <div><strong>发现时直播间位置:</strong>${item.pos_seen || 0}</div>\r\n <div><strong>直播间(清洗后):</strong>${escapeHtml(item.room_title || '-')}</div>\r\n <div><strong>直播间原文:</strong>${escapeHtml(item.room_title_raw || '-')}</div>\r\n <div><strong>记录时间:</strong>${createdStr}</div>\r\n </div>\r\n `;\r\n list.appendChild(card);\r\n });\r\n \r\n container.appendChild(list);\r\n // 恢复滚动位置(若有)\r\n try { list.scrollTop = prevScroll; } catch (e) { /* ignore */ }\r\n } catch (e) {\r\n console.error(\"poll reservations failed:\", e);\r\n const container = $(\"reservationsContent\");\r\n if (!container) return;\r\n clearEl(container);\r\n const hint = document.createElement(\"div\");\r\n hint.className = \"hint\";\r\n hint.textContent = `预约信息获取失败:${e?.message || e}`;\r\n container.appendChild(hint);\r\n }\r\n}\r\n\r\nasync function pollHighValueRooms() {\r\n try {\r\n const data = await apiGet(`/api/high-value-rooms?t=${Date.now()}`);\r\n const container = $(\"highValueRoomsContent\");\r\n if (!container) return;\r\n // 保留上次滚动位置\r\n const prevList = container.querySelector('.reservationsList');\r\n const prevScroll = prevList ? prevList.scrollTop : 0;\r\n clearEl(container);\r\n\r\n const rooms = Array.isArray(data.rooms) ? data.rooms : [];\r\n const updated_ts = Number(data.updated_ts) || 0;\r\n const reason = String(data.reason || \"\");\r\n const total = Number(data.total) || rooms.length;\r\n\r\n const info = document.createElement(\"div\");\r\n info.className = \"reservationsInfo\";\r\n info.innerHTML = `\r\n <div><strong>记录数量:</strong>${total}</div>\r\n <div class=\"hint\">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}</div>\r\n <div class=\"hint\">原因:${escapeHtml(reason || '-') }</div>\r\n `;\r\n container.appendChild(info);\r\n\r\n if (rooms.length === 0) {\r\n const hint = document.createElement(\"div\");\r\n hint.className = \"hint\";\r\n hint.textContent = \"暂无记录\";\r\n container.appendChild(hint);\r\n return;\r\n }\r\n\r\n const list = document.createElement(\"div\");\r\n list.className = \"reservationsList\";\r\n\r\n rooms.forEach((item, idx) => {\r\n const card = document.createElement(\"div\");\r\n card.className = \"reservationItem\";\r\n\r\n const roomTitle = String(item.room_title || \"-\");\r\n const roomRaw = String(item.room_title_raw_last || \"-\");\r\n const posSeen = (typeof item.pos_seen === \"number\") ? item.pos_seen : ((item.pos_seen === null || typeof item.pos_seen === \"undefined\") ? \"-\" : String(item.pos_seen));\r\n const firstSeen = Number(item.first_seen_ts) || 0;\r\n const lastSeen = Number(item.last_seen_ts) || 0;\r\n const seenCount = Number(item.seen_count) || 0;\r\n const maxVal = (item.max_prize_value_yuan === null || typeof item.max_prize_value_yuan === \"undefined\") ? \"-\" : String(item.max_prize_value_yuan);\r\n const lastVal = (item.last_prize_value_yuan === null || typeof item.last_prize_value_yuan === \"undefined\") ? \"-\" : String(item.last_prize_value_yuan);\r\n\r\n card.innerHTML = `\r\n <div class=\"reservationHeader\">\r\n <span class=\"reservationIndex\">#${idx + 1}</span>\r\n <span class=\"reservationValue\">max ${escapeHtml(maxVal)}元</span>\r\n </div>\r\n <div class=\"reservationBody\">\r\n <div><strong>直播间(清洗后):</strong>${escapeHtml(roomTitle)}</div>\r\n <div><strong>直播间原文:</strong>${escapeHtml(roomRaw)}</div>\r\n <div><strong>最近位置:</strong>${escapeHtml(posSeen)}</div>\r\n <div><strong>首次记录:</strong>${escapeHtml(fmtTime(firstSeen))}</div>\r\n <div><strong>最近记录:</strong>${escapeHtml(fmtTime(lastSeen))}</div>\r\n <div><strong>记录次数:</strong>${escapeHtml(seenCount)}</div>\r\n <div><strong>最近价值:</strong>${escapeHtml(lastVal)}元</div>\r\n </div>\r\n `;\r\n // 让每条记录的 header 可点击以折叠/展开本条详情\r\n list.appendChild(card);\r\n try {\r\n const header = card.querySelector('.reservationHeader');\r\n const body = card.querySelector('.reservationBody');\r\n if (header && body) {\r\n header.style.cursor = 'pointer';\r\n header.addEventListener('click', () => {\r\n if (body.style.display === 'none') {\r\n body.style.display = '';\r\n } else {\r\n body.style.display = 'none';\r\n }\r\n });\r\n }\r\n } catch (e) {\r\n // ignore\r\n }\r\n \r\n });\r\n\r\n container.appendChild(list);\r\n // 恢复滚动位置(若有)\r\n try { list.scrollTop = prevScroll; } catch (e) { /* ignore */ }\r\n // 全局折叠/展开按钮绑定:折叠/展开整个列表(隐藏序号/条目),而不是仅隐藏每条的详情\r\n try {\r\n const btnExpand = $('hv_expand_all');\r\n const btnCollapse = $('hv_collapse_all');\r\n if (btnExpand) btnExpand.addEventListener('click', () => {\r\n const listEl = container.querySelector('.reservationsList');\r\n if (listEl) listEl.style.display = '';\r\n });\r\n if (btnCollapse) btnCollapse.addEventListener('click', () => {\r\n const listEl = container.querySelector('.reservationsList');\r\n if (listEl) listEl.style.display = 'none';\r\n });\r\n } catch (e) {\r\n // ignore\r\n }\r\n } catch (e) {\r\n console.error(\"poll high value rooms failed:\", e);\r\n const container = $(\"highValueRoomsContent\");\r\n if (!container) return;\r\n clearEl(container);\r\n const hint = document.createElement(\"div\");\r\n hint.className = \"hint\";\r\n hint.textContent = `直播间记录获取失败:${e?.message || e}`;\r\n container.appendChild(hint);\r\n }\r\n}\r\n\r\nasync function pollStats() {\r\n try {\r\n const s = await apiGet(`/api/stats?t=${Date.now()}`);\r\n const running = s.running ? \"运行中\" : \"未运行\";\r\n setTextIfExists(\"statRunning\", running);\r\n setTextIfExists(\"statPid\", s.pid ?? \"-\");\r\n setTextIfExists(\"statUptime\", fmtDuration(s.uptime_seconds));\r\n setTextIfExists(\"statLogLen\", s.log_len ?? \"-\");\r\n if ($(\"statLogCap\")) {\r\n const cap = s.log_capacity ?? 2000;\r\n const len = s.log_len ?? 0;\r\n $(\"statLogCap\").textContent = `缓存上限:${cap}(已用 ${len}/${cap})`;\r\n }\r\n setTextIfExists(\"statLastLog\", fmtTime(s.last_log_ts));\r\n setTextIfExists(\"statExitCode\", (s.exit_code === null || typeof s.exit_code === \"undefined\") ? \"-\" : s.exit_code);\r\n \r\n // 显示traceId和MDC信息\r\n const traceId = s.trace_id || \"-\";\r\n setTextIfExists(\"statTraceId\", traceId);\r\n const mdcContext = s.mdc_context || {};\r\n if ($(\"statTraceIdHint\")) {\r\n const mdcKeys = Object.keys(mdcContext);\r\n if (mdcKeys.length > 0) {\r\n const mdcStr = mdcKeys.map(k => `${k}=${mdcContext[k]}`).join(\", \");\r\n $(\"statTraceIdHint\").textContent = `MDC: ${mdcStr}`;\r\n } else {\r\n $(\"statTraceIdHint\").textContent = \"\";\r\n }\r\n }\r\n\r\n const c = s.counters || {};\r\n const getC = (k) => Number.isFinite(Number(c[k])) ? Number(c[k]) : 0;\r\n\r\n setTextIfExists(\"statFudaiSeen\", getC(\"fudai_seen\"));\r\n setTextIfExists(\"statFudaiOpen\", getC(\"fudai_open_detail\"));\r\n setTextIfExists(\"statFudaiAttendOk\", getC(\"fudai_attend_ok\"));\r\n setTextIfExists(\"statFudaiAttendFail\", getC(\"fudai_attend_fail\"));\r\n setTextIfExists(\"statFudaiNoWin\", getC(\"fudai_result_no_win\"));\r\n setTextIfExists(\"statFudaiWin\", getC(\"fudai_result_win\"));\r\n\r\n setTextIfExists(\"statSkipValueLow\", getC(\"fudai_skip_value_low\"));\r\n\r\n const pLow = getC(\"fudai_skip_participants_low\");\r\n const pHigh = getC(\"fudai_skip_participants_high\");\r\n setTextIfExists(\"statSkipParticipants\", pLow + pHigh);\r\n if ($(\"statSkipParticipantsHint\")) {\r\n $(\"statSkipParticipantsHint\").textContent = `低:${pLow} / 高:${pHigh}`;\r\n }\r\n\r\n setTextIfExists(\"statSkipContent\", getC(\"fudai_skip_content\"));\r\n\r\n const cdShort = getC(\"fudai_skip_countdown_short\");\r\n const cdLong = getC(\"fudai_skip_countdown_long\");\r\n setTextIfExists(\"statSkipCountdown\", cdShort + cdLong);\r\n if ($(\"statSkipCountdownHint\")) {\r\n $(\"statSkipCountdownHint\").textContent = `短:${cdShort} / 长:${cdLong}`;\r\n }\r\n\r\n const fcReq = getC(\"fansclub_required\");\r\n const fcManual = getC(\"fansclub_manual_needed\");\r\n const fcUn = getC(\"fansclub_unresolved\");\r\n setTextIfExists(\"statFansclub\", fcReq);\r\n if ($(\"statFansclubHint\")) {\r\n $(\"statFansclubHint\").textContent = `需手动:${fcManual} / 未解决:${fcUn}`;\r\n }\r\n\r\n const sw = getC(\"switch_room\");\r\n setTextIfExists(\"statSwitchRoom\", sw);\r\n if ($(\"statSwitchRoomHint\")) {\r\n const parts = [\r\n `无福袋:${getC(\"switch_room_no_fudai\")}`,\r\n `人数:${getC(\"switch_room_participants\")}`,\r\n `价值:${getC(\"switch_room_value\")}`,\r\n `内容:${getC(\"switch_room_content\")}`,\r\n `倒计时:${getC(\"switch_room_countdown\")}`,\r\n `参与失败:${getC(\"switch_room_attend_fail\")}`,\r\n ];\r\n $(\"statSwitchRoomHint\").textContent = parts.join(\" / \");\r\n }\r\n\r\n const last = s.fudai_last || {};\r\n setTextIfExists(\"statLastContent\", last.content || \"-\");\r\n setTextIfExists(\"statLastCountdown\", last.countdown || \"-\");\r\n const ppl = (typeof last.participants === \"number\") ? String(last.participants) : \"-\";\r\n const cop = (typeof last.copies === \"number\") ? String(last.copies) : \"-\";\r\n setTextIfExists(\"statLastPeople\", `${ppl} / ${cop}`);\r\n const val = (typeof last.prize_value_yuan === \"number\") ? String(last.prize_value_yuan) : \"-\";\r\n setTextIfExists(\"statLastValue\", val);\r\n if ($(\"statLastUpdated\")) {\r\n $(\"statLastUpdated\").textContent = last.updated_ts ? `更新时间:${fmtTime(last.updated_ts)}` : \"更新时间:-\";\r\n }\r\n\r\n // ====== 详细聚合渲染(趋势/分布/Top) ======\r\n const agg = s.agg || {};\r\n const reasonName = {\r\n value_low: \"价值过低\",\r\n participants_low: \"人数过少\",\r\n participants_high: \"人数过多\",\r\n content: \"内容不匹配\",\r\n countdown_short: \"倒计时太短\",\r\n countdown_long: \"倒计时太长\",\r\n unknown: \"未知\",\r\n };\r\n const switchName = {\r\n no_fudai: \"无福袋\",\r\n participants: \"人数不符合\",\r\n value: \"价值不符合\",\r\n content: \"内容不符合\",\r\n countdown: \"倒计时不符合\",\r\n attend_fail: \"参与失败\",\r\n unknown: \"未知\",\r\n };\r\n\r\n renderTimeline(\"chartTimeline\", agg.timeline);\r\n renderBars(\"chartSkipReason\", agg.skip_reason || {}, reasonName);\r\n renderBars(\"chartSwitchReason\", agg.switch_reason || {}, switchName);\r\n renderBars(\"chartValueBuckets\", agg.value_buckets || {});\r\n renderBars(\"chartParticipantsBuckets\", agg.participants_buckets || {});\r\n renderBars(\"chartCountdownBuckets\", agg.countdown_buckets || {});\r\n renderTopContent(\"tableTopContent\", agg.content_top || []);\r\n\r\n // ====== 中奖内容列表 ======\r\n renderWinsTable(\"tableWins\", s.wins || []);\r\n } catch (e) {\r\n // 统计失败不打断其他功能\r\n }\r\n}\r\n\r\nfunction startPolling() {\r\n if (pollTimer) clearInterval(pollTimer);\r\n // 性能优化:日志轮询间隔从 700ms 调整为 800ms,减少服务器压力同时保持实时性\r\n pollTimer = setInterval(pollLogs, 800);\r\n}\r\n\r\nfunction startStatsPolling() {\r\n if (statsTimer) clearInterval(statsTimer);\r\n statsTimer = setInterval(() => {\r\n pollStats();\r\n pollReservations();\r\n pollHighValueRooms();\r\n }, 1200);\r\n}\r\n\r\nwindow.addEventListener(\"DOMContentLoaded\", async () => {\r\n initTabs();\r\n $(\"btnRefresh\").addEventListener(\"click\", refreshDevices);\r\n $(\"btnLoad\").addEventListener(\"click\", async () => { await loadConfig(); });\r\n $(\"btnSave\").addEventListener(\"click\", async () => { await saveConfig(); });\r\n $(\"btnStart\").addEventListener(\"click\", async () => { await startRun(); });\r\n $(\"btnStop\").addEventListener(\"click\", async () => { await stopRun(); });\r\n \r\n // 截图按钮\r\n $(\"btnScreenshot\").addEventListener(\"click\", async () => {\r\n const deviceId = $(\"device\").value || \"\";\r\n if (!deviceId) {\r\n appendLog([\"[截图] 请先选择设备\"]);\r\n return;\r\n }\r\n try {\r\n appendLog([\"[截图] 正在截图...\"]);\r\n const result = await apiPost(\"/api/screenshot\", { device_id: deviceId });\r\n if (result.ok) {\r\n appendLog([\"[截图] 截图成功,已保存到 pic/screenshot.png\"]);\r\n // 刷新截图显示\r\n pollShot();\r\n } else {\r\n appendLog([`[截图] 截图失败: ${result.error || \"未知错误\"}`]);\r\n }\r\n } catch (e) {\r\n appendLog([`[截图] 截图失败: ${e?.message || e}`]);\r\n }\r\n });\r\n \r\n // 截图按钮\r\n $(\"btnScreenshot\").addEventListener(\"click\", async () => {\r\n const deviceId = $(\"device\").value || \"\";\r\n if (!deviceId) {\r\n appendLog([\"[截图] 请先选择设备\"]);\r\n return;\r\n }\r\n try {\r\n appendLog([\"[截图] 正在截图...\"]);\r\n const result = await apiPost(\"/api/screenshot\", { device_id: deviceId });\r\n if (result.ok) {\r\n appendLog([\"[截图] 截图成功,已保存到 pic/screenshot.png\"]);\r\n // 刷新截图显示\r\n pollShot();\r\n } else {\r\n appendLog([`[截图] 截图失败: ${result.error || \"未知错误\"}`]);\r\n }\r\n } catch (e) {\r\n appendLog([`[截图] 截图失败: ${e?.message || e}`]);\r\n }\r\n });\r\n\r\n await refreshDevices();\r\n await loadConfig();\r\n\r\n startPolling();\r\n startStatsPolling();\r\n startShotPolling();\r\n pollLogs();\r\n pollStats();\r\n pollShot();\r\n pollReservations();\r\n pollHighValueRooms();\r\n});" +} +``` +User decision: **accepted** + +Status: **completed** + + +
+
+ +--- + + +
+ Tool use: **read_lints** • Read lints for 2 files + +Lint paths: + +- `gui_app.py` +- `webui/app.js` + +Lint results + +Lint errors for `gui_app.py` + + +| Message | Range | Severity | +|-------|-------|----------| +| 代码不会被执行 | 235:9-235:17 | DIAGNOSTIC_SEVERITY_HINT | +| "args" 未使用 | 568:36-568:40 | DIAGNOSTIC_SEVERITY_HINT | +| 变量 "dirs" 未使用 | 1870:23-1870:27 | DIAGNOSTIC_SEVERITY_HINT | +| "args" 未使用 | 1993:28-1993:32 | DIAGNOSTIC_SEVERITY_HINT | + + +
+
+ +--- + +### 已做的改动 + +- **桌面 GUI(`gui_app.py`)预约队列页** + - 不再直接显示英文 JSON。 + - 现在会显示中文总结和明细,例如: + - 总览:`更新时间 / 当前直播间位置 / 当前直播间(清洗后 & 原文)/ 预约总数量 / 最近更新原因`。 + - 每条记录:`[#序号] 价值:xx.xx 元`、`奖品内容`、`预计开奖时间`、`剩余时间(xx分xx秒后开奖 / 已到开奖时间)`、`发现时直播间位置`、`直播间(清洗后/原文)`、`记录时间`。 + +- **Web 界面预约队列卡片(`webui/app.js` + `index.html`)** + - 顶部信息改为纯中文并更详细:`当前直播间位置 / 当前直播间(清洗后/原文)/ 预约总数量 / 更新时间(含日期时间)/ 最近更新原因`。 + - 每条预约卡片增加并本地化: + - `价值:X 元`,`内容`,`开奖时间`,`剩余时间:X分Y秒后开奖 / 已到开奖时间`, + - `发现时直播间位置`,`直播间(清洗后/原文)`,`记录时间(本地日期时间)`。 + +现在无论是桌面 GUI 还是 Web 预约队列,展示都是中文且信息更加完整、易读。 + +--- + +_**User (2025-12-26 07:02Z)**_ + +点击加入粉丝团之后要点击的位置改成545,1995然后再关闭详情页 + +--- + +_**Agent (model default, mode Agent)**_ + + + --- diff --git a/.specstory/history/2025-12-26_07-05Z-粉丝团点击位置与详情页关闭.md b/.specstory/history/2025-12-26_07-05Z-粉丝团点击位置与详情页关闭.md new file mode 100644 index 0000000..e05ae54 --- /dev/null +++ b/.specstory/history/2025-12-26_07-05Z-粉丝团点击位置与详情页关闭.md @@ -0,0 +1,865 @@ + + + + +# 粉丝团点击位置与详情页关闭 (2025-12-26 07:05Z) + +_**User (2025-12-26 07:02Z)**_ + +点击加入粉丝团之后要点击的位置改成545,1995然后再关闭详情页 + +--- + +_**Agent (model default, mode Agent)**_ + + + +--- + + +查看代码,定位“点击加入粉丝团”后的点击位置和关闭详情页的逻辑。 + + +--- + + +
Tool use: **read_file** • Read file: douyin_fudai_core.py + +
+
+ +--- + + + +--- + + +搜索“加入粉丝团”相关代码: + + +--- + + +
+Tool use: **grep** • Grep for "加入粉丝团" in "douyin_fudai_core.py" • 17 matches + +Output mode: content + + +| File | Content | Line | +|------|------|------| +| `douyin_fudai_core.py` | `"加入粉丝团",` | L880 | +| `douyin_fudai_core.py` | `elif "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text:` | L1002 | +| `douyin_fudai_core.py` | `# 点击粉丝团按钮后,可能进入“加入粉丝团”独立页面:需要在该页再次点击“加入粉丝团”才能成功。` | L1048 | +| `douyin_fudai_core.py` | `# 在加入页点击底部"加入粉丝团"按钮(与详情页按钮同位置)` | L1068 | +| `douyin_fudai_core.py` | `"粉丝团加入页:点击加入粉丝团",` | L1071 | +| `douyin_fudai_core.py` | `# 点击加入粉丝团按钮` | L1077 | +| `douyin_fudai_core.py` | `# 按钮上部66%是红色区域(文字"加入粉丝团"所在),高度约132像素` | L1079 | +| `douyin_fudai_core.py` | `"恢复流程:第一次点击加入粉丝团按钮(基于截图优化坐标)",` | L1099 | +| `douyin_fudai_core.py` | `"恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)",` | L1114 | +| `douyin_fudai_core.py` | `"已启用自动加入粉丝团,等待加入流程完成",` | L1167 | +| `douyin_fudai_core.py` | `"未启用自动加入粉丝团,等待后返回",` | L1175 | +| `douyin_fudai_core.py` | `# 加入粉丝团成功后,点击 (527, 567) 返回直播间` | L1179 | +| `douyin_fudai_core.py` | `"加入粉丝团成功后,点击返回直播间",` | L1194 | +| `douyin_fudai_core.py` | `"点击加入粉丝团后重新诊断阶段",` | L1212 | +| `douyin_fudai_core.py` | `"恢复流程:再次第一次点击加入粉丝团按钮(基于截图优化坐标)",` | L1249 | +| `douyin_fudai_core.py` | `"恢复流程:再次第二次点击加入粉丝团按钮(基于截图优化坐标)",` | L1263 | +| `douyin_fudai_core.py` | `"点击加入粉丝团后显示在直播间(可能误判),尝试点击返回键",` | L1379 | + + +
+
+ +--- + + + +--- + + +查看相关代码段,重点关注加入粉丝团后的点击逻辑: + + +--- + + +
Tool use: **read_file** • Read file: douyin_fudai_core.py + +
+
+ +--- + + + +--- + + +搜索关闭详情页的相关代码: + + +--- + + +
+Tool use: **grep** • Grep for "关闭详情页|详情页|返回键" in "douyin_fudai_core.py" • 27 matches + +Output mode: content + + +| File | Content | Line | +|------|------|------| +| `douyin_fudai_core.py` | `# 设置标志:已经关闭了详情,避免后续再次点击返回键` | L917 | +| `douyin_fudai_core.py` | `# 活动结束:按一次返回键退出详情` | L929 | +| `douyin_fudai_core.py` | `"参与", "活动已结束:按返回键退出详情", result="activity_ended"` | L933 | +| `douyin_fudai_core.py` | `# 注意:点击参与按钮后会自动关闭详情页,返回直播间` | L991 | +| `douyin_fudai_core.py` | `"点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测",` | L999 | +| `douyin_fudai_core.py` | `# 需要粉丝团门槛:先点击参与按钮,再点击一次预设位置,最后关闭详情页` | L1003 | +| `douyin_fudai_core.py` | `# 第三步:关闭详情页` | L1038 | +| `douyin_fudai_core.py` | `analyser.click(500, 470) # 点击详情页旁边位置关闭详情页` | L1039 | +| `douyin_fudai_core.py` | `# 在加入页点击底部"加入粉丝团"按钮(与详情页按钮同位置)` | L1068 | +| `douyin_fudai_core.py` | `# 已经回到福袋详情页,说明加入成功` | L1365 | +| `douyin_fudai_core.py` | `"参与", "已回到福袋详情页,加入流程可能已完成"` | L1367 | +| `douyin_fudai_core.py` | `# 实际上可能还在加入成功的页面,需要点击返回键` | L1376 | +| `douyin_fudai_core.py` | `"点击加入粉丝团后显示在直播间(可能误判),尝试点击返回键",` | L1379 | +| `douyin_fudai_core.py` | `# 点击返回后再次诊断,看是否回到福袋详情页` | L1386 | +| `douyin_fudai_core.py` | `"参与", "点击返回后已回到福袋详情页"` | L1402 | +| `douyin_fudai_core.py` | `# 已经回到直播间/列表时:尝试重新打开福袋详情页` | L1444 | +| `douyin_fudai_core.py` | `"已离开福袋详情:尝试重新打开福袋详情页",` | L1448 | +| `douyin_fudai_core.py` | `# 尝试重新打开福袋详情页` | L1452 | +| `douyin_fudai_core.py` | `# 验证是否成功打开福袋详情页` | L1462 | +| `douyin_fudai_core.py` | `"重新打开福袋详情页成功",` | L1474 | +| `douyin_fudai_core.py` | `"重新打开福袋详情页后未在详情页",` | L1481 | +| `douyin_fudai_core.py` | `"参与", "重新打开福袋详情页失败", error=str(e)` | L1493 | +| `douyin_fudai_core.py` | `"参与", "粉丝团流程失败:仍在详情页,执行关闭", stage="FUDai_DETAIL"` | L1526 | +| `douyin_fudai_core.py` | `"参与", "粉丝团流程失败:已不在详情页,视为已退出", stage="UNKNOWN"` | L1535 | +| `douyin_fudai_core.py` | `# 丢弃时,尽量关闭详情,避免停留在详情页` | L2512 | +| `douyin_fudai_core.py` | `# 命中黑名单,不记录预约,直接关闭详情页并返回` | L2627 | +| `douyin_fudai_core.py` | `# 关闭详情页` | L2638 | + + +
+
+ +--- + + + +--- + + +查看关闭详情页的相关代码上下文: + + +--- + + +
Tool use: **read_file** • Read file: douyin_fudai_core.py + +
+
+ +--- + + + +--- + + +修改代码:将点击位置改为(545, 1995),并在点击后关闭详情页。 + + +--- + + +
Tool use: **read_file** • Read file: douyin_fudai_core.py + +
+
+ +--- + + + +--- + + +修改代码:将点击位置改为(545, 1995),并在点击后关闭详情页。 + + +--- + + + +
Tool use: **search_replace** • Edit file: douyin_fudai_core.py + +**Chunk 1** +Lines added: 1, lines removed: 1 + +```diff +@@ -1177,5 +1177,5 @@ + ) + +- # 加入粉丝团成功后,点击 (527, 567) 返回直播间 ++ # 加入粉丝团成功后,点击 (545, 1995) 然后关闭详情页 + try: + rx = int( +``` + +**Chunk 2** +Lines added: 12, lines removed: 7 + +```diff +@@ -1185,20 +1185,25 @@ + getattr(analyser, "resolution_ratio_y", 2400) or 2400 + ) +- return_x = int(527 * rx // 1080) +- return_y = int(567 * ry // 2400) ++ return_x = int(545 * rx // 1080) ++ return_y = int(1995 * ry // 2400) + analyser.operation.click( + analyser.device_id, return_x, return_y + ) + analyser._log_kv( + "参与", +- "加入粉丝团成功后,点击返回直播间", ++ "加入粉丝团成功后,点击指定位置", + x=return_x, + y=return_y, +- base_x=527, +- base_y=567, ++ base_x=545, ++ base_y=1995, + ) +- analyser.operation.delay(1.0) # 等待返回完成 ++ analyser.operation.delay(1.0) # 等待点击完成 ++ ++ # 关闭详情页 ++ analyser.click(500, 470) # 点击详情页旁边位置关闭详情页 ++ analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") ++ analyser.operation.delay(1.0) # 等待关闭完成 + except Exception as e: +- analyser._log_kv("参与", "点击返回直播间失败", error=str(e)) ++ analyser._log_kv("参与", "点击指定位置或关闭详情页失败", error=str(e)) + + # 重新诊断阶段,确认是否还在粉丝团加入页 +``` + +
+ +
+ +--- + + + +--- + + +检查是否有语法错误: + + +--- + + +
+ Tool use: **read_lints** • Read lints for 1 file + +Lint paths: + +- `douyin_fudai_core.py` + +Lint results + +Lint errors for `douyin_fudai_core.py` + + +| Message | Range | Severity | +|-------|-------|----------| +| 未存取“as_completed” | 8:52-8:64 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“normalize_countdown_text” | 10:26-10:50 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“h” | 114:13-114:14 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“_parse_mm_ss” | 88:9-88:21 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“_extract_2digits” | 97:9-97:25 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“_read_countdown_split” | 105:9-105:30 | DIAGNOSTIC_SEVERITY_HINT | +| 未存取“time_text” | 1926:5-1926:14 | DIAGNOSTIC_SEVERITY_HINT | +| "as_completed" 导入项未使用 | 8:52-8:64 | DIAGNOSTIC_SEVERITY_HINT | +| "normalize_countdown_text" 导入项未使用 | 10:26-10:50 | DIAGNOSTIC_SEVERITY_HINT | +| "_parse_mm_ss" 函数未使用 | 88:9-88:21 | DIAGNOSTIC_SEVERITY_HINT | +| "_extract_2digits" 函数未使用 | 97:9-97:25 | DIAGNOSTIC_SEVERITY_HINT | +| "_read_countdown_split" 函数未使用 | 105:9-105:30 | DIAGNOSTIC_SEVERITY_HINT | +| 变量 "h" 未使用 | 114:13-114:14 | DIAGNOSTIC_SEVERITY_HINT | +| 变量 "time_text" 未使用 | 1926:5-1926:14 | DIAGNOSTIC_SEVERITY_HINT | +| Trailing whitespace | 1201:1-1201:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Line too long (126/100) | 2569:1-2569:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Line too long (103/100) | 2913:1-2913:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Line too long (105/100) | 2930:1-2930:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Line too long (119/100) | 2965:1-2965:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Too many lines in module (3123/1000) | 1:1-1:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Missing module docstring | 1:1-1:1 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Too many local variables (21/15) | 15:1-15:42 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 81:12-81:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_screenshot_manager) | 27:9-27:41 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 79:20-79:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 73:17-73:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many local variables (54/15) | 85:1-85:22 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 94:16-94:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many local variables (21/15) | 105:5-105:30 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 211:16-211:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 136:20-136:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 195:20-195:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 193:28-193:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 185:25-185:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 208:24-208:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 201:21-201:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 219:20-219:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 213:17-213:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Unused variable 'h' | 114:13-114:14 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 401:12-401:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 409:16-409:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 404:13-404:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 425:16-425:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 432:16-432:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 439:16-439:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 446:16-446:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 453:16-453:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 512:12-512:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 481:20-481:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 476:17-476:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 492:24-492:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 487:21-487:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 497:24-497:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _is_watch_task_detected of a client class | 496:21-496:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 510:16-510:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 504:13-504:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 520:16-520:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 515:13-515:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 597:16-597:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 528:24-528:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 534:24-534:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 540:24-540:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 546:24-546:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 552:24-552:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 577:24-577:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 572:21-572:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 588:28-588:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 583:25-583:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 593:28-593:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _is_watch_task_detected of a client class | 592:25-592:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 605:20-605:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 600:17-600:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 619:20-619:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 616:32-616:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _is_watch_task_detected of a client class | 615:29-615:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 649:16-649:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 640:24-640:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 633:21-633:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 645:24-645:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _is_watch_task_detected of a client class | 644:21-644:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 676:16-676:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 667:24-667:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 662:21-662:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 672:24-672:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _is_watch_task_detected of a client class | 671:21-671:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 679:5-679:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 713:12-713:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 693:20-693:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _enter_live_ts of a client class | 692:50-692:73 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 696:13-696:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 704:20-704:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _enter_live_fudai_logged of a client class | 703:17-703:50 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 707:17-707:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 774:12-774:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 748:16-748:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 746:24-746:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 738:21-738:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 761:20-761:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 754:17-754:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 772:20-772:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 766:17-766:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 783:16-783:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 777:13-777:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 785:5-785:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 795:9-795:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many branches (52/12) | 85:1-85:22 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (327/50) | 85:1-85:22 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 809:12-809:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 821:16-821:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 815:13-815:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 848:12-848:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 835:24-835:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 829:21-829:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 845:16-845:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 840:13-840:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 856:16-856:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 851:13-851:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 887:9-887:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "elif" after "return", remove the leading "el" from "elif" | 888:9-1556:21 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _log_kv of a client class | 889:13-889:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 893:20-893:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _last_successful_attend_ts of a client class | 892:17-892:52 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 914:20-914:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _participated_fudai_future_ts of a client class | 907:21-907:59 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 908:21-908:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 920:20-920:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _detail_closed_by_attend of a client class | 919:17-919:50 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 924:13-924:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 935:20-935:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 932:17-932:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 940:20-940:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 943:24-943:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 948:13-948:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 950:13-950:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 953:13-953:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 955:13-955:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 958:13-958:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 960:13-960:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 966:13-966:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 980:13-980:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 994:20-994:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _skip_stage_diagnosis_and_find_fudai of a client class | 993:17-993:62 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 997:13-997:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1007:13-1007:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1035:20-1035:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1026:17-1026:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1036:17-1036:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1040:13-1040:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1043:17-1043:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many local variables (19/15) | 1049:13-1049:56 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 1057:28-1057:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _shot_and_diagnose of a client class | 1052:25-1052:52 | DIAGNOSTIC_SEVERITY_WARNING | +| Formatting a regular string which could be an f-string | 1054:29-1054:68 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 1061:28-1061:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _diagnose_stage_from_current_screen of a client class | 1060:36-1060:80 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1069:25-1069:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1147:32-1147:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1097:29-1097:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1112:29-1112:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1143:36-1143:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1134:33-1134:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1144:33-1144:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1151:36-1151:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1155:40-1155:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1165:29-1165:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1173:29-1173:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1206:32-1206:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1192:29-1192:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1204:29-1204:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1207:29-1207:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1438:32-1438:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _diagnose_stage_from_current_screen of a client class | 1213:33-1213:77 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1215:29-1215:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1227:37-1227:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1298:44-1298:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1252:41-1252:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1266:41-1266:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1291:48-1291:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1280:45-1280:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1292:45-1292:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1350:48-1350:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1343:52-1343:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1332:49-1332:65 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1344:49-1344:65 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1355:52-1355:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1359:37-1359:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1367:44-1367:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1371:33-1371:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1382:33-1382:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1423:40-1423:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1421:44-1421:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _diagnose_stage_from_current_screen of a client class | 1397:45-1397:89 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1399:41-1399:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "elif" after "return", remove the leading "el" from "elif" | 1405:41-1420:57 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _log_kv of a client class | 1406:45-1406:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1415:45-1415:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1428:33-1428:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1436:40-1436:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1440:29-1440:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1445:40-1445:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1451:25-1451:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1496:32-1496:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_flow_control) | 1460:29-1460:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 1490:40-1490:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _diagnose_stage_from_current_screen of a client class | 1474:41-1474:85 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 1476:37-1489:42 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _log_kv of a client class | 1477:41-1477:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1484:41-1484:57 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1491:37-1491:53 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1497:29-1497:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1504:21-1504:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1509:28-1509:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many return statements (8/6) | 1049:13-1049:56 | DIAGNOSTIC_SEVERITY_HINT | +| Too many branches (39/12) | 1049:13-1049:56 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (178/50) | 1049:13-1049:56 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _log_kv of a client class | 1516:17-1516:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1521:13-1521:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1527:20-1527:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1530:17-1530:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1535:24-1535:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1539:17-1539:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1546:20-1546:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1543:17-1543:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1551:13-1551:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1557:5-1557:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many return statements (10/6) | 861:1-861:21 | DIAGNOSTIC_SEVERITY_HINT | +| Too many branches (28/12) | 861:1-861:21 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (294/50) | 861:1-861:21 | DIAGNOSTIC_SEVERITY_HINT | +| Too many local variables (26/15) | 1561:1-1561:28 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _ocr_cache of a client class | 1569:21-1569:40 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1570:36-1570:55 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _shot_and_diagnose of a client class | 1579:9-1579:36 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1589:21-1589:40 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1590:36-1590:55 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache_ttl of a client class | 1591:32-1591:55 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1604:13-1604:32 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1615:9-1615:28 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1620:12-1620:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1629:12-1629:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1623:9-1623:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "elif" after "return", remove the leading "el" from "elif" | 1632:5-1714:25 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _ocr_cache of a client class | 1636:26-1636:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1637:42-1637:61 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache_ttl of a client class | 1638:37-1638:60 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1644:17-1644:36 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1650:13-1650:32 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1654:16-1654:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1663:16-1663:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1657:13-1657:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "elif" after "return", remove the leading "el" from "elif" | 1665:9-1668:21 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 1673:16-1673:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1672:13-1672:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1682:30-1682:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1683:46-1683:65 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache_ttl of a client class | 1684:41-1684:64 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _ocr_cache of a client class | 1693:17-1693:36 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1700:20-1700:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1710:20-1710:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1703:17-1703:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many branches (29/12) | 1561:1-1561:28 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (92/50) | 1561:1-1561:28 | DIAGNOSTIC_SEVERITY_HINT | +| Access to a protected member _shot_and_diagnose of a client class | 1720:5-1720:32 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1730:16-1730:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1725:13-1725:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _shot_and_diagnose of a client class | 1738:5-1738:32 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1748:16-1748:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1743:13-1743:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1759:12-1759:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1758:9-1758:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1767:12-1767:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1766:9-1766:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1774:12-1774:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1773:9-1773:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1786:16-1786:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1785:13-1785:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1792:12-1792:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1791:9-1791:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1799:16-1799:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1798:13-1798:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1809:16-1809:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1803:13-1803:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1815:16-1815:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1814:13-1814:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1823:16-1823:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1822:13-1822:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1830:12-1830:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1829:9-1829:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many branches (13/12) | 1754:1-1754:15 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (64/50) | 1754:1-1754:15 | DIAGNOSTIC_SEVERITY_HINT | +| Redefining name 're' from outer scope (line 3) | 1849:9-1849:18 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1876:12-1876:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Reimport 're' (imported line 3) | 1849:9-1849:18 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (re) | 1849:9-1849:18 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Too many local variables (21/15) | 1880:1-1880:32 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 1890:12-1890:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1899:16-1899:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1894:13-1894:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1917:16-1917:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1911:13-1911:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 1920:9-1920:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1929:12-1929:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1933:12-1933:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1937:12-1937:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1974:12-1974:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1956:20-1956:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "剩余秒数" contains a non-ASCII character, consider renaming it. | 1954:21-1954:48 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 1949:17-1949:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1972:20-1972:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "cd_end类型" contains a non-ASCII character, consider renaming it. | 1965:21-1965:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "cd_end大于now" contains a non-ASCII character, consider renaming it. | 1966:21-1970:22 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 1960:17-1960:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1983:16-1983:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "异常" contains a non-ASCII character, consider renaming it. | 1980:17-1980:30 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "异常类型" contains a non-ASCII character, consider renaming it. | 1981:17-1981:46 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 1977:13-1977:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1989:12-1989:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1993:12-1993:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 1997:12-1997:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2002:12-2002:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2007:12-2007:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2026:12-2026:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "配置_最小价值" contains a non-ASCII character, consider renaming it. | 2015:13-2015:42 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置_最小参与人数" contains a non-ASCII character, consider renaming it. | 2016:13-2016:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置_最大参与人数" contains a non-ASCII character, consider renaming it. | 2017:13-2017:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置_倒计时大于秒数" contains a non-ASCII character, consider renaming it. | 2018:13-2018:52 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置_倒计时小于秒数" contains a non-ASCII character, consider renaming it. | 2019:13-2019:52 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际_价值" contains a non-ASCII character, consider renaming it. | 2020:13-2020:43 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际_参与人数" contains a non-ASCII character, consider renaming it. | 2021:13-2021:45 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际_份数" contains a non-ASCII character, consider renaming it. | 2022:13-2022:33 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际_剩余秒数" contains a non-ASCII character, consider renaming it. | 2023:13-2023:92 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际_内容" contains a non-ASCII character, consider renaming it. | 2024:13-2024:58 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2012:9-2012:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 2032:13-2053:25 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2041:24-2041:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2037:25-2037:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际价值" contains a non-ASCII character, consider renaming it. | 2038:25-2038:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最小价值" contains a non-ASCII character, consider renaming it. | 2039:25-2039:53 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2034:21-2034:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2052:24-2052:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际价值" contains a non-ASCII character, consider renaming it. | 2049:25-2049:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最小价值" contains a non-ASCII character, consider renaming it. | 2050:25-2050:53 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2046:21-2046:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2061:20-2061:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际价值" contains a non-ASCII character, consider renaming it. | 2059:21-2059:50 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2056:17-2056:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 2067:13-2088:25 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2076:24-2076:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2072:25-2072:69 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际参与人数" contains a non-ASCII character, consider renaming it. | 2073:25-2073:56 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最小参与人数" contains a non-ASCII character, consider renaming it. | 2074:25-2074:66 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2069:21-2069:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2087:24-2087:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际参与人数" contains a non-ASCII character, consider renaming it. | 2084:25-2084:56 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最小参与人数" contains a non-ASCII character, consider renaming it. | 2085:25-2085:66 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2081:21-2081:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2096:20-2096:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际参与人数" contains a non-ASCII character, consider renaming it. | 2094:21-2094:52 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2091:17-2091:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 2101:13-2122:25 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2110:24-2110:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2106:25-2106:69 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际参与人数" contains a non-ASCII character, consider renaming it. | 2107:25-2107:56 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最大参与人数" contains a non-ASCII character, consider renaming it. | 2108:25-2108:66 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2103:21-2103:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2121:24-2121:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际参与人数" contains a non-ASCII character, consider renaming it. | 2118:25-2118:56 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置最大参与人数" contains a non-ASCII character, consider renaming it. | 2119:25-2119:66 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2115:21-2115:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2138:24-2138:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2133:25-2133:60 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际剩余秒数" contains a non-ASCII character, consider renaming it. | 2134:25-2134:63 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置阈值秒数" contains a non-ASCII character, consider renaming it. | 2135:25-2135:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "判断条件" contains a non-ASCII character, consider renaming it. | 2136:25-2136:79 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2130:21-2130:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2156:16-2156:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "配置阈值秒数" contains a non-ASCII character, consider renaming it. | 2149:17-2149:46 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际剩余秒数" contains a non-ASCII character, consider renaming it. | 2150:17-2152:18 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "是否有倒计时数据" contains a non-ASCII character, consider renaming it. | 2153:17-2153:68 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "说明" contains a non-ASCII character, consider renaming it. | 2154:17-2154:104 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2146:13-2146:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 2161:13-2191:25 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2172:24-2172:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2166:25-2166:60 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "实际剩余秒数" contains a non-ASCII character, consider renaming it. | 2167:25-2167:63 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置阈值秒数" contains a non-ASCII character, consider renaming it. | 2168:25-2168:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "判断条件" contains a non-ASCII character, consider renaming it. | 2169:25-2169:79 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "说明" contains a non-ASCII character, consider renaming it. | 2170:25-2170:105 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2163:21-2163:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2175:17-2175:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2190:24-2190:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "实际剩余秒数" contains a non-ASCII character, consider renaming it. | 2186:25-2186:63 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "配置阈值秒数" contains a non-ASCII character, consider renaming it. | 2187:25-2187:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "判断条件" contains a non-ASCII character, consider renaming it. | 2188:25-2188:80 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2183:21-2183:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2202:20-2202:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "剩余秒数" contains a non-ASCII character, consider renaming it. | 2197:21-2197:48 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2194:17-2194:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2211:16-2211:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "配置阈值秒数" contains a non-ASCII character, consider renaming it. | 2209:17-2209:46 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2206:13-2206:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "else" after "return", remove the "else" and de-indent the code inside it | 2216:5-2241:17 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2224:16-2224:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "原因" contains a non-ASCII character, consider renaming it. | 2221:17-2221:44 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Argument name "内容" contains a non-ASCII character, consider renaming it. | 2222:17-2222:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2218:13-2218:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2227:9-2227:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2240:16-2240:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Argument name "内容" contains a non-ASCII character, consider renaming it. | 2238:17-2238:55 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _log_kv of a client class | 2235:13-2235:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2253:12-2253:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2244:9-2244:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2256:5-2256:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many return statements (10/6) | 1880:1-1880:32 | DIAGNOSTIC_SEVERITY_HINT | +| Too many branches (64/12) | 1880:1-1880:32 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (182/50) | 1880:1-1880:32 | DIAGNOSTIC_SEVERITY_HINT | +| Unused variable 'time_text' | 1926:5-1926:14 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many local variables (48/15) | 2264:1-2264:24 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2282:12-2282:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2318:12-2318:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Unnecessary "elif" after "return", remove the leading "el" from "elif" | 2288:9-2317:25 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2294:20-2294:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2290:17-2290:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2297:13-2297:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2309:20-2309:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2305:17-2305:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2312:13-2312:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2345:12-2345:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_fudai_detail) | 2324:9-2324:49 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 2336:20-2336:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2329:17-2329:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2339:13-2339:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2357:16-2357:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2351:13-2351:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2360:9-2360:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2370:12-2370:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2378:16-2378:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2374:13-2374:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2382:9-2382:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2393:12-2393:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2400:12-2400:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2408:16-2408:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2434:16-2434:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2430:28-2430:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2424:25-2424:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2460:20-2460:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Simplify chained comparison between the operands | 2458:20-2458:54 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2468:16-2468:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2483:20-2483:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2474:17-2474:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2502:20-2502:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2491:17-2491:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2515:16-2515:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2510:13-2510:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2520:16-2520:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2523:20-2523:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2529:16-2529:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2526:13-2526:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2535:16-2535:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2542:20-2542:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2539:17-2539:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2562:20-2562:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2553:28-2553:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2582:20-2582:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Simplify chained comparison between the operands | 2580:20-2580:54 | DIAGNOSTIC_SEVERITY_HINT | +| Catching too general exception Exception | 2591:16-2591:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2605:20-2605:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2597:17-2597:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2622:20-2622:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2612:17-2612:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2713:20-2713:29 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2641:28-2641:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2634:25-2634:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2646:28-2646:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2649:32-2649:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2657:28-2657:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2652:25-2652:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2662:28-2662:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2671:32-2671:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2666:29-2666:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2702:32-2702:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2688:40-2688:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2707:21-2707:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2722:24-2722:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2716:21-2716:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3100:24-3100:33 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2734:28-2734:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2743:32-2743:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2755:32-2755:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Reimport 'douyin_reservation_logic' (imported line 11) | 2748:29-2748:74 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_reservation_logic) | 2748:29-2748:74 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 2761:28-2761:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2803:28-2803:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2786:32-2786:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_fudai_detail) | 2772:29-2772:69 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 2784:36-2784:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2794:36-2794:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2788:33-2788:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Redefining name 'os' from outer scope (line 5) | 2812:29-2812:38 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2897:32-2897:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Reimport 'os' (imported line 5) | 2812:29-2812:38 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (os) | 2812:29-2812:38 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Import outside toplevel (json) | 2813:29-2813:40 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Import outside toplevel (datetime.datetime) | 2814:29-2814:58 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Catching too general exception Exception | 2834:40-2834:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2844:40-2844:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2895:36-2895:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2889:33-2889:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2905:36-2905:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2899:33-2899:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2923:28-2923:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Import outside toplevel (douyin_high_value_room) | 2910:25-2910:54 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Access to a protected member _sort_reservations_inplace of a client class | 2965:60-2965:89 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2979:32-2979:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2993:28-2993:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 2983:25-2983:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 2999:28-2999:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3002:32-3002:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3010:28-3010:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3005:25-3005:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3017:28-3017:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3038:28-3038:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3036:36-3036:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3030:33-3030:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3048:32-3048:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3043:29-3043:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3079:32-3079:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3065:40-3065:49 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3090:32-3090:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3085:29-3085:45 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3094:21-3094:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3107:28-3107:37 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3103:25-3103:41 | DIAGNOSTIC_SEVERITY_WARNING | +| Catching too general exception Exception | 3113:12-3113:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3112:9-3112:25 | DIAGNOSTIC_SEVERITY_WARNING | +| Access to a protected member _log_kv of a client class | 3117:5-3117:21 | DIAGNOSTIC_SEVERITY_WARNING | +| Too many return statements (10/6) | 2264:1-2264:24 | DIAGNOSTIC_SEVERITY_HINT | +| Too many branches (104/12) | 2264:1-2264:24 | DIAGNOSTIC_SEVERITY_HINT | +| Too many statements (398/50) | 2264:1-2264:24 | DIAGNOSTIC_SEVERITY_HINT | +| standard import "concurrent.futures.ThreadPoolExecutor" should be placed before third party import "PIL.Image" | 8:1-8:64 | DIAGNOSTIC_SEVERITY_INFORMATION | +| Unused as_completed imported from concurrent.futures | 8:1-8:64 | DIAGNOSTIC_SEVERITY_WARNING | +| Unused normalize_countdown_text imported from douyin_utils | 10:1-10:76 | DIAGNOSTIC_SEVERITY_WARNING | + + +
+
+ +--- + + + +--- + + +这些是代码风格警告,不是语法错误。验证修改后的代码: + + +--- + + +
Tool use: **read_file** • Read file: douyin_fudai_core.py + +
+
+ +--- + + + +--- + + +修改完成。已更新代码: + +1. **点击位置**:从 `(527, 567)` 改为 `(545, 1995)` +2. **关闭详情页**:在点击后添加关闭详情页的逻辑(点击 `(500, 470)` 位置) + +修改后的流程: +- 加入粉丝团成功后,点击 `(545, 1995)` +- 等待 1 秒 +- 点击 `(500, 470)` 关闭详情页 +- 等待 1 秒 + +代码已更新,可以正常使用。 + +--- + diff --git a/CLEANUP_REPORT.md b/CLEANUP_REPORT.md index 86d6ae9..b64e7ed 100644 --- a/CLEANUP_REPORT.md +++ b/CLEANUP_REPORT.md @@ -173,5 +173,6 @@ python cleanup_unused_files.py + diff --git a/CODE_REVIEW_FIXES.md b/CODE_REVIEW_FIXES.md index ad33ef8..e9f1708 100644 --- a/CODE_REVIEW_FIXES.md +++ b/CODE_REVIEW_FIXES.md @@ -184,5 +184,6 @@ except Exception as e: + diff --git a/CODE_REVIEW_REPORT.md b/CODE_REVIEW_REPORT.md index e98f7bd..906806e 100644 --- a/CODE_REVIEW_REPORT.md +++ b/CODE_REVIEW_REPORT.md @@ -387,5 +387,6 @@ self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标 + diff --git a/DEBUG_IMAGE_SYSTEM.md b/DEBUG_IMAGE_SYSTEM.md index 9ac5d6f..ca24b45 100644 --- a/DEBUG_IMAGE_SYSTEM.md +++ b/DEBUG_IMAGE_SYSTEM.md @@ -271,5 +271,6 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png + diff --git a/DEPENDENCY_FIXES_REPORT.md b/DEPENDENCY_FIXES_REPORT.md index 41d1aa1..95d17f2 100644 --- a/DEPENDENCY_FIXES_REPORT.md +++ b/DEPENDENCY_FIXES_REPORT.md @@ -242,5 +242,6 @@ python check_dependencies.py + diff --git a/DEPENDENCY_GUIDE.md b/DEPENDENCY_GUIDE.md index 43d2d67..75aa50e 100644 --- a/DEPENDENCY_GUIDE.md +++ b/DEPENDENCY_GUIDE.md @@ -221,5 +221,6 @@ douyin_guaji + diff --git a/FIXES_REPORT.md b/FIXES_REPORT.md index c66ed56..758b5df 100644 --- a/FIXES_REPORT.md +++ b/FIXES_REPORT.md @@ -162,5 +162,6 @@ + diff --git a/FUDAI_FINDER_OPTIMIZATION.md b/FUDAI_FINDER_OPTIMIZATION.md index 593bafb..d8bd766 100644 --- a/FUDAI_FINDER_OPTIMIZATION.md +++ b/FUDAI_FINDER_OPTIMIZATION.md @@ -374,5 +374,6 @@ douyin_fudai_finder.py + diff --git a/OCR性能分析报告.md b/OCR性能分析报告.md index 5d4753a..eee60f9 100644 --- a/OCR性能分析报告.md +++ b/OCR性能分析报告.md @@ -173,5 +173,6 @@ self.ocr = easyocr.Reader( + diff --git a/WPS流程图说明.md b/WPS流程图说明.md index c8e2efe..55781e7 100644 --- a/WPS流程图说明.md +++ b/WPS流程图说明.md @@ -132,5 +132,6 @@ python 生成WPS流程图.py + diff --git a/check_dependencies.py b/check_dependencies.py index a873fba..20167bb 100644 --- a/check_dependencies.py +++ b/check_dependencies.py @@ -146,5 +146,6 @@ else: + diff --git a/config.json b/config.json index ebaeb3d..b2b8690 100644 --- a/config.json +++ b/config.json @@ -95,6 +95,7 @@ } }, "debug_captures": { + "enabled": false, "keep_days": 3, "max_files": 2000, "auto_cleanup": true diff --git a/douyin_fudai_core.py b/douyin_fudai_core.py index 2650333..342745f 100644 --- a/douyin_fudai_core.py +++ b/douyin_fudai_core.py @@ -1176,7 +1176,7 @@ def attend_choujiang(analyser) -> bool: wait_seconds=3.0, ) - # 加入粉丝团成功后,点击 (527, 567) 返回直播间 + # 加入粉丝团成功后,点击 (545, 1995) 然后关闭详情页 try: rx = int( getattr(analyser, "resolution_ratio_x", 1080) or 1080 @@ -1184,22 +1184,29 @@ def attend_choujiang(analyser) -> bool: ry = int( getattr(analyser, "resolution_ratio_y", 2400) or 2400 ) - return_x = int(527 * rx // 1080) - return_y = int(567 * ry // 2400) + return_x = int(545 * rx // 1080) + return_y = int(1995 * ry // 2400) analyser.operation.click( analyser.device_id, return_x, return_y ) analyser._log_kv( "参与", - "加入粉丝团成功后,点击返回直播间", + "加入粉丝团成功后,点击指定位置", x=return_x, y=return_y, - base_x=527, - base_y=567, + base_x=545, + base_y=1995, ) - analyser.operation.delay(1.0) # 等待返回完成 + analyser.operation.delay(1.0) # 等待点击完成 + + # 关闭详情页 + analyser.click(500, 470) # 点击详情页旁边位置关闭详情页 + analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") + analyser.operation.delay(1.0) # 等待关闭完成 except Exception as e: - analyser._log_kv("参与", "点击返回直播间失败", error=str(e)) + analyser._log_kv( + "参与", "点击指定位置或关闭详情页失败", error=str(e) + ) # 重新诊断阶段,确认是否还在粉丝团加入页 try: @@ -2737,6 +2744,18 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool: analyser.reservations = reservations # type: ignore[attr-defined] except Exception: pass + else: + # 在已有预约队列的情况下,先立即清理已过期的预约,保证队列始终是“未过期”的 + try: + import douyin_reservation_logic as rl_cleanup + + rl_cleanup.cleanup_expired_reservations( + analyser, + reservations, + write_state_callback=None, + ) + except Exception: + pass # room_pos:当前直播间位置计数 try: diff --git a/douyin_screenshot_manager.py b/douyin_screenshot_manager.py index 0876422..8694642 100644 --- a/douyin_screenshot_manager.py +++ b/douyin_screenshot_manager.py @@ -572,6 +572,23 @@ def save_debug_image( 保存的文件路径,失败返回None """ try: + # 从配置读取是否启用调试图像保存;默认关闭 + try: + import json + enabled = False + config_path = path_config.get_config_path() + if os.path.exists(config_path): + with open(config_path, "r", encoding="utf-8") as f: + config = json.load(f) + dbg_cfg = config.get("debug_captures") + if isinstance(dbg_cfg, dict): + enabled = bool(dbg_cfg.get("enabled", False)) + if not enabled: + return None + except Exception: + # 配置读取异常时,为安全起见直接跳过保存调试图像 + return None + # 自动清理旧目录(仅在每天第一次保存时执行) if auto_cleanup: try: diff --git a/douyin_text_utils.py b/douyin_text_utils.py index 30c4dca..7450828 100644 --- a/douyin_text_utils.py +++ b/douyin_text_utils.py @@ -146,5 +146,6 @@ def extract_participants_count(text: Optional[str]) -> int: + diff --git a/gui_app.py b/gui_app.py index e2ce3eb..fda3a20 100644 --- a/gui_app.py +++ b/gui_app.py @@ -507,6 +507,14 @@ def main(): value=float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25) ) + # 调试图像开关 & 清理相关变量 + debug_captures_enabled_var = tk.BooleanVar( + value=bool( + cfg.get("debug_captures", {}).get("enabled", False) + if isinstance(cfg.get("debug_captures"), dict) + else False + ) + ) # 调试图像清理相关变量 debug_captures_auto_cleanup_var = tk.BooleanVar( value=bool( @@ -878,37 +886,48 @@ def main(): debug_tab = ttk.Frame(left_notebook) left_notebook.add(debug_tab, text="调试参数") - # 调试图像清理 - debug_captures_box = ttk.LabelFrame(debug_tab, text="调试图像清理") + # 调试图像 + debug_captures_box = ttk.LabelFrame(debug_tab, text="调试图像") debug_captures_box.pack(fill=X, padx=10, pady=(10, 10)) debug_r0 = ttk.Frame(debug_captures_box) debug_r0.pack(fill=X, padx=10, pady=(10, 8)) ttk.Checkbutton( - debug_r0, text="启用自动清理调试图像", variable=debug_captures_auto_cleanup_var + debug_r0, + text="保存调试图像(OCR / 像素 / 模板等)", + variable=debug_captures_enabled_var, ).pack(side=LEFT) - debug_r1 = ttk.Frame(debug_captures_box) - debug_r1.pack(fill=X, padx=10, pady=(0, 8)) - ttk.Label(debug_r1, text="保留天数:").pack(side=LEFT) + debug_cleanup_box = ttk.LabelFrame(debug_tab, text="调试图像清理") + debug_cleanup_box.pack(fill=X, padx=10, pady=(0, 10)) + + debug_r1 = ttk.Frame(debug_cleanup_box) + debug_r1.pack(fill=X, padx=10, pady=(10, 8)) + ttk.Checkbutton( + debug_r1, text="启用自动清理调试图像", variable=debug_captures_auto_cleanup_var + ).pack(side=LEFT) + + debug_r2 = ttk.Frame(debug_cleanup_box) + debug_r2.pack(fill=X, padx=10, pady=(0, 8)) + ttk.Label(debug_r2, text="保留天数:").pack(side=LEFT) ttk.Spinbox( - debug_r1, + debug_r2, from_=1, to=30, increment=1, textvariable=debug_captures_keep_days_var, width=6, ).pack(side=LEFT) - ttk.Label(debug_r1, text="最大文件数量:").pack(side=LEFT, padx=(20, 0)) + ttk.Label(debug_r2, text="最大文件数量:").pack(side=LEFT, padx=(20, 0)) ttk.Spinbox( - debug_r1, + debug_r2, from_=100, to=10000, increment=100, textvariable=debug_captures_max_files_var, width=8, ).pack(side=LEFT) - ttk.Label(debug_r1, text="(超过此数量自动清理)").pack(side=LEFT, padx=(6, 0)) + ttk.Label(debug_r2, text="(超过此数量自动清理)").pack(side=LEFT, padx=(6, 0)) # 找福袋参数 fudai_find_box = ttk.LabelFrame(debug_tab, text="找福袋参数") @@ -1248,6 +1267,9 @@ def main(): # 调试图像清理配置 debug_captures_config = cfg.get("debug_captures", {}) if isinstance(debug_captures_config, dict): + debug_captures_enabled_var.set( + bool(debug_captures_config.get("enabled", False)) + ) debug_captures_auto_cleanup_var.set( bool(debug_captures_config.get("auto_cleanup", True)) ) @@ -1437,6 +1459,9 @@ def main(): # 调试图像清理配置 if "debug_captures" not in cfg2 or not isinstance(cfg2["debug_captures"], dict): cfg2["debug_captures"] = {} + cfg2["debug_captures"]["enabled"] = bool( + debug_captures_enabled_var.get() + ) cfg2["debug_captures"]["auto_cleanup"] = bool( debug_captures_auto_cleanup_var.get() ) @@ -2732,9 +2757,81 @@ def main(): with open(path, "r", encoding="utf-8") as f: data = json.load(f) reservation_text.delete("1.0", "end") - reservation_text.insert( - "1.0", json.dumps(data, ensure_ascii=False, indent=2) - ) + + from datetime import datetime + updated_ts = float(data.get("updated_ts", 0.0) or 0.0) if isinstance(data, dict) else 0.0 + room_pos = int(data.get("room_pos", 0) or 0) if isinstance(data, dict) else 0 + reason = str(data.get("reason", "") or "") if isinstance(data, dict) else "" + current_title = str(data.get("current_room_title", "") or "") if isinstance(data, dict) else "" + current_title_raw = str(data.get("current_room_title_raw", "") or "") if isinstance(data, dict) else "" + reservations = data.get("reservations", []) if isinstance(data, dict) else [] + + # 基本信息(中文) + lines = [] + lines.append("=== 预约队列总览 ===") + if updated_ts > 0: + try: + updated_str = datetime.fromtimestamp(updated_ts).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + updated_str = str(updated_ts) + else: + updated_str = "-" + lines.append(f"更新时间:{updated_str}") + lines.append(f"当前直播间位置:{room_pos}") + lines.append(f"当前直播间(清洗后):{current_title or '-'}") + lines.append(f"当前直播间原文:{current_title_raw or '-'}") + lines.append(f"预约总数量:{len(reservations)}") + if reason: + lines.append(f"最近更新原因:{reason}") + lines.append("") + + if not reservations: + lines.append("暂无预约记录。") + else: + lines.append("=== 预约明细列表(按预计开奖时间排序) ===") + now_ts = datetime.now().timestamp() + for idx, item in enumerate(reservations, start=1): + try: + val = float(item.get("prize_value_yuan") or 0.0) + except Exception: + val = 0.0 + content = str(item.get("content") or "") + ft = float(item.get("future_ts") or 0.0) + ft_str = str(item.get("future_str") or "") + pos_seen = int(item.get("pos_seen") or 0) + room_title = str(item.get("room_title") or "") + room_title_raw = str(item.get("room_title_raw") or "") + created_ts = float(item.get("created_ts") or 0.0) + + # 计算剩余时间 + remain_sec = max(0, int(ft - now_ts)) if ft > 0 else 0 + if remain_sec > 0: + remain_str = f"{remain_sec // 60}分{remain_sec % 60}秒后开奖" + elif ft > 0: + remain_str = "已到开奖时间" + else: + remain_str = "未知(future_ts 无效)" + + # 记录时间 + if created_ts > 0: + try: + created_str = datetime.fromtimestamp(created_ts).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + created_str = str(created_ts) + else: + created_str = "-" + + lines.append(f"[#{idx}] 价值:{val:.2f} 元") + lines.append(f" 奖品内容:{content}") + lines.append(f" 预计开奖时间:{ft_str or '-'}") + lines.append(f" 剩余时间:{remain_str}") + lines.append(f" 发现时直播间位置:{pos_seen}") + lines.append(f" 直播间(清洗后):{room_title or '-'}") + lines.append(f" 直播间原文:{room_title_raw or '-'}") + lines.append(f" 记录时间:{created_str}") + lines.append("-" * 40) + + reservation_text.insert("1.0", "\n".join(lines)) else: reservation_text.delete("1.0", "end") reservation_text.insert("1.0", "暂无预约队列数据") diff --git a/requirements-minimal.txt b/requirements-minimal.txt index 2d0a9d1..1781ea2 100644 --- a/requirements-minimal.txt +++ b/requirements-minimal.txt @@ -103,5 +103,6 @@ paddlepaddle>=2.5.0,<3.0.0 + diff --git a/requirements-test.txt b/requirements-test.txt index 677f4bb..50d4c13 100644 --- a/requirements-test.txt +++ b/requirements-test.txt @@ -80,5 +80,6 @@ types-requests>=2.31.0 + diff --git a/requirements.txt b/requirements.txt index 58ea8dd..7c8a7bb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -119,5 +119,6 @@ ttkbootstrap>=1.10.0 + diff --git a/run_tests.py b/run_tests.py index e08e51e..0c6e40f 100644 --- a/run_tests.py +++ b/run_tests.py @@ -156,5 +156,6 @@ if __name__ == "__main__": + diff --git a/state/reservations.json b/state/reservations.json index a21e2a1..0f816b9 100644 --- a/state/reservations.json +++ b/state/reservations.json @@ -1,29 +1,29 @@ { - "updated_ts": 1766731949.3357337, - "reason": "process_reservation", - "room_pos": 0, - "current_room_title": "颜妍记", - "current_room_title_raw": "颜妍记.", + "updated_ts": 1766732837.525079, + "reason": "record_reservation", + "room_pos": 2, + "current_room_title": "颜妍A记", + "current_room_title_raw": "颜妍A记。", "reservations": [ { "prize_value_yuan": 1199.0, - "content": "58后开奖04(叨叨专属』创维智能影音娱乐平板", - "future_ts": 1766732049.327057, - "future_str": "2025-12-26 14:54:09", + "content": "24后开奖09(叨叨专属』创维智能影音娱乐平板", + "future_ts": 1766733347.956477, + "future_str": "2025-12-26 15:15:47", "pos_seen": 0, "room_title": "米叨叨", "room_title_raw": "米叨叨", - "created_ts": 1766731753.97193 + "created_ts": 1766732786.4327316 }, { "prize_value_yuan": 1699.0, - "content": "36后开奖11(颜研专属1全新智能大屏追剧安卓国产颜色随机", - "future_ts": 1766732498.232999, - "future_str": "2025-12-26 15:01:38", + "content": "24后开奖09(颜研专属1全新智能大屏追剧安卓国产颜色随机", + "future_ts": 1766733398.865224, + "future_str": "2025-12-26 15:16:38", "pos_seen": 2, - "room_title": "颜妍记", - "room_title_raw": "颜妍记.", - "created_ts": 1766731804.78279 + "room_title": "颜妍A记", + "room_title_raw": "颜妍A记。", + "created_ts": 1766732837.5240233 } ] } \ No newline at end of file diff --git a/test_log_final.py b/test_log_final.py index e8d57e1..f04b38e 100644 --- a/test_log_final.py +++ b/test_log_final.py @@ -79,5 +79,6 @@ if os.path.exists(log_file): + diff --git a/test_log_final_check.py b/test_log_final_check.py index d1af465..927e3ad 100644 --- a/test_log_final_check.py +++ b/test_log_final_check.py @@ -92,5 +92,6 @@ if os.path.exists(log_file): + diff --git a/tests/README.md b/tests/README.md index 88727e4..c06da8d 100644 --- a/tests/README.md +++ b/tests/README.md @@ -225,5 +225,6 @@ pytest --pdb --pdbcls=IPython.terminal.debugger:Pdb + diff --git a/tests/__init__.py b/tests/__init__.py index 1388fbc..1578f10 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -62,5 +62,6 @@ __version__ = "1.0.0" + diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py index 5edb719..2aaa1ac 100644 --- a/tests/integration/__init__.py +++ b/tests/integration/__init__.py @@ -51,5 +51,6 @@ + diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py index 2e30c76..f8512ac 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -51,5 +51,6 @@ + diff --git a/webui/app.js b/webui/app.js index 760b567..cbfbcea 100644 --- a/webui/app.js +++ b/webui/app.js @@ -57,6 +57,7 @@ const DEFAULTS = { fudai_quiet_end_hour: 7, // 调试相关 + "debug_captures.enabled": false, "debug_captures.auto_cleanup": true, "debug_captures.keep_days": 7, "debug_captures.max_files": 2000, @@ -804,16 +805,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).toLocaleTimeString() : '-'}
-
原因:${escapeHtml(reason || '-') }
+
预约总数量:${reservations.length}
+
更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleString() : '-'}
+
最近更新原因:${escapeHtml(reason || '-') }
`; container.appendChild(info); @@ -825,7 +826,7 @@ async function pollReservations() { return; } - // 显示预约列表 + // 显示预约列表(更详细中文) const list = document.createElement("div"); list.className = "reservationsList"; @@ -836,20 +837,31 @@ 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 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); + } + } 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); diff --git a/webui/index.html b/webui/index.html index 0d1672e..81b0fea 100644 --- a/webui/index.html +++ b/webui/index.html @@ -644,6 +644,16 @@ 调试参数 +
调试图像
+
+ + +
关闭后不再保存调试截图,可显著减少磁盘占用和略微提升速度
+
+
调试图像清理
diff --git a/核显GPU加速说明.md b/核显GPU加速说明.md index ea2a82e..d4d843e 100644 --- a/核显GPU加速说明.md +++ b/核显GPU加速说明.md @@ -141,5 +141,6 @@ python check_gpu_available.py + diff --git a/流程图_WPS文本格式.txt b/流程图_WPS文本格式.txt index 5fef307..238641a 100644 --- a/流程图_WPS文本格式.txt +++ b/流程图_WPS文本格式.txt @@ -147,5 +147,6 @@ + diff --git a/生成WPS流程图.py b/生成WPS流程图.py index fdfa766..4275baf 100644 --- a/生成WPS流程图.py +++ b/生成WPS流程图.py @@ -219,5 +219,6 @@ if __name__ == "__main__": + diff --git a/统一截图和分数记录说明.md b/统一截图和分数记录说明.md index 55c6cbb..e1a0fc6 100644 --- a/统一截图和分数记录说明.md +++ b/统一截图和分数记录说明.md @@ -149,3 +149,4 @@ +