"""TextIn 云服务(手写擦除 / 通用识别)。 为什么单开一个模块: - 本机 OCR 走 Windows.Media.Ocr,只能认字、不能"擦",而且部署到 Linux 上就没有了; - TextIn 的手写擦除正好补上产品里缺的一环:把卷子上孩子的笔迹擦掉,得到一张干净的空白卷, 既能重新打印,也能让"切题"少被手写干扰。 零依赖:urllib + json,凭据从环境变量或 data/textin.env 读。 """ from __future__ import annotations import base64 import json import os import urllib.error import urllib.parse import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parent.parent ENV_FILE = ROOT / "data" / "textin.env" BASE = "https://api.textin.com" # 手写擦除:返回 result.image(base64 的 jpg) P_ERASE = "/ai/service/v1/handwritten_erase" # 通用文字识别(版面上带坐标,可辅助切题) P_OCR = "/ai/service/v1/general_ocr" def _load_env() -> None: """把 data/textin.env 里的键读进环境变量(不覆盖已有的)。""" if not ENV_FILE.exists(): return try: text = ENV_FILE.read_text(encoding="utf-8-sig") except OSError: return for line in text.splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue k, v = line.split("=", 1) k, v = k.strip(), v.strip() if k and v and not os.environ.get(k): os.environ[k] = v _load_env() def app_id() -> str: return os.environ.get("TEXTIN_APP_ID", "").strip() def secret() -> str: return os.environ.get("TEXTIN_SECRET_CODE", "").strip() def mode() -> str: """live / none。""" return "live" if (app_id() and secret()) else "none" def available() -> bool: return mode() == "live" def _request(path: str, data: bytes, params: dict | None = None, timeout: int = 30) -> dict: """返回 {ok, data|error, code, message}。永不抛异常。""" if not available(): return {"ok": False, "code": "TEXTIN_NOT_CONFIGURED", "message": "没配 TEXTIN_APP_ID / TEXTIN_SECRET_CODE"} url = BASE + path if params: q = "&".join(f"{k}={urllib.parse.quote(str(v))}" for k, v in params.items()) url = f"{url}?{q}" req = urllib.request.Request( url, data=data, method="POST", headers={ "x-ti-app-id": app_id(), "x-ti-secret-code": secret(), "Content-Type": "application/octet-stream", }, ) try: with urllib.request.urlopen(req, timeout=timeout) as r: raw = r.read() except urllib.error.HTTPError as e: return {"ok": False, "code": f"HTTP_{e.code}", "message": f"HTTP {e.code}"} except Exception as e: # noqa: BLE001 return {"ok": False, "code": "TEXTIN_UNREACHABLE", "message": f"{type(e).__name__}: {e}"} try: payload = json.loads(raw.decode("utf-8", "replace")) except ValueError: return {"ok": False, "code": "TEXTIN_BAD_JSON", "message": "返回不是 JSON"} code = payload.get("code") if code != 200: msg = payload.get("message") or payload.get("msg") or "" return {"ok": False, "code": f"TEXTIN_{code}", "message": msg, "request_id": payload.get("x_request_id")} return {"ok": True, "data": payload.get("result") or {}, "ms": payload.get("duration"), "request_id": payload.get("x_request_id")} def erase_handwriting(image: bytes, *, color: bool = True, dewarp: bool = True, crop: bool = False, timeout: int = 40) -> dict: """擦掉手写笔迹,返回 {ok, image(bytes), ms, message}。 color=True 保留红色批改以外的原卷色彩(试卷上老师的红钩会尽量保留); 传 False 得到黑白图,打印更省墨。 """ params = { "image_type": 1 if color else 0, "dewarp": 1 if dewarp else 0, "crop": 1 if crop else 0, "binarization": 1, } r = _request(P_ERASE, image, params, timeout=timeout) if not r["ok"]: return {"ok": False, "code": r["code"], "message": r["message"]} b64 = (r["data"] or {}).get("image") or "" if not b64: return {"ok": False, "code": "TEXTIN_NO_IMAGE", "message": "接口成功但没返回图"} try: out = base64.b64decode(b64) except Exception as e: # noqa: BLE001 return {"ok": False, "code": "TEXTIN_BAD_BASE64", "message": str(e)} return {"ok": True, "image": out, "ms": r.get("ms"), "bytes": len(out)} def general_ocr(image: bytes, timeout: int = 30) -> dict: """通用识别:返回 [{text, x, y, w, h}],形状对齐 ocr.recognize() 用的 lines。""" r = _request(P_OCR, image, {"straighten": 0}, timeout=timeout) if not r["ok"]: return {"ok": False, "code": r["code"], "message": r["message"], "lines": []} res = r["data"] or {} lines = [] for item in (res.get("lines") or []): pos = item.get("pos") or [] xs = [p[0] for p in pos if isinstance(p, (list, tuple)) and p] ys = [p[1] for p in pos if isinstance(p, (list, tuple)) and len(p) > 1] if not xs or not ys: continue lines.append({ "text": (item.get("text") or "").strip(), "x": int(min(xs)), "y": int(min(ys)), "w": int(max(xs) - min(xs)), "h": int(max(ys) - min(ys)), }) lines.sort(key=lambda l: (l["y"], l["x"])) return {"ok": True, "lines": [l for l in lines if l["text"]], "ms": r.get("ms")}