From 37729981378d85e5148f996cfdf9a1c9201e5fe5 Mon Sep 17 00:00:00 2001 From: zimoyin <2556608754@qq.com> Date: Wed, 14 Oct 2026 12:31:44 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20GUI.html=20?= =?UTF-8?q?=E5=AE=8C=E5=85=A8=E4=B8=8D=E5=8F=AF=E7=94=A8=EF=BC=8C=E5=B9=B6?= =?UTF-8?q?=E4=B8=BA=E7=BD=91=E9=A1=B5=E5=AE=A2=E6=88=B7=E7=AB=AF=E5=BC=80?= =?UTF-8?q?=E5=90=AF=20CORS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GUI.html 里有一句硬语法错误: progressFill?.style.width = '100%'; 可选链不能做赋值目标,整个 + + 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 里没找到