refactor: 优化代码格式,合并多行赋值为单行,调整异常处理逻辑

This commit is contained in:
Your Name committed 2026-01-04 09:06:55 +08:00
1 parent a61ba62864
commit 9009b15a2b
4 files changed
+495 -147

No files matched your search

+83 -17
View File
@@ -321,7 +321,9 @@ class fudai_analyse:
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
douyin_helpers.HelperFunctions.click(self, x, y)
def swipe(self, start_x: int, start_y: int, end_x: int, end_y: int, duration_ms: int = 300) -> None:
def swipe(
self, start_x: int, start_y: int, end_x: int, end_y: int, duration_ms: int = 300
) -> None:
"""兼容原版 fudai_analyse.swipe:转发到底层 operation.swipe。
参数使用像素坐标,duration_ms 为滑动持续时间(毫秒)。
@@ -329,7 +331,9 @@ class fudai_analyse:
try:
# 首选底层 operation 的 swipe 实现
try:
self.operation.swipe(self.device_id, start_x, start_y, end_x, end_y, duration_ms)
self.operation.swipe(
self.device_id, start_x, start_y, end_x, end_y, duration_ms
)
return
except Exception:
pass
@@ -339,7 +343,13 @@ class fudai_analyse:
from douyin.handlers import douyin_swipe_ops
ok = douyin_swipe_ops._adb_swipe_direct(
getattr(self, "device_id", ""), start_x, start_y, end_x, end_y, duration_ms, self.operation
getattr(self, "device_id", ""),
start_x,
start_y,
end_x,
end_y,
duration_ms,
self.operation,
)
if ok:
return
@@ -348,12 +358,28 @@ class fudai_analyse:
# 最后兜底:记录滑动失败
try:
self._log_kv("滑动", "swipe 失败 - 无可用实现", start_x=start_x, start_y=start_y, end_x=end_x, end_y=end_y, duration_ms=duration_ms)
self._log_kv(
"滑动",
"swipe 失败 - 无可用实现",
start_x=start_x,
start_y=start_y,
end_x=end_x,
end_y=end_y,
duration_ms=duration_ms,
)
except Exception:
pass
except Exception:
try:
self._log_kv("滑动", "swipe 异常", start_x=start_x, start_y=start_y, end_x=end_x, end_y=end_y, duration_ms=duration_ms)
self._log_kv(
"滑动",
"swipe 异常",
start_x=start_x,
start_y=start_y,
end_x=end_x,
end_y=end_y,
duration_ms=duration_ms,
)
except Exception:
pass
@@ -764,7 +790,11 @@ class fudai_analyse:
pass
with open(pic_path, "rb") as f:
data2 = f.read()
if data2 and data2.startswith(b"\x89PNG") and b"IEND" in data2[-512:]:
if (
data2
and data2.startswith(b"\x89PNG")
and b"IEND" in data2[-512:]
):
try:
img = Image.open(io.BytesIO(data2))
img.load()
@@ -785,18 +815,29 @@ class fudai_analyse:
# 保存到 pic 目录,使用 label 区分
out_dir = path_config.get_pic_dir()
os.makedirs(out_dir, exist_ok=True)
fname = f"roi_{label}_{getattr(self, '_run_id', 'run')}_{int(time.time())}.png"
fname = (
f"roi_{label}_{getattr(self, '_run_id', 'run')}_{int(time.time())}.png"
)
out_path = os.path.join(out_dir, fname)
roi.save(out_path)
return out_path
except Exception:
try:
self._log_kv("截图", "_capture_roi_screenshot 失败", label=label, sx=sx, sy=sy, size=size)
self._log_kv(
"截图",
"_capture_roi_screenshot 失败",
label=label,
sx=sx,
sy=sy,
size=size,
)
except Exception:
pass
return ""
def _match_icon_template(self, roi_path: str, template_path: str, threshold: float | None = None) -> Tuple[bool, float]:
def _match_icon_template(
self, roi_path: str, template_path: str, threshold: float | None = None
) -> Tuple[bool, float]:
"""对比 ROI 与模板,返回 (detected: bool, score: float)。
使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。
@@ -830,7 +871,10 @@ class fudai_analyse:
tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32)
# 若模板尺寸等于 ROI,则直接计算相关系数
if roi_gray.shape[0] == tpl_gray.shape[0] and roi_gray.shape[1] == tpl_gray.shape[1]:
if (
roi_gray.shape[0] == tpl_gray.shape[0]
and roi_gray.shape[1] == tpl_gray.shape[1]
):
A = roi_gray.flatten()
B = tpl_gray.flatten()
else:
@@ -849,14 +893,21 @@ class fudai_analyse:
b = tpl_gray.flatten()
a = a - a.mean()
b = b - b.mean()
denom = (np.linalg.norm(a) * np.linalg.norm(b))
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom > 1e-6:
score = float(np.dot(a, b) / denom)
else:
score = -1.0
# 若中心裁剪得分足够好则直接返回
if score >= 0.55:
used_thr = float(threshold) if threshold is not None else float(getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70)
used_thr = (
float(threshold)
if threshold is not None
else float(
getattr(self, "yanghao_icon_match_threshold", 0.70)
or 0.70
)
)
detected = score >= used_thr
return bool(detected), float(score)
@@ -873,7 +924,7 @@ class fudai_analyse:
b = tpl_gray.flatten()
a = a - a.mean()
b = b - b.mean()
denom = (np.linalg.norm(a) * np.linalg.norm(b))
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom <= 1e-6:
continue
score = float(np.dot(a, b) / denom)
@@ -882,7 +933,13 @@ class fudai_analyse:
if best < -0.5:
return False, 0.0
score = float(best)
used_thr = float(threshold) if threshold is not None else float(getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70)
used_thr = (
float(threshold)
if threshold is not None
else float(
getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70
)
)
detected = score >= used_thr
return bool(detected), float(score)
@@ -891,16 +948,25 @@ class fudai_analyse:
B = tpl_gray.flatten()
A = A - A.mean()
B = B - B.mean()
denom = (np.linalg.norm(A) * np.linalg.norm(B))
denom = np.linalg.norm(A) * np.linalg.norm(B)
if denom <= 1e-6:
return False, 0.0
score = float(np.dot(A, B) / denom)
used_thr = float(threshold) if threshold is not None else float(getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70)
used_thr = (
float(threshold)
if threshold is not None
else float(getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70)
)
detected = score >= used_thr
return bool(detected), float(score)
except Exception:
try:
self._log_kv("检测", "_match_icon_template 异常", roi_path=roi_path, template_path=template_path)
self._log_kv(
"检测",
"_match_icon_template 异常",
roi_path=roi_path,
template_path=template_path,
)
except Exception:
pass
return False, 0.0
+339 -98
View File
@@ -22,7 +22,9 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
def _step_shot(label: str) -> None:
# 环境变量优先:YANGHAO_STEP_SCREENSHOT=1
try:
env_on = bool(str(os.environ.get("YANGHAO_STEP_SCREENSHOT", "")).strip())
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)):
@@ -31,14 +33,22 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
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)
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":
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)
@@ -47,7 +57,11 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
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))
print(
"[养号] 动作: 下滑/切换 direction={} dist={}px".format(
getattr(analyser, "yanghao_after_dwell_swipe_direction", "up"), dist
)
)
_step_shot("after_swipe")
# 标记:下滑后下一轮截图/检测前需要随机等待,避免动画未结束影响识别
need_settle_after_swipe = True
@@ -66,7 +80,9 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
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]:
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:
# 下滑后:先随机等一下,再进行截图与模板匹配
@@ -83,7 +99,10 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
else:
# 尝试相对于 config 路径的仓库根解析(保证 assets/ 在不同 cwd 下也能被找到)
try:
cfg = getattr(analyser, "config_path", "config/config.json") or "config/config.json"
cfg = (
getattr(analyser, "config_path", "config/config.json")
or "config/config.json"
)
cfg_abspath = os.path.abspath(cfg)
project_root = os.path.dirname(os.path.dirname(cfg_abspath))
candidate = os.path.join(project_root, tpl)
@@ -95,7 +114,9 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
except Exception:
tpl_exists = False
print(f"[养号][DEBUG] _detect_icon action={action} template_path='{template_path}' tpl_exists={tpl_exists}")
print(
f"[养号][DEBUG] _detect_icon action={action} template_path='{template_path}' tpl_exists={tpl_exists}"
)
if int(base_x or 0) <= 0 or int(base_y or 0) <= 0:
if tpl_exists:
try:
@@ -124,8 +145,16 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
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)
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 大小,优先使用专用配置,否则回退到通用配置
@@ -158,6 +187,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
if len(pts) >= 1:
xs = [int(p[0]) for p in pts]
ys = [int(p[1]) for p in pts]
# 计算多边形质心(面积加权),若顶点过少回退到顶点平均
def _poly_centroid(pts_list):
if len(pts_list) < 3:
@@ -190,27 +220,49 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
w = x2 - x1
h = y2 - y1
size = max(1, int(max(w, h)))
sx, sy = analyser._scale_from_base(int(base_cx), int(base_cy))
sx, sy = analyser._scale_from_base(
int(base_cx), int(base_cy)
)
try:
scale_x = float(getattr(analyser, "resolution_ratio_x", 1080)) / 1080.0
scale_y = float(getattr(analyser, "resolution_ratio_y", 2400)) / 2400.0
scale_x = (
float(getattr(analyser, "resolution_ratio_x", 1080))
/ 1080.0
)
scale_y = (
float(getattr(analyser, "resolution_ratio_y", 2400))
/ 2400.0
)
except Exception:
scale_x = scale_y = 1.0
try:
if action == "爱心":
action_scale = float(getattr(analyser, "yanghao_like_roi_scale", 1.5))
action_scale = float(
getattr(analyser, "yanghao_like_roi_scale", 1.5)
)
elif action == "收藏":
action_scale = float(getattr(analyser, "yanghao_fav_roi_scale", 1.5))
action_scale = float(
getattr(analyser, "yanghao_fav_roi_scale", 1.5)
)
else:
action_scale = 1.0
except Exception:
action_scale = 1.5
size_px = max(1, int(size * max(scale_x, scale_y) * float(action_scale)))
roi_path = analyser._capture_roi_screenshot(roi_label, sx, sy, int(size_px))
size_px = max(
1,
int(size * max(scale_x, scale_y) * float(action_scale)),
)
roi_path = analyser._capture_roi_screenshot(
roi_label, sx, sy, int(size_px)
)
rect_used = True
except Exception:
rect_used = False
elif rx1 is not None and ry1 is not None and rx2 is not None and ry2 is not None:
elif (
rx1 is not None
and ry1 is not None
and rx2 is not None
and ry2 is not None
):
try:
# 允许任意顺序的点,取 min/max
x1 = int(min(int(rx1), int(rx2)))
@@ -224,21 +276,35 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
size = max(1, int(max(w, h)))
sx, sy = analyser._scale_from_base(int(base_cx), int(base_cy))
try:
scale_x = float(getattr(analyser, "resolution_ratio_x", 1080)) / 1080.0
scale_y = float(getattr(analyser, "resolution_ratio_y", 2400)) / 2400.0
scale_x = (
float(getattr(analyser, "resolution_ratio_x", 1080))
/ 1080.0
)
scale_y = (
float(getattr(analyser, "resolution_ratio_y", 2400))
/ 2400.0
)
except Exception:
scale_x = scale_y = 1.0
try:
if action == "爱心":
action_scale = float(getattr(analyser, "yanghao_like_roi_scale", 1.5))
action_scale = float(
getattr(analyser, "yanghao_like_roi_scale", 1.5)
)
elif action == "收藏":
action_scale = float(getattr(analyser, "yanghao_fav_roi_scale", 1.5))
action_scale = float(
getattr(analyser, "yanghao_fav_roi_scale", 1.5)
)
else:
action_scale = 1.0
except Exception:
action_scale = 1.5
size_px = max(1, int(size * max(scale_x, scale_y) * float(action_scale)))
roi_path = analyser._capture_roi_screenshot(roi_label, sx, sy, int(size_px))
size_px = max(
1, int(size * max(scale_x, scale_y) * float(action_scale))
)
roi_path = analyser._capture_roi_screenshot(
roi_label, sx, sy, int(size_px)
)
rect_used = True
except Exception:
rect_used = False
@@ -246,48 +312,90 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
if not rect_used:
try:
if action == "爱心":
roi_size = int(getattr(analyser, "yanghao_like_icon_roi_size", None) or getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
roi_size = int(
getattr(analyser, "yanghao_like_icon_roi_size", None)
or getattr(analyser, "yanghao_icon_roi_size", 180)
or 180
)
elif action == "收藏":
roi_size = int(getattr(analyser, "yanghao_fav_icon_roi_size", None) or getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
roi_size = int(
getattr(analyser, "yanghao_fav_icon_roi_size", None)
or getattr(analyser, "yanghao_icon_roi_size", 180)
or 180
)
else:
roi_size = int(getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
roi_size = int(
getattr(analyser, "yanghao_icon_roi_size", 180) or 180
)
except Exception:
roi_size = int(getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
roi_size = int(
getattr(analyser, "yanghao_icon_roi_size", 180) or 180
)
try:
scale_x = float(getattr(analyser, "resolution_ratio_x", 1080)) / 1080.0
scale_y = float(getattr(analyser, "resolution_ratio_y", 2400)) / 2400.0
scale_x = (
float(getattr(analyser, "resolution_ratio_x", 1080))
/ 1080.0
)
scale_y = (
float(getattr(analyser, "resolution_ratio_y", 2400))
/ 2400.0
)
except Exception:
scale_x = scale_y = 1.0
try:
if action == "爱心":
action_scale = float(getattr(analyser, "yanghao_like_roi_scale", 1.5))
action_scale = float(
getattr(analyser, "yanghao_like_roi_scale", 1.5)
)
elif action == "收藏":
action_scale = float(getattr(analyser, "yanghao_fav_roi_scale", 1.5))
action_scale = float(
getattr(analyser, "yanghao_fav_roi_scale", 1.5)
)
else:
action_scale = 1.0
except Exception:
action_scale = 1.5
roi_px = max(1, int(roi_size * max(scale_x, scale_y) * float(action_scale)))
roi_path = analyser._capture_roi_screenshot(roi_label, sx, sy, int(roi_px))
roi_px = max(
1, int(roi_size * max(scale_x, scale_y) * float(action_scale))
)
roi_path = analyser._capture_roi_screenshot(
roi_label, sx, sy, int(roi_px)
)
except Exception:
try:
default_size = int(getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
scale_x = float(getattr(analyser, "resolution_ratio_x", 1080)) / 1080.0
scale_y = float(getattr(analyser, "resolution_ratio_y", 2400)) / 2400.0
default_size = int(
getattr(analyser, "yanghao_icon_roi_size", 180) or 180
)
scale_x = (
float(getattr(analyser, "resolution_ratio_x", 1080)) / 1080.0
)
scale_y = (
float(getattr(analyser, "resolution_ratio_y", 2400)) / 2400.0
)
except Exception:
scale_x = scale_y = 1.0
default_size = int(getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
default_size = int(
getattr(analyser, "yanghao_icon_roi_size", 180) or 180
)
try:
if action == "爱心":
action_scale = float(getattr(analyser, "yanghao_like_roi_scale", 1.5))
action_scale = float(
getattr(analyser, "yanghao_like_roi_scale", 1.5)
)
elif action == "收藏":
action_scale = float(getattr(analyser, "yanghao_fav_roi_scale", 1.5))
action_scale = float(
getattr(analyser, "yanghao_fav_roi_scale", 1.5)
)
else:
action_scale = 1.0
except Exception:
action_scale = 1.5
roi_px = max(1, int(default_size * max(scale_x, scale_y) * float(action_scale)))
roi_path = analyser._capture_roi_screenshot(roi_label, sx, sy, int(roi_px))
roi_px = max(
1, int(default_size * max(scale_x, scale_y) * float(action_scale))
)
roi_path = analyser._capture_roi_screenshot(
roi_label, sx, sy, int(roi_px)
)
if not template_path or not os.path.exists(template_path):
print(f"[养号] 检测: {action} -> 失败(缺少模板文件:{template_path})")
return False, 0.0
@@ -299,12 +407,18 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
else:
thr = None
if thr is None:
detected, score = analyser._match_icon_template(roi_path, template_path)
detected, score = analyser._match_icon_template(
roi_path, template_path
)
else:
detected, score = analyser._match_icon_template(roi_path, template_path, float(thr))
detected, score = analyser._match_icon_template(
roi_path, template_path, float(thr)
)
except Exception:
detected, score = analyser._match_icon_template(roi_path, template_path)
print(f"[养号] 检测: {action} -> {'检测到' if detected else '未检测到'}(score={score:.3f})")
print(
f"[养号] 检测: {action} -> {'检测到' if detected else '未检测到'}(score={score:.3f})"
)
return detected, score
# 当已配置坐标或已提供模板文件时,启用图标检测
@@ -318,7 +432,10 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
return True, tpl
# 尝试相对于 config 路径的仓库根解析
try:
cfg = getattr(analyser, "config_path", "config/config.json") or "config/config.json"
cfg = (
getattr(analyser, "config_path", "config/config.json")
or "config/config.json"
)
cfg_abspath = os.path.abspath(cfg)
project_root = os.path.dirname(os.path.dirname(cfg_abspath))
candidate = os.path.join(project_root, tpl)
@@ -331,17 +448,26 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
return False, tpl_path
try:
like_tpl = str(getattr(analyser, "yanghao_like_template_path", "") or "").strip()
fav_tpl = str(getattr(analyser, "yanghao_fav_template_path", "") or "").strip()
like_tpl = str(
getattr(analyser, "yanghao_like_template_path", "") or ""
).strip()
fav_tpl = str(
getattr(analyser, "yanghao_fav_template_path", "") or ""
).strip()
like_tpl_exists, like_tpl = _tpl_exists_check(like_tpl)
fav_tpl_exists, fav_tpl = _tpl_exists_check(fav_tpl)
try:
cfg = getattr(analyser, "config_path", "config/config.json") or "config/config.json"
cfg = (
getattr(analyser, "config_path", "config/config.json")
or "config/config.json"
)
cfg_abspath = os.path.abspath(cfg)
project_root = os.path.dirname(os.path.dirname(cfg_abspath))
except Exception:
project_root = None
print(f"[养号][DEBUG] like_tpl='{like_tpl}' exists={like_tpl_exists}; fav_tpl='{fav_tpl}' exists={fav_tpl_exists}; project_root={project_root}")
print(
f"[养号][DEBUG] like_tpl='{like_tpl}' exists={like_tpl_exists}; fav_tpl='{fav_tpl}' exists={fav_tpl_exists}; project_root={project_root}"
)
# 如果解析得到的绝对路径不同,更新属性以便后续使用
if like_tpl_exists:
try:
@@ -358,14 +484,11 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
fav_tpl_exists = False
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
)
or (like_tpl_exists and fav_tpl_exists)
)
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
) or (like_tpl_exists and fav_tpl_exists)
start_ts = time.time()
last_desktop_check_ts = 0.0
@@ -393,18 +516,33 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
# 每次循环尝试按概率执行点赞/收藏/下滑
try:
# 尝试点赞(使用配置坐标作为兜底)
like_prob = float(getattr(analyser, "yanghao_like_prob", 0) or 0)
like_prob = float(
getattr(analyser, "yanghao_like_prob", 0) or 0
)
fav_prob = float(getattr(analyser, "yanghao_fav_prob", 0) or 0)
# 随机触发动作
r = random.random()
if r < like_prob and int(getattr(analyser, "yanghao_like_icon_x", 0) or 0) > 0:
if (
r < like_prob
and int(getattr(analyser, "yanghao_like_icon_x", 0) or 0)
> 0
):
_step_shot("before_like_click_fallback")
_scaled_click(int(getattr(analyser, "yanghao_like_icon_x", 0) or 0), int(getattr(analyser, "yanghao_like_icon_y", 0) or 0))
_scaled_click(
int(getattr(analyser, "yanghao_like_icon_x", 0) or 0),
int(getattr(analyser, "yanghao_like_icon_y", 0) or 0),
)
_step_shot("after_like_click_fallback")
print("[养号] 退化动作: 点爱心(坐标兜底)")
elif r < like_prob + fav_prob and int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0) > 0:
elif (
r < like_prob + fav_prob
and int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0) > 0
):
_step_shot("before_fav_click_fallback")
_scaled_click(int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0), int(getattr(analyser, "yanghao_fav_icon_y", 0) or 0))
_scaled_click(
int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0),
int(getattr(analyser, "yanghao_fav_icon_y", 0) or 0),
)
_step_shot("after_fav_click_fallback")
print("[养号] 退化动作: 点收藏(坐标兜底)")
else:
@@ -449,18 +587,29 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
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)
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))
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))
_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))
_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;否则走剪贴板/兜底)
@@ -470,19 +619,29 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
)
prev_ime = ""
try:
ok_ime, prev_ime, _adb_ime = analyser.operation.ensure_adbkeyboard_ime(analyser.device_id)
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)
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))
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")
@@ -494,40 +653,81 @@ def yanghao_idle(analyser, total_seconds: int) -> None:
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))
_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)
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)))
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):
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))
_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)))
print(
"[养号] 动作: 点爱心(prob={})".format(
getattr(analyser, "yanghao_like_prob", 0)
)
)
else:
print("[养号] 动作: 跳过点爱心(prob={})".format(getattr(analyser, "yanghao_like_prob", 0)))
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):
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))
_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)))
print(
"[养号] 动作: 点收藏(prob={})".format(
getattr(analyser, "yanghao_fav_prob", 0)
)
)
else:
print("[养号] 动作: 跳过点收藏(prob={})".format(getattr(analyser, "yanghao_fav_prob", 0)))
print(
"[养号] 动作: 跳过点收藏(prob={})".format(
getattr(analyser, "yanghao_fav_prob", 0)
)
)
# 停留
analyser.operation.delay(dwell)
@@ -584,7 +784,9 @@ def yanghao_try_tap_text_or_fallback(
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)
ok = analyser.operation.tap_by_text(
analyser.device_id, text, contains=contains, timeout_seconds=tap_timeout
)
except Exception:
ok = False
if ok:
@@ -644,12 +846,19 @@ def yanghao_check_and_recover_from_desktop(analyser) -> bool:
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):
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))
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)
@@ -692,7 +901,11 @@ def yanghao_recommend_flow(analyser, total_seconds: int) -> None:
try:
print("[养号] 推荐页流程:退出直播→推荐→养号→直播→进入直播间")
capture_steps = str(os.environ.get("YANGHAO_STEP_SCREENSHOT", "")).strip() in ("1", "true", "True")
capture_steps = str(os.environ.get("YANGHAO_STEP_SCREENSHOT", "")).strip() in (
"1",
"true",
"True",
)
if capture_steps:
analyser._save_step_screenshot("start")
@@ -749,7 +962,9 @@ def yanghao_wait(analyser, total_seconds: int) -> None:
if not bool(getattr(analyser, "yanghao_enabled", True)):
# 用户要求:关闭养号后不要再等待太久,而是继续执行主流程
print(f"[养号] yanghao_enabled=0:跳过推荐页养号(不再等待 {int(total_seconds)}s,快速继续)")
print(
f"[养号] yanghao_enabled=0:跳过推荐页养号(不再等待 {int(total_seconds)}s,快速继续)"
)
try:
analyser.operation.delay(1)
except Exception:
@@ -760,16 +975,23 @@ def yanghao_wait(analyser, total_seconds: int) -> None:
try:
# 如果启用了高价值预约且存在未完成的预约,则在开始养号前等待预约完成
try:
high_value_enabled = bool(getattr(analyser, "high_value_fudai_enabled", False))
high_value_enabled = bool(
getattr(analyser, "high_value_fudai_enabled", False)
)
except Exception:
high_value_enabled = False
if high_value_enabled:
try:
has_reservations = bool(getattr(analyser, "reservations", None) and len(getattr(analyser, "reservations", [])) > 0)
has_reservations = bool(
getattr(analyser, "reservations", None)
and len(getattr(analyser, "reservations", [])) > 0
)
except Exception:
has_reservations = False
try:
after_pending = bool(getattr(analyser, "reservation_after_action_pending", False))
after_pending = bool(
getattr(analyser, "reservation_after_action_pending", False)
)
except Exception:
after_pending = False
@@ -778,7 +1000,11 @@ def yanghao_wait(analyser, total_seconds: int) -> None:
analyser._log_kv(
"养号",
"检测到未完成的预约,养号将等待预约完成后再开始",
reservations_count=(len(getattr(analyser, "reservations", [])) if getattr(analyser, "reservations", None) else 0),
reservations_count=(
len(getattr(analyser, "reservations", []))
if getattr(analyser, "reservations", None)
else 0
),
reservation_after_action_pending=after_pending,
)
except Exception:
@@ -789,8 +1015,13 @@ def yanghao_wait(analyser, total_seconds: int) -> None:
waited = 0
while True:
try:
still_has = bool(getattr(analyser, "reservations", None) and len(getattr(analyser, "reservations", [])) > 0)
still_pending = bool(getattr(analyser, "reservation_after_action_pending", False))
still_has = bool(
getattr(analyser, "reservations", None)
and len(getattr(analyser, "reservations", [])) > 0
)
still_pending = bool(
getattr(analyser, "reservation_after_action_pending", False)
)
if not still_has and not still_pending:
break
except Exception:
@@ -808,8 +1039,14 @@ def yanghao_wait(analyser, total_seconds: int) -> None:
"养号",
"预约已完成,开始养号",
waited_seconds=waited,
reservations_count=(len(getattr(analyser, "reservations", [])) if getattr(analyser, "reservations", None) else 0),
reservation_after_action_pending=bool(getattr(analyser, "reservation_after_action_pending", False)),
reservations_count=(
len(getattr(analyser, "reservations", []))
if getattr(analyser, "reservations", None)
else 0
),
reservation_after_action_pending=bool(
getattr(analyser, "reservation_after_action_pending", False)
),
)
except Exception:
print(f"[养号] 预约已完成,等待了{waited}s,开始养号")
@@ -821,7 +1058,9 @@ def yanghao_wait(analyser, total_seconds: int) -> None:
dt = now - last_ts
if dt < interval:
remain = int(interval - dt)
print(f"[养号] 推荐页养号冷却中,剩余 {remain}s,跳过本次(改为等待 {int(total_seconds)}s)")
print(
f"[养号] 推荐页养号冷却中,剩余 {remain}s,跳过本次(改为等待 {int(total_seconds)}s)"
)
analyser.operation.delay(int(max(1, total_seconds)))
return
analyser._yanghao_last_recommend_ts = time.time()
@@ -854,7 +1093,11 @@ def maybe_reset_after_swipes(analyser, needswitch: bool, swipe_times: int) -> in
if swipe_times < threshold:
return swipe_times
print("已切换直播间{}次,达到阈值{}:下滑回退到第一个直播间".format(swipe_times, threshold))
print(
"已切换直播间{}次,达到阈值{}:下滑回退到第一个直播间".format(
swipe_times, threshold
)
)
# 回退次数按当前已切换次数来(更符合“回到本轮第一个直播间”的语义)
back_times = int(swipe_times)
if back_times <= 0:
@@ -862,9 +1105,7 @@ def maybe_reset_after_swipes(analyser, needswitch: bool, swipe_times: int) -> in
# 下滑回退:与上划切换相反方向
# 使用配置的滑动持续时间,如果没有配置则使用300ms(比之前的200ms更快)
swipe_duration_ms = int(
getattr(analyser, "swipe_duration_ms", 300) or 300
)
swipe_duration_ms = int(getattr(analyser, "swipe_duration_ms", 300) or 300)
for i in range(back_times):
analyser.swipe(760, 800, 760, 1600, swipe_duration_ms)
print("回退直播间 {}/{}".format(i + 1, back_times))
+34 -12
View File
@@ -305,13 +305,17 @@ class ConfigManager:
# 模板路径(点赞/收藏)
if "yanghao_like_template_path" in config:
try:
analyser.yanghao_like_template_path = str(config["yanghao_like_template_path"] or "")
analyser.yanghao_like_template_path = str(
config["yanghao_like_template_path"] or ""
)
except Exception:
pass
if "yanghao_fav_template_path" in config:
try:
analyser.yanghao_fav_template_path = str(config["yanghao_fav_template_path"] or "")
analyser.yanghao_fav_template_path = str(
config["yanghao_fav_template_path"] or ""
)
except Exception:
pass
@@ -352,42 +356,59 @@ class ConfigManager:
# per-action ROI scale multipliers (用于扩大检测范围)
if "yanghao_like_roi_scale" in config:
try:
analyser.yanghao_like_roi_scale = float(config["yanghao_like_roi_scale"] or 1.5)
analyser.yanghao_like_roi_scale = float(
config["yanghao_like_roi_scale"] or 1.5
)
except Exception:
analyser.yanghao_like_roi_scale = 1.5
else:
analyser.yanghao_like_roi_scale = getattr(analyser, "yanghao_like_roi_scale", 1.5)
analyser.yanghao_like_roi_scale = getattr(
analyser, "yanghao_like_roi_scale", 1.5
)
if "yanghao_fav_roi_scale" in config:
try:
analyser.yanghao_fav_roi_scale = float(config["yanghao_fav_roi_scale"] or 1.5)
analyser.yanghao_fav_roi_scale = float(
config["yanghao_fav_roi_scale"] or 1.5
)
except Exception:
analyser.yanghao_fav_roi_scale = 1.5
else:
analyser.yanghao_fav_roi_scale = getattr(analyser, "yanghao_fav_roi_scale", 1.5)
analyser.yanghao_fav_roi_scale = getattr(
analyser, "yanghao_fav_roi_scale", 1.5
)
# per-action match thresholds (可在 config 中单独设置)
if "yanghao_like_icon_match_threshold" in config:
try:
analyser.yanghao_like_icon_match_threshold = float(config["yanghao_like_icon_match_threshold"])
analyser.yanghao_like_icon_match_threshold = float(
config["yanghao_like_icon_match_threshold"]
)
except Exception:
analyser.yanghao_like_icon_match_threshold = None
else:
analyser.yanghao_like_icon_match_threshold = getattr(analyser, "yanghao_like_icon_match_threshold", None)
analyser.yanghao_like_icon_match_threshold = getattr(
analyser, "yanghao_like_icon_match_threshold", None
)
if "yanghao_fav_icon_match_threshold" in config:
try:
analyser.yanghao_fav_icon_match_threshold = float(config["yanghao_fav_icon_match_threshold"])
analyser.yanghao_fav_icon_match_threshold = float(
config["yanghao_fav_icon_match_threshold"]
)
except Exception:
analyser.yanghao_fav_icon_match_threshold = None
else:
analyser.yanghao_fav_icon_match_threshold = getattr(analyser, "yanghao_fav_icon_match_threshold", None)
analyser.yanghao_fav_icon_match_threshold = getattr(
analyser, "yanghao_fav_icon_match_threshold", None
)
# per-action ROI sizes
if "yanghao_like_icon_roi_size" in config:
try:
analyser.yanghao_like_icon_roi_size = int(
config["yanghao_like_icon_roi_size"] or analyser.yanghao_icon_roi_size
config["yanghao_like_icon_roi_size"]
or analyser.yanghao_icon_roi_size
)
except Exception:
analyser.yanghao_like_icon_roi_size = analyser.yanghao_icon_roi_size
@@ -395,7 +416,8 @@ class ConfigManager:
if "yanghao_fav_icon_roi_size" in config:
try:
analyser.yanghao_fav_icon_roi_size = int(
config["yanghao_fav_icon_roi_size"] or analyser.yanghao_icon_roi_size
config["yanghao_fav_icon_roi_size"]
or analyser.yanghao_icon_roi_size
)
except Exception:
analyser.yanghao_fav_icon_roi_size = analyser.yanghao_icon_roi_size
+39 -20
View File
@@ -3,16 +3,20 @@ import sys
from pprint import pprint
# Ensure project root is on sys.path
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
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
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)
print("Failed to import fudai_analyse:", e)
sys.exit(2)
@@ -35,28 +39,30 @@ def test_detection_for_polygon(poly, tpl_path, label):
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)
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
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))
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))
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})")
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)
print("roi saved to:", roi)
if not roi or not os.path.exists(roi):
print('ROI not available, abort')
print("ROI not available, abort")
return
detected, score = a._match_icon_template(roi, tpl_path)
@@ -65,22 +71,35 @@ def test_detection_for_polygon(poly, tpl_path, label):
def main():
ss = get_screenshot_path()
print('Using screenshot:', ss)
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.')
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 from config
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]]
fav_poly = [
[938, 1601],
[972, 1597],
[987, 1566],
[1006, 1596],
[1037, 1604],
[1015, 1628],
[1019, 1660],
[989, 1648],
[959, 1661],
[963, 1628],
]
print('\nTesting like polygon:')
test_detection_for_polygon(like_poly, like_tpl, 'like')
print("\nTesting like polygon:")
test_detection_for_polygon(like_poly, like_tpl, "like")
print('\nTesting fav polygon:')
test_detection_for_polygon(fav_poly, fav_tpl, 'fav')
print("\nTesting fav polygon:")
test_detection_for_polygon(fav_poly, fav_tpl, "fav")
if __name__ == '__main__':
if __name__ == "__main__":
main()