feat: 更新配置文件以启用调试捕获,调整福袋相关坐标,优化预约处理逻辑,增强界面显示信息

This commit is contained in:
Your Name committed 2026-01-16 03:04:11 +08:00
1 parent 362b7c841c
commit df65adfe4e
19 files changed
+127 -1994

No files matched your search

+1 -1
View File
@@ -192,7 +192,7 @@
"monitor_critical_mb": 60.0
},
"debug_captures": {
"enabled": false,
"enabled": true,
"keep_days": 3,
"max_files": 2000,
"auto_cleanup": true,
+1 -1
View File
@@ -9,7 +9,7 @@
# 福袋相关常用坐标
# 福袋价值裁剪区域 (left, top, right, bottom)
VALUE_BOX_TARGET = (656, 1466, 769, 1656)
VALUE_BOX_TARGET = (643, 1466, 769, 1656)
# 福袋详情内容区域(任务/描述)
CONTENT_BOX = (389, 1273, 1000, 1534)
@@ -133,6 +133,12 @@ class ReservationHandler:
if best_match_pos is not None:
try:
room_info = room_pos_map[best_match_pos]
if isinstance(room_info, dict):
recorded_title = room_info.get("title", "")
else:
recorded_title = room_info[0] if room_info else ""
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] _find_room_pos_by_title:在映射表中找到匹配位置",
@@ -140,11 +146,7 @@ class ReservationHandler:
target_title=target_title[:50] if target_title else "",
found_pos=best_match_pos,
match_score=round(best_match_score, 3),
recorded_title=(
room_pos_map[best_match_pos][0][:50]
if room_pos_map[best_match_pos][0]
else ""
),
recorded_title=recorded_title[:50] if recorded_title else "",
)
except Exception:
pass
@@ -941,12 +943,15 @@ def _dump_room_pos_map_to_state(analyser: Any) -> None:
filtered = {}
for k, v in room_pos_map.items():
try:
title = (v[0] or "").strip()
if isinstance(v, dict):
title = (v.get("title", "") or "").strip()
title_raw = (v.get("title_raw", "") or "").strip()
else:
# 兼容旧格式
title = (v[0] or "").strip() if len(v) > 0 else ""
title_raw = (v[1] or "").strip() if len(v) > 1 else ""
except Exception:
title = ""
try:
title_raw = (v[1] or "").strip()
except Exception:
title_raw = ""
if not title and not title_raw:
continue
@@ -982,12 +987,23 @@ def _dump_room_pos_map_to_state(analyser: Any) -> None:
# 写 CSV
with open(csv_tmp, "w", encoding="utf-8", newline="") as cf:
writer = csv.writer(cf)
writer.writerow(["pos", "title", "title_raw"])
writer.writerow(["pos", "title", "title_raw", "has_fudai", "fudai_content"])
for k in sorted(
filtered.keys(), key=lambda x: int(x) if x.isdigit() else x
):
v = filtered.get(k, ["", ""]) or ["", ""]
writer.writerow([k, v[0], v[1]])
v = room_pos_map.get(int(k) if k.isdigit() else k, {})
if isinstance(v, dict):
title = v.get("title", "")
title_raw = v.get("title_raw", "")
has_fudai = v.get("has_fudai", False)
fudai_content = v.get("fudai_content", "")
else:
# 兼容旧格式
title = v[0] if len(v) > 0 else ""
title_raw = v[1] if len(v) > 1 else ""
has_fudai = False
fudai_content = ""
writer.writerow([k, title, title_raw, has_fudai, fudai_content[:100]])
try:
os.replace(csv_tmp, csv_path)
except Exception:
@@ -996,15 +1012,24 @@ def _dump_room_pos_map_to_state(analyser: Any) -> None:
# 写 Markdown(顶部注释 source)
with open(md_tmp, "w", encoding="utf-8") as mf:
mf.write(f"<!-- source: {final_path} -->\n\n")
mf.write("| 位置 | 标题 | 原始标题 |\n")
mf.write("|-:|:-|:-|\n")
mf.write("| 位置 | 标题 | 原始标题 | 有福袋 | 福袋内容 |\n")
mf.write("|-:|:-|:-|:-:|:-|\n")
for k in sorted(
filtered.keys(), key=lambda x: int(x) if x.isdigit() else x
):
v = filtered.get(k, ["", ""]) or ["", ""]
title = v[0].replace("|", "\\|")
title_raw = v[1].replace("|", "\\|")
mf.write(f"| {k} | {title} | {title_raw} |\n")
v = room_pos_map.get(int(k) if k.isdigit() else k, {})
if isinstance(v, dict):
title = v.get("title", "").replace("|", "\\|")
title_raw = v.get("title_raw", "").replace("|", "\\|")
has_fudai = "✓" if v.get("has_fudai", False) else ""
fudai_content = (v.get("fudai_content", "")[:50] + "..." if len(v.get("fudai_content", "")) > 50 else v.get("fudai_content", "")).replace("|", "\\|")
else:
# 兼容旧格式
title = (v[0] if len(v) > 0 else "").replace("|", "\\|")
title_raw = (v[1] if len(v) > 1 else "").replace("|", "\\|")
has_fudai = ""
fudai_content = ""
mf.write(f"| {k} | {title} | {title_raw} | {has_fudai} | {fudai_content} |\n")
try:
os.replace(md_tmp, md_path)
except Exception:
+82 -14
View File
@@ -2686,7 +2686,7 @@ def main():
map_ctrl = ttk.Frame(map_box)
map_ctrl.pack(fill=X, padx=10, pady=(8, 6))
map_auto_refresh_var = tk.BooleanVar(value=False)
map_auto_refresh_var = tk.BooleanVar(value=True)
ttk.Checkbutton(
map_ctrl, text="自动刷新(5s)", variable=map_auto_refresh_var
).pack(side=LEFT)
@@ -2697,14 +2697,28 @@ def main():
ttk.Label(map_ctrl, textvariable=mapping_source_var).pack(side=LEFT, padx=(8, 0))
mapping_tree = ttk.Treeview(
mapping_tab, columns=("pos", "title", "title_raw"), show="headings", height=12
mapping_tab, columns=("pos", "title", "title_raw", "has_fudai", "fudai_content", "fudai_time", "fudai_value", "participants", "copies", "is_reserved"), show="headings", height=12
)
mapping_tree.heading("pos", text="位置")
mapping_tree.heading("title", text="标题")
mapping_tree.heading("title_raw", text="原始标题")
mapping_tree.column("pos", width=80, anchor="e")
mapping_tree.column("title", width=340, anchor="w")
mapping_tree.column("title_raw", width=340, anchor="w")
mapping_tree.heading("has_fudai", text="有福袋")
mapping_tree.heading("fudai_content", text="福袋内容")
mapping_tree.heading("fudai_time", text="开奖时间")
mapping_tree.heading("fudai_value", text="价值(元)")
mapping_tree.heading("participants", text="参与人数")
mapping_tree.heading("copies", text="份数")
mapping_tree.heading("is_reserved", text="已预约")
mapping_tree.column("pos", width=50, anchor="e")
mapping_tree.column("title", width=150, anchor="w")
mapping_tree.column("title_raw", width=150, anchor="w")
mapping_tree.column("has_fudai", width=60, anchor="center")
mapping_tree.column("fudai_content", width=150, anchor="w")
mapping_tree.column("fudai_time", width=120, anchor="center")
mapping_tree.column("fudai_value", width=80, anchor="e")
mapping_tree.column("participants", width=80, anchor="e")
mapping_tree.column("copies", width=60, anchor="e")
mapping_tree.column("is_reserved", width=60, anchor="center")
mapping_tree.pack(fill=BOTH, expand=True, padx=10, pady=(6, 10))
# 加载映射表到表格(尝试多个可能的路径)
@@ -2715,6 +2729,33 @@ def main():
except Exception:
pass
# 加载预约状态(用于检查是否已预约)
reservations_data = {}
try:
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
reservations_paths = [
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
os.path.join(base_dir, "douyin", "state", "reservations.json"),
os.path.join(os.getcwd(), "douyin", "core", "state", "reservations.json"),
]
for res_path in reservations_paths:
try:
if os.path.exists(res_path):
with open(res_path, "r", encoding="utf-8") as f:
res_raw = f.read()
res_parsed = json.loads(res_raw)
if isinstance(res_parsed, dict) and "queue" in res_parsed:
# 提取预约队列中的位置信息
for item in res_parsed["queue"]:
pos = item.get("pos_seen", 0)
if pos:
reservations_data[pos] = item
break
except Exception:
pass
except Exception:
pass
# 优先使用基于项目目录的固定路径,避免不同工作目录导致无法找到状态文件
try:
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
@@ -2743,7 +2784,7 @@ def main():
if not parsed:
# 非JSON或解析错误:在表格中显示原始文本的一行提示
mapping_tree.insert(
"", "end", values=("-", "(非JSON,查看原始文件)", "")
"", "end", values=("-", "(非JSON,查看原始文件)", "", "", "", "", "", "", "", "")
)
else:
# 移除元信息
@@ -2763,18 +2804,45 @@ def main():
if isinstance(v, dict):
# 新格式:字典
title = (v.get("title", "") or "").strip() or "-"
title_raw = (v.get("title_raw", "") or "").strip() or "-"
has_fudai = v.get("has_fudai", False)
fudai_content = (v.get("fudai_content", "") or "").strip()
if has_fudai and fudai_content:
title += f" [福袋:{fudai_content[:20]}]"
title_raw = (
v.get("title_raw", "") or ""
).strip() or "-"
has_fudai = "✓" if v.get("has_fudai", False) else ""
fudai_content = (
v.get("fudai_content", "") or ""
).strip() or "-"
# 提取福袋详细信息
fudai_detail = v.get("fudai_detail")
if fudai_detail and isinstance(fudai_detail, (tuple, list)) and len(fudai_detail) >= 5:
# fudai_detail结构: (content, time_text, participants, copies, prize_value_yuan, countdown_tuple)
fudai_time = fudai_detail[1] or "-" # time_text
fudai_value = f"{fudai_detail[4] or 0:.2f}" if fudai_detail[4] else "-" # prize_value_yuan
participants = str(fudai_detail[2] or 0) if fudai_detail[2] else "-" # participants
copies = str(fudai_detail[3] or 0) if fudai_detail[3] else "-" # copies
else:
fudai_time = "-"
fudai_value = "-"
participants = "-"
copies = "-"
# 检查是否已预约
is_reserved = "✓" if int(k) in reservations_data else ""
else:
# 兼容旧格式:元组
title = (v[0] or "").strip() or "-"
title_raw = (v[1] or "").strip() or "-"
has_fudai = ""
fudai_content = "-"
fudai_time = "-"
fudai_value = "-"
participants = "-"
copies = "-"
is_reserved = "✓" if int(k) in reservations_data else ""
except Exception:
title, title_raw = "-", "-"
mapping_tree.insert("", "end", values=(k, title, title_raw))
title, title_raw, has_fudai, fudai_content, fudai_time, fudai_value, participants, copies, is_reserved = "-", "-", "", "-", "-", "-", "-", "-", "-"
mapping_tree.insert("", "end", values=(k, title, title_raw, has_fudai, fudai_content, fudai_time, fudai_value, participants, copies, is_reserved))
found = True
break
@@ -2784,7 +2852,7 @@ def main():
if not found:
mapping_source_var.set("未找到 room_pos_map.json")
mapping_tree.insert("", "end", values=("-", "未找到映射表文件", ""))
mapping_tree.insert("", "end", values=("-", "未找到映射表文件", "", "", "", "", "", "", "", ""))
# 绑定刷新按钮与自动刷新
btns = map_ctrl.winfo_children()
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

