From dc6ae7d1e4d82bf12aa61543dd698ed054fdb864 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 4 Jun 2026 11:15:45 +0800 Subject: [PATCH] fix task count digit detection --- assets/fudai_task_count_digit_1.png | Bin 0 -> 548 bytes assets/fudai_task_count_digit_2.png | Bin 0 -> 1208 bytes douyin/detection/detection_pkg/detail.py | 321 +++++++++++++++++++---- douyin/detection/pixel/stage.py | 18 +- tests/test_detection_pixel.py | 10 +- tests/test_fudai_detail_ui_v2.py | 125 +++++++-- 6 files changed, 400 insertions(+), 74 deletions(-) create mode 100644 assets/fudai_task_count_digit_1.png create mode 100644 assets/fudai_task_count_digit_2.png diff --git a/assets/fudai_task_count_digit_1.png b/assets/fudai_task_count_digit_1.png new file mode 100644 index 0000000000000000000000000000000000000000..0fb8f76ca4d3b37ad055704a60e67ce9220700ba GIT binary patch literal 548 zcmV+<0^9wGP)*M^6x%AFCL!WX0z-W#kU)OeqFszu3sj% z(|15PT^+ze`@a72@%j2?ax{5vty@_sD4-OYU|Ax{Ky1=1+mDMF z<^E>J44u{!J>*YHM+Hx0hln^t5e3c_F=*l}aIQ{Wm&m@ixcbd9bEf73)dJaZDppl^ zxt(PqeI9uf{4eI5T?#<{%Q}qq>nx6mjAUvTsipw+Dk-0HYZ8kzAg8O%r7A>3f|$<} z#2Xwf7heG)8!N@GfzZ;_%v(xlf;1V;D_jjDnUeOG64t_goH+s&IqU7>d57gi0G)r4 zQuY+dVP1r-HAf}rkkcs5Cf8hVBkIu8d8((%iWH=-^du=qc2lE8Dyc6;b2FdEVWgns m*=QqeurkvMt5ulP0Pq7SN726E{xT*20000A355T04T#4mQ-ByN+)`DvOsX#zt0s9X>dP$YUraDqdmo>37$xuHrupo$8C3PSCH z3qpt!;)HsDOAiGE2QE~CG&D{^+9siiow)vs?Kfz4cK5AIe^@1XdAl<^v)_F4?ZeUR ziwHmfL|_M^e((eW`U?uY0058mrp_Oo$_8B)jr(rWB07D2_4}QY zyfUCuVR&J7IvWIn+5?;!FvR!s6OX1-=2hwU-h^@%ZK7|tw!hmc{#|b*0H=Gx`P|Sm zeHmwvKwLOHdh(AY_CJyBpG)`n&TlOhu9Ws12X5~-f7va+H#zp|&>?5`L?%6x3YV&N z^~zv83jkkkZ2ef;Gxd#3wE*FxwVTCO)3zLCJzQP)zd z1w_HA#p^Mlq+y)9rn@CH&8AGvWGq%{L=c#ayntRq#G@|=p7l!DBKmdj4k84O&(dLT z#0S;k=W|0T=7@>*!%nf(Yyv_|8|TZI#iyW%Xr`xUJ~!kH+eDw=*pl8<-1D6q2-?!i zK#)$TbJG)n&_LUMz46aVy)JKx1>!#`*yci1a5jHrA`IP1q29P~V?(S_`p1>U{dHA( zcYN%*{sYdr+K%42w$g}nJrM{o(2dOL%1)j(z{!!}*N27OJl!H#SSqa4Yg|(eJF zOcLkJ;Mxsd9z6Kwc+M~3nZnx7yX6kFi1m}SING3^0mrlbrzgi+B}^;?&=cbp-Y z4f!_!EvRwgNXL3JALNfHNk=<>wR!uCTbsth83GUHpO8do_ed&res-$cz{=*Awu>LH zuA9U>f=BwPd_A2Alb_AzdlO1p7Xf}MmCr1%-9>1In$JuCWcW`2gWX*h=ccn=tmqQq zYNfjHSE1!!5U#*B-#``)BoY_rrgKS_1Q~@|{nX-eO-e0PL{OU85lf341R2N>)h9>u z`JT`ndTYP=#^Q3Z)iO1Sm7udbiTH~7aAxvJRxxwtJMHN0YlZD*Gbx=U!EC}BY@s)B zPUjwfZ9X?_s_Ze>|Nnktv077OVbVEwbn(NS#aP{Q_Wuqd^-!M&Ziko~c;52YFv|&< zOqm8VYvxVENz#8- int: if ui_mode == "legacy": return _check_detail_task_count_legacy_pixels(analyser) - detected_v2_pixels = _check_detail_task_count_v2_pixels(analyser) - if detected_v2_pixels: - return detected_v2_pixels + detected_v2_template = _check_detail_task_count_v2(analyser) + if detected_v2_template: + return detected_v2_template return 0 @@ -268,7 +268,7 @@ def _check_detail_task_count_legacy_pixels(analyser: Any) -> int: def _check_detail_task_count_v2_pixels(analyser: Any) -> int: - """Fast v2 task-count decision from popup height pixels before OCR regions are chosen.""" + """Fast v2 task-count decision from scanning the dark task-card top edge.""" try: from douyin.fudai.core.coords import normalize_fudai_detail_ui_mode @@ -299,16 +299,33 @@ def _check_detail_task_count_v2_pixels(analyser: Any) -> int: except Exception: ry = 2400 - x = 536 * rx // 1080 - y_task_text = 1970 * ry // 2400 - y_task_card = 1955 * ry // 2400 - if not (0 <= x < width and 0 <= y_task_text < height and 0 <= y_task_card < height): + # 快速区分 two-task:你提供的上方大横带在 two-task 样本里深色命中明显更多。 + upper_x_start = 2 * rx // 1080 + upper_x_end = 1075 * rx // 1080 + upper_y_start = 1018 * ry // 2400 + upper_y_end = 1080 * ry // 2400 + # one-task 兜底:保留较低位置的任务卡顶部横带检测。 + lower_x_start = 420 * rx // 1080 + lower_x_end = 860 * rx // 1080 + lower_y_band = 1866 * ry // 2400 + legacy_two_task_y1 = 1686 * ry // 2400 + legacy_two_task_y2 = 1788 * ry // 2400 + if not ( + 0 <= upper_x_start < width + and 0 < upper_x_end <= width + and upper_x_start < upper_x_end + and 0 <= upper_y_start < height + and 0 < upper_y_end <= height + and upper_y_start < upper_y_end + and 0 <= lower_x_start < width + and 0 < lower_x_end <= width + and lower_x_start < lower_x_end + and 0 <= lower_y_band < height + and 0 <= legacy_two_task_y1 < height + and 0 <= legacy_two_task_y2 < height + ): return 0 - def _rgb_at(y_coord: int) -> tuple[int, int, int]: - p = pic.getpixel((x, y_coord)) - return int(p[0]), int(p[1]), int(p[2]) - def _is_white_text(pixel: tuple[int, int, int]) -> bool: r, g, b = pixel return r >= 215 and g >= 215 and b >= 215 @@ -317,22 +334,65 @@ def _check_detail_task_count_v2_pixels(analyser: Any) -> int: r, g, b = pixel return 5 <= r <= 45 and 10 <= g <= 55 and 35 <= b <= 95 + upper_sample_xs = [ + int(v) + for v in ( + upper_x_start, + upper_x_start + (upper_x_end - upper_x_start) * 0.2, + upper_x_start + (upper_x_end - upper_x_start) * 0.4, + upper_x_start + (upper_x_end - upper_x_start) * 0.6, + upper_x_start + (upper_x_end - upper_x_start) * 0.8, + upper_x_end - 1, + ) + ] + upper_sample_xs = [x for x in upper_sample_xs if 0 <= x < width] + lower_sample_xs = [ + int(v) + for v in ( + lower_x_start, + lower_x_start + (lower_x_end - lower_x_start) * 0.25, + lower_x_start + (lower_x_end - lower_x_start) * 0.5, + lower_x_start + (lower_x_end - lower_x_start) * 0.75, + lower_x_end - 1, + ) + ] + lower_sample_xs = [x for x in lower_sample_xs if 0 <= x < width] + + def _dark_hits_at_y(y_coord: int, xs: list[int]) -> int: + hits = 0 + for sx in xs: + try: + pixel = pic.getpixel((sx, y_coord)) + except Exception: + continue + if _is_dark_card((int(pixel[0]), int(pixel[1]), int(pixel[2]))): + hits += 1 + return hits + + upper_band_dark_sum = 0 + lower_band_dark_hits = 0 + legacy_two_task_hits_1 = 0 + legacy_two_task_hits_2 = 0 try: - task_text_pixel = _rgb_at(y_task_text) - task_card_pixel = _rgb_at(y_task_card) + for y_coord in range(upper_y_start, upper_y_end + 1, max(1, 4 * ry // 2400)): + upper_band_dark_sum += _dark_hits_at_y(y_coord, upper_sample_xs) + lower_band_dark_hits = _dark_hits_at_y(lower_y_band, lower_sample_xs) + legacy_two_task_hits_1 = _dark_hits_at_y(legacy_two_task_y1, lower_sample_xs) + legacy_two_task_hits_2 = _dark_hits_at_y(legacy_two_task_y2, lower_sample_xs) except Exception: return 0 - # 当前 2.0 UI:一个任务时中线 y=1970 命中任务文案白字; - # 两个任务时同点仍是任务卡片深色背景。先用这个高度差选 profile。 detected = 0 reason = "" - if _is_white_text(task_text_pixel): - detected = 1 - reason = "task_text_white_at_v2_one_task_y" - elif _is_dark_card(task_text_pixel) and _is_dark_card(task_card_pixel): + if upper_band_dark_sum >= 36: detected = 2 - reason = "dark_card_continues_at_v2_two_task_y" + reason = "upper_band_dark_sum_two_task" + elif legacy_two_task_hits_1 >= 3 and legacy_two_task_hits_2 >= 3: + detected = 2 + reason = "legacy_two_task_band_hits" + elif lower_band_dark_hits >= 3: + detected = 1 + reason = "lower_band_dark_hits_one_task" if detected: try: @@ -349,11 +409,21 @@ def _check_detail_task_count_v2_pixels(analyser: Any) -> int: task_count=detected, source="v2_pixels", reason=reason, - check_x=x, - task_text_y=y_task_text, - task_text_pixel=task_text_pixel, - task_card_y=y_task_card, - task_card_pixel=task_card_pixel, + upper_x_start=upper_x_start, + upper_x_end=upper_x_end, + upper_y_start=upper_y_start, + upper_y_end=upper_y_end, + upper_sample_xs=",".join(str(v) for v in upper_sample_xs), + upper_band_dark_sum=upper_band_dark_sum, + lower_x_start=lower_x_start, + lower_x_end=lower_x_end, + lower_y_band=lower_y_band, + lower_sample_xs=",".join(str(v) for v in lower_sample_xs), + lower_band_dark_hits=lower_band_dark_hits, + legacy_two_task_y1=legacy_two_task_y1, + legacy_two_task_y2=legacy_two_task_y2, + legacy_two_task_hits_1=legacy_two_task_hits_1, + legacy_two_task_hits_2=legacy_two_task_hits_2, ui_mode=ui_mode, log_type="DEBUG", ) @@ -363,47 +433,196 @@ def _check_detail_task_count_v2_pixels(analyser: Any) -> int: def _check_detail_task_count_v2(analyser: Any) -> int: - """Fast v2 detail task-count OCR: parse denominator from '(1/2)'.""" + """Fast v2 detail task-count recognition by matching the task-count digit only.""" try: + import cv2 # type: ignore[import-untyped] + import numpy as np # type: ignore[import-untyped] + from PIL import Image + from douyin.core import path_config from douyin.fudai.core.coords import DETAIL_UI_V2_0, DETAIL_UI_V2_0_ONE_TASK - for name, profile in ( - ("福袋任务数量_v2_1task", DETAIL_UI_V2_0_ONE_TASK), - ("福袋任务数量_v2", DETAIL_UI_V2_0), - ): - box = tuple(profile.get("task_count") or ()) - if len(box) != 4: + pic_path = path_config.get_screenshot_path() + if not os.path.exists(pic_path): + return 0 + pic = Image.open(pic_path).convert("RGB") + pic_rgb = np.asarray(pic) + pic_gray = cv2.cvtColor(pic_rgb, cv2.COLOR_RGB2GRAY) + + def _pink_digit_mask(rgb_arr: Any) -> Any: + r = rgb_arr[:, :, 0].astype(np.int16) + g = rgb_arr[:, :, 1].astype(np.int16) + b = rgb_arr[:, :, 2].astype(np.int16) + return ( + (r > 145) + & (g > 25) + & (g < 170) + & (b > 60) + & (b < 220) + & ((r - g) > 45) + & ((b - g) > 10) + ) + + def _mask_iou(mask_a: Any, mask_b: Any) -> float: + intersection = np.logical_and(mask_a, mask_b).sum() + union = np.logical_or(mask_a, mask_b).sum() + return float(intersection / union) if union else 0.0 + + assets_dir = path_config.get_assets_dir() + candidates = ( + ( + 1, + "one_task", + tuple(DETAIL_UI_V2_0_ONE_TASK.get("task_count") or ()), + os.path.join(assets_dir, "fudai_task_count_digit_1.png"), + ), + ( + 2, + "two_task", + tuple(DETAIL_UI_V2_0.get("task_count") or ()), + os.path.join(assets_dir, "fudai_task_count_digit_2.png"), + ), + ) + + best_count = 0 + best_score = -1.0 + best_variant = "" + best_box = None + best_passes = False + for task_count, variant, box, template_path in candidates: + if len(box) != 4 or not os.path.exists(template_path): continue - if hasattr(analyser, "cut_pic"): - analyser.cut_pic(*box, "", name, getattr(analyser, "y_pianyi", 0)) - raw = "" - try: - raw = str(analyser.operation.analyse_pic_word(name, 0) or "") - except Exception: - raw = str(analyser.operation.analyse_pic_digits(name, 0) or "") - m = re.search(r"[\(/(]\s*\d+\s*[//]\s*([1-3])\s*[\))]?", raw) - if not m: - m = re.search(r"\d+\s*[//]\s*([1-3])", raw) - if not m: + digit_box = get_detail_task_count_digit_box(tuple(int(v) for v in box)) + x1, y1, x2, y2 = digit_box + roi_full = pic_gray[y1:y2, x1:x2] + roi_rgb = pic_rgb[y1:y2, x1:x2] + if roi_full.size == 0: continue - task_count = int(m.group(1)) + template = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE) + if template is None: + continue + template_rgb = np.asarray(Image.open(template_path).convert("RGB")) + rh, rw = roi_full.shape[:2] + th, tw = template.shape[:2] + if th <= 0 or tw <= 0 or rh <= 0 or rw <= 0: + continue + w = min(rw, tw) + h = min(rh, th) + roi_resized = cv2.resize(roi_full, (w, h)) + tpl_resized = cv2.resize(template, (w, h)) + roi_rgb_resized = cv2.resize(roi_rgb, (w, h), interpolation=cv2.INTER_NEAREST) + tpl_rgb_resized = cv2.resize(template_rgb, (w, h), interpolation=cv2.INTER_NEAREST) + + roi_eq = cv2.equalizeHist(roi_resized) + tpl_eq = cv2.equalizeHist(tpl_resized) + score_eq = float( + cv2.matchTemplate(roi_eq, tpl_eq, cv2.TM_CCOEFF_NORMED)[0][0] + ) + + roi_bin = cv2.threshold(roi_resized, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] + tpl_bin = cv2.threshold(tpl_resized, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] + score_bin = float( + cv2.matchTemplate(roi_bin, tpl_bin, cv2.TM_CCOEFF_NORMED)[0][0] + ) + + roi_mask = _pink_digit_mask(roi_rgb_resized) + tpl_mask = _pink_digit_mask(tpl_rgb_resized) + mask_score = _mask_iou(roi_mask, tpl_mask) + roi_mask_pixels = int(roi_mask.sum()) + tpl_mask_pixels = int(tpl_mask.sum()) + + score = max(score_eq, score_bin, mask_score) + passes_digit_mask = ( + mask_score >= 0.30 + and roi_mask_pixels >= max(40, int(tpl_mask_pixels * 0.45)) + ) + passes_full_template = score >= 0.94 + should_replace_best = ( + (passes_full_template or passes_digit_mask) and not best_passes + ) or ( + (passes_full_template or passes_digit_mask) == best_passes + and score > best_score + ) + if should_replace_best: + best_score = score + best_count = task_count + best_variant = variant + best_box = box + best_passes = passes_full_template or passes_digit_mask try: analyser._log_kv( - "检测", - f"识别到福袋任务数量:{task_count}个(v2 OCR)", + "任务数诊断", + "[TASK_COUNT_DIAG] candidate_scored", task_count=task_count, - source="v2_ocr", - profile_variant=str(profile.get("variant") or "default"), - raw=raw[:50], + variant=variant, + digit_box=digit_box, + score_eq=round(score_eq, 4), + score_bin=round(score_bin, 4), + score_mask=round(mask_score, 4), + mask_pixels=roi_mask_pixels, + score=max(round(score, 4), 0.0), ) except Exception: pass - return task_count + + if best_count and best_passes: + try: + setattr(analyser, "_fudai_detail_task_count_source", "v2_template") + analyser._log_kv( + "检测", + f"识别到福袋任务数量:{best_count}个(v2 数字模板匹配)", + task_count=best_count, + source="v2_digit_template", + profile_variant=best_variant, + template_score=round(best_score, 4), + digit_box=get_detail_task_count_digit_box(tuple(int(v) for v in best_box)), + ) + analyser._log_kv( + "任务数诊断", + "[TASK_COUNT_DIAG] matched", + task_count=best_count, + variant=best_variant, + template_score=round(best_score, 4), + digit_box=get_detail_task_count_digit_box(tuple(int(v) for v in best_box)), + ) + except Exception: + pass + return best_count + try: + analyser._log_kv( + "任务数诊断", + "[TASK_COUNT_DIAG] no_match", + best_count=best_count, + best_variant=best_variant, + best_score=round(best_score, 4) if best_score >= 0 else best_score, + ) + except Exception: + pass except Exception: return 0 return 0 +def get_detail_task_count_digit_box(task_count_box: tuple[int, int, int, int]) -> tuple[int, int, int, int]: + """Extract the trailing task-count digit box inside the (0/1)/(1/2) badge.""" + x1, y1, x2, y2 = [int(v) for v in task_count_box] + # one-task and two-task badges have different anchors in current verified samples. + if y1 >= 1830: + digit_x1 = x1 + 86 + digit_x2 = x1 + 98 + digit_y1 = y1 + 16 + digit_y2 = y1 + 46 + else: + digit_x1 = x1 + 114 + digit_x2 = x1 + 135 + digit_y1 = y1 + 44 + digit_y2 = y1 + 75 + if digit_x2 <= digit_x1: + digit_x2 = min(x2, digit_x1 + 1) + if digit_y2 <= digit_y1: + digit_y2 = min(y2, digit_y1 + 1) + return digit_x1, digit_y1, digit_x2, digit_y2 + + def check_in_fudai_detail(analyser: Any) -> bool: diff --git a/douyin/detection/pixel/stage.py b/douyin/detection/pixel/stage.py index c8106fd..e3818d7 100644 --- a/douyin/detection/pixel/stage.py +++ b/douyin/detection/pixel/stage.py @@ -91,8 +91,24 @@ def _save_pixel_stage_overview( } if state.get("has_fudai_detail"): regions["detail_body"] = ("has_fudai_detail", get_fudai_detail_body_region()) + from douyin.detection.detection_pkg.detail import get_detail_task_count_digit_box + from douyin.fudai.core.coords import DETAIL_UI_V2_0, DETAIL_UI_V2_0_ONE_TASK + if task_count not in (None, 0): - regions["task_count"] = ("has_fudai_detail", tuple(detail_profile.get("task_count") or (860, 1770, 1035, 1875))) + task_count_box = tuple(detail_profile.get("task_count") or (860, 1770, 1035, 1875)) + regions["task_count"] = ( + "has_fudai_detail", + get_detail_task_count_digit_box(task_count_box), + ) + else: + regions["task_count_one"] = ( + "has_fudai_detail", + get_detail_task_count_digit_box(tuple(DETAIL_UI_V2_0_ONE_TASK.get("task_count") or (890, 1855, 1040, 1960))), + ) + regions["task_count_two"] = ( + "has_fudai_detail", + get_detail_task_count_digit_box(tuple(DETAIL_UI_V2_0.get("task_count") or (860, 1770, 1035, 1875))), + ) else: if details.get("has_coupon_bg", {}).get("method") != "disabled": regions["coupon"] = ("has_coupon_bg", get_pixel_region("coupon_popup", (9, 1173, 1079, 2255))) diff --git a/tests/test_detection_pixel.py b/tests/test_detection_pixel.py index ec2a984..8da9d7a 100644 --- a/tests/test_detection_pixel.py +++ b/tests/test_detection_pixel.py @@ -270,7 +270,7 @@ class TestPixelStage: "has_lucky_draw_result": False, "has_attend_button_red": False, "has_fansclub_join_red": False, - "has_fudai_detail": False, + "has_fudai_detail": True, "has_live_room_pixel": True, }, { @@ -287,10 +287,12 @@ class TestPixelStage: assert saved_images overview = saved_images[0] - # Candidate boxes are visible again: red means checked but not matched. - assert overview.getpixel((9, 1173)) == (255, 70, 70) - assert overview.getpixel((290, 1300)) == (255, 70, 70) + # Task-count digit candidate boxes are visible when the detail page is seen + # but the task count itself has not matched yet. + assert overview.getpixel((9, 1173)) != (255, 70, 70) assert overview.getpixel((200, 300)) != (255, 70, 70) + assert overview.getpixel((977, 1874)) == (0, 220, 80) + assert overview.getpixel((975, 1817)) == (0, 220, 80) # Successful live-room icon detection is still annotated. assert overview.getpixel((1002, 172)) == (0, 220, 80) diff --git a/tests/test_fudai_detail_ui_v2.py b/tests/test_fudai_detail_ui_v2.py index f19761e..3c6de4b 100644 --- a/tests/test_fudai_detail_ui_v2.py +++ b/tests/test_fudai_detail_ui_v2.py @@ -184,32 +184,35 @@ def test_config_manager_loads_fudai_detail_ui_and_ocr_switches(tmp_path): assert analyser.fudai_detail_ocr_participants_enabled is True -def test_check_detail_height_v2_does_not_run_task_count_ocr(monkeypatch): +def test_check_detail_height_v2_uses_template_match_path(monkeypatch): from douyin.detection.detection_pkg import detail - monkeypatch.setattr(detail, "_check_detail_task_count_v2_pixels", lambda _analyser: 0) - - def _ocr_should_not_run(_analyser): - raise AssertionError("v2 detail detection must not fallback to task-count OCR") - - monkeypatch.setattr(detail, "_check_detail_task_count_v2", _ocr_should_not_run) + monkeypatch.setattr(detail, "_check_detail_task_count_v2", lambda _analyser: 2) analyser = SimpleNamespace(fudai_detail_ui_mode="v2_0") - assert detail.check_detail_height(analyser) == 0 + assert detail.check_detail_height(analyser) == 2 def test_v2_task_count_pixels_choose_one_task_before_ocr(tmp_path, monkeypatch): - from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2_pixels + from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2 + from douyin.core import path_config + import numpy as np + import cv2 screenshot_path = tmp_path / "one_task.png" - img = Image.new("RGB", (1080, 2400), (10, 15, 46)) - img.putpixel((536, 1970), (255, 255, 255)) - img.save(screenshot_path) + assets_dir = tmp_path / "assets" + assets_dir.mkdir() + Image.new("RGB", (1080, 2400), (255, 255, 255)).save(screenshot_path) + Image.new("L", (40, 80), 255).save(assets_dir / "fudai_task_count_digit_1.png") + Image.new("L", (40, 80), 255).save(assets_dir / "fudai_task_count_digit_2.png") monkeypatch.setattr( "douyin.core.path_config.get_screenshot_path", lambda: str(screenshot_path), ) + monkeypatch.setattr(path_config, "get_assets_dir", lambda: str(assets_dir)) + scores = iter([0.99, 0.98, 0.81, 0.80]) + monkeypatch.setattr(cv2, "matchTemplate", lambda *_a, **_k: np.array([[next(scores)]], dtype=np.float32)) analyser = SimpleNamespace( fudai_detail_ui_mode="auto", @@ -218,20 +221,29 @@ def test_v2_task_count_pixels_choose_one_task_before_ocr(tmp_path, monkeypatch): _log_kv=lambda *_args, **_kwargs: None, ) - assert _check_detail_task_count_v2_pixels(analyser) == 1 - assert analyser._fudai_detail_task_count_source == "v2_pixels" + assert _check_detail_task_count_v2(analyser) == 1 + assert analyser._fudai_detail_task_count_source == "v2_template" def test_v2_task_count_pixels_choose_two_task_from_dark_card(tmp_path, monkeypatch): - from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2_pixels + from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2 + from douyin.core import path_config + import numpy as np + import cv2 screenshot_path = tmp_path / "two_task.png" - img = Image.new("RGB", (1080, 2400), (10, 15, 46)) - img.save(screenshot_path) + assets_dir = tmp_path / "assets" + assets_dir.mkdir() + Image.new("RGB", (1080, 2400), (255, 255, 255)).save(screenshot_path) + Image.new("L", (40, 80), 255).save(assets_dir / "fudai_task_count_digit_1.png") + Image.new("L", (40, 80), 255).save(assets_dir / "fudai_task_count_digit_2.png") monkeypatch.setattr( "douyin.core.path_config.get_screenshot_path", lambda: str(screenshot_path), ) + monkeypatch.setattr(path_config, "get_assets_dir", lambda: str(assets_dir)) + scores = iter([0.81, 0.80, 0.99, 1.0]) + monkeypatch.setattr(cv2, "matchTemplate", lambda *_a, **_k: np.array([[next(scores)]], dtype=np.float32)) analyser = SimpleNamespace( fudai_detail_ui_mode="v2_0", @@ -240,7 +252,84 @@ def test_v2_task_count_pixels_choose_two_task_from_dark_card(tmp_path, monkeypat _log_kv=lambda *_args, **_kwargs: None, ) - assert _check_detail_task_count_v2_pixels(analyser) == 2 + assert _check_detail_task_count_v2(analyser) == 2 + + +def test_v2_task_count_pixels_does_not_misread_two_task_when_lower_text_is_white(tmp_path, monkeypatch): + from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2 + from douyin.core import path_config + import numpy as np + import cv2 + + screenshot_path = tmp_path / "two_task_with_white_text.png" + assets_dir = tmp_path / "assets" + assets_dir.mkdir() + Image.new("RGB", (1080, 2400), (255, 255, 255)).save(screenshot_path) + Image.new("L", (40, 80), 255).save(assets_dir / "fudai_task_count_digit_1.png") + Image.new("L", (40, 80), 255).save(assets_dir / "fudai_task_count_digit_2.png") + monkeypatch.setattr( + "douyin.core.path_config.get_screenshot_path", + lambda: str(screenshot_path), + ) + monkeypatch.setattr(path_config, "get_assets_dir", lambda: str(assets_dir)) + scores = iter([0.97, 0.96, 0.98, 0.99]) + monkeypatch.setattr(cv2, "matchTemplate", lambda *_a, **_k: np.array([[next(scores)]], dtype=np.float32)) + + analyser = SimpleNamespace( + fudai_detail_ui_mode="v2_0", + resolution_ratio_x=1080, + resolution_ratio_y=2400, + _log_kv=lambda *_args, **_kwargs: None, + ) + + assert _check_detail_task_count_v2(analyser) == 2 + + +def test_v2_task_count_uses_digit_templates_instead_of_full_card_templates(tmp_path, monkeypatch): + from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2 + from douyin.core import path_config + import numpy as np + import cv2 + + screenshot_path = tmp_path / "digit_based.png" + assets_dir = tmp_path / "assets" + assets_dir.mkdir() + Image.new("RGB", (1080, 2400), (255, 255, 255)).save(screenshot_path) + Image.new("L", (40, 80), 255).save(assets_dir / "fudai_task_count_digit_1.png") + Image.new("L", (40, 80), 255).save(assets_dir / "fudai_task_count_digit_2.png") + monkeypatch.setattr( + "douyin.core.path_config.get_screenshot_path", + lambda: str(screenshot_path), + ) + monkeypatch.setattr(path_config, "get_assets_dir", lambda: str(assets_dir)) + + seen_paths = [] + + def _fake_imread(path, _flag): + seen_paths.append(path) + return np.full((80, 40), 255, dtype=np.uint8) + + scores = iter([0.80, 0.79, 0.99, 0.98]) + monkeypatch.setattr(cv2, "imread", _fake_imread) + monkeypatch.setattr(cv2, "matchTemplate", lambda *_a, **_k: np.array([[next(scores)]], dtype=np.float32)) + + analyser = SimpleNamespace( + fudai_detail_ui_mode="v2_0", + resolution_ratio_x=1080, + resolution_ratio_y=2400, + _log_kv=lambda *_args, **_kwargs: None, + ) + + assert _check_detail_task_count_v2(analyser) == 2 + assert any(path.endswith("fudai_task_count_digit_1.png") for path in seen_paths) + assert any(path.endswith("fudai_task_count_digit_2.png") for path in seen_paths) + + +def test_get_detail_task_count_digit_box_targets_trailing_digit_for_one_and_two_task(): + from douyin.detection.detection_pkg.detail import get_detail_task_count_digit_box + + assert get_detail_task_count_digit_box((890, 1855, 1040, 1960)) == (976, 1871, 988, 1901) + assert get_detail_task_count_digit_box((860, 1770, 1035, 1875)) == (974, 1814, 995, 1845) def test_v2_task_count_pixels_disabled_for_legacy(tmp_path, monkeypatch):