Files
zimoyin ec6b9c7ae3 feat: 新增 bat/sh 版 API 客户端,修复 bat 吞退出码与 CRLF 问题
新增 scripts/api-client.bat 与 api-client.sh:上传图片 -> 轮询 -> 打印识别文本与
抽取字段。自动挑解释器(优先 .venv,退回系统 Python);api_client.py 只用标准库,
所以一台只装 Python、不装本项目依赖的机器也能当客户端用。

修掉两个 bat 上的真 bug(都是实测出来的,不是看代码看出来的):

1. 退出码被吞。`if exist ... ( ... exit /b %errorlevel% )` 里的 %errorlevel%
   是**解析时**展开的,取到的是启动程序之前的值,于是失败也返回 0。
   start.bat 同样中招(启动失败会被吞成成功)。两处都改成 goto 结构。

2. .bat 必须 CRLF。同一份内容,CRLF 正常跑完;LF 会让 cmd 解析挂住——
   无任何输出、也不退出,看起来像服务卡死。download-models.bat 原本也是 LF,
   一并修正;新增 .gitattributes 钉死 *.bat=eol:crlf、*.sh=eol:lf。

另:参数校验挪到探活之前,参数写错时不会因为连不上服务报出误导性错误;
stdout 加 flush,重定向到文件时输出顺序不再错乱。

测试:新增两条回归用例(bat 必须 CRLF;Windows 上 bat 能被 cmd 跑通,带超时
以免坏掉时把测试卡死)。99 passed。

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-14 12:15:39 +08:00

