aram-mayhem-dsh 0.3.2 → 0.4.0
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/README.md +21 -9
- package/config/settings.json +70 -57
- package/docs/DETAIL.md +19 -3
- package/docs/DETAIL.zh.md +19 -3
- package/index.js +3 -1
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -2
- package/requirements-dsh.txt +3 -0
- package/scripts/desktop_overlay.py +128 -14
- package/scripts/dsh_service.py +8 -4
- package/src/app.py +7 -0
- package/src/core/settings.py +34 -18
- package/src/data/matcher.py +89 -0
- package/src/data/models.py +1 -0
- package/src/main.py +1 -0
- package/src/ui/augment_panel.py +2 -2
- package/src/vision/capture.py +28 -0
- package/src/vision/debug_export.py +66 -0
- package/src/vision/ocr_engine.py +194 -1
- package/src/vision/scanner.py +135 -19
- package/src/vision/title_strip.py +127 -0
package/src/core/settings.py
CHANGED
|
@@ -28,15 +28,9 @@ class WindowSettings:
|
|
|
28
28
|
always_on_top: bool = True
|
|
29
29
|
mini: bool = False
|
|
30
30
|
click_through: bool = False
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
class HotkeySettings:
|
|
35
|
-
enabled: bool = True
|
|
36
|
-
toggle_visible: str = "Ctrl+Shift+H"
|
|
37
|
-
toggle_mini: str = "Ctrl+Shift+M"
|
|
38
|
-
rescan_augments: str = "Ctrl+Shift+R"
|
|
39
|
-
toggle_click_through: str = "Ctrl+Shift+L"
|
|
31
|
+
edge_hide: bool = True
|
|
32
|
+
edge_hide_ratio: float = 0.55
|
|
33
|
+
edge_hover_delay_ms: int = 400
|
|
40
34
|
|
|
41
35
|
|
|
42
36
|
@dataclass
|
|
@@ -48,11 +42,25 @@ class LCUSettings:
|
|
|
48
42
|
request_timeout: float = 3.0
|
|
49
43
|
|
|
50
44
|
|
|
45
|
+
@dataclass
|
|
46
|
+
class HotkeySettings:
|
|
47
|
+
enabled: bool = True
|
|
48
|
+
toggle_visible: str = "Ctrl+Shift+H"
|
|
49
|
+
toggle_mini: str = "Ctrl+Shift+M"
|
|
50
|
+
rescan_augments: str = "Ctrl+Shift+R"
|
|
51
|
+
toggle_click_through: str = "Ctrl+Shift+L"
|
|
52
|
+
debug_vision: str = "F9"
|
|
53
|
+
|
|
54
|
+
|
|
51
55
|
@dataclass
|
|
52
56
|
class VisionSettings:
|
|
53
57
|
enabled: bool = True
|
|
54
|
-
interval: float =
|
|
58
|
+
interval: float = 0.25
|
|
55
59
|
region: list[float] = field(default_factory=lambda: [0.06, 0.12, 0.88, 0.76])
|
|
60
|
+
augment_title_strip: list[float] = field(default_factory=lambda: [0.08, 0.38, 0.84, 0.055])
|
|
61
|
+
card_merge_gap_ratio: float = 0.025
|
|
62
|
+
ocr_closed_threshold: float = 0.65
|
|
63
|
+
debug_vision: bool = False
|
|
56
64
|
ocr_min_confidence: float = 0.45
|
|
57
65
|
match_threshold: float = 0.72
|
|
58
66
|
min_matches: int = 2
|
|
@@ -134,6 +142,8 @@ class Settings:
|
|
|
134
142
|
w.height = max(320, min(1400, int(w.height)))
|
|
135
143
|
w.min_width = max(300, min(w.width, int(w.min_width)))
|
|
136
144
|
w.opacity = max(0.35, min(1.0, float(w.opacity)))
|
|
145
|
+
w.edge_hide_ratio = max(0.25, min(0.8, float(w.edge_hide_ratio)))
|
|
146
|
+
w.edge_hover_delay_ms = max(100, min(1500, int(w.edge_hover_delay_ms)))
|
|
137
147
|
if w.x is not None:
|
|
138
148
|
w.x = int(w.x)
|
|
139
149
|
if w.y is not None:
|
|
@@ -143,23 +153,29 @@ class Settings:
|
|
|
143
153
|
self.lcu.reconnect_interval = max(1.0, min(60.0, float(self.lcu.reconnect_interval)))
|
|
144
154
|
self.lcu.request_timeout = max(1.0, min(30.0, float(self.lcu.request_timeout)))
|
|
145
155
|
|
|
146
|
-
self.vision.interval = max(0.
|
|
156
|
+
self.vision.interval = max(0.15, min(15.0, float(self.vision.interval)))
|
|
147
157
|
self.vision.ocr_min_confidence = max(0.0, min(0.99, float(self.vision.ocr_min_confidence)))
|
|
148
158
|
self.vision.match_threshold = max(0.4, min(1.0, float(self.vision.match_threshold)))
|
|
159
|
+
self.vision.ocr_closed_threshold = max(0.4, min(1.0, float(self.vision.ocr_closed_threshold)))
|
|
160
|
+
self.vision.card_merge_gap_ratio = max(0.005, min(0.12, float(self.vision.card_merge_gap_ratio)))
|
|
149
161
|
self.vision.min_matches = max(1, min(6, int(self.vision.min_matches)))
|
|
150
162
|
self.vision.cooldown = max(0.0, min(120.0, float(self.vision.cooldown)))
|
|
151
163
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
164
|
+
for attr, default in (
|
|
165
|
+
("region", [0.06, 0.12, 0.88, 0.76]),
|
|
166
|
+
("augment_title_strip", [0.08, 0.38, 0.84, 0.055]),
|
|
167
|
+
):
|
|
168
|
+
region = getattr(self.vision, attr)
|
|
169
|
+
if not isinstance(region, (list, tuple)) or len(region) != 4:
|
|
170
|
+
warnings.append(f"vision.{attr} 无效,已恢复默认区域")
|
|
171
|
+
setattr(self.vision, attr, default)
|
|
172
|
+
continue
|
|
157
173
|
x, y, width, height = (float(v) for v in region)
|
|
158
174
|
x = max(0.0, min(0.99, x))
|
|
159
175
|
y = max(0.0, min(0.99, y))
|
|
160
176
|
width = max(0.05, min(1.0 - x, width))
|
|
161
|
-
height = max(0.
|
|
162
|
-
self.vision
|
|
177
|
+
height = max(0.005, min(1.0 - y, height))
|
|
178
|
+
setattr(self.vision, attr, [round(x, 4), round(y, 4), round(width, 4), round(height, 4)])
|
|
163
179
|
|
|
164
180
|
self.data.refresh_hours = max(0.25, min(24 * 30, float(self.data.refresh_hours)))
|
|
165
181
|
return warnings
|
package/src/data/matcher.py
CHANGED
|
@@ -14,6 +14,17 @@ import re
|
|
|
14
14
|
import threading
|
|
15
15
|
import unicodedata
|
|
16
16
|
from collections.abc import Iterable, Sequence
|
|
17
|
+
from functools import lru_cache
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
from pypinyin import lazy_pinyin
|
|
21
|
+
except Exception: # pragma: no cover - optional at import time
|
|
22
|
+
lazy_pinyin = None
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
from rapidfuzz import fuzz as rapid_fuzz
|
|
26
|
+
except Exception: # pragma: no cover - optional at import time
|
|
27
|
+
rapid_fuzz = None
|
|
17
28
|
|
|
18
29
|
from .models import (
|
|
19
30
|
Augment,
|
|
@@ -214,6 +225,36 @@ def _similarity(left: str, right: str) -> float:
|
|
|
214
225
|
return difflib.SequenceMatcher(None, left, right, autojunk=False).ratio()
|
|
215
226
|
|
|
216
227
|
|
|
228
|
+
@lru_cache(maxsize=4096)
|
|
229
|
+
def _pinyin_key(text: str) -> str:
|
|
230
|
+
if not text:
|
|
231
|
+
return ""
|
|
232
|
+
if lazy_pinyin is None:
|
|
233
|
+
return text
|
|
234
|
+
try:
|
|
235
|
+
return "".join(lazy_pinyin(text, errors="ignore"))
|
|
236
|
+
except Exception:
|
|
237
|
+
return text
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def closed_text_score(left: str, right: str) -> float:
|
|
241
|
+
"""0–1 score combining glyph similarity and pinyin similarity."""
|
|
242
|
+
|
|
243
|
+
if not left or not right:
|
|
244
|
+
return 0.0
|
|
245
|
+
if left == right:
|
|
246
|
+
return 1.0
|
|
247
|
+
if rapid_fuzz is not None:
|
|
248
|
+
glyph = rapid_fuzz.ratio(left, right) / 100.0
|
|
249
|
+
pinyin = rapid_fuzz.ratio(_pinyin_key(left), _pinyin_key(right)) / 100.0
|
|
250
|
+
else:
|
|
251
|
+
glyph = difflib.SequenceMatcher(None, left, right, autojunk=False).ratio()
|
|
252
|
+
pinyin = difflib.SequenceMatcher(
|
|
253
|
+
None, _pinyin_key(left), _pinyin_key(right), autojunk=False
|
|
254
|
+
).ratio()
|
|
255
|
+
return 0.6 * glyph + 0.4 * pinyin
|
|
256
|
+
|
|
257
|
+
|
|
217
258
|
class NameMatcher:
|
|
218
259
|
"""Generic normalized-name index with conservative fuzzy fallback."""
|
|
219
260
|
|
|
@@ -257,6 +298,30 @@ class NameMatcher:
|
|
|
257
298
|
return best
|
|
258
299
|
return None
|
|
259
300
|
|
|
301
|
+
def closed_match(self, text: str, *, threshold: float = 0.65) -> tuple[int, str, float] | None:
|
|
302
|
+
"""Closed-set OCR correction with glyph + pinyin similarity."""
|
|
303
|
+
|
|
304
|
+
normalized = normalize_text(text)
|
|
305
|
+
if len(normalized) < 2:
|
|
306
|
+
return None
|
|
307
|
+
candidates = text_variants(text)
|
|
308
|
+
if not candidates:
|
|
309
|
+
return None
|
|
310
|
+
best: tuple[int, str, float] | None = None
|
|
311
|
+
for key, name, variants in self._entries:
|
|
312
|
+
for candidate in candidates:
|
|
313
|
+
for variant in variants:
|
|
314
|
+
if len(variant) < 2:
|
|
315
|
+
continue
|
|
316
|
+
score = closed_text_score(candidate, variant)
|
|
317
|
+
if best is None or score > best[2]:
|
|
318
|
+
best = (key, name, score)
|
|
319
|
+
if score >= 0.999:
|
|
320
|
+
return best
|
|
321
|
+
if best is not None and best[2] >= threshold:
|
|
322
|
+
return best
|
|
323
|
+
return None
|
|
324
|
+
|
|
260
325
|
def __len__(self) -> int:
|
|
261
326
|
return len(self._entries)
|
|
262
327
|
|
|
@@ -347,6 +412,30 @@ class StatsMatcher:
|
|
|
347
412
|
match_score=found[2],
|
|
348
413
|
)
|
|
349
414
|
|
|
415
|
+
def match_augment_closed(
|
|
416
|
+
self,
|
|
417
|
+
text: str,
|
|
418
|
+
*,
|
|
419
|
+
confidence: float = 1.0,
|
|
420
|
+
threshold: float = 0.65,
|
|
421
|
+
center_x: float = 0.0,
|
|
422
|
+
center_y: float = 0.0,
|
|
423
|
+
) -> AugmentMatch | None:
|
|
424
|
+
found = self.augment_matcher.closed_match(text, threshold=threshold)
|
|
425
|
+
if not found:
|
|
426
|
+
return None
|
|
427
|
+
augment = self.repo.get_augment(found[0])
|
|
428
|
+
if not augment:
|
|
429
|
+
return None
|
|
430
|
+
return AugmentMatch(
|
|
431
|
+
augment=augment,
|
|
432
|
+
raw_text=text,
|
|
433
|
+
confidence=max(0.0, min(1.0, confidence)),
|
|
434
|
+
match_score=found[2],
|
|
435
|
+
center_x=center_x,
|
|
436
|
+
center_y=center_y,
|
|
437
|
+
)
|
|
438
|
+
|
|
350
439
|
def match_augment_lines(
|
|
351
440
|
self,
|
|
352
441
|
lines: Iterable[OCRLine],
|
package/src/data/models.py
CHANGED
package/src/main.py
CHANGED
|
@@ -32,6 +32,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
|
32
32
|
parser.add_argument("--demo", action="store_true", help="使用演示数据启动,不连接 LCU")
|
|
33
33
|
parser.add_argument("--no-lcu", action="store_true", help="不连接英雄联盟客户端")
|
|
34
34
|
parser.add_argument("--debug", action="store_true", help="输出调试日志")
|
|
35
|
+
parser.add_argument("--debug-vision", action="store_true", help="启动后导出一次 F9 视觉调试包")
|
|
35
36
|
parser.add_argument("--screenshot", default="", help="启动演示并保存窗口截图后退出")
|
|
36
37
|
parser.add_argument("--quit-after", type=float, default=0.0, help="N 秒后自动退出(调试用)")
|
|
37
38
|
parser.add_argument("--settings", default="", help="使用自定义 settings.json")
|
package/src/ui/augment_panel.py
CHANGED
|
@@ -58,7 +58,7 @@ class AugmentPanel(QWidget):
|
|
|
58
58
|
|
|
59
59
|
def set_waiting(self, message: str = "进入对局后自动识别海克斯卡片") -> None:
|
|
60
60
|
clear_layout(self.layout)
|
|
61
|
-
header = SectionHeader("
|
|
61
|
+
header = SectionHeader("海克斯选择", "识别待机")
|
|
62
62
|
self.layout.addWidget(header)
|
|
63
63
|
card = QFrame()
|
|
64
64
|
card.setObjectName("Card")
|
|
@@ -108,7 +108,7 @@ class AugmentPanel(QWidget):
|
|
|
108
108
|
self.layout.addWidget(self._empty_detection(raw_matches))
|
|
109
109
|
self.layout.addStretch(1)
|
|
110
110
|
else:
|
|
111
|
-
header = SectionHeader("
|
|
111
|
+
header = SectionHeader(f"本局 {len(evaluations)} 选一", f"{len(evaluations)} 张 · 按推荐度排序")
|
|
112
112
|
self.layout.addWidget(header)
|
|
113
113
|
for evaluation in evaluations:
|
|
114
114
|
self.layout.addWidget(self._candidate_card(evaluation, champion))
|
package/src/vision/capture.py
CHANGED
|
@@ -47,6 +47,22 @@ class WindowRect:
|
|
|
47
47
|
bottom = top + max(1, round(max(0.0, min(1.0, height)) * self.height))
|
|
48
48
|
return (left, top, min(right, self.right), min(bottom, self.bottom))
|
|
49
49
|
|
|
50
|
+
def safe_crop_box(self, region: tuple[float, float, float, float]) -> tuple[int, int, int, int]:
|
|
51
|
+
"""Crop relative to a centered 16:9 safe area.
|
|
52
|
+
|
|
53
|
+
On a 21:9 monitor, the card row remains centered in the 16:9 region
|
|
54
|
+
rather than stretching into the ultrawide side bars.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
safe_width = min(self.width, round(self.height * 16 / 9))
|
|
58
|
+
safe_left = self.left + (self.width - safe_width) // 2
|
|
59
|
+
x, y, width, height = region
|
|
60
|
+
left = safe_left + round(max(0.0, min(1.0, x)) * safe_width)
|
|
61
|
+
top = self.top + round(max(0.0, min(1.0, y)) * self.height)
|
|
62
|
+
right = left + max(1, round(max(0.0, min(1.0, width)) * safe_width))
|
|
63
|
+
bottom = top + max(1, round(max(0.0, min(1.0, height)) * self.height))
|
|
64
|
+
return (left, top, min(right, self.right), min(bottom, self.bottom))
|
|
65
|
+
|
|
50
66
|
|
|
51
67
|
@dataclass(frozen=True)
|
|
52
68
|
class GameWindow:
|
|
@@ -211,6 +227,18 @@ class ScreenCapture:
|
|
|
211
227
|
image = self.grab(box)
|
|
212
228
|
return image, window
|
|
213
229
|
|
|
230
|
+
def grab_game_safe(self, region: tuple[float, float, float, float]) -> tuple[Image.Image, GameWindow]:
|
|
231
|
+
"""Capture inside a centered 16:9 safe area (ultrawide friendly)."""
|
|
232
|
+
|
|
233
|
+
window = find_game_window()
|
|
234
|
+
if window is None:
|
|
235
|
+
raise CaptureError("未找到英雄联盟游戏窗口(请先进入对局)")
|
|
236
|
+
box = window.rect.safe_crop_box(region)
|
|
237
|
+
if box[2] <= box[0] or box[3] <= box[1]:
|
|
238
|
+
raise CaptureError("裁剪区域超出游戏窗口")
|
|
239
|
+
image = self.grab(box)
|
|
240
|
+
return image, window
|
|
241
|
+
|
|
214
242
|
def grab_fullscreen(self) -> Image.Image:
|
|
215
243
|
try:
|
|
216
244
|
sct = self._ensure()
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""F9 / debug-vision export for the augment title strip."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from PIL import Image, ImageDraw
|
|
9
|
+
|
|
10
|
+
from ..core.paths import PROJECT_ROOT
|
|
11
|
+
from ..data.models import AugmentMatch, OCRLine
|
|
12
|
+
from .title_strip import CardCluster
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def save_vision_debug(
|
|
16
|
+
strip: Image.Image,
|
|
17
|
+
processed: Image.Image,
|
|
18
|
+
clusters: list[CardCluster],
|
|
19
|
+
lines: list[OCRLine],
|
|
20
|
+
matches: list[AugmentMatch],
|
|
21
|
+
*,
|
|
22
|
+
output_dir: Path | None = None,
|
|
23
|
+
fullscreen: Image.Image | None = None,
|
|
24
|
+
) -> Path:
|
|
25
|
+
target = output_dir or (PROJECT_ROOT / "debug_output")
|
|
26
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
27
|
+
stamp = time.strftime("%Y%m%d-%H%M%S")
|
|
28
|
+
run_dir = target / stamp
|
|
29
|
+
run_dir.mkdir(parents=True, exist_ok=True)
|
|
30
|
+
|
|
31
|
+
strip.save(run_dir / "title_strip_raw.png")
|
|
32
|
+
processed.save(run_dir / "title_strip_processed.png")
|
|
33
|
+
|
|
34
|
+
annotated = strip.convert("RGB").copy()
|
|
35
|
+
draw = ImageDraw.Draw(annotated)
|
|
36
|
+
draw.rectangle((0, 0, annotated.width - 1, annotated.height - 1), outline="#2F80ED", width=3)
|
|
37
|
+
for index, cluster in enumerate(clusters, 1):
|
|
38
|
+
box = (
|
|
39
|
+
max(0, int(cluster.x_min)),
|
|
40
|
+
max(0, int(cluster.y_min)),
|
|
41
|
+
min(annotated.width - 1, int(cluster.x_max)),
|
|
42
|
+
min(annotated.height - 1, int(cluster.y_max)),
|
|
43
|
+
)
|
|
44
|
+
draw.rectangle(box, outline="#3DDC97", width=2)
|
|
45
|
+
draw.text((box[0] + 3, max(0, box[1] - 12)), str(index), fill="#3DDC97")
|
|
46
|
+
annotated.save(run_dir / "annotated_strip.png")
|
|
47
|
+
if fullscreen is not None:
|
|
48
|
+
fullscreen.convert("RGB").save(run_dir / "game_fullscreen.png")
|
|
49
|
+
|
|
50
|
+
lines_out = [
|
|
51
|
+
f"cards={len(matches)} clusters={len(clusters)} ocr_lines={len(lines)}",
|
|
52
|
+
"matches=" + ", ".join(f"{m.augment.name}:{m.raw_text}:{m.match_score:.3f}" for m in matches),
|
|
53
|
+
"",
|
|
54
|
+
"x_center_ratio | confidence | text | name | score",
|
|
55
|
+
]
|
|
56
|
+
for cluster in clusters:
|
|
57
|
+
match = next((m for m in matches if abs(m.x_center_ratio - cluster.x_center_ratio) < 0.02), None)
|
|
58
|
+
lines_out.append(
|
|
59
|
+
f"{cluster.x_center_ratio:.3f} | {cluster.confidence:.3f} | {cluster.text} | "
|
|
60
|
+
f"{match.augment.name if match else 'UNMATCHED'} | "
|
|
61
|
+
f"{match.match_score if match else 0:.3f}"
|
|
62
|
+
)
|
|
63
|
+
lines_out.extend(["", "raw_ocr:"])
|
|
64
|
+
lines_out.extend(f"{line.confidence:.3f}\t{line.text}" for line in lines)
|
|
65
|
+
(run_dir / "ocr_log.txt").write_text("\n".join(lines_out) + "\n", encoding="utf-8")
|
|
66
|
+
return run_dir
|
package/src/vision/ocr_engine.py
CHANGED
|
@@ -7,6 +7,7 @@ import threading
|
|
|
7
7
|
from collections.abc import Sequence
|
|
8
8
|
from typing import Protocol
|
|
9
9
|
|
|
10
|
+
import cv2
|
|
10
11
|
import numpy as np
|
|
11
12
|
from PIL import Image, ImageEnhance, ImageFilter
|
|
12
13
|
|
|
@@ -41,6 +42,122 @@ def _preprocess(image: Image.Image) -> Image.Image:
|
|
|
41
42
|
return image.filter(ImageFilter.MedianFilter(size=3))
|
|
42
43
|
|
|
43
44
|
|
|
45
|
+
def _segment_line_crops(segment: Image.Image) -> list[tuple[Image.Image, int, int]]:
|
|
46
|
+
"""Crop a card segment into one image per text line (for wrapped titles)."""
|
|
47
|
+
|
|
48
|
+
gray = np.asarray(segment.convert("L"))
|
|
49
|
+
if gray.size == 0:
|
|
50
|
+
return []
|
|
51
|
+
rows = (gray < 128).sum(axis=1)
|
|
52
|
+
active = rows > max(1, gray.shape[1] // 100)
|
|
53
|
+
runs: list[tuple[int, int]] = []
|
|
54
|
+
start = None
|
|
55
|
+
for y, flag in enumerate(active):
|
|
56
|
+
if flag and start is None:
|
|
57
|
+
start = y
|
|
58
|
+
elif not flag and start is not None:
|
|
59
|
+
runs.append((start, y))
|
|
60
|
+
start = None
|
|
61
|
+
if start is not None:
|
|
62
|
+
runs.append((start, gray.shape[0]))
|
|
63
|
+
merged: list[tuple[int, int]] = []
|
|
64
|
+
for start, end in runs:
|
|
65
|
+
if merged and start - merged[-1][1] <= 3:
|
|
66
|
+
merged[-1] = (merged[-1][0], end)
|
|
67
|
+
else:
|
|
68
|
+
merged.append((start, end))
|
|
69
|
+
result: list[tuple[Image.Image, int, int]] = []
|
|
70
|
+
for start, end in merged:
|
|
71
|
+
if end - start < 6:
|
|
72
|
+
continue
|
|
73
|
+
top = max(0, start - 4)
|
|
74
|
+
bottom = min(gray.shape[0], end + 5)
|
|
75
|
+
result.append((segment.crop((0, top, segment.width, bottom)), top, bottom))
|
|
76
|
+
return result
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def split_title_segments(processed: Image.Image, *, min_gap: int = 24, min_width: int = 30) -> list[tuple[int, int]]:
|
|
80
|
+
"""Find card-sized horizontal ink runs in a prepared title strip.
|
|
81
|
+
|
|
82
|
+
The detector occasionally merges a wide 3/4-card strip into a single line.
|
|
83
|
+
Splitting at large blank columns before OCR keeps each card independent
|
|
84
|
+
while still handling one or two wrapped title lines.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
gray = np.asarray(processed.convert("L"))
|
|
88
|
+
if gray.size == 0:
|
|
89
|
+
return []
|
|
90
|
+
height, width = gray.shape
|
|
91
|
+
binary = (gray < 128).astype(np.uint8)
|
|
92
|
+
count, labels, stats, _ = cv2.connectedComponentsWithStats(binary, connectivity=8)
|
|
93
|
+
for index in range(1, count):
|
|
94
|
+
x, _y, w, h, _area = stats[index]
|
|
95
|
+
# Card border lines are tall and very thin; remove them so they do not
|
|
96
|
+
# bridge the gap between two cards.
|
|
97
|
+
if h >= height * 0.60 and w <= max(8, width // 300):
|
|
98
|
+
binary[labels == index] = 0
|
|
99
|
+
columns = binary.sum(axis=0)
|
|
100
|
+
active = columns > max(1, height // 80)
|
|
101
|
+
runs: list[tuple[int, int]] = []
|
|
102
|
+
start = None
|
|
103
|
+
for x, flag in enumerate(active):
|
|
104
|
+
if flag and start is None:
|
|
105
|
+
start = x
|
|
106
|
+
elif not flag and start is not None:
|
|
107
|
+
runs.append((start, x))
|
|
108
|
+
start = None
|
|
109
|
+
if start is not None:
|
|
110
|
+
runs.append((start, width))
|
|
111
|
+
merged: list[tuple[int, int]] = []
|
|
112
|
+
for start, end in runs:
|
|
113
|
+
if merged and start - merged[-1][1] < min_gap:
|
|
114
|
+
merged[-1] = (merged[-1][0], end)
|
|
115
|
+
else:
|
|
116
|
+
merged.append((start, end))
|
|
117
|
+
return [(start, end) for start, end in merged if end - start >= min_width]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def preprocess_title_strip(image: Image.Image) -> Image.Image:
|
|
121
|
+
"""Make a high-contrast white-background title strip for OCR.
|
|
122
|
+
|
|
123
|
+
The strip intentionally contains gaps between cards. A global Otsu pass
|
|
124
|
+
would be dragged by bright combat effects in those gaps, so this uses an
|
|
125
|
+
HSV neutral/bright mask plus local adaptive thresholding. The result is
|
|
126
|
+
upscaled 2x and padded with white, which keeps small CJK strokes legible.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
if image.mode != "RGB":
|
|
130
|
+
image = image.convert("RGB")
|
|
131
|
+
rgb = np.asarray(image)
|
|
132
|
+
if rgb.size == 0:
|
|
133
|
+
raise OCRError("OCR 输入图像为空")
|
|
134
|
+
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
|
|
135
|
+
value = hsv[:, :, 2]
|
|
136
|
+
saturation = hsv[:, :, 1]
|
|
137
|
+
# White and pale-gold title text is bright and mostly neutral. Deep blue
|
|
138
|
+
# card backgrounds and saturated spell effects fall outside this mask.
|
|
139
|
+
mask = ((value >= 145) & (saturation <= 210)).astype(np.uint8) * 255
|
|
140
|
+
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((2, 2), np.uint8))
|
|
141
|
+
upscaled = cv2.resize(rgb, None, fx=2.0, fy=2.0, interpolation=cv2.INTER_CUBIC)
|
|
142
|
+
mask = cv2.resize(mask, (upscaled.shape[1], upscaled.shape[0]), interpolation=cv2.INTER_NEAREST)
|
|
143
|
+
gray = cv2.cvtColor(upscaled, cv2.COLOR_RGB2GRAY)
|
|
144
|
+
# Per-pixel local threshold; no global Otsu.
|
|
145
|
+
binary = cv2.adaptiveThreshold(
|
|
146
|
+
gray,
|
|
147
|
+
255,
|
|
148
|
+
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
|
149
|
+
cv2.THRESH_BINARY,
|
|
150
|
+
31,
|
|
151
|
+
-6,
|
|
152
|
+
)
|
|
153
|
+
binary = cv2.bitwise_and(binary, mask)
|
|
154
|
+
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, np.ones((2, 2), np.uint8))
|
|
155
|
+
# White background, black glyphs, 16px white safety border.
|
|
156
|
+
output = 255 - binary
|
|
157
|
+
output = cv2.copyMakeBorder(output, 16, 16, 16, 16, cv2.BORDER_CONSTANT, value=255)
|
|
158
|
+
return Image.fromarray(output, mode="L").convert("RGB")
|
|
159
|
+
|
|
160
|
+
|
|
44
161
|
class RapidOCREngine:
|
|
45
162
|
"""Lazily-initialized RapidOCR engine.
|
|
46
163
|
|
|
@@ -74,7 +191,10 @@ class RapidOCREngine:
|
|
|
74
191
|
self._load_error = f"无法导入 rapidocr_onnxruntime: {exc}"
|
|
75
192
|
raise OCRError(self._load_error) from exc
|
|
76
193
|
try:
|
|
77
|
-
|
|
194
|
+
try:
|
|
195
|
+
self._engine = RapidOCR(use_cls=False)
|
|
196
|
+
except TypeError: # older RapidOCR builds
|
|
197
|
+
self._engine = RapidOCR()
|
|
78
198
|
except Exception as exc:
|
|
79
199
|
self._load_error = f"OCR 模型初始化失败: {exc}"
|
|
80
200
|
raise OCRError(self._load_error) from exc
|
|
@@ -111,6 +231,79 @@ class RapidOCREngine:
|
|
|
111
231
|
lines.sort(key=lambda line: (round(line.center_y / 24), line.center_x))
|
|
112
232
|
return lines
|
|
113
233
|
|
|
234
|
+
def recognize_strip(self, image: Image.Image) -> tuple[list[OCRLine], Image.Image]:
|
|
235
|
+
"""Recognize one horizontal title strip and return OCR lines + debug image.
|
|
236
|
+
|
|
237
|
+
Boxes are mapped back to the original strip coordinates. The OCR pass
|
|
238
|
+
runs on the prepared white-background image with direction classifier
|
|
239
|
+
disabled for speed.
|
|
240
|
+
"""
|
|
241
|
+
|
|
242
|
+
if image.mode != "RGB":
|
|
243
|
+
image = image.convert("RGB")
|
|
244
|
+
processed = preprocess_title_strip(image)
|
|
245
|
+
engine = self._ensure_engine()
|
|
246
|
+
segments = split_title_segments(processed)
|
|
247
|
+
lines: list[OCRLine] = []
|
|
248
|
+
if 2 <= len(segments) <= 4:
|
|
249
|
+
# Recognition-only batch: one detection-free pass over one crop per
|
|
250
|
+
# card/line. This is both faster and avoids the detector merging a
|
|
251
|
+
# 4-card strip into one giant text box.
|
|
252
|
+
crops: list[np.ndarray] = []
|
|
253
|
+
crop_meta: list[tuple[float, float, float, float]] = []
|
|
254
|
+
for start, end in segments:
|
|
255
|
+
segment = processed.crop((start, 0, end, processed.height))
|
|
256
|
+
for line_image, y0, y1 in _segment_line_crops(segment):
|
|
257
|
+
crops.append(np.ascontiguousarray(np.asarray(line_image)[:, :, ::-1]))
|
|
258
|
+
# Coordinates are in processed space; map back below.
|
|
259
|
+
crop_meta.append((float(start), float(end), float(y0), float(y1)))
|
|
260
|
+
texts, _elapse = ([], 0.0)
|
|
261
|
+
recognizer = getattr(engine, "text_recognizer", None)
|
|
262
|
+
if crops and recognizer is not None:
|
|
263
|
+
with self._lock:
|
|
264
|
+
texts, _elapse = recognizer(crops)
|
|
265
|
+
if len(texts) == len(crop_meta):
|
|
266
|
+
for (text, score), (x_min, x_max, y_min, y_max) in zip(texts, crop_meta):
|
|
267
|
+
confidence = float(score)
|
|
268
|
+
cleaned = str(text).strip()
|
|
269
|
+
if confidence < self.min_confidence or not cleaned:
|
|
270
|
+
continue
|
|
271
|
+
points = (
|
|
272
|
+
((x_min - 16.0) / 2.0, (y_min - 16.0) / 2.0),
|
|
273
|
+
((x_max - 16.0) / 2.0, (y_min - 16.0) / 2.0),
|
|
274
|
+
((x_max - 16.0) / 2.0, (y_max - 16.0) / 2.0),
|
|
275
|
+
((x_min - 16.0) / 2.0, (y_max - 16.0) / 2.0),
|
|
276
|
+
)
|
|
277
|
+
lines.append(OCRLine(text=cleaned, confidence=confidence, box=points))
|
|
278
|
+
lines.sort(key=lambda line: (line.center_x, line.center_y))
|
|
279
|
+
return lines, processed
|
|
280
|
+
|
|
281
|
+
bgr = np.ascontiguousarray(np.asarray(processed)[:, :, ::-1])
|
|
282
|
+
try:
|
|
283
|
+
with self._lock:
|
|
284
|
+
result, _elapse = engine(bgr)
|
|
285
|
+
except Exception as exc:
|
|
286
|
+
raise OCRError(f"OCR 识别失败: {exc}") from exc
|
|
287
|
+
for row in result or []:
|
|
288
|
+
try:
|
|
289
|
+
box, text, score = row[0], row[1], row[2]
|
|
290
|
+
confidence = float(score)
|
|
291
|
+
if confidence < self.min_confidence:
|
|
292
|
+
continue
|
|
293
|
+
cleaned = str(text).strip()
|
|
294
|
+
if not cleaned:
|
|
295
|
+
continue
|
|
296
|
+
# preprocess_title_strip: 2x cubic upscale + 16px border.
|
|
297
|
+
points = tuple(
|
|
298
|
+
((float(point[0]) - 16.0) / 2.0, (float(point[1]) - 16.0) / 2.0)
|
|
299
|
+
for point in box
|
|
300
|
+
)
|
|
301
|
+
lines.append(OCRLine(text=cleaned, confidence=confidence, box=points))
|
|
302
|
+
except (TypeError, ValueError, IndexError):
|
|
303
|
+
log.debug("Ignoring malformed OCR strip row: %r", row)
|
|
304
|
+
lines.sort(key=lambda line: (line.center_x, line.center_y))
|
|
305
|
+
return lines, processed
|
|
306
|
+
|
|
114
307
|
|
|
115
308
|
class StaticOCREngine:
|
|
116
309
|
"""Test/demo engine that returns predefined lines."""
|