diff --git a/README.md b/README.md index 9786cc6..1aea1d8 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,8 @@ ocr-server/ ├── scripts/install_paddle.py # 按显卡安装 CPU/GPU 版 paddlepaddle ├── scripts/download_models.py # 下载/补齐预置模型 ├── scripts/benchmark_ocr.py # 测量当前配置的 OCR 耗时与召回 -└── scripts/api_client.py # 命令行调用 OCR 接口 +├── scripts/api_client.py # 命令行调用 OCR 接口 +└── scripts/GUI.html # 网页客户端,浏览器直接打开 ``` ## 模型位置和下载策略 @@ -931,21 +932,23 @@ extract_include_empty: true 抽取发生在查询时(`/api/v1/i2t`),基于 `min_confidence` 过滤后的文本,因此改预设或调 `min_confidence` 不需要重新识别。`extract_fields` 留空(或删除该配置)即关闭此功能。 +### 网页客户端(GUI.html) + +`scripts/GUI.html` 是个纯前端的网页客户端:填服务地址、选图片、看进度和识别结果, +双击用浏览器打开即可,不需要装任何东西。 + +浏览器里调接口属于跨域请求,所以服务端默认开了 CORS(`cors_allow_origins: ["*"]`, +见「配置」一节)。关掉它网页客户端就用不了,命令行脚本不受影响。 + ### 命令行客户端 -不想记接口细节就用现成的客户端,它只用标准库(不依赖 requests),可直接拷到别的机器上跑: - -```bat -rem Windows(也可以直接把图片拖到 bat 上) -scripts\api-client.bat 图片.png -scripts\api-client.bat 图片.png --min-confidence 0.6 -scripts\api-client.bat --health -``` +不想记接口细节就用 `scripts/api_client.py`,它只用标准库(不依赖 requests), +可直接拷到别的机器上跑: ```bash -# Linux / 源码环境,等价 -./scripts/api-client.sh 图片.png python scripts/api_client.py 图片.png +python scripts/api_client.py 图片.png --min-confidence 0.6 +python scripts/api_client.py --health ``` 常用参数(服务默认在 `http://127.0.0.1:8000`): @@ -1061,6 +1064,7 @@ log_level: INFO | `use_tensorrt` | `false` | 是否启用 TensorRT;**只在 `device` 为 GPU 时生效** | | `precision` | `fp32` | `fp32` / `fp16`;`fp16` 只在 GPU 上生效 | | `enable_cinn` | `false` | 是否启用 CINN 编译器(面向国产加速卡);普通 CPU/GPU 保持 `false` | +| `cors_allow_origins` | `["*"]` | 允许跨域的来源,只影响网页客户端;`[]` 表示关闭 | | `log_level` | `INFO` | 日志级别:`DEBUG`、`INFO`、`WARNING`、`ERROR` | 接口文档:启动后访问 。 diff --git a/config.yaml b/config.yaml index 1f8e19c..ffa5468 100644 --- a/config.yaml +++ b/config.yaml @@ -150,6 +150,15 @@ mkldnn_cache_capacity: 10 # 日志级别:DEBUG / INFO / WARNING / ERROR log_level: INFO +# 允许跨域访问的来源(CORS)。只影响浏览器里的网页客户端, +# 命令行脚本和系统对接不受影响。 +# ["*"] 任意来源都可以调(默认)。scripts/GUI.html 双击打开就能用。 +# ["http://localhost:5173"] 只放行指定来源 +# [] 完全关闭 +# ⚠️ 服务默认只监听 127.0.0.1,风险有限;但如果把 host 改成 0.0.0.0 暴露到局域网, +# 建议这里收紧成具体来源,否则任意网页都能借用户的浏览器调这个接口。 +cors_allow_origins: ["*"] + # ── 字段提取预设 ────────────────────────────────────────────── # 识别完成后按键值抽取,结果放在响应的 data.fields 里。 # diff --git a/scripts/GUI.html b/scripts/GUI.html new file mode 100644 index 0000000..2cfdca3 --- /dev/null +++ b/scripts/GUI.html @@ -0,0 +1,513 @@ + + + + + + OCR 服务 Web 客户端 + + + +
+

OCR 服务 Web 客户端

