", on_click)
+
+ print(f"\n交互窗口已打开,你可以:")
+ print(f" - 移动鼠标查看坐标")
+ print(f" - 点击鼠标记录坐标")
+ print(f" - 关闭窗口退出")
+
+ root.mainloop()
+ except ImportError:
+ print("\n提示: 安装 tkinter 可以启用交互模式")
+ print(" Windows通常自带,如果缺失可以安装 python-tk 包")
+
+ except Exception as e:
+ print(f"打开图片失败: {e}")
+
+if __name__ == "__main__":
+ # 默认查看 screenshot.png
+ base_dir = os.path.dirname(os.path.abspath(__file__))
+ screenshot_path = os.path.join(base_dir, 'pic', 'screenshot.png')
+
+ if len(sys.argv) > 1 and sys.argv[1] != 'interactive':
+ # 如果提供了文件路径
+ image_path = sys.argv[1]
+ else:
+ image_path = screenshot_path
+
+ show_image_coordinates(image_path)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tools/legacy/check_indent.py b/tools/legacy/check_indent.py
new file mode 100644
index 0000000..e5bd867
--- /dev/null
+++ b/tools/legacy/check_indent.py
@@ -0,0 +1,37 @@
+import re
+
+with open('douyin_fudai.py', 'r', encoding='utf-8') as f:
+ content = f.read()
+ lines = content.split('\n')
+
+# 查找所有可能的缩进问题模式
+problems = []
+for i in range(len(lines)-1):
+ line = lines[i]
+ next_line = lines[i+1] if i+1 < len(lines) else ''
+
+ stripped = line.rstrip()
+ next_stripped = next_line.rstrip()
+
+ if not stripped or not next_stripped:
+ continue
+
+ # 当前行缩进
+ indent = len(line) - len(line.lstrip())
+ next_indent = len(next_line) - len(next_line.lstrip())
+
+ # 如果当前行是控制语句(以冒号结尾)
+ if stripped.endswith(':'):
+ next_content = next_stripped.lstrip()
+ # 下一行不是 else/elif/except/finally,且缩进不正确
+ if next_content and not next_content.startswith(('else:', 'elif ', 'except', 'finally:')):
+ if next_indent <= indent:
+ problems.append((i+2, indent, next_indent, stripped[-80:], next_stripped[:80]))
+
+print(f'Found {len(problems)} potential indentation problems:')
+for p in problems[:50]:
+ print(f'Line {p[0]}: expected indent > {p[1]}, got {p[2]}')
+ print(f' After: ...{p[3]}')
+ print(f' Line: {p[4]}')
+ print()
+
diff --git a/tools/legacy/ocr_optimizer.py b/tools/legacy/ocr_optimizer.py
new file mode 100644
index 0000000..d588d55
--- /dev/null
+++ b/tools/legacy/ocr_optimizer.py
@@ -0,0 +1,375 @@
+"""
+OCR优化模块:支持多种OCR方案,可配置切换
+
+支持的方案:
+1. PaddleOCR(当前默认,准确但较慢)
+2. EasyOCR(推荐,快速且准确)
+3. 百度OCR API(在线,极快极准,有免费额度)
+4. 腾讯OCR API(在线,极快极准,有免费额度)
+
+使用方法:
+1. 设置环境变量 OCR_TYPE=easyocr 或 baidu 或 tencent
+2. 或在 config.json 中设置 "ocr_type": "easyocr"
+"""
+
+import os
+import base64
+import json
+import time
+from typing import Optional, Tuple
+from PIL import Image
+import numpy as np
+
+
+class OCRProvider:
+ """OCR提供者基类"""
+
+ def __init__(self):
+ self.initialized = False
+ self.provider = None
+
+ def initialize(self):
+ """初始化OCR引擎"""
+ raise NotImplementedError
+
+ def recognize(self, image: Image.Image) -> str:
+ """识别图片中的文字"""
+ raise NotImplementedError
+
+
+class PaddleOCRProvider(OCRProvider):
+ """PaddleOCR提供者(当前默认)"""
+
+ def initialize(self):
+ if self.initialized:
+ return
+ try:
+ import contextlib
+ devnull = open(os.devnull, "w")
+ with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
+ from paddleocr import PaddleOCR
+ self.provider = PaddleOCR(
+ lang="ch",
+ ocr_version="PP-OCRv4",
+ use_doc_orientation_classify=False,
+ use_doc_unwarping=False,
+ use_textline_orientation=False,
+ )
+ devnull.close()
+ self.initialized = True
+ except Exception as e:
+ print(f"[OCR] PaddleOCR初始化失败: {e}")
+ self.provider = None
+
+ def recognize(self, image: Image.Image) -> str:
+ if not self.initialized:
+ self.initialize()
+ if self.provider is None:
+ return ""
+
+ try:
+ img_np = np.array(image.convert('RGB'))
+ result = self.provider.ocr(img_np)
+ if result == [None]:
+ return ""
+
+ # 提取文本
+ texts = []
+ if isinstance(result, list):
+ for item in result:
+ if isinstance(item, list):
+ for sub_item in item:
+ if isinstance(sub_item, (list, tuple)) and len(sub_item) >= 2:
+ text = sub_item[1]
+ if isinstance(text, (list, tuple)) and len(text) >= 1:
+ texts.append(str(text[0]))
+ elif isinstance(text, str):
+ texts.append(text)
+ elif isinstance(text, dict):
+ texts.append(str(text.get("text", text.get("rec_text", ""))))
+
+ return "".join(texts)
+ except Exception as e:
+ print(f"[OCR] PaddleOCR识别失败: {e}")
+ return ""
+
+
+class EasyOCRProvider(OCRProvider):
+ """EasyOCR提供者(推荐:快速且准确)"""
+
+ def initialize(self):
+ if self.initialized:
+ return
+ try:
+ import easyocr
+ # 只加载中文和英文,加快初始化速度
+ self.provider = easyocr.Reader(['ch_sim', 'en'], gpu=False) # gpu=True 如果可用GPU
+ self.initialized = True
+ print("[OCR] EasyOCR初始化成功")
+ except Exception as e:
+ print(f"[OCR] EasyOCR初始化失败: {e}")
+ print("[OCR] 请安装: pip install easyocr")
+ self.provider = None
+
+ def recognize(self, image: Image.Image) -> str:
+ if not self.initialized:
+ self.initialize()
+ if self.provider is None:
+ return ""
+
+ try:
+ img_np = np.array(image.convert('RGB'))
+ results = self.provider.readtext(img_np)
+
+ # EasyOCR返回格式: [(bbox, text, confidence), ...]
+ texts = [result[1] for result in results if len(result) >= 2]
+ return "".join(texts)
+ except Exception as e:
+ print(f"[OCR] EasyOCR识别失败: {e}")
+ return ""
+
+
+class BaiduOCRProvider(OCRProvider):
+ """百度OCR API提供者(在线,极快极准)"""
+
+ def __init__(self):
+ super().__init__()
+ self.api_key = os.environ.get("BAIDU_OCR_API_KEY", "")
+ self.secret_key = os.environ.get("BAIDU_OCR_SECRET_KEY", "")
+ self.access_token = None
+
+ def initialize(self):
+ if self.initialized:
+ return
+ if not self.api_key or not self.secret_key:
+ print("[OCR] 百度OCR API: 未设置API_KEY和SECRET_KEY")
+ print("[OCR] 请设置环境变量: BAIDU_OCR_API_KEY 和 BAIDU_OCR_SECRET_KEY")
+ print("[OCR] 或访问: https://ai.baidu.com/tech/ocr/general")
+ return
+
+ try:
+ import requests
+ # 获取access_token
+ token_url = "https://aip.baidubce.com/oauth/2.0/token"
+ params = {
+ "grant_type": "client_credentials",
+ "client_id": self.api_key,
+ "client_secret": self.secret_key
+ }
+ response = requests.post(token_url, params=params, timeout=5)
+ if response.status_code == 200:
+ self.access_token = response.json().get("access_token")
+ self.initialized = True
+ print("[OCR] 百度OCR API初始化成功")
+ else:
+ print(f"[OCR] 百度OCR API获取token失败: {response.text}")
+ except Exception as e:
+ print(f"[OCR] 百度OCR API初始化失败: {e}")
+
+ def recognize(self, image: Image.Image) -> str:
+ if not self.initialized or not self.access_token:
+ return ""
+
+ try:
+ import requests
+ # 将图片转换为base64
+ from io import BytesIO
+ buffer = BytesIO()
+ image.save(buffer, format='PNG')
+ img_base64 = base64.b64encode(buffer.getvalue()).decode()
+
+ # 调用API
+ url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token={self.access_token}"
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
+ data = {"image": img_base64}
+
+ response = requests.post(url, headers=headers, data=data, timeout=5)
+ if response.status_code == 200:
+ result = response.json()
+ if "words_result" in result:
+ texts = [item.get("words", "") for item in result["words_result"]]
+ return "".join(texts)
+ return ""
+ except Exception as e:
+ print(f"[OCR] 百度OCR API识别失败: {e}")
+ return ""
+
+
+class TencentOCRProvider(OCRProvider):
+ """腾讯OCR API提供者(在线,极快极准)"""
+
+ def __init__(self):
+ super().__init__()
+ self.secret_id = os.environ.get("TENCENT_OCR_SECRET_ID", "")
+ self.secret_key = os.environ.get("TENCENT_OCR_SECRET_KEY", "")
+
+ def initialize(self):
+ if self.initialized:
+ return
+ if not self.secret_id or not self.secret_key:
+ print("[OCR] 腾讯OCR API: 未设置SECRET_ID和SECRET_KEY")
+ print("[OCR] 请设置环境变量: TENCENT_OCR_SECRET_ID 和 TENCENT_OCR_SECRET_KEY")
+ return
+
+ try:
+ from tencentcloud.common import credential
+ from tencentcloud.common.profile.client_profile import ClientProfile
+ from tencentcloud.common.profile.http_profile import HttpProfile
+ from tencentcloud.ocr.v20181119 import ocr_client, models
+
+ cred = credential.Credential(self.secret_id, self.secret_key)
+ httpProfile = HttpProfile()
+ httpProfile.endpoint = "ocr.tencentcloudapi.com"
+ clientProfile = ClientProfile()
+ clientProfile.httpProfile = httpProfile
+
+ self.provider = ocr_client.OcrClient(cred, "ap-beijing", clientProfile)
+ self.models = models
+ self.initialized = True
+ print("[OCR] 腾讯OCR API初始化成功")
+ except Exception as e:
+ print(f"[OCR] 腾讯OCR API初始化失败: {e}")
+ print("[OCR] 请安装: pip install tencentcloud-sdk-python")
+ self.provider = None
+
+ def recognize(self, image: Image.Image) -> str:
+ if not self.initialized or self.provider is None:
+ return ""
+
+ try:
+ # 将图片转换为base64
+ from io import BytesIO
+ buffer = BytesIO()
+ image.save(buffer, format='PNG')
+ img_base64 = base64.b64encode(buffer.getvalue()).decode()
+
+ # 调用API
+ req = self.models.GeneralBasicOCRRequest()
+ req.ImageBase64 = img_base64
+
+ resp = self.provider.GeneralBasicOCR(req)
+ if resp.TextDetections:
+ texts = [item.DetectedText for item in resp.TextDetections]
+ return "".join(texts)
+ return ""
+ except Exception as e:
+ print(f"[OCR] 腾讯OCR API识别失败: {e}")
+ return ""
+
+
+def get_ocr_provider(ocr_type: Optional[str] = None) -> OCRProvider:
+ """
+ 获取OCR提供者
+
+ Args:
+ ocr_type: OCR类型 ('paddleocr', 'easyocr', 'baidu', 'tencent')
+ 如果为None,则从环境变量或config.json读取
+
+ Returns:
+ OCRProvider实例
+ """
+ if ocr_type is None:
+ # 优先从环境变量读取
+ ocr_type = os.environ.get("OCR_TYPE", "").lower()
+
+ # 如果环境变量未设置,尝试从config.json读取
+ if not ocr_type:
+ try:
+ config_path = os.path.join(os.path.dirname(__file__), "config.json")
+ if os.path.exists(config_path):
+ with open(config_path, 'r', encoding='utf-8') as f:
+ config = json.load(f)
+ ocr_type = config.get("ocr_type", "").lower()
+ except Exception:
+ pass
+
+ # 默认使用paddleocr
+ if not ocr_type:
+ ocr_type = "paddleocr"
+
+ ocr_type = ocr_type.lower()
+
+ if ocr_type == "easyocr":
+ return EasyOCRProvider()
+ elif ocr_type == "baidu":
+ return BaiduOCRProvider()
+ elif ocr_type == "tencent":
+ return TencentOCRProvider()
+ else:
+ return PaddleOCRProvider()
+
+
+# 全局OCR提供者实例(单例模式)
+_global_ocr_provider: Optional[OCRProvider] = None
+
+
+def get_global_ocr_provider() -> OCRProvider:
+ """获取全局OCR提供者实例(单例)"""
+ global _global_ocr_provider
+ if _global_ocr_provider is None:
+ _global_ocr_provider = get_ocr_provider()
+ _global_ocr_provider.initialize()
+ return _global_ocr_provider
+
+
+def recognize_image(image_path: str, ocr_type: Optional[str] = None) -> str:
+ """
+ 识别图片中的文字(便捷函数)
+
+ Args:
+ image_path: 图片路径
+ ocr_type: OCR类型(可选)
+
+ Returns:
+ 识别到的文字
+ """
+ try:
+ img = Image.open(image_path)
+ provider = get_global_ocr_provider() if ocr_type is None else get_ocr_provider(ocr_type)
+ if not provider.initialized:
+ provider.initialize()
+ return provider.recognize(img)
+ except Exception as e:
+ print(f"[OCR] 识别失败: {e}")
+ return ""
+
+
+if __name__ == "__main__":
+ # 测试代码
+ import sys
+ if len(sys.argv) > 1:
+ image_path = sys.argv[1]
+ ocr_type = sys.argv[2] if len(sys.argv) > 2 else None
+
+ start = time.time()
+ text = recognize_image(image_path, ocr_type)
+ elapsed = (time.time() - start) * 1000
+
+ print(f"识别结果: {text}")
+ print(f"耗时: {elapsed:.0f}ms")
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tools/legacy/organize_folder.py b/tools/legacy/organize_folder.py
new file mode 100644
index 0000000..f23e552
--- /dev/null
+++ b/tools/legacy/organize_folder.py
@@ -0,0 +1,187 @@
+"""
+文件夹整理脚本:整理项目文件夹结构,同时更新代码中的路径引用
+"""
+import os
+import shutil
+import re
+
+# 项目根目录
+PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
+
+# 整理方案:
+# 1. pic/ 目录分类:
+# - pic/screenshot.png (保持根目录,运行时临时截图)
+# - pic/ocr/ (OCR识别用的图片,运行时生成)
+# - pic/debug/ (调试截图,可归档)
+# - pic/test/ (测试图片)
+# - pic/archive/ (归档的旧截图)
+
+# 运行时必须保持在 pic/ 根目录的文件(不能移动)
+RUNTIME_FILES = {
+ 'screenshot.png', # 当前屏幕截图
+ 'cut.png', # 裁剪后的临时图片
+ 'window_dump.xml', # UI dump文件
+}
+
+# 必须保持的子目录(不能移动)
+KEEP_DIRS = {
+ 'save', # 保存验证图片的目录
+}
+
+# OCR识别用的图片(会从根目录移动到 ocr/ 子目录,但代码中已改为从 ocr/ 读取)
+OCR_FILES = [
+ # 诊断相关
+ 'diag_attend_btn.png', '诊断优惠券按钮.png', '诊断优惠券标题.png',
+ 'diag_fansclub_join.png', 'diag_follow_title.png', 'diag_guess_like_check.png',
+ 'diag_guess_like.png', 'diag_list_title.png', 'diag_live_plaza.png',
+ 'diag_recommend_title_check.png', 'diag_recommend_title.png', 'diag_result.png',
+ '诊断购物红包.png', '诊断购物红包按钮.png', 'diag_status.png',
+ # 福袋相关
+ 'fudai_content.png', 'fudai_countdown_m.png', 'fudai_countdown_s.png',
+ 'fudai_countdown.png', 'fudai_value.png', 'fudai_task_once_1.png',
+ 'fudai_task_once_2.png', 'fudai_task_once_3.png', 'fudai_tasks_1.png',
+ 'fudai_tasks_2.png', 'fudai_tasks_3.png',
+ # 按钮/界面元素
+ 'attend_button.png', '参与按钮.png', '优惠券按钮.png', '优惠券标题.png',
+ '抽奖结果.png', '直播广场.png', '福袋价值.png',
+ '福袋倒计时_分钟.png', '福袋倒计时_秒.png', '福袋倒计时.png',
+ '福袋内容.png', '购物红包.png', '任务用户区域.png',
+ # 直播间相关
+ 'live_room_title_large.png', '直播间标题_中.png', 'live_room_title_small.png',
+ 'live_room_title.png', 'live_room_title2.png', 'zhibo_follow_list_title.png',
+ 'zhibo_follow_list.png', 'zhibo_hongbao.png',
+ 'zhibo_status.png', 'zhibo_yanzheng.png',
+ # 其他运行时文件
+ 'lucky_draw_result.png', 'no_award_confirm.png', 'bottom_bar.png',
+ 'follow_precise_location.png', 'follow_region_precise.png',
+ 'follow_tab_detection.png', 'follow_tab_region_detailed.png', 'follow_tab_region.png',
+ '福袋任务_单次_1.png', '福袋任务_单次_2.png',
+]
+
+# 测试文件(移动到 test/ 子目录)
+TEST_FILES = [
+ 'test_bottom_tab_follow.png', 'test_bottom_tab.png',
+ 'test_bottom_中间区域消息.png', 'test_bottom_关注标签区域.png',
+ 'test_bottom_右侧区域我.png', 'test_bottom_完整底部标签栏.png',
+ 'test_bottom_左侧区域首页_推荐.png', 'test_follow_title.png',
+ 'test_guess_like.png', 'test_list_title.png', 'test_recommend_expanded.png',
+ 'test_recommend_title.png',
+]
+
+# 调试/归档文件(移动到 archive/ 子目录)
+DEBUG_DIRS = [
+ 'action_fav_roi', 'action_like_roi', 'after_fav_click', 'after_like_click',
+ 'after_swipe', 'before_detect_action_fav_roi', 'before_detect_action_like_roi',
+ 'before_fav_click', 'before_like_click', 'before_swipe',
+ 'comment_after_close', 'comment_after_focus', 'comment_after_input',
+ 'comment_after_open', 'comment_after_send', 'comment_before_open',
+ 'desktop_icon', 'start', 'step1_close', 'step2_back', 'step3_browse_done',
+ 'step4_live', 'step5_enter',
+]
+
+DEBUG_FILES = [
+ 'screenshot_annotated.png', 'screenshot_regions_marked.png',
+ 'screenshot_直播广场_标注.png',
+]
+
+
+def organize_pic_directory():
+ """整理 pic 目录"""
+ pic_dir = os.path.join(PROJECT_ROOT, 'pic')
+ if not os.path.exists(pic_dir):
+ print(f"[整理] pic 目录不存在,跳过")
+ return
+
+ # 创建子目录
+ ocr_dir = os.path.join(pic_dir, 'ocr')
+ test_dir = os.path.join(pic_dir, 'test')
+ archive_dir = os.path.join(pic_dir, 'archive')
+
+ for d in [ocr_dir, test_dir, archive_dir]:
+ os.makedirs(d, exist_ok=True)
+
+ # 移动 OCR 文件
+ moved_ocr = 0
+ for filename in OCR_FILES:
+ src = os.path.join(pic_dir, filename)
+ if os.path.exists(src):
+ dst = os.path.join(ocr_dir, filename)
+ if not os.path.exists(dst):
+ shutil.move(src, dst)
+ moved_ocr += 1
+ print(f"[整理] 移动 OCR 文件: {filename} -> ocr/{filename}")
+
+ # 移动测试文件
+ moved_test = 0
+ for filename in TEST_FILES:
+ src = os.path.join(pic_dir, filename)
+ if os.path.exists(src):
+ dst = os.path.join(test_dir, filename)
+ if not os.path.exists(dst):
+ shutil.move(src, dst)
+ moved_test += 1
+ print(f"[整理] 移动测试文件: {filename} -> test/{filename}")
+
+ # 移动调试目录(跳过需要保留的目录)
+ moved_dirs = 0
+ for dirname in DEBUG_DIRS:
+ if dirname in KEEP_DIRS:
+ continue # 跳过需要保留的目录
+ src = os.path.join(pic_dir, dirname)
+ if os.path.exists(src) and os.path.isdir(src):
+ dst = os.path.join(archive_dir, dirname)
+ if not os.path.exists(dst):
+ shutil.move(src, dst)
+ moved_dirs += 1
+ print(f"[整理] 移动调试目录: {dirname}/ -> archive/{dirname}/")
+
+ # 移动调试文件
+ moved_debug = 0
+ for filename in DEBUG_FILES:
+ src = os.path.join(pic_dir, filename)
+ if os.path.exists(src):
+ dst = os.path.join(archive_dir, filename)
+ if not os.path.exists(dst):
+ shutil.move(src, dst)
+ moved_debug += 1
+ print(f"[整理] 移动调试文件: {filename} -> archive/{filename}")
+
+ print(f"\n[整理完成] pic 目录整理统计:")
+ print(f" - OCR 文件: {moved_ocr} 个 -> pic/ocr/")
+ print(f" - 测试文件: {moved_test} 个 -> pic/test/")
+ print(f" - 调试目录: {moved_dirs} 个 -> pic/archive/")
+ print(f" - 调试文件: {moved_debug} 个 -> pic/archive/")
+ print(f"\n[提示] 代码已更新,支持新旧路径查找(向后兼容)")
+
+
+if __name__ == '__main__':
+ import sys
+ print("=" * 60)
+ print("文件夹整理脚本")
+ print("=" * 60)
+ print("\n此脚本将:")
+ print(" 1. 整理 pic/ 目录,将文件分类到子目录")
+ print(" 2. OCR文件 -> pic/ocr/")
+ print(" 3. 测试文件 -> pic/test/")
+ print(" 4. 调试文件/目录 -> pic/archive/")
+ print("\n运行时文件(screenshot.png, cut.png)保持在根目录")
+ print("\n[提示] 代码已更新,支持新旧路径查找(向后兼容)")
+ print("=" * 60)
+
+ # 支持命令行参数 --yes 自动确认
+ auto_confirm = '--yes' in sys.argv or '-y' in sys.argv
+
+ if not auto_confirm:
+ try:
+ response = input("\n是否继续?(y/n): ").strip().lower()
+ except (EOFError, KeyboardInterrupt):
+ print("\n已取消(非交互式环境,使用 --yes 参数可自动确认)")
+ sys.exit(0)
+ else:
+ response = 'y'
+
+ if response == 'y':
+ organize_pic_directory()
+ else:
+ print("已取消")
+
diff --git a/test_follow_tab_coordinates.py b/tools/legacy/test_follow_tab_coordinates.py
similarity index 100%
rename from test_follow_tab_coordinates.py
rename to tools/legacy/test_follow_tab_coordinates.py
diff --git a/tools/legacy/view_image_coords.py b/tools/legacy/view_image_coords.py
new file mode 100644
index 0000000..76d9457
--- /dev/null
+++ b/tools/legacy/view_image_coords.py
@@ -0,0 +1,84 @@
+"""
+简单的图片坐标查看工具
+直接查看现有的 OCR 截图文件,帮助你确认坐标
+"""
+
+import os
+import sys
+from PIL import Image
+
+# 修复 Windows 控制台编码问题
+if sys.platform == 'win32':
+ try:
+ sys.stdout.reconfigure(encoding='utf-8', errors='replace')
+ except Exception:
+ pass
+
+def show_image_info(image_path):
+ """显示图片信息和简单的坐标提示"""
+ if not os.path.exists(image_path):
+ print(f"❌ 图片文件不存在: {image_path}")
+ return False
+
+ try:
+ img = Image.open(image_path)
+ width, height = img.size
+ file_size = os.path.getsize(image_path) / 1024 # KB
+
+ print(f"\n{'='*60}")
+ print(f"图片信息: {os.path.basename(image_path)}")
+ print(f"{'='*60}")
+ print(f"📐 尺寸: {width} x {height} 像素")
+ print(f"📦 文件大小: {file_size:.2f} KB")
+ print(f"📍 路径: {image_path}")
+ print(f"\n💡 如何获取坐标:")
+ print(f" 方法1: Windows画图工具(推荐)")
+ print(f" 1. 双击图片文件,用画图打开")
+ print(f" 2. 将鼠标移动到目标位置")
+ print(f" 3. 查看画图左下角状态栏,显示格式: 'X: 123 Y: 456'")
+ print(f" 4. 记录左上角坐标 (x1, y1) 和右下角坐标 (x2, y2)")
+ print(f"\n 方法2: 使用截图工具")
+ print(f" 1. 打开 QQ截图 / 微信截图 / Snipping Tool")
+ print(f" 2. 框选目标区域")
+ print(f" 3. 查看显示的区域大小和位置")
+ print(f"\n 方法3: 使用交互式查看器(需要 tkinter)")
+ print(f" 运行: python check_image_coordinates.py interactive")
+ print(f"\n📝 坐标格式说明:")
+ print(f" - 坐标系: 左上角为原点 (0, 0)")
+ print(f" - X轴: 向右递增")
+ print(f" - Y轴: 向下递增")
+ print(f" - 格式: cut_pic(x1, y1, x2, y2, ...)")
+ print(f" - 示例: cut_pic(100, 150, 400, 200, ...) 表示")
+ print(f" 左上角(100, 150) 到 右下角(400, 200) 的矩形区域")
+ print(f"{'='*60}\n")
+ return True
+ except Exception as e:
+ print(f"❌ 打开图片失败: {e}")
+ return False
+
+if __name__ == "__main__":
+ base_dir = os.path.dirname(os.path.abspath(__file__))
+
+ # 查看多个可能的图片
+ images_to_check = [
+ ('当前截图', os.path.join(base_dir, 'pic', 'screenshot.png')),
+ ('直播间标题_中', os.path.join(base_dir, 'pic', 'ocr', '直播间标题_中.png')),
+ ('直播间标题(large)', os.path.join(base_dir, 'pic', 'ocr', 'live_room_title_large.png')),
+ ('直播间标题(small)', os.path.join(base_dir, 'pic', 'ocr', 'live_room_title_small.png')),
+ ]
+
+ print("🔍 直播间标题坐标查看工具\n")
+
+ # 只显示存在的图片
+ found_images = []
+ for name, path in images_to_check:
+ if os.path.exists(path):
+ found_images.append((name, path))
+
+ if not found_images:
+ print("❌ 没有找到任何图片文件")
+ print(f" 请确保程序已运行过,生成了截图文件")
+ else:
+ for name, path in found_images:
+ show_image_info(path)
+
diff --git a/tools/test_web_gui.py b/tools/test_web_gui.py
new file mode 100644
index 0000000..7104e4a
--- /dev/null
+++ b/tools/test_web_gui.py
@@ -0,0 +1,328 @@
+"""
+Web 端自動化巡檢腳本
+====================
+
+用途:
+- 打開 Web GUI(預設 http://127.0.0.1:8000/)
+- 點擊「開始運行」
+- 週期性採集:
+ - 日誌區域:
+ - 實時截圖:
+- 在本地保留整個測試期間的所有截圖,並將每次截圖時的日誌文本一併保存,方便一一對應排查。
+
+依賴:
+ pip install playwright
+ playwright install
+
+用法示例(PowerShell)::
+
+ cd C:\\Users\\12742\\Desktop\\douyin_guaji-main
+ python -m tools.test_web_gui ^
+ --url http://127.0.0.1:8000 ^
+ --duration-seconds 300 ^
+ --interval-seconds 5 ^
+ --output-dir web_test_artifacts
+
+注意:
+- 本腳本只負責 Web 前端監控,不會啟動後端服務;
+ 請先確保你的 Web GUI(例如 web_gui.py / webgui_launcher.py)已經在本機監聽 8000 埠。
+- 爲了測得更全面,建議在測試前先配置好 Web GUI 的各種選項(福袋條件、定時禁搶、預約、高價值回訪等),
+ 然後再跑本腳本。
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import textwrap
+from dataclasses import dataclass, asdict
+from datetime import datetime
+from pathlib import Path
+from typing import List, Optional
+import shutil
+
+from playwright.async_api import async_playwright, Page
+
+
+LOG_SELECTOR = "pre#log"
+SHOT_SELECTOR = "img#liveShot"
+
+
+@dataclass
+class SampleRecord:
+ index: int
+ timestamp: str
+ screenshot_path: str
+ log_path: str
+ log_tail: str
+
+
+async def _click_button_if_exists(page: Page, name: str) -> bool:
+ """按 aria-label/文字內容尋找對應按鈕並點擊。"""
+ try:
+ button = page.get_by_role("button", name=name)
+ if await button.count() > 0:
+ await button.first.click()
+ return True
+ except Exception:
+ # 測試腳本不因一次點擊失敗而中止
+ return False
+ return False
+
+
+async def _ensure_started(page: Page) -> None:
+ """嘗試點擊「開始運行」啟動 Web GUI 後端任務。"""
+ # 先嘗試點「刷新設備」,避免沒有設備時直接失敗
+ await _click_button_if_exists(page, "刷新设备")
+ await asyncio.sleep(2.0) # 增加等待時間,確保設備列表刷新完成
+
+ # 檢查是否有設備可用
+ try:
+ # 嘗試讀取日誌,看是否有設備相關信息
+ log_element = await page.query_selector(LOG_SELECTOR)
+ if log_element:
+ log_text = await log_element.inner_text()
+ if "未检测到设备" in log_text or "未发现设备" in log_text:
+ print("[警告] Web GUI 顯示未檢測到設備,請確認:")
+ print(" 1. 手機已通過 USB 連接電腦")
+ print(" 2. 已開啟 USB 調試並授權")
+ print(" 3. 在命令行運行 'adb devices' 能看到設備")
+ except Exception:
+ pass
+
+ # 點擊「開始運行」
+ clicked = await _click_button_if_exists(page, "开始运行")
+ if clicked:
+ print("[測試腳本] 已點擊「開始運行」按鈕")
+ await asyncio.sleep(3.0) # 等待後端啟動子進程
+
+ # 再次檢查日誌,確認是否真的啟動了
+ try:
+ log_element = await page.query_selector(LOG_SELECTOR)
+ if log_element:
+ log_text = await log_element.inner_text()
+ if "[啟動]" in log_text or "[主循環]" in log_text or "設備分辨率" in log_text:
+ print("[測試腳本] ✓ 掛機進程似乎已啟動(日誌中有啟動相關信息)")
+ elif "already running" in log_text or "已在運行" in log_text:
+ print("[測試腳本] ⚠ Web GUI 顯示任務已在運行中")
+ else:
+ print("[測試腳本] ⚠ 未在日誌中看到明顯的啟動信息,可能:")
+ print(" - 設備未選擇或未連接")
+ print(" - 後端啟動子進程失敗")
+ print(" - 請手動在瀏覽器中檢查 Web GUI 的日誌區域")
+ except Exception:
+ pass
+ else:
+ print("[測試腳本] ⚠ 未能點擊「開始運行」按鈕,可能按鈕不存在或頁面未完全加載")
+
+
+async def _ensure_stopped(page: Page) -> None:
+ """測試結束時,嘗試點擊「停止」按鈕。"""
+ await _click_button_if_exists(page, "停止")
+
+
+async def run_web_test(
+ url: str,
+ duration_seconds: int,
+ interval_seconds: float,
+ output_dir: Path,
+) -> List[SampleRecord]:
+ """主測試邏輯。
+
+ - 打開頁面並嘗試點「開始運行」
+ - 在整個 duration_seconds 期間,每 interval_seconds:
+ - 讀取 #log 文字並寫入 .log 檔
+ - 對 #liveShot 做元素截圖,保存為 .png
+ - 記錄 index / timestamp / 檔名 / 日誌尾部(方便快速總覽)
+ """
+ output_dir.mkdir(parents=True, exist_ok=True)
+ screenshots_dir = output_dir / "screenshots"
+ logs_dir = output_dir / "logs"
+ screenshots_dir.mkdir(exist_ok=True)
+ logs_dir.mkdir(exist_ok=True)
+
+ meta_records: List[SampleRecord] = []
+
+ async with async_playwright() as p:
+ browser = await p.chromium.launch(headless=True)
+ page = await browser.new_page()
+ await page.goto(url)
+
+ # 等頁面穩定
+ await page.wait_for_timeout(2000)
+
+ # 儘量確保任務已經啟動
+ await _ensure_started(page)
+
+ start = datetime.utcnow()
+ end_time = start.timestamp() + duration_seconds
+ index = 0
+ last_log_text: Optional[str] = None
+
+ while datetime.utcnow().timestamp() < end_time:
+ now = datetime.utcnow()
+ timestamp_str = now.strftime("%Y-%m-%d_%H-%M-%S")
+
+ # 抓取日誌
+ log_element = await page.query_selector(LOG_SELECTOR)
+ log_text = ""
+ if log_element is not None:
+ try:
+ log_text = await log_element.inner_text()
+ except Exception:
+ log_text = ""
+
+ # 取日誌尾部幾行方便總覽
+ log_tail = ""
+ if log_text:
+ lines = [ln for ln in log_text.splitlines() if ln.strip()]
+ tail_lines = lines[-10:] if len(lines) > 10 else lines
+ log_tail = "\n".join(tail_lines)
+
+ # 保存完整日誌到檔案
+ log_filename = f"log_{index:04d}_{timestamp_str}.log"
+ log_path = logs_dir / log_filename
+ log_path.write_text(log_text, encoding="utf-8", errors="ignore")
+
+ # 抓取實時截圖元素
+ shot_element = await page.query_selector(SHOT_SELECTOR)
+ screenshot_filename = f"screenshot_{index:04d}_{timestamp_str}.png"
+ screenshot_path = screenshots_dir / screenshot_filename
+
+ if shot_element is not None:
+ try:
+ await shot_element.screenshot(path=str(screenshot_path))
+ except Exception:
+ # 如果元素截圖失敗,退而求其次截整頁
+ await page.screenshot(path=str(screenshot_path))
+ else:
+ # 找不到元素,同樣退回整頁截圖
+ await page.screenshot(path=str(screenshot_path))
+
+ record = SampleRecord(
+ index=index,
+ timestamp=timestamp_str,
+ screenshot_path=str(screenshot_path),
+ log_path=str(log_path),
+ log_tail=log_tail,
+ )
+ meta_records.append(record)
+
+ # 簡單在控制台輸出概況,幫助快速觀察測試是否卡死
+ has_new_log = log_text != last_log_text
+ last_log_text = log_text
+ summary_tail = textwrap.shorten(
+ log_tail.replace("\n", " / "), width=120, placeholder="..."
+ )
+ print(
+ f"[{index:04d}] {timestamp_str} "
+ f"new_log={has_new_log} "
+ f"screenshot={screenshot_filename} "
+ f"log_tail={summary_tail}"
+ )
+
+ index += 1
+ await asyncio.sleep(interval_seconds)
+
+ # 測試結束,嘗試點「停止」
+ await _ensure_stopped(page)
+ await browser.close()
+
+ # 把所有採樣記錄寫入 summary.json,方便後續分析
+ summary_path = output_dir / "summary.json"
+ summary_path.write_text(
+ json.dumps([asdict(r) for r in meta_records], ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+ print(f"\n測試完成,共生成 {len(meta_records)} 組截圖+日誌樣本,詳見:{output_dir}")
+ return meta_records
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="針對 Web GUI 的自動化巡檢腳本,監控 #log 與 #liveShot 並保存全部截圖。"
+ )
+ parser.add_argument(
+ "--url",
+ default="http://127.0.0.1:8000/",
+ help="Web GUI 的地址(預設: http://127.0.0.1:8000/)",
+ )
+ parser.add_argument(
+ "--duration-seconds",
+ type=int,
+ default=300,
+ help="整體測試時長(秒),預設 300 秒(5分鐘)",
+ )
+ parser.add_argument(
+ "--interval-seconds",
+ type=float,
+ default=5.0,
+ help="採樣間隔(秒),預設 5 秒保存一次截圖與日誌",
+ )
+ parser.add_argument(
+ "--output-dir",
+ type=str,
+ default="web_test_runs",
+ help="測試根目錄(會在其中按時間自動建立子目錄),用於保存本次測試的所有資料",
+ )
+ return parser.parse_args()
+
+
+def _snapshot_context_files(run_root: Path) -> None:
+ """在每次測試目錄下備份當前關鍵配置與狀態,方便之後一併打包分析。"""
+ project_root = Path(".").resolve()
+ context_dir = run_root / "context"
+ context_dir.mkdir(parents=True, exist_ok=True)
+
+ # 一些關鍵單檔:當前配置與入口/主流程
+ important_files = [
+ "config.json",
+ "run_cli.py",
+ "douyin_fudai.py",
+ "douyin_stage.py",
+ "douyin_fudai_core.py",
+ "douyin_reservation.py",
+ "douyin_robot.py",
+ ]
+ for name in important_files:
+ src = project_root / name
+ if src.exists():
+ shutil.copy2(src, context_dir / src.name)
+
+ # state 目錄(包括 reservations.json / high_value_rooms.json 等)
+ state_src = project_root / "state"
+ if state_src.is_dir():
+ state_dst = context_dir / "state"
+ shutil.copytree(state_src, state_dst, dirs_exist_ok=True)
+
+
+def main() -> None:
+ args = parse_args()
+ root_dir = Path(args.output_dir)
+
+ # 爲每次測試建立單獨的子目錄,名稱帶時間戳,方便你直接整個資料夾打包給我分析
+ ts = datetime.now().strftime("run_%Y%m%d_%H%M%S")
+ run_root = root_dir / ts
+ run_root.mkdir(parents=True, exist_ok=True)
+
+ # 備份當前配置與狀態
+ _snapshot_context_files(run_root)
+
+ # 再在該目錄下建立 web 測試輸出
+ output_dir = run_root / "web_artifacts"
+
+ asyncio.run(
+ run_web_test(
+ url=args.url,
+ duration_seconds=args.duration_seconds,
+ interval_seconds=args.interval_seconds,
+ output_dir=output_dir,
+ )
+ )
+
+
+if __name__ == "__main__":
+ main()
+
+
diff --git a/web_gui.py b/web_gui.py
index 443607f..3c3c5e6 100644
--- a/web_gui.py
+++ b/web_gui.py
@@ -624,9 +624,9 @@ class ProcRunner:
if idx < 0:
idx = 0
log_len = len(self._log)
- # 如果索引越界,说明日志可能被截断了(比如内存日志被清理)
- # 返回所有日志,让前端能够检测到并重置索引
- if idx > log_len:
+ # 如果索引越界或等于日志长度(说明日志可能被截断了),返回所有日志
+ # 让前端能够检测到并重置索引
+ if idx >= log_len:
idx = 0
lines = self._log[idx:]
return log_len, lines
@@ -690,6 +690,20 @@ class ProcRunner:
needswitch = bool(_pick("needswitch", False))
reset_after_swipes_enabled = bool(_pick("reset_after_swipes_enabled", False))
wait_minutes = int(_pick("wait_minutes", 5) or 5)
+
+ # 启动时自动截图
+ if device_id:
+ try:
+ from Underlying_Operations import underlying_operations
+ ops = underlying_operations()
+ self._append_log(f"[启动] 自动截图: device={device_id}")
+ result = ops.get_screenshot(device_id)
+ if result:
+ self._append_log("[启动] 截图成功,已保存到 pic/screenshot.png")
+ else:
+ self._append_log("[启动] 截图失败")
+ except Exception as e:
+ self._append_log(f"[启动] 截图异常: {e}")
# 这些运行参数与 run_cli.py --help 对齐
min_prize_value_yuan = float(_pick("min_prize_value_yuan", 0) or 0)
@@ -998,6 +1012,29 @@ class Handler(BaseHTTPRequestHandler):
except Exception:
out_lines = [""]
return self._send_json({"ok": True, "path": path, "lines": out_lines})
+
+ if u.path == "/api/actions":
+ # 返回精简行为日志(logs/actions.log)的尾部若干行,便于在 Web GUI 中单独查看点击/识别耗时
+ qs = parse_qs(u.query)
+ try:
+ n = int((qs.get("lines") or [200])[0])
+ except Exception:
+ n = 200
+ path = os.path.join(BASE_DIR, "logs", "actions.log")
+ out_lines: list[str] = []
+ try:
+ if os.path.exists(path):
+ size = os.path.getsize(path)
+ read_bytes = min(size, 65536)
+ with open(path, "rb") as f:
+ if read_bytes < size:
+ f.seek(-read_bytes, os.SEEK_END)
+ data = f.read().decode("utf-8", errors="replace")
+ parts = data.splitlines()
+ out_lines = parts[-n:]
+ except Exception:
+ out_lines = [""]
+ return self._send_json({"ok": True, "path": path, "lines": out_lines})
self.send_error(HTTPStatus.NOT_FOUND)
return
@@ -1159,6 +1196,21 @@ class Handler(BaseHTTPRequestHandler):
if u.path == "/api/stop":
RUNNER.stop()
return self._send_json({"ok": True})
+
+ if u.path == "/api/screenshot":
+ # 手动截图接口
+ body = self._read_json()
+ device_id = str(body.get("device_id") or "").strip()
+ try:
+ from Underlying_Operations import underlying_operations
+ ops = underlying_operations()
+ result = ops.get_screenshot(device_id)
+ if result:
+ return self._send_json({"ok": True, "message": "截图成功"})
+ else:
+ return self._send_json({"ok": False, "error": "截图失败"}, status=500)
+ except Exception as e:
+ return self._send_json({"ok": False, "error": str(e)}, status=500)
self.send_error(HTTPStatus.NOT_FOUND)
diff --git a/webgui_launcher.py b/webgui_launcher.py
new file mode 100644
index 0000000..128aea1
--- /dev/null
+++ b/webgui_launcher.py
@@ -0,0 +1,372 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+Web GUI 启动器 - GUI版本
+用于启动和管理抖音挂机 Web GUI 服务
+"""
+
+import os
+import sys
+import subprocess
+import threading
+import time
+import webbrowser
+from pathlib import Path
+import tkinter as tk
+from tkinter import ttk, scrolledtext, messagebox
+
+# 获取脚本所在目录
+BASE_DIR = Path(__file__).parent.absolute()
+LOG_FILE = BASE_DIR / "webgui_startup.log"
+WEB_GUI_PY = BASE_DIR / "web_gui.py"
+
+# 默认端口
+DEFAULT_PORT = 8000
+
+
+class WebGUILauncher:
+ def __init__(self, root):
+ self.root = root
+ self.root.title("抖音挂机 Web GUI 启动器")
+ self.root.geometry("700x550")
+ self.root.resizable(True, True)
+
+ # 服务进程
+ self.webgui_process = None
+ self.monitor_thread = None
+ self.is_running = False
+ self.port = DEFAULT_PORT
+
+ # 创建UI
+ self.create_ui()
+
+ # 检查初始状态
+ self.check_service_status()
+
+ # 定期检查服务状态
+ self.schedule_status_check()
+
+ def create_ui(self):
+ """创建用户界面"""
+ # 主框架
+ main_frame = ttk.Frame(self.root, padding="10")
+ main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
+
+ # 配置网格权重
+ self.root.columnconfigure(0, weight=1)
+ self.root.rowconfigure(0, weight=1)
+ main_frame.columnconfigure(1, weight=1)
+ main_frame.rowconfigure(2, weight=1)
+
+ # 标题
+ title_label = ttk.Label(
+ main_frame,
+ text="抖音挂机 Web GUI 启动器",
+ font=("Arial", 16, "bold")
+ )
+ title_label.grid(row=0, column=0, columnspan=3, pady=(0, 20))
+
+ # 状态区域
+ status_frame = ttk.LabelFrame(main_frame, text="服务状态", padding="10")
+ status_frame.grid(row=1, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
+ status_frame.columnconfigure(1, weight=1)
+
+ self.status_label = ttk.Label(status_frame, text="检查中...", font=("Arial", 10))
+ self.status_label.grid(row=0, column=0, columnspan=2, sticky=tk.W)
+
+ self.port_label = ttk.Label(status_frame, text=f"端口: {self.port}")
+ self.port_label.grid(row=1, column=0, sticky=tk.W, pady=(5, 0))
+
+ # 按钮区域
+ button_frame = ttk.Frame(main_frame)
+ button_frame.grid(row=2, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
+
+ self.start_button = ttk.Button(
+ button_frame,
+ text="启动服务",
+ command=self.start_service,
+ width=15
+ )
+ self.start_button.pack(side=tk.LEFT, padx=(0, 5))
+
+ self.stop_button = ttk.Button(
+ button_frame,
+ text="停止服务",
+ command=self.stop_service,
+ width=15,
+ state=tk.DISABLED
+ )
+ self.stop_button.pack(side=tk.LEFT, padx=(0, 5))
+
+ self.open_browser_button = ttk.Button(
+ button_frame,
+ text="打开浏览器",
+ command=self.open_browser,
+ width=15,
+ state=tk.DISABLED
+ )
+ self.open_browser_button.pack(side=tk.LEFT, padx=(0, 5))
+
+ self.refresh_button = ttk.Button(
+ button_frame,
+ text="刷新状态",
+ command=self.check_service_status,
+ width=15
+ )
+ self.refresh_button.pack(side=tk.LEFT)
+
+ # 日志区域
+ log_frame = ttk.LabelFrame(main_frame, text="启动日志", padding="10")
+ log_frame.grid(row=3, column=0, columnspan=3, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
+ log_frame.columnconfigure(0, weight=1)
+ log_frame.rowconfigure(0, weight=1)
+ main_frame.rowconfigure(3, weight=1)
+
+ self.log_text = scrolledtext.ScrolledText(
+ log_frame,
+ height=15,
+ width=80,
+ wrap=tk.WORD,
+ font=("Consolas", 9)
+ )
+ self.log_text.pack(fill=tk.BOTH, expand=True)
+
+ # 底部信息
+ info_frame = ttk.Frame(main_frame)
+ info_frame.grid(row=4, column=0, columnspan=3, sticky=(tk.W, tk.E))
+
+ info_label = ttk.Label(
+ info_frame,
+ text="提示: 服务启动后会自动打开浏览器,也可以手动点击'打开浏览器'按钮",
+ font=("Arial", 9),
+ foreground="gray"
+ )
+ info_label.pack()
+
+ def log(self, message):
+ """添加日志"""
+ timestamp = time.strftime("%H:%M:%S")
+ log_message = f"[{timestamp}] {message}\n"
+ self.log_text.insert(tk.END, log_message)
+ self.log_text.see(tk.END)
+ print(log_message.strip()) # 同时输出到控制台
+
+ def check_service_status(self):
+ """检查服务状态"""
+ try:
+ import socket
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.settimeout(1)
+ result = sock.connect_ex(('127.0.0.1', self.port))
+ sock.close()
+
+ if result == 0:
+ # 端口已监听,服务运行中
+ self.is_running = True
+ self.status_label.config(text="✓ 服务运行中", foreground="green")
+ self.start_button.config(state=tk.DISABLED)
+ self.stop_button.config(state=tk.NORMAL)
+ self.open_browser_button.config(state=tk.NORMAL)
+ else:
+ # 端口未监听,服务未运行
+ self.is_running = False
+ self.status_label.config(text="✗ 服务未运行", foreground="red")
+ self.start_button.config(state=tk.NORMAL)
+ self.stop_button.config(state=tk.DISABLED)
+ self.open_browser_button.config(state=tk.DISABLED)
+ except Exception as e:
+ self.log(f"检查服务状态时出错: {e}")
+ self.is_running = False
+ self.status_label.config(text="? 状态未知", foreground="orange")
+
+ def start_service(self):
+ """启动服务"""
+ if self.is_running:
+ messagebox.showwarning("警告", "服务已经在运行中")
+ return
+
+ # 检查文件是否存在
+ if not WEB_GUI_PY.exists():
+ messagebox.showerror("错误", f"未找到 web_gui.py 文件\n路径: {WEB_GUI_PY}")
+ return
+
+ self.log("=" * 50)
+ self.log("开始启动 Web GUI 服务...")
+
+ # 停止旧进程
+ self.stop_old_processes()
+
+ # 设置环境变量
+ env = os.environ.copy()
+ env['PYTHONIOENCODING'] = 'utf-8'
+ env['PYTHONUNBUFFERED'] = '1'
+ if 'PORT' not in env and 'WEB_GUI_PORT' not in env:
+ env['PORT'] = str(self.port)
+
+ try:
+ # 检查是否有虚拟环境
+ venv_python = BASE_DIR / ".venv" / "Scripts" / "python.exe"
+ if venv_python.exists():
+ python_exe = str(venv_python)
+ self.log("使用虚拟环境启动...")
+ else:
+ python_exe = sys.executable
+ self.log("使用系统Python启动...")
+
+ # 启动进程(在Windows上显示控制台窗口以便查看日志)
+ creation_flags = 0
+ if sys.platform == 'win32':
+ # 使用普通窗口,不隐藏,这样可以看到日志
+ creation_flags = 0
+
+ self.webgui_process = subprocess.Popen(
+ [python_exe, str(WEB_GUI_PY)],
+ cwd=str(BASE_DIR),
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ bufsize=1,
+ creationflags=creation_flags
+ )
+
+ self.log(f"服务进程已启动 (PID: {self.webgui_process.pid})")
+
+ # 启动监控线程
+ self.monitor_thread = threading.Thread(
+ target=self.monitor_process,
+ daemon=True
+ )
+ self.monitor_thread.start()
+
+ # 等待服务启动
+ self.wait_for_service()
+
+ except Exception as e:
+ self.log(f"启动服务失败: {e}")
+ messagebox.showerror("错误", f"启动服务失败:\n{e}")
+ self.webgui_process = None
+
+ def stop_service(self):
+ """停止服务"""
+ if not self.is_running and not self.webgui_process:
+ messagebox.showinfo("提示", "服务未运行")
+ return
+
+ self.log("正在停止服务...")
+
+ # 停止进程
+ self.stop_old_processes()
+
+ if self.webgui_process:
+ try:
+ self.webgui_process.terminate()
+ self.webgui_process.wait(timeout=5)
+ self.log("服务已停止")
+ except subprocess.TimeoutExpired:
+ self.webgui_process.kill()
+ self.log("服务已强制停止")
+ except Exception as e:
+ self.log(f"停止服务时出错: {e}")
+ finally:
+ self.webgui_process = None
+
+ time.sleep(1)
+ self.check_service_status()
+
+ def stop_old_processes(self):
+ """停止旧的web_gui.py进程"""
+ try:
+ if sys.platform == 'win32':
+ # 使用PowerShell命令停止旧进程
+ ps_cmd = (
+ "Get-CimInstance Win32_Process | "
+ "Where-Object { ($_.CommandLine -like '*web_gui.py*') -and ($_.Name -like 'python*') } | "
+ "ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"
+ )
+ subprocess.run(
+ ['powershell', '-NoProfile', '-Command', ps_cmd],
+ capture_output=True,
+ timeout=5
+ )
+ else:
+ # Linux/Mac
+ subprocess.run(
+ ['pkill', '-f', 'web_gui.py'],
+ capture_output=True,
+ timeout=5
+ )
+ except Exception as e:
+ self.log(f"停止旧进程时出错: {e}")
+
+ def monitor_process(self):
+ """监控进程输出"""
+ if not self.webgui_process:
+ return
+
+ try:
+ for line in iter(self.webgui_process.stdout.readline, ''):
+ if not line:
+ break
+ line = line.strip()
+ if line:
+ self.root.after(0, self.log, line)
+ except Exception:
+ pass
+
+ def wait_for_service(self):
+ """等待服务启动"""
+ self.log("等待服务启动...")
+ max_wait = 30
+ for i in range(max_wait):
+ time.sleep(1)
+ self.check_service_status()
+ if self.is_running:
+ self.log("服务启动成功!")
+ self.open_browser()
+ return
+ self.root.update()
+
+ self.log("服务启动超时,请检查日志")
+ messagebox.showwarning("警告", "服务启动超时,请检查日志窗口")
+
+ def open_browser(self):
+ """打开浏览器"""
+ url = f"http://127.0.0.1:{self.port}"
+ self.log(f"打开浏览器: {url}")
+ try:
+ webbrowser.open(url)
+ except Exception as e:
+ self.log(f"打开浏览器失败: {e}")
+ messagebox.showerror("错误", f"打开浏览器失败:\n{e}")
+
+ def schedule_status_check(self):
+ """定期检查服务状态"""
+ self.check_service_status()
+ # 每5秒检查一次
+ self.root.after(5000, self.schedule_status_check)
+
+
+def main():
+ """主函数"""
+ root = tk.Tk()
+ app = WebGUILauncher(root)
+
+ # 处理窗口关闭事件
+ def on_closing():
+ if app.is_running:
+ if messagebox.askyesno("确认", "服务正在运行,是否要停止服务?"):
+ app.stop_service()
+ root.destroy()
+
+ root.protocol("WM_DELETE_WINDOW", on_closing)
+
+ try:
+ root.mainloop()
+ except KeyboardInterrupt:
+ pass
+
+
+if __name__ == "__main__":
+ main()
+
diff --git a/webui/app.js b/webui/app.js
index f1c7a7e..65b13d0 100644
--- a/webui/app.js
+++ b/webui/app.js
@@ -4,6 +4,7 @@ let statsTimer = null;
let shotTimer = null;
let lastLogUpdateTime = 0; // 最后成功获取日志的时间
let logErrorCount = 0; // 连续错误计数
+let emptyResponseCount = 0; // 连续空响应计数(用于检测索引卡住)
const DEFAULTS = {
// 筛选
@@ -42,7 +43,11 @@ const DEFAULTS = {
high_value_room_revisit_enabled: true,
high_value_room_revisit_only_current_run: false,
reservation_back_verify_enabled: true,
+ // 找福袋图标相关
fudai_find_max_attempts: 5,
+ fudai_icon_retry_delay_seconds: 0.6,
+ fudai_icon_max_wait_seconds: 5.0,
+ live_room_match_threshold: 0.8,
reservation_preempt_min_value: 0,
reservation_back_swipe_delay: 0.6,
@@ -577,9 +582,27 @@ async function startRun() {
appendLog([`[WEB] 已开始运行:device=${deviceId || '(auto)'}`]);
+ // 启动时自动截图
+ if (deviceId) {
+ try {
+ appendLog(["[截图] 启动时自动截图..."]);
+ const screenshotResult = await apiPost("/api/screenshot", { device_id: deviceId });
+ if (screenshotResult.ok) {
+ appendLog(["[截图] 启动截图成功,已保存到 pic/screenshot.png"]);
+ // 刷新截图显示
+ pollShot();
+ } else {
+ appendLog([`[截图] 启动截图失败: ${screenshotResult.error || "未知错误"}`]);
+ }
+ } catch (e) {
+ appendLog([`[截图] 启动截图失败: ${e?.message || e}`]);
+ }
+ }
+
// 重置本地日志索引并清空显示区域,然后立即拉取最新日志
try {
logIdx = 0;
+ emptyResponseCount = 0; // 重置空响应计数
// 清空日志显示区域,准备显示新进程的日志
const logEl = $("log");
if (logEl) {
@@ -591,7 +614,12 @@ async function startRun() {
}
} catch (e) {
console.error("[WEB] startRun error:", e);
- appendLog([`[WEB] 启动时出错: ${e.message || e}`]);
+ const errorMsg = e.message || String(e);
+ appendLog([`[WEB] 启动失败: ${errorMsg}`]);
+ // 如果是"running"错误,显示友好提示
+ if (errorMsg === "running" || (e.status === 409)) {
+ appendLog([`[WEB] 提示:已有进程在运行中,请先点击"停止"按钮`]);
+ }
}
}
@@ -615,6 +643,7 @@ async function stopRun() {
// 重置并拉取日志,确保能看到后端的停止确认输出
try {
logIdx = 0;
+ emptyResponseCount = 0; // 重置空响应计数
await pollLogs();
} catch (e) {
// ignore
@@ -632,15 +661,25 @@ async function pollLogs() {
return;
}
- // 重置错误计数
+ // 重置错误计数(API调用成功)
logErrorCount = 0;
- lastLogUpdateTime = Date.now();
+ // 记录API调用成功的时间(即使没有新日志,也说明连接正常)
+ const apiCallTime = Date.now();
- // 先检查索引是否异常(后端返回的next小于当前索引,说明日志被截断了)
- const nextIdx = typeof data.next === 'number' ? data.next : logIdx;
+ // 获取返回的索引
+ const nextIdx = typeof data.next === 'number' ? data.next : 0;
+
+ // 如果返回的索引小于当前索引,说明日志被截断了,需要重置
+ // 或者如果返回了所有日志(lines数量很大),也可能是重置了索引
if (nextIdx < logIdx && logIdx > 0) {
console.warn('[WEB_DBG] pollLogs: 检测到日志截断,重置索引', { oldIdx: logIdx, newIdx: nextIdx });
logIdx = 0;
+ emptyResponseCount = 0; // 重置空响应计数
+ // 清空日志显示区域,准备重新显示
+ const log = document.getElementById('log');
+ if (log) {
+ log.textContent = '';
+ }
// 重新请求一次以获取所有日志
const retryData = await apiGet(`/api/logs?since=0`);
if (retryData && typeof retryData === 'object' && Array.isArray(retryData.lines)) {
@@ -653,28 +692,26 @@ async function pollLogs() {
}
// 更新日志索引
- if (typeof data.next === 'number') {
- logIdx = data.next;
- }
+ logIdx = nextIdx;
+ // API调用成功,更新最后更新时间(不管是否有新日志)
+ lastLogUpdateTime = apiCallTime;
// 追加日志
if (Array.isArray(data.lines) && data.lines.length > 0) {
appendLog(data.lines);
- lastLogUpdateTime = Date.now();
+ emptyResponseCount = 0; // 重置空响应计数
+ } else {
+ // 没有新日志是正常的(比如脚本没有运行),不需要重置索引
+ // 只有在检测到索引不同步时才重置(已在前面处理)
+ emptyResponseCount++;
+ // 移除自动重置逻辑,避免在没有新日志时频繁清空日志显示
}
// 容错:确保索引不为负数
if (logIdx < 0) {
console.warn('[WEB_DBG] pollLogs: logIdx为负数,重置为0');
logIdx = 0;
- }
-
- // 如果超过30秒没有获取到新日志且索引很大,可能是索引卡住了,重置索引
- const now = Date.now();
- if (lastLogUpdateTime > 0 && (now - lastLogUpdateTime > 30000) && logIdx > 1000) {
- console.warn('[WEB_DBG] pollLogs: 长时间未更新,重置索引尝试恢复', { logIdx, lastUpdate: now - lastLogUpdateTime });
- logIdx = 0;
- lastLogUpdateTime = 0;
+ emptyResponseCount = 0;
}
} catch (e) {
logErrorCount++;
@@ -684,6 +721,7 @@ async function pollLogs() {
console.warn('[WEB_DBG] pollLogs: 连续10次错误,重置索引');
logIdx = 0;
logErrorCount = 0;
+ emptyResponseCount = 0; // 重置空响应计数
}
// 错误时不追加日志到界面,避免刷屏,只在控制台输出
// 如果是网络错误或超时,不重置索引;如果是其他错误,考虑重置
@@ -693,6 +731,7 @@ async function pollLogs() {
if (e.message.includes('JSON') || e.message.includes('parse')) {
console.warn('[WEB_DBG] pollLogs: 数据解析错误,重置索引');
logIdx = 0;
+ emptyResponseCount = 0; // 重置空响应计数
}
}
}
@@ -1031,6 +1070,50 @@ window.addEventListener("DOMContentLoaded", async () => {
$("btnSave").addEventListener("click", async () => { await saveConfig(); });
$("btnStart").addEventListener("click", async () => { await startRun(); });
$("btnStop").addEventListener("click", async () => { await stopRun(); });
+
+ // 截图按钮
+ $("btnScreenshot").addEventListener("click", async () => {
+ const deviceId = $("device").value || "";
+ if (!deviceId) {
+ appendLog(["[截图] 请先选择设备"]);
+ return;
+ }
+ try {
+ appendLog(["[截图] 正在截图..."]);
+ const result = await apiPost("/api/screenshot", { device_id: deviceId });
+ if (result.ok) {
+ appendLog(["[截图] 截图成功,已保存到 pic/screenshot.png"]);
+ // 刷新截图显示
+ pollShot();
+ } else {
+ appendLog([`[截图] 截图失败: ${result.error || "未知错误"}`]);
+ }
+ } catch (e) {
+ appendLog([`[截图] 截图失败: ${e?.message || e}`]);
+ }
+ });
+
+ // 截图按钮
+ $("btnScreenshot").addEventListener("click", async () => {
+ const deviceId = $("device").value || "";
+ if (!deviceId) {
+ appendLog(["[截图] 请先选择设备"]);
+ return;
+ }
+ try {
+ appendLog(["[截图] 正在截图..."]);
+ const result = await apiPost("/api/screenshot", { device_id: deviceId });
+ if (result.ok) {
+ appendLog(["[截图] 截图成功,已保存到 pic/screenshot.png"]);
+ // 刷新截图显示
+ pollShot();
+ } else {
+ appendLog([`[截图] 截图失败: ${result.error || "未知错误"}`]);
+ }
+ } catch (e) {
+ appendLog([`[截图] 截图失败: ${e?.message || e}`]);
+ }
+ });
await refreshDevices();
await loadConfig();
@@ -1043,4 +1126,4 @@ window.addEventListener("DOMContentLoaded", async () => {
pollShot();
pollReservations();
pollHighValueRooms();
-});
+});
\ No newline at end of file
diff --git a/webui/index.html b/webui/index.html
index 8b9bb64..513e6a2 100644
--- a/webui/index.html
+++ b/webui/index.html
@@ -26,6 +26,12 @@
刷新设备
+