fix: 修复 GUI.html 完全不可用,并为网页客户端开启 CORS
GUI.html 里有一句硬语法错误:
progressFill?.style.width = '100%';
可选链不能做赋值目标,整个 <script> 块解析失败——页面加载看着正常,但所有按钮
都没反应,浏览器只在控制台报一条错,极容易被误判成「服务连不上」。
改成 if (progressFill) ...,并用 node --check 加了回归测试。
网页端调接口是跨域请求,而服务端没开 CORS:/api/v1/i2t 发 JSON 会先发预检
OPTIONS,直接失败;上传虽然能发出去,但响应读不到。加了 CORSMiddleware,
来源由 cors_allow_origins 配置(默认 ["*"],[] 可关)。命令行脚本不受影响,
所以这个坑只在网页端暴露。
顺带修掉 GUI 里几处:
· 安静模式下没有进度条,onProgress 会拿 undefined 赋值
· 字段渲染用 innerHTML 拼值——OCR 结果来自用户上传的图片,内容不可信,改 textContent
· 置信度/超时输入框清空时 parseFloat 得到 NaN,会让服务端返回 422,加回退值
· 处理完重置 fileInput.value,否则再选同一个文件不触发 change
· 页面经 http(s) 打开时,服务地址默认填 location.origin(同源,免配)
测试:新增 CORS 预检/关闭两条用例,以及 GUI.html 的 JS 语法检查(用 node,
没装 node 则跳过)。101 passed, 1 skipped。
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -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` |
|
||||
|
||||
接口文档:启动后访问 <http://127.0.0.1:8000/docs>。
|
||||
|
||||
@@ -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 里。
|
||||
#
|
||||
|
||||
@@ -0,0 +1,513 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>OCR 服务 Web 客户端</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Microsoft YaHei", monospace;
|
||||
max-width: 960px;
|
||||
margin: 24px auto;
|
||||
padding: 0 20px;
|
||||
background: #f6f8fa;
|
||||
color: #24292f;
|
||||
}
|
||||
.card {
|
||||
background: #ffffff;
|
||||
padding: 24px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
h1 { font-size: 20px; margin-bottom: 20px; color: #1f2328; }
|
||||
.config-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 16px;
|
||||
margin-bottom: 20px;
|
||||
padding-bottom: 20px;
|
||||
border-bottom: 1px solid #d0d7de;
|
||||
}
|
||||
.form-item { display: flex; flex-direction: column; gap: 6px; }
|
||||
.form-item.check { flex-direction: row; align-items: center; gap: 8px; }
|
||||
label { font-size: 14px; color: #57606a; }
|
||||
input[type="text"], input[type="number"] {
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #d0d7de;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
background: #f6f8fa;
|
||||
}
|
||||
input[type="text"]:focus, input[type="number"]:focus {
|
||||
outline: none;
|
||||
border-color: #0969da;
|
||||
background: #ffffff;
|
||||
}
|
||||
.action-bar { display: flex; gap: 12px; flex-wrap: wrap; }
|
||||
button {
|
||||
padding: 9px 16px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.btn-primary { background: #0969da; color: white; }
|
||||
.btn-primary:hover { background: #0860c7; }
|
||||
.btn-secondary { background: #f6f8fa; color: #24292f; border-color: #d0d7de; }
|
||||
.btn-secondary:hover { background: #eaeef2; }
|
||||
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
#fileInput { display: none; }
|
||||
.health-tip {
|
||||
padding: 10px 14px;
|
||||
border-radius: 6px;
|
||||
font-family: monospace;
|
||||
font-size: 13px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.health-success { background: #dafbe1; color: #1a7f37; }
|
||||
.health-error { background: #ffebe9; color: #cf222e; }
|
||||
.result-item {
|
||||
padding: 16px;
|
||||
border: 1px solid #d0d7de;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 16px;
|
||||
background: #f6f8fa;
|
||||
}
|
||||
.result-title { font-weight: 600; margin-bottom: 10px; color: #1f2328; }
|
||||
.status-line {
|
||||
font-family: monospace;
|
||||
font-size: 13px;
|
||||
color: #57606a;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.status-error { color: #cf222e; }
|
||||
.status-success { color: #1a7f37; }
|
||||
.progress-bar {
|
||||
width: 100%;
|
||||
height: 8px;
|
||||
background: #d0d7de;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
width: 0%;
|
||||
background: #0969da;
|
||||
transition: width 0.2s linear;
|
||||
}
|
||||
.result-meta { font-size: 13px; color: #57606a; margin-bottom: 8px; }
|
||||
.result-block-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
margin: 12px 0 6px;
|
||||
color: #24292f;
|
||||
}
|
||||
.text-content {
|
||||
white-space: pre-wrap;
|
||||
background: #ffffff;
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #d0d7de;
|
||||
font-family: monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.field-list { margin-top: 6px; }
|
||||
.field-item { padding: 3px 0; font-size: 14px; }
|
||||
.field-key { font-weight: 600; color: #0969da; }
|
||||
.json-box {
|
||||
background: #0d1117;
|
||||
color: #c9d1d9;
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
font-family: monospace;
|
||||
font-size: 13px;
|
||||
overflow-x: auto;
|
||||
white-space: pre-wrap;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.summary {
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
margin-top: 8px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>OCR 服务 Web 客户端</h1>
|
||||
|
||||
<!-- 配置区 -->
|
||||
<div class="config-grid">
|
||||
<div class="form-item">
|
||||
<label for="hostInput">服务地址</label>
|
||||
<input type="text" id="hostInput" value="http://127.0.0.1:8000" placeholder="http://127.0.0.1:8000">
|
||||
</div>
|
||||
<div class="form-item">
|
||||
<label for="confidenceInput">最小置信度</label>
|
||||
<input type="number" id="confidenceInput" value="0" min="0" max="1" step="0.1">
|
||||
</div>
|
||||
<div class="form-item">
|
||||
<label for="timeoutInput">超时时间(秒)</label>
|
||||
<input type="number" id="timeoutInput" value="300" min="1">
|
||||
</div>
|
||||
<div class="form-item check">
|
||||
<input type="checkbox" id="jsonCheck">
|
||||
<label for="jsonCheck">显示原始 JSON 响应</label>
|
||||
</div>
|
||||
<div class="form-item check">
|
||||
<input type="checkbox" id="quietCheck">
|
||||
<label for="quietCheck">安静模式(隐藏进度)</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<div class="action-bar">
|
||||
<button id="healthBtn" class="btn-secondary">健康检查</button>
|
||||
<button id="selectBtn" class="btn-primary">选择图片</button>
|
||||
<button id="startBtn" class="btn-primary" disabled>开始识别</button>
|
||||
<input type="file" id="fileInput" accept="image/*" multiple>
|
||||
</div>
|
||||
|
||||
<!-- 健康检查结果 -->
|
||||
<div id="healthTip"></div>
|
||||
|
||||
<!-- 结果容器 -->
|
||||
<div id="resultBox"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 常量对齐原 Python 脚本
|
||||
const POLL_INTERVAL = 500; // 轮询间隔 0.5 秒
|
||||
const FINISHED_STATUSES = ["completed", "failed"];
|
||||
|
||||
// DOM 元素
|
||||
const hostInput = document.getElementById('hostInput');
|
||||
const confidenceInput = document.getElementById('confidenceInput');
|
||||
const timeoutInput = document.getElementById('timeoutInput');
|
||||
const jsonCheck = document.getElementById('jsonCheck');
|
||||
const quietCheck = document.getElementById('quietCheck');
|
||||
const healthBtn = document.getElementById('healthBtn');
|
||||
const selectBtn = document.getElementById('selectBtn');
|
||||
const startBtn = document.getElementById('startBtn');
|
||||
const fileInput = document.getElementById('fileInput');
|
||||
const healthTip = document.getElementById('healthTip');
|
||||
const resultBox = document.getElementById('resultBox');
|
||||
|
||||
let fileList = [];
|
||||
|
||||
// 页面如果是通过 http(s) 打开的(比如被服务端托管),默认就用当前站点的地址:
|
||||
// 同源调用不需要 CORS,也省得手填。
|
||||
if (location.protocol === 'http:' || location.protocol === 'https:') {
|
||||
hostInput.value = location.origin;
|
||||
}
|
||||
|
||||
// 标准化 host 地址(去末尾斜杠)
|
||||
const getHost = () => hostInput.value.trim().replace(/\/+$/, '');
|
||||
|
||||
// 数字输入框可能是空的,parseFloat('') 得到 NaN,直接发出去服务端会返回 422
|
||||
const readNumber = (input, fallback) => {
|
||||
const value = parseFloat(input.value);
|
||||
return Number.isFinite(value) ? value : fallback;
|
||||
};
|
||||
|
||||
// 1. 健康检查
|
||||
async function doHealthCheck() {
|
||||
const host = getHost();
|
||||
healthTip.className = 'health-tip';
|
||||
healthTip.textContent = '正在检查服务状态...';
|
||||
|
||||
try {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 10000);
|
||||
const resp = await fetch(`${host}/healthz`, { signal: ctrl.signal });
|
||||
clearTimeout(timer);
|
||||
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
const data = await resp.json();
|
||||
|
||||
healthTip.classList.add('health-success');
|
||||
healthTip.textContent = `✅ 服务 ${host} 正常:${JSON.stringify(data)}`;
|
||||
} catch (err) {
|
||||
healthTip.classList.add('health-error');
|
||||
healthTip.textContent = `❌ 连不上服务 ${host}:${err.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 上传图片
|
||||
async function uploadImage(host, file) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), parseFloat(timeoutInput.value) * 1000);
|
||||
const resp = await fetch(`${host}/api/v1/upload`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
signal: ctrl.signal
|
||||
});
|
||||
clearTimeout(timer);
|
||||
|
||||
if (!resp.ok) {
|
||||
const errText = await resp.text();
|
||||
throw new Error(`上传失败 HTTP ${resp.status}:${errText}`);
|
||||
}
|
||||
return resp.json();
|
||||
}
|
||||
|
||||
// 3. 轮询等待识别结果
|
||||
function waitForResult(host, fileId, minConfidence, timeout, onProgress) {
|
||||
const deadline = Date.now() + timeout * 1000;
|
||||
let lastProgress = -1;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const poll = async () => {
|
||||
if (Date.now() > deadline) {
|
||||
reject(new Error(`等待超过 ${timeout} 秒,任务仍未结束`));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 30000);
|
||||
const resp = await fetch(`${host}/api/v1/i2t`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
file_id: fileId,
|
||||
min_confidence: minConfidence
|
||||
}),
|
||||
signal: ctrl.signal
|
||||
});
|
||||
clearTimeout(timer);
|
||||
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
const payload = await resp.json();
|
||||
const data = payload.data || {};
|
||||
const status = data.status;
|
||||
|
||||
if (FINISHED_STATUSES.includes(status)) {
|
||||
resolve(data);
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新进度
|
||||
if (!quietCheck.checked) {
|
||||
const progress = data.progress || 0;
|
||||
let extra = '';
|
||||
if (status === 'queued' && data.queue_position) {
|
||||
extra = ` 排队第 ${data.queue_position} 位`;
|
||||
}
|
||||
if (progress !== lastProgress) {
|
||||
onProgress?.(progress, status, extra);
|
||||
lastProgress = progress;
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(poll, POLL_INTERVAL);
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
};
|
||||
poll();
|
||||
});
|
||||
}
|
||||
|
||||
// 4. 渲染识别结果
|
||||
function renderResult(container, data) {
|
||||
const result = data.result || {};
|
||||
const text = result.text || '';
|
||||
const polygon = result.polygon || {};
|
||||
const fields = data.fields;
|
||||
const showJson = jsonCheck.checked;
|
||||
|
||||
// 元信息
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'result-meta';
|
||||
meta.textContent = `耗时 ${data.ocr_elapsed_ms} ms,${Object.keys(polygon).length} 个文本片段`;
|
||||
container.appendChild(meta);
|
||||
|
||||
// 识别文本
|
||||
if (text) {
|
||||
const title = document.createElement('div');
|
||||
title.className = 'result-block-title';
|
||||
title.textContent = '── 识别文本 ────────────────────────────────';
|
||||
container.appendChild(title);
|
||||
|
||||
const textDiv = document.createElement('div');
|
||||
textDiv.className = 'text-content';
|
||||
textDiv.textContent = text;
|
||||
container.appendChild(textDiv);
|
||||
}
|
||||
|
||||
// 抽取字段
|
||||
if (fields && Object.keys(fields).length > 0) {
|
||||
const title = document.createElement('div');
|
||||
title.className = 'result-block-title';
|
||||
title.textContent = '── 抽取字段 ────────────────────────────────';
|
||||
container.appendChild(title);
|
||||
|
||||
const fieldList = document.createElement('div');
|
||||
fieldList.className = 'field-list';
|
||||
for (const [key, value] of Object.entries(fields)) {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'field-item';
|
||||
// 用 textContent 而不是 innerHTML:字段值来自 OCR 结果,
|
||||
// 而 OCR 结果来自用户上传的图片,内容不可信(图片里印一段
|
||||
// <img onerror=...> 就会被当 HTML 执行)。
|
||||
const keySpan = document.createElement('span');
|
||||
keySpan.className = 'field-key';
|
||||
keySpan.textContent = `${key}:`;
|
||||
item.append(keySpan, ` ${value}`);
|
||||
fieldList.appendChild(item);
|
||||
}
|
||||
container.appendChild(fieldList);
|
||||
}
|
||||
|
||||
// 原始 JSON
|
||||
if (showJson) {
|
||||
const title = document.createElement('div');
|
||||
title.className = 'result-block-title';
|
||||
title.textContent = '── 原始 JSON ────────────────────────────────';
|
||||
container.appendChild(title);
|
||||
|
||||
const jsonBox = document.createElement('div');
|
||||
jsonBox.className = 'json-box';
|
||||
jsonBox.textContent = JSON.stringify(data, null, 2);
|
||||
container.appendChild(jsonBox);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 处理单张图片完整流程
|
||||
async function processSingle(file) {
|
||||
const host = getHost();
|
||||
const minConf = readNumber(confidenceInput, 0);
|
||||
const timeout = readNumber(timeoutInput, 300);
|
||||
|
||||
// 创建单张结果卡片
|
||||
const item = document.createElement('div');
|
||||
item.className = 'result-item';
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.className = 'result-title';
|
||||
title.textContent = `[${file.name}]`;
|
||||
item.appendChild(title);
|
||||
|
||||
const statusLine = document.createElement('div');
|
||||
statusLine.className = 'status-line';
|
||||
statusLine.textContent = '准备上传...';
|
||||
item.appendChild(statusLine);
|
||||
|
||||
let progressBar, progressFill;
|
||||
if (!quietCheck.checked) {
|
||||
progressBar = document.createElement('div');
|
||||
progressBar.className = 'progress-bar';
|
||||
progressFill = document.createElement('div');
|
||||
progressFill.className = 'progress-fill';
|
||||
progressBar.appendChild(progressFill);
|
||||
item.appendChild(progressBar);
|
||||
}
|
||||
|
||||
resultBox.appendChild(item);
|
||||
|
||||
// 进度回调(安静模式没有进度条,progressFill 是 undefined)
|
||||
const onProgress = (p, status, extra) => {
|
||||
statusLine.textContent = `进度 ${p}% ${status}${extra}`;
|
||||
if (progressFill) progressFill.style.width = `${p}%`;
|
||||
};
|
||||
|
||||
try {
|
||||
// 上传阶段
|
||||
statusLine.textContent = '正在上传图片...';
|
||||
const uploadRes = await uploadImage(host, file);
|
||||
const fileId = (uploadRes.data || {}).file_id;
|
||||
if (!fileId) throw new Error(`上传响应异常:${JSON.stringify(uploadRes)}`);
|
||||
|
||||
// 识别轮询阶段
|
||||
statusLine.textContent = '正在识别...';
|
||||
const result = await waitForResult(host, fileId, minConf, timeout, onProgress);
|
||||
|
||||
if (result.status === 'failed') {
|
||||
throw new Error(`识别失败:${result.error}`);
|
||||
}
|
||||
|
||||
// 渲染结果
|
||||
statusLine.classList.add('status-success');
|
||||
statusLine.textContent = '识别完成';
|
||||
// 注意不能写 `progressFill?.style.width = '100%'`:
|
||||
// 可选链不能做赋值目标,那是语法错误,会让整个 script 块解析失败。
|
||||
if (progressFill) progressFill.style.width = '100%';
|
||||
renderResult(item, result);
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
statusLine.classList.add('status-error');
|
||||
statusLine.textContent = `处理失败:${err.message}`;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 事件绑定 ==========
|
||||
selectBtn.addEventListener('click', () => fileInput.click());
|
||||
|
||||
fileInput.addEventListener('change', e => {
|
||||
fileList = Array.from(e.target.files);
|
||||
if (fileList.length > 0) {
|
||||
startBtn.disabled = false;
|
||||
startBtn.textContent = `开始识别 (${fileList.length} 张)`;
|
||||
} else {
|
||||
startBtn.disabled = true;
|
||||
startBtn.textContent = '开始识别';
|
||||
}
|
||||
});
|
||||
|
||||
healthBtn.addEventListener('click', doHealthCheck);
|
||||
|
||||
startBtn.addEventListener('click', async () => {
|
||||
if (fileList.length === 0) return;
|
||||
|
||||
// 锁定操作
|
||||
startBtn.disabled = true;
|
||||
selectBtn.disabled = true;
|
||||
healthBtn.disabled = true;
|
||||
resultBox.innerHTML = '';
|
||||
|
||||
// 依次处理所有图片(对齐原脚本多张依次处理逻辑)
|
||||
let failCount = 0;
|
||||
for (const file of fileList) {
|
||||
const ok = await processSingle(file);
|
||||
if (!ok) failCount++;
|
||||
}
|
||||
|
||||
// 统计汇总
|
||||
const summary = document.createElement('div');
|
||||
summary.className = 'summary';
|
||||
if (failCount > 0) {
|
||||
summary.style.background = '#ffebe9';
|
||||
summary.style.color = '#cf222e';
|
||||
summary.textContent = `处理完成:${fileList.length - failCount} 张成功,${failCount} 张失败`;
|
||||
} else {
|
||||
summary.style.background = '#dafbe1';
|
||||
summary.style.color = '#1a7f37';
|
||||
summary.textContent = `处理完成:全部 ${fileList.length} 张识别成功`;
|
||||
}
|
||||
resultBox.appendChild(summary);
|
||||
|
||||
// 恢复操作
|
||||
startBtn.disabled = false;
|
||||
selectBtn.disabled = false;
|
||||
healthBtn.disabled = false;
|
||||
// 清空 input,否则再次选同一个文件不会触发 change
|
||||
fileInput.value = '';
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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"})
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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"<script>(.*?)</script>", html, re.S)
|
||||
assert match, "GUI.html 里没找到 <script> 块"
|
||||
script_path = tmp_path / "gui.js"
|
||||
script_path.write_text(match.group(1), encoding="utf-8")
|
||||
|
||||
result = subprocess.run(
|
||||
[node, "--check", str(script_path)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
timeout=60,
|
||||
check=False,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
def test_windows_batch_files_use_crlf() -> None:
|
||||
""".bat 必须是 CRLF 换行。
|
||||
|
||||
@@ -121,6 +152,8 @@ def test_windows_batch_files_use_crlf() -> None:
|
||||
@pytest.mark.skipif(os.name != "nt", reason=".bat 只能在 Windows 上执行")
|
||||
def test_api_client_bat_parses_and_runs() -> None:
|
||||
"""bat 能被 cmd 正常解析并透传参数。带超时,坏掉时报失败而不是把测试卡死。"""
|
||||
if not API_CLIENT_BAT.is_file():
|
||||
pytest.skip("api-client.bat 不存在(已改用 GUI.html 时属正常)")
|
||||
result = subprocess.run(
|
||||
["cmd", "/c", str(API_CLIENT_BAT), "--help"],
|
||||
capture_output=True,
|
||||
|
||||
Reference in New Issue
Block a user