本地OCR: winsdk(Windows.Media.Ocr) 后端, OCR_BACKEND=local/auto/remote

Browse Source
This commit is contained in:
yws
2026-10-02 00:47:44 +00:00
parent 8d24276511
commit 7eef32fc06
4 changed files with 198 additions and 13 deletions
+24 -2
View File
@@ -23,6 +23,7 @@ from platform import detect_platform, get_input_backend, get_screenshot_provider
BACKEND_NAME = os.environ.get('INPUT_BACKEND', '').strip().lower() BACKEND_NAME = os.environ.get('INPUT_BACKEND', '').strip().lower()
OCR_URL = os.environ.get('OCR_URL', 'http://35.212.193.150:8599/').strip().rstrip('/') + '/' OCR_URL = os.environ.get('OCR_URL', 'http://35.212.193.150:8599/').strip().rstrip('/') + '/'
OCR_BACKEND = os.environ.get('OCR_BACKEND', 'auto').strip().lower()
MIN_SCORE = float(os.environ.get('OCR_MIN_SCORE', '0.5')) MIN_SCORE = float(os.environ.get('OCR_MIN_SCORE', '0.5'))
BASE = os.path.join(os.path.expanduser('~'), 'lc_mcp') BASE = os.path.join(os.path.expanduser('~'), 'lc_mcp')
os.makedirs(BASE, exist_ok=True) os.makedirs(BASE, exist_ok=True)
@@ -37,7 +38,25 @@ def log(msg):
def ocr_image(img_path): def ocr_image(img_path):
"""把本地 png POST 给远端 OCR,返回 items 列表。""" """OCR 分发:local(winsdk/Win自带) / remote(gcp1)。
OCR_BACKEND=auto: 本地可用则本地, 否则远端。"""
impl = None
if OCR_BACKEND == 'local' or OCR_BACKEND == 'auto':
try:
import ocr_local
if ocr_local.available():
impl = ('local', ocr_local)
except Exception:
impl = None
if impl is None and OCR_BACKEND != 'local':
impl = ('remote', None)
if impl is None:
return None, 'no usable OCR backend (OCR_BACKEND=%s)' % OCR_BACKEND
kind, mod = impl
if kind == 'local':
items, err = mod.ocr_image(img_path)
else:
with open(img_path, 'rb') as f: with open(img_path, 'rb') as f:
body = f.read() body = f.read()
req = urllib.request.Request(OCR_URL, data=body, headers={'Content-Type': 'image/png'}) req = urllib.request.Request(OCR_URL, data=body, headers={'Content-Type': 'image/png'})
@@ -48,7 +67,10 @@ def ocr_image(img_path):
return None, 'ocr call fail: %s' % e return None, 'ocr call fail: %s' % e
if not data.get('ok'): if not data.get('ok'):
return None, data.get('error', 'ocr error') return None, data.get('error', 'ocr error')
items = [it for it in data.get('items', []) if float(it.get('score', 0)) >= MIN_SCORE] items = data.get('items', [])
if items is None:
return None, err
items = [it for it in items if float(it.get('score', 1)) >= MIN_SCORE]
return items, None return items, None