Files
ocr-server/scripts/api_client.py
T
zimoyin 0a299dec18 feat: 新增命令行 API 客户端,修复发布配置改写的反斜杠 bug
scripts/api_client.py:完整走一遍 upload -> 轮询 i2t -> 打印识别文本与抽取字段。
只用标准库(不依赖 requests),可直接拷到别的机器上跑;支持多图、
--min-confidence(服务端过滤)、--json、--health。参数校验放在探活之前,
参数写错时不会因为连不上服务而报出误导性错误。

scripts/prepare_release_config.py:re.sub 的**替换串**里反斜杠是转义序列,
写 Windows 路径(model_dir=D:\...)必然抛 "bad escape \c"。改用函数式替换。

.gitignore 补 *.zip:打包产物压出来有数 GB,别误提交。

README:补命令行客户端用法、发布包共用项目 models 目录的做法。

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

189 lines
7.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.
"""调用 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}]")
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:
print(f"服务 {host} 正常:{json.loads(response.read().decode('utf-8'))}")
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())