Files
douyi_guaji_main/douyin/handlers/live_tab_ocr.py
T

351 lines
12 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
LIVE_TAB_LAYOUT_CENTER_X_1080 = 718
@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 _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]))
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):
item = _plain(item)
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 = _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):
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 _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
):
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 _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
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) > 20:
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 _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:
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)
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)
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:
debug["reason"] = "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:
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
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"