From 6121154370453ceabf38f832dc97eee1bb187a34 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 4 Jan 2026 16:27:19 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=9B=B4=E6=96=B0=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E8=B7=AF=E5=BE=84=EF=BC=8C=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E7=AE=A1=E7=90=86=E9=80=BB=E8=BE=91=EF=BC=8C?= =?UTF-8?q?=E5=A2=9E=E5=BC=BA=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E7=9A=84?= =?UTF-8?q?=E5=85=BC=E5=AE=B9=E6=80=A7=E5=92=8C=E5=8F=AF=E8=AF=BB=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- ...ig.json => config.json.bak_20260104_161454 | 0 config/README.md | 4 +- config/config.json | 21 +- douyin/other/douyin_yanghao.py | 17 +- douyin/utils/douyin_config.py | 21 ++ gui/gui_core.py | 16 +- gui/web_gui.py | 16 +- tools/_dump_lines.py | 6 + tools/test_yanghao_detection.py | 234 +++++++++++++++++- 10 files changed, 327 insertions(+), 12 deletions(-) rename config.json => config.json.bak_20260104_161454 (100%) create mode 100644 tools/_dump_lines.py diff --git a/README.md b/README.md index 69e0b16..c57beea 100644 --- a/README.md +++ b/README.md @@ -534,7 +534,7 @@ python run_cli.py \ ## ⚙️ 详细配置说明 -所有配置保存在 `config.json` 文件中,可通过 GUI 界面修改,也可以直接编辑 JSON 文件。 +所有配置保存在 `config/config.json` 文件中(运行时通过 `path_config.get_config_path()` 读取),可通过 GUI 界面修改,也可以直接编辑 JSON 文件。 ### 运行设置 @@ -1073,7 +1073,7 @@ douyin_guaji-main/ ### 配置文件 -#### `config.json` +#### `config/config.json` - **职责**:所有配置参数 - **格式**:JSON - **说明**:详见"详细配置说明"章节 diff --git a/config.json b/config.json.bak_20260104_161454 similarity index 100% rename from config.json rename to config.json.bak_20260104_161454 diff --git a/config/README.md b/config/README.md index 18481f0..7a94bec 100644 --- a/config/README.md +++ b/config/README.md @@ -4,13 +4,13 @@ ## 配置文件列表 -- **config.json** - 主配置文件,包含所有运行时配置参数 +- **config.json** - 主配置文件(唯一配置入口),包含所有运行时配置参数 - **pyrightconfig.json** - Pyright类型检查器配置 - **pytest.ini** - pytest测试框架配置 ## 注意事项 -- `config.json` 是运行时配置文件,会被程序读取和修改 +- `config/config.json` 是运行时配置文件,会被程序读取和修改 - 建议在修改配置前备份原文件 - 配置文件使用 UTF-8 编码 diff --git a/config/config.json b/config/config.json index 34997f9..f727481 100644 --- a/config/config.json +++ b/config/config.json @@ -49,6 +49,14 @@ "yanghao_like_roi_offset_y": -50, "yanghao_fav_roi_offset_x": 40, "yanghao_fav_roi_offset_y": 0, + "yanghao_like_rect_x1": 795, + "yanghao_like_rect_y1": 1008, + "yanghao_like_rect_x2": 1013, + "yanghao_like_rect_y2": 1226, + "yanghao_fav_rect_x1": 903, + "yanghao_fav_rect_y1": 1469, + "yanghao_fav_rect_x2": 1119, + "yanghao_fav_rect_y2": 1685, "contains_want": [], "contains_not_want": [ "首饰盒", @@ -165,7 +173,15 @@ "system", "user_action" ] - } + }, + "compress_logs": true, + "max_total_size_gb": 10.0, + "compress_after_days": 7, + "max_bytes": 104857600, + "backup_count": 10, + "enable_monitor": true, + "monitor_warning_mb": 500.0, + "monitor_critical_mb": 2000.0 }, "debug_captures": { "enabled": false, @@ -190,5 +206,6 @@ "fansclub_manual_wait_seconds": 3.0, "enable_streaming_screenshot": false, "fudai_exit_after_misses": 30, - "yanghao_only": true + "yanghao_only": true, + "record_room_title_mapping_enabled": true } diff --git a/douyin/other/douyin_yanghao.py b/douyin/other/douyin_yanghao.py index 5380d09..da8543e 100644 --- a/douyin/other/douyin_yanghao.py +++ b/douyin/other/douyin_yanghao.py @@ -900,6 +900,12 @@ def yanghao_recommend_flow(analyser, total_seconds: int) -> None: 如果识别不到文字,会使用坐标兜底;兜底仍失败时就退化成原地养号(不阻塞主流程)。 """ + # 养号属于长循环场景:为避免“修改 config 后不生效”,进入推荐页养号时热加载一次配置。 + try: + if hasattr(analyser, "load_config"): + analyser.load_config() + except Exception: + pass try: print("[养号] 推荐页流程:退出直播→推荐→养号→直播→进入直播间") @@ -967,9 +973,14 @@ def yanghao_wait(analyser, total_seconds: int) -> None: print( f"[养号] yanghao_enabled=0:跳过推荐页养号(不再等待 {int(total_seconds)}s,快速继续)" ) - try: - analyser.operation.delay(1) - except Exception: + try: + debug_on = bool(str(os.environ.get("YANGHAO_DEBUG", "")).strip()) + except Exception: + debug_on = False + if debug_on: + print( + f"[养号][DEBUG] like_tpl='{like_tpl}' exists={like_tpl_exists}; fav_tpl='{fav_tpl}' exists={fav_tpl_exists}; project_root={project_root}" + ) pass return diff --git a/douyin/utils/douyin_config.py b/douyin/utils/douyin_config.py index d47e2d3..88d8154 100644 --- a/douyin/utils/douyin_config.py +++ b/douyin/utils/douyin_config.py @@ -23,6 +23,7 @@ class ConfigManager: analyser: fudai_analyse 实例 config_path: 配置文件路径,如果为 None 则使用 analyser.config_path """ + passed_in_config_path = config_path is not None if config_path is None: try: import path_config @@ -34,6 +35,26 @@ class ConfigManager: default_config_path = path_config.get_config_path() config_path = getattr(analyser, "config_path", default_config_path) + # 兼容旧版把 config_path 指到项目根目录的 `config.json` 的情况: + # 本仓库真实配置文件为 `config/config.json`(见 path_config.get_config_path)。 + # 若 analyser.config_path 指向根目录 config.json,则自动切换到 config/config.json。 + try: + preferred = default_config_path + preferred_abs = os.path.abspath(preferred) + cp_abs = os.path.abspath(str(config_path)) + root_abs = os.path.abspath(path_config.get_project_root()) + legacy_abs = os.path.join(root_abs, "config.json") + if os.path.normcase(cp_abs) == os.path.normcase(legacy_abs) and os.path.exists( + preferred_abs + ): + config_path = preferred_abs + except Exception: + pass + + # 如果调用方显式传入 config_path,则尊重其选择(不做自动迁移) + if passed_in_config_path: + pass + # 如果 config_path 仍然为 None,直接返回(使用默认值) if config_path is None: return diff --git a/gui/gui_core.py b/gui/gui_core.py index d2feaf0..a0d8356 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -66,8 +66,22 @@ def read_config() -> dict: def write_config(cfg: dict) -> None: + # GUI 表单通常只生成“已知字段”的子集;直接覆盖写会丢失其它键(例如 ROI rect/poly 等扩展配置)。 + # 这里做一次 merge:保留原配置中的未知键,再用新 cfg 覆盖同名键。 + merged = {} + try: + merged = read_config() + if not isinstance(merged, dict): + merged = {} + except Exception: + merged = {} + try: + if isinstance(cfg, dict): + merged.update(cfg) + except Exception: + pass with open(CONFIG_PATH, "w", encoding="utf-8") as f: - json.dump(cfg, f, ensure_ascii=False, indent=4) + json.dump(merged, f, ensure_ascii=False, indent=4) f.write("\n") diff --git a/gui/web_gui.py b/gui/web_gui.py index aea5edc..ab0b220 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -73,8 +73,22 @@ def read_config() -> dict: def write_config(cfg: dict) -> None: + # Web 表单通常只生成“已知字段”的子集;直接覆盖写会丢失其它键(例如 ROI rect/poly 等扩展配置)。 + # 这里做一次 merge:保留原配置中的未知键,再用新 cfg 覆盖同名键。 + merged = {} + try: + merged = read_config() + if not isinstance(merged, dict): + merged = {} + except Exception: + merged = {} + try: + if isinstance(cfg, dict): + merged.update(cfg) + except Exception: + pass with open(CONFIG_PATH, "w", encoding="utf-8") as f: - json.dump(cfg, f, ensure_ascii=False, indent=4) + json.dump(merged, f, ensure_ascii=False, indent=4) f.write("\n") diff --git a/tools/_dump_lines.py b/tools/_dump_lines.py new file mode 100644 index 0000000..2303169 --- /dev/null +++ b/tools/_dump_lines.py @@ -0,0 +1,6 @@ +import sys +p='douyin/other/douyin_yanghao.py' +with open(p,'rb') as f: + lines=f.read().splitlines() +for i in range(959,979): + print(f"{i+1:4}: {lines[i]!r}") diff --git a/tools/test_yanghao_detection.py b/tools/test_yanghao_detection.py index 413a77c..cc5aecb 100644 --- a/tools/test_yanghao_detection.py +++ b/tools/test_yanghao_detection.py @@ -1,6 +1,10 @@ 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__), "..")) @@ -69,6 +73,198 @@ def test_detection_for_polygon(poly, tpl_path, label): 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) @@ -79,7 +275,7 @@ def main(): like_tpl = get_like_template_path() fav_tpl = get_fav_template_path() - # polygon from config + # 默认 polygon(若未从配置读到则回退) like_poly = [[927, 1161], [1039, 1164], [1049, 1265], [940, 1263]] fav_poly = [ [938, 1601], @@ -94,12 +290,48 @@ def main(): [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()