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>
This commit is contained in:
zimoyin
2026-10-14 12:15:39 +08:00
parent 0a299dec18
commit ec6b9c7ae3
7 changed files with 162 additions and 32 deletions
+2
View File
@@ -0,0 +1,2 @@
*.bat text eol=crlf
*.sh text eol=lf
+21 -6
View File
@@ -933,17 +933,32 @@ extract_include_empty: true
### 命令行客户端
不想记接口细节就用 `scripts/api_client.py`,它只用标准库,不依赖 requests,可直接拷到别的机器上跑:
不想记接口细节就用现成的客户端,它只用标准库(不依赖 requests),可直接拷到别的机器上跑:
```bat
rem Windows(也可以直接把图片拖到 bat 上)
scripts\api-client.bat 图片.png
scripts\api-client.bat 图片.png --min-confidence 0.6
scripts\api-client.bat --health
```
```bash
# 服务默认在 http://127.0.0.1:8000,可用 --host 指定别的地址
# Linux / 源码环境,等价
./scripts/api-client.sh 图片.png
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 # 只要置信度 >= 0.6 的片段
python scripts/api_client.py 图片.png --json # 打印原始 JSON 响应
python scripts/api_client.py --health # 只探活
```
常用参数(服务默认在 `http://127.0.0.1:8000`):
| 参数 | 说明 |
| --- | --- |
| `图片1 图片2 …` | 要识别的图片,可给多个,依次处理 |
| `--host URL` | 换服务地址,例如 `--host http://192.168.1.10:8000` |
| `--min-confidence 0.6` | 只返回置信度 ≥ 0.6 的片段(服务端过滤,实测 0.999 时 34 段 → 2 段) |
| `--json` | 打印完整 JSON 响应 |
| `--quiet` | 不打印轮询进度 |
| `--health` | 只探活 |
输出示例:
```text
+38
View File
@@ -0,0 +1,38 @@
@echo off
rem 命令行调用 OCR 接口:上传图片 -> 轮询 -> 打印识别文本与抽取字段。
rem
rem 用法(也可以直接把图片拖到这个 bat 上):
rem scripts\api-client.bat 图片.png
rem scripts\api-client.bat 图片.png --min-confidence 0.6
rem scripts\api-client.bat 图片.png --host http://192.168.1.10:8000
rem scripts\api-client.bat --health
rem
rem 服务默认在 http://127.0.0.1:8000。完整参数见 scripts\api_client.py --help
rem
rem 两个容易踩的点,改动前先看:
rem 1. 本文件必须保持 CRLF 换行。实测 LF 换行的 bat 会让 cmd 解析挂住
rem (同一份内容 CRLF 正常、LF 无输出且不退出)。.gitattributes 已钉死 eol=crlf。
rem 2. 退出码不要写成 `if ... ( ... exit /b %errorlevel% )` 这种括号块:
rem 块里的 %errorlevel% 是**解析时**展开的,拿到的是 python 跑之前的值,
rem 会把失败吞成成功。所以下面用 goto 而不是括号块。
setlocal
cd /d "%~dp0.."
rem 优先用 .venv 里的解释器:不经过 uv,也就不会触发环境同步。
rem (uv run 会按 pyproject.toml 同步环境,而 paddle 不在依赖里,会被整个移除)
if not exist ".venv\Scripts\python.exe" goto try_system_python
".venv\Scripts\python.exe" "scripts\api_client.py" %*
exit /b %errorlevel%
:try_system_python
rem 退回系统 Python:api_client.py 只用标准库,任何 Python 3.8+ 都能跑,
rem 也就是说这台机器只装 Python、不装本项目依赖也能当客户端用。
where python >nul 2>nul
if errorlevel 1 goto no_python
python "scripts\api_client.py" %*
exit /b %errorlevel%
:no_python
echo [错误] 找不到 Python 解释器。
echo 请先运行 scripts\switch_env.py --cpu 建好 .venv,或安装 Python 3.8+。
exit /b 1
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# 命令行调用 OCR 接口:上传图片 -> 轮询 -> 打印识别文本与抽取字段。
#
# 用法:
# ./scripts/api-client.sh 图片.png
# ./scripts/api-client.sh 图片.png --min-confidence 0.6
# ./scripts/api-client.sh 图片.png --host http://192.168.1.10:8000
# ./scripts/api-client.sh --health
#
# 服务默认在 http://127.0.0.1:8000。完整参数见 scripts/api_client.py --help
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")/.."
# 优先用 .venv 里的解释器:不经过 uv,也就不会触发环境同步。
# (uv run 会按 pyproject.toml 同步环境,而 paddle 不在依赖里,会被整个移除)
if [[ -x .venv/bin/python ]]; then
exec .venv/bin/python scripts/api_client.py "$@"
fi
# 退回系统 Python:api_client.py 只用标准库,任何 Python 3.8+ 都能跑。
if command -v python3 >/dev/null 2>&1; then
exec python3 scripts/api_client.py "$@"
fi
printf '%s\n' '[错误] 找不到 Python 解释器。请先运行 scripts/switch_env.py --cpu 建好 .venv,或安装 Python 3.8+。' >&2
exit 1
+4 -2
View File
@@ -114,7 +114,7 @@ def print_result(data: dict, show_json: bool) -> None:
def process_one(host: str, image_path: Path, args: argparse.Namespace) -> bool:
print(f"[{image_path.name}]")
print(f"[{image_path.name}]", flush=True)
if not image_path.is_file():
print(f" 文件不存在:{image_path}", file=sys.stderr)
return False
@@ -170,7 +170,9 @@ def main() -> int:
try:
with urllib.request.urlopen(f"{host}/healthz", timeout=10) as response:
print(f"服务 {host} 正常:{json.loads(response.read().decode('utf-8'))}")
# 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
+39 -24
View File
@@ -1,32 +1,47 @@
@echo off
rem 启动 OCR 服务,按下面的顺序找可执行的东西,找到就跑:
rem 1. 发布包 dist\ocr-server\ocr-server.exe (CPU 版)
rem 2. 发布包 dist\ocr-server-gpu\ocr-server-gpu.exe (GPU 版,device: auto 自动选卡)
rem 3. 源码环境 .venv\Scripts\ocr-server.exe
rem 4. uv run --no-sync ocr-server
rem
rem 两个容易踩的点,改动前先看:
rem 1. 本文件必须保持 CRLF 换行。实测 LF 换行的 bat 会让 cmd 解析挂住。
rem .gitattributes 已钉死 eol=crlf。
rem 2. 退出码不要写成 `if exist ... ( ... exit /b %errorlevel% )`:
rem 括号块里的 %errorlevel% 是**解析时**展开的,拿到的是启动程序之前的值,
rem 会把启动失败吞成成功。所以下面用 goto 而不是括号块。
setlocal
cd /d "%~dp0.."
rem 优先跑发布包:CPU 版 dist\ocr-server,GPU 版 dist\ocr-server-gpu。
rem 两个都存在时用 CPU 版(GPU 包只有装了 GPU 版 paddle 的机器才能用,见 README)。
rem 想直接跑 GPU 包就写全路径:dist\ocr-server-gpu\ocr-server-gpu.exe
if exist "dist\ocr-server\ocr-server.exe" (
"dist\ocr-server\ocr-server.exe"
exit /b %errorlevel%
)
if exist "dist\ocr-server-gpu\ocr-server-gpu.exe" (
"dist\ocr-server-gpu\ocr-server-gpu.exe"
exit /b %errorlevel%
)
if exist "dist\ocr-server\ocr-server.exe" goto run_cpu_package
if exist "dist\ocr-server-gpu\ocr-server-gpu.exe" goto run_gpu_package
if exist ".venv\Scripts\ocr-server.exe" goto run_venv
goto run_uv
rem 优先直接跑 .venv 里的入口脚本:直接执行不会触发 uv 的环境同步。
rem 必须这样做的原因:uv run 会先按 pyproject.toml 同步环境,而 paddle 不在依赖里,
rem 同步会把它整个移除(实测)。入口脚本名固定是 ocr-server,与变体无关。
if exist ".venv\Scripts\ocr-server.exe" (
".venv\Scripts\ocr-server.exe"
exit /b %errorlevel%
)
:run_cpu_package
"dist\ocr-server\ocr-server.exe"
exit /b %errorlevel%
:run_gpu_package
"dist\ocr-server-gpu\ocr-server-gpu.exe"
exit /b %errorlevel%
:run_venv
rem 直接跑 .venv 里的入口脚本:不经过 uv,也就不会触发环境同步
rem (uv run 会按 pyproject.toml 同步环境,而 paddle 不在依赖里,会被整个移除)。
rem 入口脚本名固定是 ocr-server,与 CPU/GPU 变体无关。
".venv\Scripts\ocr-server.exe"
exit /b %errorlevel%
:run_uv
where uv >nul 2>nul
if errorlevel 1 (
echo 未找到发布包,也未安装 uv。请先运行 scripts\package-windows.ps1 或 scripts/switch_env.py --cpu。
exit /b 1
)
rem --no-sync 是必须的,理由同上。环境尚未建好时,请先运行一次 scripts/switch_env.py --cpu。
if errorlevel 1 goto no_launcher
rem --no-sync 是必须的,理由同上。环境尚未建好时先跑 scripts\switch_env.py --cpu。
uv run --no-sync ocr-server
exit /b %errorlevel%
:no_launcher
echo [错误] 没找到可启动的东西:既没有 dist 下的发布包,也没有 .venv,uv 也没装。
echo 请先运行 scripts\switch_env.py --cpu(源码方式),或 scripts\package-windows.ps1(打包方式)。
exit /b 1
+32
View File
@@ -1,15 +1,19 @@
"""打包辅助脚本的回归测试(config 改写与 paddle 变体探测)。"""
import os
import subprocess
import sys
from pathlib import Path
import pytest
PROJECT_ROOT = Path(__file__).resolve().parents[1]
PREPARE_CONFIG = PROJECT_ROOT / "scripts" / "prepare_release_config.py"
PADDLE_ENV = PROJECT_ROOT / "scripts" / "paddle_env.py"
INSTALL_PADDLE = PROJECT_ROOT / "scripts" / "install_paddle.py"
SWITCH_ENV = PROJECT_ROOT / "scripts" / "switch_env.py"
API_CLIENT = PROJECT_ROOT / "scripts" / "api_client.py"
API_CLIENT_BAT = PROJECT_ROOT / "scripts" / "api-client.bat"
SAMPLE = """\
# 中文注释必须原样保留
@@ -102,6 +106,34 @@ def test_install_paddle_rejects_unknown_cuda_channel() -> None:
assert result.returncode == 2
def test_windows_batch_files_use_crlf() -> None:
""".bat 必须是 CRLF 换行。
实测:同一份内容,CRLF 的 bat 正常跑完;LF 的会让 cmd 解析挂住——无任何输出、
也不退出。这个坑很难查(看起来像服务或脚本卡死),所以用测试钉住。
"""
for bat in sorted((PROJECT_ROOT / "scripts").glob("*.bat")):
raw = bat.read_bytes()
assert b"\r\n" in raw, f"{bat.name} 没有 CRLF 换行"
assert raw.replace(b"\r\n", b"").count(b"\n") == 0, f"{bat.name} 里混有 LF 换行"
@pytest.mark.skipif(os.name != "nt", reason=".bat 只能在 Windows 上执行")
def test_api_client_bat_parses_and_runs() -> None:
"""bat 能被 cmd 正常解析并透传参数。带超时,坏掉时报失败而不是把测试卡死。"""
result = subprocess.run(
["cmd", "/c", str(API_CLIENT_BAT), "--help"],
capture_output=True,
text=True,
encoding="utf-8",
cwd=PROJECT_ROOT,
check=False,
timeout=60,
)
assert result.returncode == 0, result.stderr
assert "api_client.py" in result.stdout
def test_api_client_help_and_missing_args() -> None:
assert run_script(API_CLIENT, "--help").returncode == 0
# 不给图片又不带 --health:argparse 应该报错退出(2)