Files
lc-mcp/ocr_local.py
T

75 lines
2.2 KiB
Python
Raw 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 -*-
"""本地 OCR:Windows.Media.Ocr(winsdk),零远端依赖。
只支持 Windows;Linux/mac 上 import winsdk 会失败 -> 用 remote 后端。
"""
import asyncio
def available():
try:
from winsdk.windows.media.ocr import OcrEngine # noqa: F401
return True
except Exception:
return False
def _engine():
from winsdk.windows.media.ocr import OcrEngine
from winsdk.windows.globalization import Language
try:
eng = OcrEngine.try_create_from_language(Language('zh-Hans'))
if eng:
return eng
except Exception:
pass
return OcrEngine.try_create_from_user_profile_languages()
async def _ocr_async(path):
from winsdk.windows.media.ocr import OcrEngine # noqa: F401
from winsdk.windows.storage import StorageFile, FileAccessMode
from winsdk.windows.graphics.imaging import BitmapDecoder
file = await StorageFile.get_file_from_path_async(path)
stream = await file.open_async(FileAccessMode.READ)
decoder = await BitmapDecoder.create_async(stream)
bitmap = await decoder.get_software_bitmap_async()
eng = _engine()
if eng is None:
return None, 'no OCR engine (language pack missing?)'
result = await eng.recognize_async(bitmap)
items = []
for line in result.lines:
words = line.words
if not words:
continue
text = ' '.join(w.text for w in words)
w0 = words[0].bounding_rect
x0, y0 = w0.x, w0.y
x1, y1 = w0.x + w0.width, w0.y + w0.height
for w in words[1:]:
r = w.bounding_rect
if r.x < x0:
x0 = r.x
if r.y < y0:
y0 = r.y
if r.x + r.width > x1:
x1 = r.x + r.width
if r.y + r.height > y1:
y1 = r.y + r.height
items.append({
'text': text,
'x': int(x0), 'y': int(y0),
'w': int(x1 - x0), 'h': int(y1 - y0),
})
return items, None
def ocr_image(path):
"""同步接口。返回 (items, None) 或 (None, error)。"""
try:
return asyncio.run(_ocr_async(path))
except Exception as e:
return None, 'local ocr fail: %s' % e