Files
douyi_guaji_main/douyin/handlers/live_tab_ocr.py
T

245 lines
8.6 KiB
Python

"""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
@dataclass(frozen=True)
class LiveTabCandidate:
box: OcrTextBox
center_x: float
center_y: float
def choose_live_tab_candidate(boxes: Iterable[OcrTextBox]) -> LiveTabCandidate | None:
"""Pick the top-tab "直播" OCR hit.
PaddleOCR often returns the whole tab row, e.g. "商城关注直播推荐", rather than
separate boxes. In that case click the estimated center of the "直播" substring
inside the row bbox.
"""
candidates: list[tuple[int, LiveTabCandidate]] = []
for box in boxes:
text = str(box.text or "").strip().replace(" ", "")
if "直播" not in text:
continue
if "直播广场" in text:
continue
if len(text) > 12:
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
live_idx = text.find("直播")
if live_idx < 0:
continue
char_count = max(1, len(text))
center_x = x1 + width * ((live_idx + 1.0) / char_count)
center_y = (y1 + y2) / 2.0
score = 10
if text == "直播":
score += 20
elif text in ("关注直播推荐", "商城关注直播推荐"):
score += 12
if box.confidence is not None:
score += int(max(0.0, min(1.0, box.confidence)) * 10)
candidates.append((score, LiveTabCandidate(box=box, center_x=center_x, center_y=center_y)))
if not candidates:
return None
candidates.sort(key=lambda item: item[0], reverse=True)
return candidates[0][1]
def choose_live_tab_box(boxes: Iterable[OcrTextBox]) -> OcrTextBox | None:
"""Backward-compatible wrapper returning only the selected OCR box."""
candidate = choose_live_tab_candidate(boxes)
return candidate.box if candidate else None
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_candidate(boxes)
if selected is None:
return None
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
click_x = int((x1 + selected.center_x) * rx // 1080)
click_y = int((y1 + selected.center_y) * ry // 2400)
return click_x, click_y, {
"ocr_text": selected.box.text,
"bbox": [round(v, 2) for v in selected.box.bbox],
"confidence": selected.box.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"