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

-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()