diff --git a/douyin/fudai/core/coords.py b/douyin/fudai/core/coords.py index 0ea8df6..0171d76 100644 --- a/douyin/fudai/core/coords.py +++ b/douyin/fudai/core/coords.py @@ -124,7 +124,7 @@ DETAIL_UI_LEGACY = { DETAIL_UI_V2_0 = { "version": "v2_0", "content": (365, 1368, 1040, 1465), - "value": (300, 1518, 650, 1615), + "value": (300, 1518, 820, 1695), "countdown_full": (760, 1265, 1040, 1345), "task_list": (60, 1840, 1030, 2005), "task_count": (860, 1770, 1035, 1875), @@ -158,7 +158,7 @@ STALE_DETAIL_REGION_DEFAULTS = { "content": (360, 1410, 1035, 1495), "value": (300, 1585, 650, 1685), "countdown_full": (760, 1328, 1038, 1398), - } + }, } PIXEL_REGION_DEFAULTS = { diff --git a/douyin/fudai/douyin_fudai_finder_pkg/detector.py b/douyin/fudai/douyin_fudai_finder_pkg/detector.py index 0b31c83..044e413 100644 --- a/douyin/fudai/douyin_fudai_finder_pkg/detector.py +++ b/douyin/fudai/douyin_fudai_finder_pkg/detector.py @@ -718,6 +718,112 @@ class FudaiDetector: except Exception as exc: return False, {"commercial_overlay_error": str(exc)} + def _is_commercial_redpacket_widget(self, arr: Any) -> Tuple[bool, Dict[str, Any]]: + """Detect left-side shopping/live redpacket widgets near the fudai slot.""" + try: + import numpy as np # type: ignore[import-untyped] + + height, width = arr.shape[:2] + if height <= 0 or width <= 0: + return False, {"reason": "empty_window"} + + r = arr[:, :, 0] + g = arr[:, :, 1] + b = arr[:, :, 2] + + pink_body = ( + (r >= 205) + & (g >= 25) + & (g <= 120) + & (b >= 95) + & (b <= 190) + ) + pale_badge = (r >= 230) & (g >= 150) & (b >= 130) + orange_badge = (r >= 220) & (g >= 120) & (g <= 205) & (b <= 120) + avatar_like = ( + (r >= 85) + & (r <= 245) + & (g >= 45) + & (g <= 210) + & (b >= 25) + & (b <= 190) + ) + + pink_area, pink_box = self._largest_component_box(pink_body) + avatar_band = avatar_like[: max(1, int(height * 0.45)), :] + avatar_area, avatar_box = self._largest_component_box(avatar_band) + badge_area, badge_box = self._largest_component_box(pale_badge | orange_badge) + pink_ratio = float(np.mean(pink_body)) if pink_body.size else 0.0 + + pink_large = False + if pink_box is not None: + _px, _py, pw, ph = pink_box + pink_large = pink_area >= 1000 and pw >= 35 and ph >= 40 + + avatar_large = False + if avatar_box is not None: + _ax, ay, aw, ah = avatar_box + avatar_large = avatar_area >= 500 and aw >= 22 and ah >= 22 and ay <= height * 0.45 + + badge_present = badge_area >= 80 + redpacket_like = pink_large and avatar_large and badge_present and pink_ratio >= 0.04 + return bool(redpacket_like), { + "pink_ratio": round(pink_ratio, 4), + "pink_area": pink_area, + "pink_box": pink_box, + "avatar_area": avatar_area, + "avatar_box": avatar_box, + "badge_area": badge_area, + "badge_box": badge_box, + } + except Exception as exc: + return False, {"redpacket_widget_error": str(exc)} + + def _has_redpacket_neighbor_widget( + self, pic: Image.Image, detected_x: int + ) -> Tuple[bool, Dict[str, Any]]: + """Detect a redpacket/popularity widget immediately to the right.""" + try: + import numpy as np # type: ignore[import-untyped] + + width, height = pic.size + detected_x_scaled = int(detected_x * self.rx / 1080) + x1 = max(0, detected_x_scaled + 35) + x2 = min(width, detected_x_scaled + 210) + y1 = max(0, int(300 * self.ry / 2400) + self.y_pianyi) + y2 = min(height, int(520 * self.ry / 2400) + self.y_pianyi) + if x1 >= x2 or y1 >= y2: + return False, {"reason": "empty_neighbor"} + + arr = np.asarray(pic.crop((x1, y1, x2, y2)).convert("RGB")) + r = arr[:, :, 0] + g = arr[:, :, 1] + b = arr[:, :, 2] + pink = (r >= 200) & (g <= 115) & (b >= 85) & (b <= 210) + red = (r >= 190) & (g <= 110) & (b <= 130) + white = (r >= 220) & (g >= 220) & (b >= 220) + dark = (r <= 80) & (g <= 80) & (b <= 95) + + pink_ratio = float(np.mean(pink)) if pink.size else 0.0 + red_ratio = float(np.mean(red)) if red.size else 0.0 + white_ratio = float(np.mean(white)) if white.size else 0.0 + dark_ratio = float(np.mean(dark)) if dark.size else 0.0 + widget_like = ( + white_ratio >= 0.35 + and pink_ratio >= 0.06 + and red_ratio >= 0.06 + and dark_ratio <= 0.12 + ) + return bool(widget_like), { + "pink_ratio": round(pink_ratio, 4), + "red_ratio": round(red_ratio, 4), + "white_ratio": round(white_ratio, 4), + "dark_ratio": round(dark_ratio, 4), + "neighbor": (x1, y1, x2, y2), + } + except Exception as exc: + return False, {"redpacket_neighbor_error": str(exc)} + def confirm_pixel_candidate_shape(self, pic: Image.Image, detected_x: int) -> bool: """Validate that the pixel hit has the compact shape of a fudai badge.""" try: @@ -748,8 +854,14 @@ class FudaiDetector: valid_cols = int(np.sum(cols >= 2)) max_col = int(np.max(cols)) if cols.size else 0 commercial_overlay, commercial_info = self._is_commercial_coupon_overlay(arr) + redpacket_widget, redpacket_info = self._is_commercial_redpacket_widget(arr) + redpacket_neighbor, redpacket_neighbor_info = self._has_redpacket_neighbor_widget( + pic, detected_x + ) passed = ( not commercial_overlay + and not redpacket_widget + and not redpacket_neighbor and 20 <= total <= 120 and 6 <= valid_cols <= 45 and 2 <= max_col <= 10 @@ -765,6 +877,10 @@ class FudaiDetector: max_col=max_col, commercial_overlay=commercial_overlay, commercial_info=commercial_info, + redpacket_widget=redpacket_widget, + redpacket_info=redpacket_info, + redpacket_neighbor=redpacket_neighbor, + redpacket_neighbor_info=redpacket_neighbor_info, window=(x1, y1, x2, y2), ) except Exception: diff --git a/douyin/handlers/screenshot_manager/cleanup.py b/douyin/handlers/screenshot_manager/cleanup.py index 7500dc8..6bbd07e 100644 --- a/douyin/handlers/screenshot_manager/cleanup.py +++ b/douyin/handlers/screenshot_manager/cleanup.py @@ -120,6 +120,7 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: # 按日期排序(最旧的在前) dirs_info.sort(key=lambda x: x["date"]) + today_name = datetime.now().strftime("%Y-%m-%d") # 先按天数清理:删除超过保留天数的目录 for dir_info in dirs_info[:]: @@ -147,6 +148,14 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: for dir_info in dirs_info[:]: if deleted_files_count >= need_delete_count: break + if dir_info["name"] == today_name: + try: + _mgr_log( + f"[调试图像清理] 保留当天调试图像目录: {dir_info['name']},避免丢失当前测试证据" + ) + except Exception: + pass + continue try: shutil.rmtree(dir_info["path"]) diff --git a/douyin/handlers/screenshot_manager/save_image_helpers.py b/douyin/handlers/screenshot_manager/save_image_helpers.py index 7a41601..ac3ee92 100644 --- a/douyin/handlers/screenshot_manager/save_image_helpers.py +++ b/douyin/handlers/screenshot_manager/save_image_helpers.py @@ -130,6 +130,7 @@ def maybe_auto_cleanup(auto_cleanup: bool, mgr_log) -> None: try: debug_base_dir = get_debug_captures_base_dir() cleanup_marker = os.path.join(debug_base_dir, ".cleanup_marker") + over_limit_marker = os.path.join(debug_base_dir, ".over_limit_marker") today_str = datetime.now().strftime("%Y-%m-%d") need_cleanup = True @@ -167,6 +168,13 @@ def maybe_auto_cleanup(auto_cleanup: bool, mgr_log) -> None: return try: + if os.path.exists(over_limit_marker): + try: + with open(over_limit_marker, "r", encoding="utf-8") as f: + if f.read().strip() == today_str: + return + except Exception: + pass config_path = path_config.get_config_path() max_files = 2000 if os.path.exists(config_path): @@ -181,7 +189,17 @@ def maybe_auto_cleanup(auto_cleanup: bool, mgr_log) -> None: mgr_log(f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理") except Exception: pass - cleanup_debug_captures(keep_days=999, max_files=max_files) + deleted = cleanup_debug_captures(keep_days=999, max_files=max_files) + if deleted == 0: + try: + mgr_log("[调试图像清理] 当前仅保留当天测试证据,本日跳过后续超限扫描") + except Exception: + pass + try: + with open(over_limit_marker, "w", encoding="utf-8") as f: + f.write(today_str) + except Exception: + pass except Exception: pass except Exception: diff --git a/tests/fixtures/fudai_detail_v2_two_task_guohao_1199_regions.png b/tests/fixtures/fudai_detail_v2_two_task_guohao_1199_regions.png new file mode 100644 index 0000000..05a3987 Binary files /dev/null and b/tests/fixtures/fudai_detail_v2_two_task_guohao_1199_regions.png differ diff --git a/tests/fixtures/fudai_detail_v2_two_task_redmi_2999_regions.png b/tests/fixtures/fudai_detail_v2_two_task_redmi_2999_regions.png new file mode 100644 index 0000000..919823d Binary files /dev/null and b/tests/fixtures/fudai_detail_v2_two_task_redmi_2999_regions.png differ diff --git a/tests/fixtures/fudai_icon_regression/false_shopping_redpacket_left_x168.png b/tests/fixtures/fudai_icon_regression/false_shopping_redpacket_left_x168.png new file mode 100644 index 0000000..7754ac1 Binary files /dev/null and b/tests/fixtures/fudai_icon_regression/false_shopping_redpacket_left_x168.png differ diff --git a/tests/test_fudai_detail_ui_v2.py b/tests/test_fudai_detail_ui_v2.py index 58b2151..649e8da 100644 --- a/tests/test_fudai_detail_ui_v2.py +++ b/tests/test_fudai_detail_ui_v2.py @@ -29,7 +29,7 @@ def test_v2_profile_keeps_legacy_and_adds_expected_regions(monkeypatch): 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"] == (365, 1368, 1040, 1465) - assert DETAIL_UI_V2_0["value"] == (300, 1518, 650, 1615) + assert DETAIL_UI_V2_0["value"] == (300, 1518, 820, 1695) assert DETAIL_UI_V2_0["countdown_full"] == (760, 1265, 1040, 1345) assert DETAIL_UI_V2_0["task_list"] == (60, 1840, 1030, 2005) assert DETAIL_UI_V2_0["task_count"] == (860, 1770, 1035, 1875) @@ -148,6 +148,33 @@ def test_v2_two_task_profile_covers_batu_4999_sample_regions(): assert crop_has_bright_text(DETAIL_UI_V2_0["content"]) > 0.01 +def test_v2_two_task_value_region_covers_reference_value_line(): + from pathlib import Path + from douyin.fudai.core.coords import DETAIL_UI_V2_0 + + samples = [ + Path("tests/fixtures/fudai_detail_v2_two_task_redmi_2999_regions.png"), + Path("tests/fixtures/fudai_detail_v2_two_task_guohao_1199_regions.png"), + ] + missing = [sample for sample in samples if not sample.exists()] + if missing: + pytest.skip("v2 two-task value samples are unavailable") + + value_box = DETAIL_UI_V2_0["value"] + assert value_box[2] >= 760 + assert value_box[3] >= 1690 + + def crop_has_reference_line_text(sample: Path) -> float: + img = Image.open(sample).convert("RGB") + crop = img.crop((340, 1585, min(value_box[2], 820), min(value_box[3], 1695))) + pixels = list(crop.getdata()) + bright = sum(1 for r, g, b in pixels if r > 185 and g > 185 and b > 185) + return bright / max(1, len(pixels)) + + for sample in samples: + assert crop_has_reference_line_text(sample) > 0.03 + + 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_fudai_finder_pkg.py b/tests/test_fudai_finder_pkg.py index 2f51ee8..f218703 100644 --- a/tests/test_fudai_finder_pkg.py +++ b/tests/test_fudai_finder_pkg.py @@ -42,6 +42,7 @@ ICON_REGRESSION_CASES = [ ("false_left_coupon_x162.png", False, None, None), ("false_no_fudai_light10.png", False, None, None), ("false_right_coupon_strip_x366.png", False, None, None), + ("false_shopping_redpacket_left_x168.png", False, None, None), ] @@ -177,6 +178,20 @@ class TestFudaiDetector: assert elapsed_ms < 5.0 + def test_redpacket_neighbor_detector_rejects_shopping_redpacket_entry(self): + sample = FIXTURE_DIR / "false_shopping_redpacket_left_x168.png" + if not sample.exists(): + pytest.skip("fixture unavailable") + + d = FudaiDetector(FakeAnalyser()) + img = Image.open(sample).convert("RGB") + + redpacket_like, info = d._has_redpacket_neighbor_widget(img, 168) + + assert redpacket_like is True + assert info["white_ratio"] >= 0.35 + assert info["pink_ratio"] >= 0.06 + def test_current_icon_template_confirms_clean_countdown_sample(self): sample = Path( "artifacts/live_fudai_flow_20260618_0530_valid/snapshots/" diff --git a/tests/test_screenshot_manager_pkg.py b/tests/test_screenshot_manager_pkg.py index 29ceaa5..1d36518 100644 --- a/tests/test_screenshot_manager_pkg.py +++ b/tests/test_screenshot_manager_pkg.py @@ -5,6 +5,7 @@ from __future__ import annotations import os +from datetime import datetime import pytest @@ -21,6 +22,7 @@ from douyin.handlers.screenshot_manager import ( get_ocr_dir, reset_async_save_counters, ) +from douyin.handlers.screenshot_manager.cleanup import cleanup_debug_captures # ============================================================ @@ -143,6 +145,26 @@ class TestEnsureDirs: ensure_debug_captures_dir() ensure_debug_captures_dir() + def test_cleanup_keeps_today_debug_captures_when_file_limit_exceeded( + self, tmp_path, monkeypatch + ): + base_dir = tmp_path / "debug_captures" + today_dir = base_dir / datetime.now().strftime("%Y-%m-%d") + today_dir.mkdir(parents=True) + for index in range(3): + (today_dir / f"capture_{index}.png").write_bytes(b"png") + + monkeypatch.setattr( + "douyin.handlers.screenshot_manager.cleanup.get_debug_captures_base_dir", + lambda: str(base_dir), + ) + + deleted = cleanup_debug_captures(keep_days=999, max_files=1) + + assert deleted == 0 + assert today_dir.exists() + assert len(list(today_dir.glob("*.png"))) == 3 + # ============================================================ # _common.py — 异步计数器 diff --git a/tests/test_screenshot_manager_submodules.py b/tests/test_screenshot_manager_submodules.py index b5d9db0..ae43444 100644 --- a/tests/test_screenshot_manager_submodules.py +++ b/tests/test_screenshot_manager_submodules.py @@ -223,6 +223,40 @@ class TestSaveImageModule: if g >= 160 and r <= 80 and b <= 120: green_pixels += 1 assert green_pixels > 20 + + def test_maybe_auto_cleanup_skips_repeated_same_day_over_limit_scan( + self, tmp_path, monkeypatch + ): + from datetime import datetime + from douyin.handlers.screenshot_manager import save_image_helpers as helpers + + debug_base = tmp_path / "debug_captures" + debug_base.mkdir() + today = datetime.now().strftime("%Y-%m-%d") + (debug_base / ".cleanup_marker").write_text(today, encoding="utf-8") + config_path = tmp_path / "config.json" + config_path.write_text( + '{"debug_captures":{"max_files":1}}', + encoding="utf-8", + ) + calls = {"count": 0} + + monkeypatch.setattr(helpers, "get_debug_captures_base_dir", lambda: str(debug_base)) + monkeypatch.setattr( + "douyin.handlers.screenshot_manager.save_image_helpers.path_config.get_config_path", + lambda: str(config_path), + ) + monkeypatch.setattr( + helpers, + "count_debug_captures_files", + lambda: calls.__setitem__("count", calls["count"] + 1) or 2, + ) + monkeypatch.setattr(helpers, "cleanup_debug_captures", lambda **_kwargs: 0) + + helpers.maybe_auto_cleanup(True, lambda _msg: None) + helpers.maybe_auto_cleanup(True, lambda _msg: None) + + assert calls["count"] == 1 class TestScreenshotManagerSubmodules: