884 lines
38 KiB
Python
884 lines
38 KiB
Python
from __future__ import annotations
|
||
|
||
import re
|
||
import time
|
||
from abc import ABC, abstractmethod
|
||
from dataclasses import dataclass
|
||
from pathlib import Path
|
||
from typing import TYPE_CHECKING
|
||
|
||
import cv2
|
||
from PySide6.QtCore import QThreadPool, QTimer
|
||
from PySide6.QtGui import QColor, QPainter, QPen
|
||
|
||
from ocr_task import (
|
||
OCRMatch,
|
||
OCRScanWorker,
|
||
OCRService,
|
||
OCRWorker,
|
||
aim_at_target,
|
||
qimage_to_bgr,
|
||
text_matches,
|
||
)
|
||
|
||
if TYPE_CHECKING:
|
||
from logging import LoggerAdapter
|
||
from desktop_app import BrowserInstance
|
||
|
||
|
||
# Status-bar clocks change every minute and would break "stream stopped moving" detection.
|
||
CLOCK_TEXT = re.compile(r"^\d{1,2}:\d{2}$")
|
||
# OCR boxes jitter by a pixel or two between identical frames; quantize before comparing.
|
||
SIGNATURE_GRID = 4
|
||
# A side-by-side target must sit to the right of the anchor row (small slack for rounding).
|
||
RIGHT_SIDE_SLACK = 8.0
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ScriptStep:
|
||
"""One action in a script flow.
|
||
|
||
kind:
|
||
- "home": click the cloud-phone Home control
|
||
- "ocr_click": find step text via OCR and click it
|
||
- "scroll_ocr_click": find step text to the right of the anchor row; scroll
|
||
down and retry until found or the stream stops moving
|
||
- "await_click": once the confirm text shows up, wait at most await_ms for
|
||
step text (or any of alt_texts) and click it; give up when neither appears
|
||
- "delay_click": wait delay_ms, then click a stream-relative point (icon
|
||
targets that carry no OCR-readable text, e.g. an ad close X)
|
||
- "cond_ratio_click": scan until the confirm text shows up, then click a
|
||
stream-relative point; skip the step when the text never appears
|
||
- "loop": jump back to step `loop_to` until the body has run `loop_times`
|
||
times in total
|
||
- "delay_home": wait delay_ms, then click the cloud-phone Home control
|
||
- "cond_ocr_click": scan until the confirm text shows up, then click the
|
||
step text (first of text/alt_texts); skip the whole branch via skip_to
|
||
when the confirm never appears
|
||
- "gray_end": scan a stream-relative region; when it turns fully gray
|
||
(colored-pixel share at or below gray_threshold, e.g. finished task
|
||
buttons losing their color), end the whole script as completed
|
||
"""
|
||
|
||
kind: str
|
||
label: str
|
||
text: str = ""
|
||
# Alternative texts accepted for the same action: await_click clicks the first
|
||
# of text/alt_texts that shows up (ad templates swap the CTA label, e.g.
|
||
# "了解详情" / "立即体验").
|
||
alt_texts: tuple[str, ...] = ()
|
||
anchor: str = ""
|
||
confirm: str = ""
|
||
# Alternative confirm texts for cond_ratio_click: the step fires when any of
|
||
# confirm/alt_confirms shows up (ad templates swap the banner label, e.g.
|
||
# "看15秒" vs the reward notification bar "恭喜已获得").
|
||
alt_confirms: tuple[str, ...] = ()
|
||
# Countdown guard for cond_ratio_click: while any of these texts is on
|
||
# screen the confirm must not fire, so a reward notification bar
|
||
# ("恭喜已获得奖励…") cannot trigger the click before the "继续浏览15秒"
|
||
# countdown finishes, and other always-on markers cannot fake the confirm.
|
||
absent: str = ""
|
||
alt_absents: tuple[str, ...] = ()
|
||
await_ms: int = 10_000
|
||
delay_ms: int = 20_000
|
||
x_ratio: float = 0.0
|
||
y_ratio: float = 0.0
|
||
# "gray_end" step: detection region size as fractions of the stream rect;
|
||
# the whole stream when left at defaults.
|
||
w_ratio: float = 1.0
|
||
h_ratio: float = 1.0
|
||
# "gray_end" step: the region counts as "fully gray" when the colored-pixel
|
||
# share (HSV saturation >= 60 and value >= 60) drops to or below this
|
||
# threshold — finished task buttons lose their color, so a fully gray task
|
||
# row means every reward has been claimed.
|
||
gray_threshold: float = 0.03
|
||
offset_y_ratio: float = 0.0
|
||
max_scans: int = 20
|
||
# Template-dependent targets skip forward instead of failing the script when
|
||
# they never show up (e.g. reward popups whose close flow differs per ad).
|
||
optional: bool = False
|
||
# "loop" step: index to jump back to and how many times the loop body runs.
|
||
loop_to: int = -1
|
||
loop_times: int = 1
|
||
# "cond_ocr_click" step: when the confirm never appears within max_scans,
|
||
# jump straight to this step index instead of the next one, skipping the
|
||
# whole conditional branch.
|
||
skip_to: int = -1
|
||
# Pick the first (topmost) among multiple same-text matches instead of the
|
||
# best-scoring one (download pages repeat the 立即下载 button).
|
||
pick_top: bool = False
|
||
|
||
|
||
def _box_bounds(match: OCRMatch) -> tuple[float, float, float, float]:
|
||
xs = [point[0] for point in match.box]
|
||
ys = [point[1] for point in match.box]
|
||
return min(xs), max(xs), min(ys), max(ys)
|
||
|
||
|
||
class BrowserScript(ABC):
|
||
script_id: str
|
||
label: str
|
||
target_text: str
|
||
# Home-screen app names are rendered below their icons, so the touch target is above the OCR label.
|
||
click_offset_y_ratio: float = 0.0
|
||
# Multi-step flow; None keeps the legacy "Home → click target_text" two-step script.
|
||
steps: list[ScriptStep] | None = None
|
||
|
||
def __init__(self, instance: "BrowserInstance", ocr_service: OCRService, logger: "LoggerAdapter") -> None:
|
||
self.instance = instance
|
||
self.ocr_service = ocr_service
|
||
self.logger = logger
|
||
self.running = False
|
||
self.attempts = 0
|
||
self.step_index = 0
|
||
self.scan_index = 0
|
||
self.static_scans = 0
|
||
self.frame_signature: tuple | None = None
|
||
# Monotonic deadline for await_click steps; None until the landmark is seen.
|
||
self.await_deadline: float | None = None
|
||
self.workers: list[OCRWorker] = []
|
||
self.scan_workers: list[OCRScanWorker] = []
|
||
self.last_capture = None
|
||
# Executions of each "loop" step so far, keyed by step index.
|
||
self.loop_counts: dict[int, int] = {}
|
||
|
||
def plan_steps(self) -> list[ScriptStep]:
|
||
if self.steps is not None:
|
||
return list(self.steps)
|
||
return [
|
||
ScriptStep(kind="home", label="点击云手机 Home 按钮"),
|
||
ScriptStep(
|
||
kind="ocr_click",
|
||
label=f"OCR 查找“{self.target_text}”",
|
||
text=self.target_text,
|
||
offset_y_ratio=self.click_offset_y_ratio,
|
||
),
|
||
]
|
||
|
||
def start(self) -> None:
|
||
if self.running:
|
||
return
|
||
if not self.instance.page_ready:
|
||
self.logger.info("script=%s delayed: page is not ready", self.script_id)
|
||
# Store the instance itself so ad-hoc scripts (live debug panel)
|
||
# resume without a registry lookup.
|
||
self.instance.pending_script = self
|
||
self.instance.set_status("等待页面")
|
||
self.instance.message.setText("页面加载完成后自动开始脚本")
|
||
return
|
||
|
||
self.running = True
|
||
self.instance.active_script = self
|
||
self.attempts = 0
|
||
self.step_index = 0
|
||
self.loop_counts = {}
|
||
self.logger.info("script=%s started target=%s url=%s", self.script_id, self.target_text, self.instance.page.url().toString())
|
||
self.run_current_step()
|
||
|
||
def stop(self) -> None:
|
||
if self.running:
|
||
self.logger.info("script=%s stopped by user", self.script_id)
|
||
self.running = False
|
||
self.instance.pending_script = None
|
||
self.instance.set_status("已暂停")
|
||
self.instance.message.setText("脚本已停止,浏览器保持打开")
|
||
|
||
def run_current_step(self) -> None:
|
||
if not self.running:
|
||
return
|
||
steps = self.plan_steps()
|
||
step = steps[self.step_index]
|
||
self.instance.message.setText(f"步骤 {self.step_index + 1}/{len(steps)}:{step.label}")
|
||
if step.kind == "home":
|
||
self.instance.set_status("Task: Home")
|
||
self.instance.click_cloud_home()
|
||
self.logger.debug("cloud phone Home navigation click requested")
|
||
QTimer.singleShot(600, self.advance_step)
|
||
elif step.kind == "ocr_click":
|
||
self.instance.set_status("Task: OCR")
|
||
self.attempts = 0
|
||
self.find_target()
|
||
elif step.kind == "scroll_ocr_click":
|
||
self.instance.set_status("Task: OCR")
|
||
self.scan_index = 0
|
||
self.static_scans = 0
|
||
self.frame_signature = None
|
||
self.instance.probe_stream_rect()
|
||
# Give the freshly opened screen a moment to settle before the first scan.
|
||
QTimer.singleShot(800, self.find_scan)
|
||
elif step.kind == "await_click":
|
||
self.instance.set_status("Task: OCR")
|
||
self.scan_index = 0
|
||
self.await_deadline = None
|
||
# The freshly opened screen needs a moment before the first scan.
|
||
QTimer.singleShot(800, self.find_scan)
|
||
elif step.kind == "cond_ratio_click":
|
||
self.instance.set_status("Task: OCR")
|
||
self.scan_index = 0
|
||
# Cache the stream rect so the conditional click uses live geometry.
|
||
self.instance.probe_stream_rect()
|
||
# The screen may still be mid-transition; give it a moment first.
|
||
QTimer.singleShot(800, self.find_scan)
|
||
elif step.kind == "delay_click":
|
||
self.instance.set_status("Task: Wait")
|
||
# Cache the stream rect now so the click after the wait uses live geometry.
|
||
self.instance.probe_stream_rect()
|
||
QTimer.singleShot(step.delay_ms, self.click_stream_point)
|
||
elif step.kind == "gray_end":
|
||
self.instance.set_status("Task: OCR")
|
||
self.scan_index = 0
|
||
# Cache the stream rect so the region check uses live geometry.
|
||
self.instance.probe_stream_rect()
|
||
# The freshly opened screen needs a moment before the first check.
|
||
QTimer.singleShot(800, self.gray_check)
|
||
elif step.kind == "loop":
|
||
executed = self.loop_counts.get(self.step_index, 0) + 1
|
||
self.loop_counts[self.step_index] = executed
|
||
if executed < step.loop_times:
|
||
self.logger.info(
|
||
"loop round=%d/%d jumping to step=%d",
|
||
executed,
|
||
step.loop_times,
|
||
step.loop_to,
|
||
)
|
||
self.step_index = step.loop_to
|
||
self.run_current_step()
|
||
else:
|
||
self.advance_step(f"已循环完成 {step.loop_times} 轮")
|
||
elif step.kind == "delay_home":
|
||
self.instance.set_status("Task: Wait")
|
||
self.logger.info("delay_home waiting %dms before going Home", step.delay_ms)
|
||
QTimer.singleShot(step.delay_ms, self.delay_home_click)
|
||
elif step.kind == "cond_ocr_click":
|
||
self.instance.set_status("Task: OCR")
|
||
self.scan_index = 0
|
||
# The freshly entered screen needs a moment before the first scan.
|
||
QTimer.singleShot(800, self.find_scan)
|
||
else:
|
||
self.logger.error("script=%s unknown step kind=%r", self.script_id, step.kind)
|
||
self.finish("脚本失败", f"未知步骤类型:{step.kind}")
|
||
|
||
def advance_step(self, note: str = "") -> None:
|
||
if not self.running:
|
||
return
|
||
self.step_index += 1
|
||
if self.step_index >= len(self.plan_steps()):
|
||
self.finish("脚本完成", note or "全部步骤已完成")
|
||
return
|
||
self.run_current_step()
|
||
|
||
# --- ocr_click step ------------------------------------------------------
|
||
|
||
def find_target(self) -> None:
|
||
if not self.running:
|
||
return
|
||
self.attempts += 1
|
||
steps = self.plan_steps()
|
||
step = steps[self.step_index]
|
||
self.instance.set_status("Task: OCR")
|
||
self.instance.message.setText(
|
||
f"步骤 {self.step_index + 1}/{len(steps)}:{step.label}(第 {self.attempts} 次)"
|
||
)
|
||
image = self.instance.view.grab().toImage()
|
||
self.last_capture = image.copy()
|
||
frame = qimage_to_bgr(image)
|
||
self.logger.info(
|
||
"ocr attempt=%d target=%s image=%dx%d dpr=%.3f view=%dx%d url=%s",
|
||
self.attempts,
|
||
step.text,
|
||
frame.shape[1],
|
||
frame.shape[0],
|
||
image.devicePixelRatio(),
|
||
self.instance.view.width(),
|
||
self.instance.view.height(),
|
||
self.instance.page.url().toString(),
|
||
)
|
||
worker = OCRWorker(self.ocr_service, frame, step.text, self.logger)
|
||
self.workers.append(worker)
|
||
worker.signals.finished.connect(self.ocr_finished)
|
||
QThreadPool.globalInstance().start(worker)
|
||
|
||
def ocr_finished(self, match: object, error: object) -> None:
|
||
if self.workers:
|
||
self.workers.pop(0)
|
||
if not self.running:
|
||
return
|
||
if error is not None:
|
||
self.logger.error("ocr failed error=%r", error)
|
||
self.finish("OCR 失败", f"OCR 执行失败:{error}")
|
||
return
|
||
if match is None:
|
||
step = self.plan_steps()[self.step_index]
|
||
self.logger.warning("ocr attempt=%d target=%s: no match", self.attempts, step.text)
|
||
if self.attempts < 8:
|
||
QTimer.singleShot(700, self.find_target)
|
||
else:
|
||
self.finish("未找到目标", f"OCR 未找到“{step.text}”,浏览器保持打开")
|
||
return
|
||
|
||
step = self.plan_steps()[self.step_index]
|
||
x, y = self.click_point_of(step, match)
|
||
self.logger.info(
|
||
"ocr match text=%r score=%.4f box_center=(%.1f,%.1f) image=%dx%d click_offset_y_ratio=%.3f mapped_click=(%d,%d)",
|
||
match.text,
|
||
match.score,
|
||
match.center_x,
|
||
match.center_y,
|
||
match.image_width,
|
||
match.image_height,
|
||
step.offset_y_ratio,
|
||
x,
|
||
y,
|
||
)
|
||
self.save_debug_capture(match, x, y, "ocr")
|
||
self.instance.click_ocr_point(x, y, match, self.click_finished)
|
||
|
||
# --- scroll_ocr_click step -----------------------------------------------
|
||
|
||
def find_scan(self) -> None:
|
||
if not self.running:
|
||
return
|
||
steps = self.plan_steps()
|
||
step = steps[self.step_index]
|
||
self.scan_index += 1
|
||
self.instance.set_status("Task: OCR")
|
||
self.instance.message.setText(
|
||
f"步骤 {self.step_index + 1}/{len(steps)}:{step.label}(第 {self.scan_index} 次扫描)"
|
||
)
|
||
image = self.instance.view.grab().toImage()
|
||
self.last_capture = image.copy()
|
||
frame = qimage_to_bgr(image)
|
||
self.logger.info(
|
||
"ocr scan=%d anchor=%s confirm=%s target=%s image=%dx%d dpr=%.3f view=%dx%d url=%s",
|
||
self.scan_index,
|
||
step.anchor,
|
||
step.confirm,
|
||
step.text,
|
||
frame.shape[1],
|
||
frame.shape[0],
|
||
image.devicePixelRatio(),
|
||
self.instance.view.width(),
|
||
self.instance.view.height(),
|
||
self.instance.page.url().toString(),
|
||
)
|
||
worker = OCRScanWorker(self.ocr_service, frame, self.logger)
|
||
self.scan_workers.append(worker)
|
||
worker.signals.finished.connect(self.scan_finished)
|
||
QThreadPool.globalInstance().start(worker)
|
||
|
||
def scan_finished(self, detections: object, error: object) -> None:
|
||
if self.scan_workers:
|
||
self.scan_workers.pop(0)
|
||
if not self.running:
|
||
return
|
||
if error is not None:
|
||
self.logger.error("ocr scan failed error=%r", error)
|
||
self.finish("OCR 失败", f"OCR 执行失败:{error}")
|
||
return
|
||
step = self.plan_steps()[self.step_index]
|
||
items = [detection for detection in (detections or []) if isinstance(detection, OCRMatch)]
|
||
if step.kind == "await_click":
|
||
self.await_scan_finished(step, items)
|
||
return
|
||
if step.kind == "cond_ratio_click":
|
||
self.cond_scan_finished(step, items)
|
||
return
|
||
if step.kind == "cond_ocr_click":
|
||
self.cond_click_scan_finished(step, items)
|
||
return
|
||
target = self.match_beside_anchor(items, step.anchor, step.text)
|
||
if target is not None:
|
||
x, y = self.click_point_of(step, target)
|
||
self.logger.info(
|
||
"scan match text=%r score=%.4f box_center=(%.1f,%.1f) anchor=%r mapped_click=(%d,%d)",
|
||
target.text,
|
||
target.score,
|
||
target.center_x,
|
||
target.center_y,
|
||
step.anchor,
|
||
x,
|
||
y,
|
||
)
|
||
self.save_debug_capture(target, x, y, "scan")
|
||
self.instance.click_ocr_point(x, y, target, self.click_finished)
|
||
return
|
||
|
||
self.logger.warning(
|
||
"ocr scan=%d anchor=%s target=%s: no side-by-side match",
|
||
self.scan_index,
|
||
step.anchor,
|
||
step.text,
|
||
)
|
||
signature = self.frame_signature_of(items)
|
||
if signature == self.frame_signature:
|
||
self.static_scans += 1
|
||
else:
|
||
self.static_scans = 0
|
||
self.frame_signature = signature
|
||
if self.static_scans >= 2:
|
||
self.logger.info("scan=%d stream stopped moving: reached the bottom", self.scan_index)
|
||
self.finish("未找到目标", f"已滚动到底部,未见“{step.text}”")
|
||
return
|
||
if self.scan_index >= step.max_scans:
|
||
self.logger.warning("scan=%d reached max scans=%d", self.scan_index, step.max_scans)
|
||
self.finish("未找到目标", f"扫描 {self.scan_index} 次仍未找到“{step.text}”")
|
||
return
|
||
self.instance.scroll_stream()
|
||
self.logger.info("stream scroll down requested after scan=%d", self.scan_index)
|
||
QTimer.singleShot(1500, self.find_scan)
|
||
|
||
# --- await_click step ----------------------------------------------------
|
||
|
||
def await_scan_finished(self, step: ScriptStep, items: list[OCRMatch]) -> None:
|
||
"""Handle one await_click scan: click the target as soon as it shows up."""
|
||
wanted = [text for text in (step.text, *step.alt_texts) if text]
|
||
target = None
|
||
target_text = ""
|
||
best_rank = None
|
||
for detection in items:
|
||
for wanted_text in wanted:
|
||
if not text_matches(detection.text, wanted_text):
|
||
continue
|
||
# Prefer the detection whose length matches the wanted text: the CTA
|
||
# button label equals the target, while hint sentences merely contain
|
||
# it ("确定要放弃福利吗" vs the actual "放弃福利" button).
|
||
rank = (abs(len(detection.text.strip()) - len(wanted_text)), -detection.score)
|
||
if best_rank is None or rank < best_rank:
|
||
best_rank = rank
|
||
target = detection
|
||
target_text = wanted_text
|
||
if target is not None:
|
||
target = aim_at_target(target, target_text)
|
||
x, y = self.click_point_of(step, target)
|
||
self.logger.info(
|
||
"await match text=%r score=%.4f box_center=(%.1f,%.1f) target=%r mapped_click=(%d,%d)",
|
||
target.text,
|
||
target.score,
|
||
target.center_x,
|
||
target.center_y,
|
||
target_text,
|
||
x,
|
||
y,
|
||
)
|
||
self.save_debug_capture(target, x, y, "scan")
|
||
self.instance.click_ocr_point(x, y, target, self.click_finished)
|
||
return
|
||
|
||
display = "/".join(wanted)
|
||
now = time.monotonic()
|
||
landmark_seen = not step.confirm or any(
|
||
text_matches(detection.text, step.confirm) for detection in items
|
||
)
|
||
if landmark_seen and self.await_deadline is None:
|
||
self.await_deadline = now + step.await_ms / 1000.0
|
||
self.logger.info(
|
||
"await landmark=%r confirmed; waiting up to %.0fs for %r",
|
||
step.confirm,
|
||
step.await_ms / 1000.0,
|
||
display,
|
||
)
|
||
if self.await_deadline is not None:
|
||
if now >= self.await_deadline:
|
||
if step.optional:
|
||
self.logger.info(
|
||
"await scan=%d target=%r not shown within %dms; optional, continuing",
|
||
self.scan_index,
|
||
display,
|
||
step.await_ms,
|
||
)
|
||
self.advance_step(f"等待 {step.await_ms // 1000} 秒未见“{display}”,跳过")
|
||
return
|
||
self.logger.warning(
|
||
"await scan=%d target=%r not shown within %dms",
|
||
self.scan_index,
|
||
display,
|
||
step.await_ms,
|
||
)
|
||
self.finish("未找到目标", f"等待 {step.await_ms // 1000} 秒未见“{display}”,任务终止")
|
||
return
|
||
elif self.scan_index >= step.max_scans:
|
||
# The landmark never showed up: probably not on the expected page at all.
|
||
if step.optional:
|
||
self.logger.info(
|
||
"await scan=%d landmark=%r not seen; optional, continuing",
|
||
self.scan_index,
|
||
step.confirm,
|
||
)
|
||
self.advance_step(f"未见“{step.confirm}”提示,跳过")
|
||
return
|
||
self.logger.warning(
|
||
"await scan=%d landmark=%r not seen", self.scan_index, step.confirm
|
||
)
|
||
self.finish("未找到目标", f"未见“{step.confirm}”提示,任务终止")
|
||
return
|
||
QTimer.singleShot(1000, self.find_scan)
|
||
|
||
# --- cond_ratio_click step ------------------------------------------------
|
||
|
||
def cond_scan_finished(self, step: ScriptStep, items: list[OCRMatch]) -> None:
|
||
"""Handle one cond_ratio_click scan: click the stream point once the confirm text shows up."""
|
||
confirms = [text for text in (step.confirm, *step.alt_confirms) if text]
|
||
blockers = [text for text in (step.absent, *step.alt_absents) if text]
|
||
if blockers:
|
||
blocker = next(
|
||
(
|
||
detection
|
||
for detection in items
|
||
if any(text_matches(detection.text, wanted) for wanted in blockers)
|
||
),
|
||
None,
|
||
)
|
||
if blocker is not None and self.scan_index < step.max_scans:
|
||
# A blocker text is still on screen: the confirm seen now would
|
||
# be an always-on marker (notification bar / other page), not
|
||
# the finished countdown.
|
||
self.logger.debug(
|
||
"cond confirm=%r blocked by absent text=%r; waiting",
|
||
"/".join(confirms),
|
||
blocker.text,
|
||
)
|
||
QTimer.singleShot(1000, self.find_scan)
|
||
return
|
||
for wanted in confirms:
|
||
hit = next(
|
||
(detection for detection in items if text_matches(detection.text, wanted)),
|
||
None,
|
||
)
|
||
if hit is not None:
|
||
self.logger.info(
|
||
"cond match text=%r confirmed via=%r; clicking stream point (%.3f, %.3f)",
|
||
hit.text,
|
||
wanted,
|
||
step.x_ratio,
|
||
step.y_ratio,
|
||
)
|
||
self.instance.set_status("Task: Click")
|
||
self.last_capture = self.instance.view.grab().toImage().copy()
|
||
self.save_raw_capture("ratio")
|
||
self.instance.click_stream_ratio(step.x_ratio, step.y_ratio, self.stream_click_finished)
|
||
return
|
||
if self.scan_index >= step.max_scans:
|
||
self.logger.info(
|
||
"cond scan=%d confirm=%r not seen; skipping step",
|
||
self.scan_index,
|
||
"/".join(confirms),
|
||
)
|
||
self.advance_step(f"未见“{'/'.join(confirms)}”,跳过")
|
||
return
|
||
QTimer.singleShot(1000, self.find_scan)
|
||
|
||
# --- delay_click step ----------------------------------------------------
|
||
|
||
def click_stream_point(self) -> None:
|
||
"""Click the fixed stream-relative point of a delay_click step."""
|
||
if not self.running:
|
||
return
|
||
step = self.plan_steps()[self.step_index]
|
||
self.instance.set_status("Task: Click")
|
||
self.last_capture = self.instance.view.grab().toImage().copy()
|
||
self.save_raw_capture("ratio")
|
||
self.instance.click_stream_ratio(step.x_ratio, step.y_ratio, self.stream_click_finished)
|
||
|
||
def stream_click_finished(self, x: int, y: int) -> None:
|
||
self.logger.info("stream ratio click done coord=(%d,%d)", x, y)
|
||
self.advance_step(f"已点击坐标 ({x},{y})")
|
||
|
||
# --- gray_end step ---------------------------------------------------------
|
||
|
||
def gray_check(self) -> None:
|
||
"""Handle one gray_end scan: end the script when the region turns fully gray."""
|
||
if not self.running:
|
||
return
|
||
steps = self.plan_steps()
|
||
step = steps[self.step_index]
|
||
self.scan_index += 1
|
||
self.instance.set_status("Task: OCR")
|
||
self.instance.message.setText(
|
||
f"步骤 {self.step_index + 1}/{len(steps)}:{step.label}(第 {self.scan_index} 次扫描)"
|
||
)
|
||
image = self.instance.view.grab().toImage()
|
||
self.last_capture = image.copy()
|
||
frame = qimage_to_bgr(image)
|
||
rect = self.instance.stream_rect if isinstance(self.instance.stream_rect, dict) else None
|
||
if rect is None:
|
||
# No probed rect: fall back to the whole view as the stream region.
|
||
rect = {
|
||
"x": 0,
|
||
"y": 0,
|
||
"width": self.instance.view.width(),
|
||
"height": self.instance.view.height(),
|
||
}
|
||
try:
|
||
scale_x = frame.shape[1] / max(1, self.instance.view.width())
|
||
scale_y = frame.shape[0] / max(1, self.instance.view.height())
|
||
left = max(0, int((float(rect["x"]) + float(rect["width"]) * step.x_ratio) * scale_x))
|
||
top = max(0, int((float(rect["y"]) + float(rect["height"]) * step.y_ratio) * scale_y))
|
||
right = min(
|
||
frame.shape[1],
|
||
int((float(rect["x"]) + float(rect["width"]) * (step.x_ratio + step.w_ratio)) * scale_x),
|
||
)
|
||
bottom = min(
|
||
frame.shape[0],
|
||
int((float(rect["y"]) + float(rect["height"]) * (step.y_ratio + step.h_ratio)) * scale_y),
|
||
)
|
||
except (KeyError, TypeError, ValueError):
|
||
self.logger.warning("gray check region invalid rect=%r", rect)
|
||
self.advance_step("无法定位检测区域,跳过")
|
||
return
|
||
region = frame[top:bottom, left:right]
|
||
if region.size == 0:
|
||
self.logger.warning(
|
||
"gray check region empty left=%d top=%d right=%d bottom=%d",
|
||
left,
|
||
top,
|
||
right,
|
||
bottom,
|
||
)
|
||
self.advance_step("检测区域为空,跳过")
|
||
return
|
||
hsv = cv2.cvtColor(region, cv2.COLOR_BGR2HSV)
|
||
colored = float(((hsv[..., 1] >= 60) & (hsv[..., 2] >= 60)).mean())
|
||
self.logger.info(
|
||
"gray check scan=%d region=%dx%d+%d,%d colored=%.1f%% threshold=%.1f%%",
|
||
self.scan_index,
|
||
right - left,
|
||
bottom - top,
|
||
left,
|
||
top,
|
||
colored * 100,
|
||
step.gray_threshold * 100,
|
||
)
|
||
if colored <= step.gray_threshold:
|
||
self.save_raw_capture("gray")
|
||
self.logger.info(
|
||
"gray check scan=%d region fully gray (%.1f%% colored); ending script",
|
||
self.scan_index,
|
||
colored * 100,
|
||
)
|
||
self.finish(
|
||
"脚本完成",
|
||
f"检测到任务区已全灰(彩色像素 {colored * 100:.1f}%),奖励已领完,流程结束",
|
||
)
|
||
return
|
||
if self.scan_index >= step.max_scans:
|
||
self.logger.info(
|
||
"gray check scan=%d region still colored (%.1f%%); continuing script",
|
||
self.scan_index,
|
||
colored * 100,
|
||
)
|
||
self.advance_step(f"任务区未全灰(彩色像素 {colored * 100:.1f}%),继续流程")
|
||
return
|
||
QTimer.singleShot(1000, self.gray_check)
|
||
|
||
# --- delay_home step ------------------------------------------------------
|
||
|
||
def delay_home_click(self) -> None:
|
||
"""Click the cloud-phone Home control after the delay_home wait."""
|
||
if not self.running:
|
||
return
|
||
self.instance.set_status("Task: Home")
|
||
self.instance.click_cloud_home()
|
||
self.logger.info("delay_home clicked the cloud phone Home control")
|
||
QTimer.singleShot(600, self.advance_step)
|
||
|
||
# --- cond_ocr_click step ---------------------------------------------------
|
||
|
||
def cond_click_scan_finished(self, step: ScriptStep, items: list[OCRMatch]) -> None:
|
||
"""Handle one cond_ocr_click scan: click the step text once the confirm text shows up."""
|
||
confirmed = not step.confirm or any(
|
||
text_matches(detection.text, step.confirm) for detection in items
|
||
)
|
||
if confirmed:
|
||
wanted = [text for text in (step.text, *step.alt_texts) if text]
|
||
candidates = [
|
||
detection
|
||
for detection in items
|
||
if any(text_matches(detection.text, text) for text in wanted)
|
||
]
|
||
if candidates:
|
||
if step.pick_top:
|
||
# Repeated same-text buttons (download pages): take the first
|
||
# on screen, not the best-scoring one.
|
||
target = min(candidates, key=lambda detection: detection.center_y)
|
||
else:
|
||
target = max(candidates, key=lambda detection: detection.score)
|
||
target_text = next(
|
||
text for text in wanted if text_matches(target.text, text)
|
||
)
|
||
target = aim_at_target(target, target_text)
|
||
x, y = self.click_point_of(step, target)
|
||
self.logger.info(
|
||
"cond click match text=%r score=%.4f box_center=(%.1f,%.1f) target=%r pick_top=%s mapped_click=(%d,%d)",
|
||
target.text,
|
||
target.score,
|
||
target.center_x,
|
||
target.center_y,
|
||
target_text,
|
||
step.pick_top,
|
||
x,
|
||
y,
|
||
)
|
||
self.save_debug_capture(target, x, y, "scan")
|
||
self.instance.click_ocr_point(x, y, target, self.click_finished)
|
||
return
|
||
# Confirm hit but no clickable text: treat the confirm itself as the
|
||
# trigger and click the step text anyway on the next pass.
|
||
self.logger.warning(
|
||
"cond click confirm=%r seen but no %r candidate; rescanning",
|
||
step.confirm,
|
||
"/".join(wanted),
|
||
)
|
||
if self.scan_index >= step.max_scans:
|
||
if step.skip_to >= 0:
|
||
self.logger.info(
|
||
"cond click scan=%d confirm=%r not seen; skipping branch to step=%d",
|
||
self.scan_index,
|
||
step.confirm,
|
||
step.skip_to,
|
||
)
|
||
self.step_index = step.skip_to
|
||
self.run_current_step()
|
||
return
|
||
self.logger.warning(
|
||
"cond click scan=%d confirm=%r not seen; skipping step",
|
||
self.scan_index,
|
||
step.confirm,
|
||
)
|
||
self.advance_step(f"未见“{step.confirm}”,跳过")
|
||
return
|
||
QTimer.singleShot(1000, self.find_scan)
|
||
|
||
def match_beside_anchor(self, detections: list[OCRMatch], anchor: str, target: str) -> OCRMatch | None:
|
||
"""Return the best `target` detection sitting to the right of the anchor text row."""
|
||
candidates = [detection for detection in detections if text_matches(detection.text, target)]
|
||
if not anchor:
|
||
return max(candidates, key=lambda detection: detection.score) if candidates else None
|
||
anchors = [detection for detection in detections if text_matches(detection.text, anchor)]
|
||
best: OCRMatch | None = None
|
||
for anchor_match in sorted(anchors, key=lambda detection: -detection.score):
|
||
_, anchor_x1, anchor_y0, anchor_y1 = _box_bounds(anchor_match)
|
||
for candidate in sorted(candidates, key=lambda detection: -detection.score):
|
||
candidate_x0, _, candidate_y0, candidate_y1 = _box_bounds(candidate)
|
||
same_row = anchor_y0 < candidate_y1 and candidate_y0 < anchor_y1
|
||
to_the_right = candidate_x0 >= anchor_x1 - RIGHT_SIDE_SLACK
|
||
if same_row and to_the_right and (best is None or candidate.score > best.score):
|
||
best = candidate
|
||
if best is None:
|
||
# OCR often merges the anchor row and its button into one detection
|
||
# ("看精彩视频领积分去观看"); aim straight at the target inside that box.
|
||
merged = [
|
||
detection
|
||
for detection in candidates
|
||
if text_matches(detection.text, anchor)
|
||
]
|
||
if merged:
|
||
best = aim_at_target(max(merged, key=lambda detection: detection.score), target)
|
||
return best
|
||
|
||
def frame_signature_of(self, detections: list[OCRMatch]) -> tuple:
|
||
"""Fingerprint of the phone-screen text; equal fingerprints mean the stream did not move."""
|
||
dpr = float(self.last_capture.devicePixelRatio() or 1.0) if self.last_capture else 1.0
|
||
rect = self.instance.stream_rect if isinstance(self.instance.stream_rect, dict) else None
|
||
items = []
|
||
for detection in detections:
|
||
if CLOCK_TEXT.match(detection.text.strip()):
|
||
continue
|
||
x0, x1, y0, y1 = _box_bounds(detection)
|
||
if rect is not None:
|
||
try:
|
||
left = float(rect["x"]) * dpr
|
||
top = float(rect["y"]) * dpr
|
||
right = left + float(rect["width"]) * dpr
|
||
bottom = top + float(rect["height"]) * dpr
|
||
except (KeyError, TypeError, ValueError):
|
||
left = top = right = bottom = None
|
||
if right is not None and not (left <= detection.center_x <= right and top <= detection.center_y <= bottom):
|
||
# H5 toolbar / page text outside the phone screen; ignore it.
|
||
continue
|
||
items.append(
|
||
(
|
||
detection.text,
|
||
round(x0 / SIGNATURE_GRID),
|
||
round(y0 / SIGNATURE_GRID),
|
||
round(x1 / SIGNATURE_GRID),
|
||
round(y1 / SIGNATURE_GRID),
|
||
)
|
||
)
|
||
return tuple(sorted(items))
|
||
|
||
# --- shared helpers -------------------------------------------------------
|
||
|
||
def click_point_of(self, step: ScriptStep, match: OCRMatch) -> tuple[int, int]:
|
||
click_center_y = match.center_y + step.offset_y_ratio * match.image_height
|
||
click_center_y = max(0.0, min(float(match.image_height), click_center_y))
|
||
x = int(match.center_x * self.instance.view.width() / match.image_width)
|
||
y = int(click_center_y * self.instance.view.height() / match.image_height)
|
||
return x, y
|
||
|
||
def save_debug_capture(self, match: object, x: int, y: int, tag: str) -> None:
|
||
if self.last_capture is None:
|
||
return
|
||
image = self.last_capture.copy()
|
||
painter = QPainter(image)
|
||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||
painter.setPen(QPen(QColor("#ff3b30"), 3))
|
||
points = [
|
||
(int(px), int(py))
|
||
for px, py in match.box
|
||
]
|
||
for index, point in enumerate(points):
|
||
next_point = points[(index + 1) % len(points)]
|
||
painter.drawLine(point[0], point[1], next_point[0], next_point[1])
|
||
painter.setPen(QPen(QColor("#00d26a"), 4))
|
||
painter.drawEllipse(int(match.center_x) - 8, int(match.center_y) - 8, 16, 16)
|
||
click_image_x = x * image.width() / max(1, self.instance.view.width())
|
||
click_image_y = y * image.height() / max(1, self.instance.view.height())
|
||
painter.setPen(QPen(QColor("#1769ff"), 4))
|
||
painter.drawEllipse(int(click_image_x) - 10, int(click_image_y) - 10, 20, 20)
|
||
painter.end()
|
||
|
||
output_dir = Path(__file__).resolve().parent.parent / "data" / "logs" / "screenshots"
|
||
output_dir.mkdir(parents=True, exist_ok=True)
|
||
sequence = self.attempts if tag == "ocr" else self.scan_index
|
||
output = output_dir / f"instance-{self.instance.instance_id}-{tag}-{sequence}.png"
|
||
if image.save(str(output), "PNG"):
|
||
self.logger.info(
|
||
"debug image saved path=%s ocr_center=(%.1f,%.1f) click_marker=(%.1f,%.1f) mapped_click=(%d,%d)",
|
||
output,
|
||
match.center_x,
|
||
match.center_y,
|
||
click_image_x,
|
||
click_image_y,
|
||
x,
|
||
y,
|
||
)
|
||
else:
|
||
self.logger.warning("debug image save failed path=%s", output)
|
||
|
||
def save_raw_capture(self, tag: str) -> None:
|
||
"""Save the current capture without annotations (icon-click diagnostics)."""
|
||
if self.last_capture is None:
|
||
return
|
||
output_dir = Path(__file__).resolve().parent.parent / "data" / "logs" / "screenshots"
|
||
output_dir.mkdir(parents=True, exist_ok=True)
|
||
output = output_dir / f"instance-{self.instance.instance_id}-{tag}-{self.step_index + 1}.png"
|
||
if self.last_capture.save(str(output), "PNG"):
|
||
self.logger.info("raw capture saved path=%s", output)
|
||
else:
|
||
self.logger.warning("raw capture save failed path=%s", output)
|
||
|
||
def click_finished(self, result: object, match: object, x: int, y: int) -> None:
|
||
self.logger.info("click result=%r coord=(%d,%d) match=%r", result, x, y, match.text)
|
||
method = result.get("method", "unknown") if isinstance(result, dict) else "unknown"
|
||
self.advance_step(f"已点击“{match.text}”(置信度 {match.score:.2f},{method})")
|
||
|
||
def finish(self, status: str, message: str) -> None:
|
||
self.running = False
|
||
self.instance.set_status(status)
|
||
self.instance.message.setText(message)
|
||
self.logger.info("script=%s finished status=%s message=%s", self.script_id, status, message)
|
||
|
||
@abstractmethod
|
||
def name(self) -> str:
|
||
raise NotImplementedError
|