2 Commits
Author SHA1 Message Date
Your Name ffebc8d0dc add direct attend button ocr fallback 2026-06-24 00:56:36 +08:00
Your Name 61d3ad5d83 fix pixel button detection for rgba screenshots 2026-06-24 00:47:55 +08:00
4 changed files with 175 additions and 4 deletions

No files matched your search

+10 -2
View File
@@ -19,6 +19,14 @@ from typing import Any, Optional
from ._common import _safe_open_screenshot_rgb
def _read_rgb_pixel(pic_rgb: Image.Image, x: int, y: int) -> tuple[int, int, int]:
pixel = pic_rgb.getpixel((x, y))
if isinstance(pixel, tuple):
return int(pixel[0]), int(pixel[1]), int(pixel[2])
value = int(pixel)
return value, value, value
def detect_attend_button_red_area(
pic_rgb: Image.Image,
return_info: bool = False,
@@ -86,7 +94,7 @@ def detect_attend_button_red_area(
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
r, g, b = _read_rgb_pixel(pic_rgb, x, y)
# 检测红色:R值高,G和B相对较低
if r > 200 and (r - g) > 50 and (r - b) > 50:
red_count += 1
@@ -253,7 +261,7 @@ def detect_fansclub_join_red_area(
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
r, g, b = _read_rgb_pixel(pic_rgb, x, y)
# 检测红色:R值高,G和B相对较低
if r > 200 and (r - g) > 50 and (r - b) > 50:
red_count += 1
@@ -15,6 +15,7 @@ from typing import Any, Dict, Optional
from douyin.core import path_config
from douyin.fudai import douyin_fudai_detail
from douyin.fudai.douyin_fudai_core_pkg.button_state import (
decide_button_status,
is_button_text_non_actionable,
)
from douyin.handlers import douyin_swipe_handler
@@ -320,6 +321,58 @@ def _reservation_button_fallback_is_actionable(analyser: Any, item: Dict[str, An
return False, button_text, button_status
def _ocr_current_attend_button_if_actionable(analyser: Any, item: Dict[str, Any]) -> tuple[bool, str, str]:
try:
from douyin.fudai.core.coords import get_fudai_detail_profile
from douyin.fudai.douyin_fudai_core_pkg.ocr_tasks import _BUTTON_KEYWORDS
from douyin.utils.ocr_preprocess import preprocess_for_ocr
try:
task_count = int(item.get("task_count") or 2)
except Exception:
task_count = 2
profile = get_fudai_detail_profile("auto", task_count=task_count)
button_box = tuple(profile.get("button") or (70, 2020, 1010, 2165))
if len(button_box) != 4:
return False, "", ""
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
analyser.cut_pic(*button_box, "", "参与按钮", y_pianyi)
picname = preprocess_for_ocr(analyser, "参与按钮")
button_text = str(analyser.operation.analyse_pic_word(picname, 0) or "").strip()
if button_text and not any(k in button_text for k in _BUTTON_KEYWORDS):
retry_text = str(analyser.operation.analyse_pic_word(picname, 0) or "").strip()
if retry_text:
button_text = retry_text
button_status = decide_button_status(button_text)
ok = not is_button_text_non_actionable(button_text) and (
button_status in _DIRECT_ATTEND_ACTIONABLE_BUTTON_STATUSES
or any(snippet in button_text for snippet in _DIRECT_ATTEND_ACTIONABLE_BUTTON_TEXT_SNIPPETS)
)
try:
analyser._log_kv(
"预约",
"[预约] 预约直参当前按钮OCR兜底",
button_text=button_text[:80],
button_status=button_status,
result=bool(ok),
reason="reservation_button_ocr_fallback_checked",
)
except Exception:
pass
return bool(ok), button_text, button_status
except Exception as exc:
try:
analyser._log_kv(
"预约",
"[预约] 预约直参当前按钮OCR兜底异常",
error=str(exc),
reason="reservation_button_ocr_fallback_exception",
)
except Exception:
pass
return False, "", ""
def handle_reservation_direct_attend(analyser: Any) -> None:
"""预约回退后直接参与:直接查找福袋并点击,使用按钮检测进行决策,跳过OCR识别。
@@ -768,6 +821,14 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
fallback_ok, fallback_button_text, fallback_button_status = (
_reservation_button_fallback_is_actionable(analyser, first_reservation)
)
fallback_source = "reservation_button_text"
fallback_reason = "reservation_button_text_fallback_click_sent"
if not fallback_ok:
fallback_ok, fallback_button_text, fallback_button_status = (
_ocr_current_attend_button_if_actionable(analyser, first_reservation)
)
fallback_source = "current_button_ocr"
fallback_reason = "reservation_button_ocr_fallback_click_sent"
if fallback_ok:
try:
analyser._log_kv( # type: ignore[attr-defined]
@@ -776,13 +837,14 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
button_info=button_info,
button_text=fallback_button_text,
button_status=fallback_button_status,
reason="reservation_button_text_fallback_click_sent",
fallback_source=fallback_source,
reason=fallback_reason,
)
except Exception:
pass
button_info = {
**(button_info or {}),
"fallback": "reservation_button_text",
"fallback": fallback_source,
"button_text": fallback_button_text,
"button_status": fallback_button_status,
}
+38
View File
@@ -240,11 +240,49 @@ class TestPixelButtons:
params = list(sig.parameters.keys())
assert "pic_rgb" in params or len(params) >= 1
def test_detect_attend_button_accepts_rgba_image(self):
from PIL import Image
from douyin.detection.pixel.buttons import detect_attend_button_red_area
img = Image.new("RGBA", (1080, 2400), (0, 0, 0, 255))
for x in range(200, 880):
for y in range(2000, 2120):
img.putpixel((x, y), (255, 80, 120, 255))
detected, info = detect_attend_button_red_area(
img,
return_info=True,
red_ratio_threshold=0.25,
)
assert detected is True
assert info["red_ratio"] >= 0.25
def test_detect_fansclub_join_exists(self):
from douyin.detection.pixel.buttons import detect_fansclub_join_red_area
assert callable(detect_fansclub_join_red_area)
def test_detect_fansclub_join_accepts_rgba_image(self):
from PIL import Image
from douyin.detection.pixel.buttons import detect_fansclub_join_red_area
img = Image.new("RGBA", (1080, 2400), (0, 0, 0, 255))
for x in range(200, 880):
for y in range(1940, 2140):
img.putpixel((x, y), (255, 80, 120, 255))
detected, info = detect_fansclub_join_red_area(
img,
return_info=True,
red_ratio_threshold=0.25,
)
assert detected is True
assert info["red_ratio"] >= 0.25
class TestPixelStage:
"""pixel/stage 模块测试。"""
@@ -362,3 +362,66 @@ def test_direct_attend_uses_reservation_text_fallback_when_button_pixel_misses()
analyser.operation.click.assert_called()
assert _has_log_reason(analyser, "reservation_button_text_fallback_click_sent")
def test_direct_attend_uses_button_ocr_fallback_only_after_pixel_and_cache_miss():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
)
analyser = _mk_analyser()
analyser.reservations[0]["button_text"] = "加入购物粉丝团并关注主播"
analyser.reservations[0]["button_status"] = "需要加入粉丝团"
analyser.y_pianyi = 0
analyser.cut_pic = MagicMock(return_value=None)
analyser.operation.analyse_pic_word = MagicMock(return_value="一键发表评论")
with patch(
"douyin.core.douyin_flow_control.find_and_open_fudai_detail",
side_effect=[True, False],
), patch(
"douyin.core.path_config.get_screenshot_path",
return_value="C:/mock/screenshot.png",
), patch(
"PIL.Image.open",
) as mock_open, patch(
"douyin.detection.douyin_pixel.detect_attend_button_red_area",
return_value=(False, {"reason": "red_ratio_below_threshold"}),
):
mock_image = MagicMock()
mock_open.return_value = mock_image
handle_reservation_direct_attend(analyser)
analyser.cut_pic.assert_called_once()
analyser.operation.analyse_pic_word.assert_called_once()
analyser.operation.click.assert_called()
assert _has_log_reason(analyser, "reservation_button_ocr_fallback_click_sent")
def test_direct_attend_does_not_use_button_ocr_fallback_when_pixel_hits():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
)
analyser = _mk_analyser()
analyser.cut_pic = MagicMock(return_value=None)
analyser.operation.analyse_pic_word = MagicMock(return_value="一键发表评论")
with patch(
"douyin.core.douyin_flow_control.find_and_open_fudai_detail",
side_effect=[True, False],
), patch(
"douyin.core.path_config.get_screenshot_path",
return_value="C:/mock/screenshot.png",
), patch(
"PIL.Image.open",
) as mock_open, patch(
"douyin.detection.douyin_pixel.detect_attend_button_red_area",
return_value=(True, {"mock": True}),
):
mock_image = MagicMock()
mock_open.return_value = mock_image
handle_reservation_direct_attend(analyser)
analyser.cut_pic.assert_not_called()
analyser.operation.analyse_pic_word.assert_not_called()