+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + + + +
+ + +
+ + +
+
+ + + + diff --git a/scripts/api-client.bat b/scripts/api-client.bat deleted file mode 100644 index 826b4e8..0000000 --- a/scripts/api-client.bat +++ /dev/null @@ -1,38 +0,0 @@ -@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 diff --git a/scripts/api-client.sh b/scripts/api-client.sh deleted file mode 100644 index 6574859..0000000 --- a/scripts/api-client.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/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 diff --git a/src/ocr_server/app.py b/src/ocr_server/app.py index db068c2..77f6b4c 100644 --- a/src/ocr_server/app.py +++ b/src/ocr_server/app.py @@ -1,6 +1,7 @@ import logging from fastapi import FastAPI, File, HTTPException, UploadFile, status +from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from ocr_server.config import Settings @@ -27,6 +28,17 @@ def create_app(settings: Settings | None = None) -> FastAPI: tasks = OCRTaskQueue(create_ocr, worker_count=settings.ocr_workers) app = FastAPI(title="OCR Server", version="0.1.0") + # 浏览器里的页面(scripts/GUI.html 之类)从别的来源调这个接口时,没有这几个响应头 + # 就会被浏览器全部拦掉:/api/v1/i2t 发的是 JSON,还会先发一个预检 OPTIONS 直接失败。 + # 命令行客户端不受影响,所以这个问题只在网页端暴露。 + if settings.cors_allow_origins: + app.add_middleware( + CORSMiddleware, + allow_origins=settings.cors_allow_origins, + allow_methods=["*"], + allow_headers=["*"], + ) + @app.get("/healthz", response_model=ApiResponse, tags=["system"]) def healthz() -> ApiResponse: return ApiResponse(data={"status": "ok"}) diff --git a/src/ocr_server/config.py b/src/ocr_server/config.py index 68f9209..0b3aed4 100644 --- a/src/ocr_server/config.py +++ b/src/ocr_server/config.py @@ -140,6 +140,9 @@ class Settings(BaseModel): use_tensorrt: bool = False precision: Literal["fp32", "fp16"] = "fp32" enable_cinn: bool = False + # 允许跨域访问的来源。填 ["*"] 表示任意来源,[] 表示完全关闭 CORS。 + # 只影响浏览器里的网页客户端;命令行脚本、系统对接不受影响。 + cors_allow_origins: list[str] = Field(default_factory=lambda: ["*"]) extract_fields: list[FieldPreset] = Field(default_factory=list) extract_separators: list[str] = Field(default_factory=lambda: [":", ":"]) extract_include_empty: bool = False diff --git a/tests/test_api.py b/tests/test_api.py index 9891a5e..3cc62e9 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -34,6 +34,45 @@ def test_health() -> None: } +def test_cors_allows_browser_page_clients() -> None: + """网页客户端(scripts/GUI.html)从别的来源调接口时,没有 CORS 头浏览器会把响应全拦掉。 + + `/api/v1/i2t` 发的是 JSON,浏览器还会先发一个预检 OPTIONS,缺 CORS 直接失败。 + 命令行脚本不受影响,所以这个问题只在网页端暴露。 + """ + response = client().options( + "/api/v1/i2t", + headers={ + "Origin": "null", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "content-type", + }, + ) + assert response.status_code == 200 + assert response.headers["access-control-allow-origin"] == "*" + assert "POST" in response.headers["access-control-allow-methods"] + + # 实际请求也要带上这个头,否则浏览器读不到响应 + actual = client().post( + "/api/v1/i2t", json={"file_id": str(uuid4())}, headers={"Origin": "null"} + ) + assert actual.headers["access-control-allow-origin"] == "*" + + +def test_cors_can_be_disabled_with_empty_origins() -> None: + directory = TemporaryDirectory() + app = create_app( + Settings(upload_dir=Path(directory.name), cors_allow_origins=[]) + ) + test_client = TestClient(app) + test_client._ocr_test_directory = directory + + response = test_client.post( + "/api/v1/i2t", json={"file_id": str(uuid4())}, headers={"Origin": "null"} + ) + assert "access-control-allow-origin" not in response.headers + + def test_upload_and_missing_image() -> None: response = client().post( "/api/v1/upload", diff --git a/tests/test_release_helpers.py b/tests/test_release_helpers.py index 7cef3b8..f171969 100644 --- a/tests/test_release_helpers.py +++ b/tests/test_release_helpers.py @@ -1,6 +1,8 @@ """打包辅助脚本的回归测试(config 改写与 paddle 变体探测)。""" import os +import re +import shutil import subprocess import sys from pathlib import Path @@ -14,6 +16,7 @@ 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" +GUI_HTML = PROJECT_ROOT / "scripts" / "GUI.html" SAMPLE = """\ # 中文注释必须原样保留 @@ -106,6 +109,34 @@ def test_install_paddle_rejects_unknown_cuda_channel() -> None: assert result.returncode == 2 +def test_gui_html_javascript_parses(tmp_path: Path) -> None: + """GUI.html 里的 script 必须能通过 JS 语法检查。 + + 实测踩过:一句 `progressFill?.style.width = '100%'` 是语法错误(可选链不能做 + 赋值目标),整个 script 块解析失败——页面加载正常,但所有按钮都没反应, + 浏览器只在控制台报一条错,很容易被误判成「服务连不上」。 + """ + node = shutil.which("node") + if node is None: + pytest.skip("本机没有 node,跳过 JS 语法检查") + + html = GUI_HTML.read_text(encoding="utf-8") + match = re.search(r"", html, re.S) + assert match, "GUI.html 里没找到