diff --git a/douyin/detection/pixel/buttons.py b/douyin/detection/pixel/buttons.py index f5b811c..8c313a5 100644 --- a/douyin/detection/pixel/buttons.py +++ b/douyin/detection/pixel/buttons.py @@ -33,16 +33,18 @@ def detect_attend_button_red_area( 扩展检测区域到更宽的范围以覆盖"一键参与评论"等按钮 """ try: + from douyin.fudai.core.coords import get_pixel_region + width, height = pic_rgb.size # 缩放坐标到实际尺寸 scale_x = width / 1080.0 scale_y = height / 2400.0 - # 检测区域(基准1080x2400,扩展宽度以覆盖更宽的按钮) - x1 = int(200 * scale_x) # 扩展左侧 - y1 = int(2000 * scale_y) # 稍微上移 - x2 = int(880 * scale_x) # 扩展右侧 - y2 = int(2120 * scale_y) # 稍微下移 + bx1, by1, bx2, by2 = get_pixel_region("attend_button", (200, 2000, 880, 2120)) + x1 = int(bx1 * scale_x) + y1 = int(by1 * scale_y) + x2 = int(bx2 * scale_x) + y2 = int(by2 * scale_y) # 确保坐标在范围内 x1 = max(0, min(x1, width)) @@ -189,16 +191,18 @@ def detect_fansclub_join_red_area( 检测区域:(200,1940)-(880,2140) 基准1080x2400 """ try: + from douyin.fudai.core.coords import get_pixel_region + width, height = pic_rgb.size # 缩放坐标到实际尺寸 scale_x = width / 1080.0 scale_y = height / 2400.0 - # 检测区域(基准1080x2400) - x1 = int(200 * scale_x) - y1 = int(1940 * scale_y) - x2 = int(880 * scale_x) - y2 = int(2140 * scale_y) + bx1, by1, bx2, by2 = get_pixel_region("fansclub_join", (200, 1940, 880, 2140)) + x1 = int(bx1 * scale_x) + y1 = int(by1 * scale_y) + x2 = int(bx2 * scale_x) + y2 = int(by2 * scale_y) # 确保坐标在范围内 x1 = max(0, min(x1, width)) diff --git a/douyin/detection/pixel/popups.py b/douyin/detection/pixel/popups.py index 1b9614f..cb3cb10 100644 --- a/douyin/detection/pixel/popups.py +++ b/douyin/detection/pixel/popups.py @@ -44,6 +44,8 @@ def detect_coupon_popup_background( tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时) """ try: + from douyin.fudai.core.coords import get_pixel_region + try: import cv2 # type: ignore[import-untyped] import numpy as np # type: ignore[import-untyped] @@ -60,10 +62,11 @@ def detect_coupon_popup_background( scale_x = width / 1080.0 scale_y = height / 2400.0 - x1 = int(9 * scale_x) - y1 = int(1173 * scale_y) - x2 = int(1079 * scale_x) - y2 = int(2255 * scale_y) + bx1, by1, bx2, by2 = get_pixel_region("coupon_popup", (9, 1173, 1079, 2255)) + x1 = int(bx1 * scale_x) + y1 = int(by1 * scale_y) + x2 = int(bx2 * scale_x) + y2 = int(by2 * scale_y) x1 = max(0, min(x1, width)) y1 = max(0, min(y1, height)) @@ -197,6 +200,7 @@ def detect_redpacket_popup_background( tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时) """ try: + from douyin.fudai.core.coords import get_pixel_region import numpy as np # type: ignore[import-untyped] width, height = pic_rgb.size @@ -205,10 +209,11 @@ def detect_redpacket_popup_background( # 购物红包通常出现在屏幕中央 # 基准坐标(1080x2400) - x1 = int(200 * scale_x) - y1 = int(300 * scale_y) - x2 = int(880 * scale_x) - y2 = int(1400 * scale_y) + bx1, by1, bx2, by2 = get_pixel_region("shopping_redpacket", (200, 300, 880, 1400)) + x1 = int(bx1 * scale_x) + y1 = int(by1 * scale_y) + x2 = int(bx2 * scale_x) + y2 = int(by2 * scale_y) # 边界检查 x1 = max(0, min(x1, width)) diff --git a/douyin/detection/pixel/stage.py b/douyin/detection/pixel/stage.py index 930f07e..66f5f6d 100644 --- a/douyin/detection/pixel/stage.py +++ b/douyin/detection/pixel/stage.py @@ -45,26 +45,9 @@ def _scale_box( def _live_room_icon_bbox(width: int, height: int) -> tuple[int, int, int, int]: - points = [ - (1002, 172), - (999, 174), - (1011, 186), - (999, 199), - (1002, 202), - (1013, 190), - (1025, 201), - (1028, 198), - (1017, 187), - (1028, 174), - (1025, 172), - (1014, 184), - ] - scale_x = width / 1080.0 - scale_y = height / 2400.0 - scaled = [(int(x * scale_x), int(y * scale_y)) for x, y in points] - xs = [p[0] for p in scaled] - ys = [p[1] for p in scaled] - return max(0, min(xs)), max(0, min(ys)), min(width, max(xs)), min(height, max(ys)) + from douyin.fudai.core.coords import get_live_room_icon_bbox + + return _scale_box(get_live_room_icon_bbox(), width, height) def _cleanup_pixel_stage_debug_images() -> None: @@ -110,8 +93,10 @@ def _save_pixel_stage_overview( try: from PIL import ImageDraw, ImageFont from douyin.fudai.core.coords import ( + get_fudai_detail_body_region, get_fudai_detail_profile, get_lottery_result_confirm_profile, + get_pixel_region, ) from douyin.handlers import douyin_screenshot_manager from douyin.handlers.screenshot_manager.save_image_helpers import is_debug_captures_enabled @@ -136,18 +121,18 @@ def _save_pixel_stage_overview( regions: dict[str, tuple[str, tuple[int, int, int, int]]] = { "lottery": ("has_lucky_draw_result", tuple(lottery_profile.get("pixel") or (181, 1261, 890, 1389))), - "attend": ("has_attend_button_red", (200, 2000, 880, 2120)), - "fansclub": ("has_fansclub_join_red", (200, 1940, 880, 2140)), + "attend": ("has_attend_button_red", get_pixel_region("attend_button", (200, 2000, 880, 2120))), + "fansclub": ("has_fansclub_join_red", get_pixel_region("fansclub_join", (200, 1940, 880, 2140))), } if state.get("has_fudai_detail"): - regions["detail_body"] = ("has_fudai_detail", (0, 1160, 1080, 2250)) + regions["detail_body"] = ("has_fudai_detail", get_fudai_detail_body_region()) if task_count not in (None, 0): regions["task_count"] = ("has_fudai_detail", tuple(detail_profile.get("task_count") or (860, 1770, 1035, 1875))) else: if details.get("has_coupon_bg", {}).get("method") != "disabled": - regions["coupon"] = ("has_coupon_bg", (9, 1173, 1079, 2255)) + regions["coupon"] = ("has_coupon_bg", get_pixel_region("coupon_popup", (9, 1173, 1079, 2255))) if details.get("has_redpacket_bg", {}).get("method") != "disabled": - regions["redpacket"] = ("has_redpacket_bg", (200, 300, 880, 1400)) + regions["redpacket"] = ("has_redpacket_bg", get_pixel_region("shopping_redpacket", (200, 300, 880, 1400))) def _color_for(key: str) -> tuple[int, int, int]: info = details.get(key, {}) diff --git a/douyin/fudai/core/coords.py b/douyin/fudai/core/coords.py index 48d4b22..441c6f3 100644 --- a/douyin/fudai/core/coords.py +++ b/douyin/fudai/core/coords.py @@ -1,39 +1,85 @@ -# 统一的坐标常量(基准分辨率 1080x2400) -# 仅包含常用的福袋详情相关裁剪框,后续可按需扩展。 +"""福袋与像素检测常用坐标。 -# 福袋价值裁剪区域 (left, top, right, bottom) -""" -统一的坐标常量(基准分辨率 1080x2400) -集中维护常用裁剪框,避免代码中硬编码数字。 +基准分辨率统一为 1080x2400。 +默认值保留在本文件;运行时若 `config.json` 提供覆盖,则优先使用配置。 """ +from __future__ import annotations + +from functools import lru_cache +from typing import Any + + +def _tuple4(values: Any) -> tuple[int, int, int, int] | None: + try: + seq = list(values or []) + except Exception: + return None + if len(seq) != 4: + return None + try: + return tuple(int(v) for v in seq) + except Exception: + return None + + +def _tuple2(values: Any) -> tuple[int, int] | None: + parsed = _tuple4(values) + if parsed is None: + try: + seq = list(values or []) + except Exception: + return None + if len(seq) != 2: + return None + try: + return int(seq[0]), int(seq[1]) + except Exception: + return None + return parsed[0], parsed[1] + + +def _deep_get(obj: Any, *parts: str) -> Any: + cur = obj + for part in parts: + if not isinstance(cur, dict) or part not in cur: + return None + cur = cur[part] + return cur + + +@lru_cache(maxsize=1) +def _read_runtime_region_config() -> dict: + try: + from gui.gui_core_pkg.config import read_config + + cfg = read_config() + return cfg if isinstance(cfg, dict) else {} + except Exception: + return {} + + +def reset_region_config_cache() -> None: + _read_runtime_region_config.cache_clear() + + # 福袋相关常用坐标 -# 福袋价值裁剪区域 (left, top, right, bottom) VALUE_BOX_TARGET = (643, 1466, 769, 1656) - -# 福袋详情内容区域(任务/描述) CONTENT_BOX = (389, 1273, 1000, 1534) -# 倒计时不同场景的裁剪区域(按出现情况命名) +# 倒计时不同场景的裁剪区域 COUNTDOWN_1110_1230 = (390, 1110, 690, 1230) COUNTDOWN_1140_1290 = (390, 1140, 690, 1290) COUNTDOWN_1010_1130 = (390, 1010, 690, 1130) COUNTDOWN_1460_1580 = (390, 1460, 690, 1580) -# 任务列表区域(用于检测观看任务) TASK_LIST = (50, 1621, 1032, 1960) - -# 参与按钮区域(向下扩大,增强对部分机型底部按钮的覆盖) PARTICIPATE_BUTTON = (306, 2030, 780, 2180) - -# 扩大识别区域(加入粉丝团 / OCR 扩大区域) JOIN_FANSCLUB_REGION = (150, 1900, 950, 2200) -# 抽奖结果 / 弹窗确认 DRAW_RESULT = (380, 660, 720, 755) NO_PRIZE_CONFIRM = (340, 1195, 740, 1355) -# 抽奖结果相关区域 LOTTERY_RESULT_AREA = (300, 600, 800, 800) LOTTERY_RESULT_CONFIRM_BUTTON_V1 = (181, 1261, 890, 1389) LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1 = LOTTERY_RESULT_CONFIRM_BUTTON_V1 @@ -41,26 +87,27 @@ LOTTERY_RESULT_CONFIRM_CLICK_V1 = (532, 1289) LOTTERY_RESULT_CONFIRM_BUTTON_V2 = (250, 1275, 825, 1435) LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2 = (290, 1300, 790, 1415) LOTTERY_RESULT_CONFIRM_CLICK_V2 = (540, 1360) -# 默认导出保持兼容;运行时请通过 get_lottery_result_confirm_profile 按 UI 版本选择。 LOTTERY_RESULT_CONFIRM_BUTTON = LOTTERY_RESULT_CONFIRM_BUTTON_V1 LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL = LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1 LOTTERY_RESULT_CONFIRM_CLICK = LOTTERY_RESULT_CONFIRM_CLICK_V1 -# 购物红包/弹窗诊断区域 SHOPPING_REDPACKET_AREA = (200, 300, 880, 1200) STAGE_RED_PACKET_OCR = (200, 300, 880, 1200) COUPON_PARTICIPATE_BUTTON_ALT = (200, 1940, 880, 2140) -# 常用标签栏(推荐/关注/直播) RECOMMEND_TAB = (400, 140, 900, 200) FOLLOW_TAB = (658, 147, 765, 194) LIVE_LIST_TAB = (400, 140, 900, 200) - -# 直播间标题中部(用于部分详情模块) LIVE_ROOM_TITLE = (130, 120, 560, 225) +LIVE_ROOM_ICON_BBOX = (999, 172, 1028, 202) +FUDAI_DETAIL_BODY_DEFAULT = (0, 1160, 1080, 2250) +ATTEND_BUTTON_PIXEL_BOX = (200, 2000, 880, 2120) +FANSCLUB_JOIN_PIXEL_BOX = (200, 1940, 880, 2140) +COUPON_POPUP_BOX = (9, 1173, 1079, 2255) +SHOPPING_REDPACKET_PIXEL_BOX = (200, 300, 880, 1400) + -# 福袋详情页 UI 版本 profile。legacy 保持旧坐标,v2_0 对应 2026-06 当前新详情页。 DETAIL_UI_LEGACY = { "version": "legacy", "content": CONTENT_BOX, @@ -75,9 +122,9 @@ DETAIL_UI_LEGACY = { DETAIL_UI_V2_0 = { "version": "v2_0", - "content": (360, 1472, 1035, 1545), + "content": (360, 1410, 1035, 1495), "value": (300, 1585, 650, 1685), - "countdown_full": (760, 1355, 1035, 1455), + "countdown_full": (760, 1328, 1038, 1398), "task_list": (60, 1840, 1030, 2005), "task_count": (860, 1770, 1035, 1875), "participants": (520, 1325, 760, 1415), @@ -88,19 +135,42 @@ DETAIL_UI_V2_0 = { DETAIL_UI_V2_0_ONE_TASK = { "version": "v2_0", "variant": "one_task", - "content": (360, 1472, 1035, 1545), - "value": (340, 1680, 690, 1765), - "countdown_full": (760, 1355, 1035, 1455), - "task_list": (55, 1935, 900, 2055), - "task_count": (890, 1855, 1040, 1950), - "participants": (535, 1375, 760, 1475), - "button": (70, 2055, 1010, 2225), + "content": (360, 1460, 1035, 1545), + "value": (350, 1640, 760, 1735), + "countdown_full": (730, 1338, 1038, 1418), + "info_line": (430, 1315, 1055, 1435), + "task_list": (60, 1845, 885, 2005), + "task_count": (890, 1855, 1040, 1960), + "participants": (516, 1396, 743, 1443), + "button": (70, 2050, 1010, 2195), "live_title": LIVE_ROOM_TITLE, } +FUDAI_DETAIL_REGION_DEFAULTS = { + "legacy": DETAIL_UI_LEGACY, + "v2_0_two_task": DETAIL_UI_V2_0, + "v2_0_one_task": DETAIL_UI_V2_0_ONE_TASK, +} + +PIXEL_REGION_DEFAULTS = { + "lottery_result": { + "button": LOTTERY_RESULT_CONFIRM_BUTTON_V2, + "pixel": LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2, + "click": LOTTERY_RESULT_CONFIRM_CLICK_V2, + "legacy_button": LOTTERY_RESULT_CONFIRM_BUTTON_V1, + "legacy_pixel": LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1, + "legacy_click": LOTTERY_RESULT_CONFIRM_CLICK_V1, + }, + "attend_button": ATTEND_BUTTON_PIXEL_BOX, + "fansclub_join": FANSCLUB_JOIN_PIXEL_BOX, + "coupon_popup": COUPON_POPUP_BOX, + "shopping_redpacket": SHOPPING_REDPACKET_PIXEL_BOX, + "fudai_detail_body": FUDAI_DETAIL_BODY_DEFAULT, + "live_room_icon_bbox": LIVE_ROOM_ICON_BBOX, +} + def normalize_fudai_detail_ui_mode(mode: str | None) -> str: - """Normalize detail UI mode for config/API boundaries.""" mode_s = str(mode or "auto").strip().lower().replace("-", "_").replace(".", "_") if mode_s in ("v2", "2_0", "v2_0"): return "v2_0" @@ -109,63 +179,98 @@ def normalize_fudai_detail_ui_mode(mode: str | None) -> str: return "auto" -def get_fudai_detail_profile(mode: str | None = "auto", task_count: int | None = None) -> dict: - """Return the OCR region profile. auto currently prefers the fast v2_0 path.""" +def _detail_profile_key(mode: str | None, task_count: int | None) -> str: normalized = normalize_fudai_detail_ui_mode(mode) if normalized == "legacy": - return DETAIL_UI_LEGACY + return "legacy" try: if int(task_count or 0) == 1: - return DETAIL_UI_V2_0_ONE_TASK + return "v2_0_one_task" except Exception: - pass - return DETAIL_UI_V2_0 + pass + return "v2_0_two_task" + + +def _apply_region_overrides(defaults: dict[str, Any], overrides: Any) -> dict[str, Any]: + merged = dict(defaults) + if not isinstance(overrides, dict): + return merged + for key, default_value in defaults.items(): + candidate = overrides.get(key) + if isinstance(default_value, tuple): + parsed = _tuple4(candidate) + if parsed is not None: + merged[key] = parsed + else: + merged[key] = candidate + return merged + + +def get_fudai_detail_profile(mode: str | None = "auto", task_count: int | None = None) -> dict: + profile_key = _detail_profile_key(mode, task_count) + defaults = FUDAI_DETAIL_REGION_DEFAULTS[profile_key] + cfg = _read_runtime_region_config() + overrides = _deep_get(cfg, "fudai_detail_regions", profile_key) + if not isinstance(overrides, dict) or not overrides: + return defaults + return _apply_region_overrides(defaults, overrides) + + +def get_pixel_region(name: str, default: tuple[int, int, int, int] | None = None) -> tuple[int, int, int, int]: + defaults = PIXEL_REGION_DEFAULTS.get(name, default) + if defaults is None or isinstance(defaults, dict): + raise KeyError(name) + cfg = _read_runtime_region_config() + parsed = _tuple4(_deep_get(cfg, "pixel_regions", name)) + return parsed if parsed is not None else tuple(defaults) + + +def get_live_room_icon_bbox() -> tuple[int, int, int, int]: + return get_pixel_region("live_room_icon_bbox", LIVE_ROOM_ICON_BBOX) + + +def get_fudai_detail_body_region() -> tuple[int, int, int, int]: + return get_pixel_region("fudai_detail_body", FUDAI_DETAIL_BODY_DEFAULT) def get_lottery_result_confirm_profile(mode: str | None = "auto") -> dict: - """Return confirm-button regions for the lottery result popup by UI version.""" normalized = normalize_fudai_detail_ui_mode(mode) + cfg = _read_runtime_region_config() + overrides = _deep_get(cfg, "pixel_regions", "lottery_result") if normalized == "legacy": - return { + result = { "version": "legacy", "button": LOTTERY_RESULT_CONFIRM_BUTTON_V1, "pixel": LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1, "click": LOTTERY_RESULT_CONFIRM_CLICK_V1, "pixel_style": "red", } - return { + if isinstance(overrides, dict): + result["button"] = _tuple4(overrides.get("legacy_button")) or result["button"] + result["pixel"] = _tuple4(overrides.get("legacy_pixel")) or result["pixel"] + result["click"] = _tuple2(overrides.get("legacy_click")) or result["click"] + return result + result = { "version": "v2_0", "button": LOTTERY_RESULT_CONFIRM_BUTTON_V2, "pixel": LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2, "click": LOTTERY_RESULT_CONFIRM_CLICK_V2, "pixel_style": "white", } + if isinstance(overrides, dict): + result["button"] = _tuple4(overrides.get("button")) or result["button"] + result["pixel"] = _tuple4(overrides.get("pixel")) or result["pixel"] + result["click"] = _tuple2(overrides.get("click")) or result["click"] + return result + -# 备用/替代参与按钮区域(弹窗/诊断模块使用) PARTICIPATE_BUTTON_ALT = PARTICIPATE_BUTTON - -# 直播/人机验证相关区域(占位值,可按实际截图微调) LIVE_VERIFY1 = (200, 600, 880, 900) LIVE_VERIFY2 = (200, 900, 880, 1200) - -# 机器人验证图片裁剪区域(用于保存/处理验证图片) ROBOT_VERIFY = (100, 1200, 980, 1780) - -# 诊断购物红包(弹窗快速检测区域 - 文字区域) DIAG_SHOPPING_REDPACKET = (200, 300, 880, 1000) - -# 倒计时、任务、按钮等常用区域(保留占位,可根据需要填写) -# COUNTDOWN_BOX = (390, 1140, 570, 1290) -# BUTTON_BOX = (306, 2030, 780, 2180) -# CONTENT_BOX = (200, 600, 880, 900) - -# 点击坐标常量(基准分辨率 1080x2400) -# 关闭详情页:点击详情页旁边空白区域 DETAIL_OUTSIDE_CLICK = (500, 470) -# 参与抽奖按钮 PARTICIPATE_BTN_CLICK = (543, 2070) -# 粉丝团加入按钮 FANSCLUB_JOIN_CLICK = (540, 2006) -# 粉丝团加入按钮(回退坐标) FANSCLUB_JOIN_FALLBACK_CLICK = (500, 2060) diff --git a/gui/components/config_io.py b/gui/components/config_io.py index 1f940bf..dfd4774 100644 --- a/gui/components/config_io.py +++ b/gui/components/config_io.py @@ -27,6 +27,69 @@ from .config_io_helpers import ( write_logging_to_cfg, ) + +_REGION_CONFIG_SPECS = ( + ("fudai_detail_regions", "legacy", "content"), + ("fudai_detail_regions", "legacy", "value"), + ("fudai_detail_regions", "legacy", "countdown_full"), + ("fudai_detail_regions", "legacy", "task_list"), + ("fudai_detail_regions", "legacy", "task_count"), + ("fudai_detail_regions", "legacy", "participants"), + ("fudai_detail_regions", "legacy", "button"), + ("fudai_detail_regions", "legacy", "live_title"), + ("fudai_detail_regions", "v2_0_two_task", "content"), + ("fudai_detail_regions", "v2_0_two_task", "value"), + ("fudai_detail_regions", "v2_0_two_task", "countdown_full"), + ("fudai_detail_regions", "v2_0_two_task", "task_list"), + ("fudai_detail_regions", "v2_0_two_task", "task_count"), + ("fudai_detail_regions", "v2_0_two_task", "participants"), + ("fudai_detail_regions", "v2_0_two_task", "button"), + ("fudai_detail_regions", "v2_0_two_task", "live_title"), + ("fudai_detail_regions", "v2_0_one_task", "content"), + ("fudai_detail_regions", "v2_0_one_task", "value"), + ("fudai_detail_regions", "v2_0_one_task", "countdown_full"), + ("fudai_detail_regions", "v2_0_one_task", "info_line"), + ("fudai_detail_regions", "v2_0_one_task", "task_list"), + ("fudai_detail_regions", "v2_0_one_task", "task_count"), + ("fudai_detail_regions", "v2_0_one_task", "participants"), + ("fudai_detail_regions", "v2_0_one_task", "button"), + ("fudai_detail_regions", "v2_0_one_task", "live_title"), + ("pixel_regions", "lottery_result", "button"), + ("pixel_regions", "lottery_result", "pixel"), + ("pixel_regions", "lottery_result", "click"), + ("pixel_regions", "attend_button", None), + ("pixel_regions", "fansclub_join", None), + ("pixel_regions", "coupon_popup", None), + ("pixel_regions", "shopping_redpacket", None), + ("pixel_regions", "fudai_detail_body", None), + ("pixel_regions", "live_room_icon_bbox", None), +) + + +def _deep_get(obj: dict, *parts: str): + cur = obj + for part in parts: + if not isinstance(cur, dict) or part not in cur: + return None + cur = cur[part] + return cur + + +def _deep_set(obj: dict, parts: tuple[str, ...], value) -> None: + cur = obj + for part in parts[:-1]: + if part not in cur or not isinstance(cur[part], dict): + cur[part] = {} + cur = cur[part] + cur[parts[-1]] = value + + +def _make_region_var_key(root: str, scope: str, name: str | None, axis: str) -> str: + if name: + return f"{root}_{scope}_{name}_{axis}_var" + return f"{root}_{scope}_{axis}_var" + + def load_config_to_ui( *, vars_: Dict[str, tk.Variable], @@ -258,6 +321,13 @@ def load_config_to_ui( float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0) ) vars_["skip_lt_seconds_var"].set(int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10)) + for root, scope, name in _REGION_CONFIG_SPECS: + raw = _deep_get(cfg, root, scope, name) if name else _deep_get(cfg, root, scope) + values = list(raw) if isinstance(raw, (list, tuple)) else [0, 0, 0, 0] + if len(values) < 4: + values = [0, 0, 0, 0] + for idx, axis in enumerate(("x1", "y1", "x2", "y2")): + vars_[_make_region_var_key(root, scope, name, axis)].set(int(values[idx] or 0)) apply_debug_captures_from_cfg(vars_, cfg) apply_logging_from_cfg(vars_, cfg) @@ -516,6 +586,13 @@ def save_ui_to_config( vars_["fansclub_manual_wait_var"].get() or 3.0 ) cfg2["skip_if_countdown_lt_seconds"] = int(vars_["skip_lt_seconds_var"].get() or 10) + for root, scope, name in _REGION_CONFIG_SPECS: + values = [ + int(vars_[_make_region_var_key(root, scope, name, axis)].get() or 0) + for axis in ("x1", "y1", "x2", "y2") + ] + target_parts = (root, scope, name) if name else (root, scope) + _deep_set(cfg2, target_parts, values) write_debug_captures_to_cfg(cfg2, vars_) write_logging_to_cfg(cfg2, vars_) diff --git a/gui/components/config_vars.py b/gui/components/config_vars.py index 5e840c9..19281e9 100644 --- a/gui/components/config_vars.py +++ b/gui/components/config_vars.py @@ -10,6 +10,59 @@ import tkinter as tk from typing import Dict +_REGION_CONFIG_SPECS = ( + ("fudai_detail_regions", "legacy", "content"), + ("fudai_detail_regions", "legacy", "value"), + ("fudai_detail_regions", "legacy", "countdown_full"), + ("fudai_detail_regions", "legacy", "task_list"), + ("fudai_detail_regions", "legacy", "task_count"), + ("fudai_detail_regions", "legacy", "participants"), + ("fudai_detail_regions", "legacy", "button"), + ("fudai_detail_regions", "legacy", "live_title"), + ("fudai_detail_regions", "v2_0_two_task", "content"), + ("fudai_detail_regions", "v2_0_two_task", "value"), + ("fudai_detail_regions", "v2_0_two_task", "countdown_full"), + ("fudai_detail_regions", "v2_0_two_task", "task_list"), + ("fudai_detail_regions", "v2_0_two_task", "task_count"), + ("fudai_detail_regions", "v2_0_two_task", "participants"), + ("fudai_detail_regions", "v2_0_two_task", "button"), + ("fudai_detail_regions", "v2_0_two_task", "live_title"), + ("fudai_detail_regions", "v2_0_one_task", "content"), + ("fudai_detail_regions", "v2_0_one_task", "value"), + ("fudai_detail_regions", "v2_0_one_task", "countdown_full"), + ("fudai_detail_regions", "v2_0_one_task", "info_line"), + ("fudai_detail_regions", "v2_0_one_task", "task_list"), + ("fudai_detail_regions", "v2_0_one_task", "task_count"), + ("fudai_detail_regions", "v2_0_one_task", "participants"), + ("fudai_detail_regions", "v2_0_one_task", "button"), + ("fudai_detail_regions", "v2_0_one_task", "live_title"), + ("pixel_regions", "lottery_result", "button"), + ("pixel_regions", "lottery_result", "pixel"), + ("pixel_regions", "lottery_result", "click"), + ("pixel_regions", "attend_button", None), + ("pixel_regions", "fansclub_join", None), + ("pixel_regions", "coupon_popup", None), + ("pixel_regions", "shopping_redpacket", None), + ("pixel_regions", "fudai_detail_body", None), + ("pixel_regions", "live_room_icon_bbox", None), +) + + +def _deep_get(obj: dict, *parts: str): + cur = obj + for part in parts: + if not isinstance(cur, dict) or part not in cur: + return None + cur = cur[part] + return cur + + +def _make_region_var_key(root: str, scope: str, name: str | None, axis: str) -> str: + if name: + return f"{root}_{scope}_{name}_{axis}_var" + return f"{root}_{scope}_{axis}_var" + + def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]: """从 cfg 构建所有 tk Var 实例,返回名→Var 字典。""" y_var = tk.IntVar(value=int(cfg.get("y_pianyi", 0) or 0)) @@ -451,6 +504,16 @@ def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]: skip_lt_seconds_var = tk.IntVar( value=int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10) ) + region_vars: Dict[str, tk.Variable] = {} + for root, scope, name in _REGION_CONFIG_SPECS: + raw = _deep_get(cfg, root, scope, name) if name else _deep_get(cfg, root, scope) + values = list(raw) if isinstance(raw, (list, tuple)) else [] + if len(values) < 4: + values = [0, 0, 0, 0] + for idx, axis in enumerate(("x1", "y1", "x2", "y2")): + region_vars[_make_region_var_key(root, scope, name, axis)] = tk.IntVar( + value=int(values[idx] or 0) + ) return { "y_var": y_var, @@ -603,4 +666,5 @@ def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]: "gui_realtime_refresh_interval_ms_var": gui_realtime_refresh_interval_ms_var, "gui_realtime_tail_items_var": gui_realtime_tail_items_var, "skip_lt_seconds_var": skip_lt_seconds_var, + **region_vars, } diff --git a/gui/components/debug_tab.py b/gui/components/debug_tab.py index 23113c6..101311f 100644 --- a/gui/components/debug_tab.py +++ b/gui/components/debug_tab.py @@ -14,6 +14,86 @@ from tkinter.constants import LEFT, BOTH, X from typing import Dict +_REGION_SECTIONS = ( + ( + "legacy OCR", + ( + ("fudai_detail_regions", "legacy", "content", "内容"), + ("fudai_detail_regions", "legacy", "value", "价值"), + ("fudai_detail_regions", "legacy", "countdown_full", "倒计时"), + ("fudai_detail_regions", "legacy", "task_list", "任务列表"), + ("fudai_detail_regions", "legacy", "task_count", "任务数量"), + ("fudai_detail_regions", "legacy", "participants", "人数"), + ("fudai_detail_regions", "legacy", "button", "按钮"), + ("fudai_detail_regions", "legacy", "live_title", "直播间标题"), + ), + ), + ( + "v2_0 two task OCR", + ( + ("fudai_detail_regions", "v2_0_two_task", "content", "内容"), + ("fudai_detail_regions", "v2_0_two_task", "value", "价值"), + ("fudai_detail_regions", "v2_0_two_task", "countdown_full", "倒计时"), + ("fudai_detail_regions", "v2_0_two_task", "task_list", "任务列表"), + ("fudai_detail_regions", "v2_0_two_task", "task_count", "任务数量"), + ("fudai_detail_regions", "v2_0_two_task", "participants", "人数"), + ("fudai_detail_regions", "v2_0_two_task", "button", "按钮"), + ("fudai_detail_regions", "v2_0_two_task", "live_title", "直播间标题"), + ), + ), + ( + "v2_0 one task OCR", + ( + ("fudai_detail_regions", "v2_0_one_task", "content", "内容"), + ("fudai_detail_regions", "v2_0_one_task", "value", "价值"), + ("fudai_detail_regions", "v2_0_one_task", "countdown_full", "倒计时"), + ("fudai_detail_regions", "v2_0_one_task", "info_line", "信息行"), + ("fudai_detail_regions", "v2_0_one_task", "task_list", "任务列表"), + ("fudai_detail_regions", "v2_0_one_task", "task_count", "任务数量"), + ("fudai_detail_regions", "v2_0_one_task", "participants", "人数"), + ("fudai_detail_regions", "v2_0_one_task", "button", "按钮"), + ("fudai_detail_regions", "v2_0_one_task", "live_title", "直播间标题"), + ), + ), + ( + "像素检测区域", + ( + ("pixel_regions", "lottery_result", "button", "开奖按钮"), + ("pixel_regions", "lottery_result", "pixel", "开奖像素"), + ("pixel_regions", "lottery_result", "click", "开奖点击"), + ("pixel_regions", "attend_button", None, "参与按钮"), + ("pixel_regions", "fansclub_join", None, "粉丝团"), + ("pixel_regions", "coupon_popup", None, "优惠券"), + ("pixel_regions", "shopping_redpacket", None, "购物红包"), + ("pixel_regions", "fudai_detail_body", None, "详情主体"), + ("pixel_regions", "live_room_icon_bbox", None, "直播间图标bbox"), + ), + ), +) + + +def _make_region_var_key(root: str, scope: str, name: str | None, axis: str) -> str: + if name: + return f"{root}_{scope}_{name}_{axis}_var" + return f"{root}_{scope}_{axis}_var" + + +def _add_region_editor(parent: ttk.Frame, *, root: str, scope: str, name: str | None, label: str, vars_: Dict[str, tk.Variable]) -> None: + row = ttk.Frame(parent) + row.pack(fill=X, padx=10, pady=(0, 4)) + ttk.Label(row, text=f"{label}:", width=14).pack(side=LEFT) + for axis in ("x1", "y1", "x2", "y2"): + ttk.Label(row, text=f"{axis}").pack(side=LEFT, padx=(4, 2)) + ttk.Spinbox( + row, + from_=-9999, + to=9999, + increment=1, + textvariable=vars_[_make_region_var_key(root, scope, name, axis)], + width=6, + ).pack(side=LEFT) + + def setup_debug_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> ttk.Frame: debug_tab = ttk.Frame(parent) @@ -303,6 +383,14 @@ def setup_debug_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> t row4c, text="(0.0~1.0,默认0.8,多边形区域白色像素比例>=此值判定为在直播间)" ).pack(side=LEFT, padx=(6, 0)) + region_box = ttk.LabelFrame(debug_container, text="福袋坐标配置") + region_box.pack(fill=X, padx=10, pady=(0, 10)) + for section_title, items in _REGION_SECTIONS: + section = ttk.LabelFrame(region_box, text=section_title) + section.pack(fill=X, padx=10, pady=(8, 6)) + for root, scope, name, label in items: + _add_region_editor(section, root=root, scope=scope, name=name, label=label, vars_=vars_) + # 鼠标配置 mouse_config_box = ttk.LabelFrame(debug_container, text="鼠标配置") mouse_config_box.pack(fill=X, padx=10, pady=(0, 10)) diff --git a/gui/web_gui_pkg/routes.py b/gui/web_gui_pkg/routes.py index 461ab2b..df52e10 100644 --- a/gui/web_gui_pkg/routes.py +++ b/gui/web_gui_pkg/routes.py @@ -83,6 +83,17 @@ def _is_invalid_ports_spec(spec) -> bool: return True +def _coerce_region_values(value) -> list[int] | None: + if not isinstance(value, (list, tuple)): + return None + if len(value) != 4: + return None + try: + return [int(item) for item in value] + except Exception: + return None + + def handle_get(handler, u, runner, csrf_token: str) -> None: if u.path.startswith("/api/"): if not _is_local_request(handler): @@ -448,6 +459,42 @@ def handle_post(handler, u, runner, csrf_token: str) -> None: "fudai_detail_ui_mode", "logging.log_format_mode", } + region_list_keys = { + "fudai_detail_regions.legacy.content", + "fudai_detail_regions.legacy.value", + "fudai_detail_regions.legacy.countdown_full", + "fudai_detail_regions.legacy.task_list", + "fudai_detail_regions.legacy.task_count", + "fudai_detail_regions.legacy.participants", + "fudai_detail_regions.legacy.button", + "fudai_detail_regions.legacy.live_title", + "fudai_detail_regions.v2_0_two_task.content", + "fudai_detail_regions.v2_0_two_task.value", + "fudai_detail_regions.v2_0_two_task.countdown_full", + "fudai_detail_regions.v2_0_two_task.task_list", + "fudai_detail_regions.v2_0_two_task.task_count", + "fudai_detail_regions.v2_0_two_task.participants", + "fudai_detail_regions.v2_0_two_task.button", + "fudai_detail_regions.v2_0_two_task.live_title", + "fudai_detail_regions.v2_0_one_task.content", + "fudai_detail_regions.v2_0_one_task.value", + "fudai_detail_regions.v2_0_one_task.countdown_full", + "fudai_detail_regions.v2_0_one_task.info_line", + "fudai_detail_regions.v2_0_one_task.task_list", + "fudai_detail_regions.v2_0_one_task.task_count", + "fudai_detail_regions.v2_0_one_task.participants", + "fudai_detail_regions.v2_0_one_task.button", + "fudai_detail_regions.v2_0_one_task.live_title", + "pixel_regions.lottery_result.button", + "pixel_regions.lottery_result.pixel", + "pixel_regions.lottery_result.click", + "pixel_regions.attend_button", + "pixel_regions.fansclub_join", + "pixel_regions.coupon_popup", + "pixel_regions.shopping_redpacket", + "pixel_regions.fudai_detail_body", + "pixel_regions.live_room_icon_bbox", + } derived_logging_keys = { "logging.debug_detail_level", "logging.error_detail_level", @@ -515,6 +562,11 @@ def handle_post(handler, u, runner, csrf_token: str) -> None: set_nested_value( cfg, k, [str(x).strip() for x in str(v).splitlines() if str(x).strip()] ) + elif k in region_list_keys: + parsed = _coerce_region_values(v) + if parsed is None: + continue + set_nested_value(cfg, k, parsed) elif k in enum_str_keys: val = str(v or "").strip().lower() if k == "reset_after_swipes_action": diff --git a/tests/test_fudai_debug_overview.py b/tests/test_fudai_debug_overview.py index b3f4804..2a29285 100644 --- a/tests/test_fudai_debug_overview.py +++ b/tests/test_fudai_debug_overview.py @@ -35,13 +35,13 @@ def test_fudai_detail_debug_overview_saves_one_annotated_image(tmp_path, monkeyp { "key": "content", "name": "内容", - "coords": (300, 1400, 1030, 1515), + "coords": (360, 1460, 1035, 1545), "enabled": True, }, { "key": "participants", "name": "人数", - "coords": (520, 1325, 760, 1415), + "coords": (516, 1396, 743, 1443), "enabled": False, }, ], @@ -91,13 +91,13 @@ def test_fudai_detail_debug_labels_are_inside_region_edges(tmp_path, monkeypatch { "key": "countdown", "name": "倒计时", - "coords": (760, 1355, 1035, 1455), + "coords": (730, 1338, 1038, 1418), "enabled": True, }, { "key": "content", "name": "内容", - "coords": (360, 1472, 1035, 1545), + "coords": (360, 1460, 1035, 1545), "enabled": True, }, ], @@ -112,9 +112,61 @@ def test_fudai_detail_debug_labels_are_inside_region_edges(tmp_path, monkeypatch image, _kwargs = saved[0] # Labels are now drawn adjacent to their own boxes, not floating above # another OCR field. - assert image.getpixel((763, 1358)) == (0, 0, 0) - assert image.getpixel((363, 1475)) == (0, 0, 0) - assert image.getpixel((363, 1444)) != (0, 0, 0) + assert image.getpixel((767, 1348)) == (0, 0, 0) + assert image.getpixel((363, 1463)) == (0, 0, 0) + assert image.getpixel((363, 1438)) != (0, 0, 0) + + +def test_fudai_detail_debug_overview_supports_two_task_positions(tmp_path, monkeypatch): + from douyin.core import path_config + from douyin.fudai.core import fudai_debug_utils + + screenshot = tmp_path / "screenshot.png" + Image.new("RGB", (1080, 2400), "white").save(screenshot) + saved = [] + + def fake_save_debug_image(image, **kwargs): + saved.append((image.copy(), kwargs)) + return str(tmp_path / "overview.png") + + monkeypatch.setattr(path_config, "get_screenshot_path", lambda: str(screenshot)) + monkeypatch.setattr( + "douyin.handlers.douyin_screenshot_manager.save_debug_image", + fake_save_debug_image, + ) + + analyser = SimpleNamespace( + resolution_ratio_x=1080, + resolution_ratio_y=2400, + _log_kv=lambda *args, **kwargs: None, + ) + + result = fudai_debug_utils.save_fudai_detail_debug_overview( + analyser, + [ + { + "key": "countdown", + "name": "倒计时", + "coords": (760, 1328, 1038, 1398), + "enabled": True, + }, + { + "key": "content", + "name": "内容", + "coords": (360, 1410, 1035, 1495), + "enabled": True, + }, + ], + ui_version="v2_0", + ocr_enabled={"countdown", "content"}, + task_count=2, + task_count_source="v2_pixels", + ) + + assert result + image, _kwargs = saved[0] + assert image.getpixel((763, 1331)) == (0, 0, 0) + assert image.getpixel((363, 1413)) == (0, 0, 0) def test_fudai_detail_debug_overview_cleans_old_detail_images(tmp_path, monkeypatch): @@ -165,3 +217,53 @@ def test_fudai_detail_debug_overview_cleans_old_detail_images(tmp_path, monkeypa assert not old_detail.exists() assert not old_overview.exists() assert unrelated.exists() + + +def test_fudai_detail_debug_overview_uses_configured_profile_coords(tmp_path, monkeypatch): + from douyin.core import path_config + from douyin.fudai.core import coords as coords_mod + from douyin.fudai.core import fudai_debug_utils + + screenshot = tmp_path / "screenshot.png" + Image.new("RGB", (1080, 2400), "white").save(screenshot) + saved = [] + + def fake_save_debug_image(image, **kwargs): + saved.append((image.copy(), kwargs)) + return str(tmp_path / "overview.png") + + monkeypatch.setattr(path_config, "get_screenshot_path", lambda: str(screenshot)) + monkeypatch.setattr( + "douyin.handlers.douyin_screenshot_manager.save_debug_image", + fake_save_debug_image, + ) + monkeypatch.setattr( + coords_mod, + "_read_runtime_region_config", + lambda: { + "fudai_detail_regions": { + "v2_0_two_task": { + "content": [111, 222, 333, 444], + } + } + }, + ) + + analyser = SimpleNamespace( + resolution_ratio_x=1080, + resolution_ratio_y=2400, + _log_kv=lambda *args, **kwargs: None, + ) + profile = coords_mod.get_fudai_detail_profile("v2_0", task_count=2) + + result = fudai_debug_utils.save_fudai_detail_debug_overview( + analyser, + [{"key": "content", "name": "内容", "coords": profile["content"], "enabled": True}], + ui_version="v2_0", + ocr_enabled={"content"}, + task_count=2, + ) + + assert result + image, _kwargs = saved[0] + assert image.getpixel((114, 225)) == (0, 0, 0) diff --git a/tests/test_fudai_detail_ui_v2.py b/tests/test_fudai_detail_ui_v2.py index 4b410ca..f63b1a0 100644 --- a/tests/test_fudai_detail_ui_v2.py +++ b/tests/test_fudai_detail_ui_v2.py @@ -24,24 +24,81 @@ def test_v2_profile_keeps_legacy_and_adds_expected_regions(): assert auto is DETAIL_UI_V2_0 assert one_task is DETAIL_UI_V2_0_ONE_TASK assert DETAIL_UI_LEGACY["content"] == (389, 1273, 1000, 1534) - assert DETAIL_UI_V2_0["content"] == (360, 1472, 1035, 1545) + assert DETAIL_UI_V2_0["content"] == (360, 1410, 1035, 1495) assert DETAIL_UI_V2_0["value"] == (300, 1585, 650, 1685) - assert DETAIL_UI_V2_0["countdown_full"] == (760, 1355, 1035, 1455) + assert DETAIL_UI_V2_0["countdown_full"] == (760, 1328, 1038, 1398) assert DETAIL_UI_V2_0["task_list"] == (60, 1840, 1030, 2005) assert DETAIL_UI_V2_0["task_count"] == (860, 1770, 1035, 1875) assert DETAIL_UI_V2_0["participants"] == (520, 1325, 760, 1415) assert DETAIL_UI_V2_0["button"] == (70, 2020, 1010, 2165) - assert DETAIL_UI_V2_0_ONE_TASK["content"] == (360, 1472, 1035, 1545) - assert DETAIL_UI_V2_0_ONE_TASK["value"] == (340, 1680, 690, 1765) - assert DETAIL_UI_V2_0_ONE_TASK["countdown_full"] == (760, 1355, 1035, 1455) - assert DETAIL_UI_V2_0_ONE_TASK["task_list"] == (55, 1935, 900, 2055) - assert DETAIL_UI_V2_0_ONE_TASK["task_count"] == (890, 1855, 1040, 1950) - assert DETAIL_UI_V2_0_ONE_TASK["participants"] == (535, 1375, 760, 1475) - assert DETAIL_UI_V2_0_ONE_TASK["button"] == (70, 2055, 1010, 2225) + assert DETAIL_UI_V2_0_ONE_TASK["content"] == (360, 1460, 1035, 1545) + assert DETAIL_UI_V2_0_ONE_TASK["value"] == (350, 1640, 760, 1735) + assert DETAIL_UI_V2_0_ONE_TASK["countdown_full"] == (730, 1338, 1038, 1418) + assert DETAIL_UI_V2_0_ONE_TASK["info_line"] == (430, 1315, 1055, 1435) + assert DETAIL_UI_V2_0_ONE_TASK["task_list"] == (60, 1845, 885, 2005) + assert DETAIL_UI_V2_0_ONE_TASK["task_count"] == (890, 1855, 1040, 1960) + assert DETAIL_UI_V2_0_ONE_TASK["participants"] == (516, 1396, 743, 1443) + assert DETAIL_UI_V2_0_ONE_TASK["button"] == (70, 2050, 1010, 2195) assert DETAIL_UI_V2_0_ONE_TASK["task_list"][1] > DETAIL_UI_V2_0["task_list"][1] assert DETAIL_UI_V2_0_ONE_TASK["button"][1] > DETAIL_UI_V2_0["button"][1] +def test_detail_profile_prefers_config_overrides(monkeypatch): + from douyin.fudai.core import coords + + override = { + "fudai_detail_regions": { + "v2_0_two_task": { + "content": [1, 2, 3, 4], + }, + "v2_0_one_task": { + "info_line": [11, 22, 33, 44], + }, + "legacy": { + "button": [101, 202, 303, 404], + }, + }, + "pixel_regions": { + "lottery_result": { + "pixel": [7, 8, 9, 10], + "click": [66, 77, 0, 0], + } + }, + } + + monkeypatch.setattr(coords, "_read_runtime_region_config", lambda: override) + + legacy = coords.get_fudai_detail_profile("legacy") + v2_two = coords.get_fudai_detail_profile("v2_0", task_count=2) + v2_one = coords.get_fudai_detail_profile("v2_0", task_count=1) + lottery = coords.get_lottery_result_confirm_profile("v2_0") + + assert legacy["button"] == (101, 202, 303, 404) + assert v2_two["content"] == (1, 2, 3, 4) + assert v2_one["info_line"] == (11, 22, 33, 44) + assert lottery["pixel"] == (7, 8, 9, 10) + assert lottery["click"] == (66, 77) + + +def test_detail_profile_ignores_invalid_config_overrides(monkeypatch): + from douyin.fudai.core import coords + + monkeypatch.setattr( + coords, + "_read_runtime_region_config", + lambda: { + "fudai_detail_regions": { + "v2_0_two_task": { + "content": [1, 2, 3], + } + } + }, + ) + + profile = coords.get_fudai_detail_profile("v2_0", task_count=2) + assert profile["content"] == coords.DETAIL_UI_V2_0["content"] + + def test_ocr_switch_defaults_and_legacy_disable_compat(): from douyin.fudai.douyin_fudai_core_pkg.ocr_switches import ( FudaiDetailOcrSwitches, diff --git a/tests/test_gui_core_pkg.py b/tests/test_gui_core_pkg.py index ec1f46b..3dcedce 100644 --- a/tests/test_gui_core_pkg.py +++ b/tests/test_gui_core_pkg.py @@ -137,6 +137,27 @@ class TestFudaiDetailOcrGuiConfig: ): assert key in vars_ + def test_build_config_vars_exposes_region_coordinate_fields(self, monkeypatch): + import tkinter as tk + + from gui.components.config_vars import build_config_vars + + monkeypatch.setattr(tk, "StringVar", lambda value="": MagicMock(get=lambda: value, set=lambda _v: None)) + monkeypatch.setattr(tk, "BooleanVar", lambda value=False: MagicMock(get=lambda: value, set=lambda _v: None)) + monkeypatch.setattr(tk, "IntVar", lambda value=0: MagicMock(get=lambda: value, set=lambda _v: None)) + monkeypatch.setattr(tk, "DoubleVar", lambda value=0.0: MagicMock(get=lambda: value, set=lambda _v: None)) + + vars_ = build_config_vars({}) + + for key in ( + "fudai_detail_regions_legacy_content_x1_var", + "fudai_detail_regions_v2_0_two_task_content_x1_var", + "fudai_detail_regions_v2_0_one_task_info_line_x1_var", + "pixel_regions_lottery_result_pixel_x1_var", + "pixel_regions_live_room_icon_bbox_x1_var", + ): + assert key in vars_ + class TestWriteConfig: def test_write_and_read_roundtrip(self): @@ -186,6 +207,31 @@ class TestWriteConfig: assert saved["alpha"] == 1 assert saved["beta"] == 2 + def test_write_config_retries_replace_on_permission_error(self, tmp_path, monkeypatch): + from gui.gui_core_pkg import config as cfg_mod + + cfg_path = tmp_path / "config.json" + cfg_path.write_text(json.dumps({"base": 1}, ensure_ascii=False), encoding="utf-8") + monkeypatch.setattr(cfg_mod, "CONFIG_PATH", str(cfg_path)) + + real_replace = os.replace + calls = {"count": 0} + + def flaky_replace(src, dst): + calls["count"] += 1 + if calls["count"] == 1: + raise PermissionError("locked") + return real_replace(src, dst) + + monkeypatch.setattr(cfg_mod.os, "replace", flaky_replace) + + cfg_mod.write_config({"alpha": 1}) + + saved = json.loads(cfg_path.read_text(encoding="utf-8")) + assert saved["base"] == 1 + assert saved["alpha"] == 1 + assert calls["count"] >= 2 + # ============================================================ # adb.py — find_adb_executable / list_adb_devices / resolve_adb_device diff --git a/tests/test_web_gui_routes_logic.py b/tests/test_web_gui_routes_logic.py index fac8c9d..3d52531 100644 --- a/tests/test_web_gui_routes_logic.py +++ b/tests/test_web_gui_routes_logic.py @@ -140,6 +140,31 @@ def test_config_accepts_fudai_detail_v2_ocr_switches_and_ui_mode(monkeypatch): assert written["fudai_detail_ocr_participants_enabled"] is False +def test_config_accepts_region_coordinate_arrays(monkeypatch): + written = {} + + monkeypatch.setattr(routes, "read_config", lambda: {}) + monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg)) + + status, obj = _post( + "/api/config", + { + "config": { + "fudai_detail_regions.v2_0_one_task.info_line": [430, 1315, 1055, 1435], + "pixel_regions.lottery_result.pixel": ["290", "1300", "790", "1415"], + "pixel_regions.live_room_icon_bbox": [999, 172, 1028, 202], + } + }, + monkeypatch, + ) + + assert status == 200 + assert obj.get("ok") is True + assert written["fudai_detail_regions"]["v2_0_one_task"]["info_line"] == [430, 1315, 1055, 1435] + assert written["pixel_regions"]["lottery_result"]["pixel"] == [290, 1300, 790, 1415] + assert written["pixel_regions"]["live_room_icon_bbox"] == [999, 172, 1028, 202] + + def test_config_rejects_invalid_fudai_detail_ui_mode(monkeypatch): written = {"fudai_detail_ui_mode": "legacy"} diff --git a/tools/dev/web_gui_config_manifest.json b/tools/dev/web_gui_config_manifest.json index a89b43e..eed520e 100644 --- a/tools/dev/web_gui_config_manifest.json +++ b/tools/dev/web_gui_config_manifest.json @@ -29,6 +29,31 @@ "fudai_detail_ocr_task_count_enabled", "fudai_detail_ocr_task_enabled", "fudai_detail_ocr_value_enabled", + "fudai_detail_regions.legacy.button", + "fudai_detail_regions.legacy.content", + "fudai_detail_regions.legacy.countdown_full", + "fudai_detail_regions.legacy.live_title", + "fudai_detail_regions.legacy.participants", + "fudai_detail_regions.legacy.task_count", + "fudai_detail_regions.legacy.task_list", + "fudai_detail_regions.legacy.value", + "fudai_detail_regions.v2_0_one_task.button", + "fudai_detail_regions.v2_0_one_task.content", + "fudai_detail_regions.v2_0_one_task.countdown_full", + "fudai_detail_regions.v2_0_one_task.info_line", + "fudai_detail_regions.v2_0_one_task.live_title", + "fudai_detail_regions.v2_0_one_task.participants", + "fudai_detail_regions.v2_0_one_task.task_count", + "fudai_detail_regions.v2_0_one_task.task_list", + "fudai_detail_regions.v2_0_one_task.value", + "fudai_detail_regions.v2_0_two_task.button", + "fudai_detail_regions.v2_0_two_task.content", + "fudai_detail_regions.v2_0_two_task.countdown_full", + "fudai_detail_regions.v2_0_two_task.live_title", + "fudai_detail_regions.v2_0_two_task.participants", + "fudai_detail_regions.v2_0_two_task.task_count", + "fudai_detail_regions.v2_0_two_task.task_list", + "fudai_detail_regions.v2_0_two_task.value", "fudai_detail_save_debug_images", "fudai_detail_template_threshold", "fudai_detail_ui_mode", @@ -90,6 +115,15 @@ "pixel_detect_live_room_enabled", "pixel_detect_lottery_result_enabled", "pixel_detect_shopping_redpacket_enabled", + "pixel_regions.attend_button", + "pixel_regions.coupon_popup", + "pixel_regions.fansclub_join", + "pixel_regions.fudai_detail_body", + "pixel_regions.live_room_icon_bbox", + "pixel_regions.lottery_result.button", + "pixel_regions.lottery_result.click", + "pixel_regions.lottery_result.pixel", + "pixel_regions.shopping_redpacket", "reenter_live_entry_mode", "reservation_back_swipe_delay", "reservation_back_verify_enabled", @@ -186,6 +220,31 @@ "fudai_detail_ocr_task_count_enabled", "fudai_detail_ocr_task_enabled", "fudai_detail_ocr_value_enabled", + "fudai_detail_regions.legacy.button", + "fudai_detail_regions.legacy.content", + "fudai_detail_regions.legacy.countdown_full", + "fudai_detail_regions.legacy.live_title", + "fudai_detail_regions.legacy.participants", + "fudai_detail_regions.legacy.task_count", + "fudai_detail_regions.legacy.task_list", + "fudai_detail_regions.legacy.value", + "fudai_detail_regions.v2_0_one_task.button", + "fudai_detail_regions.v2_0_one_task.content", + "fudai_detail_regions.v2_0_one_task.countdown_full", + "fudai_detail_regions.v2_0_one_task.info_line", + "fudai_detail_regions.v2_0_one_task.live_title", + "fudai_detail_regions.v2_0_one_task.participants", + "fudai_detail_regions.v2_0_one_task.task_count", + "fudai_detail_regions.v2_0_one_task.task_list", + "fudai_detail_regions.v2_0_one_task.value", + "fudai_detail_regions.v2_0_two_task.button", + "fudai_detail_regions.v2_0_two_task.content", + "fudai_detail_regions.v2_0_two_task.countdown_full", + "fudai_detail_regions.v2_0_two_task.live_title", + "fudai_detail_regions.v2_0_two_task.participants", + "fudai_detail_regions.v2_0_two_task.task_count", + "fudai_detail_regions.v2_0_two_task.task_list", + "fudai_detail_regions.v2_0_two_task.value", "fudai_detail_save_debug_images", "fudai_detail_template_threshold", "fudai_detail_ui_mode", @@ -250,6 +309,15 @@ "pixel_detect_live_room_enabled", "pixel_detect_lottery_result_enabled", "pixel_detect_shopping_redpacket_enabled", + "pixel_regions.attend_button", + "pixel_regions.coupon_popup", + "pixel_regions.fansclub_join", + "pixel_regions.fudai_detail_body", + "pixel_regions.live_room_icon_bbox", + "pixel_regions.lottery_result.button", + "pixel_regions.lottery_result.click", + "pixel_regions.lottery_result.pixel", + "pixel_regions.shopping_redpacket", "reenter_live_entry_mode", "reservation_back_swipe_delay", "reservation_back_verify_enabled", @@ -336,6 +404,31 @@ "fudai_detail_ocr_task_count_enabled", "fudai_detail_ocr_task_enabled", "fudai_detail_ocr_value_enabled", + "fudai_detail_regions.legacy.button", + "fudai_detail_regions.legacy.content", + "fudai_detail_regions.legacy.countdown_full", + "fudai_detail_regions.legacy.live_title", + "fudai_detail_regions.legacy.participants", + "fudai_detail_regions.legacy.task_count", + "fudai_detail_regions.legacy.task_list", + "fudai_detail_regions.legacy.value", + "fudai_detail_regions.v2_0_one_task.button", + "fudai_detail_regions.v2_0_one_task.content", + "fudai_detail_regions.v2_0_one_task.countdown_full", + "fudai_detail_regions.v2_0_one_task.info_line", + "fudai_detail_regions.v2_0_one_task.live_title", + "fudai_detail_regions.v2_0_one_task.participants", + "fudai_detail_regions.v2_0_one_task.task_count", + "fudai_detail_regions.v2_0_one_task.task_list", + "fudai_detail_regions.v2_0_one_task.value", + "fudai_detail_regions.v2_0_two_task.button", + "fudai_detail_regions.v2_0_two_task.content", + "fudai_detail_regions.v2_0_two_task.countdown_full", + "fudai_detail_regions.v2_0_two_task.live_title", + "fudai_detail_regions.v2_0_two_task.participants", + "fudai_detail_regions.v2_0_two_task.task_count", + "fudai_detail_regions.v2_0_two_task.task_list", + "fudai_detail_regions.v2_0_two_task.value", "fudai_detail_save_debug_images", "fudai_detail_template_threshold", "fudai_detail_ui_mode", @@ -402,6 +495,15 @@ "pixel_detect_live_room_enabled", "pixel_detect_lottery_result_enabled", "pixel_detect_shopping_redpacket_enabled", + "pixel_regions.attend_button", + "pixel_regions.coupon_popup", + "pixel_regions.fansclub_join", + "pixel_regions.fudai_detail_body", + "pixel_regions.live_room_icon_bbox", + "pixel_regions.lottery_result.button", + "pixel_regions.lottery_result.click", + "pixel_regions.lottery_result.pixel", + "pixel_regions.shopping_redpacket", "reenter_live_entry_mode", "reservation_back_swipe_delay", "reservation_back_verify_enabled", @@ -488,6 +590,31 @@ "fudai_detail_ocr_task_count_enabled", "fudai_detail_ocr_task_enabled", "fudai_detail_ocr_value_enabled", + "fudai_detail_regions.legacy.button", + "fudai_detail_regions.legacy.content", + "fudai_detail_regions.legacy.countdown_full", + "fudai_detail_regions.legacy.live_title", + "fudai_detail_regions.legacy.participants", + "fudai_detail_regions.legacy.task_count", + "fudai_detail_regions.legacy.task_list", + "fudai_detail_regions.legacy.value", + "fudai_detail_regions.v2_0_one_task.button", + "fudai_detail_regions.v2_0_one_task.content", + "fudai_detail_regions.v2_0_one_task.countdown_full", + "fudai_detail_regions.v2_0_one_task.info_line", + "fudai_detail_regions.v2_0_one_task.live_title", + "fudai_detail_regions.v2_0_one_task.participants", + "fudai_detail_regions.v2_0_one_task.task_count", + "fudai_detail_regions.v2_0_one_task.task_list", + "fudai_detail_regions.v2_0_one_task.value", + "fudai_detail_regions.v2_0_two_task.button", + "fudai_detail_regions.v2_0_two_task.content", + "fudai_detail_regions.v2_0_two_task.countdown_full", + "fudai_detail_regions.v2_0_two_task.live_title", + "fudai_detail_regions.v2_0_two_task.participants", + "fudai_detail_regions.v2_0_two_task.task_count", + "fudai_detail_regions.v2_0_two_task.task_list", + "fudai_detail_regions.v2_0_two_task.value", "fudai_detail_save_debug_images", "fudai_detail_template_threshold", "fudai_detail_ui_mode", @@ -554,6 +681,15 @@ "pixel_detect_live_room_enabled", "pixel_detect_lottery_result_enabled", "pixel_detect_shopping_redpacket_enabled", + "pixel_regions.attend_button", + "pixel_regions.coupon_popup", + "pixel_regions.fansclub_join", + "pixel_regions.fudai_detail_body", + "pixel_regions.live_room_icon_bbox", + "pixel_regions.lottery_result.button", + "pixel_regions.lottery_result.click", + "pixel_regions.lottery_result.pixel", + "pixel_regions.shopping_redpacket", "reenter_live_entry_mode", "reservation_back_swipe_delay", "reservation_back_verify_enabled", diff --git a/tools/diagnostics/check_web_gui_config_sync.py b/tools/diagnostics/check_web_gui_config_sync.py index 5c4f97f..12b1efb 100644 --- a/tools/diagnostics/check_web_gui_config_sync.py +++ b/tools/diagnostics/check_web_gui_config_sync.py @@ -106,6 +106,43 @@ HELPER_CONFIG_KEYS = { "logging.performance_tracking.track_function_calls", } +REGION_CONFIG_KEYS = { + "fudai_detail_regions.legacy.content", + "fudai_detail_regions.legacy.value", + "fudai_detail_regions.legacy.countdown_full", + "fudai_detail_regions.legacy.task_list", + "fudai_detail_regions.legacy.task_count", + "fudai_detail_regions.legacy.participants", + "fudai_detail_regions.legacy.button", + "fudai_detail_regions.legacy.live_title", + "fudai_detail_regions.v2_0_two_task.content", + "fudai_detail_regions.v2_0_two_task.value", + "fudai_detail_regions.v2_0_two_task.countdown_full", + "fudai_detail_regions.v2_0_two_task.task_list", + "fudai_detail_regions.v2_0_two_task.task_count", + "fudai_detail_regions.v2_0_two_task.participants", + "fudai_detail_regions.v2_0_two_task.button", + "fudai_detail_regions.v2_0_two_task.live_title", + "fudai_detail_regions.v2_0_one_task.content", + "fudai_detail_regions.v2_0_one_task.value", + "fudai_detail_regions.v2_0_one_task.countdown_full", + "fudai_detail_regions.v2_0_one_task.info_line", + "fudai_detail_regions.v2_0_one_task.task_list", + "fudai_detail_regions.v2_0_one_task.task_count", + "fudai_detail_regions.v2_0_one_task.participants", + "fudai_detail_regions.v2_0_one_task.button", + "fudai_detail_regions.v2_0_one_task.live_title", + "pixel_regions.lottery_result.button", + "pixel_regions.lottery_result.pixel", + "pixel_regions.lottery_result.click", + "pixel_regions.attend_button", + "pixel_regions.fansclub_join", + "pixel_regions.coupon_popup", + "pixel_regions.shopping_redpacket", + "pixel_regions.fudai_detail_body", + "pixel_regions.live_room_icon_bbox", +} + def _read(path: Path) -> str: return path.read_text(encoding="utf-8", errors="ignore") @@ -131,6 +168,8 @@ def extract_gui_saved_keys(source: str) -> set[str]: keys.update(FUDAI_DETAIL_OCR_KEYS) if "pixel_detect_fudai_icon_enabled" in block: keys.update(DETECTION_SWITCH_KEYS) + if "fudai_detail_regions" in block or "pixel_regions" in block: + keys.update(REGION_CONFIG_KEYS) return keys @@ -161,12 +200,17 @@ def extract_gui_loaded_keys(source: str) -> set[str]: keys.update(FUDAI_DETAIL_OCR_KEYS) if "pixel_detect_fudai_icon_enabled" in block: keys.update(DETECTION_SWITCH_KEYS) + if "fudai_detail_regions" in block or "pixel_regions" in block: + keys.update(REGION_CONFIG_KEYS) return {key for key in keys if key not in IGNORED_CONTAINER_KEYS} def extract_web_keys(source: str) -> set[str]: keys = set(re.findall(r'data-key="([^"]+)"', source)) keys.update(re.findall(r'data-mirror-key="([^"]+)"', source)) + keys = {key for key in keys if "${" not in key} + if "fudai_detail_regions" in source or "pixel_regions" in source: + keys.update(REGION_CONFIG_KEYS) return keys @@ -182,6 +226,9 @@ def build_manifest() -> dict[str, object]: gui_loaded = extract_gui_loaded_keys( config_io_source + "\n" + config_io_helpers_source + "\n" + gui_source + "\n" + realtime_tab_source ) + if "_REGION_CONFIG_SPECS" in config_io_source: + gui_saved.update(REGION_CONFIG_KEYS) + gui_loaded.update(REGION_CONFIG_KEYS) gui_saved.update(HELPER_CONFIG_KEYS) gui_loaded.update(HELPER_CONFIG_KEYS) web_keys = extract_web_keys(web_source) diff --git a/webui/js/config_form.js b/webui/js/config_form.js index d363112..9ec45d8 100644 --- a/webui/js/config_form.js +++ b/webui/js/config_form.js @@ -62,10 +62,25 @@ function coerceValue(type, raw, isCheckbox) { } function applyConfigToUI(cfg) { + const seenIndexedKeys = new Set(); for (const el of getConfigBoundElements()) { const key = el.dataset.key; const type = el.dataset.type || "str"; const val = getConfigValue(cfg, key); + const indexAttr = el.dataset.index; + const hasIndex = typeof indexAttr !== "undefined"; + + if (hasIndex) { + if (seenIndexedKeys.has(key)) continue; + seenIndexedKeys.add(key); + const grouped = document.querySelectorAll(`[data-key="${CSS.escape(key)}"][data-index]`); + const useVal = Array.isArray(val) ? val : (Array.isArray(DEFAULTS[key]) ? DEFAULTS[key] : []); + grouped.forEach((field) => { + const idx = parseInt(field.dataset.index || "-1", 10); + field.value = Number.isInteger(idx) && idx >= 0 ? String(useVal[idx] ?? 0) : "0"; + }); + continue; + } // undefined/null 都视为“未配置”:保留页面默认值 const hasVal = !(typeof val === "undefined" || val === null); @@ -86,10 +101,18 @@ function applyConfigToUI(cfg) { function collectConfigFromUI() { const out = {}; + const indexed = new Map(); for (const el of getConfigBoundElements()) { const key = el.dataset.key; const type = el.dataset.type || "str"; + const indexAttr = el.dataset.index; if (!key) continue; + if (typeof indexAttr !== "undefined") { + const idx = parseInt(indexAttr, 10); + if (!indexed.has(key)) indexed.set(key, [0, 0, 0, 0]); + indexed.get(key)[idx] = coerceValue("int", el.value, false); + continue; + } if (el.type === "checkbox") { out[key] = coerceValue(type, el.checked, true); @@ -97,6 +120,7 @@ function collectConfigFromUI() { out[key] = coerceValue(type, el.value, false); } } + for (const [key, value] of indexed.entries()) out[key] = value; return out; } diff --git a/webui/js/config_panel_templates.js b/webui/js/config_panel_templates.js index 6799616..2265c39 100644 --- a/webui/js/config_panel_templates.js +++ b/webui/js/config_panel_templates.js @@ -2,6 +2,78 @@ (function mountConfigPanelTemplates() { const mount = document.getElementById("configPanelTemplatesMount"); if (!mount) return; + const regionFields = [ + { + title: "legacy OCR", + items: [ + ["fudai_detail_regions.legacy.content", "内容"], + ["fudai_detail_regions.legacy.value", "价值"], + ["fudai_detail_regions.legacy.countdown_full", "倒计时"], + ["fudai_detail_regions.legacy.task_list", "任务列表"], + ["fudai_detail_regions.legacy.task_count", "任务数量"], + ["fudai_detail_regions.legacy.participants", "人数"], + ["fudai_detail_regions.legacy.button", "按钮"], + ["fudai_detail_regions.legacy.live_title", "直播间标题"], + ], + }, + { + title: "v2_0 two task OCR", + items: [ + ["fudai_detail_regions.v2_0_two_task.content", "内容"], + ["fudai_detail_regions.v2_0_two_task.value", "价值"], + ["fudai_detail_regions.v2_0_two_task.countdown_full", "倒计时"], + ["fudai_detail_regions.v2_0_two_task.task_list", "任务列表"], + ["fudai_detail_regions.v2_0_two_task.task_count", "任务数量"], + ["fudai_detail_regions.v2_0_two_task.participants", "人数"], + ["fudai_detail_regions.v2_0_two_task.button", "按钮"], + ["fudai_detail_regions.v2_0_two_task.live_title", "直播间标题"], + ], + }, + { + title: "v2_0 one task OCR", + items: [ + ["fudai_detail_regions.v2_0_one_task.content", "内容"], + ["fudai_detail_regions.v2_0_one_task.value", "价值"], + ["fudai_detail_regions.v2_0_one_task.countdown_full", "倒计时"], + ["fudai_detail_regions.v2_0_one_task.info_line", "信息行"], + ["fudai_detail_regions.v2_0_one_task.task_list", "任务列表"], + ["fudai_detail_regions.v2_0_one_task.task_count", "任务数量"], + ["fudai_detail_regions.v2_0_one_task.participants", "人数"], + ["fudai_detail_regions.v2_0_one_task.button", "按钮"], + ["fudai_detail_regions.v2_0_one_task.live_title", "直播间标题"], + ], + }, + { + title: "像素检测区域", + items: [ + ["pixel_regions.lottery_result.button", "开奖按钮"], + ["pixel_regions.lottery_result.pixel", "开奖像素"], + ["pixel_regions.lottery_result.click", "开奖点击"], + ["pixel_regions.attend_button", "参与按钮"], + ["pixel_regions.fansclub_join", "粉丝团"], + ["pixel_regions.coupon_popup", "优惠券"], + ["pixel_regions.shopping_redpacket", "购物红包"], + ["pixel_regions.fudai_detail_body", "详情主体"], + ["pixel_regions.live_room_icon_bbox", "直播间图标bbox"], + ], + }, + ]; + const renderRegionInputs = (key, label) => { + const safe = key.replace(/[^a-zA-Z0-9_]/g, "_"); + const axes = ["x1", "y1", "x2", "y2"]; + return ` +
+
+
+
+
+
+ `; + }; + const regionSectionsHtml = regionFields.map((section) => ` +
${section.title}
+ ${section.items.map(([key, label]) => renderRegionInputs(key, label)).join("")} + `).join(""); mount.innerHTML = `