noracu 0.1.2 → 0.1.4

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.
@@ -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 .window import get_bounds
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,289 @@ 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 text_probe(text: str) -> str | None:
183
+ """The OCR probe for ``text`` (screen_shows_text's rule: the first ≤12
184
+ characters after NFKC, lowercasing and whitespace removal), or None when
185
+ it is shorter than 2 characters — too short for OCR to confirm."""
186
+ probe = _compact(text)[:12]
187
+ return probe if len(probe) >= 2 else None
188
+
189
+
190
+ def probe_count(text: str, hits) -> int | None:
191
+ """How many times ``text``'s probe occurs in the joined OCR ``hits``;
192
+ None when the text is too short for a probe. The phone's "Pasting from …"
193
+ box is left out (F44): its words are never the typed text, even when the
194
+ probe is a piece of them ("from", "pro" in a Mac named "M5pro")."""
195
+ probe = text_probe(text)
196
+ if probe is None:
197
+ return None
198
+ return _compact("".join(getattr(hit, "text", hit) for hit in hits
199
+ if not _is_paste_hud(hit))).count(probe)
200
+
201
+
202
+ # F44 (2026-11-05 real device, load ~25): when the phone is slow to fetch a paste
203
+ # it shows a "Pasting from <Mac name>…" progress box mid-screen. That box alone
204
+ # moves the whole-window frame diff past TYPE_MIN_DIFF while the text has not
205
+ # arrived, and type_text() reported such pastes as typed. English UI only: an
206
+ # iPhone in another language shows the box in that language, unrecognized here.
207
+ PASTE_HUD_PROBE = "pastingfrom"
208
+
209
+
210
+ def _is_paste_hud(hit) -> bool:
211
+ return PASTE_HUD_PROBE in _compact(getattr(hit, "text", hit))
212
+
213
+
214
+ def shows_paste_hud(hits) -> bool:
215
+ """True when one OCR hit reads like the phone's "Pasting from …" progress
216
+ box (compared like probes: NFKC, lowercase, whitespace removed). While it
217
+ shows, a paste is still on its way to the phone."""
218
+ return any(_is_paste_hud(hit) for hit in hits)
219
+
220
+
221
+ def screen_shows_text(text: str, read_screen) -> bool:
222
+ """Report whether the OCR'd screen shows ``text`` (probe match).
223
+
224
+ The probe is the first min(12, len) characters of ``text`` after
225
+ NFKC normalization, lowercasing, and whitespace removal; the OCR
226
+ hits are normalized the same way and joined into one haystack.
227
+ OCR is too unreliable for single characters, so a probe shorter
228
+ than 2 characters always returns False.
229
+ """
230
+
231
+ def norm(s: str) -> str:
232
+ return "".join(
233
+ ch for ch in unicodedata.normalize("NFKC", s).lower() if not ch.isspace()
234
+ )
235
+
236
+ probe = norm(text)[:12]
237
+ if len(probe) < 2:
238
+ return False
239
+ haystack = norm("".join(getattr(hit, "text", hit) for hit in read_screen()))
240
+ return probe in haystack
241
+
242
+
243
+ def _compact(s: str) -> str:
244
+ """NFKC, lowercase, whitespace removed."""
245
+ return "".join(
246
+ ch for ch in unicodedata.normalize("NFKC", s).lower() if not ch.isspace()
247
+ )
248
+
249
+
250
+ def is_short_text(text: str, limit: int = 2) -> bool:
251
+ """True when ``text`` normalizes to 1..``limit`` characters (F27).
252
+
253
+ Such texts are OCR-fragile: Vision's full-frame pass can skip an isolated
254
+ one- or two-character label entirely, so callers add a pass with
255
+ vision.ocr_sweep().
256
+ """
257
+ return 0 < len(_compact(text)) <= limit
258
+
259
+
260
+ def _fold_label(s: str) -> str:
261
+ """Exact-reading key for a short label (F27).
262
+
263
+ NFKC, lowercase, whitespace removed, trailing ".,:;" dropped, and "×"
264
+ folded to "x" — the readings Vision gives the one-letter app "X" — so
265
+ "X", "x", "×", "X." and full-width "X" share one key while "Xcode" or
266
+ "Box" never match it.
267
+ """
268
+ return _compact(s).rstrip(".,:;").replace("×", "x")
269
+
270
+
271
+ def new_text_positions(text: str, before, after, eps: float = 0.03) -> list:
272
+ """Centres of hits in ``after`` reading exactly ``text`` where ``before`` had none (F27).
273
+
274
+ Same matching as new_text_occurrences(); returns the (nx, ny) of each
275
+ such hit instead of their count.
276
+ """
277
+ want = _fold_label(text)
278
+ if not want:
279
+ return []
280
+ olds = [h for h in before if _fold_label(h.text) == want]
281
+ return [
282
+ (h.nx, h.ny) for h in after
283
+ if _fold_label(h.text) == want
284
+ and not any(abs(h.nx - o.nx) <= eps and abs(h.ny - o.ny) <= eps for o in olds)
285
+ ]
286
+
287
+
288
+ class RepeatedSighting:
289
+ """Evidence that a typed single character really arrived (F27/F33, review).
290
+
291
+ One read showing the character at a new position is not enough: a
292
+ label the baseline read missed, a banner, a list still moving or a
293
+ "×" glyph can all pose as it. add() takes one read at a time and
294
+ returns True once the SAME new position (within ``eps``) has shown up
295
+ in two separate reads.
296
+ """
297
+
298
+ def __init__(self, text: str, before, eps: float = 0.03):
299
+ self._text, self._before, self._eps = text, before, eps
300
+ self._seen: list = []
301
+
302
+ def add(self, hits) -> bool:
303
+ new = new_text_positions(self._text, self._before, hits, self._eps)
304
+ eps = self._eps
305
+ repeated = any(abs(p[0] - q[0]) <= eps and abs(p[1] - q[1]) <= eps
306
+ for p in new for q in self._seen)
307
+ self._seen.extend(new)
308
+ return repeated
309
+
310
+
311
+ def wait_still(luma=None, *, sleep=None, clock=None, timeout_s: float = 1.5,
312
+ poll_s: float = 0.15) -> bool:
313
+ """Wait until two consecutive frames differ by less than TYPE_MIN_DIFF.
314
+
315
+ True once the screen is still; False when it kept moving for
316
+ ``timeout_s`` (an animation, a video). Capture errors propagate.
317
+ """
318
+ import time as _time
319
+
320
+ luma = luma or window_luma
321
+ sleep = sleep or _time.sleep
322
+ clock = clock or _time.monotonic
323
+ deadline = clock() + timeout_s
324
+ prev = luma()
325
+ while True:
326
+ sleep(poll_s)
327
+ cur = luma()
328
+ if mean_abs_diff(prev, cur) < TYPE_MIN_DIFF:
329
+ return True
330
+ if clock() >= deadline:
331
+ return False
332
+ prev = cur
333
+
334
+
335
+ def new_text_occurrences(text: str, before, after, eps: float = 0.03) -> int:
336
+ """Hits in ``after`` reading exactly ``text`` where ``before`` had none (F27).
337
+
338
+ A hit counts when no matching hit in ``before`` lay within ``eps`` (in
339
+ both axes) of it: evidence that a typed single character showed up even
340
+ when an identical label was already on screen. Comparing positions rather
341
+ than totals keeps a blinking text cursor — which makes the echo in a
342
+ search field come and go between reads — from hiding the new result.
343
+ """
344
+ return len(new_text_positions(text, before, after, eps))
345
+
346
+
347
+ def screen_contains(expect: str, hits) -> bool:
348
+ """Report whether the OCR'd screen contains ``expect`` (guard match).
349
+
350
+ The hit texts are joined in reading order with single spaces; both
351
+ the joined text and ``expect`` are NFKC-normalized, lowercased, and
352
+ have whitespace runs collapsed to one space, so case, full-width
353
+ characters, and whitespace differences do not matter, and a phrase
354
+ split across two OCR fragments ("Replying" + "to") still matches.
355
+ An ``expect`` that normalizes to empty never matches.
356
+ """
357
+
358
+ def norm(s: str) -> str:
359
+ return " ".join(unicodedata.normalize("NFKC", s).lower().split())
360
+
361
+ needle = norm(expect)
362
+ if not needle:
363
+ return False
364
+ haystack = norm(" ".join(getattr(hit, "text", hit) for hit in hits))
365
+ return needle in haystack
@@ -11,18 +11,32 @@ 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 re
17
+ import shutil
15
18
  import subprocess
