noracu 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -0
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/docs/tools.md +11 -11
- package/imctl/src/imctl/cli.py +201 -19
- package/imctl/src/imctl/gestures.py +390 -29
- package/imctl/src/imctl/input.py +360 -41
- package/imctl/src/imctl/verify.py +250 -1
- package/imctl/src/imctl/vision.py +214 -29
- package/imctl/src/imctl/window.py +189 -35
- package/package.json +1 -1
- package/src/server.mjs +111 -28
|
@@ -12,9 +12,11 @@ from __future__ import annotations
|
|
|
12
12
|
import hashlib
|
|
13
13
|
import subprocess
|
|
14
14
|
import tempfile
|
|
15
|
+
import unicodedata
|
|
15
16
|
from dataclasses import dataclass
|
|
16
17
|
|
|
17
|
-
from .
|
|
18
|
+
from .vision import CaptureError
|
|
19
|
+
from .window import WindowError, get_bounds, get_window_info
|
|
18
20
|
|
|
19
21
|
|
|
20
22
|
@dataclass(frozen=True)
|
|
@@ -75,3 +77,250 @@ def verify_action(action, *args, settle_s: float = 1.5, **kwargs) -> bool:
|
|
|
75
77
|
time.sleep(settle_s)
|
|
76
78
|
after = capture_hash()
|
|
77
79
|
return changed(before, after)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _capture_window_image(window_id: int):
|
|
83
|
+
"""CGWindowListCreateImage for one window id (injectable in tests).
|
|
84
|
+
|
|
85
|
+
Reads the window's own pixels — valid even when other windows cover
|
|
86
|
+
it. Module-level so tests can substitute a synthetic image instead
|
|
87
|
+
of touching the real screen.
|
|
88
|
+
"""
|
|
89
|
+
import Quartz
|
|
90
|
+
|
|
91
|
+
return Quartz.CGWindowListCreateImage(
|
|
92
|
+
Quartz.CGRectNull,
|
|
93
|
+
Quartz.kCGWindowListOptionIncludingWindow,
|
|
94
|
+
window_id,
|
|
95
|
+
(Quartz.kCGWindowImageBoundsIgnoreFraming
|
|
96
|
+
| Quartz.kCGWindowImageNominalResolution),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def window_luma(size: tuple[int, int] = (36, 78)) -> bytes:
|
|
101
|
+
"""Capture the mirroring window as a small grayscale luma map.
|
|
102
|
+
|
|
103
|
+
Reads the window's own pixels with CGWindowListCreateImage — valid
|
|
104
|
+
even when other windows cover it — and renders them into an 8-bit
|
|
105
|
+
gray bitmap whose backing store is a Python bytearray. No temp
|
|
106
|
+
files, no sips, no subprocess (unlike capture_hash). Returns
|
|
107
|
+
``w*h`` bytes, one gray level (0-255) per pixel. Raises WindowError
|
|
108
|
+
when the window cannot be found, is not on screen (hidden,
|
|
109
|
+
minimized or on another Space), its image cannot be captured, or
|
|
110
|
+
the frame is a near-single gray level: during window transitions
|
|
111
|
+
CGWindowListCreateImage can hand back a blank/transparent frame,
|
|
112
|
+
and a frame diff against it "confirms" changes that never happened
|
|
113
|
+
on the phone (F25).
|
|
114
|
+
"""
|
|
115
|
+
import Quartz
|
|
116
|
+
|
|
117
|
+
w, h = size
|
|
118
|
+
if w <= 0 or h <= 0:
|
|
119
|
+
raise ValueError(f"size must be positive, got {size!r}")
|
|
120
|
+
wi = get_window_info()
|
|
121
|
+
if not wi:
|
|
122
|
+
raise WindowError("iPhone Mirroring window not found")
|
|
123
|
+
if not wi.get("onscreen", False):
|
|
124
|
+
raise WindowError(
|
|
125
|
+
"the mirroring window is not on screen "
|
|
126
|
+
"(hidden, minimized or on another Space)"
|
|
127
|
+
)
|
|
128
|
+
import time
|
|
129
|
+
|
|
130
|
+
img = None
|
|
131
|
+
for attempt in range(3):
|
|
132
|
+
img = _capture_window_image(wi["id"])
|
|
133
|
+
if img is not None:
|
|
134
|
+
buf = bytearray(w * h) # bitmap backing store; never resized while ctx lives
|
|
135
|
+
ctx = Quartz.CGBitmapContextCreate(
|
|
136
|
+
buf, w, h, 8, w,
|
|
137
|
+
Quartz.CGColorSpaceCreateDeviceGray(),
|
|
138
|
+
Quartz.kCGImageAlphaNone,
|
|
139
|
+
)
|
|
140
|
+
if ctx is None:
|
|
141
|
+
raise WindowError("CGBitmapContextCreate failed")
|
|
142
|
+
Quartz.CGContextDrawImage(ctx, Quartz.CGRectMake(0, 0, w, h), img)
|
|
143
|
+
luma = bytes(buf)
|
|
144
|
+
if max(luma) - min(luma) >= 4:
|
|
145
|
+
return luma
|
|
146
|
+
# F31: a transition can hand back no image or a blank frame for a
|
|
147
|
+
# moment; look again shortly. Only a real frame is ever accepted (F25).
|
|
148
|
+
if attempt < 2:
|
|
149
|
+
time.sleep(0.12)
|
|
150
|
+
if img is None:
|
|
151
|
+
raise WindowError("could not capture the mirroring window image")
|
|
152
|
+
raise WindowError("the mirroring window frame is blank (a window transition)")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def is_capture_error(exc: BaseException) -> bool:
|
|
156
|
+
"""True when ``exc`` means the pixels a check needed are not the phone's.
|
|
157
|
+
|
|
158
|
+
F25: WindowError (window missing, offscreen, or a blank/transparent
|
|
159
|
+
frame) and CaptureError (screencapture by window id failed) both
|
|
160
|
+
mean a verification could not observe the screen — every check that
|
|
161
|
+
depends on a capture must count that as "unconfirmed", never as
|
|
162
|
+
success.
|
|
163
|
+
"""
|
|
164
|
+
return isinstance(exc, (WindowError, CaptureError))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def mean_abs_diff(a: bytes, b: bytes) -> float:
|
|
168
|
+
"""Mean absolute per-byte difference between two luma maps (0-255).
|
|
169
|
+
|
|
170
|
+
Pure function — no capture, no I/O. Raises ValueError when the
|
|
171
|
+
buffers are empty or of different lengths.
|
|
172
|
+
"""
|
|
173
|
+
if not a or len(a) != len(b):
|
|
174
|
+
raise ValueError("buffers must be non-empty and of equal length")
|
|
175
|
+
return sum(abs(x - y) for x, y in zip(a, b)) / len(a)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# 待真机标定:粘贴后整窗 luma 帧差下限(type_text 确认粘贴已上屏的快路径阈值)。
|
|
179
|
+
TYPE_MIN_DIFF = 0.5
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def screen_shows_text(text: str, read_screen) -> bool:
|
|
183
|
+
"""Report whether the OCR'd screen shows ``text`` (probe match).
|
|
184
|
+
|
|
185
|
+
The probe is the first min(12, len) characters of ``text`` after
|
|
186
|
+
NFKC normalization, lowercasing, and whitespace removal; the OCR
|
|
187
|
+
hits are normalized the same way and joined into one haystack.
|
|
188
|
+
OCR is too unreliable for single characters, so a probe shorter
|
|
189
|
+
than 2 characters always returns False.
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
def norm(s: str) -> str:
|
|
193
|
+
return "".join(
|
|
194
|
+
ch for ch in unicodedata.normalize("NFKC", s).lower() if not ch.isspace()
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
probe = norm(text)[:12]
|
|
198
|
+
if len(probe) < 2:
|
|
199
|
+
return False
|
|
200
|
+
haystack = norm("".join(getattr(hit, "text", hit) for hit in read_screen()))
|
|
201
|
+
return probe in haystack
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _compact(s: str) -> str:
|
|
205
|
+
"""NFKC, lowercase, whitespace removed."""
|
|
206
|
+
return "".join(
|
|
207
|
+
ch for ch in unicodedata.normalize("NFKC", s).lower() if not ch.isspace()
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def is_short_text(text: str, limit: int = 2) -> bool:
|
|
212
|
+
"""True when ``text`` normalizes to 1..``limit`` characters (F27).
|
|
213
|
+
|
|
214
|
+
Such texts are OCR-fragile: Vision's full-frame pass can skip an isolated
|
|
215
|
+
one- or two-character label entirely, so callers add a pass with
|
|
216
|
+
vision.ocr_sweep().
|
|
217
|
+
"""
|
|
218
|
+
return 0 < len(_compact(text)) <= limit
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _fold_label(s: str) -> str:
|
|
222
|
+
"""Exact-reading key for a short label (F27).
|
|
223
|
+
|
|
224
|
+
NFKC, lowercase, whitespace removed, trailing ".,:;" dropped, and "×"
|
|
225
|
+
folded to "x" — the readings Vision gives the one-letter app "X" — so
|
|
226
|
+
"X", "x", "×", "X." and full-width "X" share one key while "Xcode" or
|
|
227
|
+
"Box" never match it.
|
|
228
|
+
"""
|
|
229
|
+
return _compact(s).rstrip(".,:;").replace("×", "x")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def new_text_positions(text: str, before, after, eps: float = 0.03) -> list:
|
|
233
|
+
"""Centres of hits in ``after`` reading exactly ``text`` where ``before`` had none (F27).
|
|
234
|
+
|
|
235
|
+
Same matching as new_text_occurrences(); returns the (nx, ny) of each
|
|
236
|
+
such hit instead of their count.
|
|
237
|
+
"""
|
|
238
|
+
want = _fold_label(text)
|
|
239
|
+
if not want:
|
|
240
|
+
return []
|
|
241
|
+
olds = [h for h in before if _fold_label(h.text) == want]
|
|
242
|
+
return [
|
|
243
|
+
(h.nx, h.ny) for h in after
|
|
244
|
+
if _fold_label(h.text) == want
|
|
245
|
+
and not any(abs(h.nx - o.nx) <= eps and abs(h.ny - o.ny) <= eps for o in olds)
|
|
246
|
+
]
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class RepeatedSighting:
|
|
250
|
+
"""Evidence that a typed single character really arrived (F27/F33, review).
|
|
251
|
+
|
|
252
|
+
One read showing the character at a new position is not enough: a
|
|
253
|
+
label the baseline read missed, a banner, a list still moving or a
|
|
254
|
+
"×" glyph can all pose as it. add() takes one read at a time and
|
|
255
|
+
returns True once the SAME new position (within ``eps``) has shown up
|
|
256
|
+
in two separate reads.
|
|
257
|
+
"""
|
|
258
|
+
|
|
259
|
+
def __init__(self, text: str, before, eps: float = 0.03):
|
|
260
|
+
self._text, self._before, self._eps = text, before, eps
|
|
261
|
+
self._seen: list = []
|
|
262
|
+
|
|
263
|
+
def add(self, hits) -> bool:
|
|
264
|
+
new = new_text_positions(self._text, self._before, hits, self._eps)
|
|
265
|
+
eps = self._eps
|
|
266
|
+
repeated = any(abs(p[0] - q[0]) <= eps and abs(p[1] - q[1]) <= eps
|
|
267
|
+
for p in new for q in self._seen)
|
|
268
|
+
self._seen.extend(new)
|
|
269
|
+
return repeated
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def wait_still(luma=None, *, sleep=None, clock=None, timeout_s: float = 1.5,
|
|
273
|
+
poll_s: float = 0.15) -> bool:
|
|
274
|
+
"""Wait until two consecutive frames differ by less than TYPE_MIN_DIFF.
|
|
275
|
+
|
|
276
|
+
True once the screen is still; False when it kept moving for
|
|
277
|
+
``timeout_s`` (an animation, a video). Capture errors propagate.
|
|
278
|
+
"""
|
|
279
|
+
import time as _time
|
|
280
|
+
|
|
281
|
+
luma = luma or window_luma
|
|
282
|
+
sleep = sleep or _time.sleep
|
|
283
|
+
clock = clock or _time.monotonic
|
|
284
|
+
deadline = clock() + timeout_s
|
|
285
|
+
prev = luma()
|
|
286
|
+
while True:
|
|
287
|
+
sleep(poll_s)
|
|
288
|
+
cur = luma()
|
|
289
|
+
if mean_abs_diff(prev, cur) < TYPE_MIN_DIFF:
|
|
290
|
+
return True
|
|
291
|
+
if clock() >= deadline:
|
|
292
|
+
return False
|
|
293
|
+
prev = cur
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def new_text_occurrences(text: str, before, after, eps: float = 0.03) -> int:
|
|
297
|
+
"""Hits in ``after`` reading exactly ``text`` where ``before`` had none (F27).
|
|
298
|
+
|
|
299
|
+
A hit counts when no matching hit in ``before`` lay within ``eps`` (in
|
|
300
|
+
both axes) of it: evidence that a typed single character showed up even
|
|
301
|
+
when an identical label was already on screen. Comparing positions rather
|
|
302
|
+
than totals keeps a blinking text cursor — which makes the echo in a
|
|
303
|
+
search field come and go between reads — from hiding the new result.
|
|
304
|
+
"""
|
|
305
|
+
return len(new_text_positions(text, before, after, eps))
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def screen_contains(expect: str, hits) -> bool:
|
|
309
|
+
"""Report whether the OCR'd screen contains ``expect`` (guard match).
|
|
310
|
+
|
|
311
|
+
The hit texts are joined in reading order with single spaces; both
|
|
312
|
+
the joined text and ``expect`` are NFKC-normalized, lowercased, and
|
|
313
|
+
have whitespace runs collapsed to one space, so case, full-width
|
|
314
|
+
characters, and whitespace differences do not matter, and a phrase
|
|
315
|
+
split across two OCR fragments ("Replying" + "to") still matches.
|
|
316
|
+
An ``expect`` that normalizes to empty never matches.
|
|
317
|
+
"""
|
|
318
|
+
|
|
319
|
+
def norm(s: str) -> str:
|
|
320
|
+
return " ".join(unicodedata.normalize("NFKC", s).lower().split())
|
|
321
|
+
|
|
322
|
+
needle = norm(expect)
|
|
323
|
+
if not needle:
|
|
324
|
+
return False
|
|
325
|
+
haystack = norm(" ".join(getattr(hit, "text", hit) for hit in hits))
|
|
326
|
+
return needle in haystack
|
|
@@ -11,18 +11,30 @@ to the window size so results map directly onto tap(nx, ny).
|
|
|
11
11
|
|
|
12
12
|
from __future__ import annotations
|
|
13
13
|
|
|
14
|
+
import atexit
|
|
14
15
|
import os
|
|
16
|
+
import shutil
|
|
15
17
|
import subprocess
|
|
16
18
|
import tempfile
|
|
19
|
+
import time
|
|
17
20
|
from dataclasses import dataclass
|
|
18
21
|
|
|
19
|
-
from .window import
|
|
22
|
+
from .window import get_window_info
|
|
20
23
|
|
|
21
24
|
|
|
22
25
|
class OCRError(RuntimeError):
|
|
23
26
|
"""Raised when OCR fails."""
|
|
24
27
|
|
|
25
28
|
|
|
29
|
+
class CaptureError(Exception):
|
|
30
|
+
"""Raised when the mirroring window cannot be captured by window id (F25)."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# Injectable so tests can drive capture_window() without ever running a
|
|
34
|
+
# real screencapture: this is the only place one is executed.
|
|
35
|
+
_run = subprocess.run
|
|
36
|
+
|
|
37
|
+
|
|
26
38
|
@dataclass(frozen=True)
|
|
27
39
|
class OCRHit:
|
|
28
40
|
text: str
|
|
@@ -34,37 +46,98 @@ class OCRHit:
|
|
|
34
46
|
return f"({self.nx:.2f},{self.ny:.2f}) {self.text!r} [{self.confidence:.2f}]"
|
|
35
47
|
|
|
36
48
|
|
|
37
|
-
def
|
|
38
|
-
"""
|
|
49
|
+
def _capture_by_id(path: str) -> bool:
|
|
50
|
+
"""One ``screencapture -l`` attempt; True when a non-empty PNG landed.
|
|
39
51
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
52
|
+
The window id is resolved fresh on every call, so the retry in
|
|
53
|
+
capture_window() can pick up a window that was mid-transition
|
|
54
|
+
(Space switch, un-minimize) on the first look.
|
|
43
55
|
"""
|
|
44
|
-
if path is None:
|
|
45
|
-
path = tempfile.mktemp(prefix="imctl_", suffix=".png")
|
|
46
56
|
info = get_window_info()
|
|
47
|
-
if info is
|
|
48
|
-
|
|
57
|
+
if info is None:
|
|
58
|
+
return False
|
|
59
|
+
try:
|
|
60
|
+
# A normal capture takes 0.1-1.2 s; on a loaded Mac one hung for
|
|
61
|
+
# ~10 s, and with the retry that alone ate most of the server's
|
|
62
|
+
# 30 s budget (2026-11-04). A hung attempt now fails after 4 s.
|
|
63
|
+
r = _run(
|
|
49
64
|
["screencapture", "-x", "-o", "-l", str(info["id"]), path],
|
|
50
65
|
capture_output=True,
|
|
51
|
-
timeout=
|
|
66
|
+
timeout=4,
|
|
52
67
|
)
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
68
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
69
|
+
# A missing or hung screencapture is a failed attempt, not a
|
|
70
|
+
# crash: it takes the same retry-then-CaptureError path as a
|
|
71
|
+
# nonzero return code, so callers report the capture as failed
|
|
72
|
+
# instead of dying with a raw traceback (F25).
|
|
73
|
+
return False
|
|
74
|
+
return r.returncode == 0 and os.path.exists(path) and os.path.getsize(path) > 0
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
_FRAME_DIR: str | None = None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _frame_path() -> str:
|
|
81
|
+
"""A new PNG path in this process's private temp directory.
|
|
82
|
+
|
|
83
|
+
Mirror frames show whatever the phone shows (messages, notes, one-time
|
|
84
|
+
codes). They used to land in the shared temp directory as world-readable
|
|
85
|
+
files nothing deleted; now they go to an owner-only (0700) directory made
|
|
86
|
+
once per process with mkdtemp and removed at exit, and read_screen() and
|
|
87
|
+
find() delete each frame as soon as it has been read.
|
|
88
|
+
"""
|
|
89
|
+
global _FRAME_DIR
|
|
90
|
+
if _FRAME_DIR is None or not os.path.isdir(_FRAME_DIR):
|
|
91
|
+
_FRAME_DIR = tempfile.mkdtemp(prefix="imctl_")
|
|
92
|
+
atexit.register(shutil.rmtree, _FRAME_DIR, True)
|
|
93
|
+
fd, path = tempfile.mkstemp(prefix="frame_", suffix=".png", dir=_FRAME_DIR)
|
|
94
|
+
os.close(fd)
|
|
61
95
|
return path
|
|
62
96
|
|
|
63
97
|
|
|
64
|
-
def
|
|
98
|
+
def discard_frame(path: str) -> None:
|
|
99
|
+
"""Delete a frame file; one that is already gone is fine."""
|
|
100
|
+
try:
|
|
101
|
+
os.remove(path)
|
|
102
|
+
except OSError:
|
|
103
|
+
pass
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def capture_window(path: str | None = None) -> str:
|
|
107
|
+
"""Screenshot the mirroring window to a PNG file; returns the path.
|
|
108
|
+
|
|
109
|
+
Captures by CGWindow id (``screencapture -l``) so the image is the window's own content even when
|
|
110
|
+
other windows cover it or it is not frontmost. There is deliberately NO fallback to a screen-region
|
|
111
|
+
capture of the AX bounds: a region capture returns whatever windows happen to sit inside those
|
|
112
|
+
bounds — during a real session it once returned another app's sidebar, and every consumer (OCR,
|
|
113
|
+
expect guards, paste confirmation) would have trusted those pixels as the phone (F25). When the
|
|
114
|
+
window id cannot be resolved, or screencapture fails (nonzero exit, missing or hung binary) or
|
|
115
|
+
writes nothing, one retry follows after 0.2 s (the window may be mid-transition); a second
|
|
116
|
+
failure raises CaptureError so callers report the capture as failed instead of acting on
|
|
117
|
+
another window's pixels.
|
|
118
|
+
"""
|
|
119
|
+
owned = path is None
|
|
120
|
+
if owned:
|
|
121
|
+
path = _frame_path()
|
|
122
|
+
if _capture_by_id(path):
|
|
123
|
+
return path
|
|
124
|
+
time.sleep(0.2)
|
|
125
|
+
if _capture_by_id(path):
|
|
126
|
+
return path
|
|
127
|
+
if owned:
|
|
128
|
+
discard_frame(path)
|
|
129
|
+
raise CaptureError("could not capture the iPhone Mirroring window by id")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def ocr(image_path: str, languages: tuple[str, ...] = ("en-US", "zh-Hans"),
|
|
133
|
+
language_correction: bool = True) -> list[OCRHit]:
|
|
65
134
|
"""Run Vision OCR on an image; return hits sorted reading-order.
|
|
66
135
|
|
|
67
136
|
Uses the pyobjc Vision bindings (no subprocess Swift compile).
|
|
137
|
+
``language_correction`` feeds setUsesLanguageCorrection_: keep the
|
|
138
|
+
default for prose, but pass False to read single-character labels
|
|
139
|
+
(e.g. the app "X") — language correction often drops or rewrites
|
|
140
|
+
those into other characters.
|
|
68
141
|
"""
|
|
69
142
|
try:
|
|
70
143
|
import Vision
|
|
@@ -90,7 +163,7 @@ def ocr(image_path: str, languages: tuple[str, ...] = ("en-US", "zh-Hans")) -> l
|
|
|
90
163
|
request.setRecognitionLevel_(Vision.VNRequestTextRecognitionLevelAccurate)
|
|
91
164
|
if hasattr(request, "setRecognitionLanguages_"):
|
|
92
165
|
request.setRecognitionLanguages_(list(languages))
|
|
93
|
-
request.setUsesLanguageCorrection_(
|
|
166
|
+
request.setUsesLanguageCorrection_(language_correction)
|
|
94
167
|
|
|
95
168
|
handler = Vision.VNImageRequestHandler.alloc().initWithCGImage_options_(
|
|
96
169
|
cg_image, None
|
|
@@ -123,16 +196,128 @@ def ocr(image_path: str, languages: tuple[str, ...] = ("en-US", "zh-Hans")) -> l
|
|
|
123
196
|
return hits
|
|
124
197
|
|
|
125
198
|
|
|
199
|
+
def dedupe_hits(hits: list[OCRHit], eps: float = 0.02) -> list[OCRHit]:
|
|
200
|
+
"""Collapse hits with the same text whose centres lie within ``eps``.
|
|
201
|
+
|
|
202
|
+
The passes of ocr_sweep() read most labels several times; the most
|
|
203
|
+
confident reading is kept.
|
|
204
|
+
"""
|
|
205
|
+
kept: list[OCRHit] = []
|
|
206
|
+
for hit in sorted(hits, key=lambda h: -h.confidence):
|
|
207
|
+
if any(k.text == hit.text and abs(k.nx - hit.nx) <= eps
|
|
208
|
+
and abs(k.ny - hit.ny) <= eps for k in kept):
|
|
209
|
+
continue
|
|
210
|
+
kept.append(hit)
|
|
211
|
+
return kept
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# F27 (2026-11-04): at Vision's default working scale the full-frame pass never
|
|
215
|
+
# reports an isolated single glyph (the app "X": its icon label, the Spotlight
|
|
216
|
+
# query echo). minimumTextHeight sets that working scale, and at these values
|
|
217
|
+
# the same full frame does report it. On 172 recorded mirror frames this sweep
|
|
218
|
+
# found all but 2 of the 56 "X" positions that reading the frame in overlapping
|
|
219
|
+
# strips found, plus 45 the strips missed (the Spotlight Top Hit label among
|
|
220
|
+
# them), at ~0.1 s per height instead of ~4 s for one strip read — fast enough
|
|
221
|
+
# that phone_open "X" stays well inside the server's 30 s limit.
|
|
222
|
+
SWEEP_MIN_TEXT_HEIGHTS = (0.018, 0.02, 0.022, 0.025, 0.03)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def ocr_sweep(image_path: str, languages: tuple[str, ...] = ("en-US", "zh-Hans"),
|
|
226
|
+
language_correction: bool = False,
|
|
227
|
+
heights: tuple[float, ...] = SWEEP_MIN_TEXT_HEIGHTS) -> list[OCRHit]:
|
|
228
|
+
"""Full-frame OCR once per minimumTextHeight in ``heights``; merged hits (F27).
|
|
229
|
+
|
|
230
|
+
Finds isolated one- or two-character labels that ocr() at Vision's default
|
|
231
|
+
scale skips. Hits are de-duplicated across heights (same text, centres
|
|
232
|
+
within 0.02) and returned in reading order.
|
|
233
|
+
"""
|
|
234
|
+
try:
|
|
235
|
+
import Vision
|
|
236
|
+
from Foundation import NSURL
|
|
237
|
+
from Quartz import CGImageSourceCreateImageAtIndex, CGImageSourceCreateWithURL
|
|
238
|
+
except ImportError as exc: # pragma: no cover
|
|
239
|
+
raise OCRError(f"pyobjc frameworks missing: {exc}") from exc
|
|
240
|
+
|
|
241
|
+
src = CGImageSourceCreateWithURL(NSURL.fileURLWithPath_(image_path), None)
|
|
242
|
+
if src is None:
|
|
243
|
+
raise OCRError(f"cannot open image: {image_path}")
|
|
244
|
+
cg_image = CGImageSourceCreateImageAtIndex(src, 0, None)
|
|
245
|
+
if cg_image is None:
|
|
246
|
+
raise OCRError(f"cannot decode image: {image_path}")
|
|
247
|
+
|
|
248
|
+
hits: list[OCRHit] = []
|
|
249
|
+
for min_height in heights:
|
|
250
|
+
request = Vision.VNRecognizeTextRequest.alloc().init()
|
|
251
|
+
request.setRecognitionLevel_(Vision.VNRequestTextRecognitionLevelAccurate)
|
|
252
|
+
if hasattr(request, "setRecognitionLanguages_"):
|
|
253
|
+
request.setRecognitionLanguages_(list(languages))
|
|
254
|
+
request.setUsesLanguageCorrection_(language_correction)
|
|
255
|
+
request.setMinimumTextHeight_(min_height)
|
|
256
|
+
handler = Vision.VNImageRequestHandler.alloc().initWithCGImage_options_(
|
|
257
|
+
cg_image, None)
|
|
258
|
+
if not handler.performRequests_error_([request], None):
|
|
259
|
+
raise OCRError("VNImageRequestHandler.performRequests failed")
|
|
260
|
+
for obs in request.results() or []:
|
|
261
|
+
cand = obs.topCandidates_(1)
|
|
262
|
+
if not cand:
|
|
263
|
+
continue
|
|
264
|
+
cand = cand[0]
|
|
265
|
+
box = obs.boundingBox() # bottom-left origin, normalized
|
|
266
|
+
hits.append(OCRHit(
|
|
267
|
+
text=str(cand.string()),
|
|
268
|
+
nx=box.origin.x + box.size.width / 2,
|
|
269
|
+
ny=1.0 - (box.origin.y + box.size.height / 2),
|
|
270
|
+
confidence=float(cand.confidence()),
|
|
271
|
+
))
|
|
272
|
+
hits = dedupe_hits(hits)
|
|
273
|
+
hits.sort(key=lambda h: (round(h.ny / 0.03), h.nx))
|
|
274
|
+
return hits
|
|
275
|
+
|
|
276
|
+
|
|
126
277
|
def find(text: str, image_path: str | None = None,
|
|
127
278
|
exact: bool = False) -> OCRHit | None:
|
|
128
|
-
"""Find the first OCR hit matching text; returns None if absent.
|
|
279
|
+
"""Find the first OCR hit matching text; returns None if absent.
|
|
280
|
+
|
|
281
|
+
A one- or two-character ``text`` the default pass misses is looked for
|
|
282
|
+
again with ocr_sweep() (F27). A frame this captured itself is deleted
|
|
283
|
+
after reading; a caller's ``image_path`` is left alone.
|
|
284
|
+
"""
|
|
285
|
+
def first(hits):
|
|
286
|
+
for hit in hits:
|
|
287
|
+
if (hit.text == text) if exact else (text in hit.text):
|
|
288
|
+
return hit
|
|
289
|
+
return None
|
|
290
|
+
|
|
291
|
+
owned = image_path is None
|
|
129
292
|
path = image_path or capture_window()
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
293
|
+
try:
|
|
294
|
+
hit = first(ocr(path))
|
|
295
|
+
if hit is None and 0 < len("".join(text.split())) <= 2:
|
|
296
|
+
hit = first(ocr_sweep(path))
|
|
297
|
+
return hit
|
|
298
|
+
finally:
|
|
299
|
+
if owned:
|
|
300
|
+
discard_frame(path)
|
|
134
301
|
|
|
135
302
|
|
|
136
|
-
def read_screen(
|
|
137
|
-
|
|
138
|
-
|
|
303
|
+
def read_screen(language_correction: bool = True, sweep: bool = False,
|
|
304
|
+
also_sweep: bool = False) -> list[OCRHit]:
|
|
305
|
+
"""Convenience: capture + OCR the current mirroring window.
|
|
306
|
+
|
|
307
|
+
``language_correction`` is passed through to ocr(); see there.
|
|
308
|
+
``sweep=True`` reads with ocr_sweep() instead (F27). ``also_sweep=True``
|
|
309
|
+
reads the same frame with both and merges the hits, so a short label
|
|
310
|
+
the default pass skips is still there (F32). The frame is deleted once
|
|
311
|
+
it has been read.
|
|
312
|
+
"""
|
|
313
|
+
path = capture_window()
|
|
314
|
+
try:
|
|
315
|
+
if sweep:
|
|
316
|
+
return ocr_sweep(path, language_correction=language_correction)
|
|
317
|
+
hits = ocr(path, language_correction=language_correction)
|
|
318
|
+
if also_sweep:
|
|
319
|
+
hits = dedupe_hits(hits + ocr_sweep(path))
|
|
320
|
+
hits.sort(key=lambda h: (round(h.ny / 0.03), h.nx))
|
|
321
|
+
return hits
|
|
322
|
+
finally:
|
|
323
|
+
discard_frame(path)
|