Files

99 lines
3.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""手写识别:内置手写板 -> 笔画渲染成图 -> 已配置的视觉模型读字。
为什么不用系统手写:工控机上 `TabTip.exe` 常驻但窗口永不显示,
`osk.exe` 从普通权限进程启动直接 WinError 740;本机也没有 Tablet PC 的
`Microsoft.Ink` COM,没有 WinRT 绑定。所以笔画自己采、自己渲染,读字交给
`sight`(config.vision 那套 key/模型),不再引入第二套凭据。
识别放后台线程(一次约 1.5~2.5 秒),失败不影响输入:可以重写,也可以
一键切回 ABC 键盘。
"""
import os
import re
_ROOT = (os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if not getattr(__import__('sys'), 'frozen', False)
else os.path.dirname(os.path.abspath(__import__('sys').executable)))
_CACHE_DIR = os.path.join(_ROOT, 'data', 'cache')
def render(strokes, size, scale=2, line=None):
"""笔画列表 -> PIL 图片(白底黑线,裁到墨迹边界再放大)。
strokes: [[(x, y), (x, y), ...], ...] 坐标是画板像素
size: (画板宽, 画板高)
"""
from PIL import Image, ImageDraw
w, h = max(1, int(size[0])), max(1, int(size[1]))
sw, sh = int(w * scale), int(h * scale)
img = Image.new('RGB', (sw, sh), 'white')
d = ImageDraw.Draw(img)
lw = max(3, int((line or max(5.0, h * 0.055)) * scale))
for st in strokes or []:
pts = [(int(x * scale), int(y * scale)) for x, y in st]
if not pts:
continue
if len(pts) == 1: # 一个点也要算("丶")
x, y = pts[0]
d.ellipse([x - lw / 2, y - lw / 2, x + lw / 2, y + lw / 2],
fill='black')
else:
d.line(pts, fill='black', width=lw, joint='curve')
# 裁到字的外框:模型看紧凑的图更准,也不会被大片空白带偏
ink = img.convert('L').point(lambda v: 255 if v < 128 else 0)
box = ink.getbbox()
if box:
m = lw + 10
box = (max(0, box[0] - m), max(0, box[1] - m),
min(sw, box[2] + m), min(sh, box[3] + m))
img = img.crop(box)
# 字太小容易认错,长边补到 480
long_side = max(img.width, img.height)
if 0 < long_side < 480:
k = 480.0 / long_side
img = img.resize((max(1, int(img.width * k)),
max(1, int(img.height * k))), Image.LANCZOS)
return img
def _save(img):
try:
os.makedirs(_CACHE_DIR, exist_ok=True)
path = os.path.join(_CACHE_DIR, 'handwrite.png')
img.save(path, 'PNG')
return path
except Exception:
import tempfile
fd, path = tempfile.mkstemp(suffix='.png')
os.close(fd)
img.save(path, 'PNG')
return path
def split_candidates(text):
"""模型返回 -> 候选列表(去引号/标点,最多 4 个)。"""
text = (text or '').strip()
if not text:
return []
for ch in '「」『』《》"\'`“”‘’':
text = text.replace(ch, '')
out = []
for part in re.split(r'[|,,、;;/\s\n]+', text):
part = part.strip(' .。::!!??')
if not part or part.upper() == 'EMPTY':
continue
if len(part) > 20 or part in out:
continue
out.append(part)
return out[:4]
def recognize(strokes, size, cfg, hints=None, timeout=8.0):
"""笔画 -> 候选文字列表。失败抛异常,由调用方提示。"""
img = render(strokes, size)
path = _save(img)
from core.recognition.cloud import CloudRecognizer
text = CloudRecognizer(cfg).read_text(path, hints=hints, timeout=timeout)
return split_candidates(text)