191 lines
7.4 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.
"""调用 OCR 服务的命令行客户端:上传图片 -> 轮询结果 -> 打印识别内容。
只用标准库,不依赖 requests/httpx,方便在任意机器上直接跑。
用法:
python scripts/api_client.py 图片.png
python scripts/api_client.py 图片1.png 图片2.png # 多张依次处理
python scripts/api_client.py 图片.png --min-confidence 0.6 # 过滤低置信片段
python scripts/api_client.py 图片.png --json # 打印原始响应
python scripts/api_client.py --health # 只探活
python scripts/api_client.py 图片.png --host http://192.168.1.10:8000
服务端接口(见 README「API」):
POST /api/v1/upload 上传图片,返回 file_id,任务进入队列
POST /api/v1/i2t 用 file_id 查结果;未完成时返回 queued/processing 与进度
GET /healthz 健康检查
"""
import argparse
import json
import mimetypes
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
DEFAULT_HOST = "http://127.0.0.1:8000"
POLL_INTERVAL_SECONDS = 0.5
FINISHED_STATUSES = ("completed", "failed")
def post_json(url: str, payload: dict, timeout: float) -> dict:
request = urllib.request.Request(
url,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
return json.loads(response.read().decode("utf-8"))
def upload_image(url: str, image_path: Path, timeout: float) -> dict:
boundary = "----ocrclient" + uuid.uuid4().hex
content_type = mimetypes.guess_type(image_path.name)[0] or "application/octet-stream"
head = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="file"; filename="{image_path.name}"\r\n'
f"Content-Type: {content_type}\r\n\r\n"
).encode("utf-8")
tail = f"\r\n--{boundary}--\r\n".encode("utf-8")
body = head + image_path.read_bytes() + tail
request = urllib.request.Request(
url,
data=body,
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
return json.loads(response.read().decode("utf-8"))
def wait_for_result(
host: str, file_id: str, timeout: float, quiet: bool, min_confidence: float
) -> dict:
"""轮询 /api/v1/i2t 直到任务结束。中途把进度打到同一行。"""
deadline = time.monotonic() + timeout
last_progress = -1
while time.monotonic() < deadline:
payload = post_json(
f"{host}/api/v1/i2t",
{"file_id": file_id, "min_confidence": min_confidence},
timeout=30,
)
data = payload.get("data") or {}
status = data.get("status")
if status in FINISHED_STATUSES:
if not quiet and last_progress >= 0:
print() # 结束进度行
return data
if not quiet:
progress = data.get("progress", 0)
extra = ""
if status == "queued" and data.get("queue_position"):
extra = f" 排队第 {data['queue_position']} 位"
if progress != last_progress:
print(f"\r 进度 {progress:>3}% {status}{extra} ", end="", flush=True)
last_progress = progress
time.sleep(POLL_INTERVAL_SECONDS)
raise TimeoutError(f"等待超过 {timeout:.0f} 秒,任务仍未结束")
def print_result(data: dict, show_json: bool) -> None:
if show_json:
print(json.dumps(data, ensure_ascii=False, indent=2))
return
result = data.get("result") or {}
text = result.get("text", "")
polygon = result.get("polygon") or {}
print(f" 耗时 {data.get('ocr_elapsed_ms')} ms,{len(polygon)} 个文本片段")
if text:
print(" ── 识别文本 " + "─" * 40)
for line in text.splitlines():
print(f" {line}")
fields = data.get("fields")
if fields:
print(" ── 抽取字段 " + "─" * 40)
for key, value in fields.items():
print(f" {key}: {value}")
def process_one(host: str, image_path: Path, args: argparse.Namespace) -> bool:
print(f"[{image_path.name}]", flush=True)
if not image_path.is_file():
print(f" 文件不存在:{image_path}", file=sys.stderr)
return False
try:
uploaded = upload_image(f"{host}/api/v1/upload", image_path, timeout=args.timeout)
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "ignore")
print(f" 上传失败 HTTP {exc.code}:{detail}", file=sys.stderr)
return False
except urllib.error.URLError as exc:
print(f" 连不上服务 {host}:{exc.reason}", file=sys.stderr)
return False
file_id = (uploaded.get("data") or {}).get("file_id")
if not file_id:
print(f" 上传响应异常:{uploaded}", file=sys.stderr)
return False
try:
data = wait_for_result(host, file_id, args.timeout, args.quiet, args.min_confidence)
except TimeoutError as exc:
print(f" {exc}", file=sys.stderr)
return False
if data.get("status") == "failed":
print(f" 识别失败:{data.get('error')}", file=sys.stderr)
return False
print_result(data, args.json)
return True
def main() -> int:
parser = argparse.ArgumentParser(description="OCR 服务命令行客户端")
parser.add_argument("images", nargs="*", type=Path, help="要识别的图片路径")
parser.add_argument("--host", default=DEFAULT_HOST, help=f"服务地址,默认 {DEFAULT_HOST}")
parser.add_argument("--timeout", type=float, default=300.0, help="单张图片最长等待秒数")
parser.add_argument("--json", action="store_true", help="打印完整 JSON 响应")
parser.add_argument("--quiet", action="store_true", help="不打印轮询进度")
parser.add_argument("--health", action="store_true", help="只做健康检查")
parser.add_argument(
"--min-confidence",
type=float,
default=0.0,
help="只返回置信度不低于该值的片段(服务端过滤),默认 0 表示全要",
)
args = parser.parse_args()
host = args.host.rstrip("/")
# 先校验参数再探活:参数写错时不该因为连不上服务而报出误导性的错误。
if not args.images and not args.health:
parser.error("请至少给一张图片路径(或用 --health 只探活)")
try:
with urllib.request.urlopen(f"{host}/healthz", timeout=10) as response:
# flush:stdout 重定向到文件/管道时是块缓冲的,不刷的话这条会跑到
# 后面 stderr 的错误信息之后,看起来像是顺序错乱。
print(f"服务 {host} 正常:{json.loads(response.read().decode('utf-8'))}", flush=True)
except urllib.error.HTTPError as exc:
print(f"服务 {host} 响应异常:HTTP {exc.code}", file=sys.stderr)
return 1
except urllib.error.URLError as exc:
print(f"连不上服务 {host}:{exc.reason}", file=sys.stderr)
return 1
if args.health:
return 0
failed = sum(0 if process_one(host, path, args) else 1 for path in args.images)
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())