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:
zimoyin
2026-10-14 12:31:44 +08:00
parent ec6b9c7ae3
commit 3772998137
9 changed files with 624 additions and 75 deletions
+513
View File
@@ -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>
-38
View File
@@ -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
-26
View File
@@ -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