208 lines
7.7 KiB
Python
208 lines
7.7 KiB
Python
from __future__ import annotations
|
|
|
|
import threading
|
|
from dataclasses import dataclass
|
|
from logging import LoggerAdapter
|
|
|
|
import numpy as np
|
|
from PySide6.QtCore import QObject, QRunnable, Signal
|
|
from PySide6.QtGui import QImage
|
|
from rapidocr_onnxruntime import RapidOCR
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class OCRMatch:
|
|
text: str
|
|
score: float
|
|
center_x: float
|
|
center_y: float
|
|
image_width: int
|
|
image_height: int
|
|
box: tuple[tuple[float, float], ...]
|
|
|
|
|
|
def _normalized(text: str) -> str:
|
|
return "".join(str(text).split()).lower()
|
|
|
|
|
|
def text_matches(candidate: str, target: str) -> bool:
|
|
"""True when the candidate plausibly is the target text.
|
|
|
|
Small streamed text is often misread by one glyph ("赚钱" -> "账钱"), merged
|
|
with its neighbours ("首页秒玩赚钱商城我的"), or truncated at the label edge
|
|
("放弃福利" -> "放弃福"), so besides an exact substring match we accept any
|
|
window of the candidate that differs from the target by at most one
|
|
character, and a candidate that is the target missing exactly one character.
|
|
"""
|
|
hay = _normalized(candidate)
|
|
needle = _normalized(target)
|
|
if not needle or needle in hay:
|
|
return True
|
|
if len(needle) < 2 or len(hay) < 2:
|
|
return False
|
|
if len(hay) < len(needle):
|
|
# Truncated detection: accept a contiguous piece missing exactly one glyph.
|
|
return len(hay) == len(needle) - 1 and hay in needle
|
|
for start in range(len(hay) - len(needle) + 1):
|
|
window = hay[start : start + len(needle)]
|
|
if sum(a != b for a, b in zip(window, needle)) <= 1:
|
|
return True
|
|
return False
|
|
|
|
|
|
def aim_at_target(match: OCRMatch, target: str) -> OCRMatch:
|
|
"""Shift the click center onto the target's position inside a wider detection.
|
|
|
|
When several labels merge into one detection ("首页秒玩赚钱商城我的"), the box
|
|
center falls on the middle tab, not on the wanted one; aim at the target's own
|
|
characters instead (CJK glyphs are roughly uniform width).
|
|
"""
|
|
hay = _normalized(match.text)
|
|
needle = _normalized(target)
|
|
if not hay or len(needle) >= len(hay):
|
|
return match
|
|
best_start: int | None = None
|
|
best_diff: int | None = None
|
|
for start in range(len(hay) - len(needle) + 1):
|
|
diff = sum(a != b for a, b in zip(hay[start : start + len(needle)], needle))
|
|
if best_diff is None or diff < best_diff:
|
|
best_start, best_diff = start, diff
|
|
if diff == 0:
|
|
break
|
|
if best_start is None:
|
|
return match
|
|
xs = [point[0] for point in match.box]
|
|
x0, x1 = min(xs), max(xs)
|
|
ratio = (best_start + len(needle) / 2) / len(hay)
|
|
return OCRMatch(
|
|
text=match.text,
|
|
score=match.score,
|
|
center_x=x0 + (x1 - x0) * ratio,
|
|
center_y=match.center_y,
|
|
image_width=match.image_width,
|
|
image_height=match.image_height,
|
|
box=match.box,
|
|
)
|
|
|
|
|
|
class OCRService:
|
|
"""One shared OCR model. Inference is serialized because model loading is expensive."""
|
|
|
|
def __init__(self) -> None:
|
|
self._engine: RapidOCR | None = None
|
|
self._lock = threading.Lock()
|
|
|
|
def _get_engine(self) -> RapidOCR:
|
|
if self._engine is None:
|
|
self._engine = RapidOCR()
|
|
return self._engine
|
|
|
|
def scan(self, image: np.ndarray, logger: LoggerAdapter | None = None) -> list[OCRMatch]:
|
|
"""Run OCR on the frame and return every detection."""
|
|
with self._lock:
|
|
result, _ = self._get_engine()(image)
|
|
detections = result or []
|
|
if logger:
|
|
logger.debug("ocr detections=%d", len(detections))
|
|
matches: list[OCRMatch] = []
|
|
for index, line in enumerate(detections):
|
|
box, text, score = line
|
|
try:
|
|
score_value = float(score)
|
|
except (TypeError, ValueError):
|
|
score_value = None
|
|
if logger:
|
|
logger.debug(
|
|
"ocr detection[%d] text=%r score=%r score_float=%s box=%s",
|
|
index,
|
|
text,
|
|
score,
|
|
score_value,
|
|
box,
|
|
)
|
|
if score_value is None:
|
|
if logger:
|
|
logger.warning("ocr detection=%r has invalid score=%r", text, score)
|
|
continue
|
|
points = np.asarray(box, dtype=float)
|
|
center = points.mean(axis=0)
|
|
matches.append(
|
|
OCRMatch(
|
|
text=str(text),
|
|
score=score_value,
|
|
center_x=float(center[0]),
|
|
center_y=float(center[1]),
|
|
image_width=int(image.shape[1]),
|
|
image_height=int(image.shape[0]),
|
|
box=tuple((float(point[0]), float(point[1])) for point in box),
|
|
)
|
|
)
|
|
return matches
|
|
|
|
def find_text(self, image: np.ndarray, target: str, logger: LoggerAdapter | None = None) -> OCRMatch | None:
|
|
matches = self.scan(image, logger)
|
|
wanted = _normalized(target)
|
|
exact = [match for match in matches if wanted in _normalized(match.text)]
|
|
if exact:
|
|
# Prefer the detection whose length matches the target: the clickable
|
|
# label equals the target, while hint sentences merely contain it
|
|
# ("确定要放弃福利吗" vs the actual "放弃福利" button).
|
|
best = min(exact, key=lambda match: (abs(len(_normalized(match.text)) - len(wanted)), -match.score))
|
|
return aim_at_target(best, target)
|
|
fuzzy = [match for match in matches if text_matches(match.text, target)]
|
|
if fuzzy:
|
|
best = min(fuzzy, key=lambda match: (abs(len(_normalized(match.text)) - len(wanted)), -match.score))
|
|
if logger:
|
|
logger.info("ocr fuzzy match target=%r via=%r score=%.4f", target, best.text, best.score)
|
|
return aim_at_target(best, target)
|
|
return None
|
|
|
|
|
|
class OCRSignals(QObject):
|
|
finished = Signal(object, object)
|
|
|
|
|
|
class OCRWorker(QRunnable):
|
|
def __init__(self, service: OCRService, image: np.ndarray, target: str, logger: LoggerAdapter | None = None) -> None:
|
|
super().__init__()
|
|
self.service = service
|
|
self.image = image
|
|
self.target = target
|
|
self.logger = logger
|
|
self.signals = OCRSignals()
|
|
|
|
def run(self) -> None:
|
|
try:
|
|
self.signals.finished.emit(self.service.find_text(self.image, self.target, self.logger), None)
|
|
except Exception as exc:
|
|
if self.logger:
|
|
self.logger.exception("ocr worker exception target=%r", self.target)
|
|
self.signals.finished.emit(None, exc)
|
|
|
|
|
|
class OCRScanWorker(QRunnable):
|
|
"""Async wrapper around OCRService.scan; reports every detection on the frame."""
|
|
|
|
def __init__(self, service: OCRService, image: np.ndarray, logger: LoggerAdapter | None = None) -> None:
|
|
super().__init__()
|
|
self.service = service
|
|
self.image = image
|
|
self.logger = logger
|
|
self.signals = OCRSignals()
|
|
|
|
def run(self) -> None:
|
|
try:
|
|
self.signals.finished.emit(self.service.scan(self.image, self.logger), None)
|
|
except Exception as exc:
|
|
if self.logger:
|
|
self.logger.exception("ocr scan worker exception")
|
|
self.signals.finished.emit(None, exc)
|
|
|
|
|
|
def qimage_to_bgr(image: QImage) -> np.ndarray:
|
|
converted = image.convertToFormat(QImage.Format.Format_RGBA8888)
|
|
width, height = converted.width(), converted.height()
|
|
data = converted.bits().tobytes()
|
|
rgba = np.frombuffer(data, dtype=np.uint8).reshape((height, width, 4))
|
|
return np.ascontiguousarray(rgba[:, :, :3][:, :, ::-1])
|