refactor: Remove outdated files and enhance Web GUI functionality

- Deleted obsolete markdown files related to follow tab coordinates testing and results.
- Removed outdated batch scripts for launching the Web GUI.
- Updated `config.json` to improve reservation handling and adjust prize value settings.
- Enhanced logging and error handling in `web_gui.py` and `app.js` for better user experience.
- Added automatic screenshot functionality during Web GUI startup for improved monitoring.
This commit is contained in:
Your Name committed 2025-12-19 03:31:08 +08:00
1 parent b0bd7c72c8
commit 836a31d817
59 files changed
+17232 -6965

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
{
"setup-worktree": [
"npm install"
]
}
-17
View File
@@ -1,17 +0,0 @@
# 更新记录(Changelog)
本项目采用“版本号 + 日期 + 变更点”的方式记录。
## V3.3.1 (2025-12-14)
- 高价值福袋:预约从单个 reserved 改为 reservations 队列(按开奖时间排序),支持队列上限与溢出淘汰最低价值。
- 高价值福袋:队列满时回退到“开奖时间最早”的预约项等待,临近开奖前 N 秒回退参与。
- 预约回退:修复参与窗口内等待不及时(remain<=0 时不再长时间等待,改为 1 秒促发回退参与)。
- 回退定位:回退校验失败不再清空整个队列;增加上下微调搜索以提升回退命中率。
- 回退校验:加入直播间名 OCR 辅助判断(用于更快识别是否回到目标直播间),并更新识别坐标。
- OCR:倒计时识别更稳健(按框坐标排序拼接;默认前两位为分、后两位为秒;详情倒计时分割 OCR 纠错与兜底)。
- Web GUI:统一日志落盘到 logs/unified.log,并增加实时截图卡片轮询 pic/screenshot.png。
- 工具:tools/pick_coords.py 支持手动打开图片(文件选择对话框、菜单“文件→打开…”,Ctrl+O)。
- 工程化:新增 version.py;多个入口脚本启动时打印版本号。
> 注:如果你需要更细颗粒度的提交级记录,可以在此版本下继续追加子条目。
+1231 -198
View File
File diff suppressed because it is too large. Load diff
-14
View File
@@ -1,14 +0,0 @@
@echo off
setlocal
cd /d "%~dp0"
cd /d "c:\Users\12742\Desktop\douyin_guaji-main"
:: 可修改为你需要的端口,例如 8001
set PORT=8000
set PYTHONIOENCODING=utf-8
set PYTHONUNBUFFERED=1
call .venv\Scripts\activate.bat
python web_gui.py
pause
+321 -88
View File
@@ -1,6 +1,7 @@
import subprocess
from datetime import datetime, timedelta
import os
import warnings
# PaddleOCR 3.x 会在初始化/导入时进行模型源连通性检查;在国内网络环境下容易卡住。
# 这里提前设置环境变量,避免启动耗时/卡死。
@@ -8,6 +9,11 @@ os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True")
# 额外抑制 paddle/oneDNN/glog 的冗余信息(INFO/WARNING)
os.environ.setdefault("GLOG_minloglevel", "2")
os.environ.setdefault("OMP_NUM_THREADS", "1")
# 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告)
warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning)
warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning)
import time
from PIL import Image, ImageFilter
import numpy as np
@@ -22,6 +28,9 @@ import base64
from typing import Tuple, Optional
import time as time_module
# 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用
_EXTERNAL_AXF_SCREENSHOT = r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf\pic\screenshot.png"
def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 5) -> bool:
"""安全地替换文件,处理Windows文件锁定问题。
@@ -140,37 +149,85 @@ def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 5) -> bo
return False
def _mirror_screenshot_to_external(src_file: str) -> None:
"""将当前项目下的 screenshot.png 同步一份到外部 axf 目录,便于完整版代码复用。
若外部目录/路径不存在或复制失败,会静默忽略,不影响主流程。
"""
try:
external_path = _EXTERNAL_AXF_SCREENSHOT
if not external_path:
return
external_dir = os.path.dirname(external_path)
if not external_dir:
return
os.makedirs(external_dir, exist_ok=True)
if not os.path.exists(src_file):
return
tmp = external_path + ".tmp"
import shutil
shutil.copyfile(src_file, tmp)
_safe_replace_file(tmp, external_path)
except Exception:
# 任何错误都不应该影响截图主流程
pass
class underlying_operations:
"""底层操作类"""
def __init__(self):
# 关闭文档方向/矫正等重型前处理:我们的截图是手机UI,不是扫描文档。
# 支持延迟初始化(测试流程/只做点击时不需要 OCR)。
self.ocr = None
self.ocr_type = None # 'easyocr' 或 'paddleocr'
if not str(os.environ.get("SKIP_OCR_INIT", "")).strip():
# 在导入和实例化 PaddleOCR 时重定向 stdout/stderr,
# 以抑制其在控制台打印的“Checking connectivity/create model”等信息。
# 优先使用EasyOCR(更快),如果失败则回退到PaddleOCR
# 首先尝试EasyOCR
try:
devnull = open(os.devnull, "w")
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
from paddleocr import PaddleOCR
self.ocr = PaddleOCR(
lang="ch",
ocr_version="PP-OCRv4",
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
)
import easyocr
# 只加载中文和英文,加快初始化速度
self.ocr = easyocr.Reader(['ch_sim', 'en'], gpu=False, verbose=False)
self.ocr_type = 'easyocr'
print("[OCR] 使用 EasyOCR(快速模式)")
try:
devnull.close()
except Exception:
pass
except Exception:
# 若静默初始化失败,保留 None 并允许后续按需初始化,避免阻塞启动。
except Exception as e:
# EasyOCR初始化失败,回退到PaddleOCR
try:
devnull.close()
except Exception:
pass
self.ocr = None
try:
devnull = open(os.devnull, "w")
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
from paddleocr import PaddleOCR
self.ocr = PaddleOCR(
lang="ch",
ocr_version="PP-OCRv4",
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
)
self.ocr_type = 'paddleocr'
print("[OCR] EasyOCR不可用,使用 PaddleOCR(备选方案)")
print(f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr")
try:
devnull.close()
except Exception:
pass
except Exception:
# 若静默初始化失败,保留 None 并允许后续按需初始化,避免阻塞启动。
try:
devnull.close()
except Exception:
pass
self.ocr = None
self.ocr_type = None
logging.disable(logging.DEBUG)
logging.disable(logging.WARNING)
@@ -193,27 +250,48 @@ class underlying_operations:
def _ensure_ocr(self):
if self.ocr is not None:
return
# 优先尝试EasyOCR
try:
devnull = open(os.devnull, "w")
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
from paddleocr import PaddleOCR
self.ocr = PaddleOCR(
lang="ch",
ocr_version="PP-OCRv4",
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
)
import easyocr
self.ocr = easyocr.Reader(['ch_sim', 'en'], gpu=False, verbose=False)
self.ocr_type = 'easyocr'
print("[OCR] 延迟初始化:使用 EasyOCR(快速模式)")
try:
devnull.close()
except Exception:
pass
except Exception:
# EasyOCR失败,回退到PaddleOCR
try:
devnull.close()
except Exception:
pass
self.ocr = None
try:
devnull = open(os.devnull, "w")
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
from paddleocr import PaddleOCR
self.ocr = PaddleOCR(
lang="ch",
ocr_version="PP-OCRv4",
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
)
self.ocr_type = 'paddleocr'
print("[OCR] 延迟初始化:使用 PaddleOCR(备选方案)")
try:
devnull.close()
except Exception:
pass
except Exception:
try:
devnull.close()
except Exception:
pass
self.ocr = None
self.ocr_type = None
def select_device(self):
"""选择需要连接的设备"""
@@ -248,6 +326,41 @@ class underlying_operations:
num = int(num)
return dictdevice[num]
def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]:
"""查找图片路径,支持新旧位置(向后兼容)
Args:
picname: 图片名称(不含扩展名),如 '直播广场', '福袋内容'
for_reading: True=读取(支持新旧位置),False=写入(使用新位置)
Returns:
图片的完整路径,如果找不到且for_reading=True则返回None
"""
base_dir = os.path.dirname(__file__)
pic_base = os.path.join(base_dir, 'pic')
# 运行时必需文件始终在根目录(不需要移动)
runtime_files = {'screenshot', 'cut'}
if picname in runtime_files:
path = os.path.join(pic_base, f'{picname}.png')
return path if (os.path.exists(path) or not for_reading) else None
# OCR图片文件:优先查找新位置(ocr/),然后查找旧位置(根目录)
if for_reading:
# 读取:先查新位置,再查旧位置(向后兼容)
new_path = os.path.join(pic_base, 'ocr', f'{picname}.png')
if os.path.exists(new_path):
return new_path
old_path = os.path.join(pic_base, f'{picname}.png')
if os.path.exists(old_path):
return old_path
return None
else:
# 写入:使用新位置,确保目录存在
ocr_dir = os.path.join(pic_base, 'ocr')
os.makedirs(ocr_dir, exist_ok=True)
return os.path.join(ocr_dir, f'{picname}.png')
def get_screenshot(self, device_id, path='pic'):
"""截图3个adb命令需要2S左右的时间"""
if path == 'pic':
@@ -294,6 +407,7 @@ class underlying_operations:
if _valid_png(tmp_file):
# 使用安全的文件替换函数
if _safe_replace_file(tmp_file, out_file):
_mirror_screenshot_to_external(out_file)
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功")
return True
else:
@@ -337,6 +451,7 @@ class underlying_operations:
if _valid_png(tmp_file):
# 使用安全的文件替换函数
if _safe_replace_file(tmp_file, out_file):
_mirror_screenshot_to_external(out_file)
print("{} 获取屏幕截图".format(timetag))
return True
else:
@@ -349,6 +464,7 @@ class underlying_operations:
try:
with open(tmp_file, 'rb') as src, open(out_file, 'wb') as dst:
dst.write(src.read())
_mirror_screenshot_to_external(out_file)
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)")
return True
except (OSError, PermissionError) as e:
@@ -365,6 +481,7 @@ class underlying_operations:
pass
# 尝试重命名临时文件为目标文件
os.rename(tmp_file, out_file)
_mirror_screenshot_to_external(out_file)
print("{} 获取屏幕截图(通过重命名临时文件)".format(timetag))
return True
except Exception:
@@ -410,36 +527,7 @@ class underlying_operations:
os.system("%s -s %s shell input keyevent 4" % (self._adb(), device_id))
print("点击返回键")
def get_battery_level(self, device_id):
"""获取设备电量信息"""
battery_info = subprocess.Popen("%s -s %s shell dumpsys battery" % (self._adb(), device_id), shell=True,
stdout=subprocess.PIPE)
battery_info_string = battery_info.stdout.read()
battery_info_string = bytes.decode(battery_info_string)
location = re.search('level:', battery_info_string)
if not location:
print("[警告] 无法解析电量信息,返回默认值100")
return 100
span = location.span()
start, end = span
start = end + 1
# 防止越界
max_end = min(len(battery_info_string), start + 10)
for i in range(max_end - start):
end = start + i
if end >= len(battery_info_string) or battery_info_string[end] == "\n":
break
if end <= start:
print("[警告] 无法解析电量信息,返回默认值100")
return 100
battery_level_str = battery_info_string[start:end].strip()
try:
battery_level = int(battery_level_str)
print("设备当前电量为{}".format(battery_level))
return battery_level
except ValueError:
print(f"[警告] 电量解析失败:'{battery_level_str}',返回默认值100")
return 100
# 电量检测方法已删除
def get_device_resolution(self, device_id):
"""获取设备分辨率"""
@@ -505,25 +593,139 @@ class underlying_operations:
print("保存中奖截图失败")
def cut_pic(self, left_up=(0, 63), right_down=(1080, 1620), target='', name=''):
'''裁剪图片,获取需要的区域小图片方便识别'''
if target == '' or target == False:
path = os.path.dirname(__file__) + '/pic'
pic1_path = path + '/screenshot.png'
pic = Image.open(pic1_path)
if name == '':
cut_pic_path = path + '/cut.png'
else:
cut_pic_path = path + '/' + name + '.png'
pic.crop((left_up[0], left_up[1], right_down[0], right_down[1])).save(cut_pic_path)
return True
path_target = os.path.dirname(__file__) + '/pic/' + target
pic1_path = path_target + '/screenshot.png'
pic = Image.open(pic1_path)
if name == '':
cut_pic_path = path_target + '/cut.png'
else:
cut_pic_path = path_target + '/' + name + '.png'
pic.crop((left_up[0], left_up[1], right_down[0], right_down[1])).save(cut_pic_path)
'''裁剪图片,获取需要的区域小图片方便识别
添加了错误处理:
- 检查文件是否存在
- 验证图片完整性
- 重试机制(如果文件损坏)
- 异常处理避免程序崩溃
'''
max_retries = 3
retry_delay = 0.1
for attempt in range(max_retries):
try:
if target == '' or target == False:
path = os.path.dirname(__file__) + '/pic'
pic1_path = path + '/screenshot.png'
# 检查文件是否存在
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
# 验证文件大小(至少应该有一些内容)
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
# 尝试打开并验证图片
try:
pic = Image.open(pic1_path)
# 验证图片完整性(通过访问尺寸属性)
_ = pic.size
# 确保图片已加载
pic.load()
except (SyntaxError, IOError, OSError) as e:
# 图片损坏,重试或返回False
if attempt < max_retries - 1:
print(f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}")
time_module.sleep(retry_delay * (attempt + 1))
continue
# 最后一次尝试失败,让外层异常处理
raise
if name == '':
cut_pic_path = path + '/cut.png'
else:
# 使用新的路径查找方法(写入到新位置ocr/)
cut_pic_path = self._find_pic_path(name, for_reading=False)
# 验证裁剪坐标有效性
width, height = pic.size
left, top = left_up
right, bottom = right_down
if left < 0 or top < 0 or right > width or bottom > height or left >= right or top >= bottom:
raise ValueError(f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}")
pic.crop((left, top, right, bottom)).save(cut_pic_path)
return True
else:
path_target = os.path.dirname(__file__) + '/pic/' + target
pic1_path = path_target + '/screenshot.png'
# 检查文件是否存在
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
# 验证文件大小
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
# 尝试打开并验证图片
try:
pic = Image.open(pic1_path)
_ = pic.size
pic.load()
except (SyntaxError, IOError, OSError) as e:
# 图片损坏,重试或返回False
if attempt < max_retries - 1:
print(f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}")
time_module.sleep(retry_delay * (attempt + 1))
continue
# 最后一次尝试失败,让外层异常处理
raise
if name == '':
cut_pic_path = path_target + '/cut.png'
else:
cut_pic_path = path_target + '/' + name + '.png'
# 验证裁剪坐标有效性
width, height = pic.size
left, top = left_up
right, bottom = right_down
if left < 0 or top < 0 or right > width or bottom > height or left >= right or top >= bottom:
error_msg = f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}"
if attempt == max_retries - 1:
print(f"[错误] {error_msg}")
return False
continue
pic.crop((left, top, right, bottom)).save(cut_pic_path)
return True
except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e:
# 最后一次尝试失败,打印错误信息
if attempt == max_retries - 1:
error_msg = f"[错误] 裁剪图片失败 (尝试 {max_retries} 次): {e}"
print(error_msg)
print(f" 源文件: {pic1_path}")
print(f" 目标文件: {cut_pic_path if 'cut_pic_path' in locals() else 'N/A'}")
# 不抛出异常,返回 False 让调用者处理
return False
# 继续重试
continue
except Exception as e:
# 其他未知异常
if attempt == max_retries - 1:
print(f"[错误] 裁剪图片时发生未知错误: {e}")
return False
continue
return False
def analyse_pic_word(self, picname='', change_color=0):
"""识别图像中的文字, change_color=1或2为不同的二值化模式,其他不做处理
@@ -536,11 +738,15 @@ class underlying_operations:
if self.ocr is None:
return ''
path = os.path.dirname(__file__) + '/pic'
if picname == '':
# cut.png 始终在根目录
path = os.path.dirname(__file__) + '/pic'
pic_path = path + '/cut.png'
else:
pic_path = path + '/' + picname + '.png'
# 使用新的路径查找方法(支持新旧位置)
pic_path = self._find_pic_path(picname, for_reading=True)
if not pic_path:
return ''
# 检查文件是否存在
if not os.path.exists(pic_path):
@@ -568,9 +774,10 @@ class underlying_operations:
# 性能优化:先用原尺寸跑一次 OCR;只有识别为空时才放大重试。
w, h = img.size
# 优化:对于很小的图片,直接放大,避免浪费一次OCR调用
if max(w, h) < 100:
# 提高阈值:对于UI文字(如"直播广场"),即使是172x58这样稍大的尺寸也需要放大
if max(w, h) < 200:
try:
scale = max(2, 200 // max(w, h, 1)) # 至少放大到200像素
scale = max(2, 300 // max(w, h, 1)) # 至少放大到300像素,提高小文字识别率
img = img.resize((w * scale, h * scale), Image.BICUBIC)
w, h = img.size
except Exception:
@@ -584,17 +791,28 @@ class underlying_operations:
img_sharpened = img.filter(ImageFilter.UnsharpMask(radius=1, percent=150, threshold=3))
# 再增强对比度(轻微增强,避免过度处理)
enhancer = ImageEnhance.Contrast(img_sharpened)
img_enhanced = enhancer.enhance(1.15) # 增强15%对比度
# 根据图片尺寸动态调整对比度:小图片需要更强的对比度
contrast_factor = 1.25 if max(w, h) < 300 else 1.15 # 小图片增强25%对比度
img_enhanced = enhancer.enhance(contrast_factor)
img1 = img_enhanced
except Exception:
# 如果增强失败,回退到原来的锐化
img1 = img.filter(ImageFilter.SHARPEN)
img_np = np.array(img1)
result = self.ocr.ocr(img_np)
if result == [None]:
return ''
text = self.extract_ocr_content(result)
# 根据OCR类型调用不同的识别方法
# 如果没有设置ocr_type,默认使用PaddleOCR格式(向后兼容)
if getattr(self, 'ocr_type', None) == 'easyocr':
# EasyOCR: readtext返回格式为 [(bbox, text, confidence), ...]
result = self.ocr.readtext(img_np)
text = self.extract_ocr_content(result)
else:
# PaddleOCR: ocr返回格式为 [[...]] 或 [...]
result = self.ocr.ocr(img_np)
if result == [None]:
return ''
text = self.extract_ocr_content(result)
# 如果识别为空且图片较小,尝试放大重试(精度优化:使用更好的放大算法和增强处理)
if (not text) and max(w, h) <= 1200:
@@ -610,15 +828,25 @@ class underlying_operations:
img2 = img2_enhanced
except Exception:
img2 = img2.filter(ImageFilter.SHARPEN)
result2 = self.ocr.ocr(np.array(img2))
if result2 != [None]:
text = self.extract_ocr_content(result2)
result = result2
if getattr(self, 'ocr_type', None) == 'easyocr':
result2 = self.ocr.readtext(np.array(img2))
text2 = self.extract_ocr_content(result2)
if text2:
text = text2
result = result2
else:
result2 = self.ocr.ocr(np.array(img2))
if result2 != [None]:
text2 = self.extract_ocr_content(result2)
if text2:
text = text2
result = result2
except Exception:
pass
# 对关键字段做轻量级调试输出:图片很清楚但识别为空时,通常是返回结构变化或未检出文本
if picname in ("fudai_content", "fudai_countdown") and not text:
if picname in ("福袋内容", "福袋倒计时") and not text:
try:
if isinstance(result, list) and result and isinstance(result[0], dict):
print(f"OCR调试({picname}): result[0] keys={list(result[0].keys())}")
@@ -634,8 +862,13 @@ class underlying_operations:
ocr_result = content
def _extract_text_from_item(item):
# 兼容旧格式:[box, (text, score)]
# 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence)
if isinstance(item, (list, tuple)) and len(item) >= 2:
# EasyOCR格式:item = (bbox, text, confidence),text在索引1
if isinstance(item[1], str):
return item[1]
# 兼容旧格式:[box, (text, score)]
second = item[1]
if isinstance(second, (list, tuple)) and len(second) >= 1:
if isinstance(second[0], str):
@@ -685,9 +918,10 @@ class underlying_operations:
def _extract_xy_from_item(item):
"""尽力从 OCR item 中提取用于排序的 (y, x)。无法提取则返回 None。"""
try:
# 旧格式:item = [box, (text, score)],box 为 4 点坐标
if isinstance(item, (list, tuple)) and len(item) >= 1:
box = item[0]
# EasyOCR格式:bbox = [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]
# PaddleOCR格式:box 为 4 点坐标列表
if isinstance(box, (list, tuple)) and box:
xs = []
ys = []
@@ -1371,4 +1605,3 @@ class underlying_operations:
return False
time.sleep(0.2)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

+50 -136
View File
@@ -1,155 +1,69 @@
{
"log_unified_enabled": true,
"log_unified_path": "logs/unified.log",
"webgui_log_capacity": 2000,
"contains_want": [],
"contains_not_want": [
"袜子1"
],
"min_prize_value_yuan": 199.7,
"needswitch": true,
"wait_minutes": 5,
"min_prize_value_yuan": 200.0,
"min_participants": 0,
"max_participants": 0,
"skip_if_countdown_lt_seconds": 5,
"reset_after_swipes_enabled": true,
"reset_after_swipes": 30,
"auto_join_fansclub": true,
"fansclub_fail_action": "switch",
"high_value_fudai_enabled": true,
"high_value_fudai_threshold_yuan": 500,
"high_value_fudai_join_ahead_seconds": 90,
"high_value_fudai_max_swipe_back": 0,
"high_value_fudai_max_reservations": 4,
"high_value_fudai_threshold_yuan": 500.0,
"high_value_fudai_join_ahead_seconds": 120,
"high_value_fudai_max_swipe_back": 35,
"high_value_fudai_max_reservations": 3,
"high_value_fudai_after_action": "continue",
"fudai_abnormal_reopen_delay_seconds": 1.2,
"fudai_quiet_hours_enabled": true,
"fudai_quiet_start_hour": 2,
"fudai_quiet_end_hour": 7,
"no_fudai_watchdog_enabled": false,
"reset_after_swipes": 15,
"yanghao_enabled": false,
"high_value_room_revisit_enabled": false,
"high_value_room_revisit_only_current_run": false,
"reservation_back_verify_enabled": false,
"reservation_back_swipe_delay": 0.6,
"reservation_preempt_min_value": 0.0,
"fudai_find_max_attempts": 10,
"fudai_icon_retry_delay_seconds": 0.6,
"fudai_icon_max_wait_seconds": 5.0,
"yanghao_recommend_duration_seconds": 216,
"yanghao_recommend_interval_seconds": 600,
"yanghao_enable_actions": false,
"yanghao_like_prob": 0.0,
"yanghao_fav_prob": 0.0,
"yanghao_like_icon_x": 988,
"yanghao_like_icon_y": 1290,
"yanghao_fav_icon_x": 985,
"yanghao_fav_icon_y": 1637,
"yanghao_like_prob": 1.0,
"yanghao_fav_prob": 0.85,
"yanghao_comment_prob": 1.0,
"yanghao_icon_roi_size": 240,
"yanghao_icon_match_threshold": 0.72,
"yanghao_step_screenshot": false,
"yanghao_like_roi_offset_x": 0,
"yanghao_like_roi_offset_y": -50,
"yanghao_fav_roi_offset_x": 40,
"yanghao_fav_roi_offset_y": 0,
"yanghao_icon_roi_size": 240,
"yanghao_icon_match_threshold": 0.72,
"contains_want": [],
"contains_not_want": [
"袜子"
],
"fudai_quiet_hours_enabled": true,
"fudai_quiet_start_hour": 2,
"fudai_quiet_end_hour": 6,
"yanghao_enabled": false,
"yanghao_enable_actions": false,
"yanghao_like_icon_x": 0,
"yanghao_like_icon_y": -1,
"yanghao_fav_icon_x": -1,
"yanghao_fav_icon_y": 0,
"yanghao_like_template_path": "assets/like.png",
"yanghao_fav_template_path": "assets/fav.png",
"yanghao_step_screenshot": false,
"yanghao_comment_prob": 0.0,
"yanghao_comment_btn_x": 981,
"yanghao_comment_btn_y": 1399,
"yanghao_comment_input_x": 250,
"yanghao_comment_input_y": 2218,
"yanghao_comment_send_x": 906,
"yanghao_comment_send_y": 1298,
"yanghao_comment_close_x": 586,
"yanghao_comment_close_y": 385,
"yanghao_comment_texts": [
"????????????",
"??????????????????????????????",
"?????????????????????????????????????????????",
"???????????????????????????????????????",
"???????????????????????????",
"??????????????????????????????????????????",
"???????????????????????????",
"?????????????????????",
"??????????????????",
"????????????????????????",
"????????????????????????",
"???????????????????????????",
"????????????????????????????????????",
"????????????????????????",
"????????????????????????",
"????????????????????????????????????",
"???????????????????????????",
"?????????????????????",
"????????????-1",
"????????????",
"??????????????????????????????????????????",
"?????????????????????????????????????????????",
"??????????????????????????????????????????????????????????????????????????????????????????",
"????????????????????????????????????",
"?????????????????????????????????????????????",
"?????????????????????????????????????????????????????????????????????",
"?????????????????????????????????????????????",
"??????????????????????????????????????????",
"????????????????????????????????????????????????",
"???????????????????????????????????????",
"????????????",
"?????????????????????????????????",
"????????????????????????",
"???????????????????????????????????????",
"??????????????????????????????????????????????????????????????????",
"??????????????????",
"???????????????????????????????????????",
"????????????",
"???????????????????????????",
"????????????????????????????????????????????????",
"???????????????????????????",
"?????????????????????????????????",
"??????????????????",
"????????????????????????",
"?????????????????????????????????????????????",
"????????????????????????????????????",
"????????????????????????",
"?????????",
"????????????",
"????????????",
"DJ???????????????????????????????????????????????????",
"???????????????????????????",
"?????????????????????????????????????????????",
"???????????????????????????????????????????????????????????????????????????",
"???????????????????????????",
"??????????????????????????????",
"???????????????????????????",
"???????????????????????????",
"?????????????????????????????????",
"???XX???????????????",
"???????????????????????????",
"??????????????????",
"??????????????????",
"???????????????????????????",
"???????????????????????????????????????",
"????????????????????????",
"??????????????????????????????",
"??????????????????",
"??????????????????????????????",
"?????????????????????????????????"
],
"yanghao_after_dwell_swipe_direction": "up",
"yanghao_after_dwell_swipe_distance_px": 900,
"yanghao_like_keywords": [
"???",
"??????",
"Like"
],
"yanghao_fav_keywords": [
"??????",
"????????????",
"????????????",
"Favorite"
],
"yanghao_fallback_close_x": 1030,
"yanghao_fallback_close_y": 120,
"yanghao_fallback_live_x": 718,
"yanghao_fallback_live_y": 169,
"yanghao_fallback_enter_live_x": 119,
"yanghao_fallback_enter_live_y": 345,
"reset_after_swipes_enabled": true,
"high_value_room_revisit_enabled": false,
"high_value_room_revisit_only_current_run": false,
"reservation_back_verify_enabled": false,
"fudai_icon_max_wait_seconds": 10,
"fudai_icon_adaptive_enabled": false,
"fudai_find_max_attempts": 5,
"reservation_preempt_min_value": 0,
"reservation_back_swipe_delay": 0.6
"yanghao_comment_btn_x": 0,
"yanghao_comment_btn_y": -1,
"yanghao_comment_input_x": 0,
"yanghao_comment_input_y": 0,
"yanghao_comment_send_x": 0,
"yanghao_comment_send_y": -1,
"yanghao_comment_close_x": 0,
"yanghao_comment_close_y": 0,
"yanghao_comment_texts": [],
"yanghao_like_keywords": [],
"yanghao_fav_keywords": [],
"stage_diag_max_time": 15.0,
"stage_diag_max_step_time": 4.0,
"live_room_match_threshold": 0.7
}
+500
View File
@@ -0,0 +1,500 @@
from __future__ import annotations
"""
Functional fudai detection (WebGUI version)
===========================================
This module reimplements the key detection helpers used in `douyin_fudai`:
- check_detail_height(analyser) -> int
- check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False) -> bool
- check_in_fudai_detail(analyser) -> bool
The logic is adapted from the original `axf/douyin_detection.py`, with extra
defensive checks to avoid crashes when certain analyser attributes are missing.
"""
from typing import Any
import os
import time
from PIL import Image
def _ensure_detection_cache(analyser: Any) -> None:
"""Ensure analyser has a simple detection cache structure."""
if not hasattr(analyser, "_detection_cache"):
analyser._detection_cache = {}
if not hasattr(analyser, "_detection_cache_ttl"):
analyser._detection_cache_ttl = 2.0
def check_detail_height(analyser: Any) -> int:
"""Detect how many tasks are required in the fudai detail popup.
Returns:
0 / 1 / 2 / 3 (number of tasks).
"""
path = os.path.join(os.path.dirname(__file__), "pic")
pic1_path = os.path.join(path, "screenshot.png")
pic = None
for attempt in range(3):
try:
pic = Image.open(pic1_path)
pic.load() # force load to catch truncated files early
break
except Exception:
if attempt < 2:
try:
analyser.operation.get_screenshot(analyser.device_id)
analyser.operation.delay(0.2)
except Exception:
pass
pic = None
if pic is None:
try:
analyser._log_kv("检测", "读取截图失败,默认不需要任务", level="WARN")
except Exception:
pass
return 0
pic_new = pic.convert("RGBA")
pix = pic_new.load()
width, height = pic_new.size
# X of “参与” button
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
x = 536 * rx // 1080
if not (0 <= x < width):
return 0
# (base_y, y_pianyi_offset, task_count)
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
except Exception:
y_pianyi_val = 0
check_points = [
(983, 0, 2),
(983, y_pianyi_val, 2),
(983, -y_pianyi_val, 2),
(883, 0, 3),
(883, y_pianyi_val, 3),
(883, -y_pianyi_val, 3),
(1058, 0, 1),
(1058, y_pianyi_val, 1),
(1058, -y_pianyi_val, 1),
]
def _check_pixel_color(y_coord: int) -> bool:
if not (0 <= y_coord < height):
return False
try:
p = pix[x, y_coord]
if not (isinstance(p, tuple) and len(p) >= 3):
return False
r, g, b = int(p[0]), int(p[1]), int(p[2])
return 28 <= r <= 40 and 32 <= g <= 42 and 76 <= b <= 86
except Exception:
return False
try:
for base_y, dy, task_count in check_points:
y = base_y * ry // 2400 + dy
if _check_pixel_color(y):
try:
analyser._log_kv("检测", f"识别到福袋任务数量:{task_count}个", task_count=task_count)
except Exception:
pass
return task_count
except Exception:
pass
# Optional robot-check path from original implementation
try:
if hasattr(analyser, "check_have_robot_analyse") and analyser.check_have_robot_analyse():
analyser.deal_robot_analyse()
except Exception:
pass
try:
analyser._log_kv("检测", "识别福袋任务数量:0个(不需要任务)", level="INFO", task_count=0)
except Exception:
pass
return 0
def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool = False):
"""Check whether the live-room screen currently has a fudai icon.
仅使用像素/颜色特征进行检测(无位置过滤、无 OCR):
- 先用 numpy/逐像素扫描找到疑似图标位置;
- 再通过颜色统计(粉紫/粉蓝 vs 橙色券)过滤误报。
"""
func_start = time.time()
path = os.path.join(os.path.dirname(__file__), "pic")
pic1_path = os.path.join(path, "screenshot.png")
attempt_count = 0 # 仅用于日志记录,不影响循环控制
try:
retry_delay_s = float(getattr(analyser, "fudai_icon_retry_delay_seconds", 0.3) or 0.3)
except Exception:
retry_delay_s = 0.3
try:
max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 2.5) or 2.5)
except Exception:
max_wait_s = 2.5
if retry_delay_s < 0.15:
retry_delay_s = 0.15
if max_wait_s < 0:
max_wait_s = 0.0
try:
analyser._log_kv("[找福袋图标] 开始", f"最大等待时间{max_wait_s}秒,复用截图={screenshot_ready}")
except Exception:
pass
detected_any = False
# 完全基于时间限制,不使用次数限制
while (time.time() - func_start) < max_wait_s:
attempt_start = time.time()
attempt_count += 1
# Reuse external screenshot only on first attempt if provided
if not (screenshot_ready and attempt_count == 1):
try:
analyser._shot_and_diagnose("找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False)
except Exception:
pass
try:
pic = Image.open(pic1_path)
pic.load()
except Exception:
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
pass
# 检查是否还有剩余时间
elapsed = time.time() - func_start
if elapsed < max_wait_s:
# 计算剩余时间,但至少等待 retry_delay_s
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
continue
pic_new = pic.convert("RGBA")
detected = False
detected_x = None
# Resolution ratios
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
except Exception:
y_pianyi_val = 0
# First try numpy-accelerated scan over a horizontal band
numpy_scan_start = time.time()
try:
import numpy as _np
# 优惠券一般在左侧,这里将扫描区域整体右移:
# 原范围约为 x∈[41,410],现在改为 x∈[220,960](1080 基准),
# 既避开左侧券位,又覆盖更多右侧可能出现福袋的位置。
# Y值检测范围扩大:从348到448并行检测(基于1080x2400分辨率)
x1 = max(0, 220 * rx // 1080)
x2 = min(pic_new.size[0], 960 * rx // 1080)
y_top_base = 348 * ry // 2400 + y_pianyi_val
y_bottom_base = 448 * ry // 2400 + y_pianyi_val
y_top = max(0, y_top_base)
y_bottom = min(pic_new.size[1], y_bottom_base)
if x1 < x2 and y_top < y_bottom:
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
arr = _np.array(roi)
if arr.size > 0:
r = arr[:, :, 0]
g = arr[:, :, 1]
b = arr[:, :, 2]
mask_center = (
(r >= 190)
& (r <= 206)
& (g >= 173)
& (g <= 196)
& (b >= 234)
& (b <= 250)
)
cols = _np.sum(mask_center, axis=0)
valid_cols = cols >= 2
if valid_cols.any():
col_idx = int(_np.argmax(valid_cols))
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
detected = True
detected_any = True
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
except Exception:
detected = False
numpy_scan_elapsed = time.time() - numpy_scan_start
if numpy_scan_elapsed > 0.01:
try:
elapsed_time = time.time() - func_start
analyser._log_step_time(
f"numpy像素扫描(已用时{elapsed_time:.2f}秒)", numpy_scan_start, {"结果": "命中" if detected else "未命中"}
)
except Exception:
pass
# Fallback: per-pixel scan(第一步:只做颜色/像素级粗检测)
if not detected:
pixel_scan_start = time.time()
try:
pix = pic_new.load()
pic_width, pic_height = pic_new.size
# 与 numpy 扫描保持一致:整体右移,并尽量覆盖右侧大部分区域
# Y值检测范围扩大:从348到448并行检测(基于1080x2400分辨率)
scan_x_start = 220 * rx // 1080
scan_x_end = min(960 * rx // 1080, pic_width)
scan_y_start_base = 348 * ry // 2400 + y_pianyi_val
scan_y_end_base = 448 * ry // 2400 + y_pianyi_val
scan_y_start = max(0, scan_y_start_base)
scan_y_end = min(pic_height, scan_y_end_base)
# 并行检测348到448范围内的所有Y值
for check_y in range(scan_y_start, scan_y_end):
if not (0 <= check_y < pic_height):
continue
for x_scaled in range(scan_x_start, scan_x_end):
try:
px = pix[x_scaled, check_y]
if (
len(px) >= 3
and 190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
):
detected_x = int(x_scaled * 1080.0 / max(1, rx))
detected = True
detected_any = True
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
break
except Exception:
continue
if detected:
break
except Exception:
pass
pixel_scan_elapsed = time.time() - pixel_scan_start
if pixel_scan_elapsed > 0.01:
try:
elapsed_time = time.time() - func_start
analyser._log_step_time(
f"逐像素扫描(已用时{elapsed_time:.2f}秒)", pixel_scan_start, {"结果": "命中" if detected else "未命中"}
)
except Exception:
pass
if detected and detected_x is not None:
# 颜色分布过滤:在候选区域统计“粉紫/粉蓝”(福袋) vs “橙色”(券) 像素数量
try:
base_y = 403 * ry // 2400 + y_pianyi_val
cx1 = max(0, int((detected_x - 45) * rx / 1080))
cx2 = min(pic_new.size[0], int((detected_x + 45) * rx / 1080))
cy1 = max(0, base_y - 45)
cy2 = min(pic_new.size[1], base_y + 45)
fudai_like = 0
coupon_like = 0
if cx1 < cx2 and cy1 < cy2:
pix2 = pic_new.load()
step = max(1, (cx2 - cx1) // 24) # 下采样防止太慢
for yy in range(cy1, cy2, step):
for xx in range(cx1, cx2, step):
try:
p = pix2[xx, yy]
except Exception:
continue
if not (isinstance(p, tuple) and len(p) >= 3):
continue
r, g, b = int(p[0]), int(p[1]), int(p[2])
# 福袋:粉/紫/粉蓝:R 高、B 也高,G 中等
if r >= 200 and b >= 210 and 80 <= g <= 230:
fudai_like += 1
# 券:偏黄橙色:R 高、G 中等、B 明显偏低
if r >= 200 and 120 <= g <= 230 and b <= 180:
coupon_like += 1
# 如果“橙券像素”明显多于“粉袋像素”,判定为优惠券,丢弃
if coupon_like > fudai_like * 1.2:
try:
analyser._log_kv(
"[找福袋图标] 颜色过滤未通过",
"区域颜色更接近优惠券,视为非福袋",
fudai_like=fudai_like,
coupon_like=coupon_like,
x=detected_x,
)
except Exception:
pass
detected = False
detected_x = None
except Exception:
detected = False
detected_x = None
if detected and detected_x is not None:
# store last X if analyser expects it(此时已通过颜色过滤)
try:
analyser._last_fudai_icon_x = detected_x
except Exception:
pass
break
# 检查是否还有剩余时间
elapsed = time.time() - func_start
if elapsed < max_wait_s:
# 计算剩余时间,但至少等待 retry_delay_s
remaining_time = max_wait_s - elapsed
sleep_time = min(retry_delay_s, remaining_time)
if sleep_time > 0:
try:
analyser.operation.delay(sleep_time)
except Exception:
time.sleep(sleep_time)
try:
total_elapsed = time.time() - func_start
analyser._log_kv(
"[找福袋图标] 结束",
"检测完成",
detected=bool(detected_any and detected_x is not None),
elapsed_ms=int(total_elapsed * 1000),
)
except Exception:
pass
# 与原始 fudai.py 的 check_have_fudai 行为保持一致:
# 返回福袋图标的 x 坐标(1080 基准坐标),未找到返回 False。
return int(detected_x) if detected_x is not None else False
def check_in_fudai_detail(analyser: Any) -> bool:
"""Detect whether we are currently on the fudai detail page."""
_ensure_detection_cache(analyser)
cache_key = "check_in_fudai_detail"
now = time.time()
cached = analyser._detection_cache.get(cache_key)
if cached:
cached_ts, cached_result = cached
ttl = float(getattr(analyser, "_detection_cache_ttl", 2.0) or 2.0)
if (now - cached_ts) < ttl:
return bool(cached_result)
path = os.path.join(os.path.dirname(__file__), "pic")
pic1_path = os.path.join(path, "screenshot.png")
try:
try:
pic0 = Image.open(pic1_path)
pic0.load()
pic = pic0.convert("RGBA")
except Exception:
try:
analyser.operation.get_screenshot(analyser.device_id)
pic0 = Image.open(pic1_path)
pic0.load()
pic = pic0.convert("RGBA")
except Exception:
analyser._detection_cache[cache_key] = (now, False)
return False
pix = pic.load()
width, height = pic.size
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
except Exception:
y_pianyi_val = 0
x = 536 * rx // 1080
if not (0 <= x < width):
analyser._detection_cache[cache_key] = (now, False)
return False
base_ys = (883, 983, 1058)
offsets = (0, y_pianyi_val, -y_pianyi_val)
for base_y in base_ys:
y0 = base_y * ry // 2400
for dy in offsets:
y = y0 + dy
if not (0 <= y < height):
continue
try:
p = pix[x, y]
if not (isinstance(p, tuple) and len(p) >= 3):
continue
r, g, b = int(p[0]), int(p[1]), int(p[2])
if 30 <= r <= 38 and 34 <= g <= 40 and 78 <= b <= 84:
analyser._detection_cache[cache_key] = (now, True)
return True
except Exception:
continue
except Exception:
pass
# OCR fallback (lighter version of original implementation)
try:
try:
min_interval = float(getattr(analyser, "detail_ocr_check_min_interval_seconds", 8.0) or 0.0)
except Exception:
min_interval = 8.0
last = float(getattr(analyser, "_last_detail_ocr_check_ts", 0.0) or 0.0)
if min_interval > 0 and (now - last) < min_interval:
analyser._detection_cache[cache_key] = (now, False)
return False
analyser._last_detail_ocr_check_ts = now
analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮")
t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
keywords = ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看")
if not t_btn or not any(k in t_btn for k in keywords):
t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "")
if any(k in t_btn for k in keywords):
analyser._detection_cache[cache_key] = (now, True)
return True
except Exception:
pass
analyser._detection_cache[cache_key] = (now, False)
return False
+199
View File
@@ -0,0 +1,199 @@
from __future__ import annotations
"""
Flow control main helpers (本地模块化实现,基础版)
================================================
当前只实现与你"基础抢福袋、不启用预约"相关的核心流程:
- handle_stage_after_diagnosis:记录阶段信息(暂不做复杂跳转)
- find_and_open_fudai_detail:通过像素检测福袋图标并点击打开详情
- handle_no_fudai_situation:在没有福袋时做简单的等待/上滑切换
- filter_fudai_detail:根据 config.json 对福袋进行基础筛选
"""
from typing import Any, List, Tuple
import time
from douyin_detection import check_have_fudai_with_ready_screenshot
from douyin_fudai_core import should_skip_fudai_by_config
def handle_stage_after_diagnosis(
analyser: Any,
stage: str,
seen: str,
loop_count: int,
) -> bool:
"""记录阶段诊断结果,当前不改变主流程走向。"""
try:
analyser._log_kv(
"流程",
"handle_stage_after_diagnosis",
stage=stage,
seen=seen,
loop_count=loop_count,
)
except Exception:
pass
return False
def find_and_open_fudai_detail(
analyser: Any,
room_pos_ref: List[int],
) -> bool:
"""在当前直播间查找福袋图标并尝试点击打开详情(基础版,不做预约)。"""
device_id = getattr(analyser, "device_id", "")
# 1. 利用像素检测福袋图标的 X 坐标(1080 基准)
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False)
if not x:
try:
analyser._log_kv("流程", "find_and_open_fudai_detail:未检测到福袋图标", x=int(x or 0))
except Exception:
pass
return False
# 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度)
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
base_y = 403 # 与检测时使用的同一水平线附近
click_x = int(x * rx / 1080)
click_y = int(base_y * ry / 2400)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标并点击",
fudai_x=int(x),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 优先走底层 operation.click,失败再尝试 analyser.click
try:
analyser.operation.click(device_id, click_x, click_y)
analyser.operation.delay(1.0)
return True
except Exception:
try:
analyser.click(x, base_y)
return True
except Exception:
return False
def handle_no_fudai_situation(
analyser: Any,
x: int,
swipe_times: int,
wait_times_ref: List[int],
needswitch: bool,
reservation_focus_until_ts: float,
reservations: list,
room_pos: int,
post_switch_delay_s: float,
swipe_up_switch_callback,
swipe_down_back_callback,
sort_reservations_callback,
clear_reservations_callback,
write_state_callback,
back_to_list_callback,
into_list_callback,
reservation_focus_until_ts_ref: List[float],
reset_to_list_after_reservations_ref: List[bool],
swipe_times_ref: List[int],
) -> bool:
"""当前直播间没有福袋时的基础处理:稍微等待,然后按需要上滑切换。"""
try:
analyser._log_kv(
"流程",
"handle_no_fudai_situation",
x=x,
swipe_times=swipe_times,
room_pos=room_pos,
reservations=len(reservations),
)
except Exception:
pass
# 简单策略:轻微等待 + 上滑切换
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
if needswitch and swipe_up_switch_callback:
swipe_up_switch_callback()
try:
analyser.operation.delay(post_switch_delay_s or 1.2)
except Exception:
time.sleep(post_switch_delay_s or 1.2)
return False
def filter_fudai_detail(
analyser: Any,
detail: Tuple,
x: int,
needswitch: bool,
post_switch_delay_s: float,
close_detail_callback,
swipe_up_switch_callback,
add_reservation_callback,
) -> bool:
"""福袋详情过滤逻辑:根据 config.json 中的配置决定是否丢弃该福袋。
返回:
True 表示"已丢弃/已处理",上层不再参与;
False 表示"不过滤",可继续参与抽奖。
"""
skip, reason = should_skip_fudai_by_config(analyser, detail)
try:
content = str(detail[0] or "") if isinstance(detail, tuple) and len(detail) >= 1 else ""
analyser._log_kv(
"流程",
"filter_fudai_detail",
x=x,
needswitch=needswitch,
skip=int(bool(skip)),
reason=reason,
content_preview=content[:60] if content else "",
)
except Exception:
pass
if not skip:
# 返回 False 表示"不丢弃",保留该福袋
return False
# 需要丢弃:先关闭详情
try:
close_detail_callback(analyser)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
# 如允许切换,则顺便切到下一个直播间
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
analyser.operation.delay(post_switch_delay_s or 1.2)
except Exception:
try:
time.sleep(post_switch_delay_s or 1.2)
except Exception:
pass
return True
return False
+523 -5859
View File
File diff suppressed because it is too large. Load diff
+744
View File
@@ -0,0 +1,744 @@
from __future__ import annotations
import re
import time
from typing import Tuple, Any
from douyin_utils import normalize_countdown_text, extract_prize_value_yuan
def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]:
"""获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。"""
def _parse_mm_ss(text: str):
m = re.search(r"(\d{1,2})[::](\d{2})", str(text or ""))
if not m:
return None
try:
return int(m.group(1)), int(m.group(2))
except Exception:
return None
def _extract_2digits(text: str) -> str:
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
if len(digits) >= 2:
return digits[:2]
if len(digits) == 1:
return "0" + digits
return ""
def _read_countdown_split(box: tuple[int, int, int, int]) -> str:
"""将倒计时区域按三等分切成“分钟段/秒段/后开奖段”,分别OCR分钟与秒,组合为 mm:ss。"""
try:
x1, y1, x2, y2 = box
w = max(1, int(x2 - x1))
seg = max(1, w // 3)
# 前 1/3:分钟;中 1/3:秒(第三段通常包含“后开奖”)
analyser.cut_pic(x1, y1, x1 + seg, y2, "", "福袋倒计时_分钟", analyser.y_pianyi)
analyser.cut_pic(x1 + seg, y1, x1 + 2 * seg, y2, "", "福袋倒计时_秒", analyser.y_pianyi)
mm_raw = analyser.operation.analyse_pic_word("福袋倒计时_分钟", 0)
ss_raw = analyser.operation.analyse_pic_word("福袋倒计时_秒", 0)
mm = _extract_2digits(mm_raw)
ss = _extract_2digits(ss_raw)
if mm and ss:
return f"{mm}:{ss}"
except Exception:
return ""
return ""
def _extract_participants_and_clean(text: str):
if not text:
return 0, 0, ""
compact = re.sub(r"\s+", "", str(text))
# 例如:共1份1173人已参与
copies = 0
participants = 0
m = re.search(r"共(\d+)份", compact)
if m:
copies = int(m.group(1))
m = re.search(r"(\d+)人已参与", compact)
if m:
participants = int(m.group(1))
# 清理掉份数/参与人数等尾巴,避免干扰关键词匹配
cleaned = re.sub(r"共\d+份", "", compact)
cleaned = re.sub(r"\d+人已参与", "", cleaned)
return participants, copies, cleaned
countdown_box = None
if renwu == 2: # 如果是2个任务的
# 优化:稍微缩小宽度(1000->980),增加高度(1460->1470),减少右侧干扰,确保内容完整
analyser.cut_pic(390, 1240, 980, 1470, "", "福袋内容", analyser.y_pianyi) # 福袋内容详情
# 优化:稍微扩大高度(1220->1230),确保包含完整的"后开奖"文字
countdown_box = (390, 1110, 690, 1230)
analyser.cut_pic(*countdown_box, "", "福袋倒计时", analyser.y_pianyi) # 完整福袋详情倒计时
# 优化:增加高度(1560->1580),确保包含"元"等单位文字
analyser.cut_pic(390, 1460, 1000, 1580, "", "福袋价值", analyser.y_pianyi) # 奖品价值/价格
elif renwu == 1: # 如果是1个任务的
# 优化:稍微缩小宽度,增加高度,减少干扰
analyser.cut_pic(390, 1300, 980, 1530, "", "福袋内容", analyser.y_pianyi) # 福袋内容详情
# 优化:稍微扩大高度,确保完整
countdown_box = (390, 1180, 690, 1300)
analyser.cut_pic(*countdown_box, "", "福袋倒计时", analyser.y_pianyi) # 完整福袋详情倒计时
# 优化:增加高度,包含单位
analyser.cut_pic(390, 1520, 1000, 1630, "", "福袋价值", analyser.y_pianyi) # 奖品价值/价格
elif renwu == 3: # 如果是3个任务的
# 优化:稍微缩小宽度,增加高度
analyser.cut_pic(390, 1160, 980, 1390, "", "福袋内容", analyser.y_pianyi) # 福袋内容详情
# 优化:稍微扩大高度
countdown_box = (390, 1010, 690, 1130)
analyser.cut_pic(*countdown_box, "", "福袋倒计时", analyser.y_pianyi) # 完整福袋详情倒计时
# 优化:增加高度
analyser.cut_pic(390, 1380, 1000, 1490, "", "福袋价值", analyser.y_pianyi) # 奖品价值/价格
else:
# 优化:稍微缩小宽度,增加高度
analyser.cut_pic(390, 1600, 980, 1830, "", "福袋内容", analyser.y_pianyi) # 福袋内容详情
# 优化:稍微扩大高度
countdown_box = (390, 1460, 690, 1580)
analyser.cut_pic(*countdown_box, "", "福袋倒计时", analyser.y_pianyi) # 完整福袋详情倒计时
# 优化:增加高度
analyser.cut_pic(390, 1820, 1000, 1930, "", "福袋价值", analyser.y_pianyi) # 奖品价值/价格
fudai_content_raw = analyser.operation.analyse_pic_word("福袋内容", 0)
participants, copies, fudai_content_text = _extract_participants_and_clean(fudai_content_raw)
analyser._log_kv("福袋", "识别福袋内容", level="INFO", content=fudai_content_text[:60] if fudai_content_text else "未识别到")
# 记录进入直播间到识别到福袋的耗时(仅记录一次)
try:
if getattr(analyser, "_enter_live_ts", 0.0) and not getattr(analyser, "_enter_live_fudai_logged", False):
try:
secs = float(time.time() - float(analyser._enter_live_ts or 0.0))
except Exception:
secs = -1.0
reason = str(getattr(analyser, "_enter_live_reason", "") or "")
analyser._log_kv("性能", "进入直播间到识别福袋耗时", seconds=round(secs, 2), enter_reason=reason)
try:
analyser._enter_live_fudai_logged = True
except Exception:
pass
if copies:
analyser._log_kv("福袋", "识别福袋信息", copies=copies, participants=participants if participants else 0)
except Exception:
pass
# 倒计时:优先用完整OCR(更快,只需1次),失败再用分割OCR
time_text = ""
time_raw = analyser.operation.analyse_pic_word("福袋倒计时", 0)
time_text = normalize_countdown_text(time_raw)
if not time_text or not _parse_mm_ss(time_text):
try:
if countdown_box:
split_raw = _read_countdown_split(countdown_box)
split_text = normalize_countdown_text(split_raw)
if _parse_mm_ss(split_text):
time_text = split_text
except Exception:
pass
analyser._log_kv("福袋", "识别倒计时", countdown=time_text if time_text else "未识别到")
value_raw = analyser.operation.analyse_pic_word("福袋价值", 0)
prize_value_yuan = extract_prize_value_yuan(value_raw)
if prize_value_yuan:
if float(prize_value_yuan).is_integer():
show_value = int(prize_value_yuan)
else:
show_value = prize_value_yuan
analyser._log_kv("福袋", "识别奖品价值", value_yuan=show_value)
return fudai_content_text, time_text, participants, copies, prize_value_yuan
def check_contain(analyser, contains: str = "") -> bool:
"""检查福袋内容是否是想要,从配置文件 config 中读取。
返回值语义与原版保持一致:
- True : “建议丢弃”(内容不是想要的 / 未明确是否想要)
- False : “可以保留”(内容是想要的,或凌晨时段不做内容过滤)
"""
try:
hour = int(analyser.operation.get_current_hour())
except Exception:
hour = -1
# 凌晨:不对内容做要求(不过滤)
if 0 < hour < 7:
try:
analyser._log_kv("筛选", "凌晨不过滤福袋内容", hour=hour, contains=contains[:50] if contains else "")
except Exception:
pass
return False
try:
for contain in getattr(analyser, "contains_want", []) or []:
if contain and contain in (contains or ""):
try:
analyser._log_kv("筛选", "福袋内容是想要的", keyword=contain, contains=contains[:80] if contains else "")
except Exception:
pass
return False
for contain in getattr(analyser, "contains_not_want", []) or []:
if contain and contain in (contains or ""):
try:
analyser._log_kv("筛选", "福袋内容不是想要的", keyword=contain, contains=contains[:80] if contains else "")
except Exception:
pass
return True
try:
analyser._log_kv("筛选", "福袋内容未明确是否想要", contains=contains[:80] if contains else "")
except Exception:
pass
return True
except Exception:
# 容错:异常时不过滤
try:
analyser._log_kv("筛选", "check_contain 异常,默认保留", contains=contains[:80] if contains else "")
except Exception:
pass
return False
def attend_choujiang(analyser) -> bool:
"""点击参与抽奖。"""
analyser.last_attend_fail_reason = ""
click_times = 0
while click_times < 2:
analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字
# 优化:尝试多种OCR模式提高精准度(优先保证精准)
attend_button_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "")
if not attend_button_text or not any(
k in attend_button_text for k in ("参与成功", "还需看播", "评论", "参与抽奖", "开始观看", "参与")
):
attend_button_text = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "")
analyser._log_kv("参与", "识别参与按钮", text=attend_button_text)
if "参与成功" in attend_button_text: # 如果识别到已经参与抽奖
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
analyser.click(500, 470) # 点击刚才打开福袋的旁边位置
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return True
elif "还需看播" in attend_button_text: # 如果识别到需要看播
analyser.last_attend_fail_reason = "watch_required"
analyser._log_kv("参与", "需要看播时长:默认不参与", result="看播门槛")
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif "无法参与" in attend_button_text:
analyser._log_kv("参与", "无法参与(条件不满足)", result="无法参与")
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif "时长不足" in attend_button_text:
analyser._log_kv("参与", "无法参与(看播时长不足)", result="时长不足")
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif "评论" in attend_button_text:
analyser.click(500, 2060)
analyser._log_kv("参与", "点击参与抽奖", action="点击参与", mode="评论")
return True
elif "参与抽奖" in attend_button_text:
analyser.click(500, 2060)
analyser._log_kv("参与", "点击参与抽奖", action="点击参与", mode="普通")
return True
elif "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text:
# 需要粉丝团门槛:先点击尝试进入加入/点亮流程
analyser.last_attend_fail_reason = "fansclub_required"
analyser.click(500, 2060)
analyser._log_kv("参与", "粉丝团门槛:已点击加入按钮", result="需要粉丝团")
analyser.operation.delay(2)
if not analyser.auto_join_fansclub:
analyser._log_kv("参与", "未启用自动加粉丝团:等待手动确认", wait_seconds=15)
analyser.operation.delay(15)
# 点击粉丝团按钮后,可能进入“加入粉丝团”独立页面:需要在该页再次点击“加入粉丝团”才能成功。
def _recover_to_fudai_detail_after_fansclub(max_steps: int = 4) -> bool:
for i in range(int(max_steps or 4)):
try:
analyser._shot_and_diagnose("粉丝团", "粉丝团后定位福袋详情({}/{})".format(i + 1, max_steps), analyser.device_id)
except Exception:
pass
try:
st, seen = analyser._diagnose_stage_from_current_screen()
except Exception:
st, seen = "", ""
if st == "FUDai_DETAIL":
return True
if st == "FANSCLUB_JOIN":
# 在加入页点击底部“加入粉丝团”按钮(与详情页按钮同位置)
analyser._log_kv("参与", "粉丝团加入页:点击加入粉丝团", stage=st, seen=seen, attempt=i + 1)
try:
analyser.click(500, 2060)
except Exception:
pass
analyser.operation.delay(2)
# 尝试返回到详情
try:
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(1)
except Exception:
pass
continue
# 已经回到直播间/列表时:不要继续按返回键,避免退出直播
if st in ("IN_LIVE_ROOM", "FOLLOW_LIST", "LIVE_LIST"):
analyser._log_kv("参与", "已离开福袋详情:停止继续返回", stage=st, seen=seen)
return False
# 其它未知弹窗:尝试一次返回
analyser._log_kv("参与", "粉丝团流程:尝试返回", stage=st, seen=seen)
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
analyser.operation.delay(1)
return False
ok = _recover_to_fudai_detail_after_fansclub()
if ok:
analyser._log_kv("参与", "粉丝团流程结束:已回到福袋详情", result="回到详情")
return attend_choujiang(analyser)
analyser._log_kv("参与", "粉丝团流程失败:未回到福袋详情", result="粉丝团门槛仍未解决")
analyser.operation.delay(1.2)
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
pass
if analyser.check_in_fudai_detail():
analyser._log_kv("参与", "粉丝团流程失败:仍在详情页,执行关闭", stage="FUDai_DETAIL")
try:
analyser.click(500, 470)
except Exception:
pass
analyser.operation.delay(0.8)
else:
analyser._log_kv("参与", "粉丝团流程失败:已不在详情页,视为已退出", stage="UNKNOWN")
try:
analyser._log_kv("参与", "粉丝团门槛仍未解决", result="粉丝团门槛仍未解决")
except Exception:
pass
return False
else:
# 未识别到任何可用文案:再尝试一次
analyser._log_kv("参与", "未识别到可用参与按钮文案", text=attend_button_text or "")
click_times += 1
analyser.operation.delay(1)
continue
analyser._log_kv("参与", "参与抽奖多次点击失败", result="多次失败")
return False
def check_lucky_draw_result(analyser):
"""判定福袋抽奖的结果。"""
# 速度优化:只在需要时截图(如果有最近截图且缓存有效,可跳过)
cache_key = ("lucky_draw_result", 0)
now = time.time()
need_screenshot = True
# 检查缓存是否有效
if cache_key in analyser._ocr_cache:
cached_ts, cached_result = analyser._ocr_cache[cache_key]
if (now - cached_ts) < 0.5 and cached_result and ("没有抽中" in cached_result or "抽中福袋" in cached_result):
need_screenshot = False
if need_screenshot:
analyser._shot_and_diagnose("开奖结果", "识别是否中奖/未中奖", analyser.device_id)
# 优化:稍微扩大区域(655->650, 755->765),确保包含完整的开奖结果文字
analyser.cut_pic(350, 650, 750, 765, "", "抽奖结果") # 没有抽中福袋位置
# 诊断开始时间
t0 = time.time()
# 检查缓存
if cache_key in analyser._ocr_cache:
cached_ts, cached_result = analyser._ocr_cache[cache_key]
if (now - cached_ts) < analyser._ocr_cache_ttl:
lucky_draw_result = cached_result
else:
lucky_draw_result = str(analyser.operation.analyse_pic_word("抽奖结果", 0) or "")
if not lucky_draw_result or ("没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result):
lucky_draw_result = str(analyser.operation.analyse_pic_word("抽奖结果", 1) or "")
analyser._ocr_cache[cache_key] = (now, lucky_draw_result)
else:
lucky_draw_result = str(analyser.operation.analyse_pic_word("抽奖结果", 0) or "")
if not lucky_draw_result or ("没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result):
lucky_draw_result = str(analyser.operation.analyse_pic_word("抽奖结果", 1) or "")
analyser._ocr_cache[cache_key] = (now, lucky_draw_result)
dur = time.time() - t0
try:
brief = (lucky_draw_result or "").replace("\n", " ")[:140]
except Exception:
brief = ""
try:
analyser._log_kv(
"开奖诊断",
"lucky_draw_result",
brief=brief,
ocr_dur=round(dur, 2),
)
except Exception:
pass
if "没有抽中" in (lucky_draw_result or ""):
# 速度优化:使用缓存避免重复OCR
cache_key2 = ("no_award_confirm", 0)
if cache_key2 in analyser._ocr_cache:
cached_ts2, cached_result2 = analyser._ocr_cache[cache_key2]
if (now - cached_ts2) < analyser._ocr_cache_ttl:
no_award_confirm = cached_result2
else:
t1 = time.time()
analyser.cut_pic(340, 1195, 740, 1355, "", "无奖励确认")
no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认")
analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm)
dur2 = time.time() - t1
else:
t1 = time.time()
analyser.cut_pic(340, 1200, 730, 1350, "", "无奖励确认")
no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认")
analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm)
dur2 = time.time() - t1
try:
dur2
except NameError:
dur2 = 0.0
try:
brief2 = (no_award_confirm or "").replace("\n", " ")[:140]
except Exception:
brief2 = ""
try:
analyser._log_kv(
"开奖诊断",
"no_award_confirm",
brief=brief2,
ocr_dur=round(dur2, 2),
)
except Exception:
pass
if "我知道了" in (no_award_confirm or ""):
return 1
elif "领取并使用" in (no_award_confirm or ""):
return 2
return 3
elif "抽中福袋" in (lucky_draw_result or ""):
try:
analyser._log_kv("开奖诊断", "恭喜中奖了", result_text=brief)
except Exception:
pass
# 速度优化:优先检测第一个常见位置,命中即返回
y_value = [1438, 1490]
for y in y_value:
cache_key3 = (f"have_read_user_agreement_{y}", 0)
have_read_user_agreement = None
dur3 = 0.0
if cache_key3 in analyser._ocr_cache:
cached_ts3, cached_result3 = analyser._ocr_cache[cache_key3]
if (now - cached_ts3) < analyser._ocr_cache_ttl:
have_read_user_agreement = cached_result3
if not have_read_user_agreement:
t2 = time.time()
analyser.cut_pic(280, y - 35, 670, y + 35, "", f"已阅读用户协议_{y}")
have_read_user_agreement = analyser.operation.analyse_pic_word(f"已阅读用户协议_{y}")
analyser._ocr_cache[cache_key3] = (time.time(), have_read_user_agreement)
dur3 = time.time() - t2
try:
brief3 = (have_read_user_agreement or "").replace("\n", " ")[:140]
except Exception:
brief3 = ""
try:
analyser._log_kv(
"开奖诊断",
"have_read_user_agreement",
brief=brief3,
ocr_dur=round(dur3, 2),
y=y,
)
except Exception:
pass
if "已阅读" in (have_read_user_agreement or ""):
return y
return False
def check_have_reward_notice_confirm(analyser) -> bool:
"""判断是否有领奖的二次确认提醒。"""
analyser._shot_and_diagnose("领奖确认", "识别是否有我知道了", analyser.device_id)
analyser.cut_pic(370, 1350, 680, 1440, "", "奖励通知确认")
reward_notice_confirm = analyser.operation.analyse_pic_word("奖励通知确认", 1)
if "我知道了" in (reward_notice_confirm or ""):
try:
analyser._log_kv(
"开奖诊断",
"存在奖品领取提醒",
text=(reward_notice_confirm or "")[:80],
)
except Exception:
pass
return True
return False
def check_in_order_confirm_page(analyser) -> bool:
"""判断是否在中奖下单后的购买成功的页面。"""
analyser._shot_and_diagnose("下单结果", "识别是否购买成功页", analyser.device_id)
analyser.cut_pic(370, 120, 700, 220, "", "订单确认")
order_confirm = analyser.operation.analyse_pic_word("订单确认")
if "购买成功" in (order_confirm or ""):
try:
analyser._log_kv(
"开奖诊断",
"订单确认页面:购买成功",
text=(order_confirm or "")[:80],
)
except Exception:
pass
return True
return False
def get_reward(analyser, reward_y: int = 0) -> None:
"""中奖后领奖然后返回。"""
analyser.operation.save_reward_pic(analyser.device_id)
try:
analyser._log_kv("领奖", "保存中奖截图", step="save_reward_pic")
except Exception:
pass
analyser.click(243, reward_y) # 勾选协议
analyser.operation.delay(1)
analyser.click(540, reward_y - 140) # 点击领取
try:
analyser._log_kv("领奖", "勾选协议并点击领取", reward_y=reward_y)
except Exception:
pass
analyser.operation.delay(5)
analyser.click(886, 2170) # 点击下单
try:
analyser._log_kv("领奖", "点击下单")
except Exception:
pass
analyser.operation.delay(10)
# 循环检查下单结果,增加保护避免极端死循环
max_checks = 5
checks = 0
while checks < max_checks and check_in_order_confirm_page(analyser):
checks += 1
analyser.operation.click_back(analyser.device_id)
try:
analyser._log_kv("领奖", "点击回退按钮", check_round=checks)
except Exception:
pass
analyser.operation.delay(4)
try:
analyser._log_kv("领奖", "下完单返回到直播间", checks=checks)
except Exception:
pass
analyser.operation.delay(4)
if check_lucky_draw_result(analyser):
try:
analyser._log_kv("领奖", "领奖弹窗未关闭,准备关闭")
except Exception:
pass
analyser.click(540, reward_y + 180)
try:
analyser._log_kv(
"领奖",
"点击关闭领奖弹窗",
x=540,
y=(reward_y + 180) * analyser.resolution_ratio_y // 2400,
)
except Exception:
pass
analyser.operation.delay(2)
analyser.operation.save_reward_pic(analyser.device_id)
try:
analyser._log_kv("领奖", "保存关闭领奖弹窗后的截图")
except Exception:
pass
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(2)
if check_have_reward_notice_confirm(analyser):
try:
analyser._log_kv("领奖", "提醒领奖弹窗未关闭,点击我知道了")
except Exception:
pass
analyser.click(540, 1400)
analyser.operation.delay(2)
try:
analyser._log_kv("领奖", "关闭中奖提醒后等待", wait_seconds=30)
except Exception:
pass
analyser.operation.delay(30)
def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str]:
"""根据 config.json 中的阈值与关键词,判断是否应丢弃当前福袋。
返回:
(skip, reason) 其中 reason 为简单文字原因,便于日志查看。
"""
if not isinstance(detail, tuple) or len(detail) < 6:
return False, "detail_tuple_invalid"
content = str(detail[0] or "")
time_text = str(detail[1] or "")
try:
participants = int(detail[2] or 0)
except Exception:
participants = 0
try:
copies = int(detail[3] or 0)
except Exception:
copies = 0
try:
prize_value_yuan = float(detail[4] or 0.0)
except Exception:
prize_value_yuan = 0.0
cd_start, cd_end = None, None
if isinstance(detail[5], (tuple, list)) and len(detail[5]) >= 2:
cd_start, cd_end = detail[5][0], detail[5][1]
now = time.time()
remain_seconds = None
try:
if isinstance(cd_end, (int, float)) and cd_end > now:
remain_seconds = float(cd_end - now)
except Exception:
remain_seconds = None
# 读取配置阈值
try:
min_value = float(getattr(analyser, "min_prize_value_yuan", 0.0) or 0.0)
except Exception:
min_value = 0.0
try:
min_participants = int(getattr(analyser, "min_participants", 0) or 0)
except Exception:
min_participants = 0
try:
max_participants = int(getattr(analyser, "max_participants", 0) or 0)
except Exception:
max_participants = 0
try:
skip_if_lt = int(getattr(analyser, "skip_if_countdown_lt_seconds", 0) or 0)
except Exception:
skip_if_lt = 0
# 1) 价值过滤
if min_value > 0 and prize_value_yuan > 0 and prize_value_yuan < min_value:
return True, f"value_lt_{min_value}"
# 2) 参与人数过滤
if min_participants > 0 and participants and participants < min_participants:
return True, f"participants_lt_{min_participants}"
if max_participants > 0 and participants and participants > max_participants:
return True, f"participants_gt_{max_participants}"
# 3) 倒计时过滤
if skip_if_lt > 0 and remain_seconds is not None and remain_seconds < skip_if_lt:
return True, f"countdown_lt_{skip_if_lt}"
# 4) 内容关键词过滤(复用 check_contain 逻辑)
if check_contain(analyser, content):
return True, "content_not_wanted"
try:
analyser._log_kv(
"筛选",
"should_skip_fudai_by_config 通过",
content=content[:60] if content else "",
participants=participants,
copies=copies,
value_yuan=prize_value_yuan,
remain_seconds=int(remain_seconds) if remain_seconds is not None else None,
)
except Exception:
pass
return False, "ok"
def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
"""基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖。
返回:
True 表示已经参与或已处理完成;
False 表示未参与(例如被配置筛掉或参与失败)。
"""
skip, reason = should_skip_fudai_by_config(analyser, detail)
if skip:
try:
analyser._log_kv(
"参与",
"basic_join_decision:按配置丢弃福袋",
reason=reason,
)
except Exception:
pass
# 丢弃时,尽量关闭详情,避免停留在详情页
try:
analyser.click(500, 470)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser._log_kv("参与", "basic_join_decision:已关闭详情", action="close_detail")
except Exception:
pass
# 如果是“内容不想要”的原因,且允许切换直播间,则立即切换到下一个直播间
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if reason == "content_not_wanted" and needswitch:
try:
analyser._log_kv("参与", "basic_join_decision:内容不想要且允许切房,立即切换直播间")
except Exception:
pass
try:
# 优先使用封装好的上滑切房方法
if hasattr(analyser, "swipe_up_to_next_live"):
analyser.swipe_up_to_next_live()
else:
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
start_x = 540 * rx // 1080
start_y = 1700 * ry // 2400
end_x = 540 * rx // 1080
end_y = 700 * ry // 2400
analyser.operation.swipe(analyser.device_id, start_x, start_y, end_x, end_y, 300)
except Exception:
# 切房失败不影响主流程,直接返回
pass
return False
# 未被筛掉:尝试参与抽奖
try:
analyser._log_kv("参与", "basic_join_decision:尝试参与抽奖")
except Exception:
pass
return attend_choujiang(analyser)
+307
View File
@@ -0,0 +1,307 @@
from __future__ import annotations
"""
Fudai detail helpers shim (WebGUI version)
==========================================
Exports:
- close_fudai_detail
- ensure_fudai_detail_open
- read_live_room_title_core
- read_fudai_detail_once
- read_fudai_detail_with_retries
- is_abnormal_time_value
"""
from typing import Any, Dict, Tuple, List, Optional
import os
import time
from PIL import Image
from douyin_detection import check_detail_height
from douyin_fudai_core import get_fudai_contain
def close_fudai_detail(analyser: Any) -> None:
"""关闭福袋详情:当前实现直接按一次返回键。"""
try:
analyser._log_kv("详情", "close_fudai_detail:按返回键一次")
except Exception:
pass
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser.operation.delay(0.5)
except Exception:
time.sleep(0.5)
def ensure_fudai_detail_open(analyser: Any) -> bool:
"""确保福袋详情已打开:当前实现只记录日志并假定已打开。"""
try:
analyser._log_kv("详情", "ensure_fudai_detail_open:假定已打开")
except Exception:
pass
return True
def _is_wrong_coupon_popup(analyser: Any) -> bool:
"""在已点击疑似福袋后,判断当前弹窗是否为优惠券类,而非真正福袋详情。
只在“点击详情后”调用,不在平时循环中使用,避免额外开销。
逻辑:对屏幕中部区域做颜色统计,若橙券像素明显多于粉袋像素,则视为优惠券弹窗。
"""
try:
analyser.operation.get_screenshot(analyser.device_id)
except Exception:
return False
path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
try:
pic = Image.open(path)
pic.load()
except Exception:
return False
pic = pic.convert("RGBA")
pix = pic.load()
w, h = pic.size
# 取画面中部偏上的一块区域作为弹窗主体
x1 = int(w * 0.15)
x2 = int(w * 0.85)
y1 = int(h * 0.25)
y2 = int(h * 0.75)
if x1 >= x2 or y1 >= y2:
return False
fudai_like = 0
coupon_like = 0
step_x = max(1, (x2 - x1) // 40)
step_y = max(1, (y2 - y1) // 40)
for yy in range(y1, y2, step_y):
for xx in range(x1, x2, step_x):
try:
p = pix[xx, yy]
except Exception:
continue
if not (isinstance(p, tuple) and len(p) >= 3):
continue
r, g, b = int(p[0]), int(p[1]), int(p[2])
# 福袋:粉/紫/粉蓝
if r >= 200 and b >= 210 and 80 <= g <= 230:
fudai_like += 1
# 券:偏橙色
if r >= 200 and 120 <= g <= 230 and b <= 180:
coupon_like += 1
try:
analyser._log_kv(
"弹窗",
"弹窗颜色统计",
fudai_like=fudai_like,
coupon_like=coupon_like,
)
except Exception:
pass
# 券像素明显多于粉袋像素,则认为是优惠券弹窗
return coupon_like > fudai_like * 1.2
def read_live_room_title_core(
analyser: Any,
y_pianyi: int,
min_len: int = 3,
) -> Tuple[str, str]:
"""Shim: return empty title and raw text placeholder."""
raw = "shim_live_room_title_raw"
return "", raw
def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
"""执行一次福袋详情识别(本地完整版实现)。
流程:
1. 若检测到优惠券弹窗,则视为误点并关闭,返回状态 coupon_popup;
2. 使用像素高度检测任务数 (`check_detail_height`);
3. 调用 `get_fudai_contain` 裁剪+OCR,识别内容/倒计时/价值;
4. 通过 `operation.check_countdown` 解析倒计时,生成 (start_ts, future_ts)。
"""
# 先检测是否是“优惠券弹窗”
if _is_wrong_coupon_popup(analyser):
try:
analyser._log_kv("弹窗", "检测到优惠券弹窗,视为误点并关闭")
except Exception:
pass
close_fudai_detail(analyser)
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 结果",
status="coupon_popup",
content="",
time_text="",
participants=0,
copies=0,
prize_value_yuan=0.0,
countdown_start=None,
countdown_end=None,
)
except Exception:
pass
return "coupon_popup", (), {"popup_type": "coupon"}
# 任务数:0/1/2/3,异常时默认按 2 个任务处理
try:
task_count = int(check_detail_height(analyser) or 0)
except Exception:
task_count = 0
if task_count not in (1, 2, 3):
task_count = 2
# 识别福袋内容 / 倒计时 / 价值
try:
content, time_text, participants, copies, prize_value_yuan = get_fudai_contain(
analyser, renwu=task_count
)
except Exception as e:
# 出现异常时,记录错误并返回占位结果
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 异常",
error=str(e),
)
except Exception:
pass
now = time.time()
tup_err = ("", "", 0, 0, 0.0, (now, now + 60.0))
return "error", tup_err, {}
# 解析倒计时 -> (剩余秒数, 未来时间戳)
countdown_start = time.time()
countdown_end = countdown_start + 60.0
try:
if time_text:
res = analyser.operation.check_countdown(time_text)
if isinstance(res, tuple) and len(res) == 2:
total_seconds, future_ts = res
try:
total_seconds = int(total_seconds)
except Exception:
total_seconds = int(float(total_seconds or 0))
if total_seconds > 0 and isinstance(future_ts, (int, float)):
countdown_start = float(countdown_start)
countdown_end = float(future_ts)
except Exception:
pass
detail_tuple = (
content or "",
time_text or "",
int(participants or 0),
int(copies or 0),
float(prize_value_yuan or 0.0),
(countdown_start, countdown_end),
)
extra: Dict[str, Any] = {
"task_count": task_count,
}
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 结果",
status="ok",
content=detail_tuple[0],
time_text=detail_tuple[1],
participants=detail_tuple[2],
copies=detail_tuple[3],
prize_value_yuan=detail_tuple[4],
countdown_start=countdown_start,
countdown_end=countdown_end,
task_count=task_count,
)
except Exception:
pass
return "ok", detail_tuple, extra
def read_fudai_detail_with_retries(
analyser: Any,
fudai_x: int,
read_once_callback,
close_detail_callback,
ensure_open_callback,
) -> Tuple:
"""多次重试读取福袋详情,返回 6 字段 detail tuple。
与原版保持兼容:总是返回
(content, time_text, participants, copies, prize_value_yuan, countdown_tuple)
"""
max_attempts = 2
try:
max_attempts = int(getattr(analyser, "fudai_detail_max_attempts", 2) or 2)
except Exception:
max_attempts = 2
if max_attempts < 1:
max_attempts = 1
retry_delay = 0.8
try:
retry_delay = float(getattr(analyser, "fudai_detail_retry_delay_seconds", 0.8) or 0.8)
except Exception:
retry_delay = 0.8
last_tuple: Optional[Tuple] = None
last_status: str = "error"
for attempt in range(max_attempts):
status, tup, extra = read_fudai_detail_once(analyser)
last_status = status
if isinstance(tup, tuple) and len(tup) >= 6:
last_tuple = tup[:6]
if status == "ok":
break
if attempt < max_attempts - 1:
try:
analyser.operation.delay(retry_delay)
except Exception:
time.sleep(retry_delay)
if last_tuple is None:
now = time.time()
last_tuple = ("", "", 0, 0, 0.0, (now, now + 60.0))
content, time_text, participants, copies, prize_value_yuan, cd = last_tuple
cd_start, cd_end = None, None
if isinstance(cd, (tuple, list)) and len(cd) >= 2:
cd_start, cd_end = cd[0], cd[1]
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries 最终结果",
status=last_status,
content=content,
time_text=time_text,
participants=participants,
copies=copies,
prize_value_yuan=prize_value_yuan,
countdown_start=cd_start,
countdown_end=cd_end,
fudai_x=fudai_x,
)
except Exception:
pass
return last_tuple
def is_abnormal_time_value(v: float) -> bool:
"""Shim: treat clearly invalid time values as abnormal."""
if v <= 0:
return True
if v > 24 * 3600 * 7:
return True
+83
View File
@@ -0,0 +1,83 @@
from __future__ import annotations
"""
douyin_fudai_flow 代理模块(WebGUI 根目录)
=========================================
完整的流程辅助函数实现位于:
C:\\Users\\12742\\.cursor\\worktrees\\douyin_guaji-main\\axf\\douyin_fudai_flow.py
本模块的作用:
1. 动态加载上述外部模块;
2. 将其中的公开符号(不以下划线开头的名称)导出到当前命名空间;
3. 确保 `stuck_guard_tick` 一定存在(若外部缺失则提供一个安全的空实现)。
这样,当 `axf/douyin_fudai.py` 执行 `import douyin_fudai_flow` 时,
会优先命中本目录的代理模块,避免由于外部模块导入不完整导致
`AttributeError: module 'douyin_fudai_flow' has no attribute 'stuck_guard_tick'`。
"""
import importlib.util
import os
import sys
from types import ModuleType
from typing import Any, Callable
_EXTERNAL_DIR = r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf"
_EXTERNAL_PATH = os.path.join(_EXTERNAL_DIR, "douyin_fudai_flow.py")
def _load_external_flow_module() -> ModuleType:
if not os.path.isfile(_EXTERNAL_PATH):
raise ImportError(f"外部 douyin_fudai_flow.py 不存在: {_EXTERNAL_PATH}")
mod_name = "douyin_fudai_flow_external"
if mod_name in sys.modules:
return sys.modules[mod_name]
spec = importlib.util.spec_from_file_location(mod_name, _EXTERNAL_PATH)
if spec is None or spec.loader is None:
raise ImportError(f"无法创建外部模块 spec: {_EXTERNAL_PATH}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) # type: ignore[arg-type]
sys.modules[mod_name] = module
return module
_ext_mod = _load_external_flow_module()
# 先将外部模块中所有公开符号导出到当前命名空间
for _name, _value in list(vars(_ext_mod).items()): # type: ignore[arg-type]
if _name.startswith("_"):
continue
globals()[_name] = _value # type: ignore[assignment]
def _noop_stuck_guard_tick(
analyser: Any,
stuck_last_hash_ref: list,
stuck_same_since_ref: list,
stuck_last_check_ts_ref: list,
stuck_last_back_ts_ref: list,
read_screen_hash_callback: Callable[[], str],
) -> None:
"""安全的空实现:不做任何操作,仅用于兜底避免 AttributeError。"""
try:
analyser._log_kv("自救", "stuck_guard_tick:当前未启用卡死检测")
except Exception:
pass
# 如果外部模块没有正确导出 stuck_guard_tick,则使用本地兜底实现
if "stuck_guard_tick" not in globals():
stuck_guard_tick = _noop_stuck_guard_tick # type: ignore[assignment]
# 清理局部变量,避免泄漏实现细节
del _name, _value
del _ext_mod
del _load_external_flow_module
del _EXTERNAL_DIR, _EXTERNAL_PATH
File renamed without changes.
+56
View File
@@ -0,0 +1,56 @@
from __future__ import annotations
"""
Live room helper functions module (WebGUI version).
This is a minimal reimplementation of the original live-room helpers,
with only the interfaces that `douyin_fudai` relies on during normal
WebGUI runs. The goal is to avoid encoding/syntax issues from the
external worktree while keeping the main logic running.
"""
from typing import Any
def reflash_zhibo(analyser: Any) -> None:
"""在关注列表,下拉刷新直播间(当前实现仅打印日志,不做真实滑动)。"""
try:
print("下划刷新直播间列表(当前实现未启用实际滑动)")
# 如果你希望保留真实行为,可以取消下面的注释:
# analyser.swipe(760, 700, 760, 1500)
# analyser.operation.delay(5)
except Exception:
pass
def check_in_follow_list(analyser: Any) -> bool:
"""判断是否界面在“我的关注”列表页(当前实现固定返回 False)。"""
try:
analyser._log_kv("检测", "check_in_follow_list:当前实现默认不在关注列表")
except Exception:
pass
return False
def check_zhibo_is_closed(analyser: Any) -> bool:
"""检查当前直播间是否关闭(当前实现固定返回 False)。"""
try:
analyser._log_kv("检测", "check_zhibo_is_closed:当前实现默认直播间未关闭")
except Exception:
pass
return False
def get_no_fudai_wait_time(analyser: Any) -> float:
"""返回距离上次识别到福袋的等待秒数(当前实现固定返回 0)。"""
try:
analyser._log_kv("检测", "get_no_fudai_wait_time:当前实现默认0秒")
except Exception:
pass
return 0.0
def check_no_fudai_time(analyser: Any) -> float:
"""Shim: compatibility wrapper returning the same as get_no_fudai_wait_time."""
return get_no_fudai_wait_time(analyser)
+179
View File
@@ -0,0 +1,179 @@
from __future__ import annotations
"""
Lottery helpers shim (WebGUI version)
=====================================
Exports:
- wait_for_lottery_result
- process_lottery_result
"""
from typing import Any, Dict, Tuple
import time
def wait_for_lottery_result(
analyser: Any,
lastsecond: int,
future_timestamp: float,
reservation_after_action_pending: bool,
reservation_should_preempt_callback,
) -> Tuple[bool, int, float | None, int | None]:
"""兼容实现:按原始签名等待开奖,当前版本只做时间等待与简单抢占判断。"""
start = time.time()
# 简单轮询等待一小段时间,保留结构但不做重型逻辑
detect_attempts = 0
first_detect_ts: float | None = None
initial_check_result: int | None = None
# 最多等待 min(倒计时+5, 15) 秒,避免阻塞过久
total_wait_s = max(0.0, float(lastsecond or 0) + 5.0)
total_wait_s = min(total_wait_s, 15.0)
step_s = 1.5
while (time.time() - start) < total_wait_s:
detect_attempts += 1
if first_detect_ts is None:
first_detect_ts = time.time()
# 若有"预约应抢占"回调,则在等待期间尊重其判断
try:
if reservation_should_preempt_callback is not None and reservation_should_preempt_callback():
return True, detect_attempts, first_detect_ts, initial_check_result or 0
except Exception:
pass
try:
analyser.operation.delay(step_s)
except Exception:
time.sleep(step_s)
# 占位返回:未被预约抢占,未检测到明确结果
return False, detect_attempts, first_detect_ts, initial_check_result
def process_lottery_result(
analyser: Any,
x: int,
t_participate: float,
detect_attempts: int,
first_detect_ts: float | None,
initial_check_result: int | None,
reservation_focus_until_ts: float,
reservation_focus_until_ts_ref: list,
reservation_after_action_pending_ref: list,
needswitch: bool,
post_switch_delay_s: float,
swipe_up_switch_callback,
clear_reservations_callback,
get_recommend_seconds_callback,
yanghao_wait_callback,
) -> bool:
"""兼容实现:记录开奖阶段的调试信息,当前版本不修改预约/房间状态。"""
try:
analyser._log_kv(
"开奖",
"process_lottery_result",
x=x,
detect_attempts=detect_attempts,
first_detect_ts=first_detect_ts,
initial_check_result=initial_check_result,
)
except Exception:
pass
return False
"""
Lottery helpers shim (WebGUI version)
=====================================
Exports:
- wait_for_lottery_result
- process_lottery_result
"""
from typing import Any, Dict, Tuple
import time
def wait_for_lottery_result(
analyser: Any,
lastsecond: int,
future_timestamp: float,
reservation_after_action_pending: bool,
reservation_should_preempt_callback,
) -> Tuple[bool, int, float | None, int | None]:
"""Shim version matching original signature.
为了安全起见,这里不做真实的开奖结果 OCR,仅按时间简单等待并返回
“未被预约抢占、未检测到结果”的占位信息,避免打断主流程。
"""
start = time.time()
# 简单轮询等待一小段时间,保留结构但不做重型逻辑
detect_attempts = 0
first_detect_ts: float | None = None
initial_check_result: int | None = None
# 最多等待 min(倒计时+5, 15) 秒,避免阻塞过久
total_wait_s = max(0.0, float(lastsecond or 0) + 5.0)
total_wait_s = min(total_wait_s, 15.0)
step_s = 1.5
while (time.time() - start) < total_wait_s:
detect_attempts += 1
if first_detect_ts is None:
first_detect_ts = time.time()
# 若有"预约应抢占"回调,则在等待期间尊重其判断
try:
if reservation_should_preempt_callback is not None and reservation_should_preempt_callback():
return True, detect_attempts, first_detect_ts, initial_check_result or 0
except Exception:
pass
try:
analyser.operation.delay(step_s)
except Exception:
time.sleep(step_s)
# 占位返回:未被预约抢占,未检测到明确结果
return False, detect_attempts, first_detect_ts, initial_check_result
def process_lottery_result(
analyser: Any,
x: int,
t_participate: float,
detect_attempts: int,
first_detect_ts: float | None,
initial_check_result: int | None,
reservation_focus_until_ts: float,
reservation_focus_until_ts_ref: list,
reservation_after_action_pending_ref: list,
needswitch: bool,
post_switch_delay_s: float,
swipe_up_switch_callback,
clear_reservations_callback,
get_recommend_seconds_callback,
yanghao_wait_callback,
) -> bool:
"""Shim: match original signature and record basic diagnostics.
为了安全起见,这里不再做复杂的开奖 OCR/状态机,仅:
- 记录一次日志方便事后分析;
- 不修改预约/房间状态;
- 始终返回 False(表示不主动中断主循环)。
"""
try:
analyser._log_kv(
"开奖",
"process_lottery_result",
x=x,
detect_attempts=detect_attempts,
first_detect_ts=first_detect_ts,
initial_check_result=initial_check_result,
)
except Exception:
pass
return False
+354
View File
@@ -0,0 +1,354 @@
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any
from PIL import Image
def _safe_open_screenshot_rgb(pic_path: str) -> Image.Image | None:
try:
if not pic_path or (not os.path.exists(pic_path)):
return None
pic = Image.open(pic_path)
return pic.convert("RGB")
except Exception:
return None
def detect_coupon_popup_background(pic_rgb: Image.Image) -> bool:
"""底部优惠券大弹窗背景(粉/红)像素快速检测。"""
try:
width, height = pic_rgb.size
check_y_base = int(height * 0.5)
check_points = [
(width // 2, height - 200), # 底部中心(按钮区域)
(width // 2, height - 400), # 底部中心偏上(标题区域)
(width // 3, height - 300), # 左侧
(width * 2 // 3, height - 300), # 右侧
(width // 2, check_y_base), # 屏幕中部(弹窗可能延伸到这里)
]
pink_red_count = 0
for x, y in check_points:
if 0 <= x < width and 0 <= y < height:
r, g, b = pic_rgb.getpixel((x, y))
# 与原逻辑一致:R 值较高且明显偏红
if r > 180 and (r - g) > 50 and (r - b) > 50:
pink_red_count += 1
return pink_red_count >= 2
except Exception:
return False
def detect_redpacket_popup_background(pic_rgb: Image.Image) -> bool:
"""中央购物红包弹窗背景(红色信封 + 黄色按钮)像素快速检测。"""
try:
width, height = pic_rgb.size
center_x = width // 2
center_y = height // 2
check_points = [
(center_x, center_y), # 屏幕正中心
(center_x, center_y - 200), # 中心偏上(信封顶部)
(center_x, center_y + 200), # 中心偏下(信封底部)
(center_x - 150, center_y), # 中心偏左
(center_x + 150, center_y), # 中心偏右
]
red_count = 0
yellow_count = 0
for x, y in check_points:
if 0 <= x < width and 0 <= y < height:
r, g, b = pic_rgb.getpixel((x, y))
if r > 200 and g < 100 and b < 100:
red_count += 1
if r > 200 and g > 200 and b < 150:
yellow_count += 1
return (red_count >= 2) or (yellow_count >= 1)
except Exception:
return False
def detect_lucky_draw_result_popup(pic_rgb: Image.Image) -> bool:
"""检测抽奖结果弹窗:大片红色背景 + 中间有"我知道了"按钮区域。
抽奖结果弹窗通常在屏幕中下部,有大片红色背景,中间有白色/浅色的"我知道了"按钮。
检测区域:(380,660)-(720,755) 基准1080x2400
"""
try:
width, height = pic_rgb.size
# 缩放坐标到实际尺寸
scale_x = width / 1080.0
scale_y = height / 2400.0
# 检测区域(基准1080x2400)
x1 = int(380 * scale_x)
y1 = int(660 * scale_y)
x2 = int(720 * scale_x)
y2 = int(755 * scale_y)
# 确保坐标在范围内
x1 = max(0, min(x1, width))
y1 = max(0, min(y1, height))
x2 = max(0, min(x2, width))
y2 = max(0, min(y2, height))
if x1 >= x2 or y1 >= y2:
return False
# 采样检测点:检测大片红色区域
red_count = 0
sample_points = []
step_x = max(1, (x2 - x1) // 10)
step_y = max(1, (y2 - y1) // 10)
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
# 检测红色:R值高,G和B相对较低
if r > 200 and (r - g) > 50 and (r - b) > 50:
red_count += 1
except Exception:
continue
# 如果红色像素占比足够高(至少30%),认为有大片红色背景
total_samples = len(list(range(y1, y2, step_y))) * len(list(range(x1, x2, step_x)))
if total_samples == 0:
return False
red_ratio = red_count / total_samples if total_samples > 0 else 0
return red_ratio >= 0.3
except Exception:
return False
def detect_attend_button_red_area(pic_rgb: Image.Image) -> bool:
"""检测参与按钮:大片红色区域。
参与按钮通常在屏幕底部,有大片红色背景。
检测区域:(306,2030)-(780,2110) 基准1080x2400,但实际可能更宽
扩展检测区域到更宽的范围以覆盖"一键参与评论"等按钮
"""
try:
width, height = pic_rgb.size
# 缩放坐标到实际尺寸
scale_x = width / 1080.0
scale_y = height / 2400.0
# 检测区域(基准1080x2400,扩展宽度以覆盖更宽的按钮)
x1 = int(200 * scale_x) # 扩展左侧
y1 = int(2000 * scale_y) # 稍微上移
x2 = int(880 * scale_x) # 扩展右侧
y2 = int(2120 * scale_y) # 稍微下移
# 确保坐标在范围内
x1 = max(0, min(x1, width))
y1 = max(0, min(y1, height))
x2 = max(0, min(x2, width))
y2 = max(0, min(y2, height))
if x1 >= x2 or y1 >= y2:
return False
# 采样检测点:检测大片红色区域
red_count = 0
sample_points = []
step_x = max(1, (x2 - x1) // 15)
step_y = max(1, (y2 - y1) // 10)
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
# 检测红色:R值高,G和B相对较低
if r > 200 and (r - g) > 50 and (r - b) > 50:
red_count += 1
except Exception:
continue
# 如果红色像素占比足够高(至少25%),认为有大片红色背景
total_samples = len(list(range(y1, y2, step_y))) * len(list(range(x1, x2, step_x)))
if total_samples == 0:
return False
red_ratio = red_count / total_samples if total_samples > 0 else 0
return red_ratio >= 0.25
except Exception:
return False
def detect_fansclub_join_red_area(pic_rgb: Image.Image) -> bool:
"""检测粉丝团加入:大片红色区域。
粉丝团加入按钮通常在屏幕中下部,有大片红色背景。
检测区域:(200,1940)-(880,2140) 基准1080x2400
"""
try:
width, height = pic_rgb.size
# 缩放坐标到实际尺寸
scale_x = width / 1080.0
scale_y = height / 2400.0
# 检测区域(基准1080x2400)
x1 = int(200 * scale_x)
y1 = int(1940 * scale_y)
x2 = int(880 * scale_x)
y2 = int(2140 * scale_y)
# 确保坐标在范围内
x1 = max(0, min(x1, width))
y1 = max(0, min(y1, height))
x2 = max(0, min(x2, width))
y2 = max(0, min(y2, height))
if x1 >= x2 or y1 >= y2:
return False
# 采样检测点:检测大片红色区域
red_count = 0
sample_points = []
step_x = max(1, (x2 - x1) // 15)
step_y = max(1, (y2 - y1) // 10)
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
# 检测红色:R值高,G和B相对较低
if r > 200 and (r - g) > 50 and (r - b) > 50:
red_count += 1
except Exception:
continue
# 如果红色像素占比足够高(至少25%),认为有大片红色背景
total_samples = len(list(range(y1, y2, step_y))) * len(list(range(x1, x2, step_x)))
if total_samples == 0:
return False
red_ratio = red_count / total_samples if total_samples > 0 else 0
return red_ratio >= 0.25
except Exception:
return False
def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
"""通过像素检测右上角x和xin图标区域,判断是否在直播间。
检测右上角区域(60%-100%宽度,0%-40%高度)的像素特征:
- x图标:通常是白色或浅色的X形状
- xin图标:通常是粉色/红色的心形图标
返回:
(detected, confidence) 其中 confidence 为置信度(0.0~1.0)
"""
try:
width, height = pic_rgb.size
# 缩放坐标到实际尺寸(基于1080x2400)
scale_x = width / 1080.0
scale_y = height / 2400.0
# 检测区域:右上角(60%-100%宽度,0%-40%高度)
x1 = int(648 * scale_x) # 60%宽度 = 648
y1 = 0
x2 = width # 100%宽度
y2 = int(960 * scale_y) # 40%高度 = 960
# 确保坐标在范围内
x1 = max(0, min(x1, width))
y1 = max(0, min(y1, height))
x2 = max(0, min(x2, width))
y2 = max(0, min(y2, height))
if x1 >= x2 or y1 >= y2:
return False, 0.0
# 采样检测点
step_x = max(1, (x2 - x1) // 20)
step_y = max(1, (y2 - y1) // 20)
# 检测特征:
# 1. 白色/浅色像素(x图标)
# 2. 粉色/红色像素(xin图标)
white_count = 0
pink_red_count = 0
total_samples = 0
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
total_samples += 1
# 检测白色/浅色(x图标):RGB值都较高且接近
if r > 200 and g > 200 and b > 200 and abs(r - g) < 30 and abs(g - b) < 30:
white_count += 1
# 检测粉色/红色(xin图标):R值高,G和B相对较低
if r > 200 and (r - g) > 50 and (r - b) > 50:
pink_red_count += 1
except Exception:
continue
if total_samples == 0:
return False, 0.0
# 计算置信度
white_ratio = white_count / total_samples if total_samples > 0 else 0
pink_red_ratio = pink_red_count / total_samples if total_samples > 0 else 0
# 如果白色或粉色/红色像素占比足够高,认为检测到图标
# 阈值:白色>=5% 或 粉色/红色>=3%
detected = white_ratio >= 0.05 or pink_red_ratio >= 0.03
# 计算置信度(基于检测到的像素比例)
confidence = min(1.0, max(white_ratio * 10, pink_red_ratio * 15))
return detected, confidence
except Exception:
return False, 0.0
def read_pixel_stage_state_from_screenshot(pic_path: str) -> dict[str, bool]:
"""从 screenshot.png 读取"阶段诊断"需要的多区域像素特征(不调用 OCR)。
使用多线程并行执行所有检测函数以提高性能。
"""
state: dict[str, bool] = {
"has_coupon_bg": False,
"has_redpacket_bg": False,
"has_lucky_draw_result": False,
"has_attend_button_red": False,
"has_fansclub_join_red": False,
}
pic_rgb = _safe_open_screenshot_rgb(pic_path)
if pic_rgb is None:
return state
# 并行执行所有检测函数
detection_tasks = {
"has_coupon_bg": detect_coupon_popup_background,
"has_redpacket_bg": detect_redpacket_popup_background,
"has_lucky_draw_result": detect_lucky_draw_result_popup,
"has_attend_button_red": detect_attend_button_red_area,
"has_fansclub_join_red": detect_fansclub_join_red_area,
}
# 使用线程池并行执行检测
with ThreadPoolExecutor(max_workers=5) as executor:
# 提交所有任务
future_to_key = {
executor.submit(detect_func, pic_rgb): key
for key, detect_func in detection_tasks.items()
}
# 收集结果
for future in as_completed(future_to_key):
key = future_to_key[future]
try:
result = future.result()
state[key] = bool(result)
except Exception:
# 如果某个检测失败,保持默认值 False
state[key] = False
return state
+321
View File
@@ -0,0 +1,321 @@
from __future__ import annotations
import os
import time
from PIL import Image
import douyin_pixel
def check_coupon_popup(analyser) -> bool:
"""從 `douyin_fudai.fudai_analyse._check_coupon_popup` 抽離。
像素優先,OCR 僅作補充且不推翻像素結論。
analyser 需提供:
- cut_pic(...)
- operation.analyse_pic_word(...)
- _log_kv(...)
"""
check_start = time.time()
# 步驟0:快速像素檢測彈窗背景(粉色/紅色區域)
pixel_check_start = time.time()
has_popup_background = False
try:
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
pic = Image.open(pic_path).convert("RGB")
has_popup_background = bool(douyin_pixel.detect_coupon_popup_background(pic))
_ = time.time() - pixel_check_start
if not has_popup_background:
return False
except Exception:
_ = time.time() - pixel_check_start
has_popup_background = False
# 步驟1:截圖標題區域
cut_title_start = time.time()
try:
analyser.cut_pic(60, 1260, 1020, 1480, "", "診斷優惠券標題")
cut_title_elapsed = time.time() - cut_title_start
except Exception as e:
cut_title_elapsed = time.time() - cut_title_start
analyser._log_kv("彈窗檢測步驟", "優惠券-截圖標題區域失敗", error=str(e), 耗時秒=f"{cut_title_elapsed:.3f}")
return False
# 步驟2:OCR 標題(模式0)
ocr_title0_start = time.time()
try:
t1 = str(analyser.operation.analyse_pic_word("診斷優惠券標題", 0) or "")
ocr_title0_elapsed = time.time() - ocr_title0_start
except Exception as e:
t1 = ""
ocr_title0_elapsed = time.time() - ocr_title0_start
analyser._log_kv("彈窗檢測步驟", "優惠券-OCR標題區域(模式0)失敗", error=str(e), 耗時秒=f"{ocr_title0_elapsed:.3f}")
# 步驟3:模式1(僅在模式0為空時)
ocr_title1_elapsed = 0.0
if not t1:
ocr_title1_start = time.time()
try:
t1 = str(analyser.operation.analyse_pic_word("診斷優惠券標題", 1) or "")
ocr_title1_elapsed = time.time() - ocr_title1_start
except Exception as e:
ocr_title1_elapsed = time.time() - ocr_title1_start
analyser._log_kv("彈窗檢測步驟", "優惠券-OCR標題區域(模式1)失敗", error=str(e), 耗時秒=f"{ocr_title1_elapsed:.3f}")
if not t1:
if has_popup_background:
total_elapsed = time.time() - check_start
analyser._log_kv(
"彈窗檢測步驟",
"優惠券-標題OCR為空但像素判定有彈窗,按像素結果返回",
總耗時秒=f"{total_elapsed:.3f}",
截圖耗時秒=f"{cut_title_elapsed:.3f}",
像素判定="有彈窗背景",
)
return True
return False
strong_keywords_title = ("購物券", "新客", "專享券")
if any(kw in t1 for kw in strong_keywords_title):
total_elapsed = time.time() - check_start
matched_strong = [kw for kw in strong_keywords_title if kw in t1]
analyser._log_kv(
"彈窗檢測步驟",
"優惠券-標題區域檢測到強關鍵詞,快速返回",
匹配到的強關鍵詞=matched_strong,
識別文本=t1[:50],
總耗時秒=f"{total_elapsed:.3f}",
截圖耗時秒=f"{cut_title_elapsed:.3f}",
OCR耗時秒=f"{(ocr_title0_elapsed + ocr_title1_elapsed):.3f}",
節省="跳過按鈕檢測",
)
return True
import re
t1_stripped = t1.strip()
possible_chars = ("券", "新", "客", "購", "物", "專", "享", "領", "取", "收", "下", "一", "得", "元", "分鐘")
if not any(char in t1_stripped for char in possible_chars):
return False
t1_clean = re.sub(r"[\s\d\W]", "", t1_stripped)
if len(t1_clean) < 2:
if has_popup_background:
total_elapsed = time.time() - check_start
analyser._log_kv(
"彈窗檢測步驟",
"優惠券-標題文本過短但像素判定有彈窗,按像素結果返回",
總耗時秒=f"{total_elapsed:.3f}",
截圖耗時秒=f"{cut_title_elapsed:.3f}",
像素判定="有彈窗背景",
標題文本=t1[:50],
)
return True
return False
# 步驟4:截圖按鈕區域
cut_btn_start = time.time()
try:
analyser.cut_pic(260, 2080, 820, 2240, "", "診斷優惠券按鈕")
cut_btn_elapsed = time.time() - cut_btn_start
except Exception as e:
cut_btn_elapsed = time.time() - cut_btn_start
analyser._log_kv("彈窗檢測步驟", "優惠券-截圖按鈕區域失敗", error=str(e), 耗時秒=f"{cut_btn_elapsed:.3f}")
cut_btn_elapsed = 0.0
# 步驟5:OCR 按鈕(模式0)
ocr_btn0_start = time.time()
try:
t2 = str(analyser.operation.analyse_pic_word("診斷優惠券按鈕", 0) or "")
ocr_btn0_elapsed = time.time() - ocr_btn0_start
except Exception as e:
t2 = ""
ocr_btn0_elapsed = time.time() - ocr_btn0_start
analyser._log_kv("彈窗檢測步驟", "優惠券-OCR按鈕區域(模式0)失敗", error=str(e), 耗時秒=f"{ocr_btn0_elapsed:.3f}")
# 步驟6:模式1(僅在模式0為空時)
ocr_btn1_elapsed = 0.0
if not t2:
ocr_btn1_start = time.time()
try:
t2 = str(analyser.operation.analyse_pic_word("診斷優惠券按鈕", 1) or "")
ocr_btn1_elapsed = time.time() - ocr_btn1_start
except Exception as e:
ocr_btn1_elapsed = time.time() - ocr_btn1_start
analyser._log_kv("彈窗檢測步驟", "優惠券-OCR按鈕區域(模式1)失敗", error=str(e), 耗時秒=f"{ocr_btn1_elapsed:.3f}")
hay = (t1 + " " + t2).strip()
if not hay:
if has_popup_background:
total_elapsed = time.time() - check_start
analyser._log_kv(
"彈窗檢測步驟",
"優惠券-OCR標題和按鈕均為空,但像素判定有彈窗,按像素結果返回",
總耗時秒=f"{total_elapsed:.3f}",
像素判定="有彈窗背景",
)
return True
return False
strong_keywords = ("購物券", "新客", "專享券")
weak_keywords = ("領取", "收下", "開心收下")
has_strong_keyword = any(kw in hay for kw in strong_keywords)
has_weak_keyword = any(kw in hay for kw in weak_keywords)
has_coupon_keyword = ("券" in hay) or ("新客" in hay) or ("購物券" in hay)
result = has_strong_keyword or (has_weak_keyword and has_coupon_keyword)
if not result and has_popup_background:
result = True
total_elapsed = time.time() - check_start
ocr_total = ocr_title0_elapsed + ocr_title1_elapsed + ocr_btn0_elapsed + ocr_btn1_elapsed
if result:
matched_keys = [kw for kw in strong_keywords if kw in hay] + [kw for kw in weak_keywords if kw in hay]
analyser._log_kv("彈窗檢測步驟", "優惠券-檢測到彈窗", 匹配到的關鍵詞=matched_keys, 總耗時秒=f"{total_elapsed:.3f}", OCR耗時秒=f"{ocr_total:.3f}")
else:
matched_keys = [kw for kw in strong_keywords if kw in hay] + [kw for kw in weak_keywords if kw in hay]
analyser._log_kv(
"彈窗檢測步驟",
"優惠券-未檢測到彈窗",
合併文本=hay[:100] if hay else "空",
匹配到的關鍵詞=matched_keys if matched_keys else [],
總耗時秒=f"{total_elapsed:.3f}",
OCR耗時秒=f"{ocr_total:.3f}",
)
return result
def check_shopping_redpacket_popup(analyser) -> bool:
"""從 `douyin_fudai.fudai_analyse._check_shopping_redpacket_popup` 抽離。
像素優先,OCR 僅作補充且不推翻像素結論。
"""
check_start = time.time()
# 步驟0:快速像素檢測中央紅色彈窗背景
pixel_check_start = time.time()
has_popup_pixel = False
try:
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
pic = Image.open(pic_path).convert("RGB")
has_popup_pixel = bool(douyin_pixel.detect_redpacket_popup_background(pic))
_ = time.time() - pixel_check_start
if not has_popup_pixel:
return False
except Exception:
_ = time.time() - pixel_check_start
has_popup_pixel = False
# 步驟1:截圖檢測區域
cut_start = time.time()
try:
analyser.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
_ = time.time() - cut_start
except Exception as e:
cut_elapsed = time.time() - cut_start
analyser._log_kv("彈窗檢測步驟", "購物紅包-截圖區域失敗", error=str(e), 耗時秒=f"{cut_elapsed:.3f}")
return False
# OCR 模式0
ocr_mode0_start = time.time()
try:
t = str(analyser.operation.analyse_pic_word("診斷購物紅包", 0) or "")
hay = t.strip() if t else ""
ocr_mode0_elapsed = time.time() - ocr_mode0_start
except Exception as e:
hay = ""
ocr_mode0_elapsed = time.time() - ocr_mode0_start
analyser._log_kv("彈窗檢測步驟", "購物紅包-OCR(模式0)失敗", error=str(e), 耗時秒=f"{ocr_mode0_elapsed:.3f}")
if not hay:
if has_popup_pixel:
total_elapsed = time.time() - check_start
analyser._log_kv(
"彈窗檢測步驟",
"購物紅包-OCR內容為空但像素判定有紅包彈窗,按像素結果返回",
總耗時秒=f"{total_elapsed:.3f}",
像素判定="有紅包彈窗背景",
)
return True
# 嘗試按鈕區域快速 OCR(兜底)
try:
analyser.cut_pic(400, 1200, 680, 1400, "", "診斷購物紅包按鈕")
btn_text = str(analyser.operation.analyse_pic_word("診斷購物紅包按鈕", 0) or "").strip()
if "搶" in btn_text:
total_elapsed = time.time() - check_start
analyser._log_kv("彈窗檢測步驟", "購物紅包-檢測到彈窗(按鈕區域)", 識別文本=btn_text[:50], 總耗時秒=f"{total_elapsed:.3f}", 檢測方式="按鈕區域快速檢測")
return True
except Exception:
pass
return False
keywords = ("邀你搶購物紅包", "搶購物紅包", "購物紅包", "邀你搶", "搶紅包", "搶")
if any(kw in hay for kw in keywords):
matched = [kw for kw in keywords if kw in hay]
total_elapsed = time.time() - check_start
analyser._log_kv("彈窗檢測步驟", "購物紅包-檢測到彈窗", 匹配到的關鍵詞=matched, 總耗時秒=f"{total_elapsed:.3f}", OCR耗時秒=f"{ocr_mode0_elapsed:.3f}")
return True
texts = [hay]
ocr_mode1_elapsed = 0.0
ocr_mode2_elapsed = 0.0
# 模式1
ocr_mode1_start = time.time()
try:
t1 = str(analyser.operation.analyse_pic_word("診斷購物紅包", 1) or "")
hay1 = t1.strip() if t1 else ""
ocr_mode1_elapsed = time.time() - ocr_mode1_start
if hay1:
texts.append(hay1)
if any(kw in hay1 for kw in keywords):
matched = [kw for kw in keywords if kw in hay1]
total_elapsed = time.time() - check_start
analyser._log_kv("彈窗檢測步驟", "購物紅包-檢測到彈窗(模式1)", 匹配到的關鍵詞=matched, 總耗時秒=f"{total_elapsed:.3f}", OCR耗時秒=f"{(ocr_mode0_elapsed + ocr_mode1_elapsed):.3f}")
return True
except Exception as e:
ocr_mode1_elapsed = time.time() - ocr_mode1_start
analyser._log_kv("彈窗檢測步驟", "購物紅包-OCR(模式1)失敗", error=str(e), 耗時秒=f"{ocr_mode1_elapsed:.3f}")
# 模式2
ocr_mode2_start = time.time()
try:
t2 = str(analyser.operation.analyse_pic_word("診斷購物紅包", 2) or "")
hay2 = t2.strip() if t2 else ""
ocr_mode2_elapsed = time.time() - ocr_mode2_start
if hay2:
texts.append(hay2)
if any(kw in hay2 for kw in keywords):
matched = [kw for kw in keywords if kw in hay2]
total_elapsed = time.time() - check_start
analyser._log_kv(
"彈窗檢測步驟",
"購物紅包-檢測到彈窗(模式2)",
匹配到的關鍵詞=matched,
總耗時秒=f"{total_elapsed:.3f}",
OCR耗時秒=f"{(ocr_mode0_elapsed + ocr_mode1_elapsed + ocr_mode2_elapsed):.3f}",
)
return True
except Exception as e:
ocr_mode2_elapsed = time.time() - ocr_mode2_start
analyser._log_kv("彈窗檢測步驟", "購物紅包-OCR(模式2)失敗", error=str(e), 耗時秒=f"{ocr_mode2_elapsed:.3f}")
combined_text = " ".join(texts).strip()
final_keywords = ("購物紅包", "邀你搶", "搶紅包")
result = any(kw in combined_text for kw in final_keywords)
if not result and has_popup_pixel:
result = True
total_elapsed = time.time() - check_start
ocr_total = ocr_mode0_elapsed + ocr_mode1_elapsed + ocr_mode2_elapsed
if result:
matched = [kw for kw in final_keywords if kw in combined_text]
analyser._log_kv("彈窗檢測步驟", "購物紅包-檢測到彈窗(合併檢查)", 匹配到的關鍵詞=matched, 總耗時秒=f"{total_elapsed:.3f}", OCR耗時秒=f"{ocr_total:.3f}")
else:
analyser._log_kv("彈窗檢測步驟", "購物紅包-未檢測到彈窗", 合併文本=combined_text[:100] if combined_text else "空", 總耗時秒=f"{total_elapsed:.3f}", OCR耗時秒=f"{ocr_total:.3f}")
return result
+119
View File
@@ -0,0 +1,119 @@
from __future__ import annotations
import json
import os
import time
from datetime import datetime
def _write_json_atomic(path: str, data: object, *, indent: int = 2) -> None:
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=indent)
f.write("\n")
os.replace(tmp, path)
def write_reservations_state(
*,
state_path: str,
reservations: list[dict],
room_pos: int,
current_room_title: str,
current_room_title_raw: str,
reason: str = "",
) -> None:
"""寫入預約隊列狀態(跨進程可讀)。"""
try:
items: list[dict] = []
for r in reservations or []:
try:
ft = float(r.get("future_ts") or 0)
except Exception:
ft = 0.0
try:
ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft else ""
except Exception:
ft_str = ""
items.append(
{
"prize_value_yuan": float(r.get("prize_value_yuan") or 0),
"content": str(r.get("content") or ""),
"future_ts": ft,
"future_str": ft_str,
"pos_seen": int(r.get("pos_seen") or 0),
"room_title": str(r.get("room_title") or ""),
"room_title_raw": str(r.get("room_title_raw") or ""),
}
)
data = {
"updated_ts": time.time(),
"reason": str(reason or ""),
"room_pos": int(room_pos),
"current_room_title": str(current_room_title or ""),
"current_room_title_raw": str(current_room_title_raw or ""),
"reservations": items,
}
_write_json_atomic(state_path, data, indent=2)
except Exception as e:
try:
print(f"[预约队列] 写入状态文件失败: {type(e).__name__}: {e}")
except Exception:
pass
def load_high_value_rooms_map(path: str) -> dict[str, dict]:
"""讀取高價值直播間映射(跨運行持久化)。"""
try:
if not os.path.exists(path):
return {}
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
# 兼容兩種格式:{"rooms": [...]} 或 直接是 [...]
rooms = None
if isinstance(data, dict):
rooms = data.get("rooms")
elif isinstance(data, list):
rooms = data
out: dict[str, dict] = {}
if isinstance(rooms, list):
for it in rooms:
if not isinstance(it, dict):
continue
key = str(it.get("room_title") or "").strip()
if not key:
continue
out[key] = dict(it)
return out
except Exception:
return {}
def write_high_value_rooms_state(path: str, rooms_map: dict, *, reason: str = "") -> None:
"""寫入高價值直播間映射(跨運行持久化)。"""
try:
rooms: list[dict] = []
for k, v in (rooms_map or {}).items():
if not k:
continue
item = dict(v or {})
item["room_title"] = str(k)
rooms.append(item)
rooms.sort(key=lambda x: float(x.get("last_seen_ts") or 0.0), reverse=True)
data = {
"updated_ts": time.time(),
"reason": str(reason or ""),
"total": int(len(rooms)),
"rooms": rooms,
}
_write_json_atomic(path, data, indent=2)
except Exception:
pass
+368
View File
@@ -0,0 +1,368 @@
from __future__ import annotations
"""
Reservation core logic shim (WebGUI version)
===========================================
Exports:
- add_reservation_core_logic
- validate_back_to_reservation
- cleanup_expired_reservations
- process_reservation_attend_window
- record_high_value_reservation
"""
from typing import Any, Dict, List
import time
def add_reservation_core_logic(
reservations: List[Dict[str, Any]],
item: Dict[str, Any],
) -> None:
"""Shim: append item if not already present by basic key."""
key = (item.get("future_ts"), item.get("content"))
for r in reservations:
if (r.get("future_ts"), r.get("content")) == key:
return
reservations.append(dict(item))
def validate_back_to_reservation(
analyser: Any,
reservations: List[Dict[str, Any]],
now_ts: float | None = None,
) -> None:
"""兼容实现:记录当前预约队列状态,不做严格校验。"""
if now_ts is None:
now_ts = time.time()
try:
analyser._log_kv(
"预约",
"validate_back_to_reservation",
count=len(reservations),
now_ts=int(now_ts),
)
except Exception:
pass
def cleanup_expired_reservations(
analyser: Any,
reservations: List[Dict[str, Any]],
write_state_callback,
) -> None:
"""兼容实现:清理已过开奖时间的预约,然后写入状态。"""
try:
now_ts_drop = time.time()
dropped = 0
for r in list(reservations):
try:
ft = float(r.get("future_ts") or 0.0)
except Exception:
ft = 0.0
if ft > 0 and now_ts_drop >= ft:
try:
reservations.remove(r)
except Exception:
try:
reservations.pop()
except Exception:
pass
dropped += 1
if dropped and write_state_callback is not None:
try:
write_state_callback()
except Exception:
pass
except Exception:
# Best-effort cleanup only; never crash main loop
pass
def process_reservation_attend_window(
analyser: Any,
reservations: List[Dict[str, Any]],
room_pos: int,
reservation_focus_until_ts_ref: list,
reservation_after_action_pending_ref: list,
reservation_back_swipe_delay_s: float,
swipe_down_back_callback,
seek_reservation_room_callback,
sort_reservations_callback,
write_state_callback,
) -> bool:
"""兼容实现:匹配原始签名,仅记录预约窗口信息,不主动抢占主流程。"""
try:
analyser._log_kv(
"预约",
"process_reservation_attend_window",
count=len(reservations),
room_pos=room_pos,
)
except Exception:
pass
return False
def record_high_value_reservation(
analyser: Any,
fudai_content_text: str,
prize_value_yuan: float,
lastsecond: int,
future_timestamp: float,
x: int,
needswitch: bool,
wait_minutes: int,
post_switch_delay_s: float,
room_pos: int,
reservations: List[Dict[str, Any]],
reservation_focus_until_ts_ref: list,
close_detail_callback,
swipe_up_switch_callback,
swipe_down_back_callback,
add_reservation_callback,
sort_reservations_callback,
write_state_callback,
) -> bool:
"""兼容实现:按原始签名追加一条简化的高价值预约记录。"""
try:
item: Dict[str, Any] = {
"future_ts": float(future_timestamp or 0.0),
"prize_value_yuan": float(prize_value_yuan or 0.0),
"content": str(fudai_content_text or ""),
"pos_seen": int(room_pos),
"created_ts": time.time(),
}
add_reservation_core_logic(reservations, item)
analyser._log_kv(
"预约",
"record_high_value_reservation:已记录高价值福袋",
value=item["prize_value_yuan"],
future_ts=item["future_ts"],
)
except Exception:
pass
return False
"""
Reservation core logic shim (WebGUI version)
===========================================
Exports:
- add_reservation_core_logic
- validate_back_to_reservation
- cleanup_expired_reservations
- process_reservation_attend_window
- record_high_value_reservation
"""
from typing import Any, Dict, List
import time
def add_reservation_core_logic(
reservations: List[Dict[str, Any]],
item: Dict[str, Any],
) -> None:
"""Shim: append item if not already present by basic key."""
key = (item.get("future_ts"), item.get("content"))
for r in reservations:
if (r.get("future_ts"), r.get("content")) == key:
return
reservations.append(dict(item))
def validate_back_to_reservation(
analyser: Any,
reservations: List[Dict[str, Any]],
now_ts: float | None = None,
) -> None:
"""兼容实现:记录当前预约队列状态,不做严格校验。"""
if now_ts is None:
now_ts = time.time()
try:
analyser._log_kv(
"预约",
"validate_back_to_reservation",
count=len(reservations),
now_ts=int(now_ts),
)
except Exception:
pass
def cleanup_expired_reservations(
analyser: Any,
reservations: List[Dict[str, Any]],
write_state_callback,
) -> None:
"""兼容实现:清理已过开奖时间的预约,然后写入状态。"""
try:
now_ts_drop = time.time()
dropped = 0
for r in list(reservations):
try:
ft = float(r.get("future_ts") or 0.0)
except Exception:
ft = 0.0
if ft > 0 and now_ts_drop >= ft:
try:
reservations.remove(r)
except Exception:
try:
reservations.pop()
except Exception:
pass
dropped += 1
if dropped and write_state_callback is not None:
try:
write_state_callback()
except Exception:
pass
except Exception:
# Best-effort cleanup only; never crash main loop
pass
def process_reservation_attend_window(
analyser: Any,
reservations: List[Dict[str, Any]],
room_pos: int,
reservation_focus_until_ts_ref: list,
reservation_after_action_pending_ref: list,
reservation_back_swipe_delay_s: float,
swipe_down_back_callback,
seek_reservation_room_callback,
sort_reservations_callback,
write_state_callback,
) -> bool:
"""兼容实现:匹配原始签名,仅记录预约窗口信息,不主动抢占主流程。"""
try:
analyser._log_kv(
"预约",
"process_reservation_attend_window",
count=len(reservations),
room_pos=room_pos,
)
except Exception:
pass
return False
def record_high_value_reservation(
analyser: Any,
fudai_content_text: str,
prize_value_yuan: float,
lastsecond: int,
future_timestamp: float,
x: int,
needswitch: bool,
wait_minutes: int,
post_switch_delay_s: float,
room_pos: int,
reservations: List[Dict[str, Any]],
reservation_focus_until_ts_ref: list,
close_detail_callback,
swipe_up_switch_callback,
swipe_down_back_callback,
add_reservation_callback,
sort_reservations_callback,
write_state_callback,
) -> bool:
"""兼容实现:按原始签名追加一条简化的高价值预约记录。"""
try:
item: Dict[str, Any] = {
"future_ts": float(future_timestamp or 0.0),
"prize_value_yuan": float(prize_value_yuan or 0.0),
"content": str(fudai_content_text or ""),
"pos_seen": int(room_pos),
"created_ts": time.time(),
}
add_reservation_core_logic(reservations, item)
analyser._log_kv(
"预约",
"record_high_value_reservation:已记录高价值福袋",
value=item["prize_value_yuan"],
future_ts=item["future_ts"],
)
except Exception:
pass
return False
def record_high_value_reservation(
analyser: Any,
fudai_content_text: str,
prize_value_yuan: float,
lastsecond: int,
future_timestamp: float,
x: int,
needswitch: bool,
wait_minutes: int,
post_switch_delay_s: float,
room_pos: int,
reservations: List[Dict[str, Any]],
reservation_focus_until_ts_ref: list,
close_detail_callback,
swipe_up_switch_callback,
swipe_down_back_callback,
add_reservation_callback,
sort_reservations_callback,
write_state_callback,
) -> bool:
"""Shim: match original signature and optionally append a simple reservation.
To keep behavior safe and simple, we:
- create a minimal reservation dict; and
- append it to `reservations` without triggering any side-effects.
"""
try:
item: Dict[str, Any] = {
"future_ts": float(future_timestamp or 0.0),
"prize_value_yuan": float(prize_value_yuan or 0.0),
"content": str(fudai_content_text or ""),
"pos_seen": int(room_pos),
"created_ts": time.time(),
}
add_reservation_core_logic(reservations, item)
analyser._log_kv(
"预约",
"使用精简版 record_high_value_reservation:已记录高价值福袋",
value=item["prize_value_yuan"],
future_ts=item["future_ts"],
)
except Exception:
pass
return False
View File
Whitespace-only changes.
+139
View File
@@ -0,0 +1,139 @@
from __future__ import annotations
import os
from typing import Any
from PIL import Image
def check_have_robot_analyse(analyser) -> int | bool:
"""检查是否存在人机校验。
返回:
- 1: 滑动图片验证
- 2: 点击图片验证(形状相同)
- 3: 人脸识别验证
- False: 未检测到人机验证
"""
analyser.cut_pic(130, 790, 680, 870, "", "直播验证")
result = analyser.operation.analyse_pic_word("直播验证", 1)
if "验证" in result:
print("存在滑动图片人机校验,需要等待完成验证.")
return 1
elif "形状相同" in result:
print("存在点击图片人机校验,需要等待完成验证.")
return 2
analyser.cut_pic(340, 1415, 700, 1518, "", "直播验证")
result = analyser.operation.analyse_pic_word("直播验证")
if "开始检测" in result:
print("存在人脸识别人机校验,需要等待完成验证.")
return 3
return False
def deal_swipe_robot_analyse(analyser, distance: int = 400) -> None:
"""处理滑动图片的人机验证。"""
if distance:
targetx = (222 + distance) * analyser.resolution_ratio_x // 1080
else:
targetx = 622 * analyser.resolution_ratio_x // 1080
analyser.swipe(222, 1444, targetx, 1444, 300)
print("滑轨滑动{}距离解锁人机验证".format(distance))
analyser.operation.delay(1)
def deal_robot_analyse(analyser) -> None:
"""处理人机校验,包含各种情况。"""
swipe_times = 0
while swipe_times < 10:
robot_result = check_have_robot_analyse(analyser)
if robot_result == 1:
distance = check_robot_pic_distance(analyser)
deal_swipe_robot_analyse(analyser, distance)
analyser.operation.delay(10)
analyser._shot_and_diagnose("人机校验", "校验后复查", analyser.device_id)
elif robot_result == 2:
print("无法处理图片验证的人机,点击关闭退出验证,等待30分钟")
analyser.click(910, 800) # 点击关闭
analyser.operation.delay(1800)
break
elif robot_result == 3:
print("无法处理人脸识别验证的人机,点击返回退出验证,等待30分钟")
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(2)
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(1800)
break
else:
break
swipe_times += 1
if swipe_times >= 10:
print("无法处理图片验证的人机,点击关闭退出验证,等待30分钟")
analyser.click(910, 800) # 点击关闭
analyser.operation.delay(1800)
def deal_robot_pic_change_color(analyser) -> None:
"""处理人机验证的图片,转为黑白图。"""
analyser.cut_pic(143, 884, 936, 1380, "save", "机器人验证")
path = os.path.join(os.path.dirname(__file__), "pic", "save")
pic = os.path.join(path, "机器人验证.png")
img = Image.open(pic)
img = img.convert("RGB")
width, height = img.size
for x in range(5, width - 40):
for y in range(20, height - 30):
current_color = img.getpixel((x, y))
if current_color[0] > 240 and current_color[1] > 240 and current_color[2] > 240:
img.putpixel((x, y), (255, 255, 255)) # 白色
elif current_color[0] < 35 and current_color[1] < 20 and current_color[2] < 20:
img.putpixel((x, y), (0, 0, 0)) # 黑色
else:
img.putpixel((x, y), (128, 128, 128)) # 灰色
os.makedirs(path, exist_ok=True)
save_pic = os.path.join(path, "机器人验证_新.png")
img.save(save_pic)
def check_robot_pic_distance(analyser) -> int:
"""根据人机图片计算需要滑动的距离。"""
analyser.cut_pic(143, 884, 936, 1380, "", "机器人验证")
# 使用新的路径查找方法(支持新旧位置)
pic_path = analyser.operation._find_pic_path("机器人验证", for_reading=True)
if not pic_path or not os.path.exists(pic_path):
raise FileNotFoundError(f"机器人验证图片不存在: {pic_path}")
img = Image.open(pic_path)
img = img.convert("RGB")
width, height = img.size
printed_first_result = False # 用于记录第一个结果是否已经输出过
printed_second_result = False # 用于记录第二个结果是否已经输出过
x = 0
y = 0
for y in range(20, height - 30):
for x in range(5, width - 40):
current_color = img.getpixel((x, y))
if current_color[0] > 240 and current_color[1] > 240 and current_color[2] > 240:
if not printed_first_result: # 确保只输出一次第一个结果
print(x, y)
printed_first_result = True
break
if printed_first_result: # 如果已经输出过第一个结果,则退出外层循环
break
for x1 in range(x, width - 40):
current_color = img.getpixel((x1, y))
if (
current_color[0] < 50
and current_color[1] < 55
and current_color[2] < 85
and current_color[0] + current_color[1] + current_color[2] < 150
):
if not printed_second_result: # 确保只输出一次第二个结果
print(x1, y)
printed_second_result = True
print("需要滑动的距离为{}".format(x1 - x))
return x1 - x
# 如果没有检测到,返回一个兜底值 0
return 0
+781
View File
@@ -0,0 +1,781 @@
from __future__ import annotations
import douyin_pixel
def diagnose_stage_from_current_screen(self):
"""完整抽離自 `douyin_fudai.fudai_analyse._diagnose_stage_from_current_screen`。
日志輸出已從 print 改為 _log_kv,方便結構化查看。
当前模式:优先使用像素检测,OCR检测已暂时关闭用于测试像素检测精准度。
"""
import time
def _log(msg: str, **fields):
"""阶段诊断统一日志入口,使用 self._log_kv 输出。"""
try:
self._log_kv("阶段诊断", msg, **fields)
except Exception:
# 兜底:避免任何日志异常影响主流程
pass
diag_start = time.time()
max_diag_time = getattr(self, "stage_diag_max_time", 10.0) # 最大诊断时间(可配置,默认10秒)
max_step_time = getattr(self, "stage_diag_max_step_time", 2.0) # 每个步骤最大耗时(可配置,默认2秒)
_log("开始阶段诊断", 最大诊断时间秒=max_diag_time, 单步最大耗时秒=max_step_time)
# ========== 步骤0:首先检测是否在直播间(最优先)==========
step_start = time.time()
_log("步骤0[检测直播间]-开始", 说明="优先像素检测,然后模板匹配,最后OCR回退")
in_live_room = False
live_room_score = 0.0
detection_method = ""
# 第一步:优先使用像素检测
# 获取像素检测阈值(用于判断置信度是否达到要求)
pixel_threshold = float(getattr(self, "live_room_match_threshold", 0.8) or 0.8)
if pixel_threshold < 0.0:
pixel_threshold = 0.0
if pixel_threshold > 1.0:
pixel_threshold = 1.0
try:
pixel_start = time.time()
import os
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
if os.path.exists(pic_path):
pic_rgb = douyin_pixel._safe_open_screenshot_rgb(pic_path)
if pic_rgb is not None:
detected, confidence = douyin_pixel.detect_live_room_icons_by_pixel(pic_rgb)
pixel_elapsed = (time.time() - pixel_start) * 1000
# 使用 live_room_match_threshold 判断像素检测的置信度是否达到阈值
if detected and confidence >= pixel_threshold:
in_live_room = True
live_room_score = float(confidence or 0.0)
detection_method = "像素检测"
_log(
"步骤0[检测直播间]-命中(像素检测)",
置信度=round(confidence, 3),
阈值=pixel_threshold,
耗时毫秒=pixel_elapsed,
)
else:
_log(
"步骤0[检测直播间]-像素检测未命中",
置信度=round(confidence, 3),
阈值=pixel_threshold,
耗时毫秒=pixel_elapsed,
)
except Exception as e:
pixel_elapsed = (time.time() - step_start) * 1000
_log("步骤0[检测直播间]-像素检测异常", 耗时毫秒=pixel_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
# 第二步:如果像素检测失败,使用模板匹配
if not in_live_room:
try:
template_start = time.time()
detected, score = self._check_in_live_room_by_icon()
template_elapsed = (time.time() - template_start) * 1000
if detected:
in_live_room = True
live_room_score = float(score or 0.0)
detection_method = "模板匹配"
_log("步骤0[检测直播间]-命中(模板匹配)", 分数=live_room_score, 耗时毫秒=template_elapsed)
else:
_log("步骤0[检测直播间]-模板匹配未命中", 分数=live_room_score, 耗时毫秒=template_elapsed)
except Exception as e:
template_elapsed = (time.time() - step_start) * 1000
_log("步骤0[检测直播间]-模板匹配异常", 耗时毫秒=template_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
if in_live_room:
total_elapsed = (time.time() - step_start) * 1000
_log("步骤0[检测直播间]-最终结果:在直播间", 检测方法=detection_method, 分数=live_room_score, 总耗时毫秒=total_elapsed)
# 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)
if not in_live_room:
_log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)")
# 步骤3:检测推荐页面、关注列表、直播列表(OCR标签栏,整合在一起检测)
step_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤3[OCR推荐页/关注列表/直播列表]-开始", 剩余时间秒=remaining_time_before)
t_recommend = ""
t_follow = ""
t_list = ""
try:
# 检测推荐页标签栏区域(包含"推荐"、"关注"、"直播"标签)
_log("步骤3[OCR推荐页标签栏]-区域", 区域="(400,140)-(900,200)")
if time.time() - step_start < max_step_time:
cut_start = time.time()
self.cut_pic(400, 140, 900, 200, "", "推荐页标签栏")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR推荐页标签栏]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
t_recommend = str(self.operation.analyse_pic_word("推荐页标签栏", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR推荐页标签栏]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_recommend),
文本预览=t_recommend[:50] if t_recommend else "",
)
if enable_ocr_mode1 and (time.time() - step_start < max_step_time) and (
not t_recommend or ("推荐" not in t_recommend and "关注" not in t_recommend and "直播" not in t_recommend)
):
ocr_start_1 = time.time()
t_recommend = str(self.operation.analyse_pic_word("推荐页标签栏", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤3[OCR推荐页标签栏]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_recommend),
文本预览=t_recommend[:50] if t_recommend else "",
)
elapsed_recommend = (time.time() - step_start) * 1000
# 如果识别到"推荐",直接返回推荐页面
if "推荐" in t_recommend:
total_elapsed = (time.time() - diag_start) * 1000
seen_text = t_recommend[:50] if t_recommend else "-"
_log(
"步骤3[OCR推荐页标签栏]-命中推荐",
耗时毫秒=elapsed_recommend,
总耗时毫秒=total_elapsed,
识别文本=seen_text,
)
_log("阶段诊断完成", 阶段="RECOMMEND_PAGE", 原因=f"标题='{t_recommend}'")
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
# 如果识别到"关注"但没有"推荐",可能是关注列表
if "关注" in t_recommend and "推荐" not in t_recommend:
_log("步骤3[OCR关注列表]-检测到关注关键词,准备精确确认", 精确区域="(658,147)-(765,194)")
step_start_follow = time.time()
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
self.cut_pic(658, 147, 765, 194, "", "关注列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR关注列表]-精确截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
t_follow = str(self.operation.analyse_pic_word("关注列表标签", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR关注列表]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_follow),
文本预览=t_follow[:50] if t_follow else "",
)
if (time.time() - step_start < max_step_time) and ("关注" not in t_follow):
ocr_start_1 = time.time()
t_follow = str(self.operation.analyse_pic_word("关注列表标签", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤3[OCR关注列表]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_follow),
文本预览=t_follow[:50] if t_follow else "",
)
except Exception as e:
import traceback
_log("步骤3[OCR关注列表]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc())
elapsed_follow = (time.time() - step_start_follow) * 1000
if "关注" in t_follow:
total_elapsed = (time.time() - diag_start) * 1000
follow_text = t_follow[:50] if t_follow else "-"
_log(
"步骤3[OCR关注列表]-命中",
耗时毫秒=elapsed_follow,
总耗时毫秒=total_elapsed,
识别文本=follow_text,
)
try:
self._last_follow_list_title_text = str(t_follow or "").strip()
except Exception:
self._last_follow_list_title_text = ""
_log("阶段诊断完成", 阶段="FOLLOW_LIST", 原因=f"标题='{t_follow}'")
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
# 如果识别到"正在直播"标签,判定为直播列表
if "正在直播" in t_recommend or ("直播" in t_recommend and "推荐" not in t_recommend and "关注" not in t_recommend):
_log("步骤3[OCR直播列表]-检测到直播关键词,准备精确确认", 精确区域="(650,145)-(800,195)")
step_start_list = time.time()
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
self.cut_pic(650, 145, 800, 195, "", "直播列表标签")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR直播列表]-精确截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
t_list = str(self.operation.analyse_pic_word("直播列表标签", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR直播列表]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_list),
文本预览=t_list[:50] if t_list else "",
)
if (time.time() - step_start < max_step_time) and ("正在直播" not in t_list):
ocr_start_1 = time.time()
t_list = str(self.operation.analyse_pic_word("直播列表标签", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤3[OCR直播列表]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_list),
文本预览=t_list[:50] if t_list else "",
)
except Exception as e:
import traceback
_log("步骤3[OCR直播列表]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc())
elapsed_list = (time.time() - step_start_list) * 1000
if "正在直播" in t_list:
total_elapsed = (time.time() - diag_start) * 1000
list_text = t_list[:50] if t_list else "-"
_log(
"步骤3[OCR直播列表]-命中",
耗时毫秒=elapsed_list,
总耗时毫秒=total_elapsed,
识别文本=list_text,
)
_log("阶段诊断完成", 阶段="LIVE_LIST", 原因=f"标题='{t_list}'")
return "LIVE_LIST", "标题='{}'".format(t_list)
# 记录诊断时看到的"关注页标题"
try:
self._last_follow_list_title_text = str(t_follow or "").strip()
except Exception:
self._last_follow_list_title_text = ""
elapsed_total = (time.time() - step_start) * 1000
if elapsed_total > max_step_time * 1000:
_log("步骤3[OCR推荐页/关注列表/直播列表]-步骤超时", 耗时毫秒=elapsed_total, 阈值毫秒=max_step_time * 1000)
else:
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-未命中",
耗时毫秒=elapsed_total,
推荐标签栏预览=t_recommend[:30] if t_recommend else "",
)
except Exception as e:
elapsed_total = (time.time() - step_start) * 1000
import traceback
_log(
"步骤3[OCR推荐页/关注列表/直播列表]-异常",
耗时毫秒=elapsed_total,
异常类型=type(e).__name__,
异常信息=str(e),
堆栈=traceback.format_exc(),
)
# 如果不在直播间且OCR也未识别到特定页面,返回未知状态
total_elapsed = (time.time() - diag_start) * 1000
_log("不在直播间且OCR未识别到特定页面", 总耗时毫秒=total_elapsed)
_log("阶段诊断完成", 阶段="UNKNOWN", 原因="不在直播间且未识别到特定页面")
return "UNKNOWN", "不在直播间且未识别到特定页面"
# ========== 在直播间:继续执行像素检测 ==========
_log("在直播间,继续执行像素检测")
# ========== 第一步:基于同一张截图并行采集所有像素特征 ==========
# 这是最优先的检测方式,速度快且准确,所有像素检测在screenshot中并行执行
pixel_state = {}
pixel_detection_start = time.time()
try:
pixel_state = self._read_pixel_stage_state()
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
_log(
"像素状态(并行检测完成)",
耗时毫秒=pixel_detection_elapsed,
优惠券背景=bool(pixel_state.get("has_coupon_bg", False)),
购物红包背景=bool(pixel_state.get("has_redpacket_bg", False)),
抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)),
参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)),
粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)),
)
except Exception as e:
import traceback
pixel_detection_elapsed = (time.time() - pixel_detection_start) * 1000
_log("像素状态读取异常", 耗时毫秒=pixel_detection_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
pixel_state = {}
# ========== 优先使用像素检测结果判断阶段(按优先级顺序)==========
# 根据像素检测结果,按优先级返回阶段
# 优先级1:抽奖结果弹窗(大片红色+我知道了)
if pixel_state.get("has_lucky_draw_result", False):
# 像素检测到抽奖结果弹窗,使用OCR兜底确认
step_result_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤1[检测抽奖结果弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到抽奖结果弹窗,OCR兜底确认")
result_verified = False
try:
# 检测抽奖结果文字区域 (350, 650)-(750, 765)
if time.time() - step_result_start < max_step_time:
cut_start = time.time()
self.cut_pic(350, 650, 750, 765, "", "抽奖结果")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤1[检测抽奖结果弹窗]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_result_start < max_step_time:
ocr_start = time.time()
result_text = str(self.operation.analyse_pic_word("抽奖结果", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤1[检测抽奖结果弹窗]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(result_text),
文本预览=result_text[:50] if result_text else "",
)
if (time.time() - step_result_start < max_step_time) and (not result_text or ("没有抽中" not in result_text and "抽中福袋" not in result_text)):
ocr_start_1 = time.time()
result_text = str(self.operation.analyse_pic_word("抽奖结果", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤1[检测抽奖结果弹窗]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(result_text),
文本预览=result_text[:50] if result_text else "",
)
# 检测"我知道了"按钮区域 (340, 1195)-(740, 1355)
if result_text and ("没有抽中" in result_text or "抽中福袋" in result_text):
if time.time() - step_result_start < max_step_time:
cut_confirm_start = time.time()
self.cut_pic(340, 1195, 740, 1355, "", "无奖励确认")
cut_confirm_elapsed = (time.time() - cut_confirm_start) * 1000
_log("步骤1[检测抽奖结果弹窗]-确认按钮截图完成", 耗时毫秒=cut_confirm_elapsed)
if time.time() - step_result_start < max_step_time:
ocr_confirm_start = time.time()
confirm_text = str(self.operation.analyse_pic_word("无奖励确认", 0) or "")
ocr_confirm_elapsed = (time.time() - ocr_confirm_start) * 1000
_log(
"步骤1[检测抽奖结果弹窗]-确认按钮OCR模式0",
耗时毫秒=ocr_confirm_elapsed,
文本长度=len(confirm_text),
文本预览=confirm_text[:50] if confirm_text else "",
)
if confirm_text and ("我知道了" in confirm_text or "领取并使用" in confirm_text):
result_verified = True
else:
# OCR未识别到确认按钮,即使像素检测到也不判定为抽奖结果弹窗
_log("步骤1[检测抽奖结果弹窗]-OCR未识别到确认按钮", 说明="OCR未匹配,不判定为抽奖结果弹窗")
else:
# OCR未识别到结果文字("没有抽中"或"抽中福袋"),即使像素检测到也不判定为抽奖结果弹窗
_log("步骤1[检测抽奖结果弹窗]-OCR未识别到结果文字", 说明="OCR未匹配关键词,不判定为抽奖结果弹窗")
except Exception as e:
result_elapsed = (time.time() - step_result_start) * 1000
_log("步骤1[检测抽奖结果弹窗]-异常", 耗时毫秒=result_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
# OCR异常时,不判定为抽奖结果弹窗(需要OCR确认)
_log("步骤1[检测抽奖结果弹窗]-OCR异常,不判定为抽奖结果弹窗", 说明="需要OCR确认才能判定")
if result_verified:
total_elapsed = (time.time() - diag_start) * 1000
result_elapsed = (time.time() - step_result_start) * 1000
_log(
"阶段诊断完成(抽奖结果弹窗)",
阶段="FUDai_RESULT",
原因="像素检测+OCR确认(抽奖结果弹窗)",
总耗时毫秒=total_elapsed,
结果检测耗时毫秒=result_elapsed,
)
return "FUDai_RESULT", "像素检测+OCR确认(抽奖结果弹窗)"
# 优先级1.5:购物红包弹窗检测(保持现有检测方式)
if pixel_state.get("has_redpacket_bg", False):
step_redpacket_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤1.5[检测购物红包弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到购物红包背景")
redpacket_detected = False
try:
if time.time() - step_redpacket_start < max_step_time:
cut_start = time.time()
self.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤1.5[检测购物红包弹窗]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_redpacket_start < max_step_time:
ocr_start = time.time()
redpacket_text = str(self.operation.analyse_pic_word("診斷購物紅包", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤1.5[检测购物红包弹窗]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
)
# 检查是否包含购物红包关键词
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if redpacket_text and any(kw in redpacket_text for kw in redpacket_keywords):
redpacket_detected = True
else:
# OCR未识别到关键词,不判定为购物红包弹窗(以OCR为准)
_log("步骤1.5[检测购物红包弹窗]-OCR未识别到关键词", 说明="OCR未匹配,不判定为购物红包弹窗")
except Exception as e:
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
_log("步骤1.5[检测购物红包弹窗]-异常", 耗时毫秒=redpacket_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
# OCR异常时,不判定为购物红包弹窗(以OCR为准)
_log("步骤1.5[检测购物红包弹窗]-OCR异常,不判定为购物红包弹窗", 说明="需要OCR确认才能判定")
if redpacket_detected:
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_redpacket_start) * 1000
_log(
"阶段诊断完成(购物红包弹窗)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="检测到购物红包弹窗",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(购物红包弹窗)"
# 优先级2:优惠券弹窗检测(使用参与按钮区域,检测"开心收下")
# 优惠券弹窗和参与福袋按钮在同一个位置,需要通过OCR区分
has_red_button_area = pixel_state.get("has_attend_button_red", False) or pixel_state.get("has_fansclub_join_red", False)
if has_red_button_area:
# 先检测是否是优惠券弹窗("开心收下")
step_coupon_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤2[检测优惠券弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="使用参与按钮区域检测优惠券弹窗")
coupon_text = ""
try:
if time.time() - step_coupon_start < max_step_time:
cut_start = time.time()
# 使用与参与按钮相同的区域 (200, 1940)-(880, 2140)
self.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤2[检测优惠券弹窗]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_coupon_start < max_step_time:
ocr_start = time.time()
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤2[检测优惠券弹窗]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
if (time.time() - step_coupon_start < max_step_time) and (not coupon_text or "开心收下" not in coupon_text):
ocr_start_1 = time.time()
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤2[检测优惠券弹窗]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
except Exception as e:
coupon_elapsed = (time.time() - step_coupon_start) * 1000
_log("步骤2[检测优惠券弹窗]-异常", 耗时毫秒=coupon_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
# 如果检测到"开心收下",判定为优惠券弹窗
if coupon_text and "开心收下" in coupon_text:
total_elapsed = (time.time() - diag_start) * 1000
coupon_elapsed = (time.time() - step_coupon_start) * 1000
_log(
"阶段诊断完成(优惠券弹窗)",
阶段="COUPON_POPUP",
原因="检测到开心收下(优惠券弹窗)",
总耗时毫秒=total_elapsed,
优惠券检测耗时毫秒=coupon_elapsed,
)
return "COUPON_POPUP", "OCR确认(开心收下)"
# 优先级3:参与按钮/粉丝团加入区域(大片红色,需要OCR区分)
# 注意:这两个检测区域重叠,检测到红色区域后需要用OCR区分是"加入粉丝团"还是"一键发表评论"
if has_red_button_area:
step_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤2[OCR区分按钮类型]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到红色按钮区域,需OCR区分类型")
# 使用粉丝团加入的区域进行OCR(覆盖范围更广)
t_button = ""
ocr_mode_0_result = ""
ocr_mode_1_result = ""
try:
if time.time() - step_start < max_step_time:
cut_start = time.time()
self.cut_pic(200, 1940, 880, 2140, "", "粉丝团加入")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤2[OCR区分按钮类型]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_start < max_step_time:
ocr_start = time.time()
t_button = str(self.operation.analyse_pic_word("粉丝团加入", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
ocr_mode_0_result = t_button
_log(
"步骤2[OCR区分按钮类型]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(t_button),
文本预览=t_button[:50] if t_button else "",
)
if (time.time() - step_start < max_step_time) and (not t_button or ("加入粉丝团" not in t_button and "一键" not in t_button and "发表" not in t_button and "评论" not in t_button)):
ocr_start_1 = time.time()
t_button = str(self.operation.analyse_pic_word("粉丝团加入", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
ocr_mode_1_result = t_button
_log(
"步骤2[OCR区分按钮类型]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(t_button),
文本预览=t_button[:50] if t_button else "",
)
except Exception as e:
import traceback
elapsed = (time.time() - step_start) * 1000
_log("步骤2[OCR区分按钮类型]-异常", 异常类型=type(e).__name__, 异常信息=str(e), 堆栈=traceback.format_exc())
elapsed = (time.time() - step_start) * 1000
total_elapsed = (time.time() - diag_start) * 1000
# 根据OCR结果判断阶段
if "加入粉丝团" in t_button:
_log(
"步骤2[OCR区分按钮类型]-命中粉丝团加入",
耗时毫秒=elapsed,
总耗时毫秒=total_elapsed,
识别文本=t_button[:50] if t_button else "",
)
_log("阶段诊断完成(像素+OCR)", 阶段="FANSCLUB_JOIN", 原因=f"OCR识别:{t_button[:30]}")
return "FANSCLUB_JOIN", f"像素检测+OCR确认(加入粉丝团)"
elif "一键" in t_button or "发表" in t_button or "评论" in t_button or "参与" in t_button:
_log(
"步骤2[OCR区分按钮类型]-命中参与按钮",
耗时毫秒=elapsed,
总耗时毫秒=total_elapsed,
识别文本=t_button[:50] if t_button else "",
)
_log("阶段诊断完成(像素+OCR)", 阶段="FUDai_DETAIL", 原因=f"OCR识别:{t_button[:30]}")
return "FUDai_DETAIL", f"像素检测+OCR确认(参与按钮)"
else:
# OCR未识别到明确文字,不判定为任何阶段(以OCR为准)
_log(
"步骤2[OCR区分按钮类型]-OCR未识别到明确文字,不判定为任何阶段",
耗时毫秒=elapsed,
总耗时毫秒=total_elapsed,
OCR结果=t_button[:50] if t_button else "(空)",
)
# 不返回任何阶段,继续后续检测
# ========== 步骤1:像素检测福袋详情页(补充检测)==========
# 如果像素检测未命中,再用这个方法检测
step_start = time.time()
_log("步骤1[像素检测福袋详情]-开始", 说明="补充检测")
detail_detected = False
try:
check_result = self.check_in_fudai_detail()
elapsed = (time.time() - step_start) * 1000
total_elapsed = (time.time() - diag_start) * 1000
if check_result:
detail_detected = True
_log("步骤1[像素检测福袋详情]-命中", 耗时毫秒=elapsed, 总耗时毫秒=total_elapsed)
_log("阶段诊断完成(像素检测)", 阶段="FUDai_DETAIL", 原因="福袋详情页像素检测")
return "FUDai_DETAIL", "像素检测确认(福袋详情页)"
else:
_log("步骤1[像素检测福袋详情]-未命中", 耗时毫秒=elapsed)
except Exception as e:
import traceback
elapsed = (time.time() - step_start) * 1000
_log("步骤1[像素检测福袋详情]-异常", 耗时毫秒=elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
# 如果像素检测未命中,使用OCR兜底检测
if not detail_detected:
step_ocr_detail_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤1[OCR兜底检测福袋详情]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测未命中,OCR兜底确认")
try:
if time.time() - step_ocr_detail_start < max_step_time:
cut_start = time.time()
# 使用参与按钮区域进行OCR检测 (200, 1940)-(880, 2140)
self.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤1[OCR兜底检测福袋详情]-截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_detail_start < max_step_time:
ocr_start = time.time()
detail_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤1[OCR兜底检测福袋详情]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(detail_text),
文本预览=detail_text[:50] if detail_text else "",
)
# 检测福袋详情页关键词
detail_keywords = ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看", "一键", "发表")
if detail_text and any(kw in detail_text for kw in detail_keywords):
detail_detected = True
elif (time.time() - step_ocr_detail_start < max_step_time) and (not detail_text or not any(kw in detail_text for kw in detail_keywords)):
ocr_start_1 = time.time()
detail_text = str(self.operation.analyse_pic_word("参与按钮", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤1[OCR兜底检测福袋详情]-OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(detail_text),
文本预览=detail_text[:50] if detail_text else "",
)
if detail_text and any(kw in detail_text for kw in detail_keywords):
detail_detected = True
except Exception as e:
detail_ocr_elapsed = (time.time() - step_ocr_detail_start) * 1000
_log("步骤1[OCR兜底检测福袋详情]-异常", 耗时毫秒=detail_ocr_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
if detail_detected:
total_elapsed = (time.time() - diag_start) * 1000
_log("步骤1[像素检测福袋详情]-最终命中", 总耗时毫秒=total_elapsed)
_log("阶段诊断完成(像素检测+OCR兜底)", 阶段="FUDai_DETAIL", 原因="福袋详情页检测")
return "FUDai_DETAIL", "像素检测+OCR兜底确认(福袋详情页)"
# ========== 所有像素检测完成,未命中任何特定阶段 ==========
# 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要OCR再次确认
# 因为有些直播间背景颜色可能与弹窗颜色相似,导致误判
has_suspicious_popup_pixel = (
pixel_state.get("has_coupon_bg", False) or
pixel_state.get("has_redpacket_bg", False)
)
if has_suspicious_popup_pixel:
step_ocr_verify_start = time.time()
remaining_time_before = max_diag_time - (time.time() - diag_start)
_log("步骤3[OCR确认弹窗]-开始", 剩余时间秒=remaining_time_before, 说明="像素检测到弹窗背景,但未匹配到弹窗阶段,OCR再次确认")
# 检测优惠券弹窗(使用参与按钮区域,检测"开心收下")
if pixel_state.get("has_coupon_bg", False):
coupon_verified = False
try:
if time.time() - step_ocr_verify_start < max_step_time:
cut_start = time.time()
self.cut_pic(200, 1940, 880, 2140, "", "参与按钮")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR确认弹窗]-优惠券截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_verify_start < max_step_time:
ocr_start = time.time()
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR确认弹窗]-优惠券OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
if enable_ocr_mode1 and (time.time() - step_ocr_verify_start < max_step_time) and (not coupon_text or "开心收下" not in coupon_text):
ocr_start_1 = time.time()
coupon_text = str(self.operation.analyse_pic_word("参与按钮", 1) or "")
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤3[OCR确认弹窗]-优惠券OCR模式1",
耗时毫秒=ocr_elapsed_1,
文本长度=len(coupon_text),
文本预览=coupon_text[:50] if coupon_text else "",
)
if coupon_text and "开心收下" in coupon_text:
coupon_verified = True
except Exception as e:
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log("步骤3[OCR确认弹窗]-优惠券异常", 耗时毫秒=coupon_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
if coupon_verified:
total_elapsed = (time.time() - diag_start) * 1000
coupon_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log(
"阶段诊断完成(优惠券弹窗-OCR确认)",
阶段="COUPON_POPUP",
原因="像素检测到背景+OCR确认(开心收下)",
总耗时毫秒=total_elapsed,
优惠券检测耗时毫秒=coupon_elapsed,
)
return "COUPON_POPUP", "OCR确认(开心收下)"
# 检测购物红包弹窗
if pixel_state.get("has_redpacket_bg", False):
redpacket_verified = False
try:
if time.time() - step_ocr_verify_start < max_step_time:
cut_start = time.time()
self.cut_pic(230, 450, 860, 550, "", "診斷購物紅包")
cut_elapsed = (time.time() - cut_start) * 1000
_log("步骤3[OCR确认弹窗]-购物红包截图完成", 耗时毫秒=cut_elapsed)
if time.time() - step_ocr_verify_start < max_step_time:
ocr_start = time.time()
redpacket_text = str(self.operation.analyse_pic_word("診斷購物紅包", 0) or "")
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤3[OCR确认弹窗]-购物红包OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
)
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
if redpacket_text and any(kw in redpacket_text for kw in redpacket_keywords):
redpacket_verified = True
except Exception as e:
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log("步骤3[OCR确认弹窗]-购物红包异常", 耗时毫秒=redpacket_elapsed, 异常类型=type(e).__name__, 异常信息=str(e))
if redpacket_verified:
total_elapsed = (time.time() - diag_start) * 1000
redpacket_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log(
"阶段诊断完成(购物红包弹窗-OCR确认)",
阶段="SHOPPING_REDPACKET_POPUP",
原因="像素检测到背景+OCR确认(购物红包)",
总耗时毫秒=total_elapsed,
红包检测耗时毫秒=redpacket_elapsed,
)
return "SHOPPING_REDPACKET_POPUP", "OCR确认(购物红包弹窗)"
# OCR确认后仍未匹配到弹窗,说明是直播间背景颜色误判
ocr_verify_elapsed = (time.time() - step_ocr_verify_start) * 1000
_log("步骤3[OCR确认弹窗]-未匹配到弹窗", 耗时毫秒=ocr_verify_elapsed, 说明="OCR确认后未匹配,判定为直播间背景颜色")
# 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段
if in_live_room:
total_elapsed = (time.time() - diag_start) * 1000
_log("所有阶段检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed)
_log(
"阶段诊断完成(在直播间)",
阶段="IN_LIVE_ROOM",
原因=f"识别到在直播间({detection_method}),其他阶段未识别",
检测方法=detection_method,
分数=live_room_score,
)
return "IN_LIVE_ROOM", f"识别到在直播间({detection_method}),其他阶段未识别"
# 如果不在直播间,默认返回:在直播间内(IN_LIVE_ROOM)
# 这种情况可能是检测失败,但为了流程继续,默认返回在直播间
total_elapsed = (time.time() - diag_start) * 1000
_log("所有像素检测完成,未匹配到特定阶段", 总耗时毫秒=total_elapsed)
_log("阶段诊断完成(像素检测)", 阶段="IN_LIVE_ROOM", 原因="像素检测未命中,默认直播间")
return "IN_LIVE_ROOM", "像素检测未命中,默认直播间"
View File
Whitespace-only changes.
+53
View File
@@ -0,0 +1,53 @@
from __future__ import annotations
from typing import Any
def swipe_up_switch_live(analyser: Any) -> None:
"""上滑切换到下一个直播间(基础版封装)。
采用 1080x2400 基准坐标,在屏幕中下部向上滑一段距离。
"""
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
device_id = getattr(analyser, "device_id", "")
# 基准坐标(1080x2400):从中下部往上滑
start_x_base = 540
start_y_base = 1700
end_x_base = 540
end_y_base = 700
start_x = start_x_base * rx // 1080
end_x = end_x_base * rx // 1080
start_y = start_y_base * ry // 2400
end_y = end_y_base * ry // 2400
try:
analyser._log_kv(
"滑动",
"swipe_up_switch_live:上滑切换直播间",
start_x=start_x_base,
start_y=start_y_base,
end_x=end_x_base,
end_y=end_y_base,
)
except Exception:
pass
# 优先调用底层 swipe,失败则静默忽略(不影响主流程)
try:
analyser.operation.swipe(device_id, start_x, start_y, end_x, end_y, 300)
except Exception:
try:
# 如果 analyser 自身提供 swipe 封装,则退回到该封装
analyser.swipe(start_x_base, start_y_base, end_x_base, end_y_base, 300)
except Exception:
pass
View File
Whitespace-only changes.
+168
View File
@@ -0,0 +1,168 @@
import os
import re
from typing import Iterable
def normalize_countdown_text(text: str) -> str:
"""对福袋倒计时类 OCR 文本做标准化,抽离自 douyin_fudai.py,方便复用与单元测试。"""
if not text:
return ''
t = re.sub(r"\s+", "", str(text))
t = t.replace(':', ':')
# 常见 OCR 混淆纠正(只做轻量替换,避免影响其它文字)
t = t.translate(str.maketrans({
'O': '0', 'o': '0', 'Q': '0', 'D': '0',
'I': '1', 'l': '1', '|': '1', '!': '1',
'S': '5', 's': '5',
'B': '8',
'G': '6',
'Z': '2',
}))
# 中文:x分y秒 / y秒
m = re.search(r"(\d{1,2})分(\d{1,2})秒", t)
if m:
mm = int(m.group(1))
ss = int(m.group(2))
if ss >= 60:
mm += ss // 60
ss = ss % 60
return f"{mm:02d}:{ss:02d}"
m = re.search(r"(\d{1,3})秒", t)
if m:
ss = int(m.group(1))
mm = ss // 60
ss = ss % 60
return f"{mm:02d}:{ss:02d}"
# 标准样式:11:37后开奖 / 11:37后开奖
m = re.search(r"(\d{1,2})[::](\d{2}).*后开奖", t)
if m:
mm = int(m.group(1))
ss = int(m.group(2))
# 若分秒识别反了(例如 53:08 实际应为 08:53),优先选择 <= 15 分钟的解释
if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900:
mm, ss = ss, mm
return f"{mm:02d}:{ss:02d}后开奖"
# 识别错序:54后开奖04
m = re.search(r"(\d{1,2})后开奖(\d{2})", t)
if m:
mm = int(m.group(1))
ss = int(m.group(2))
if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900:
mm, ss = ss, mm
return f"{mm:02d}:{ss:02d}后开奖"
# 纯数字 1137 / 5404
digits = ''.join(ch for ch in t if ch.isdigit())
if len(digits) == 4:
a = int(digits[:2])
b = int(digits[2:])
# 生成两种解释:mm:ss 以及交换后的 mm:ss
mm1, ss1 = a, b
mm2, ss2 = b, a
total1 = mm1 * 60 + ss1
total2 = mm2 * 60 + ss2
# 默认相信“从左到右”的顺序:前两位=分,后两位=秒。
# 只有在明显异常(>15分钟)或秒数不合法时才交换。
if ss1 >= 60 and ss2 < 60:
mm, ss = mm2, ss2
elif ss2 >= 60 and ss1 < 60:
mm, ss = mm1, ss1
elif total1 > 900 and total2 <= 900:
mm, ss = mm2, ss2
elif total2 > 900 and total1 <= 900:
mm, ss = mm1, ss1
else:
mm, ss = mm1, ss1
return f"{mm:02d}:{ss:02d}"
# 3 位数字:934 => 09:34
if len(digits) == 3:
mm = int(digits[0])
ss = int(digits[1:])
if ss >= 60:
# 尝试 15:09(OCR 丢 0)
mm2 = int(digits[:2])
ss2 = int(digits[2])
if ss2 < 60:
return f"{mm2:02d}:{ss2:02d}"
mm += ss // 60
ss = ss % 60
return f"{mm:02d}:{ss:02d}"
# 2 位数字:31 => 00:31(更符合临近开奖)
if len(digits) == 2:
return f"00:{int(digits):02d}"
return t
def extract_prize_value_yuan(text: str) -> float:
"""从 OCR 文本中抽取奖品价值金额(元),抽离自 douyin_fudai.py。"""
if not text:
return 0.0
t = re.sub(r"\s+", "", str(text))
# 先去掉倒计时类数字,避免把 00:31 解析成 31 元
t = re.sub(r"\b\d{1,2}[::]\d{2}\b", "", t)
# 优先匹配带币种符号/单位的金额:参考价值¥199 / ¥199.9 / ¥199 / 199元
currency_matches = re.findall(r"[¥¥](\d+(?:\.\d+)?)", t)
yuan_matches = re.findall(r"(\d+(?:\.\d+)?)元", t)
tagged: Iterable[str] = list(currency_matches) + list(yuan_matches)
if tagged:
vals: list[float] = []
for n in tagged:
try:
vals.append(float(n))
except ValueError:
pass
return max(vals) if vals else 0.0
# 去掉常见干扰:份数/参与人数
t = re.sub(r"共\d+份", "", t)
t = re.sub(r"\d+人已参与", "", t)
# 退化:抓小数
decimals = re.findall(r"\d+\.\d+", t)
if decimals:
vals = []
for n in decimals:
try:
vals.append(float(n))
except ValueError:
pass
return max(vals) if vals else 0.0
# 再退化:抓整数
ints = re.findall(r"\d+", t)
if ints:
vals = []
for n in ints:
try:
v = int(n)
except ValueError:
continue
if 1 <= v <= 99999:
vals.append(float(v))
return max(vals) if vals else 0.0
return 0.0
class Tee:
"""将 print 输出同时写入多个文件对象的简单工具类。"""
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush()
def flush(self):
for f in self.files:
f.flush()
+531
View File
@@ -0,0 +1,531 @@
from __future__ import annotations
import os
import random
import time
def yanghao_idle(analyser, total_seconds: int) -> None:
"""养号等待。
- 若启用 `yanghao_enable_actions`:停留期间可按概率点爱心/收藏,停留结束后自动滑动。
- 否则:保持原有“分段等待 + 可选轻微滑动 + 定时休息”。
"""
if total_seconds <= 0:
return
if getattr(analyser, "yanghao_enable_actions", False):
# 循环:持续检测图标;都未检测到则立刻下滑继续;检测到则停留 10-15 秒并按概率执行动作,然后再下滑。
need_settle_after_swipe = False
def _step_shot(label: str) -> None:
# 环境变量优先:YANGHAO_STEP_SCREENSHOT=1
try:
env_on = bool(str(os.environ.get("YANGHAO_STEP_SCREENSHOT", "")).strip())
except Exception:
env_on = False
if env_on or bool(getattr(analyser, "yanghao_step_screenshot", False)):
analyser._save_step_screenshot(label)
def _do_swipe_next() -> None:
nonlocal need_settle_after_swipe
_step_shot("before_swipe")
dist = int(getattr(analyser, "yanghao_after_dwell_swipe_distance_px", 900) or 900)
if dist < 200:
dist = 200
if dist > 1400:
dist = 1400
x = int(1080 * 0.7)
y_mid = int(2400 * 0.55)
if str(getattr(analyser, "yanghao_after_dwell_swipe_direction", "up") or "up").lower() == "up":
# up:上滑切换到下一个内容(手指从下往上)
y1 = y_mid + int(dist / 2)
y2 = y_mid - int(dist / 2)
else:
# down:下滑回到上一个内容(手指从上往下)
y1 = y_mid - int(dist / 2)
y2 = y_mid + int(dist / 2)
analyser.swipe(x, y1, x, y2, 180)
print("[养号] 动作: 下滑/切换 direction={} dist={}px".format(getattr(analyser, "yanghao_after_dwell_swipe_direction", "up"), dist))
_step_shot("after_swipe")
# 标记:下滑后下一轮截图/检测前需要随机等待,避免动画未结束影响识别
need_settle_after_swipe = True
def _scaled_click(base_x: int, base_y: int) -> None:
sx, sy = analyser._scale_from_base(int(base_x), int(base_y))
analyser.operation.click(analyser.device_id, sx, sy)
def _human_delay(min_s: float = 0.4, max_s: float = 1.2) -> None:
try:
mn = float(min_s)
mx = float(max_s)
if mx < mn:
mx = mn
analyser.operation.delay(random.uniform(mn, mx))
except Exception:
analyser.operation.delay(1)
def _detect_icon(action: str, base_x: int, base_y: int, template_path: str, roi_label: str) -> tuple[bool, float]:
nonlocal need_settle_after_swipe
if need_settle_after_swipe:
# 下滑后:先随机等一下,再进行截图与模板匹配
_human_delay(1.0, 2.2)
need_settle_after_swipe = False
_step_shot(f"before_detect_{roi_label}")
if int(base_x or 0) <= 0 or int(base_y or 0) <= 0:
return False, 0.0
# ROI 中心点允许独立偏移(仅影响截图检测,不影响点击坐标)
off_x = 0
off_y = 0
if action == "爱心":
off_x = int(getattr(analyser, "yanghao_like_roi_offset_x", 0) or 0)
off_y = int(getattr(analyser, "yanghao_like_roi_offset_y", 0) or 0)
elif action == "收藏":
off_x = int(getattr(analyser, "yanghao_fav_roi_offset_x", 0) or 0)
off_y = int(getattr(analyser, "yanghao_fav_roi_offset_y", 0) or 0)
sx, sy = analyser._scale_from_base(int(base_x), int(base_y))
if off_x or off_y:
try:
sx = int(sx) + int(off_x * int(getattr(analyser, "resolution_ratio_x", 1080)) / 1080)
sy = int(sy) + int(off_y * int(getattr(analyser, "resolution_ratio_y", 2400)) / 2400)
except Exception:
pass
roi_path = analyser._capture_roi_screenshot(roi_label, sx, sy, int(getattr(analyser, "yanghao_icon_roi_size", 180) or 180))
if not template_path or not os.path.exists(template_path):
print(f"[养号] 检测: {action} -> 失败(缺少模板文件:{template_path})")
return False, 0.0
detected, score = analyser._match_icon_template(roi_path, template_path)
print(f"[养号] 检测: {action} -> {'检测到' if detected else '未检测到'}(score={score:.3f})")
return detected, score
use_icon = (
int(getattr(analyser, "yanghao_like_icon_x", 0) or 0) > 0
and int(getattr(analyser, "yanghao_like_icon_y", 0) or 0) > 0
and int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0) > 0
and int(getattr(analyser, "yanghao_fav_icon_y", 0) or 0) > 0
)
start_ts = time.time()
last_desktop_check_ts = 0.0
while True:
if time.time() - start_ts >= total_seconds:
return
# 定期检测是否在桌面(每5秒检测一次,避免过于频繁)
now_ts = time.time()
check_interval = 5.0
if now_ts - last_desktop_check_ts >= check_interval:
last_desktop_check_ts = now_ts
try:
if yanghao_check_and_recover_from_desktop(analyser):
print("[养号] 检测到在桌面,已尝试恢复")
analyser.operation.delay(1)
except Exception:
pass
if not use_icon:
# 未配置图标检测就退化为“原地等待”
analyser.operation.delay(int(max(1, total_seconds)))
return
like_ok, _like_score = _detect_icon(
"爱心",
int(getattr(analyser, "yanghao_like_icon_x", 0) or 0),
int(getattr(analyser, "yanghao_like_icon_y", 0) or 0),
getattr(analyser, "yanghao_like_template_path", "") or "",
"action_like_roi",
)
fav_ok, _fav_score = _detect_icon(
"收藏",
int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0),
int(getattr(analyser, "yanghao_fav_icon_y", 0) or 0),
getattr(analyser, "yanghao_fav_template_path", "") or "",
"action_fav_roi",
)
if (not like_ok) and (not fav_ok):
# 两个都没检测到:立刻下滑继续检测
_human_delay(0.3, 0.8)
_do_swipe_next()
# 下滑后的延迟在下一轮截图/检测前统一处理
continue
# 检测到其中任意一个:在这里停留 10-15 秒,并按概率执行动作
dwell = int(random.randint(10, 15))
print(f"[养号] 检测到图标,停留 {dwell}s 后再切换")
# 仅当“同时检测到爱心+收藏”时,按概率触发评论动作
if (
like_ok
and fav_ok
and float(getattr(analyser, "yanghao_comment_prob", 0) or 0) > 0
and random.random() < float(getattr(analyser, "yanghao_comment_prob", 0) or 0)
):
comment_texts = getattr(analyser, "yanghao_comment_texts", None)
if comment_texts:
msg = random.choice(comment_texts)
print("[养号] 动作: 评论(prob={}) -> {}".format(getattr(analyser, "yanghao_comment_prob", 0), msg))
try:
_step_shot("comment_before_open")
_scaled_click(int(getattr(analyser, "yanghao_comment_btn_x", 0) or 0), int(getattr(analyser, "yanghao_comment_btn_y", 0) or 0))
_human_delay(0.8, 1.6)
_step_shot("comment_after_open")
_scaled_click(int(getattr(analyser, "yanghao_comment_input_x", 0) or 0), int(getattr(analyser, "yanghao_comment_input_y", 0) or 0))
_human_delay(0.6, 1.2)
_step_shot("comment_after_focus")
# 输入随机文本(优先 ADBKeyboard;否则走剪贴板/兜底)
ix, iy = analyser._scale_from_base(
int(getattr(analyser, "yanghao_comment_input_x", 0) or 0),
int(getattr(analyser, "yanghao_comment_input_y", 0) or 0),
)
prev_ime = ""
try:
ok_ime, prev_ime, _adb_ime = analyser.operation.ensure_adbkeyboard_ime(analyser.device_id)
except Exception:
ok_ime = False
ok_input = False
if ok_ime:
try:
ok_input = analyser.operation.input_text_adbkeyboard(analyser.device_id, msg, restore_prev=False)
except Exception:
ok_input = False
if not ok_input:
ok_input = bool(analyser.operation.paste_text_at(analyser.device_id, ix, iy, msg))
print(f"[养号] 评论输入{'成功' if ok_input else '失败'}")
_step_shot("comment_after_input")
_human_delay(0.6, 1.4)
# 发送:改为键盘确认(优先 ADBKeyBoard 的 SEND editor action;兜底 Enter)
try:
analyser.operation.confirm_from_keyboard(analyser.device_id)
except Exception:
pass
_human_delay(0.8, 1.6)
_step_shot("comment_after_send")
_scaled_click(int(getattr(analyser, "yanghao_comment_close_x", 0) or 0), int(getattr(analyser, "yanghao_comment_close_y", 0) or 0))
_human_delay(0.6, 1.2)
_step_shot("comment_after_close")
# 恢复原输入法(如果之前切换过)
if prev_ime:
try:
analyser.operation.restore_ime(analyser.device_id, prev_ime)
except Exception:
pass
except Exception as e:
print(f"[养号] 动作: 评论失败:{e}")
else:
print("[养号] 动作: 评论(prob={}) -> 跳过(未配置文案列表)".format(getattr(analyser, "yanghao_comment_prob", 0)))
if like_ok and float(getattr(analyser, "yanghao_like_prob", 0) or 0) > 0 and random.random() < float(getattr(analyser, "yanghao_like_prob", 0) or 0):
_human_delay(0.3, 0.9)
_step_shot("before_like_click")
_scaled_click(int(getattr(analyser, "yanghao_like_icon_x", 0) or 0), int(getattr(analyser, "yanghao_like_icon_y", 0) or 0))
_human_delay(0.2, 0.6)
_step_shot("after_like_click")
print("[养号] 动作: 点爱心(prob={})".format(getattr(analyser, "yanghao_like_prob", 0)))
else:
print("[养号] 动作: 跳过点爱心(prob={})".format(getattr(analyser, "yanghao_like_prob", 0)))
if fav_ok and float(getattr(analyser, "yanghao_fav_prob", 0) or 0) > 0 and random.random() < float(getattr(analyser, "yanghao_fav_prob", 0) or 0):
_human_delay(0.3, 0.9)
_step_shot("before_fav_click")
_scaled_click(int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0), int(getattr(analyser, "yanghao_fav_icon_y", 0) or 0))
_human_delay(0.2, 0.6)
_step_shot("after_fav_click")
print("[养号] 动作: 点收藏(prob={})".format(getattr(analyser, "yanghao_fav_prob", 0)))
else:
print("[养号] 动作: 跳过点收藏(prob={})".format(getattr(analyser, "yanghao_fav_prob", 0)))
# 停留
analyser.operation.delay(dwell)
# 接着下滑
_human_delay(0.4, 1.0)
_do_swipe_next()
# 下滑后的延迟在下一轮截图/检测前统一处理
# 理论上不会走到这里
return
# 不启用动作时,采用原有“分段等待 + 桌面检测”逻辑
start_ts = time.time()
last_desktop_check_ts = 0.0
while True:
now = time.time()
elapsed = now - start_ts
if elapsed >= total_seconds:
return
# 定期检测是否在桌面(每5秒检测一次,避免过于频繁)
check_interval = 5.0
if now - last_desktop_check_ts >= check_interval:
last_desktop_check_ts = now
try:
if yanghao_check_and_recover_from_desktop(analyser):
print("[养号] 检测到在桌面,已尝试恢复")
analyser.operation.delay(1)
except Exception:
pass
# 分段等待(避免一次 sleep 太久,看起来更自然)
remaining = int(total_seconds - (time.time() - start_ts))
if remaining <= 0:
return
chunk = 10 if remaining > 10 else remaining
analyser.operation.delay(chunk)
def yanghao_try_tap_text_or_fallback(
analyser,
text: str,
fx: int,
fy: int,
contains: bool = True,
wait_after: float = 1.2,
use_fallback: bool = True,
tap_timeout: float = 1.5,
) -> bool:
ok = False
# 测试模式下尽量快(避免用户以为卡死)
if str(os.environ.get("FAST_UI", "")).strip() in ("1", "true", "True"):
wait_after = 0.2
try:
ok = analyser.operation.tap_by_text(analyser.device_id, text, contains=contains, timeout_seconds=tap_timeout)
except Exception:
ok = False
if ok:
print("[养号] 点击 '{}':UI 命中".format(text))
else:
if use_fallback:
print("[养号] 点击 '{}':UI 未命中,坐标兜底 ({},{})".format(text, fx, fy))
analyser.click(int(fx), int(fy))
ok = True
else:
print("[养号] 点击 '{}':UI 未命中,跳过兜底".format(text))
if wait_after and wait_after > 0:
analyser.operation.delay(wait_after)
return ok
def yanghao_try_multi_texts(
analyser,
texts: list[str],
contains: bool = True,
wait_after: float = 1.2,
tap_timeout: float = 2.5,
) -> bool:
"""依次尝试多组文案(无坐标兜底)。"""
for idx, t in enumerate(texts, 1):
ok = yanghao_try_tap_text_or_fallback(
analyser,
t,
0,
0,
contains=contains,
wait_after=wait_after if idx == len(texts) else 0.0,
use_fallback=False,
tap_timeout=tap_timeout,
)
if ok:
return True
return False
def yanghao_tap_close_icon(analyser) -> None:
"""仅使用系统返回键退出当前页(不再尝试坐标点击)。"""
print("[养号] 发送系统返回键 1/1")
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(0.8)
def yanghao_check_and_recover_from_desktop(analyser) -> bool:
"""检测是否在桌面,如果是则尝试恢复回到抖音。
返回 True 表示检测到桌面并已尝试恢复,False 表示不在桌面或无需处理。
"""
try:
top_pkg = ""
try:
top_pkg = str(analyser.operation.get_top_package(analyser.device_id) or "")
except Exception:
top_pkg = ""
# 如果包名存在且不是抖音相关包,说明可能在桌面或其他应用
if top_pkg and ("aweme" not in top_pkg and "douyin" not in top_pkg and "com.ss.android.ugc" not in top_pkg):
print(f"[养号] 检测到不在抖音前台(前台包: {top_pkg}),尝试恢复")
try:
# 点击桌面图标的预设坐标
try:
analyser.click(int(getattr(analyser, "desktop_icon_x", 0) or 0), int(getattr(analyser, "desktop_icon_y", 0) or 0))
except Exception:
# 退化为默认硬编码位置
analyser.click(153, 260)
analyser.operation.delay(2)
# 点击直播与进入直播间的备用坐标
try:
lx = int(getattr(analyser, "yanghao_fallback_live_x", 0) or 0)
ly = int(getattr(analyser, "yanghao_fallback_live_y", 0) or 0)
print(f"[养号] 点击直播按钮 -> ({lx},{ly})")
analyser.click(lx, ly)
analyser.operation.delay(1.5)
except Exception:
pass
try:
ex = int(getattr(analyser, "yanghao_fallback_enter_live_x", 0) or 0)
ey = int(getattr(analyser, "yanghao_fallback_enter_live_y", 0) or 0)
print(f"[养号] 点击进入直播间 -> ({ex},{ey}) 连点两次")
analyser.click(ex, ey)
analyser.operation.delay(0.6)
analyser.click(ex, ey)
analyser.operation.delay(2.0)
except Exception:
pass
return True
except Exception as e:
print(f"[养号] 恢复失败: {e}")
# 仍然返回 True 表示检测到了问题并尝试过恢复
return True
except Exception:
pass
return False
def yanghao_recommend_flow(analyser, total_seconds: int) -> None:
"""按你的需求执行:X 退出直播 -> 点推荐 -> 养号 -> 点直播 -> 点“点击进入直播间”。
如果识别不到文字,会使用坐标兜底;兜底仍失败时就退化成原地养号(不阻塞主流程)。
"""
try:
print("[养号] 推荐页流程:退出直播→推荐→养号→直播→进入直播间")
capture_steps = str(os.environ.get("YANGHAO_STEP_SCREENSHOT", "")).strip() in ("1", "true", "True")
if capture_steps:
analyser._save_step_screenshot("start")
print("[养号] Step1/5:系统返回键退出当前页")
yanghao_tap_close_icon(analyser)
print("[养号] step1: 已发送系统返回键(1次)")
if capture_steps:
analyser._save_step_screenshot("step1_close")
print("[养号] Step2/5:再次发送返回键")
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(1.2)
if capture_steps:
analyser._save_step_screenshot("step2_back")
print("[养号] Step3/5:在当前页停留/浏览 {} 秒".format(int(total_seconds)))
# 养号前检测是否在桌面
if yanghao_check_and_recover_from_desktop(analyser):
print("[养号] 检测到在桌面,已尝试恢复,继续养号流程")
analyser.operation.delay(1)
yanghao_idle(analyser, total_seconds)
print("[养号] step3: 停留/浏览完成 {} 秒".format(total_seconds))
if capture_steps:
analyser._save_step_screenshot("step3_browse_done")
print("[养号] Step4/5:回到『直播』")
fx = int(getattr(analyser, "yanghao_fallback_live_x", 0) or 0)
fy = int(getattr(analyser, "yanghao_fallback_live_y", 0) or 0)
print("[养号] step4: 坐标点击直播 -> ({},{})".format(fx, fy))
analyser.click(fx, fy)
analyser.operation.delay(1.5)
if capture_steps:
analyser._save_step_screenshot("step4_live")
print("[养号] Step5/5:点击『点击进入直播间』")
ex = int(getattr(analyser, "yanghao_fallback_enter_live_x", 0) or 0)
ey = int(getattr(analyser, "yanghao_fallback_enter_live_y", 0) or 0)
print("[养号] step5: 坐标点击进入直播间 -> ({},{}) 连点两次".format(ex, ey))
analyser.click(ex, ey)
analyser.operation.delay(0.6)
analyser.click(ex, ey)
analyser.operation.delay(2.0)
if capture_steps:
analyser._save_step_screenshot("step5_enter")
print("[养号] 推荐页流程完成")
except Exception as e:
print("[养号] 推荐页流程失败,退化为原地养号:{}".format(e))
yanghao_idle(analyser, total_seconds)
def yanghao_wait(analyser, total_seconds: int) -> None:
if total_seconds <= 0:
return
if not bool(getattr(analyser, "yanghao_enabled", True)):
# 用户要求:关闭养号后不要再等待太久,而是继续执行主流程
print(f"[养号] yanghao_enabled=0:跳过推荐页养号(不再等待 {int(total_seconds)}s,快速继续)")
try:
analyser.operation.delay(1)
except Exception:
pass
return
# 只保留推荐页养号;增加“间隔(冷却)”控制,避免触发过于频繁
try:
now = time.time()
interval = int(getattr(analyser, "yanghao_recommend_interval_seconds", 0) or 0)
last_ts = float(getattr(analyser, "_yanghao_last_recommend_ts", 0.0) or 0.0)
if interval > 0 and last_ts > 0:
dt = now - last_ts
if dt < interval:
remain = int(interval - dt)
print(f"[养号] 推荐页养号冷却中,剩余 {remain}s,跳过本次(改为等待 {int(total_seconds)}s)")
analyser.operation.delay(int(max(1, total_seconds)))
return
analyser._yanghao_last_recommend_ts = time.time()
except Exception:
pass
yanghao_recommend_flow(analyser, total_seconds)
def yanghao_get_recommend_seconds(analyser) -> int:
s = 60
try:
s = int(getattr(analyser, "yanghao_recommend_duration_seconds", 60) or 60)
except Exception:
s = 60
if s < 1:
s = 1
if s > 3600:
s = 3600
return s
def maybe_reset_after_swipes(analyser, needswitch: bool, swipe_times: int) -> int:
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。"""
if not needswitch:
return swipe_times
if not bool(getattr(analyser, "reset_after_swipes_enabled", False)):
return swipe_times
threshold = max(1, int(getattr(analyser, "reset_after_swipes", 0) or 0))
if swipe_times < threshold:
return swipe_times
print("已切换直播间{}次,达到阈值{}:下滑回退到第一个直播间".format(swipe_times, threshold))
# 回退次数按当前已切换次数来(更符合“回到本轮第一个直播间”的语义)
back_times = int(swipe_times)
if back_times <= 0:
return 0
# 下滑回退:与上划切换相反方向
for i in range(back_times):
analyser.swipe(760, 800, 760, 1600, 200)
print("回退直播间 {}/{}".format(i + 1, back_times))
analyser.operation.delay(2)
# 回到第一个后,计数归零
analyser.operation.delay(3)
return 0
+10
View File
@@ -0,0 +1,10 @@
{
"cells": [],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
+937 -250
View File
File diff suppressed because it is too large. Load diff
+668
View File
@@ -0,0 +1,668 @@
import json
import os
import queue
import re
import shutil
import subprocess
import sys
import threading
import time
from dataclasses import dataclass
from typing import Optional
CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.json")
def find_adb_executable() -> str:
"""返回可用的 adb 可执行文件路径(优先 PATH,其次默认安装目录)。"""
adb = shutil.which("adb")
if adb:
return adb
# 默认安装目录(我们之前下载的 platform-tools)
localapp = os.environ.get("LOCALAPPDATA") or ""
candidates = []
if localapp:
candidates.append(os.path.join(localapp, "platform-tools", "adb.exe"))
# 兼容某些人手动放到用户目录的情况
userprofile = os.environ.get("USERPROFILE") or ""
if userprofile:
candidates.append(os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe"))
for p in candidates:
if os.path.exists(p):
return p
return ""
def list_adb_devices(adb_exe: str) -> list[str]:
try:
if not adb_exe:
return []
proc = subprocess.run(
[adb_exe, "devices", "-l"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
except FileNotFoundError:
return []
text = (proc.stdout or "") + "\n" + (proc.stderr or "")
pattern = r"(\b(?:[0-9]{1,3}(?:\.[0-9]{1,3}){3}(?::[0-9]+)?|[A-Za-z0-9]{8,})\b)\s*device\b"
return re.findall(pattern, text)
def read_config() -> dict:
if not os.path.exists(CONFIG_PATH):
return {}
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
return json.load(f)
def write_config(cfg: dict) -> None:
with open(CONFIG_PATH, "w", encoding="utf-8") as f:
json.dump(cfg, f, ensure_ascii=False, indent=4)
f.write("\n")
@dataclass
class RunParams:
device_id: str
y_pianyi: int
needswitch: bool
wait_minutes: int
skip_if_countdown_lt_seconds: int
reset_after_swipes_enabled: bool
reset_after_swipes: int
min_prize_value_yuan: float
min_participants: int
max_participants: int
auto_join_fansclub: bool
fansclub_fail_action: str
# Web端新增参数
high_value_room_revisit_enabled: bool
high_value_room_revisit_only_current_run: bool
reservation_back_verify_enabled: bool
reservation_back_swipe_delay: float
reservation_preempt_min_value: float
fudai_find_max_attempts: int
class Runner:
def __init__(self, on_line):
self._proc: Optional[subprocess.Popen] = None
self._on_line = on_line
self._reader_thread: Optional[threading.Thread] = None
self._lock = threading.Lock()
# 统计相关
self._start_ts: Optional[float] = None
self._last_log_ts: Optional[float] = None
self._exit_code: Optional[int] = None
self._pid: Optional[int] = None
self._counters: dict[str, int] = {}
self._fudai_last: dict[str, object] = {
"content": "",
"countdown": "",
"participants": None,
"copies": None,
"prize_value_yuan": None,
"updated_ts": None,
}
self._events: list[dict] = []
self._events_cap: int = 5000
self._wins: list[dict] = []
self._wins_cap: int = 200
def is_running(self) -> bool:
return self._proc is not None and self._proc.poll() is None
def _inc(self, key: str, n: int = 1) -> None:
with self._lock:
self._counters[key] = int(self._counters.get(key, 0)) + int(n)
def _record_event(self, typ: str, meta: dict | None = None) -> None:
ev = {
"ts": time.time(),
"type": str(typ),
"meta": meta or {},
}
with self._lock:
self._events.append(ev)
if len(self._events) > self._events_cap:
self._events = self._events[-self._events_cap:]
def _record_win(self) -> None:
item = {
"ts": time.time(),
**self._snapshot_fudai(),
}
with self._lock:
self._wins.append(item)
if len(self._wins) > self._wins_cap:
self._wins = self._wins[-self._wins_cap:]
def _snapshot_fudai(self) -> dict:
with self._lock:
return {
"content": self._fudai_last.get("content") or "",
"countdown": self._fudai_last.get("countdown") or "",
"participants": self._fudai_last.get("participants"),
"copies": self._fudai_last.get("copies"),
"prize_value_yuan": self._fudai_last.get("prize_value_yuan"),
}
def _update_stats_from_line(self, line: str) -> None:
s = (line or "").strip()
if not s:
return
with self._lock:
self._last_log_ts = time.time()
# --- 福袋:抽取"最近一次"识别到的信息 ---
if "福袋内容:" in s:
with self._lock:
self._fudai_last["content"] = s.split("福袋内容:", 1)[1].strip()
self._fudai_last["updated_ts"] = time.time()
self._inc("fudai_seen")
self._record_event("fudai_seen", self._snapshot_fudai())
m = re.search(r"参与人数:\s*(\d+)", s)
if m:
with self._lock:
self._fudai_last["participants"] = int(m.group(1))
self._fudai_last["updated_ts"] = time.time()
m = re.search(r"福袋份数:\s*(\d+)", s)
if m:
with self._lock:
self._fudai_last["copies"] = int(m.group(1))
self._fudai_last["updated_ts"] = time.time()
if "倒计时时间:" in s:
with self._lock:
self._fudai_last["countdown"] = s.split("倒计时时间:", 1)[1].strip()
self._fudai_last["updated_ts"] = time.time()
m = re.search(r"奖品价值:\s*([0-9]+(?:\.[0-9]+)?)\s*元", s)
if m:
try:
with self._lock:
self._fudai_last["prize_value_yuan"] = float(m.group(1))
self._fudai_last["updated_ts"] = time.time()
except Exception:
pass
# --- 福袋:关键流程计数 ---
if "点击打开福袋详情" in s:
self._inc("fudai_open_detail")
self._record_event("fudai_open_detail", self._snapshot_fudai())
if "点击参与抽奖" in s or ("[参与]" in s and "动作=点击参与" in s):
self._inc("fudai_click_attend")
self._record_event("fudai_click_attend", self._snapshot_fudai())
# 参与成功/已参与
if (
"已经参与,等待开奖" in s
or "已经参与,等待看播时间凑齐开奖" in s
or "已参与成功(或看播中)" in s
or ("[参与]" in s and ("结果=已参与" in s or "结果=看播中" in s))
):
self._inc("fudai_attend_ok")
self._record_event("fudai_attend_ok", self._snapshot_fudai())
if "参与抽奖失败" in s:
self._inc("fudai_attend_fail")
self._record_event("fudai_attend_fail", self._snapshot_fudai())
# --- 福袋:跳过/过滤原因 ---
if "参与人数" in s and "< 阈值" in s and "不参与" in s:
self._inc("fudai_skip_participants_low")
self._record_event("fudai_skip", {"reason": "participants_low", **self._snapshot_fudai()})
if "参与人数" in s and "> 阈值" in s and "不参与" in s:
self._inc("fudai_skip_participants_high")
self._record_event("fudai_skip", {"reason": "participants_high", **self._snapshot_fudai()})
if "奖品价值" in s and "< 阈值" in s and "不参与" in s:
self._inc("fudai_skip_value_low")
self._record_event("fudai_skip", {"reason": "value_low", **self._snapshot_fudai()})
if "福袋内容不理想" in s:
self._inc("fudai_skip_content")
self._record_event("fudai_skip", {"reason": "content", **self._snapshot_fudai()})
if "抽奖倒计时时间小于" in s and "不参与" in s:
self._inc("fudai_skip_countdown_short")
self._record_event("fudai_skip", {"reason": "countdown_short", **self._snapshot_fudai()})
if "抽奖倒计时时间大于" in s and "暂不参与" in s:
self._inc("fudai_skip_countdown_long")
self._record_event("fudai_skip", {"reason": "countdown_long", **self._snapshot_fudai()})
if (
"需要看播时长:默认不参与" in s
or "需要开始观看/看播门槛:默认不参与" in s
or ("[参与]" in s and "结果=看播门槛" in s)
):
self._inc("fudai_skip_watch_required")
self._record_event("fudai_skip", {"reason": "watch_required", **self._snapshot_fudai()})
if "打开福袋异常" in s:
self._inc("fudai_open_error")
self._record_event("fudai_open_error", self._snapshot_fudai())
if "超过10次点击福袋无法打开详情" in s:
self._inc("fudai_open_error_too_many")
self._record_event("fudai_open_error_too_many", self._snapshot_fudai())
# --- 粉丝团门槛 ---
if "需要加入粉丝团才能参与" in s or ("[参与]" in s and "结果=需要粉丝团" in s):
self._inc("fansclub_required")
self._record_event("fansclub_required", self._snapshot_fudai())
if "未启用自动加入粉丝团" in s:
self._inc("fansclub_manual_needed")
self._record_event("fansclub_manual_needed", self._snapshot_fudai())
if "粉丝团门槛仍未解决" in s or ("[参与]" in s and "粉丝团门槛仍未解决" in s):
self._inc("fansclub_unresolved")
self._record_event("fansclub_unresolved", self._snapshot_fudai())
# --- 预约队列/回退校验 ---
if ("[预约]" in s and "回退校验通过" in s) or "回退校验通过:已回到目标直播间" in s:
self._inc("reservation_back_verify_ok")
self._record_event("reservation_back_verify_ok", {})
if ("[预约]" in s and "回退校验失败" in s) or "回退校验失败" in s:
self._inc("reservation_back_verify_fail")
self._record_event("reservation_back_verify_fail", {})
if ("[预约]" in s and "预约队列已满,丢弃最低价值" in s) or "预约队列已满,丢弃最低价值" in s:
self._inc("reservation_drop_low_value")
self._record_event("reservation_drop_low_value", {})
if ("[预约]" in s and "清空预约队列" in s) or "清空预约队列" in s:
self._inc("reservation_clear")
self._record_event("reservation_clear", {})
# --- 开奖结果 ---
if "没有抽中" in s and "关闭弹窗" in s:
self._inc("fudai_result_no_win")
self._record_event("fudai_result_no_win", self._snapshot_fudai())
if "恭喜中奖了" in s or "检测到中奖结果" in s:
self._inc("fudai_result_win")
self._record_event("fudai_result_win", self._snapshot_fudai())
self._record_win()
if "福袋商品下单成功" in s:
self._inc("fudai_order_success")
self._record_event("fudai_order_success", self._snapshot_fudai())
# --- 直播间切换(按原因粗分) ---
if "上划切换直播间" in s:
self._inc("switch_room")
meta_reason = "unknown"
if "无福袋" in s:
self._inc("switch_room_no_fudai")
meta_reason = "no_fudai"
elif "参与人数" in s:
self._inc("switch_room_participants")
meta_reason = "participants"
elif "奖品价值" in s:
self._inc("switch_room_value")
meta_reason = "value"
elif "内容不理想" in s:
self._inc("switch_room_content")
meta_reason = "content"
elif "倒计时" in s:
self._inc("switch_room_countdown")
meta_reason = "countdown"
elif "参与抽奖失败" in s:
self._inc("switch_room_attend_fail")
meta_reason = "attend_fail"
self._record_event("switch_room", {"reason": meta_reason, **self._snapshot_fudai()})
def get_stats(self) -> dict:
with self._lock:
running = self._proc is not None and self._proc.poll() is None
pid = self._pid
start_ts = self._start_ts
last_log_ts = self._last_log_ts
exit_code = self._exit_code
counters = dict(self._counters)
fudai_last = dict(self._fudai_last)
wins = list(self._wins[-20:]) # 只返回最近20条
now = time.time()
uptime = 0
if start_ts and start_ts > 0:
uptime = int(max(0, now - start_ts))
return {
"running": bool(running),
"pid": pid,
"start_ts": start_ts,
"last_log_ts": last_log_ts,
"exit_code": exit_code,
"uptime_seconds": uptime,
"counters": counters,
"fudai_last": fudai_last,
"wins": wins,
}
def start(self, params: RunParams) -> None:
if self.is_running():
raise RuntimeError("已经在运行")
cmd = [
sys.executable,
os.path.join(os.path.dirname(__file__), "run_cli.py"),
"--y-pianyi",
str(params.y_pianyi),
"--wait-minutes",
str(params.wait_minutes),
]
if params.device_id:
cmd += ["--device-id", params.device_id]
if params.needswitch:
cmd.append("--needswitch")
cmd += ["--min-prize-value-yuan", str(params.min_prize_value_yuan)]
# 这些参数是新增可调节项:倒计时太短跳过、参与人数范围
cmd += ["--skip-if-countdown-lt-seconds", str(int(params.skip_if_countdown_lt_seconds or 15))]
if params.reset_after_swipes_enabled:
cmd.append("--reset-after-swipes-enabled")
cmd += ["--reset-after-swipes", str(int(params.reset_after_swipes or 10))]
else:
cmd.append("--reset-after-swipes-disabled")
if int(params.min_participants or 0) > 0:
cmd += ["--min-participants", str(int(params.min_participants))]
if int(params.max_participants or 0) > 0:
cmd += ["--max-participants", str(int(params.max_participants))]
if params.auto_join_fansclub:
cmd.append("--auto-join-fansclub")
if params.fansclub_fail_action:
cmd += ["--fansclub-fail-action", params.fansclub_fail_action]
# 高价值直播间回访
if params.high_value_room_revisit_enabled:
cmd.append("--high-value-room-revisit-enabled")
else:
cmd.append("--high-value-room-revisit-disabled")
if params.high_value_room_revisit_only_current_run:
cmd.append("--high-value-room-revisit-only-current-run")
# 预约回退校验
if params.reservation_back_verify_enabled:
cmd.append("--reservation-back-verify-enabled")
else:
cmd.append("--reservation-back-verify-disabled")
if params.reservation_back_swipe_delay > 0:
cmd += ["--reservation-back-swipe-delay", str(params.reservation_back_swipe_delay)]
# 预约抢占最小价值
if params.reservation_preempt_min_value > 0:
cmd += ["--reservation-preempt-min-value", str(params.reservation_preempt_min_value)]
# 找福袋最大尝试次数
if params.fudai_find_max_attempts > 0:
cmd += ["--fudai-find-max-attempts", str(params.fudai_find_max_attempts)]
# 继承当前环境,并确保 adb 在 PATH(即使用户没手动刷新 PATH)
env = os.environ.copy()
env.setdefault("PYTHONIOENCODING", "utf-8")
adb_exe = find_adb_executable()
if adb_exe:
adb_dir = os.path.dirname(adb_exe)
env["PATH"] = adb_dir + os.pathsep + env.get("PATH", "")
env["ADB_EXECUTABLE"] = adb_exe
else:
self._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH")
p = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
env=env,
cwd=os.path.dirname(__file__),
)
with self._lock:
self._proc = p
self._pid = p.pid
self._start_ts = time.time()
self._exit_code = None
self._last_log_ts = time.time()
self._counters = {}
self._fudai_last = {
"content": "",
"countdown": "",
"participants": None,
"copies": None,
"prize_value_yuan": None,
"updated_ts": None,
}
self._events = []
self._wins = []
def _reader():
assert self._proc is not None
out = self._proc.stdout
if out is None:
return
for line in out:
cleaned_line = line.rstrip("\n")
self._on_line(cleaned_line)
try:
self._update_stats_from_line(cleaned_line)
except Exception:
pass
rc = self._proc.wait()
with self._lock:
self._exit_code = rc
self._on_line(f"[进程结束] exit_code={rc}")
self._reader_thread = threading.Thread(target=_reader, daemon=True)
self._reader_thread.start()
def start_test_yanghao_flow(self, device_id: str, seconds: int) -> None:
if self.is_running():
raise RuntimeError("已经在运行")
seconds = int(seconds or 0)
if seconds <= 0:
seconds = 90
cmd = [
sys.executable,
os.path.join(os.path.dirname(__file__), "run_cli.py"),
"--test-yanghao-flow",
"--test-yanghao-flow-seconds",
str(seconds),
]
if device_id:
cmd += ["--device-id", device_id]
env = os.environ.copy()
env.setdefault("PYTHONIOENCODING", "utf-8")
adb_exe = find_adb_executable()
if adb_exe:
adb_dir = os.path.dirname(adb_exe)
env["PATH"] = adb_dir + os.pathsep + env.get("PATH", "")
env["ADB_EXECUTABLE"] = adb_exe
else:
self._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH")
p = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
env=env,
cwd=os.path.dirname(__file__),
)
with self._lock:
self._proc = p
self._pid = p.pid
self._start_ts = time.time()
self._exit_code = None
self._last_log_ts = time.time()
self._counters = {}
self._fudai_last = {
"content": "",
"countdown": "",
"participants": None,
"copies": None,
"prize_value_yuan": None,
"updated_ts": None,
}
self._events = []
self._wins = []
def _reader():
assert self._proc is not None
out = self._proc.stdout
if out is None:
return
for line in out:
cleaned_line = line.rstrip("\n")
self._on_line(cleaned_line)
try:
self._update_stats_from_line(cleaned_line)
except Exception:
pass
rc = self._proc.wait()
with self._lock:
self._exit_code = rc
self._on_line(f"[进程结束] exit_code={rc}")
self._reader_thread = threading.Thread(target=_reader, daemon=True)
self._reader_thread.start()
def start_test_comment(self, device_id: str, text: str) -> None:
if self.is_running():
raise RuntimeError("已经在运行")
text = str(text or "").strip()
cmd = [
sys.executable,
os.path.join(os.path.dirname(__file__), "run_cli.py"),
"--test-comment",
]
if text:
cmd += ["--test-comment-text", text]
if device_id:
cmd += ["--device-id", device_id]
env = os.environ.copy()
env.setdefault("PYTHONIOENCODING", "utf-8")
adb_exe = find_adb_executable()
if adb_exe:
adb_dir = os.path.dirname(adb_exe)
env["PATH"] = adb_dir + os.pathsep + env.get("PATH", "")
env["ADB_EXECUTABLE"] = adb_exe
else:
self._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH")
p = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
env=env,
cwd=os.path.dirname(__file__),
)
with self._lock:
self._proc = p
self._pid = p.pid
self._start_ts = time.time()
self._exit_code = None
self._last_log_ts = time.time()
self._counters = {}
self._fudai_last = {
"content": "",
"countdown": "",
"participants": None,
"copies": None,
"prize_value_yuan": None,
"updated_ts": None,
}
self._events = []
self._wins = []
def _reader():
assert self._proc is not None
out = self._proc.stdout
if out is None:
return
for line in out:
cleaned_line = line.rstrip("\n")
self._on_line(cleaned_line)
try:
self._update_stats_from_line(cleaned_line)
except Exception:
pass
rc = self._proc.wait()
with self._lock:
self._exit_code = rc
self._on_line(f"[进程结束] exit_code={rc}")
self._reader_thread = threading.Thread(target=_reader, daemon=True)
self._reader_thread.start()
def stop(self) -> None:
if not self.is_running():
return
assert self._proc is not None
self._on_line("[停止] 正在终止进程...")
self._proc.terminate()
try:
self._proc.wait(timeout=5)
except subprocess.TimeoutExpired:
self._on_line("[停止] 进程未退出,强制结束...")
self._proc.kill()
def force_stop(self) -> None:
"""更强硬的停止:直接杀掉已记录的 PID 及其子进程(主要针对 Windows 下残留进程)。"""
with self._lock:
pid = self._pid
proc = self._proc
if not pid and not proc:
self._on_line("[停止] 当前无记录中的运行进程")
return
self._on_line(f"[停止] 强制终止进程 (pid={pid}) ...")
# 先尝试通过 Popen 对象 kill
try:
if proc is not None and proc.poll() is None:
proc.kill()
except Exception:
pass
# 再通过系统命令清理可能残留的子进程
if pid:
try:
if os.name == "nt":
# Windows:使用 taskkill 结束进程树
subprocess.run(
["taskkill", "/PID", str(pid), "/T", "/F"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
else:
# 类 Unix:尝试向进程组发送 SIGKILL
import signal
os.kill(pid, signal.SIGKILL)
except Exception:
pass
with self._lock:
self._proc = None
self._pid = None
Binary file not shown.

Before

Width:  |  Height:  |  Size: 205 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 205 KiB

+163
View File
@@ -0,0 +1,163 @@
"""
路径配置模块:统一管理所有文件路径,便于整理文件夹结构而不影响代码
"""
import os
# 项目根目录(所有路径的基准)
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
def get_project_root() -> str:
"""返回项目根目录(绝对路径)"""
return PROJECT_ROOT
def get_config_path() -> str:
"""返回 config.json 的路径"""
return os.path.join(PROJECT_ROOT, "config.json")
def get_logs_dir() -> str:
"""返回 logs 目录的路径"""
return os.path.join(PROJECT_ROOT, "logs")
def get_log_file_path() -> str:
"""返回统一日志文件的路径"""
return os.path.join(PROJECT_ROOT, "logs", "unified.log")
def get_pic_dir() -> str:
"""返回 pic 目录的路径(OCR截图、临时截图等)"""
return os.path.join(PROJECT_ROOT, "pic")
def get_screenshot_path() -> str:
"""返回 screenshot.png 的路径(当前屏幕截图)"""
return os.path.join(PROJECT_ROOT, "pic", "screenshot.png")
def get_state_dir() -> str:
"""返回 state 目录的路径(状态文件)"""
return os.path.join(PROJECT_ROOT, "state")
def get_reservations_path() -> str:
"""返回预约队列状态文件的路径"""
return os.path.join(PROJECT_ROOT, "state", "reservations.json")
def get_high_value_rooms_path() -> str:
"""返回高价值房间状态文件的路径"""
return os.path.join(PROJECT_ROOT, "state", "high_value_rooms.json")
def get_assets_dir() -> str:
"""返回 assets 目录的路径(模板图片等)"""
return os.path.join(PROJECT_ROOT, "assets")
def get_like_template_path() -> str:
"""返回点赞图标模板的路径"""
return os.path.join(PROJECT_ROOT, "assets", "like.png")
def get_fav_template_path() -> str:
"""返回收藏图标模板的路径"""
return os.path.join(PROJECT_ROOT, "assets", "fav.png")
def get_desktop_template_path() -> str:
"""返回桌面图标模板的路径"""
return os.path.join(PROJECT_ROOT, "assets", "desktop.png")
def get_webui_dir() -> str:
"""返回 webui 目录的路径"""
return os.path.join(PROJECT_ROOT, "webui")
def get_pic_file_path(filename: str) -> str:
"""获取 pic 目录下指定文件的路径
Args:
filename: 文件名,可以是子目录/文件名,如 'diag_live_plaza.png' 或 'start/latest.png'
"""
return os.path.join(PROJECT_ROOT, "pic", filename)
def get_cut_pic_path(cut_pic_name: str) -> str:
"""获取裁剪后的图片路径(用于OCR)
Args:
cut_pic_name: 图片名称(不含扩展名),如 '直播广场'
"""
return os.path.join(PROJECT_ROOT, "pic", f"{cut_pic_name}.png")
def get_window_dump_path() -> str:
"""返回 window_dump.xml 的路径"""
return os.path.join(PROJECT_ROOT, "pic", "window_dump.xml")
def get_robot_verify_pic_path(save_subdir: bool = False) -> str:
"""返回机器人验证图片的路径
Args:
save_subdir: 是否在 pic/save 子目录中
"""
if save_subdir:
return os.path.join(PROJECT_ROOT, "pic", "save", "机器人验证.png")
return os.path.join(PROJECT_ROOT, "pic", "机器人验证.png")
def ensure_dir(path: str) -> None:
"""确保目录存在,不存在则创建"""
dir_path = os.path.dirname(path) if os.path.isfile(path) else path
os.makedirs(dir_path, exist_ok=True)
+45 -1
View File
@@ -1,8 +1,50 @@
import argparse
import importlib.util
import os
import shutil
import sys
# ==== 兼容导入完整逻辑模块 douyin_fudai 及其依赖 ==============================
# 当前 WebGUI 目录中没有完整版 douyin_fudai.py,而是在 Cursor 的工作树中存在完整实现。
# 同时,我们在本目录下放置了一些 shim 模块(如 douyin_text_utils、douyin_swipe_ops 等),
# 需要优先加载这些本地实现,再去加载完整逻辑模块。
_BASE_DIR = os.path.dirname(__file__)
_EXTERNAL_DOUYIN_FUDAI_DIR = r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf"
def _load_local_shim(mod_name: str, rel_path: str) -> None:
"""从当前工程目录加载本地 shim 模块,并注册到 sys.modules。"""
if mod_name in sys.modules:
return
path = os.path.join(_BASE_DIR, rel_path)
if not os.path.isfile(path):
return
try:
spec = importlib.util.spec_from_file_location(mod_name, path)
if spec is None or spec.loader is None:
return
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
sys.modules[mod_name] = module
except Exception:
# shim 加载失败不影响主流程,后续仍可尝试外部模块
return
# 1) 先加载本地 shim 模块,确保后续 import 优先使用这些实现
_load_local_shim("douyin_text_utils", "douyin_text_utils.py")
_load_local_shim("douyin_swipe_ops", "douyin_swipe_ops.py")
_load_local_shim("douyin_reservation_ops", "douyin_reservation_ops.py")
# 2) 再把完整逻辑所在目录追加到 sys.path,供 `douyin_fudai` 等模块导入
try:
if os.path.isdir(_EXTERNAL_DOUYIN_FUDAI_DIR) and _EXTERNAL_DOUYIN_FUDAI_DIR not in sys.path:
sys.path.append(_EXTERNAL_DOUYIN_FUDAI_DIR)
except Exception:
# 不影响主流程;如果目录不存在,后续导入会按默认逻辑报错
pass
# 在导入 PaddleOCR 之前设置,避免每次启动都做连通性检查提示并抑制底层 glog/oneDNN 等噪音
# DISABLE_MODEL_SOURCE_CHECK: 跳过 PaddleOCR 的主机连通性检查(国内网络环境常卡)
# GLOG_minloglevel: 2 -> ERROR 及以上,屏蔽 INFO/WARNING
@@ -158,6 +200,8 @@ def main(argv: list[str]) -> int:
analyser.y_pianyi = int(args.y_pianyi or 0)
analyser.resolution_ratio_x, analyser.resolution_ratio_y = analyser.operation.get_device_resolution(device_id)
analyser.yanghao_use_recommend_flow = True
# 加载配置(包括养号相关配置)
analyser.load_config()
print("[TEST] device_id={} res={}x{}".format(device_id, analyser.resolution_ratio_x, analyser.resolution_ratio_y))
seconds = int(getattr(args, "test_yanghao_flow_seconds", 10) or 10)
if seconds < 1:
@@ -239,4 +283,4 @@ if __name__ == "__main__":
print_version_banner("run_cli")
except Exception:
pass
raise SystemExit(main(sys.argv[1:]))
raise SystemExit(main(sys.argv[1:]))
+1
View File
@@ -0,0 +1 @@
+517 -53
View File
@@ -1,8 +1,522 @@
{
"updated_ts": 1765874930.950471,
"reason": "reservation",
"total": 58,
"updated_ts": 1765982203.946906,
"reason": "reservation_dedup",
"total": 85,
"rooms": [
{
"first_seen_ts": 1765968226.497444,
"last_seen_ts": 1765982203.946906,
"seen_count": 11,
"pos_seen": 35,
"pos_updated_ts": 1765982203.946906,
"room_title_raw_last": "琦儿12月1",
"alias_raw": [
"琦儿12月1"
],
"key_kind": "norm",
"last_content": "(琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方",
"last_prize_value_yuan": 1699.0,
"max_prize_value_yuan": 1699.0,
"room_title": "琦儿12月1"
},
{
"first_seen_ts": 1765978498.2618399,
"last_seen_ts": 1765981919.562152,
"seen_count": 2,
"pos_seen": 36,
"pos_updated_ts": 1765981919.562152,
"room_title_raw_last": "小小101",
"alias_raw": [
"小小101"
],
"key_kind": "norm",
"last_content": "(小小专属]红米Redmi14C4+64G智能手机原装。",
"last_prize_value_yuan": 999.0,
"max_prize_value_yuan": 999.0,
"room_title": "小小101"
},
{
"first_seen_ts": 1765980930.5562944,
"last_seen_ts": 1765981867.1518803,
"seen_count": 2,
"pos_seen": 35,
"pos_updated_ts": 1765981867.1518803,
"room_title_raw_last": "澳门小源(。",
"alias_raw": [
"澳门小源(。"
],
"key_kind": "norm",
"last_content": "新国标通勤通用电动代步自行车配电自行车灯XY",
"last_prize_value_yuan": 1999.0,
"max_prize_value_yuan": 1999.0,
"room_title": "澳门小源"
},
{
"first_seen_ts": 1765974519.7505262,
"last_seen_ts": 1765974519.7505262,
"seen_count": 1,
"pos_seen": 13,
"pos_updated_ts": 1765974519.7505262,
"room_title_raw_last": "海宁齐总.",
"alias_raw": [
"海宁齐总."
],
"key_kind": "norm",
"last_content": "红0红0红0红0红0红0红V129人巳参与",
"last_prize_value_yuan": 799.0,
"max_prize_value_yuan": 799.0,
"room_title": "海宁齐总"
},
{
"first_seen_ts": 1765955256.8921518,
"last_seen_ts": 1765955256.8921518,
"seen_count": 1,
"pos_seen": 4,
"pos_updated_ts": 1765955256.8921518,
"room_title_raw_last": "韩雪cecila",
"alias_raw": [
"韩雪cecila"
],
"key_kind": "norm",
"last_content": "(韩雪专属』适用左上角11英寸pad第11代颜色随机",
"last_prize_value_yuan": 2999.0,
"max_prize_value_yuan": 2999.0,
"room_title": "韩雪cecila"
},
{
"first_seen_ts": 1765954863.2691152,
"last_seen_ts": 1765954863.2691152,
"seen_count": 1,
"pos_seen": 1,
"pos_updated_ts": 1765954863.2691152,
"room_title_raw_last": "小北珠宝",
"alias_raw": [
"小北珠宝"
],
"key_kind": "norm",
"last_content": "(小北珠宝118k金片片链(假一赔三110-2A02X",
"last_prize_value_yuan": 999.0,
"max_prize_value_yuan": 999.0,
"room_title": "小北珠宝"
},
{
"first_seen_ts": 1765952156.3065248,
"last_seen_ts": 1765954423.291741,
"seen_count": 2,
"pos_seen": 5,
"pos_updated_ts": 1765954423.291741,
"room_title_raw_last": "贵人写/",
"alias_raw": [
"贵人写/"
],
"key_kind": "norm",
"last_content": "贵人鸟儿童保温水杯50Om",
"last_prize_value_yuan": 499.0,
"max_prize_value_yuan": 499.0,
"room_title": "贵人写"
},
{
"first_seen_ts": 1765952009.0600715,
"last_seen_ts": 1765954280.3851128,
"seen_count": 4,
"pos_seen": 1,
"pos_updated_ts": 1765954280.3851128,
"room_title_raw_last": "子惠在.",
"alias_raw": [
"子惠在.",
"子惠在",
"子惠在。"
],
"key_kind": "norm",
"last_content": "小米红米/redmi14C智能手机280人巳参与",
"last_prize_value_yuan": 899.0,
"max_prize_value_yuan": 899.0,
"room_title": "子惠在"
},
{
"first_seen_ts": 1765768902.1252618,
"last_seen_ts": 1765953664.6716282,
"seen_count": 33,
"pos_seen": 3,
"pos_updated_ts": 1765953664.6716282,
"room_title_raw_last": "凡客陈年",
"alias_raw": [
"凡客陈年?",
"凡客陈年"
],
"key_kind": "norm",
"last_content": "小米RedmiPadSE新款平板11英寸护眼大屏全金属",
"last_prize_value_yuan": 1199.0,
"max_prize_value_yuan": 5999.0,
"room_title": "凡客陈年"
},
{
"first_seen_ts": 1765953463.7645955,
"last_seen_ts": 1765953463.7645955,
"seen_count": 1,
"pos_seen": 4,
"pos_updated_ts": 1765953463.7645955,
"room_title_raw_last": "千惠在。",
"alias_raw": [
"千惠在。"
],
"key_kind": "norm",
"last_content": "小米红米/redmi14C智能手机437人巳参与",
"last_prize_value_yuan": 899.0,
"max_prize_value_yuan": 899.0,
"room_title": "千惠在"
},
{
"first_seen_ts": 1765952446.0599895,
"last_seen_ts": 1765952446.0599895,
"seen_count": 1,
"pos_seen": 0,
"pos_updated_ts": 1765952446.0599895,
"room_title_raw_last": "刘嫒爱17",
"alias_raw": [
"刘嫒爱17"
],
"key_kind": "norm",
"last_content": "(粉丝专属』左上角财富自由礼品款式随机143人巳参与",
"last_prize_value_yuan": 399.0,
"max_prize_value_yuan": 399.0,
"room_title": "刘嫒爱17"
},
{
"first_seen_ts": 1765942823.8096075,
"last_seen_ts": 1765952395.913568,
"seen_count": 3,
"pos_seen": 0,
"pos_updated_ts": 1765952395.913568,
"room_title_raw_last": "刘媛媛17",
"alias_raw": [
"刘媛媛:17.",
"刘媛媛:17。",
"刘媛媛17"
],
"key_kind": "norm",
"last_content": "(粉丝专属』左上角财富自由礼品款式随机",
"last_prize_value_yuan": 0.0,
"max_prize_value_yuan": 5999.0,
"room_title": "刘媛媛17"
},
{
"first_seen_ts": 1765937275.9831653,
"last_seen_ts": 1765952337.323364,
"seen_count": 1,
"pos_seen": 0,
"pos_updated_ts": 1765952337.323364,
"room_title_raw_last": "刘媛嫣17",
"alias_raw": [
"刘媛嫣17"
],
"key_kind": "norm",
"last_content": "(刘媛媛专属]ihone172566B颜色随机发10963人巳参与",
"last_prize_value_yuan": 0.0,
"max_prize_value_yuan": 5999.0,
"room_title": "刘媛嫣17"
},
{
"first_seen_ts": 1765952206.984938,
"last_seen_ts": 1765952245.0211933,
"seen_count": 2,
"pos_seen": 8,
"pos_updated_ts": 1765952245.0211933,
"room_title_raw_last": "岚钻(和",
"alias_raw": [
"岚钻(和"
],
"key_kind": "norm",
"last_content": "天然新疆夭山翠手镯",
"last_prize_value_yuan": 1099.0,
"max_prize_value_yuan": 1099.0,
"room_title": "岚钻和"
},
{
"first_seen_ts": 1765939683.9712315,
"last_seen_ts": 1765939683.9712315,
"seen_count": 1,
"pos_seen": 4,
"pos_updated_ts": 1765939683.9712315,
"room_title_raw_last": "钻爸钻",
"alias_raw": [
"钻爸钻"
],
"key_kind": "norm",
"last_content": "钻妈家左上角宠粉福袋冬被礼盒装",
"last_prize_value_yuan": 389.0,
"max_prize_value_yuan": 389.0,
"room_title": "钻爸钻"
},
{
"first_seen_ts": 1765938751.413124,
"last_seen_ts": 1765938751.413124,
"seen_count": 1,
"pos_seen": 0,
"pos_updated_ts": 1765938751.413124,
"room_title_raw_last": "SPRAYGR",
"alias_raw": [
"SPRAYGR"
],
"key_kind": "norm",
"last_content": "鲨鱼嘴新款冷帽44人巳参与",
"last_prize_value_yuan": 298.0,
"max_prize_value_yuan": 298.0,
"room_title": "SPRAYGR"
},
{
"first_seen_ts": 1765938147.3496847,
"last_seen_ts": 1765938147.3496847,
"seen_count": 1,
"pos_seen": 0,
"pos_updated_ts": 1765938147.3496847,
"room_title_raw_last": "新东方直",
"alias_raw": [
"新东方直"
],
"key_kind": "norm",
"last_content": "小米米家电烤箱家用小型大容量多功能全自动可控温",
"last_prize_value_yuan": 399.0,
"max_prize_value_yuan": 399.0,
"room_title": "新东方直"
},
{
"first_seen_ts": 1765938014.5983038,
"last_seen_ts": 1765938014.5983038,
"seen_count": 1,
"pos_seen": 1,
"pos_updated_ts": 1765938014.5983038,
"room_title_raw_last": "YK老张腕",
"alias_raw": [
"YK老张腕"
],
"key_kind": "norm",
"last_content": "凯卡思CaloricKing满夭星时尚系列轻奢女士手表腕。",
"last_prize_value_yuan": 1699.0,
"max_prize_value_yuan": 1699.0,
"room_title": "YK老张腕"
},
{
"first_seen_ts": 1765937663.8033075,
"last_seen_ts": 1765937959.922977,
"seen_count": 2,
"pos_seen": 0,
"pos_updated_ts": 1765937959.922977,
"room_title_raw_last": "弯弯的小。。",
"alias_raw": [
"弯弯的小。。",
"弯弯的小。"
],
"key_kind": "norm",
"last_content": "福袋(达播)路露营车107人巳参与",
"last_prize_value_yuan": 699.0,
"max_prize_value_yuan": 699.0,
"room_title": "弯弯的小"
},
{
"first_seen_ts": 1765935843.0916507,
"last_seen_ts": 1765935843.0916507,
"seen_count": 1,
"pos_seen": 3,
"pos_updated_ts": 1765935843.0916507,
"room_title_raw_last": "'\"1鄢点",
"alias_raw": [
"'\"1鄢点"
],
"key_kind": "norm",
"last_content": "(刘媛媛专属]ihone172566B颜色随机发20876人巳参与",
"last_prize_value_yuan": 5999.0,
"max_prize_value_yuan": 5999.0,
"room_title": "1鄢点"
},
{
"first_seen_ts": 1765850749.6202497,
"last_seen_ts": 1765935769.8568895,
"seen_count": 2,
"pos_seen": 1,
"pos_updated_ts": 1765935769.8568895,
"room_title_raw_last": "香香生活号",
"alias_raw": [
"香香生活号"
],
"key_kind": "norm",
"last_content": "便携式迷你小型宿舍手持电熨斗挂烫机熨烫机衣服家。",
"last_prize_value_yuan": 799.0,
"max_prize_value_yuan": 799.0,
"room_title": "香香生活号"
},
{
"first_seen_ts": 1765875476.9240448,
"last_seen_ts": 1765895278.3595254,
"seen_count": 5,
"pos_seen": 2,
"pos_updated_ts": 1765895278.3595254,
"room_title_raw_last": "麦小登-161优质主播--",
"alias_raw": [
"麦小登-161优质主播--",
"麦小登-161优质主播7",
"麦小登-16。。1优质主播-",
"麦小登-16优质主播"
],
"key_kind": "norm",
"last_content": "华为Hi畅享80/80s智能手机原装正品",
"last_prize_value_yuan": 1699.0,
"max_prize_value_yuan": 1699.0,
"room_title": "麦小登16优质主播",
"alias_norm": [
"麦小登161优质主播7",
"麦小登161优质主播"
],
"merged_from_last": "麦小登161优质主播",
"merged_ratio_last": 1.0
},
{
"first_seen_ts": 1765895188.980466,
"last_seen_ts": 1765895188.980466,
"seen_count": 1,
"pos_seen": 1,
"pos_updated_ts": 1765895188.980466,
"room_title_raw_last": "^122优质丰播",
"alias_raw": [
"^122优质丰播"
],
"key_kind": "norm",
"last_content": "(琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方",
"last_prize_value_yuan": 1699.0,
"max_prize_value_yuan": 1699.0,
"room_title": "122优质丰播"
},
{
"first_seen_ts": 1765892772.8962855,
"last_seen_ts": 1765895094.082833,
"seen_count": 3,
"pos_seen": 0,
"pos_updated_ts": 1765895094.082833,
"room_title_raw_last": "多余和毛。0优质丰播",
"alias_raw": [
"多余和毛。0优质丰播",
"多余和毛。。0优质丰播",
"多余和丢0优质丰播"
],
"key_kind": "norm",
"last_content": "(毛毛姐专属』适用苹果17手机17136人巳参与",
"last_prize_value_yuan": 5999.0,
"max_prize_value_yuan": 5999.0,
"room_title": "多余和丢0优质丰播",
"alias_norm": [
"多余和毛0优质丰播"
],
"merged_from_last": "多余和毛0优质丰播",
"merged_ratio_last": 0.8888888888888888
},
{
"first_seen_ts": 1765883613.880976,
"last_seen_ts": 1765894728.9513087,
"seen_count": 4,
"pos_seen": 5,
"pos_updated_ts": 1765894728.9513087,
"room_title_raw_last": "影哥.YING",
"alias_raw": [
"影哥:YING",
"影哥.YING"
],
"key_kind": "norm",
"last_content": "(YINGMOMO]影哥袜子",
"last_prize_value_yuan": 999.0,
"max_prize_value_yuan": 999.0,
"room_title": "影哥YING"
},
{
"first_seen_ts": 1765894277.634794,
"last_seen_ts": 1765894277.634794,
"seen_count": 1,
"pos_seen": 1,
"pos_updated_ts": 1765894277.634794,
"room_title_raw_last": "琦儿2122优质丰",
"alias_raw": [
"琦儿2122优质丰"
],
"key_kind": "norm",
"last_content": "(琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方",
"last_prize_value_yuan": 1699.0,
"max_prize_value_yuan": 1699.0,
"room_title": "琦儿2122优质丰"
},
{
"first_seen_ts": 1765893759.6038184,
"last_seen_ts": 1765893759.6038184,
"seen_count": 1,
"pos_seen": 6,
"pos_updated_ts": 1765893759.6038184,
"room_title_raw_last": "颜妍记.",
"alias_raw": [
"颜妍记."
],
"key_kind": "norm",
"last_content": "(颜研专属』全新智能大屏追剧安卓国产颜色随机668人巳参与",
"last_prize_value_yuan": 1699.0,
"max_prize_value_yuan": 1699.0,
"room_title": "颜妍记"
},
{
"first_seen_ts": 1765882862.0040636,
"last_seen_ts": 1765892869.9704888,
"seen_count": 6,
"pos_seen": 1,
"pos_updated_ts": 1765892869.9704888,
"room_title_raw_last": "琦儿12.。2优质主播",
"alias_raw": [
"琦儿122优质主播",
"琦儿12..2优质主播",
"琦儿12.。2优质主播"
],
"key_kind": "norm",
"last_content": "(琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方",
"last_prize_value_yuan": 1699.0,
"max_prize_value_yuan": 1699.0,
"room_title": "琦儿122优质主播"
},
{
"first_seen_ts": 1765884516.9036822,
"last_seen_ts": 1765892772.8817072,
"seen_count": 2,
"pos_seen": 0,
"pos_updated_ts": 1765892772.8817072,
"room_title_raw_last": "多余和丢0优质丰播",
"alias_raw": [
"多余和丢0优质丰播",
"多余和丢4优质主播",
"多余和丢4优质圭播"
],
"key_kind": "norm",
"last_content": "(毛毛姐专属』适用苹果17手机",
"last_prize_value_yuan": 0.0,
"max_prize_value_yuan": 5999.0,
"alias_norm": [
"多余和丢0优质丰播",
"多余和丢4优质主播"
],
"merged_from_last": "多余和丢0优质丰播",
"merged_ratio_last": 0.875,
"room_title": "多余和丢4优质圭播"
},
{
"first_seen_ts": 1765787027.4476137,
"last_seen_ts": 1765876877.9693072,
"seen_count": 11,
"pos_seen": 3,
"pos_updated_ts": 1765876877.9693072,
"room_title_raw_last": "三火孙...",
"alias_raw": [
"三火孙...",
"三火·孙.."
],
"key_kind": "norm",
"last_content": "【知音专属】999羽毛吊坠一+配送项链",
"last_prize_value_yuan": 899.0,
"max_prize_value_yuan": 1699.0,
"room_title": "三火孙"
},
{
"first_seen_ts": 1765736209.4437785,
"last_seen_ts": 1765874930.950471,
@@ -42,40 +556,6 @@
"merged_from_last": "陌玉珠宝二",
"merged_ratio_last": 0.8888888888888888
},
{
"first_seen_ts": 1765787027.4476137,
"last_seen_ts": 1765874595.4136896,
"seen_count": 8,
"pos_seen": 5,
"pos_updated_ts": 1765874595.4136896,
"room_title_raw_last": "三火孙...",
"alias_raw": [
"三火孙...",
"三火·孙.."
],
"key_kind": "norm",
"last_content": "【知音专属】创维娱乐影音畅享智能平板电脑",
"last_prize_value_yuan": 1199.0,
"max_prize_value_yuan": 1699.0,
"room_title": "三火孙"
},
{
"first_seen_ts": 1765768902.1252618,
"last_seen_ts": 1765874070.2471976,
"seen_count": 21,
"pos_seen": 1,
"pos_updated_ts": 1765874070.2471976,
"room_title_raw_last": "凡客陈年",
"alias_raw": [
"凡客陈年?",
"凡客陈年"
],
"key_kind": "norm",
"last_content": "小米RedmiPadSE新款平板11英寸护眼大屏全金属",
"last_prize_value_yuan": 1199.0,
"max_prize_value_yuan": 5999.0,
"room_title": "凡客陈年"
},
{
"first_seen_ts": 1765871013.503363,
"last_seen_ts": 1765871013.503363,
@@ -435,22 +915,6 @@
"max_prize_value_yuan": 2999.0,
"room_title": "帝克5惠T快乐33万本场"
},
{
"first_seen_ts": 1765850749.6202497,
"last_seen_ts": 1765850749.6202497,
"seen_count": 1,
"pos_seen": 1,
"pos_updated_ts": 1765850749.6202497,
"room_title_raw_last": "香香生活号",
"alias_raw": [
"香香生活号"
],
"key_kind": "norm",
"last_content": "便携式迷你小型宿舍手持电熨斗挂烫机熨烫机衣服家..",
"last_prize_value_yuan": 799.0,
"max_prize_value_yuan": 799.0,
"room_title": "香香生活号"
},
{
"first_seen_ts": 1765818808.158832,
"last_seen_ts": 1765819942.8913167,
+6 -25
View File
@@ -1,27 +1,8 @@
{
"updated_ts": 1765874930.9473379,
"reason": "add",
"room_pos": 2,
"current_room_title": "梵象名品",
"current_room_title_raw": "梵象名品...",
"reservations": [
{
"prize_value_yuan": 1580.0,
"content": "天然缅料A货翡翠甜甜圈吊坠/一件(微瑕)多样性:",
"future_ts": 1765875275.730418,
"future_str": "2025-12-16 16:54:35",
"pos_seen": 1,
"room_title": "陌玉珠宝",
"room_title_raw": "陌玉珠宝~"
},
{
"prize_value_yuan": 999.0,
"content": "Camudin黑水鬼系列黑盘钢带款(附带调表器)",
"future_ts": 1765875733.617007,
"future_str": "2025-12-16 17:02:13",
"pos_seen": 2,
"room_title": "梵象名品",
"room_title_raw": "梵象名品..."
}
]
"updated_ts": 1765986410.2242348,
"reason": "init",
"room_pos": 0,
"current_room_title": "",
"current_room_title_raw": "",
"reservations": []
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 702 KiB

+74
View File
@@ -0,0 +1,74 @@
import sys
import shutil
from pathlib import Path
def auto_fix_indentation(path: Path, indent_size: int = 4) -> int:
"""Naively fix lines whose indentation is not deeper than a preceding colon line.
Heuristic:
- When a line endswith ':' (non-blank, non-comment), the next non-empty line
that is not an 'else/elif/except/finally' should be indented strictly more.
- If it is not, increase its leading spaces to (prev_indent + indent_size).
This is a best-effort fixer for common mistakes that cause IndentationError.
"""
lines = path.read_text(encoding="utf-8").splitlines()
fixes = 0
def leading_spaces(s: str) -> int:
return len(s) - len(s.lstrip(" "))
for i in range(len(lines) - 1):
cur = lines[i]
nxt = lines[i + 1]
cur_strip = cur.strip()
nxt_strip = nxt.strip()
if not cur_strip:
continue
if cur_strip.startswith("#"):
continue
if not cur_strip.endswith(":"):
continue
# skip multi-colon lines like dicts etc. Simple heuristic: has space before colon.
# We still treat most control statements/defs.
# Skip the next line if it's empty or a comment.
if not nxt_strip or nxt_strip.startswith("#"):
continue
# If next line is a peer control keyword, don't force indent.
if nxt_strip.startswith(("else:", "elif ", "except", "finally:")):
continue
cur_indent = leading_spaces(cur)
nxt_indent = leading_spaces(nxt)
expected = cur_indent + indent_size
if nxt_indent <= cur_indent:
lines[i + 1] = " " * expected + nxt_strip
fixes += 1
if fixes:
path.write_text("\n".join(lines), encoding="utf-8")
return fixes
def main():
target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("douyin_fudai.py")
if not target.exists():
print(f"File not found: {target}")
sys.exit(1)
backup = target.with_suffix(target.suffix + ".bak")
shutil.copyfile(target, backup)
fixes = auto_fix_indentation(target)
print(f"Auto-fix done. Applied {fixes} indentation adjustments.")
print(f"Backup saved to: {backup}")
if __name__ == "__main__":
main()
+142
View File
@@ -0,0 +1,142 @@
"""
用于查看截图文件并确认坐标位置的辅助脚本
使用方法:
1. 运行程序后,会打开当前截图
2. 在图片上点击,会显示点击位置的坐标
3. 记录你需要的区域坐标
"""
import os
from PIL import Image
import sys
def show_image_coordinates(image_path):
"""显示图片并允许用户查看坐标"""
if not os.path.exists(image_path):
print(f"图片文件不存在: {image_path}")
return
try:
img = Image.open(image_path)
width, height = img.size
print(f"\n图片信息:")
print(f" 文件路径: {image_path}")
print(f" 尺寸: {width} x {height} 像素")
print(f"\n坐标说明:")
print(f" - 坐标系原点 (0, 0) 在左上角")
print(f" - X 轴向右递增")
print(f" - Y 轴向下递增")
print(f" - 格式: (x, y) 或 (x1, y1, x2, y2)")
print(f"\n如何获取坐标:")
print(f" 方法1: 使用Windows画图工具")
print(f" 1. 右键点击图片 -> 打开方式 -> 画图")
print(f" 2. 将鼠标移动到目标位置,状态栏会显示坐标 (X, Y)")
print(f" 3. 记录左上角坐标 (x1, y1) 和右下角坐标 (x2, y2)")
print(f"\n 方法2: 使用Python脚本交互式查看")
print(f" 运行: python {__file__} interactive")
print(f"\n 方法3: 使用代码获取图片尺寸")
print(f" 当前图片尺寸: {width} x {height}")
print(f" 你可以根据这个尺寸估算坐标")
# 如果是交互模式,尝试使用 tkinter 显示图片
if len(sys.argv) > 1 and sys.argv[1] == 'interactive':
try:
import tkinter as tk
from PIL import ImageTk
root = tk.Tk()
root.title(f"坐标查看器 - {os.path.basename(image_path)}")
# 计算显示尺寸(如果图片太大,缩放显示)
max_display_size = 1200
display_width, display_height = width, height
if width > max_display_size or height > max_display_size:
scale = min(max_display_size / width, max_display_size / height)
display_width = int(width * scale)
display_height = int(height * scale)
img_resized = img.resize((display_width, display_height), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(img_resized)
label = tk.Label(root, image=photo)
label.pack()
coord_label = tk.Label(root, text="将鼠标移动到图片上查看坐标", font=("Arial", 12))
coord_label.pack()
def on_mouse_move(event):
# 将显示坐标转换为实际坐标
if display_width != width or display_height != height:
scale_x = width / display_width
scale_y = height / display_height
actual_x = int(event.x * scale_x)
actual_y = int(event.y * scale_y)
else:
actual_x = event.x
actual_y = event.y
coord_label.config(text=f"坐标: ({actual_x}, {actual_y}) | 显示: ({event.x}, {event.y})")
def on_click(event):
# 将显示坐标转换为实际坐标
if display_width != width or display_height != height:
scale_x = width / display_width
scale_y = height / display_height
actual_x = int(event.x * scale_x)
actual_y = int(event.y * scale_y)
else:
actual_x = event.x
actual_y = event.y
print(f"点击坐标: ({actual_x}, {actual_y})")
coord_label.config(text=f"点击坐标: ({actual_x}, {actual_y})", fg="red")
label.bind("<Motion>", on_mouse_move)
label.bind("<Button-1>", 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)
+37
View File
@@ -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()
+375
View File
@@ -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")
+187
View File
@@ -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("已取消")
File renamed without changes.
+84
View File
@@ -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)
+328
View File
@@ -0,0 +1,328 @@
"""
Web 端自動化巡檢腳本
====================
用途:
- 打開 Web GUI(預設 http://127.0.0.1:8000/)
- 點擊「開始運行」
- 週期性採集:
- 日誌區域:<pre id="log">
- 實時截圖:<img id="liveShot">
- 在本地保留整個測試期間的所有截圖,並將每次截圖時的日誌文本一併保存,方便一一對應排查。
依賴:
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()
+55 -3
View File
@@ -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 = ["<failed to read logfile>"]
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 = ["<failed to read actions.log>"]
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)
+372
View File
@@ -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()
+101 -18
View File
@@ -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();
});
});
+23 -1
View File
@@ -26,6 +26,12 @@
</span>
刷新设备
</button>
<button id="btnScreenshot" class="btn">
<span class="btnIcon" aria-hidden="true">
<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>
</span>
截图
</button>
<button id="btnLoad" class="btn">
<span class="btnIcon" 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 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>
@@ -136,6 +142,22 @@
<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" />
<div class="hint">找小福袋图标时的最大重试次数,默认 5</div>
</div>
<div class="row grid2">
<div>
<label class="label">找福袋重试间隔(秒)</label>
<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" />
</div>
<div>
<label class="label">找福袋最大等待时间(秒)</label>
<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" />
<div class="hint">识别到福袋一般 4–6 秒,可按设备/网络情况微调</div>
</div>
</div>
<div class="row">
<label class="label">直播间检测阈值</label>
<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" />
<div class="hint">模板匹配阈值(0.0~1.0),默认0.8,值越高越严格,建议≥0.8</div>
</div>
<div class="row">
<label class="label">预约抢占最小价值(元)</label>
<input id="reservation_preempt_min_value" class="input" data-key="reservation_preempt_min_value" data-type="float" type="number" min="0" step="1" />
@@ -663,4 +685,4 @@
<script src="app.js"></script>
</body>
</html>
</html>
+132 -54
View File
@@ -1,100 +1,178 @@
@echo off
chcp 65001 >nul
REM ==========================================
REM Douyin Web GUI Launcher (Stable Version)
REM ==========================================
REM Save original code page
for /f "tokens=2 delims=:" %%a in ('chcp') do set "_ORIG_CP=%%a"
set "_ORIG_CP=%_ORIG_CP: =%"
chcp 65001 >nul 2>&1
setlocal enabledelayedexpansion
REM 切到脚本所在目录
pushd "%~dp0"
echo ========================================
echo 抖音挂机 Web GUI 一键启动
echo ========================================
echo.
REM 检查Python是否安装
python --version >nul 2>&1
REM Change to script directory
cd /d "%~dp0"
if errorlevel 1 (
echo [错误] 未检测到Python,请先安装Python
echo 下载地址: https://www.python.org/downloads/
echo [ERROR] Cannot change to script directory
pause
exit /b 1
goto :cleanup
)
echo [1/5] Python环境检查... OK
REM Save current directory to variable (for delayed expansion)
set "WORK_DIR=%~dp0"
set "WORK_DIR=!WORK_DIR:~0,-1!"
REM Create log file
set "LOG_FILE=%~dp0webgui_startup.log"
(
echo ========================================
echo Start time: %date% %time%
echo ========================================
) >> "%LOG_FILE%" 2>&1
echo.
echo ========================================
echo Douyin Web GUI Launcher
echo ========================================
echo.
REM 检查web_gui.py是否存在
REM [1/6] Check Python environment
echo [1/6] Checking Python environment...
python --version >> "%LOG_FILE%" 2>&1
if errorlevel 1 (
echo [ERROR] Python not detected, please install Python first
echo Download: https://www.python.org/downloads/
echo [ERROR] Python not installed >> "%LOG_FILE%"
pause
goto :cleanup
)
echo [1/6] Python environment check... OK
echo.
REM [2/6] Check required files
echo [2/6] Checking required files...
if not exist "web_gui.py" (
echo [错误] 未找到 web_gui.py 文件
echo [ERROR] web_gui.py not found
echo Current directory: !WORK_DIR!
echo [ERROR] web_gui.py does not exist >> "%LOG_FILE%"
pause
exit /b 1
goto :cleanup
)
echo [2/5] 文件检查... OK
echo [2/6] File check... OK
echo.
REM 停止旧的web_gui.py进程(避免端口占用)
echo [3/5] 停止旧进程...
powershell -NoProfile -Command "$ps = Get-CimInstance Win32_Process | Where-Object { ($_.CommandLine -like '*web_gui.py*') -and ($_.Name -like 'python*') }; if ($ps) { $ps | ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue; Write-Host \" [已停止] PID=$($_.ProcessId)\" } catch {} } } else { Write-Host \" [无旧进程]\" }" 2>nul
timeout /t 1 /nobreak >nul
echo [3/5] 停止旧进程... OK
REM [3/6] Stop old processes
echo [3/6] Stopping old processes...
REM Silently stop old processes, redirect all output to nul to avoid garbled text
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='SilentlyContinue'; Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object {$_.CommandLine -like '*web_gui.py*' -and $_.Name -like 'python*'} | ForEach-Object {Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue}" >nul 2>&1
timeout /t 2 /nobreak >nul
echo [3/6] Stopping old processes... OK
echo.
REM 设置端口(支持环境变量,默认8000)
REM [4/6] Port configuration
set "WEB_PORT=8000"
if defined PORT set "WEB_PORT=%PORT%"
if defined WEB_GUI_PORT set "WEB_PORT=%WEB_GUI_PORT%"
if defined PORT set "WEB_PORT=!PORT!"
if defined WEB_GUI_PORT set "WEB_PORT=!WEB_GUI_PORT!"
echo [4/6] Port configuration: !WEB_PORT!
echo.
REM 设置Python环境变量
REM [5/6] Start service
echo [5/6] Starting Web GUI service (Port: !WEB_PORT!)...
echo.
REM Set Python environment variables
set PYTHONIOENCODING=utf-8
set PYTHONUNBUFFERED=1
REM 启动Web GUI
echo [4/5] 启动Web GUI服务(端口: %WEB_PORT%)...
echo.
REM Determine Python executable path
set "PYTHON_EXE="
set "USE_VENV=0"
REM 检查是否有虚拟环境,如果有则使用,否则直接使用python
if exist ".venv\Scripts\activate.bat" (
start "抖音挂机 Web GUI" /D "%~dp0" cmd /c ".venv\Scripts\activate.bat && python web_gui.py"
REM Prefer virtual environment Python
if exist ".venv\Scripts\python.exe" (
set "PYTHON_EXE=.venv\Scripts\python.exe"
set "USE_VENV=1"
echo Virtual environment detected, using venv Python
) else if exist ".venv\Scripts\activate.bat" (
REM If python.exe not found, try using activate.bat
set "USE_VENV=2"
echo Virtual environment detected, using activate.bat
) else (
start "抖音挂机 Web GUI" /D "%~dp0" python web_gui.py
set "PYTHON_EXE=python"
set "USE_VENV=0"
echo Using system Python
)
REM 等待服务启动
echo 正在启动服务,请稍候...
REM Start service (in new window, keep window open)
if !USE_VENV! equ 1 (
REM Use virtual environment python.exe directly (use full path)
set "PYTHON_CMD=!WORK_DIR!\.venv\Scripts\python.exe web_gui.py"
) else if !USE_VENV! equ 2 (
REM Use activate.bat
set "PYTHON_CMD=call !WORK_DIR!\.venv\Scripts\activate.bat && python web_gui.py"
) else (
REM Use system Python
set "PYTHON_CMD=python web_gui.py"
)
REM Start command with proper quoting
start "Douyin Web GUI" /D "!WORK_DIR!" cmd /k "cd /d !WORK_DIR! && echo Starting Web GUI service... && echo. && !PYTHON_CMD!"
REM Wait for service to start
echo Starting service, please wait...
set /a count=0
:wait_loop
timeout /t 1 /nobreak >nul
timeout /t 2 /nobreak >nul
set /a count+=1
powershell -NoProfile -Command "$listener = Get-NetTCPConnection -LocalPort %WEB_PORT% -State Listen -ErrorAction SilentlyContinue; if ($listener) { exit 0 } else { exit 1 }" >nul 2>&1
REM Check if port is listening (use temporary variable to pass port number)
set "CHECK_PORT=!WEB_PORT!"
powershell -NoProfile -Command "$listener = Get-NetTCPConnection -LocalPort %CHECK_PORT% -State Listen -ErrorAction SilentlyContinue; if ($listener) { exit 0 } else { exit 1 }" >nul 2>&1
if not errorlevel 1 (
echo [4/5] Web GUI服务已启动
echo [5/6] Web GUI service started
goto :open_browser
)
if !count! geq 10 (
echo [警告] 服务启动超时,但仍将尝试打开浏览器
REM Timeout check (wait up to 30 seconds)
if !count! geq 15 (
echo [WARNING] Service startup timeout (waited 30 seconds)
echo Please check the error message in the new "Douyin Web GUI" window
echo Or check log file: %LOG_FILE%
goto :open_browser
)
goto :wait_loop
:open_browser
REM [6/6] Open browser
echo.
echo [5/5] 打开浏览器...
start "" "http://127.0.0.1:%WEB_PORT%"
echo [6/6] Opening browser...
timeout /t 1 /nobreak >nul
start "" "http://127.0.0.1:!WEB_PORT!"
echo.
echo ========================================
echo 启动完成!
echo Startup Complete!
echo ========================================
echo.
echo Web GUI地址: http://127.0.0.1:%WEB_PORT%
echo Web GUI URL: http://127.0.0.1:!WEB_PORT!
echo Log file: %LOG_FILE%
echo.
echo 提示:
echo - 关闭此窗口不会停止Web GUI服务
echo - 要停止服务,请运行"停止WebGUI服务.bat"
echo Notes:
echo - Web GUI service is running in a new window, do not close that window
echo - Closing this window will not stop the Web GUI service
echo - To stop the service, close the "Douyin Web GUI" window
echo - Or run "StopWebGUIService.bat"
echo.
echo 按任意键退出...
pause >nul
popd
REM Ask if view log
set /p view_log="View startup log? (Y/N): "
if /i "!view_log!"=="Y" (
if exist "%LOG_FILE%" (
notepad "%LOG_FILE%"
)
)
:cleanup
endlocal
if defined _ORIG_CP chcp %_ORIG_CP% >nul 2>&1
exit /b 0
+6
View File
@@ -1,4 +1,8 @@
@echo off
REM 保存原始代码页
for /f "tokens=2 delims=:" %%a in ('chcp') do set _ORIG_CP=%%a
set _ORIG_CP=%_ORIG_CP: =%
REM 设置为UTF-8编码
chcp 65001 >nul
echo ========================================
echo 停止抖音挂机 Web GUI 服务
@@ -14,3 +18,5 @@ echo.
echo 操作完成!
echo.
pause
REM 恢复原始代码页
if defined _ORIG_CP chcp %_ORIG_CP% >nul
File diff suppressed because it is too large. Load diff
-53
View File
@@ -1,53 +0,0 @@
@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
REM 切到脚本所在目录(项目根目录)
pushd "%~dp0"
echo ========================================
echo 抖音挂机 Web GUI 后台启动脚本
echo ========================================
echo.
REM 检查Python是否安装
python --version >nul 2>&1
if errorlevel 1 (
echo [错误] 未检测到Python,请先安装Python
pause
exit /b 1
)
REM 检查web_gui.py是否存在
if not exist "web_gui.py" (
echo [错误] 未找到 web_gui.py 文件
pause
exit /b 1
)
REM 停止旧的web_gui.py进程
powershell -NoProfile -Command "$ps = Get-CimInstance Win32_Process | Where-Object { ($_.CommandLine -like '*web_gui.py*') -and ($_.Name -like 'python*') }; $ps | ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } catch {} }" >nul 2>&1
timeout /t 1 /nobreak >nul
REM 读取端口配置
set "WEB_PORT=8000"
if defined PORT set "WEB_PORT=%PORT%"
if defined WEB_GUI_PORT set "WEB_PORT=%WEB_GUI_PORT%"
REM 启动Web GUI(隐藏窗口)
powershell -NoProfile -Command "Start-Process -FilePath python -ArgumentList 'web_gui.py' -WorkingDirectory (Get-Location).Path -WindowStyle Hidden" >nul 2>&1
REM 等待服务启动
timeout /t 2 /nobreak >nul
REM 打开浏览器
start "" "http://127.0.0.1:%WEB_PORT%"
echo Web GUI已启动(后台运行)
echo 访问地址: http://127.0.0.1:%WEB_PORT%
echo.
echo 3秒后自动关闭此窗口...
timeout /t 3 /nobreak >nul
popd
endlocal
-63
View File
@@ -1,63 +0,0 @@
# 关注标签坐标功能测试计划
## 测试目标
验证更新后的关注标签坐标 (712, 169) 是否正常工作。
## 更新内容
- **坐标位置**:左上角 (674, 153),右下角 (749, 185)
- **中心点**:x=712, y=169(基于1080x2400分辨率)
- **代码位置**:`douyin_fudai.py` 第566-567行
## 测试步骤
### 1. 代码验证测试
- [x] 确认坐标已更新为 (712, 169)
- [ ] 验证代码中使用了正确的坐标
- [ ] 确认坐标会在运行时被正确读取
### 2. 功能测试(需要实际运行)
#### 测试场景1:推荐页面检测
1. 确保脚本运行在推荐页面(推荐标签页)
2. 观察日志中是否输出:`检测到推荐页面,点击关注标签 -> (712, 169)`
3. 验证点击位置是否准确落在关注标签上
#### 测试场景2:页面跳转
1. 从推荐页面点击关注标签后
2. 验证是否成功切换到关注页面
3. 检查后续流程是否正常(进入直播间)
### 3. 坐标精度测试
- 如果点击位置不够准确,可以微调:
- 如果点击偏左:增加 x 值(例如 715)
- 如果点击偏右:减少 x 值(例如 710)
- 如果点击偏上:减少 y 值(例如 167)
- 如果点击偏下:增加 y 值(例如 171)
## 关键代码位置
### 坐标定义
```python
# douyin_fudai.py 第566-567行
self.yanghao_follow_tab_x = 712 # 关注标签中心的 x 坐标(1080x2400 基准)
self.yanghao_follow_tab_y = 169 # 关注标签中心的 y 坐标(1080x2400 基准)
```
### 坐标使用
```python
# douyin_fudai.py 第4810-4812行
follow_tab_x = int(getattr(self, "yanghao_follow_tab_x", 270))
follow_tab_y = int(getattr(self, "yanghao_follow_tab_y", 2340))
self.click(follow_tab_x, follow_tab_y)
```
## 注意事项
1. 坐标基于 1080x2400 分辨率,不同分辨率会自动缩放
2. 如果设备分辨率不是 1080x2400,需要确认缩放是否正确
3. 关注标签位于页面顶部,不在底部标签栏
## 预期结果
- 日志中显示正确的坐标值 (712, 169)
- 点击后成功切换到关注页面
- 后续流程正常执行
-62
View File
@@ -1,62 +0,0 @@
# 关注标签坐标更新 - 测试结果总结
## ✅ 测试通过
### 1. 坐标配置验证
- **当前坐标**: (712, 169)
- **预期坐标**: (712, 169)
- **状态**: ✅ 配置正确
### 2. 代码逻辑验证
- ✅ 坐标定义正确(douyin_fudai.py 第566-567行)
- ✅ 坐标使用代码正确(douyin_fudai.py 第4810-4811行)
- ✅ 日志输出代码存在(会显示点击的坐标值)
### 3. 功能说明
#### 坐标位置
- **左上角**: (674, 153)
- **右下角**: (749, 185)
- **中心点**: (712, 169)
- **分辨率基准**: 1080x2400
#### 使用场景
当脚本检测到当前在"推荐页面"(RECOMMEND_PAGE)时:
1. 会点击关注标签(坐标712, 169)
2. 等待2秒后点击进入直播间位置
3. 日志中会显示:`检测到推荐页面,点击关注标签 -> (712, 169)`
## 📝 后续测试建议
### 实际运行测试
1. **启动脚本**
- 通过Web GUI或命令行启动脚本
- 确保设备在推荐页面
2. **观察日志**
- 查看日志中是否出现:`检测到推荐页面,点击关注标签 -> (712, 169)`
- 验证坐标值是否正确
3. **验证点击准确性**
- 观察点击是否准确落在关注标签上
- 如果位置不准确,可以微调坐标
### 坐标微调指南
如果点击位置不够准确:
- **偏左**: 增加x值(例如 715)
- **偏右**: 减少x值(例如 710)
- **偏上**: 减少y值(例如 167)
- **偏下**: 增加y值(例如 171)
## 🔧 已修复的问题
- ✅ 更新了默认值从 (270, 2340) 改为 (712, 169)
- ✅ 更新了注释说明(从"底部标签栏"改为"顶部标签栏")
## 📋 测试完成清单
- [x] 坐标配置验证
- [x] 代码逻辑验证
- [x] 默认值更新
- [x] 注释更新
- [ ] 实际运行测试(需要连接设备)
- [ ] 点击位置准确性验证(需要实际运行)
-70
View File
@@ -1,70 +0,0 @@
# "开始运行"按钮没反应 - 问题排查
## 已完成的修复
### 1. 改进了错误处理
- ✅ 添加了 try-catch 包裹整个 startRun 函数
- ✅ 添加了"正在启动..."的提示信息
- ✅ 检查API返回结果,如果 `ok === false` 会显示错误信息
- ✅ 改进了 apiPost 函数,更好地处理错误响应
### 2. 代码改进点
**前端错误处理 (`webui/app.js`)**:
- 添加了启动提示:`[WEB] 正在启动...`
- 检查API返回结果,如果失败会显示错误信息
- 如果错误是"running",会提示用户先点击"停止"按钮
**API错误处理**:
- apiPost 函数现在会正确解析错误响应
- 如果API返回错误,会在日志中显示
## 可能的问题原因
根据测试,发现以下情况:
1. **进程启动成功但可能立即退出**
- 从日志看,进程确实启动了
- 但退出码是1,说明可能有错误
- 需要查看具体错误信息
2. **日志清空问题**
- 启动时会清空日志显示区域
- 但新的日志可能没有及时显示
- 需要检查日志轮询是否正常
3. **按钮点击可能被阻止**
- 如果已有进程在运行,会返回409错误
- 但现在会正确显示错误信息
## 排查步骤
### 步骤1:检查是否有进程在运行
1. 查看页面上的"运行状态"统计信息
2. 如果显示"运行中",说明已有进程
3. 需要先点击"停止"按钮
### 步骤2:查看日志
1. 点击"开始运行"后,查看日志区域
2. 应该会看到:`[WEB] 正在启动...`
3. 然后会看到:`[WEB] 已开始运行:device=...`
4. 或者错误信息:`[WEB] 启动失败: ...`
### 步骤3:查看浏览器控制台
1. 按F12打开开发者工具
2. 查看Console标签,看是否有错误信息
3. 查看Network标签,检查 `/api/start-run` 请求的响应
### 步骤4:检查后端日志
如果前端没有显示错误,可以查看:
- Web GUI的命令行窗口输出
- `logs/unified.log` 文件的最后几行
## 如果问题仍然存在
请提供以下信息:
1. 点击"开始运行"后,日志区域显示了什么?
2. 浏览器控制台(F12)有什么错误信息?
3. 页面上的"运行状态"显示什么?
4. 是否有其他提示信息?