-360
View File
@@ -1,360 +0,0 @@
#!/usr/bin/env python3
"""
预约回退功能完整测试脚本
=======================
测试预约系统能否成功回退到目标直播间。
测试内容:
1. 预约队列处理和排序
2. 位置计算和回退方向判断
3. 滑动操作模拟
4. 回退校验逻辑
5. 完整回退流程
运行方法:
python test_reservation_backtrack.py
"""
import time
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from douyin.reservation.douyin_reservation_logic import (
process_reservation_attend_window,
_sort_reservations_inplace,
ReservationItem,
)
from douyin.reservation.douyin_reservation_verify import validate_back_to_reservation
class MockAnalyser:
"""模拟分析器对象"""
def __init__(self):
# 基本配置
self.reservation_back_verify_enabled = True
self.high_value_fudai_max_swipe_back = 10
self.reservation_back_total_timeout_seconds = 10.0
# 位置信息
self.room_pos = 5 # 当前在第5个直播间
self._room_pos_to_title_map = {
1: ("主播小明直播间", "主播小明直播间"),
2: ("美女主播在线", "美女主播在线"),
3: ("游戏直播高手", "游戏直播高手"),
4: ("音乐现场直播", "音乐现场直播"),
5: ("科技数码直播", "科技数码直播"), # 当前位置
6: ("美食烹饪教学", "美食烹饪教学"),
7: ("旅游风景直播", "旅游风景直播"),
}
# 滑动计数器
self.swipe_up_count = 0
self.swipe_down_count = 0
# 日志
self.logs = []
def _log_kv(self, tag, message, **kwargs):
"""记录日志"""
log_entry = f"[{tag}] {message}"
if kwargs:
log_entry += f" {kwargs}"
self.logs.append(log_entry)
print(log_entry)
def _seek_reservation_room(self, item):
"""模拟回退到预约直播间"""
target_pos = int(item.get("pos_seen", 0))
current_pos = self.room_pos
pos_diff = target_pos - current_pos
print(f"模拟回退:从位置 {current_pos} 到位置 {target_pos} (差值: {pos_diff})")
if pos_diff < 0:
# 向上回退
back_times = min(abs(pos_diff), self.high_value_fudai_max_swipe_back)
self.swipe_down_count += back_times
print(f"执行 {back_times} 次向下滑动")
elif pos_diff > 0:
# 向下前进
forward_times = min(pos_diff, self.high_value_fudai_max_swipe_back)
self.swipe_up_count += forward_times
print(f"执行 {forward_times} 次向上滑动")
# 更新当前位置
if abs(pos_diff) <= self.high_value_fudai_max_swipe_back:
self.room_pos = target_pos
print(f"成功回退到位置 {target_pos}")
return True
else:
print(
f"回退距离过大,限制在 {self.high_value_fudai_max_swipe_back} 次滑动内"
)
return False
def test_reservation_backtrack():
"""测试预约回退功能"""
print("=" * 70)
print("预约回退功能完整测试")
print("=" * 70)
# 创建模拟分析器
analyser = MockAnalyser()
# 测试1:预约队列排序
print("\n测试1:预约队列排序")
print("-" * 40)
reservations = [
{
"future_ts": time.time() + 600, # 10分钟后
"prize_value_yuan": 50.0,
"created_ts": time.time() - 100,
"pos_seen": 3,
"room_title": "游戏直播高手",
},
{
"future_ts": time.time() + 300, # 5分钟后
"prize_value_yuan": 100.0,
"created_ts": time.time() - 200,
"pos_seen": 1,
"room_title": "主播小明直播间",
},
{
"future_ts": time.time() + 300, # 5分钟后
"prize_value_yuan": 80.0,
"created_ts": time.time() - 50,
"pos_seen": 7,
"room_title": "旅游风景直播",
},
]
print("排序前:")
for i, r in enumerate(reservations):
print(
f" {i+1}. {r['room_title']} (位置{r['pos_seen']}) - {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元"
)
_sort_reservations_inplace(reservations)
print("排序后:")
for i, r in enumerate(reservations):
print(
f" {i+1}. {r['room_title']} (位置{r['pos_seen']}) - {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元"
)
# 验证排序:时间优先,其次价值
if (
reservations[0]["future_ts"] <= reservations[1]["future_ts"]
and reservations[1]["future_ts"] <= reservations[2]["future_ts"]
):
print("✓ 测试1通过:预约队列排序正确")
else:
print("✗ 测试1失败:预约队列排序不正确")
# 测试2:位置计算和回退方向
print("\n测试2:位置计算和回退方向")
print("-" * 40)
test_cases = [
{
"pos_seen": 3,
"expected_direction": "up",
"expected_steps": 2,
}, # 从5到3,向上2步
{
"pos_seen": 7,
"expected_direction": "down",
"expected_steps": 2,
}, # 从5到7,向下2步
{
"pos_seen": 5,
"expected_direction": "none",
"expected_steps": 0,
}, # 已在目标位置
{
"pos_seen": 1,
"expected_direction": "up",
"expected_steps": 4,
}, # 从5到1,向上4步
]
for i, case in enumerate(test_cases):
analyser.room_pos = 5 # 重置位置
analyser.swipe_up_count = 0
analyser.swipe_down_count = 0
target_pos = case["pos_seen"]
pos_diff = target_pos - analyser.room_pos
print(f"测试{i+1}: 从位置 {analyser.room_pos} 到位置 {target_pos}")
if pos_diff == 0:
direction = "none"
steps = 0
elif pos_diff < 0:
direction = "up"
steps = min(abs(pos_diff), analyser.high_value_fudai_max_swipe_back)
else:
direction = "down"
steps = min(pos_diff, analyser.high_value_fudai_max_swipe_back)
if direction == case["expected_direction"] and steps == case["expected_steps"]:
print(f" ✓ 方向: {direction}, 步数: {steps}")
else:
print(
f" ✗ 期望: {case['expected_direction']}/{case['expected_steps']}, 实际: {direction}/{steps}"
)
print("✓ 测试2通过:位置计算和回退方向正确")
# 测试3:完整回退流程
print("\n测试3:完整回退流程")
print("-" * 40)
# 重置分析器状态
analyser.room_pos = 5
analyser.swipe_up_count = 0
analyser.swipe_down_count = 0
analyser.logs = []
# 创建预约队列(只有一个预约项用于测试)
test_reservations = [
{
"future_ts": time.time() + 300, # 5分钟后
"prize_value_yuan": 100.0,
"created_ts": time.time() - 100,
"pos_seen": 3, # 目标位置
"room_title": "游戏直播高手",
"room_title_raw": "游戏直播高手",
}
]
# 模拟回调函数
def mock_swipe_down_back():
analyser.swipe_down_count += 1
analyser.room_pos -= 1
print(f"执行向下滑动,当前位置: {analyser.room_pos}")
def mock_swipe_up_to_next():
analyser.swipe_up_count += 1
analyser.room_pos += 1
print(f"执行向上滑动,当前位置: {analyser.room_pos}")
def mock_seek_reservation_room(item):
return analyser._seek_reservation_room(item)
def mock_sort_reservations():
pass
def mock_write_state():
pass
# 模拟 process_reservation_attend_window 调用
print(f"当前所在位置: {analyser.room_pos}")
print(f"目标预约位置: {test_reservations[0]['pos_seen']}")
# 直接调用回退函数
result = analyser._seek_reservation_room(test_reservations[0])
if result and analyser.room_pos == 3:
print("✓ 测试3通过:成功回退到目标直播间")
print(
f" 滑动统计: 向上{analyser.swipe_up_count}次, 向下{analyser.swipe_down_count}次"
)
else:
print("✗ 测试3失败:回退失败")
print(
f" 当前位置: {analyser.room_pos}, 目标位置: {test_reservations[0]['pos_seen']}"
)
# 测试4:回退校验
print("\n测试4:回退校验")
print("-" * 40)
# 模拟读取直播间标题的函数
def mock_read_live_room_title_core(analyser, y_pianyi):
# 根据当前位置返回对应的标题
pos = analyser.room_pos
if pos in analyser._room_pos_to_title_map:
room_info = analyser._room_pos_to_title_map[pos]
if isinstance(room_info, dict):
return room_info.get("title", "未知直播间"), room_info.get(
"title_raw", "未知直播间"
)
else:
# 兼容旧格式
title, title_raw = room_info
return title, title_raw
return "未知直播间", "未知直播间"
# 替换实际函数
import douyin.fudai.douyin_fudai_detail
original_func = douyin.fudai.douyin_fudai_detail.read_live_room_title_core
douyin.fudai.douyin_fudai_detail.read_live_room_title_core = (
mock_read_live_room_title_core
)
try:
# 测试校验通过的情况
analyser.room_pos = 3 # 在目标位置
result, detail = validate_back_to_reservation(analyser, test_reservations[0])
if result:
print("✓ 校验通过:正确识别目标直播间")
else:
print("✗ 校验失败:应该通过但失败了")
# 测试校验失败的情况
analyser.room_pos = 6 # 在位置6(直播间F),目标是位置3(直播间C)
result, detail = validate_back_to_reservation(analyser, test_reservations[0])
if not result:
print("✓ 校验失败:正确识别非目标直播间")
else:
print("✗ 校验通过:应该失败但通过了")
print("✓ 测试4通过:回退校验功能正常")
finally:
# 恢复原始函数
douyin.fudai.douyin_fudai_detail.read_live_room_title_core = original_func
# 测试5:边界情况
print("\n测试5:边界情况测试")
print("-" * 40)
# 测试超出最大回退次数的情况
analyser.room_pos = 5
analyser.high_value_fudai_max_swipe_back = 2 # 限制最大回退2次
far_reservation = {
"future_ts": time.time() + 300,
"prize_value_yuan": 100.0,
"created_ts": time.time() - 100,
"pos_seen": 1, # 距离5个位置
"room_title": "直播间A",
"room_title_raw": "直播间A",
}
result = analyser._seek_reservation_room(far_reservation)
if not result or analyser.room_pos != 1:
print("✓ 边界情况处理正确:超出最大回退次数限制")
else:
print("✗ 边界情况处理错误:不应该回退超过限制")
print("✓ 测试5通过:边界情况处理正确")
print("\n" + "=" * 70)
print("所有测试完成")
print("=" * 70)
if __name__ == "__main__":
test_reservation_backtrack()
-334
View File
@@ -1,334 +0,0 @@
#!/usr/bin/env python3
"""
预约回退错误场景测试脚本
=======================
特意制造各种差错,测试预约系统能否正确回退。
测试内容:
1. 滑动操作失败:模拟ADB命令执行失败
2. 位置计算错误:模拟room_pos更新异常
3. 校验失败重试:模拟校验失败后的重试逻辑
4. 回退超时:模拟回退操作超时
5. 映射表不一致:模拟运行时映射表与预约记录不匹配
6. 最大回退次数限制:测试超出限制后的处理
运行方法:
python test_reservation_error_scenarios.py
预期结果:
系统能在各种错误情况下正确处理并成功回退
"""
import time
import sys
import os
import random
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from douyin.reservation.douyin_reservation_verify import validate_back_to_reservation
class MockOperation:
"""模拟操作对象"""
def __init__(self):
self.mock_ocr_result = "美女主播在线" # 默认OCR结果
def get_screenshot(self, device_id):
"""模拟截图"""
pass
def analyse_pic_word(self, cut_name, change_color):
"""模拟OCR识别"""
return self.mock_ocr_result
class MockAnalyser:
"""模拟分析器对象,支持各种错误场景"""
def __init__(self, error_scenario=None):
# 基本配置
self.reservation_back_verify_enabled = True
self.high_value_fudai_max_swipe_back = 5 # 较小的限制便于测试
self.reservation_back_total_timeout_seconds = 5.0
# 位置信息
self.room_pos = 5 # 当前在第5个直播间
self._room_pos_to_title_map = {
1: ("主播小明直播间", "主播小明直播间"),
2: ("美女主播在线", "美女主播在线"),
3: ("游戏直播高手", "游戏直播高手"),
4: ("音乐现场直播", "音乐现场直播"),
5: ("科技数码直播", "科技数码直播"), # 当前位置
6: ("美食烹饪教学", "美食烹饪教学"),
7: ("旅游风景直播", "旅游风景直播"),
}
# 滑动计数器和错误控制
self.swipe_up_count = 0
self.swipe_down_count = 0
self.swipe_failures = 0
self.position_update_failures = 0
# 错误场景控制
self.error_scenario = error_scenario
self.retry_count = 0
self.max_retries = 3
# 日志
self.logs = []
# Mock operation对象
self.operation = MockOperation()
self.device_id = "mock_device"
def _log_kv(self, tag, message, **kwargs):
"""记录日志"""
log_entry = f"[{tag}] {message}"
if kwargs:
log_entry += f" {kwargs}"
self.logs.append(log_entry)
print(log_entry)
def cut_pic(self, x1, y1, x2, y2, filename, desc, y_pianyi=0):
"""模拟截图裁剪"""
pass
def _simulate_swipe_error(self):
"""模拟滑动错误"""
if self.error_scenario == "swipe_failure" and random.random() < 0.3:
self.swipe_failures += 1
print(f"模拟滑动失败 #{self.swipe_failures}")
return False
return True
def _simulate_position_error(self):
"""模拟位置更新错误"""
if self.error_scenario == "position_update_failure" and random.random() < 0.2:
self.position_update_failures += 1
print(f"模拟位置更新失败 #{self.position_update_failures}")
return False
return True
def _seek_reservation_room_with_errors(self, item):
"""带错误模拟的回退函数"""
target_pos = int(item.get("pos_seen", 0))
current_pos = self.room_pos
pos_diff = target_pos - current_pos
print(f"模拟回退:从位置 {current_pos} 到位置 {target_pos} (差值: {pos_diff})")
if pos_diff == 0:
print("已在目标位置")
return True
# 计算需要滑动的次数
if pos_diff < 0:
# 向上回退
max_steps = min(abs(pos_diff), self.high_value_fudai_max_swipe_back)
direction = "down"
else:
# 向下前进
max_steps = min(pos_diff, self.high_value_fudai_max_swipe_back)
direction = "up"
print(f"需要执行 {max_steps} 次向{direction}滑动")
# 模拟滑动过程,包含错误
actual_steps = 0
for i in range(max_steps):
if not self._simulate_swipe_error():
print(f"滑动失败,停止在步骤 {i+1}")
break
# 执行滑动
if direction == "down":
self.swipe_down_count += 1
if self._simulate_position_error():
self.room_pos -= 1
else:
self.swipe_up_count += 1
if self._simulate_position_error():
self.room_pos += 1
actual_steps += 1
print(f"步骤 {i+1}: 滑动成功,当前位置 {self.room_pos}")
# 检查是否到达目标
if self.room_pos == target_pos:
print(f"成功到达目标位置 {target_pos}")
return True
# 检查最终位置
if self.room_pos == target_pos:
print("最终成功到达目标位置")
return True
else:
print(f"回退未完成:当前位置 {self.room_pos}, 目标位置 {target_pos}")
return False
def test_error_scenarios():
"""测试各种错误场景"""
print("=" * 80)
print("预约回退错误场景测试")
print("=" * 80)
test_cases = [
{"name": "正常情况", "scenario": None, "description": "无错误情况下的正常回退"},
{
"name": "滑动失败",
"scenario": "swipe_failure",
"description": "模拟滑动操作随机失败",
},
{
"name": "位置更新失败",
"scenario": "position_update_failure",
"description": "模拟位置更新随机失败",
},
{
"name": "组合错误",
"scenario": "combined_errors",
"description": "同时模拟滑动和位置更新错误",
},
]
# 测试预约项
test_reservation = {
"future_ts": time.time() + 300, # 5分钟后
"prize_value_yuan": 100.0,
"created_ts": time.time() - 100,
"pos_seen": 2, # 目标位置(距离较远,便于测试错误)
"room_title": "美女主播在线",
"room_title_raw": "美女主播在线",
}
for i, test_case in enumerate(test_cases, 1):
print(f"\n测试{i}:{test_case['name']}")
print("-" * 50)
print(f"描述:{test_case['description']}")
# 创建分析器
analyser = MockAnalyser(test_case["scenario"])
# 设置随机种子以便重现
random.seed(42 + i)
# 重置状态
analyser.room_pos = 5
analyser.swipe_up_count = 0
analyser.swipe_down_count = 0
analyser.swipe_failures = 0
analyser.position_update_failures = 0
print(f"初始位置: {analyser.room_pos}")
print(f"目标位置: {test_reservation['pos_seen']}")
# 执行回退
start_time = time.time()
result = analyser._seek_reservation_room_with_errors(test_reservation)
end_time = time.time()
# 输出结果
print(f"回退结果: {'成功' if result else '失败'}")
print(f"最终位置: {analyser.room_pos}")
print(
f"滑动统计: 向上{analyser.swipe_up_count}次, 向下{analyser.swipe_down_count}次"
)
print(
f"错误统计: 滑动失败{analyser.swipe_failures}次, 位置更新失败{analyser.position_update_failures}次"
)
print(f"执行时间: {end_time - start_time:.2f}秒")
# 验证结果
if result and analyser.room_pos == test_reservation["pos_seen"]:
print("✓ 测试通过:成功回退到目标位置")
elif not result and analyser.room_pos != test_reservation["pos_seen"]:
print("✓ 测试通过:正确处理了错误情况")
else:
print("✗ 测试失败:结果不符合预期")
# 测试校验失败重试逻辑
print("\n测试5:校验失败重试逻辑")
print("-" * 50)
analyser = MockAnalyser()
analyser.room_pos = 5 # 故意设置错误位置
# 模拟校验失败后的重试
max_retry_attempts = 3
for attempt in range(max_retry_attempts):
print(f"重试次数 {attempt + 1}/{max_retry_attempts}")
# 模拟回退操作
analyser.room_pos = 5 # 重置到错误位置
analyser._seek_reservation_room_with_errors(test_reservation)
# 执行校验
result, detail = validate_back_to_reservation(analyser, test_reservation)
if result:
print(f"✓ 第{attempt + 1}次重试成功")
break
else:
print(f"✗ 第{attempt + 1}次校验失败,继续重试")
# 在实际系统中,这里会再次尝试回退
analyser.room_pos = 5 # 模拟重新开始
if not result:
print("✗ 重试逻辑测试失败:多次重试后仍未成功")
# 测试超时情况
print("\n测试6:超时情况")
print("-" * 50)
analyser = MockAnalyser()
analyser.reservation_back_total_timeout_seconds = 0.1 # 很短的超时时间
start_time = time.time()
# 模拟耗时操作
time.sleep(0.2) # 超过超时时间
end_time = time.time()
if end_time - start_time > analyser.reservation_back_total_timeout_seconds:
print("✓ 超时检测正确:操作时间超过限制")
else:
print("✗ 超时检测失败")
# 测试映射表不一致
print("\n测试7:映射表不一致")
print("-" * 50)
analyser = MockAnalyser()
analyser.room_pos = 2 # 在目标位置
# 修改映射表,使当前位置的标题与预约记录不一致
analyser._room_pos_to_title_map[2] = {
"title": "错误的直播间",
"title_raw": "错误的直播间",
"has_fudai": False,
"fudai_content": "",
"fudai_detail": None,
"timestamp": time.time(),
}
# 设置OCR识别结果为错误的标题
analyser.operation.mock_ocr_result = "错误的直播间"
result, detail = validate_back_to_reservation(analyser, test_reservation)
if not result:
print("✓ 映射表不一致检测正确:校验失败")
else:
print("✗ 映射表不一致检测失败:校验错误通过")
print("\n" + "=" * 80)
print("错误场景测试完成")
print("=" * 80)
if __name__ == "__main__":
test_error_scenarios()
-285
View File
@@ -1,285 +0,0 @@
#!/usr/bin/env python3
"""
预约回退校验测试脚本
===================
测试预约校验是否能正确回退直播间。
测试内容:
1. 基本校验通过:直播间标题匹配时校验通过
2. 标题不匹配:直播间标题不匹配时校验失败
3. 校验禁用:当校验开关关闭时直接通过
4. 福袋详情匹配:预约项与实际福袋详情匹配
5. 福袋详情不匹配:预约项与实际福袋详情不匹配
6. 观看任务检测:自动检测并跳过观看任务类型的福袋
7. 预约队列排序:验证预约队列按时间和价值正确排序
运行方法:
python test_reservation_verify.py
预期结果:
所有测试用例都应该通过(显示 ✓ 标记)
"""
import time
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from douyin.reservation.douyin_reservation_verify import (
validate_back_to_reservation,
match_reservation,
)
from douyin.reservation.douyin_reservation_logic import ReservationItem
class MockAnalyser:
"""模拟分析器对象"""
def __init__(self):
self.reservation_back_verify_enabled = True
self._room_pos_to_title_map = {}
self.y_pianyi = 0
self.logs = []
def _log_kv(self, tag, message, **kwargs):
"""记录日志"""
log_entry = f"[{tag}] {message}"
if kwargs:
log_entry += f" {kwargs}"
self.logs.append(log_entry)
print(log_entry)
def get_screenshot(self, device_id, use_service=False):
"""模拟截图"""
pass
def mock_read_live_room_title_core(analyser, y_pianyi):
"""模拟读取直播间标题"""
# 模拟当前在目标直播间
return "测试直播间", "测试直播间"
def test_reservation_verify():
"""测试预约回退校验"""
print("=" * 60)
print("预约回退校验测试")
print("=" * 60)
# 创建模拟分析器
analyser = MockAnalyser()
# 模拟替换实际的读取函数
import douyin.fudai.douyin_fudai_detail
original_func = douyin.fudai.douyin_fudai_detail.read_live_room_title_core
douyin.fudai.douyin_fudai_detail.read_live_room_title_core = (
mock_read_live_room_title_core
)
try:
# 测试1:基本校验通过
print("\n测试1:基本校验通过")
print("-" * 30)
reservation_item = {
"room_title": "测试直播间",
"room_title_raw": "测试直播间",
"pos_seen": 1,
"content": "测试福袋",
"prize_value_yuan": 100.0,
"future_ts": time.time() + 300, # 5分钟后
}
# 设置运行时映射表
analyser._room_pos_to_title_map = {1: ("测试直播间", "测试直播间")}
result, detail = validate_back_to_reservation(analyser, reservation_item)
print(f"校验结果: {result}")
print(f"详情: {detail}")
if result:
print("✓ 测试1通过:校验正确通过")
else:
print("✗ 测试1失败:校验应该通过但失败了")
# 测试2:标题不匹配
print("\n测试2:标题不匹配")
print("-" * 30)
analyser.logs = [] # 清空日志
def mock_read_live_room_title_core_wrong(analyser, y_pianyi):
"""模拟读取到错误的直播间标题"""
return "完全不同的直播间名称", "完全不同的直播间名称"
douyin.fudai.douyin_fudai_detail.read_live_room_title_core = (
mock_read_live_room_title_core_wrong
)
result, detail = validate_back_to_reservation(analyser, reservation_item)
print(f"校验结果: {result}")
print(f"详情: {detail}")
if not result:
print("✓ 测试2通过:校验正确失败")
else:
print("✗ 测试2失败:校验应该失败但通过了")
# 测试3:校验禁用
print("\n测试3:校验禁用")
print("-" * 30)
analyser.logs = [] # 清空日志
analyser.reservation_back_verify_enabled = False
result, detail = validate_back_to_reservation(analyser, reservation_item)
print(f"校验结果: {result}")
print(f"详情: {detail}")
if result:
print("✓ 测试3通过:校验禁用时直接通过")
else:
print("✗ 测试3失败:校验禁用时应该直接通过")
# 测试4:福袋详情匹配
print("\n测试4:福袋详情匹配")
print("-" * 30)
analyser.reservation_back_verify_enabled = True
analyser.logs = [] # 清空日志
# 模拟福袋详情
detail_tuple = (
"测试福袋", # content
"05:00", # time_text
100, # participants
10, # copies
100.0, # prize_value_yuan
(time.time(), time.time() + 300), # countdown_tuple
)
match_result, reason, debug_info = match_reservation(
reservation_item, detail_tuple
)
print(f"匹配结果: {match_result}")
print(f"原因: {reason}")
print(f"调试信息: {debug_info}")
if match_result:
print("✓ 测试4通过:福袋详情匹配成功")
else:
print("✗ 测试4失败:福袋详情应该匹配")
# 测试5:福袋详情不匹配
print("\n测试5:福袋详情不匹配")
print("-" * 30)
analyser.logs = [] # 清空日志
# 模拟不匹配的福袋详情
detail_tuple_mismatch = (
"不同的福袋", # content
"05:00", # time_text
100, # participants
10, # copies
200.0, # prize_value_yuan (不匹配)
(time.time(), time.time() + 600), # countdown_tuple (时间不匹配)
)
match_result, reason, debug_info = match_reservation(
reservation_item, detail_tuple_mismatch
)
print(f"匹配结果: {match_result}")
print(f"原因: {reason}")
print(f"调试信息: {debug_info}")
# 测试6:观看任务检测
print("\n测试6:观看任务检测")
print("-" * 30)
analyser.logs = [] # 清空日志
# 模拟观看任务的福袋详情
watch_task_detail = (
"观看5分钟领取福袋奖励", # content
"05:00", # time_text
100, # participants
10, # copies
100.0, # prize_value_yuan
(time.time(), time.time() + 300), # countdown_tuple
)
match_result, reason, debug_info = match_reservation(
reservation_item, watch_task_detail
)
print(f"匹配结果: {match_result}")
print(f"原因: {reason}")
print(f"调试信息: {debug_info}")
if not match_result and reason == "watch_task_detected":
print("✓ 测试6通过:观看任务正确被检测并跳过")
else:
print("✗ 测试6失败:观看任务应该被检测并跳过")
# 测试7:预约队列排序
print("\n测试7:预约队列排序")
print("-" * 30)
from douyin.reservation.douyin_reservation_logic import (
_sort_reservations_inplace,
)
reservations = [
{
"future_ts": time.time() + 600, # 10分钟后
"prize_value_yuan": 50.0,
"created_ts": time.time() - 100,
},
{
"future_ts": time.time() + 300, # 5分钟后
"prize_value_yuan": 100.0,
"created_ts": time.time() - 200,
},
{
"future_ts": time.time() + 300, # 5分钟后
"prize_value_yuan": 80.0,
"created_ts": time.time() - 50,
},
]
print("排序前:")
for i, r in enumerate(reservations):
print(
f" {i+1}. 时间: {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元"
)
_sort_reservations_inplace(reservations)
print("排序后:")
for i, r in enumerate(reservations):
print(
f" {i+1}. 时间: {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元"
)
# 验证排序:时间优先,其次价值
expected_order = [1, 2, 0] # 索引顺序
if (
reservations[0]["future_ts"] <= reservations[1]["future_ts"]
and reservations[1]["future_ts"] <= reservations[2]["future_ts"]
):
print("✓ 测试7通过:预约队列排序正确")
else:
print("✗ 测试7失败:预约队列排序不正确")
finally:
# 恢复原始函数
douyin.fudai.douyin_fudai_detail.read_live_room_title_core = original_func
if __name__ == "__main__":
test_reservation_verify()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 MiB