19
+ import sys
16
20
  import tempfile
21
+ import time
17
22
  from dataclasses import dataclass
18
23
 
19
- from .window import get_bounds, get_window_info
24
+ from .window import get_window_info
20
25
 
21
26
 
22
27
  class OCRError(RuntimeError):
23
28
  """Raised when OCR fails."""
24
29
 
25
30
 
31
+ class CaptureError(Exception):
32
+ """Raised when the mirroring window cannot be captured by window id (F25)."""
33
+
34
+
35
+ # Injectable so tests can drive capture_window() without ever running a
36
+ # real screencapture: this is the only place one is executed.
37
+ _run = subprocess.run
38
+
39
+
26
40
  @dataclass(frozen=True)
27
41
  class OCRHit:
28
42
  text: str
@@ -34,37 +48,147 @@ class OCRHit:
34
48
  return f"({self.nx:.2f},{self.ny:.2f}) {self.text!r} [{self.confidence:.2f}]"
35
49
 
36
50
 
37
- def capture_window(path: str | None = None) -> str:
38
- """Screenshot the mirroring window to a PNG file; returns the path.
51
+ def _capture_by_id(path: str) -> bool:
52
+ """One ``screencapture -l`` attempt; True when a non-empty PNG landed.
39
53
 
40
- Captures by CGWindow id (``screencapture -l``) so the image is the window's own content even when
41
- other windows cover it or it is not frontmost. Falls back to a screen-region capture of the AX bounds
42
- when the window id cannot be resolved.
54
+ The window id is resolved fresh on every call, so the retry in
55
+ capture_window() can pick up a window that was mid-transition
56
+ (Space switch, un-minimize) on the first look.
43
57
  """
44
- if path is None:
45
- path = tempfile.mktemp(prefix="imctl_", suffix=".png")
46
58
  info = get_window_info()
47
- if info is not None:
48
- r = subprocess.run(
59
+ if info is None:
60
+ return False
61
+ try:
62
+ # A normal capture takes 0.1-1.2 s; on a loaded Mac one hung for
63
+ # ~10 s, and with the retry that alone ate most of the server's
64
+ # 30 s budget (2026-11-04). A hung attempt now fails after 4 s.
65
+ r = _run(
49
66
  ["screencapture", "-x", "-o", "-l", str(info["id"]), path],
50
67
  capture_output=True,
51
- timeout=10,
68
+ timeout=4,
52
69
  )
53
- if r.returncode == 0 and os.path.exists(path) and os.path.getsize(path) > 0:
54
- return path
55
- b = get_bounds()
56
- subprocess.run(
57
- ["screencapture", "-x", f"-R{b.x},{b.y},{b.width},{b.height}", path],
58
- check=True,
59
- timeout=10,
60
- )
70
+ except (OSError, subprocess.TimeoutExpired):
71
+ # A missing or hung screencapture is a failed attempt, not a
72
+ # crash: it takes the same retry-then-CaptureError path as a
73
+ # nonzero return code, so callers report the capture as failed
74
+ # instead of dying with a raw traceback (F25).
75
+ return False
76
+ return r.returncode == 0 and os.path.exists(path) and os.path.getsize(path) > 0
77
+
78
+
79
+ _FRAME_DIR: str | None = None
80
+
81
+
82
+ def _frame_path() -> str:
83
+ """A new PNG path in this process's private temp directory.
84
+
85
+ Mirror frames show whatever the phone shows (messages, notes, one-time
86
+ codes). They used to land in the shared temp directory as world-readable
87
+ files nothing deleted; now they go to an owner-only (0700) directory made
88
+ once per process with mkdtemp and removed at exit, and read_screen() and
89
+ find() delete each frame as soon as it has been read.
90
+ """
91
+ global _FRAME_DIR
92
+ if _FRAME_DIR is None or not os.path.isdir(_FRAME_DIR):
93
+ _FRAME_DIR = tempfile.mkdtemp(prefix="imctl_")
94
+ atexit.register(shutil.rmtree, _FRAME_DIR, True)
95
+ fd, path = tempfile.mkstemp(prefix="frame_", suffix=".png", dir=_FRAME_DIR)
96
+ os.close(fd)
61
97
  return path
62
98
 
63
99
 
64
- def ocr(image_path: str, languages: tuple[str, ...] = ("en-US", "zh-Hans")) -> list[OCRHit]:
100
+ def discard_frame(path: str) -> None:
101
+ """Delete a frame file; one that is already gone is fine."""
102
+ try:
103
+ os.remove(path)
104
+ except OSError:
105
+ pass
106
+
107
+
108
+ def capture_window(path: str | None = None) -> str:
109
+ """Screenshot the mirroring window to a PNG file; returns the path.
110
+
111
+ Captures by CGWindow id (``screencapture -l``) so the image is the window's own content even when
112
+ other windows cover it or it is not frontmost. There is deliberately NO fallback to a screen-region
113
+ capture of the AX bounds: a region capture returns whatever windows happen to sit inside those
114
+ bounds — during a real session it once returned another app's sidebar, and every consumer (OCR,
115
+ expect guards, paste confirmation) would have trusted those pixels as the phone (F25). When the
116
+ window id cannot be resolved, or screencapture fails (nonzero exit, missing or hung binary) or
117
+ writes nothing, one retry follows after 0.2 s (the window may be mid-transition); a second
118
+ failure raises CaptureError so callers report the capture as failed instead of acting on
119
+ another window's pixels.
120
+ """
121
+ owned = path is None
122
+ if owned:
123
+ path = _frame_path()
124
+ if _capture_by_id(path):
125
+ return path
126
+ time.sleep(0.2)
127
+ if _capture_by_id(path):
128
+ return path
129
+ if owned:
130
+ discard_frame(path)
131
+ raise CaptureError("could not capture the iPhone Mirroring window by id")
132
+
133
+
134
+ # F36 (2026-11-05, macOS 27.2): Vision weights the languages in the order given. With
135
+ # English first it returned no Chinese at all on a Spotlight frame (0 CJK hits; the
136
+ # Top Hit label 拼多多 was missing, so phone_open could not find the app and every
137
+ # Chinese `expect` failed). Chinese first read the same frame's Chinese AND its English
138
+ # labels (it even read "Suggestions" correctly where English-first read
139
+ # "Sugestions"), slightly faster. One shared default for ocr() and ocr_sweep().
140
+ # NORACU_OCR_LANGUAGES (comma-separated, e.g. "zh-Hant,en-US" or "en-US") overrides it.
141
+ DEFAULT_OCR_LANGUAGES: tuple[str, ...] = ("zh-Hans", "en-US")
142
+
143
+
144
+ def _ocr_languages(raw: str | None) -> tuple[str, ...]:
145
+ # ASCII and full-width commas, and the ideographic enumeration comma
146
+ langs = tuple(x.strip() for x in re.split(r"[,,、]", raw or "") if x.strip())
147
+ return langs or DEFAULT_OCR_LANGUAGES
148
+
149
+
150
+ OCR_LANGUAGES: tuple[str, ...] = _ocr_languages(os.environ.get("NORACU_OCR_LANGUAGES"))
151
+
152
+
153
+ _SUPPORTED_LANGUAGES: set | None = None # read once per process
154
+ _WARNED_LANGUAGES: set = set()
155
+
156
+
157
+ def _supported_languages(request, languages):
158
+ """``languages`` minus any Vision does not support (a typo in
159
+ NORACU_OCR_LANGUAGES must not break every OCR call); none left → the
160
+ defaults. Exact codes from Vision's list only (e.g. "en-US", not "en");
161
+ a dropped code is reported once on stderr. When the supported list cannot
162
+ be read, ``languages`` as given."""
163
+ global _SUPPORTED_LANGUAGES
164
+ if _SUPPORTED_LANGUAGES is None:
165
+ try:
166
+ res = request.supportedRecognitionLanguagesAndReturnError_(None)
167
+ found = res[0] if isinstance(res, tuple) else res
168
+ _SUPPORTED_LANGUAGES = {str(x) for x in (found or [])}
169
+ except Exception:
170
+ _SUPPORTED_LANGUAGES = set()
171
+ supported = _SUPPORTED_LANGUAGES
172
+ if not supported:
173
+ return tuple(languages)
174
+ kept = tuple(x for x in languages if x in supported)
175
+ for x in languages:
176
+ if x not in supported and x not in _WARNED_LANGUAGES:
177
+ _WARNED_LANGUAGES.add(x)
178
+ print(f"imctl: OCR language {x!r} is not supported by Vision here; skipped",
179
+ file=sys.stderr)
180
+ return kept or tuple(x for x in DEFAULT_OCR_LANGUAGES if x in supported) or tuple(languages)
181
+
182
+
183
+ def ocr(image_path: str, languages: tuple[str, ...] = OCR_LANGUAGES,
184
+ language_correction: bool = True) -> list[OCRHit]:
65
185
  """Run Vision OCR on an image; return hits sorted reading-order.
