fix: use ocr live tab and merge stuck room titles
This commit is contained in:
1 parent
e286cd46c8
commit
25f7f9af9e
9 files changed
+582
-16
No files matched your search
@@ -443,11 +443,20 @@ def dispatch_stage_branch(
|
||||
seen=seen,
|
||||
)
|
||||
try:
|
||||
# 直接点击 (718, 169) 进入直播页 - 基于1080x2400分辨率
|
||||
live_tab_x = int(718 * self.resolution_ratio_x // 1080)
|
||||
live_tab_y = int(169 * self.resolution_ratio_y // 2400)
|
||||
self.operation.click(self.device_id, live_tab_x, live_tab_y)
|
||||
self._log_kv("流程", "点击进入直播页", x=live_tab_x, y=live_tab_y)
|
||||
from douyin.handlers.live_tab_ocr import (
|
||||
click_live_tab_on_recommend_page,
|
||||
)
|
||||
|
||||
live_tab_x, live_tab_y, live_tab_method = (
|
||||
click_live_tab_on_recommend_page(self)
|
||||
)
|
||||
self._log_kv(
|
||||
"流程",
|
||||
"点击进入直播页",
|
||||
x=live_tab_x,
|
||||
y=live_tab_y,
|
||||
method=live_tab_method,
|
||||
)
|
||||
self.operation.delay(self.FOLLOW_TAB_CLICK_DELAY)
|
||||
|
||||
# 点击进入直播间位置(支持模式切换:关注列表坐标/屏幕中心),连点两次
|
||||
|
||||
@@ -709,12 +709,18 @@ class SwipeHandler:
|
||||
|
||||
# 点击关注标签并进入直播间
|
||||
try:
|
||||
follow_tab_x = int(709 * analyser.resolution_ratio_x // 1080)
|
||||
follow_tab_y = int(169 * analyser.resolution_ratio_y // 2400)
|
||||
analyser.operation.click(analyser.device_id, follow_tab_x, follow_tab_y)
|
||||
from douyin.handlers.live_tab_ocr import click_live_tab_on_recommend_page
|
||||
|
||||
follow_tab_x, follow_tab_y, live_tab_method = click_live_tab_on_recommend_page(
|
||||
analyser
|
||||
)
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程", "点击关注标签", x=follow_tab_x, y=follow_tab_y
|
||||
"流程",
|
||||
"点击直播标签",
|
||||
x=follow_tab_x,
|
||||
y=follow_tab_y,
|
||||
method=live_tab_method,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
"""OCR helper for clicking the top "直播" tab on the recommendation page."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Iterable
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from douyin.fudai.core.coords import RECOMMEND_TAB
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OcrTextBox:
|
||||
text: str
|
||||
bbox: tuple[float, float, float, float]
|
||||
confidence: float | None = None
|
||||
|
||||
|
||||
def _iter_ocr_items(raw: Any) -> Iterable[Any]:
|
||||
if not isinstance(raw, list):
|
||||
return []
|
||||
if len(raw) == 1 and isinstance(raw[0], list):
|
||||
return raw[0]
|
||||
return raw
|
||||
|
||||
|
||||
def _bbox_to_rect(box: Any) -> tuple[float, float, float, float] | None:
|
||||
try:
|
||||
if not isinstance(box, (list, tuple)) or not box:
|
||||
return None
|
||||
xs: list[float] = []
|
||||
ys: list[float] = []
|
||||
for point in box:
|
||||
if isinstance(point, (list, tuple)) and len(point) >= 2:
|
||||
xs.append(float(point[0]))
|
||||
ys.append(float(point[1]))
|
||||
if not xs or not ys:
|
||||
return None
|
||||
return min(xs), min(ys), max(xs), max(ys)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def parse_ocr_text_boxes(raw: Any) -> list[OcrTextBox]:
|
||||
"""Parse EasyOCR/PaddleOCR style OCR output into text boxes."""
|
||||
boxes: list[OcrTextBox] = []
|
||||
for item in _iter_ocr_items(raw):
|
||||
text = ""
|
||||
confidence = None
|
||||
rect = None
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||
rect = _bbox_to_rect(item[0])
|
||||
second = item[1]
|
||||
if isinstance(second, str):
|
||||
text = second
|
||||
if len(item) >= 3:
|
||||
confidence = item[2]
|
||||
elif isinstance(second, (list, tuple)) and second:
|
||||
if isinstance(second[0], str):
|
||||
text = second[0]
|
||||
if len(second) >= 2:
|
||||
confidence = second[1]
|
||||
elif isinstance(second, dict):
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
value = second.get(key)
|
||||
if isinstance(value, str):
|
||||
text = value
|
||||
break
|
||||
confidence = second.get("confidence") or second.get("score")
|
||||
elif isinstance(item, dict):
|
||||
boxes_data = item.get("rec_boxes") or item.get("boxes") or item.get("dt_polys")
|
||||
texts = item.get("rec_texts") or item.get("texts") or item.get("text_list")
|
||||
scores = item.get("rec_scores") or item.get("scores")
|
||||
if isinstance(texts, list) and isinstance(boxes_data, list):
|
||||
for idx, text_item in enumerate(texts):
|
||||
if not isinstance(text_item, str):
|
||||
continue
|
||||
raw_box = boxes_data[idx] if idx < len(boxes_data) else None
|
||||
parsed_rect = _rect_from_axis_aligned_or_poly(raw_box)
|
||||
if parsed_rect is None:
|
||||
continue
|
||||
score = scores[idx] if isinstance(scores, list) and idx < len(scores) else None
|
||||
boxes.append(OcrTextBox(text=text_item, bbox=parsed_rect, confidence=_to_float(score)))
|
||||
continue
|
||||
|
||||
if not text or rect is None:
|
||||
continue
|
||||
boxes.append(OcrTextBox(text=text, bbox=rect, confidence=_to_float(confidence)))
|
||||
return boxes
|
||||
|
||||
|
||||
def _rect_from_axis_aligned_or_poly(raw_box: Any) -> tuple[float, float, float, float] | None:
|
||||
if isinstance(raw_box, (list, tuple)) and len(raw_box) == 4 and all(
|
||||
isinstance(v, (int, float)) for v in raw_box
|
||||
):
|
||||
x1, y1, x2, y2 = [float(v) for v in raw_box]
|
||||
return min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)
|
||||
return _bbox_to_rect(raw_box)
|
||||
|
||||
|
||||
def _to_float(value: Any) -> float | None:
|
||||
try:
|
||||
if value is None:
|
||||
return None
|
||||
return float(value)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def choose_live_tab_box(boxes: Iterable[OcrTextBox]) -> OcrTextBox | None:
|
||||
"""Pick the short top-tab "直播" OCR hit, ignoring longer page text."""
|
||||
candidates: list[tuple[int, OcrTextBox]] = []
|
||||
for box in boxes:
|
||||
text = str(box.text or "").strip().replace(" ", "")
|
||||
if "直播" not in text:
|
||||
continue
|
||||
if len(text) > 4:
|
||||
continue
|
||||
x1, y1, x2, y2 = box.bbox
|
||||
width = max(0.0, x2 - x1)
|
||||
height = max(0.0, y2 - y1)
|
||||
if width <= 0 or height <= 0:
|
||||
continue
|
||||
score = 10
|
||||
if text == "直播":
|
||||
score += 20
|
||||
if box.confidence is not None:
|
||||
score += int(max(0.0, min(1.0, box.confidence)) * 10)
|
||||
candidates.append((score, box))
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda item: item[0], reverse=True)
|
||||
return candidates[0][1]
|
||||
|
||||
|
||||
def find_live_tab_click_point_by_ocr(analyser: Any) -> tuple[int, int, dict[str, Any]] | None:
|
||||
"""Find the recommendation-page live tab click point using OCR bbox."""
|
||||
start = time.time()
|
||||
x1, y1, x2, y2 = RECOMMEND_TAB
|
||||
try:
|
||||
analyser.cut_pic(x1, y1, x2, y2, "", "推荐页直播标签")
|
||||
pic_path = analyser.operation._find_pic_path("推荐页直播标签")
|
||||
if not pic_path or not os.path.exists(pic_path):
|
||||
return None
|
||||
|
||||
with Image.open(pic_path) as img:
|
||||
img_rgb = img.convert("RGB")
|
||||
img_np = np.array(img_rgb)
|
||||
|
||||
ocr_obj = getattr(analyser.operation, "ocr", None)
|
||||
ocr_type = getattr(analyser.operation, "ocr_type", None)
|
||||
if ocr_obj is None:
|
||||
return None
|
||||
if ocr_type == "easyocr":
|
||||
raw = ocr_obj.readtext(img_np)
|
||||
else:
|
||||
predict = getattr(ocr_obj, "predict", None)
|
||||
raw = predict(img_np) if callable(predict) else ocr_obj.ocr(img_np)
|
||||
if raw == [None]:
|
||||
raw = []
|
||||
|
||||
boxes = parse_ocr_text_boxes(raw)
|
||||
selected = choose_live_tab_box(boxes)
|
||||
if selected is None:
|
||||
return None
|
||||
|
||||
bx1, by1, bx2, by2 = selected.bbox
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
click_x = int((x1 + ((bx1 + bx2) / 2.0)) * rx // 1080)
|
||||
click_y = int((y1 + ((by1 + by2) / 2.0)) * ry // 2400)
|
||||
return click_x, click_y, {
|
||||
"ocr_text": selected.text,
|
||||
"bbox": [round(v, 2) for v in selected.bbox],
|
||||
"confidence": selected.confidence,
|
||||
"ocr_elapsed_ms": round((time.time() - start) * 1000, 1),
|
||||
}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def click_live_tab_on_recommend_page(analyser: Any) -> tuple[int, int, str]:
|
||||
"""Click the recommendation-page "直播" tab via OCR, fallback to legacy coords."""
|
||||
fallback_x = int(718 * analyser.resolution_ratio_x // 1080)
|
||||
fallback_y = int(169 * analyser.resolution_ratio_y // 2400)
|
||||
result = find_live_tab_click_point_by_ocr(analyser)
|
||||
if result is None:
|
||||
analyser.operation.click(analyser.device_id, fallback_x, fallback_y)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"推荐页OCR直播入口未命中,回退固定坐标",
|
||||
x=fallback_x,
|
||||
y=fallback_y,
|
||||
reason="ocr_not_found",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return fallback_x, fallback_y, "fixed_fallback"
|
||||
|
||||
click_x, click_y, info = result
|
||||
analyser.operation.click(analyser.device_id, click_x, click_y)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"推荐页OCR直播入口命中",
|
||||
x=click_x,
|
||||
y=click_y,
|
||||
**info,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return click_x, click_y, "ocr_live_tab"
|
||||
@@ -36,6 +36,25 @@ except ImportError:
|
||||
_RESERVATION_ERROR_UTILS_AVAILABLE = False
|
||||
|
||||
|
||||
def _common_prefix_len(left: str, right: str) -> int:
|
||||
count = 0
|
||||
for lch, rch in zip(left, right):
|
||||
if lch != rch:
|
||||
break
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def _room_title_norms_match(left_norm: str, right_norm: str) -> bool:
|
||||
if not left_norm or not right_norm:
|
||||
return False
|
||||
if left_norm == right_norm or left_norm in right_norm or right_norm in left_norm:
|
||||
return True
|
||||
if min(len(left_norm), len(right_norm)) < 8:
|
||||
return False
|
||||
return _common_prefix_len(left_norm, right_norm) >= 8
|
||||
|
||||
|
||||
def _dump_room_pos_map_to_state(analyser: Any) -> None:
|
||||
"""将 analyser._room_pos_to_title_map 序列化到 douyin/core/state/room_pos_map.json。
|
||||
|
||||
@@ -69,7 +88,12 @@ def _dump_room_pos_map_to_state(analyser: Any) -> None:
|
||||
title_norm = _normalize_room_title_for_matching(t or tr)
|
||||
if not title_norm:
|
||||
continue
|
||||
old = merged_by_title.get(title_norm)
|
||||
old_key = None
|
||||
for candidate_norm in merged_by_title.keys():
|
||||
if _room_title_norms_match(candidate_norm, title_norm):
|
||||
old_key = candidate_norm
|
||||
break
|
||||
old = merged_by_title.get(old_key or title_norm)
|
||||
if old is None:
|
||||
merged_by_title[title_norm] = (k, v_raw)
|
||||
continue
|
||||
@@ -104,7 +128,7 @@ def _dump_room_pos_map_to_state(analyser: Any) -> None:
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
merged_by_title[title_norm] = (base_k, base_v)
|
||||
merged_by_title[old_key or title_norm] = (base_k, base_v)
|
||||
|
||||
# 构造合并后的 room_pos_map(保留未能归一化标题的条目)
|
||||
if merged_by_title:
|
||||
|
||||
@@ -93,7 +93,31 @@ def _titles_match(left: str, right: str) -> bool:
|
||||
right_norm = _normalize_room_title_for_matching(right)
|
||||
if not left_norm or not right_norm:
|
||||
return False
|
||||
return left_norm == right_norm or left_norm in right_norm or right_norm in left_norm
|
||||
return _room_title_norms_match(left_norm, right_norm)
|
||||
|
||||
|
||||
def _common_prefix_len(left: str, right: str) -> int:
|
||||
count = 0
|
||||
for lch, rch in zip(left, right):
|
||||
if lch != rch:
|
||||
break
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def _room_title_norms_match(left_norm: str, right_norm: str) -> bool:
|
||||
"""Match same live room titles even when OCR captures different ad suffixes."""
|
||||
if not left_norm or not right_norm:
|
||||
return False
|
||||
if left_norm == right_norm or left_norm in right_norm or right_norm in left_norm:
|
||||
return True
|
||||
shorter = min(len(left_norm), len(right_norm))
|
||||
if shorter < 8:
|
||||
return False
|
||||
prefix_len = _common_prefix_len(left_norm, right_norm)
|
||||
if prefix_len >= 8:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _should_protect_pending_reservation_target(
|
||||
@@ -430,7 +454,7 @@ def record_room_title_and_pos(analyser: Any) -> bool:
|
||||
existing_title_norm = _normalize_room_title_for_matching(
|
||||
existing_title or existing_title_raw
|
||||
)
|
||||
if existing_title_norm and existing_title_norm == current_title_norm:
|
||||
if _room_title_norms_match(existing_title_norm, current_title_norm):
|
||||
duplicate_title_positions.append(pos_int)
|
||||
|
||||
if duplicate_title_positions:
|
||||
@@ -510,7 +534,9 @@ def record_room_title_and_pos(analyser: Any) -> bool:
|
||||
getattr(analyser, "_same_room_reset_pending_title_norm", "")
|
||||
or ""
|
||||
)
|
||||
if pending_after_reset and pending_after_reset == current_title_norm:
|
||||
if pending_after_reset and _room_title_norms_match(
|
||||
pending_after_reset, current_title_norm
|
||||
):
|
||||
did_escape = False
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
@@ -550,7 +576,7 @@ def record_room_title_and_pos(analyser: Any) -> bool:
|
||||
|
||||
last_norm = str(getattr(analyser, "_last_room_title_norm_seen", "") or "")
|
||||
streak = int(getattr(analyser, "_same_room_title_streak", 0) or 0)
|
||||
if current_title_norm == last_norm:
|
||||
if _room_title_norms_match(current_title_norm, last_norm):
|
||||
streak += 1
|
||||
else:
|
||||
streak = 1
|
||||
|
||||
@@ -8,6 +8,7 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.reservation.reservation_logic import _normalize_room_title_for_matching
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -92,6 +93,66 @@ def _format_countdown(detail: dict[str, Any]) -> str:
|
||||
return mm or ss or "-"
|
||||
|
||||
|
||||
def _common_prefix_len(left: str, right: str) -> int:
|
||||
count = 0
|
||||
for lch, rch in zip(left, right):
|
||||
if lch != rch:
|
||||
break
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def _room_title_norms_match(left_norm: str, right_norm: str) -> bool:
|
||||
if not left_norm or not right_norm:
|
||||
return False
|
||||
if left_norm == right_norm or left_norm in right_norm or right_norm in left_norm:
|
||||
return True
|
||||
if min(len(left_norm), len(right_norm)) < 8:
|
||||
return False
|
||||
return _common_prefix_len(left_norm, right_norm) >= 8
|
||||
|
||||
|
||||
def _merge_mapping_row(base: dict[str, Any], extra: dict[str, Any]) -> dict[str, Any]:
|
||||
if not base:
|
||||
return dict(extra)
|
||||
merged = dict(base)
|
||||
if merged.get("has_fudai") != "是" and extra.get("has_fudai") == "是":
|
||||
for key in ("has_fudai", "value", "countdown", "participants", "copies", "button", "task", "content"):
|
||||
merged[key] = extra.get(key, merged.get(key, "-"))
|
||||
if merged.get("reserved") != "是" and extra.get("reserved") == "是":
|
||||
merged["reserved"] = "是"
|
||||
merged_positions = set(str(v) for v in merged.get("_merged_positions", []) or [])
|
||||
merged_positions.add(str(merged.get("pos", "")))
|
||||
merged_positions.add(str(extra.get("pos", "")))
|
||||
merged["_merged_positions"] = sorted(
|
||||
[v for v in merged_positions if v],
|
||||
key=lambda v: int(v) if str(v).isdigit() else 999999,
|
||||
)
|
||||
return merged
|
||||
|
||||
|
||||
def _merge_similar_mapping_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
merged: list[dict[str, Any]] = []
|
||||
norm_by_index: list[str] = []
|
||||
for row in rows:
|
||||
title_norm = _normalize_room_title_for_matching(
|
||||
str(row.get("title") or row.get("raw_title") or "")
|
||||
)
|
||||
target_idx = None
|
||||
for idx, old_norm in enumerate(norm_by_index):
|
||||
if _room_title_norms_match(old_norm, title_norm):
|
||||
target_idx = idx
|
||||
break
|
||||
if target_idx is None:
|
||||
merged.append(dict(row))
|
||||
norm_by_index.append(title_norm)
|
||||
else:
|
||||
merged[target_idx] = _merge_mapping_row(merged[target_idx], row)
|
||||
for row in merged:
|
||||
row.pop("_merged_positions", None)
|
||||
return merged
|
||||
|
||||
|
||||
def _mapping_rows() -> list[dict[str, Any]]:
|
||||
raw = _read_json(Path(path_config.get_project_root()) / "douyin" / "core" / "state" / "room_pos_map.json", {})
|
||||
reservations = _read_json(path_config.get_reservations_path(), {})
|
||||
@@ -163,7 +224,7 @@ def _mapping_rows() -> list[dict[str, Any]]:
|
||||
pos = str(row.get("pos", ""))
|
||||
return (int(pos), "") if pos.isdigit() else (999999, pos)
|
||||
|
||||
return sorted(rows, key=sort_key)
|
||||
return sorted(_merge_similar_mapping_rows(rows), key=sort_key)
|
||||
|
||||
|
||||
def load_dashboard_data() -> DashboardData:
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_dashboard_merges_similar_mapping_rows():
|
||||
from gui.dashboard_app.data import _merge_similar_mapping_rows
|
||||
|
||||
rows = [
|
||||
{
|
||||
"pos": "3",
|
||||
"title": "三资堂美妆官方旗舰抖音旗舰店铺回头率超",
|
||||
"raw_title": "三资堂美妆官方旗舰抖音旗舰店铺回头率超7",
|
||||
"reserved": "-",
|
||||
"has_fudai": "-",
|
||||
"value": "-",
|
||||
"countdown": "-",
|
||||
"participants": "-",
|
||||
"copies": "-",
|
||||
"button": "-",
|
||||
"task": "-",
|
||||
"content": "-",
|
||||
"updated": "-",
|
||||
},
|
||||
{
|
||||
"pos": "4",
|
||||
"title": "三资堂美妆官方旗舰抖音旗舰美妆达人好店",
|
||||
"raw_title": "三资堂美妆官方旗舰抖音旗舰美妆达人好店",
|
||||
"reserved": "-",
|
||||
"has_fudai": "-",
|
||||
"value": "-",
|
||||
"countdown": "-",
|
||||
"participants": "-",
|
||||
"copies": "-",
|
||||
"button": "-",
|
||||
"task": "-",
|
||||
"content": "-",
|
||||
"updated": "-",
|
||||
},
|
||||
]
|
||||
|
||||
merged = _merge_similar_mapping_rows(rows)
|
||||
|
||||
assert len(merged) == 1
|
||||
assert merged[0]["pos"] == "3"
|
||||
@@ -0,0 +1,119 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from douyin.handlers.live_tab_ocr import (
|
||||
OcrTextBox,
|
||||
choose_live_tab_box,
|
||||
click_live_tab_on_recommend_page,
|
||||
parse_ocr_text_boxes,
|
||||
)
|
||||
|
||||
|
||||
def test_parse_easyocr_live_bbox():
|
||||
raw = [([[10, 5], [50, 5], [50, 25], [10, 25]], "直播", 0.93)]
|
||||
boxes = parse_ocr_text_boxes(raw)
|
||||
assert boxes == [OcrTextBox(text="直播", bbox=(10.0, 5.0, 50.0, 25.0), confidence=0.93)]
|
||||
|
||||
|
||||
def test_parse_paddle_dict_boxes():
|
||||
raw = [{"rec_texts": ["推荐", "直播"], "rec_boxes": [[1, 2, 20, 12], [40, 2, 70, 14]], "rec_scores": [0.8, 0.9]}]
|
||||
boxes = parse_ocr_text_boxes(raw)
|
||||
assert boxes[1] == OcrTextBox(text="直播", bbox=(40.0, 2.0, 70.0, 14.0), confidence=0.9)
|
||||
|
||||
|
||||
def test_choose_live_tab_ignores_long_text():
|
||||
selected = choose_live_tab_box(
|
||||
[
|
||||
OcrTextBox(text="直播广场", bbox=(1, 1, 50, 20), confidence=0.99),
|
||||
OcrTextBox(text="直播", bbox=(70, 1, 100, 20), confidence=0.80),
|
||||
]
|
||||
)
|
||||
assert selected is not None
|
||||
assert selected.text == "直播"
|
||||
|
||||
|
||||
def test_click_live_tab_uses_ocr_bbox(monkeypatch, tmp_path):
|
||||
pic = tmp_path / "live_tab.png"
|
||||
from PIL import Image
|
||||
|
||||
Image.new("RGB", (500, 60), (255, 255, 255)).save(pic)
|
||||
|
||||
analyser = SimpleNamespace()
|
||||
analyser.device_id = "D"
|
||||
analyser.resolution_ratio_x = 1080
|
||||
analyser.resolution_ratio_y = 2400
|
||||
analyser.cut_pic = MagicMock()
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.operation = SimpleNamespace()
|
||||
analyser.operation.click = MagicMock()
|
||||
analyser.operation._find_pic_path = MagicMock(return_value=str(pic))
|
||||
analyser.operation.ocr_type = "easyocr"
|
||||
analyser.operation.ocr = SimpleNamespace(
|
||||
readtext=MagicMock(
|
||||
return_value=[
|
||||
([[300, 10], [340, 10], [340, 35], [300, 35]], "直播", 0.96)
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
x, y, method = click_live_tab_on_recommend_page(analyser)
|
||||
|
||||
assert (x, y, method) == (720, 162, "ocr_live_tab")
|
||||
analyser.operation.click.assert_called_once_with("D", 720, 162)
|
||||
|
||||
|
||||
def test_click_live_tab_falls_back_when_ocr_misses(tmp_path):
|
||||
pic = tmp_path / "live_tab.png"
|
||||
from PIL import Image
|
||||
|
||||
Image.new("RGB", (500, 60), (255, 255, 255)).save(pic)
|
||||
analyser = SimpleNamespace()
|
||||
analyser.device_id = "D"
|
||||
analyser.resolution_ratio_x = 1080
|
||||
analyser.resolution_ratio_y = 2400
|
||||
analyser.cut_pic = MagicMock()
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.operation = SimpleNamespace()
|
||||
analyser.operation.click = MagicMock()
|
||||
analyser.operation._find_pic_path = MagicMock(return_value=str(pic))
|
||||
analyser.operation.ocr_type = "easyocr"
|
||||
analyser.operation.ocr = SimpleNamespace(readtext=MagicMock(return_value=[]))
|
||||
|
||||
x, y, method = click_live_tab_on_recommend_page(analyser)
|
||||
|
||||
assert (x, y, method) == (718, 169, "fixed_fallback")
|
||||
analyser.operation.click.assert_called_once_with("D", 718, 169)
|
||||
|
||||
|
||||
def test_recommend_page_keeps_second_step_entry_mode():
|
||||
from douyin.core.fudai_modules import run_once_basic_helpers as ronce
|
||||
|
||||
s = MagicMock()
|
||||
s.device_id = "D"
|
||||
s.resolution_ratio_x = 1080
|
||||
s.resolution_ratio_y = 2400
|
||||
s.FOLLOW_TAB_CLICK_DELAY = 0
|
||||
s.ENTER_LIVE_CLICK_DELAY = 0
|
||||
s.ENTER_LIVE_FINAL_DELAY = 0
|
||||
s.RETURN_STEP_DELAY_SECONDS = 0
|
||||
s.operation.click = MagicMock()
|
||||
s.operation.delay = MagicMock()
|
||||
s._log_kv = MagicMock()
|
||||
|
||||
def _click_ocr_live_tab(analyser):
|
||||
analyser.operation.click(analyser.device_id, 720, 162)
|
||||
return 720, 162, "ocr_live_tab"
|
||||
|
||||
with patch(
|
||||
"douyin.handlers.live_tab_ocr.click_live_tab_on_recommend_page",
|
||||
side_effect=_click_ocr_live_tab,
|
||||
), patch(
|
||||
"douyin.handlers.douyin_swipe_handler.SwipeHandler.resolve_reenter_live_click_point",
|
||||
return_value=(540, 1200, "screen_center"),
|
||||
):
|
||||
ronce.dispatch_stage_branch(s, "RECOMMEND_PAGE", {}, 0.0)
|
||||
|
||||
calls = [call.args for call in s.operation.click.call_args_list]
|
||||
assert calls == [("D", 720, 162), ("D", 540, 1200), ("D", 540, 1200)]
|
||||
@@ -62,6 +62,33 @@ def test_duplicate_titles_are_merged_to_smaller_pos():
|
||||
assert merged.get("merged_positions") == [1, 2]
|
||||
|
||||
|
||||
def test_similar_long_titles_are_merged_to_smaller_pos():
|
||||
from douyin.reservation.douyin_reservation_handler_pkg import record_title as mod
|
||||
|
||||
a = _mk_analyser()
|
||||
a.room_pos = 4
|
||||
a.current_room_title = "三资堂美妆官方旗舰抖音旗舰美妆达人好店"
|
||||
a.current_room_title_raw = "三资堂美妆官方旗舰抖音旗舰美妆达人好店"
|
||||
a._room_title_identified_positions = {4}
|
||||
a._room_pos_to_title_map = {
|
||||
3: {
|
||||
"title": "三资堂美妆官方旗舰抖音旗舰店铺回头率超",
|
||||
"title_raw": "三资堂美妆官方旗舰抖音旗舰店铺回头率超7",
|
||||
"has_fudai": False,
|
||||
"fudai_content": "",
|
||||
"fudai_detail": None,
|
||||
"timestamp": 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
with patch.object(mod, "_dump_room_pos_map_to_state", return_value=None):
|
||||
consumed = mod.record_room_title_and_pos(a)
|
||||
|
||||
assert consumed is False
|
||||
assert 4 not in a._room_pos_to_title_map
|
||||
assert a._room_pos_to_title_map[3]["merged_positions"] == [3, 4]
|
||||
|
||||
|
||||
def test_merge_room_info_keeps_explicit_no_fudai_state():
|
||||
from douyin.reservation.douyin_reservation_handler_pkg import record_title as mod
|
||||
|
||||
@@ -156,6 +183,40 @@ def test_same_room_streak_triggers_reset_and_consumes_swipe():
|
||||
assert len(a._room_pos_to_title_map) >= 1
|
||||
|
||||
|
||||
def test_similar_same_room_streak_triggers_reset_and_consumes_swipe():
|
||||
from douyin.reservation.douyin_reservation_handler_pkg import record_title as mod
|
||||
|
||||
a = _mk_analyser()
|
||||
a.room_pos = 6
|
||||
a.current_room_title = "三资堂美妆官方旗舰抖音旗舰小体"
|
||||
a.current_room_title_raw = "三资堂美妆官方旗舰抖音旗舰小体"
|
||||
a._room_title_identified_positions = {6}
|
||||
a._room_pos_to_title_map = {
|
||||
6: {
|
||||
"title": "三资堂美妆官方旗舰抖音旗舰小体",
|
||||
"title_raw": "三资堂美妆官方旗舰抖音旗舰小体",
|
||||
"has_fudai": False,
|
||||
"fudai_content": "",
|
||||
"fudai_detail": None,
|
||||
"timestamp": 1.0,
|
||||
}
|
||||
}
|
||||
a._record_title_before_swipe_up = True
|
||||
a._last_room_title_norm_seen = "三资堂美妆官方旗舰抖音旗舰半年百万人搜"
|
||||
a._same_room_title_streak = 2
|
||||
|
||||
with patch.object(mod, "_dump_room_pos_map_to_state", return_value=None):
|
||||
with patch(
|
||||
"douyin.reservation.douyin_reservation_handler_pkg.record_title.douyin_swipe_handler.SwipeHandler.reset_to_top_keep_mapping",
|
||||
return_value=True,
|
||||
) as mock_reset:
|
||||
consumed = mod.record_room_title_and_pos(a)
|
||||
|
||||
assert consumed is True
|
||||
mock_reset.assert_called_once()
|
||||
assert int(getattr(a, "_same_room_title_streak", -1)) == 0
|
||||
|
||||
|
||||
def test_same_room_after_recent_reset_triggers_back_then_next_escape():
|
||||
from douyin.reservation.douyin_reservation_handler_pkg import record_title as mod
|
||||
|
||||
|
||||
Reference in new issue
Block a user