# -*- coding: utf-8 -*- """拍照识题:用 Windows 自带的 OCR(Windows.Media.Ocr),不装任何第三方库。 为什么要绕这么一圈:这台机器装不了 pip 包(网络不通),本地也没装 tesseract。 Windows 10/11 自带中文 OCR 引擎,调用一次约 0.5 秒,够用了。 如果系统没有中文 OCR 语言包,`recognize()` 会返回 ok=False, 调用方(services.create_paper_from_image)可以退回内置题库演示。 """ from __future__ import annotations import json import os import re import shutil import subprocess import tempfile import uuid from pathlib import Path HERE = Path(__file__).resolve().parent SCRIPT = HERE / "ocr_win.ps1" TIMEOUT = 25 def _http_url() -> str: return (os.environ.get("OCR_HTTP_URL") or "").strip() def _http_key() -> str: return (os.environ.get("OCR_HTTP_KEY") or "").strip() CJK = r"\u4e00-\u9fff\u3400-\u4dbf" _CJK_CHARS = re.compile(f"[{CJK},。、;:?!()《》〈〉「」『』…—~·]") _KEEP_SPACE = re.compile(r"[0-9A-Za-z.,+\-*/=<>()!%$#&|~^_\[\]{}:;'\"?]") def _find_powershell() -> str | None: """找 PowerShell。优先 5.1(WinRT 支持最好),没有再找 pwsh。""" for name in ("powershell.exe", "pwsh.exe"): p = shutil.which(name) if p: return p for cand in ( r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe", r"C:\Program Files\PowerShell\7\pwsh.exe", ): if os.path.exists(cand): return cand return None def available() -> bool: """有 HTTP OCR 就用 HTTP;否则看本机 Windows OCR。""" if _http_url(): return True return SCRIPT.exists() and _find_powershell() is not None def quality(result: dict) -> dict: """判断「这张图值不值得往下切题」。 真实遇到的两种烂图:微信转发把长边压到 400px;手抖/逆光。它们的共同表现是 识别出一堆 2–3 个字的碎片("0." "》飞"),而不是成句的文字。 宁可在这里拦下来让人重拍,也别把乱码切成题——那样孩子会看到莫名其妙的题目。 """ if not result.get("ok"): err = result.get("error") or {} return {"ok": False, "code": err.get("code", "OCR_FAILED"), "message": err.get("message", "识别失败"), "size": None, "preview": ""} lines = result.get("lines") or [] w, h = result.get("width") or 0, result.get("height") or 0 long_side = max(w, h) text = "".join(l["text"] for l in lines) preview = text[:60] if not lines: return {"ok": False, "code": "OCR_EMPTY", "message": "图里一个字都没认出来", "size": (w, h), "preview": ""} if long_side and long_side < 300: return {"ok": False, "code": "IMAGE_TOO_SMALL", "message": f"这张图只有 {w}×{h},太小了(放大也救不回来)。" f"用手机重拍一张,让卷子占满画面。", "size": (w, h), "preview": preview} frag = sum(1 for l in lines if len(l["text"]) <= 3) if len(lines) >= 6 and frag / len(lines) > 0.35: return {"ok": False, "code": "OCR_NOISY", "message": f"这张图太糊了({w}×{h}),认出来的多是碎片。把它放平、光打亮,重拍一张。", "size": (w, h), "preview": preview} if len(text) < 12: return {"ok": False, "code": "OCR_EMPTY", "message": "这张图上几乎没字", "size": (w, h), "preview": preview} return {"ok": True, "code": "OK", "message": "", "size": (w, h), "preview": preview} def tidy(text: str) -> str: """OCR 出来的中文是一个字一个空格,这里把不该有的空格去掉。 规则:空格两边都是 ASCII 可见字符才保留(这样 36 + 47 不会被粘成 36+47 之外的怪东西), 其余空格(中文之间、中文与标点之间)全部删掉。 """ s = text.replace("\u00a0", " ").strip() if not s: return "" out = [] for i, ch in enumerate(s): if ch != " ": out.append(ch) continue prev = s[i - 1] if i > 0 else "" nxt = s[i + 1] if i + 1 < len(s) else "" if _KEEP_SPACE.match(prev or "") and _KEEP_SPACE.match(nxt or ""): out.append(" ") # 中文之间的空格直接吞掉 s = "".join(out) # 连续空格压成一个 return re.sub(r" {2,}", " ", s).strip() def _pil(): """Pillow 是可选的:有就用它做「放大 + 灰度 + 锐化」,没有就走 PowerShell 里那套缩放。""" try: from PIL import Image, ImageFilter, ImageOps return Image, ImageFilter, ImageOps except Exception: # noqa: BLE001 return None def _prep(path: Path, target_long: int) -> tuple[Path, tuple[int, int]] | None: """把图放大到长边 ≈ target_long,并做灰度/自动对比度/锐化。 为什么必须做:整页网页截图只有 380px 宽时,一行字高不到 12px,OCR 拿到的 是「不慌不忙」被认成「仁张犰口干再」。放大 2 倍并锐化后,同一张图能认出 20 行。 """ mods = _pil() if not mods: return None Image, ImageFilter, ImageOps = mods try: im = Image.open(path).convert("L") w, h = im.size scale = max(1.0, target_long / float(max(w, h))) if scale > 1.01: im = im.resize((int(round(w * scale)), int(round(h * scale))), Image.LANCZOS) im = ImageOps.autocontrast(im, cutoff=1) im = im.filter(ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3)) out = Path(tempfile.gettempdir()) / f"ql_prep_{uuid.uuid4().hex}.png" im.save(out) return out, (im.size[0], im.size[1]) except Exception: # noqa: BLE001 return None def _score(lines: list[dict]) -> int: """挑「哪一档放大认得好」:成句的行加分,2–3 个字的碎片扣分。""" if not lines: return -999 long_lines = sum(1 for l in lines if len(l["text"]) >= 6) frag = sum(1 for l in lines if len(l["text"]) <= 3) return long_lines * 3 + len(lines) - frag * 4 def _run_http(path: Path) -> dict: """把图片 POST 给外部 OCR 服务(百度/腾讯云/自建 PaddleOCR 都行)。 约定(尽量宽松): 请求 {"image_b64": "...", "filename": "page.jpg"},头 Authorization: Bearer 响应 {"ok": true, "lines": [{"text","x","y","w","h"}] 或 ["一行字", ...], "width": 1000, "height": 1400} 任何异常都返回 ok=False,让上层退回「手输」,而不是给用户一个 500。 """ import base64 import urllib.error import urllib.request try: raw = path.read_bytes() except OSError as exc: return {"ok": False, "lines": [], "error": {"code": "OCR_READ_FAILED", "message": str(exc)}} body = json.dumps({"image_b64": base64.b64encode(raw).decode("ascii"), "filename": path.name}).encode("utf-8") req = urllib.request.Request(_http_url(), data=body, method="POST") req.add_header("Content-Type", "application/json") if _http_key(): req.add_header("Authorization", "Bearer " + _http_key()) try: with urllib.request.urlopen(req, timeout=TIMEOUT) as resp: payload = json.loads(resp.read().decode("utf-8", "replace") or "{}") except urllib.error.HTTPError as exc: return {"ok": False, "lines": [], "error": {"code": "OCR_HTTP_FAILED", "message": f"OCR 服务返回 {exc.code}"}} except Exception as exc: # noqa: BLE001 return {"ok": False, "lines": [], "error": {"code": "OCR_HTTP_FAILED", "message": f"连不上 OCR 服务:{exc}"}} out = [] for ln in payload.get("lines") or []: if isinstance(ln, str): out.append({"text": ln, "x": 0, "y": 0, "w": 0, "h": 0}) elif isinstance(ln, dict): out.append({"text": str(ln.get("text") or ""), "x": int(ln.get("x") or 0), "y": int(ln.get("y") or 0), "w": int(ln.get("w") or 0), "h": int(ln.get("h") or 0)}) if payload.get("ok") is False and not out: err = payload.get("error") or {} return {"ok": False, "lines": [], "error": {"code": err.get("code") or "OCR_HTTP_FAILED", "message": err.get("message") or "OCR 服务没返回文字"}} return {"ok": True, "lines": out, "lang": payload.get("lang") or "http", "width": payload.get("width"), "height": payload.get("height"), "orig_width": payload.get("width"), "orig_height": payload.get("height")} def _run(path: str) -> dict: """跑一次 ocr_win.ps1,返回它写的 json。""" exe = _find_powershell() if exe is None: return {"ok": False, "error": {"code": "NO_PS", "message": "找不到 PowerShell"}} if not SCRIPT.exists(): return {"ok": False, "error": {"code": "NO_SCRIPT", "message": "缺少 ocr_win.ps1"}} tmp = Path(tempfile.gettempdir()) / f"ql_ocr_{uuid.uuid4().hex}.json" try: proc = subprocess.run( [exe, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), "-Path", path, "-Out", str(tmp)], capture_output=True, timeout=TIMEOUT, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), ) if not tmp.exists(): msg = (proc.stderr or b"").decode("utf-8", "ignore")[-300:] or "OCR 脚本没有产出结果" return {"ok": False, "error": {"code": "OCR_FAILED", "message": msg}} return json.loads(tmp.read_text(encoding="utf-8")) except subprocess.TimeoutExpired: return {"ok": False, "error": {"code": "TIMEOUT", "message": "识别超时(图片可能太大)"}} except Exception as e: # noqa: BLE001 return {"ok": False, "error": {"code": "OCR_ERROR", "message": f"{type(e).__name__}: {e}"}} finally: try: tmp.unlink(missing_ok=True) except OSError: pass def recognize(path: str | Path) -> dict: """识别一张图,返回 {ok, lines:[{text,x,y,w,h}], lang, width, height, error}。 小图(长边 < 1600)会自动试两档放大,取认得最好的那档——网页截图/微信转发图 长边往往只有 400px 左右,不放大基本是乱码,放大过头又会把噪点一起放大。 """ src = Path(str(path)) if _http_url(): data = _run_http(src) lines = [{"text": t, "x": l["x"], "y": l["y"], "w": l["w"], "h": l["h"]} for l in data.get("lines") or [] for t in [tidy(l.get("text") or "")] if t] lines.sort(key=lambda l: (l["y"], l["x"])) if not data.get("ok"): err = data.get("error") or {} return {"ok": False, "lines": [], "width": data.get("width"), "height": data.get("height"), "error": {"code": err.get("code", "OCR_HTTP_FAILED"), "message": err.get("message", "OCR 服务不可用")}} w, h = data.get("width"), data.get("height") return {"ok": True, "lines": lines, "lang": data.get("lang"), "width": w, "height": h, "scaled": 1.0, "ocr_width": w, "ocr_height": h} orig_size = None best = None best_lines: list[dict] = [] best_scale = None mods = _pil() if mods: try: with mods[0].open(src) as _im: orig_size = _im.size except Exception: # noqa: BLE001 orig_size = None attempts: list[tuple[Path, int | None]] = [] if mods: attempts.append((src, 800)) attempts.append((src, 1200)) else: attempts.append((src, None)) temps: list[Path] = [] try: for p, target in attempts: use = p size = None if target is not None: prep = _prep(p, target) if prep: use, size = prep temps.append(use) data = _run(str(use)) if not data.get("ok"): if best is None: best = data continue lines = [] for ln in data.get("lines") or []: t = tidy(ln.get("text") or "") if not t: continue lines.append({"text": t, "x": int(ln.get("x") or 0), "y": int(ln.get("y") or 0), "w": int(ln.get("w") or 0), "h": int(ln.get("h") or 0)}) lines.sort(key=lambda l: (l["y"], l["x"])) if orig_size is None: orig_size = (data.get("orig_width") or data.get("width"), data.get("orig_height") or data.get("height")) if best is None or not best.get("ok") or _score(lines) > _score(best_lines): best, best_lines, best_scale = data, lines, target finally: for t in temps: try: t.unlink(missing_ok=True) except OSError: pass if not best or not best.get("ok"): err = (best or {}).get("error") or {} return {"ok": False, "lines": [], "width": (orig_size or (None, None))[0], "height": (orig_size or (None, None))[1], "error": {"code": err.get("code", "OCR_FAILED"), "message": err.get("message", "识别失败")}} w, h = orig_size if orig_size and orig_size[0] else (best.get("width"), best.get("height")) return {"ok": True, "lines": best_lines, "lang": best.get("lang"), "width": w, "height": h, "scaled": best_scale, "ocr_width": best.get("width"), "ocr_height": best.get("height")}