From 3c7cb45bec7029d338a71ccb6edd19a7862f30f1 Mon Sep 17 00:00:00 2001 From: Your Name Date: Tue, 23 Jun 2026 02:30:10 +0800 Subject: [PATCH] fix: parse paddle live tab ocr boxes --- douyin/handlers/live_tab_ocr.py | 114 ++++++++++++++++++++++++++++++-- tests/test_live_tab_ocr.py | 53 ++++++++++++++- 2 files changed, 160 insertions(+), 7 deletions(-) diff --git a/douyin/handlers/live_tab_ocr.py b/douyin/handlers/live_tab_ocr.py index 0498c3e..39c09ea 100644 --- a/douyin/handlers/live_tab_ocr.py +++ b/douyin/handlers/live_tab_ocr.py @@ -12,6 +12,8 @@ from PIL import Image from douyin.fudai.core.coords import RECOMMEND_TAB +LIVE_TAB_LAYOUT_CENTER_X_1080 = 718 + @dataclass(frozen=True) class OcrTextBox: @@ -28,13 +30,25 @@ def _iter_ocr_items(raw: Any) -> Iterable[Any]: return raw +def _plain(value: Any) -> Any: + """Convert numpy/PaddleOCR array-like values into regular Python lists.""" + try: + if hasattr(value, "tolist"): + return value.tolist() + except Exception: + pass + return value + + def _bbox_to_rect(box: Any) -> tuple[float, float, float, float] | None: try: + box = _plain(box) if not isinstance(box, (list, tuple)) or not box: return None xs: list[float] = [] ys: list[float] = [] for point in box: + point = _plain(point) if isinstance(point, (list, tuple)) and len(point) >= 2: xs.append(float(point[0])) ys.append(float(point[1])) @@ -49,6 +63,7 @@ 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): + item = _plain(item) text = "" confidence = None rect = None @@ -72,9 +87,12 @@ def parse_ocr_text_boxes(raw: Any) -> list[OcrTextBox]: 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") + boxes_data = _first_present(item, "rec_boxes", "boxes", "dt_polys", "rec_polys") + texts = _first_present(item, "rec_texts", "texts", "text_list") + scores = _first_present(item, "rec_scores", "scores") + boxes_data = _plain(boxes_data) + texts = _plain(texts) + scores = _plain(scores) if isinstance(texts, list) and isinstance(boxes_data, list): for idx, text_item in enumerate(texts): if not isinstance(text_item, str): @@ -93,7 +111,17 @@ def parse_ocr_text_boxes(raw: Any) -> list[OcrTextBox]: return boxes +def _first_present(item: dict[str, Any], *keys: str) -> Any: + for key in keys: + if key in item: + value = item.get(key) + if value is not None: + return value + return None + + def _rect_from_axis_aligned_or_poly(raw_box: Any) -> tuple[float, float, float, float] | None: + raw_box = _plain(raw_box) if isinstance(raw_box, (list, tuple)) and len(raw_box) == 4 and all( isinstance(v, (int, float)) for v in raw_box ): @@ -111,6 +139,35 @@ def _to_float(value: Any) -> float | None: return None +def _extract_texts_from_raw(raw: Any) -> list[str]: + texts: list[str] = [] + for item in _iter_ocr_items(raw): + item = _plain(item) + if isinstance(item, (list, tuple)) and len(item) >= 2: + second = _plain(item[1]) + if isinstance(second, str): + texts.append(second) + elif isinstance(second, (list, tuple)) and second and isinstance(second[0], str): + texts.append(second[0]) + elif isinstance(second, dict): + for key in ("text", "rec_text", "transcription"): + value = second.get(key) + if isinstance(value, str): + texts.append(value) + break + elif isinstance(item, dict): + item_texts = _plain(_first_present(item, "rec_texts", "texts", "text_list")) + if isinstance(item_texts, list): + texts.extend(str(text) for text in item_texts if isinstance(text, str)) + else: + for key in ("text", "rec_text", "transcription"): + value = item.get(key) + if isinstance(value, str): + texts.append(value) + break + return texts + + @dataclass(frozen=True) class LiveTabCandidate: box: OcrTextBox @@ -132,7 +189,7 @@ def choose_live_tab_candidate(boxes: Iterable[OcrTextBox]) -> LiveTabCandidate | continue if "直播广场" in text: continue - if len(text) > 12: + if len(text) > 20: continue x1, y1, x2, y2 = box.bbox width = max(0.0, x2 - x1) @@ -165,24 +222,50 @@ def choose_live_tab_box(boxes: Iterable[OcrTextBox]) -> OcrTextBox | None: return candidate.box if candidate else None +def _choose_text_only_live_tab(text: str, image_width: int, image_height: int) -> LiveTabCandidate | None: + cleaned = str(text or "").strip().replace(" ", "") + if "直播" not in cleaned or "直播广场" in cleaned or len(cleaned) > 20: + return None + center_x = float(image_width) * LIVE_TAB_LAYOUT_CENTER_X_1080 / 1080.0 + center_y = float(image_height) / 2.0 + return LiveTabCandidate( + box=OcrTextBox( + text=cleaned, + bbox=(0.0, 0.0, float(image_width), float(image_height)), + confidence=None, + ), + center_x=center_x, + center_y=center_y, + ) + + 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 + debug: dict[str, Any] = {"region": [x1, y1, x2, y2]} + try: + setattr(analyser, "_last_live_tab_ocr_debug", debug) + except Exception: + pass 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): + debug["reason"] = "pic_missing" return None with Image.open(pic_path) as img: img_rgb = img.convert("RGB") + img_width, img_height = img_rgb.size 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: + debug["reason"] = "ocr_unavailable" return None + debug["ocr_type"] = ocr_type if ocr_type == "easyocr": raw = ocr_obj.readtext(img_np) else: @@ -192,8 +275,28 @@ def find_live_tab_click_point_by_ocr(analyser: Any) -> tuple[int, int, dict[str, raw = [] boxes = parse_ocr_text_boxes(raw) + raw_texts = _extract_texts_from_raw(raw) selected = choose_live_tab_candidate(boxes) + fallback_text = "" if selected is None: + fallback_text = "".join(raw_texts) + if not fallback_text: + try: + fallback_text = str(analyser.operation.analyse_pic_word("推荐页直播标签", 0) or "") + except Exception: + fallback_text = "" + if fallback_text: + selected = _choose_text_only_live_tab(fallback_text, img_width, img_height) + debug.update( + { + "parsed_count": len(boxes), + "raw_texts": raw_texts[:5], + "fallback_text": fallback_text[:80], + "ocr_elapsed_ms": round((time.time() - start) * 1000, 1), + } + ) + if selected is None: + debug["reason"] = "live_text_not_selected" return None rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) @@ -207,6 +310,7 @@ def find_live_tab_click_point_by_ocr(analyser: Any) -> tuple[int, int, dict[str, "ocr_elapsed_ms": round((time.time() - start) * 1000, 1), } except Exception: + debug["reason"] = "exception" return None @@ -218,12 +322,14 @@ def click_live_tab_on_recommend_page(analyser: Any) -> tuple[int, int, str]: if result is None: analyser.operation.click(analyser.device_id, fallback_x, fallback_y) try: + debug = getattr(analyser, "_last_live_tab_ocr_debug", {}) or {} analyser._log_kv( "流程", "推荐页OCR直播入口未命中,回退固定坐标", x=fallback_x, y=fallback_y, reason="ocr_not_found", + ocr_debug=debug, ) except Exception: pass diff --git a/tests/test_live_tab_ocr.py b/tests/test_live_tab_ocr.py index 438091e..7194144 100644 --- a/tests/test_live_tab_ocr.py +++ b/tests/test_live_tab_ocr.py @@ -24,6 +24,27 @@ def test_parse_paddle_dict_boxes(): assert boxes[1] == OcrTextBox(text="直播", bbox=(40.0, 2.0, 70.0, 14.0), confidence=0.9) +def test_parse_paddle_rec_polys_boxes(): + class ArrayLike: + def __init__(self, value): + self.value = value + + def tolist(self): + return self.value + + raw = [ + { + "rec_texts": ["=购精选商城关注直播推荐"], + "rec_polys": ArrayLike([[[0, 0], [1080, 0], [1080, 80], [0, 80]]]), + "rec_scores": [0.92], + } + ] + boxes = parse_ocr_text_boxes(raw) + assert boxes == [ + OcrTextBox(text="=购精选商城关注直播推荐", bbox=(0.0, 0.0, 1080.0, 80.0), confidence=0.92) + ] + + def test_choose_live_tab_ignores_long_text(): selected = choose_live_tab_box( [ @@ -39,7 +60,7 @@ def test_choose_live_tab_from_joined_tab_row_estimates_substring_center(): selected = choose_live_tab_candidate( [ OcrTextBox( - text="商城关注直播推荐", + text="=购精选商城关注直播推荐", bbox=(0.0, 0.0, 1080.0, 80.0), confidence=0.92, ) @@ -47,8 +68,8 @@ def test_choose_live_tab_from_joined_tab_row_estimates_substring_center(): ) assert selected is not None - assert selected.box.text == "商城关注直播推荐" - assert 660 <= selected.center_x <= 700 + assert selected.box.text == "=购精选商城关注直播推荐" + assert selected.center_x == 810.0 assert selected.center_y == 40.0 @@ -139,6 +160,32 @@ def test_click_live_tab_uses_joined_row_substring(tmp_path): assert method == "ocr_live_tab" +def test_click_live_tab_uses_text_fallback_when_raw_has_no_bbox(tmp_path): + pic = tmp_path / "live_tab.png" + from PIL import Image + + Image.new("RGB", (1080, 80), (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.analyse_pic_word = MagicMock(return_value="=购精选商城关注直播推荐") + analyser.operation.ocr_type = "paddleocr" + analyser.operation.ocr = SimpleNamespace(predict=MagicMock(return_value=[{"rec_texts": []}])) + + x, y, method = click_live_tab_on_recommend_page(analyser) + + assert x == 718 + assert y == 180 + assert method == "ocr_live_tab" + analyser.operation.click.assert_called_once_with("D", x, y) + + def test_recommend_page_keeps_second_step_entry_mode(): from douyin.core.fudai_modules import run_once_basic_helpers as ronce