66
186
 
67
187
  Uses the pyobjc Vision bindings (no subprocess Swift compile).
188
+ ``language_correction`` feeds setUsesLanguageCorrection_: keep the
189
+ default for prose, but pass False to read single-character labels
190
+ (e.g. the app "X") — language correction often drops or rewrites
191
+ those into other characters.
68
192
  """
69
193
  try:
70
194
  import Vision
@@ -89,8 +213,8 @@ def ocr(image_path: str, languages: tuple[str, ...] = ("en-US", "zh-Hans")) -> l
89
213
  request = Vision.VNRecognizeTextRequest.alloc().init()
90
214
  request.setRecognitionLevel_(Vision.VNRequestTextRecognitionLevelAccurate)
91
215
  if hasattr(request, "setRecognitionLanguages_"):
92
- request.setRecognitionLanguages_(list(languages))
93
- request.setUsesLanguageCorrection_(True)
216
+ request.setRecognitionLanguages_(list(_supported_languages(request, languages)))
217
+ request.setUsesLanguageCorrection_(language_correction)
94
218
 
95
219
  handler = Vision.VNImageRequestHandler.alloc().initWithCGImage_options_(
96
220
  cg_image, None
@@ -123,16 +247,128 @@ def ocr(image_path: str, languages: tuple[str, ...] = ("en-US", "zh-Hans")) -> l
123
247
  return hits
124
248
 
125
249
 
250
+ def dedupe_hits(hits: list[OCRHit], eps: float = 0.02) -> list[OCRHit]:
251
+ """Collapse hits with the same text whose centres lie within ``eps``.
252
+
253
+ The passes of ocr_sweep() read most labels several times; the most
254
+ confident reading is kept.
255
+ """
256
+ kept: list[OCRHit] = []
257
+ for hit in sorted(hits, key=lambda h: -h.confidence):
258
+ if any(k.text == hit.text and abs(k.nx - hit.nx) <= eps
259
+ and abs(k.ny - hit.ny) <= eps for k in kept):
260
+ continue
261
+ kept.append(hit)
262
+ return kept
263
+
264
+
265
+ # F27 (2026-11-04): at Vision's default working scale the full-frame pass never
266
+ # reports an isolated single glyph (the app "X": its icon label, the Spotlight
267
+ # query echo). minimumTextHeight sets that working scale, and at these values
268
+ # the same full frame does report it. On 172 recorded mirror frames this sweep
269
+ # found all but 2 of the 56 "X" positions that reading the frame in overlapping
270
+ # strips found, plus 45 the strips missed (the Spotlight Top Hit label among
271
+ # them), at ~0.1 s per height instead of ~4 s for one strip read — fast enough
272
+ # that phone_open "X" stays well inside the server's 30 s limit.
273
+ SWEEP_MIN_TEXT_HEIGHTS = (0.018, 0.02, 0.022, 0.025, 0.03)
274
+
275
+
276
+ def ocr_sweep(image_path: str, languages: tuple[str, ...] = OCR_LANGUAGES,
277
+ language_correction: bool = False,
278
+ heights: tuple[float, ...] = SWEEP_MIN_TEXT_HEIGHTS) -> list[OCRHit]:
279
+ """Full-frame OCR once per minimumTextHeight in ``heights``; merged hits (F27).
280
+
281
+ Finds isolated one- or two-character labels that ocr() at Vision's default
282
+ scale skips. Hits are de-duplicated across heights (same text, centres
283
+ within 0.02) and returned in reading order.
284
+ """
285
+ try:
286
+ import Vision
287
+ from Foundation import NSURL
288
+ from Quartz import CGImageSourceCreateImageAtIndex, CGImageSourceCreateWithURL
289
+ except ImportError as exc: # pragma: no cover
290
+ raise OCRError(f"pyobjc frameworks missing: {exc}") from exc
291
+
292
+ src = CGImageSourceCreateWithURL(NSURL.fileURLWithPath_(image_path), None)
293
+ if src is None:
294
+ raise OCRError(f"cannot open image: {image_path}")
295
+ cg_image = CGImageSourceCreateImageAtIndex(src, 0, None)
296
+ if cg_image is None:
297
+ raise OCRError(f"cannot decode image: {image_path}")
298
+
299
+ hits: list[OCRHit] = []
300
+ for min_height in heights:
301
+ request = Vision.VNRecognizeTextRequest.alloc().init()
302
+ request.setRecognitionLevel_(Vision.VNRequestTextRecognitionLevelAccurate)
303
+ if hasattr(request, "setRecognitionLanguages_"):
304
+ request.setRecognitionLanguages_(list(_supported_languages(request, languages)))
305
+ request.setUsesLanguageCorrection_(language_correction)
306
+ request.setMinimumTextHeight_(min_height)
307
+ handler = Vision.VNImageRequestHandler.alloc().initWithCGImage_options_(
308
+ cg_image, None)
309
+ if not handler.performRequests_error_([request], None):
310
+ raise OCRError("VNImageRequestHandler.performRequests failed")
311
+ for obs in request.results() or []:
312
+ cand = obs.topCandidates_(1)
313
+ if not cand:
314
+ continue
315
+ cand = cand[0]
316
+ box = obs.boundingBox() # bottom-left origin, normalized
317
+ hits.append(OCRHit(
318
+ text=str(cand.string()),
319
+ nx=box.origin.x + box.size.width / 2,
320
+ ny=1.0 - (box.origin.y + box.size.height / 2),
321
+ confidence=float(cand.confidence()),
322
+ ))
323
+ hits = dedupe_hits(hits)
324
+ hits.sort(key=lambda h: (round(h.ny / 0.03), h.nx))
325
+ return hits
326
+
327
+
126
328
  def find(text: str, image_path: str | None = None,
127
329
  exact: bool = False) -> OCRHit | None:
128
- """Find the first OCR hit matching text; returns None if absent."""
330
+ """Find the first OCR hit matching text; returns None if absent.
331
+
332
+ A one- or two-character ``text`` the default pass misses is looked for
333
+ again with ocr_sweep() (F27). A frame this captured itself is deleted
334
+ after reading; a caller's ``image_path`` is left alone.
335
+ """
336
+ def first(hits):
337
+ for hit in hits:
338
+ if (hit.text == text) if exact else (text in hit.text):
339
+ return hit
340
+ return None
341
+
342
+ owned = image_path is None
129
343
  path = image_path or capture_window()
130
- for hit in ocr(path):
131
- if (hit.text == text) if exact else (text in hit.text):
132
- return hit
133
- return None
344
+ try:
345
+ hit = first(ocr(path))
346
+ if hit is None and 0 < len("".join(text.split())) <= 2:
347
+ hit = first(ocr_sweep(path))
348
+ return hit
349
+ finally:
350
+ if owned:
351
+ discard_frame(path)
352
+
134
353
 
354
+ def read_screen(language_correction: bool = True, sweep: bool = False,
355
+ also_sweep: bool = False) -> list[OCRHit]:
356
+ """Convenience: capture + OCR the current mirroring window.
135
357
 
136
- def read_screen() -> list[OCRHit]:
137
- """Convenience: capture + OCR the current mirroring window."""
138
- return ocr(capture_window())
358
+ ``language_correction`` is passed through to ocr(); see there.
359
+ ``sweep=True`` reads with ocr_sweep() instead (F27). ``also_sweep=True``
360
+ reads the same frame with both and merges the hits, so a short label
361
+ the default pass skips is still there (F32). The frame is deleted once
362
+ it has been read.
363
+ """
364
+ path = capture_window()
365
+ try:
366
+ if sweep:
367
+ return ocr_sweep(path, language_correction=language_correction)
368
+ hits = ocr(path, language_correction=language_correction)
369
+ if also_sweep:
370
+ hits = dedupe_hits(hits + ocr_sweep(path))
371
+ hits.sort(key=lambda h: (round(h.ny / 0.03), h.nx))
372
+ return hits
373
+ finally:
374
+ discard_frame(path)