-179
View File
@@ -1,179 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""购物红包识别功能测试脚本"""
import sys
import os
from PIL import Image
import numpy as np
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from douyin.detection.douyin_pixel import detect_redpacket_popup_background
from douyin.other.douyin_popups import check_shopping_redpacket_popup
from douyin.fudai.core.coords import (
SHOPPING_REDPACKET_AREA,
STAGE_RED_PACKET_OCR,
DIAG_SHOPPING_REDPACKET,
)
def test_pixel_detection():
"""测试像素检测函数"""
print("=" * 60)
print("测试1: 像素检测函数")
print("=" * 60)
# 创建测试图像:模拟购物红包(红色背景)
width, height = 1080, 2400
test_img = Image.new("RGB", (width, height), color=(255, 255, 255))
pixels = test_img.load()
# 在中央区域添加红色像素(模拟购物红包)
red_color = (230, 80, 80) # 红色
for y in range(400, 1200):
for x in range(300, 780):
# 80%的像素为红色,20%为其他颜色
if (x + y) % 5 != 0:
pixels[x, y] = red_color
result = detect_redpacket_popup_background(test_img)
print(f"红色像素检测结果: {result}")
print(f"预期: True (因为有超过15%的红色像素)")
print()
return result
def test_coordinates():
"""测试坐标定义"""
print("=" * 60)
print("测试2: 坐标定义")
print("=" * 60)
print(f"SHOPPING_REDPACKET_AREA: {SHOPPING_REDPACKET_AREA}")
print(f"STAGE_RED_PACKET_OCR: {STAGE_RED_PACKET_OCR}")
print(f"DIAG_SHOPPING_REDPACKET: {DIAG_SHOPPING_REDPACKET}")
# 验证坐标范围
x1, y1, x2, y2 = DIAG_SHOPPING_REDPACKET
print(f"\n诊断区域范围:")
print(f" X: {x1} - {x2} (宽度: {x2-x1})")
print(f" Y: {y1} - {y2} (高度: {y2-y1})")
# 检查坐标是否有效
if x1 < x2 and y1 < y2:
print("✓ 坐标范围有效")
else:
print("✗ 坐标范围无效")
print()
def test_ocr_keywords():
"""测试OCR关键词"""
print("=" * 60)
print("测试3: OCR关键词检查")
print("=" * 60)
# 测试文本
test_texts = [
"邀你搶購物紅包",
"搶購物紅包",
"購物紅包",
"邀你搶",
"搶紅包",
"搶",
"最高領取",
"邀你抢",
"购物红包",
"抢红包",
"最高领取",
"抢",
]
# 关键词列表(与douyin_popups.py中的保持一致)
keywords = [
"邀你搶購物紅包",
"搶購物紅包",
"購物紅包",
"邀你搶",
"搶紅包",
"搶",
"最高領取",
"邀你抢",
"购物红包",
"抢红包",
"抢",
"最高领取",
]
print(f"定义的关键词数量: {len(keywords)}")
print("关键词列表:")
for kw in keywords:
print(f" - {kw}")
print("\n测试文本匹配:")
for text in test_texts:
matched = any(kw in text for kw in keywords)
status = "✓" if matched else "✗"
print(f" {status} '{text}'")
print()
def create_redpacket_test_image():
"""创建一个测试用的购物红包图像"""
print("=" * 60)
print("创建测试图像")
print("=" * 60)
# 创建1080x2400的图像
img = Image.new("RGB", (1080, 2400), color=(255, 255, 255))
pixels = img.load()
# 在中央画一个红色矩形(模拟购物红包)
red_color = (230, 80, 80)
for y in range(400, 1400):
for x in range(300, 780):
pixels[x, y] = red_color
# 保存图像
test_img_path = os.path.join(os.path.dirname(__file__), "test_redpacket.png")
img.save(test_img_path)
print(f"✓ 测试图像已保存: {test_img_path}")
print()
return test_img_path
if __name__ == "__main__":
print("\n")
print("╔" + "=" * 58 + "╗")
print("║" + " " * 58 + "║")
print("║" + "购物红包识别功能测试".center(58) + "║")
print("║" + " " * 58 + "║")
print("╚" + "=" * 58 + "╝")
print()
# 运行所有测试
test_coordinates()
test_ocr_keywords()
result = test_pixel_detection()
test_img_path = create_redpacket_test_image()
# 总结
print("=" * 60)
print("测试总结")
print("=" * 60)
print(f"✓ 像素检测函数: {'可用' if result else '无法检测'}")
print(f"✓ 坐标定义: 已更新到中央区域")
print(f"✓ OCR关键词: 12个关键词已定义(传统+简体中文)")
print(f"✓ 测试图像: {test_img_path}")
print()
print("下一步:")
print(" 1. 在实际应用中测试购物红包识别")
print(" 2. 查看 logs/actions.log 中的调试信息")
print(" 3. 验证像素检测和OCR识别是否都能触发")
print()
-159
View File
@@ -1,159 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试养号图标检测功能的核心逻辑
"""
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
def test_detect_icon_logic():
"""直接测试 _detect_icon 的核心逻辑"""
print("=== 测试 _detect_icon 核心逻辑 ===")
# 模拟 analyser 对象
class MockAnalyser:
def __init__(self):
self.config_path = "config/config.json"
self.resolution_ratio_x = 1080
self.resolution_ratio_y = 2400
self.yanghao_like_roi_offset_x = 0
self.yanghao_like_roi_offset_y = 0
self.yanghao_fav_roi_offset_x = 0
self.yanghao_fav_roi_offset_y = 0
self.yanghao_icon_roi_size = 180
self.yanghao_like_roi_scale = 1.5
self.yanghao_fav_roi_scale = 1.5
def _scale_from_base(self, x, y):
return x, y
def _capture_roi_screenshot(
self, roi_label, sx, sy, roi_px, shared_screenshot_path
):
print(f"✅ 截图 ROI: {roi_label} at ({sx}, {sy}) size {roi_px}")
return f"/tmp/test_roi_{roi_label}.png"
analyser = MockAnalyser()
# 模拟修改后的 _detect_icon 逻辑
def mock_detect_icon(action, base_x, base_y, template_path, roi_label):
print(f"\n🔍 测试检测: {action}")
# 坐标缩放
sx, sy = analyser._scale_from_base(int(base_x), int(base_y))
print(f" 缩放坐标: ({base_x}, {base_y}) -> ({sx}, {sy})")
# ROI 大小计算
roi_size = analyser.yanghao_icon_roi_size
scale_x = analyser.resolution_ratio_x / 1080.0
scale_y = analyser.resolution_ratio_y / 2400.0
action_scale = (
analyser.yanghao_like_roi_scale
if action == "爱心"
else analyser.yanghao_fav_roi_scale
)
roi_px = max(1, int(roi_size * max(scale_x, scale_y) * float(action_scale)))
print(f" ROI 大小: {roi_px}px")
# 截图
roi_path = analyser._capture_roi_screenshot(roi_label, sx, sy, roi_px, None)
# 修改后的逻辑:只截图不识别,总是假设图标存在
print(f" 📸 只截图不识别,假设图标存在")
detected, score = True, 1.0
print(f" ✅ 结果: detected={detected}, score={score}")
return detected, score
# 测试爱心图标检测
like_ok, like_score = mock_detect_icon("爱心", 950, 1872, "", "action_like_roi")
# 测试收藏图标检测
fav_ok, fav_score = mock_detect_icon("收藏", 842, 1872, "", "action_fav_roi")
print("\n🎯 测试结果:")
print(
f" 爱心图标: {'✅ 检测成功' if like_ok else '❌ 检测失败'} (score={like_score})"
)
print(
f" 收藏图标: {'✅ 检测成功' if fav_ok else '❌ 检测失败'} (score={fav_score})"
)
if like_ok and fav_ok:
print("✅ 核心逻辑测试通过:图标检测总是成功,符合修改要求")
else:
print("❌ 核心逻辑测试失败")
return like_ok and fav_ok
def test_click_logic():
"""测试点击逻辑"""
print("\n=== 测试点击逻辑 ===")
# 模拟点击函数
click_calls = []
def mock_click(device_id, x, y):
click_calls.append((device_id, x, y))
print(f"🖱️ 点击设备 {device_id} 坐标 ({x}, {y})")
# 模拟概率点击逻辑
def simulate_action_click(action, icon_x, icon_y, prob, device_id):
print(f"\n🎲 测试 {action} 点击 (概率: {prob})")
if prob > 0 and 1.0 >= prob: # 概率为1.0时总是点击
print(f" 随机数: 0.5 (小于等于 {prob}) -> 执行点击")
mock_click(device_id, icon_x, icon_y)
return True
else:
print(f" 随机数: 0.8 (大于 {prob}) -> 跳过点击")
return False
# 测试参数
device_id = "test_device_001"
like_x, like_y = 950, 1872
fav_x, fav_y = 842, 1872
# 模拟概率为1.0(总是点击)
like_clicked = simulate_action_click("爱心", like_x, like_y, 1.0, device_id)
fav_clicked = simulate_action_click("收藏", fav_x, fav_y, 1.0, device_id)
print("\n📊 点击结果:")
print(f" 爱心点击: {'✅ 已执行' if like_clicked else '❌ 未执行'}")
print(f" 收藏点击: {'✅ 已执行' if fav_clicked else '❌ 未执行'}")
print(f" 点击记录: {len(click_calls)} 次")
expected_clicks = [(device_id, like_x, like_y), (device_id, fav_x, fav_y)]
if click_calls == expected_clicks:
print("✅ 点击逻辑测试通过:坐标正确,点击执行正常")
return True
else:
print("❌ 点击逻辑测试失败")
return False
if __name__ == "__main__":
print("🚀 开始测试养号功能修改")
print("=" * 50)
# 测试核心检测逻辑
detect_ok = test_detect_icon_logic()
# 测试点击逻辑
click_ok = test_click_logic()
print("\n" + "=" * 50)
print("📋 最终测试结果:")
print(f" 图标检测逻辑: {'✅ 通过' if detect_ok else '❌ 失败'}")
print(f" 点击执行逻辑: {'✅ 通过' if click_ok else '❌ 失败'}")
if detect_ok and click_ok:
print("\n🎉 所有测试通过!修改后的养号功能工作正常")
print(" - 图标检测:只截图不进行OCR识别,总是假设图标存在")
print(" - 点击动作:在配置坐标上正确执行")
print(" - 概率控制:根据配置概率决定是否执行动作")
else:
print("\n❌ 部分测试失败,需要检查代码修改")
-107
View File
@@ -1,107 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试养号图标检测功能
"""
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
# 模拟 analyser 对象
class MockAnalyser:
def __init__(self):
self.config_path = "config/config.json"
self.resolution_ratio_x = 1080
self.resolution_ratio_y = 2400
self.yanghao_like_roi_offset_x = 0
self.yanghao_like_roi_offset_y = 0
self.yanghao_fav_roi_offset_x = 0
self.yanghao_fav_roi_offset_y = 0
self.yanghao_icon_roi_size = 180
self.yanghao_like_roi_scale = 1.5
self.yanghao_fav_roi_scale = 1.5
def _scale_from_base(self, x, y):
return x, y
def _capture_roi_screenshot(
self, roi_label, sx, sy, roi_px, shared_screenshot_path
):
print(f"[测试] 截图 ROI: {roi_label} at ({sx}, {sy}) size {roi_px}")
return f"/tmp/test_roi_{roi_label}.png"
# 导入测试函数
from douyin.other.douyin_yanghao import yanghao_idle
def test_detect_icon():
"""测试 _detect_icon 函数"""
print("=== 测试 _detect_icon 函数 ===")
# 创建模拟 analyser
analyser = MockAnalyser()
# 模拟 yanghao_idle 中的 _detect_icon 调用
def _step_shot(label):
print(f"[测试] 步骤截图: {label}")
# 由于 _detect_icon 是嵌套函数,我们需要模拟其行为
# 直接测试修改后的逻辑
print("测试爱心图标检测...")
# 模拟截图
analyser._capture_roi_screenshot("action_like_roi", 950, 1872, 270, None)
print("[养号] 检测: 爱心 -> 只截图不识别,假设图标存在")
print("测试收藏图标检测...")
analyser._capture_roi_screenshot("action_fav_roi", 842, 1872, 270, None)
print("[养号] 检测: 收藏 -> 只截图不识别,假设图标存在")
print("✅ _detect_icon 函数测试完成")
def test_yanghao_idle():
"""测试 yanghao_idle 函数(简化版)"""
print("\n=== 测试 yanghao_idle 函数 ===")
analyser = MockAnalyser()
analyser.operation = MockOperation()
analyser.device_id = "test_device"
# 设置测试参数
analyser.yanghao_enable_actions = True
analyser.yanghao_like_prob = 1.0
analyser.yanghao_fav_prob = 1.0
analyser.yanghao_comment_prob = 0.0 # 不测试评论
analyser.yanghao_like_icon_x = 950
analyser.yanghao_like_icon_y = 1872
analyser.yanghao_fav_icon_x = 842
analyser.yanghao_fav_icon_y = 1872
analyser.yanghao_after_dwell_swipe_distance_px = 900
analyser.yanghao_after_dwell_swipe_direction = "up"
print("开始测试 yanghao_idle (5秒)...")
try:
yanghao_idle(analyser, 5) # 只运行5秒
print("✅ yanghao_idle 函数测试完成")
except Exception as e:
print(f"❌ yanghao_idle 函数测试失败: {e}")
class MockOperation:
def click(self, device_id, x, y):
print(f"[测试] 点击设备 {device_id} 坐标 ({x}, {y})")
def delay(self, seconds):
print(f"[测试] 延迟 {seconds} 秒")
def get_screenshot(self, device_id, use_service=False):
print(f"[测试] 获取设备 {device_id} 截图")
if __name__ == "__main__":
test_detect_icon()
test_yanghao_idle()
print("\n🎉 所有测试完成!")
-29
View File
@@ -1,29 +0,0 @@
from douyin.logging.douyin_logging_wrapper import LoggingWrapper
class DummyAnalyser:
def __init__(self):
self._log_seq = 0
self._last_log_tag = None
self._last_action_tag = None
self._run_id = "test"
self._std_logger = None
analyser = DummyAnalyser()
# 普通操作
LoggingWrapper.enhanced_log_kv(analyser, "操作", "执行点击", x=100, y=200)
# 截图相关
LoggingWrapper.enhanced_log_kv(
analyser, "截图", "保存截图", filename="step1.png", log_type="SCREENSHOT"
)
# 错误
try:
raise ValueError("测试错误")
except Exception as e:
LoggingWrapper.enhanced_log_kv(
analyser, "错误", "发生异常", error=str(e), log_type="ERR"
)
print("测试完成")
-73
View File
@@ -1,73 +0,0 @@
from douyin.core.douyin_fudai import fudai_analyse
from douyin.utils import douyin_config
class DummyOp:
def __init__(self):
self.clicked_back = False
self.clicked_coord = None
def click_back(self, device_id=None):
print("DummyOp.click_back called, device_id=", device_id)
self.clicked_back = True
def click(self, device_id, x, y):
print(f"DummyOp.click called at ({x},{y}), device_id={device_id}")
self.clicked_coord = (x, y)
def simulate():
a = fudai_analyse()
# use dummy op to avoid real adb
a.operation = DummyOp()
# ensure config loads (reads config/config.json)
a.load_config()
print("config enable_back_on_misses ->", getattr(a, "enable_back_on_misses", None))
# 快速验证:强制设置阈值为 1(触发返回键)
a.fudai_exit_after_misses = 1
print("(test override) fudai_exit_after_misses ->", a.fudai_exit_after_misses)
# simulate "not found" path logic
cur = int(getattr(a, "_consecutive_no_fudai_count", 0) or 0)
print("initial consecutive count ->", cur)
cur += 1
setattr(a, "_consecutive_no_fudai_count", cur)
print("after increment ->", cur)
threshold = int(getattr(a, "fudai_exit_after_misses", 0) or 0) or None
if threshold is None or threshold <= 0:
threshold = 30
if threshold and cur >= threshold:
print("threshold reached: cur=", cur, "threshold=", threshold)
enabled = getattr(a, "enable_back_on_misses", None)
print("enable_back_on_misses attribute ->", enabled)
if enabled is None:
# try load from file
try:
douyin_config.ConfigManager.load_config_from_file(a)
enabled = bool(getattr(a, "enable_back_on_misses", True))
except Exception:
enabled = True
print("final enabled ->", enabled)
if enabled:
try:
a.operation.click_back(a.device_id)
except Exception:
try:
# fallback coord click
rx = int(getattr(a, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(a, "resolution_ratio_y", 2400) or 2400)
back_x = int(50 * rx / 1080)
back_y = int(50 * ry / 2400)
a.operation.click(a.device_id, back_x, back_y)
except Exception:
print("both click_back and click fallback failed")
else:
print("enabled is False; skipping back click")
else:
print("threshold not reached: cur=", cur, "threshold=", threshold)
if __name__ == "__main__":
simulate()
-18
View File
@@ -1,18 +0,0 @@
from douyin.utils.douyin_utils import extract_prize_value_yuan
tests = [
"¥12.34",
"¥12·34",
"¥12.34",
"¥12.34",
"12.34元",
"12,345.67",
"¥O2.5O",
"¥1O.5",
"价值:12.5",
"价值12。5",
"价值12·5",
"随机文本 0.5 元",
]
for t in tests:
print(t, "->", extract_prize_value_yuan(t))
-39
View File
@@ -1,39 +0,0 @@
from douyin.handlers.douyin_swipe_handler import SwipeHandler
class DummyOp:
def click_back(self, device_id=None):
print("DummyOp.click_back called, device_id=", device_id)
def delay(self, s):
pass
class DummyAnalyser:
def __init__(self):
self.operation = DummyOp()
self.device_id = "DUMMY"
self._swipe_times = 5
self.reset_after_swipes_enabled = True
self.reset_after_swipes = 5
self.reset_after_swipes_action = "back"
self.resolution_ratio_x = 1080
self.resolution_ratio_y = 2400
self.room_pos = 3
if __name__ == "__main__":
a = DummyAnalyser()
print(
"Before maybe_reset, _swipe_times=",
a._swipe_times,
"action=",
a.reset_after_swipes_action,
)
SwipeHandler.maybe_reset_after_swipes(a)
print(
"After maybe_reset, _swipe_times=",
getattr(a, "_swipe_times", None),
"room_pos=",
getattr(a, "room_pos", None),
)
-28
View File
@@ -1,28 +0,0 @@
from douyin.handlers import douyin_swipe_ops
from douyin.core.douyin_fudai import fudai_analyse
class DummyOp:
def _adb(self):
# Return path to non-existing adb to force fallback
return "adb"
def swipe(self, device_id, sx, sy, ex, ey, duration_ms):
print(
f"DummyOp.swipe called device={device_id} from ({sx},{sy}) to ({ex},{ey}) duration={duration_ms}"
)
def simulate_once(i: int):
a = fudai_analyse()
a.operation = DummyOp()
a.device_id = f"DUMMY{i}"
a.resolution_ratio_x = 1080
a.resolution_ratio_y = 2400
print(f"--- simulate swipe #{i} ---")
douyin_swipe_ops.swipe_up_switch_live(a)
if __name__ == "__main__":
for i in range(1, 11):
simulate_once(i)
-349
View File
@@ -1,349 +0,0 @@
import os
import sys
from pprint import pprint
import time
import numpy as np
from PIL import Image
# Ensure project root is on sys.path
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
from path_config import (
get_screenshot_path,
get_like_template_path,
get_fav_template_path,
)
try:
from douyin.core.douyin_fudai import fudai_analyse
except Exception as e:
print("Failed to import fudai_analyse:", e)
sys.exit(2)
def test_detection_for_polygon(poly, tpl_path, label):
a = fudai_analyse()
# ensure template path
if not tpl_path or not os.path.exists(tpl_path):
print(f"Template for {label} not found: {tpl_path}")
return
# compute bbox
xs = [int(p[0]) for p in poly]
ys = [int(p[1]) for p in poly]
x1, x2 = min(xs), max(xs)
y1, y2 = min(ys), max(ys)
cx = (x1 + x2) // 2
cy = (y1 + y2) // 2
size = max(1, max(x2 - x1, y2 - y1))
print(f"{label} bbox: ({x1},{y1})-({x2},{y2}), center=({cx},{cy}), size={size}")
sx, sy = a._scale_from_base(int(cx), int(cy))
print("scaled center:", sx, sy)
# compute pixel ROI size similar to yanghao logic
try:
scale_x = float(getattr(a, "resolution_ratio_x", 1080)) / 1080.0
scale_y = float(getattr(a, "resolution_ratio_y", 2400)) / 2400.0
except Exception:
scale_x = scale_y = 1.0
try:
if label == "like":
action_scale = float(getattr(a, "yanghao_like_roi_scale", 1.5))
else:
action_scale = float(getattr(a, "yanghao_fav_roi_scale", 1.5))
except Exception:
action_scale = 1.5
size_px = max(1, int(size * max(scale_x, scale_y) * float(action_scale)))
print(
f"computed size_px={size_px} (base={size} scale_x={scale_x:.3f} scale_y={scale_y:.3f} action_scale={action_scale})"
)
roi = a._capture_roi_screenshot(f"test_{label}", sx, sy, int(size_px))
print("roi saved to:", roi)
if not roi or not os.path.exists(roi):
print("ROI not available, abort")
return
detected, score = a._match_icon_template(roi, tpl_path)
print(f"Result for {label}: detected={detected}, score={score}")
def _match_score_like_runtime(roi_img: Image.Image, tpl_img: Image.Image) -> float:
"""尽量复刻 `fudai_analyse._match_icon_template` 的打分逻辑(返回 score)。"""
roi_img = roi_img.convert("RGB")
tpl_img = tpl_img.convert("RGB")
rw, rh = roi_img.size
tw, th = tpl_img.size
if tw > rw or th > rh:
scale = min(rw / tw, rh / th, 1.0)
new_w = max(1, int(tw * scale))
new_h = max(1, int(th * scale))
tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS)
roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32)
tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32)
ih, iw = roi_gray.shape
th, tw = tpl_gray.shape
def _corr(a: np.ndarray, b: np.ndarray) -> float:
a = a.flatten()
b = b.flatten()
a = a - a.mean()
b = b - b.mean()
denom = float(np.linalg.norm(a) * np.linalg.norm(b))
if denom <= 1e-6:
return -1.0
return float(np.dot(a, b) / denom)
if ih == th and iw == tw:
return _corr(roi_gray, tpl_gray)
best = -1.0
if ih >= th and iw >= tw:
cy = ih // 2 - th // 2
cx = iw // 2 - tw // 2
cy = max(0, min(cy, ih - th))
cx = max(0, min(cx, iw - tw))
window = roi_gray[cy : cy + th, cx : cx + tw]
best = max(best, _corr(window, tpl_gray))
step_y = max(1, th // 6)
step_x = max(1, tw // 6)
for y in range(0, ih - th + 1, step_y):
for x in range(0, iw - tw + 1, step_x):
window = roi_gray[y : y + th, x : x + tw]
best = max(best, _corr(window, tpl_gray))
if best < -0.5:
return 0.0
return float(best)
def search_best_roi_for_polygon(poly, tpl_path, label):
"""在 `pic/screenshot.png` 上搜索 score 最好的 ROI(中心偏移+大小)。
输出:最佳 score、像素中心/大小、以及换算回 1080x2400 基准的 rect/poly。
"""
ss = get_screenshot_path()
if not os.path.exists(ss):
print("Screenshot not found at pic/screenshot.png; abort.")
return None
if not tpl_path or not os.path.exists(tpl_path):
print(f"Template for {label} not found: {tpl_path}")
return None
screenshot_img = Image.open(ss).convert("RGB")
tpl_img = Image.open(tpl_path).convert("RGB")
sw, sh = screenshot_img.size
# 使用截图尺寸推导缩放(更贴近真机)
scale_x = sw / 1080.0
scale_y = sh / 2400.0
xs = [int(p[0]) for p in poly]
ys = [int(p[1]) for p in poly]
x1, x2 = min(xs), max(xs)
y1, y2 = min(ys), max(ys)
base_cx = (x1 + x2) // 2
base_cy = (y1 + y2) // 2
base_size = max(1, max(x2 - x1, y2 - y1))
px_cx = int(round(base_cx * scale_x))
px_cy = int(round(base_cy * scale_y))
# 与 test 脚本一致的初始 size_px
a = fudai_analyse()
try:
if label == "like":
action_scale = float(getattr(a, "yanghao_like_roi_scale", 1.5))
else:
action_scale = float(getattr(a, "yanghao_fav_roi_scale", 1.5))
except Exception:
action_scale = 1.5
base_size_px = max(1, int(base_size * max(scale_x, scale_y) * float(action_scale)))
offsets = list(range(-120, 121, 12))
size_muls = [0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2]
best = {
"score": -1.0,
"cx": px_cx,
"cy": px_cy,
"size_px": base_size_px,
"dx": 0,
"dy": 0,
"mul": 1.0,
}
for dy in offsets:
for dx in offsets:
cxx = px_cx + dx
cyy = px_cy + dy
for mul in size_muls:
size_px = max(16, int(round(base_size_px * mul)))
half = size_px // 2
left = max(0, cxx - half)
top = max(0, cyy - half)
right = min(sw, cxx + half)
bottom = min(sh, cyy + half)
if right - left < 16 or bottom - top < 16:
continue
roi_img = screenshot_img.crop((left, top, right, bottom))
score = _match_score_like_runtime(roi_img, tpl_img)
if score > best["score"]:
best.update(
{
"score": float(score),
"cx": cxx,
"cy": cyy,
"size_px": size_px,
"dx": dx,
"dy": dy,
"mul": float(mul),
}
)
best_base_cx = int(round(best["cx"] / scale_x))
best_base_cy = int(round(best["cy"] / scale_y))
best_base_size = int(
round((best["size_px"] / max(scale_x, scale_y)) / float(action_scale))
)
best_base_size = max(1, best_base_size)
half_base = best_base_size // 2
rx1 = max(0, best_base_cx - half_base)
ry1 = max(0, best_base_cy - half_base)
rx2 = best_base_cx + half_base
ry2 = best_base_cy + half_base
# 保存最佳 ROI
out_path = None
try:
out_dir = os.path.join(ROOT, "pic")
os.makedirs(out_dir, exist_ok=True)
ts = time.strftime("%Y%m%d%H%M%S")
out_path = os.path.join(out_dir, f"roi_best_{label}_{ts}.png")
half = best["size_px"] // 2
left = max(0, best["cx"] - half)
top = max(0, best["cy"] - half)
right = min(sw, best["cx"] + half)
bottom = min(sh, best["cy"] + half)
screenshot_img.crop((left, top, right, bottom)).save(out_path)
except Exception:
out_path = None
print(
f"\n[{label}] best score={best['score']:.6f} dx={best['dx']} dy={best['dy']} mul={best['mul']}"
)
print(
f"[{label}] best pixel center=({best['cx']},{best['cy']}), size_px={best['size_px']}"
)
print(
f"[{label}] recommend base center=({best_base_cx},{best_base_cy}), base_size={best_base_size}"
)
print(f"[{label}] recommend rect: x1={rx1} y1={ry1} x2={rx2} y2={ry2}")
print(
f"[{label}] recommend poly: [[{rx1},{ry1}],[{rx2},{ry1}],[{rx2},{ry2}],[{rx1},{ry2}]]"
)
if out_path:
print(f"[{label}] best ROI saved: {out_path}")
return {
"score": best["score"],
"rect": (rx1, ry1, rx2, ry2),
"poly": [[rx1, ry1], [rx2, ry1], [rx2, ry2], [rx1, ry2]],
"base_center": (best_base_cx, best_base_cy),
"base_size": best_base_size,
}
def main():
ss = get_screenshot_path()
print("Using screenshot:", ss)
if not os.path.exists(ss):
print(
"Screenshot not found at pic/screenshot.png; place a device screenshot there and retry."
)
like_tpl = get_like_template_path()
fav_tpl = get_fav_template_path()
# 默认 polygon(若未从配置读到则回退)
like_poly = [[927, 1161], [1039, 1164], [1049, 1265], [940, 1263]]
fav_poly = [
[938, 1601],
[972, 1597],
[987, 1566],
[1006, 1596],
[1037, 1604],
[1015, 1628],
[1019, 1660],
[989, 1648],
[959, 1661],
[963, 1628],
]
# 尝试从 config/config.json 读取(支持 poly 或 rect),用于验证“运行时真实匹配范围”
try:
import json
cfg_path = os.path.join(ROOT, "config", "config.json")
if os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
if isinstance(cfg.get("yanghao_like_poly"), list) and cfg.get(
"yanghao_like_poly"
):
like_poly = cfg.get("yanghao_like_poly")
else:
rx1 = cfg.get("yanghao_like_rect_x1")
ry1 = cfg.get("yanghao_like_rect_y1")
rx2 = cfg.get("yanghao_like_rect_x2")
ry2 = cfg.get("yanghao_like_rect_y2")
if all(v is not None for v in [rx1, ry1, rx2, ry2]):
like_poly = [
[int(rx1), int(ry1)],
[int(rx2), int(ry1)],
[int(rx2), int(ry2)],
[int(rx1), int(ry2)],
]
if isinstance(cfg.get("yanghao_fav_poly"), list) and cfg.get(
"yanghao_fav_poly"
):
fav_poly = cfg.get("yanghao_fav_poly")
else:
rx1 = cfg.get("yanghao_fav_rect_x1")
ry1 = cfg.get("yanghao_fav_rect_y1")
rx2 = cfg.get("yanghao_fav_rect_x2")
ry2 = cfg.get("yanghao_fav_rect_y2")
if all(v is not None for v in [rx1, ry1, rx2, ry2]):
fav_poly = [
[int(rx1), int(ry1)],
[int(rx2), int(ry1)],
[int(rx2), int(ry2)],
[int(rx1), int(ry2)],
]
except Exception:
pass
print("\nTesting like polygon:")
test_detection_for_polygon(like_poly, like_tpl, "like")
print("\nSearching best like ROI (grid search):")
search_best_roi_for_polygon(like_poly, like_tpl, "like")
print("\nTesting fav polygon:")
test_detection_for_polygon(fav_poly, fav_tpl, "fav")
print("\nSearching best fav ROI (grid search):")
search_best_roi_for_polygon(fav_poly, fav_tpl, "fav")
if __name__ == "__main__":
main()