captcha / index.html
freexiaochuan's picture
Upload index.html
9848dea verified
Raw History Blame Contribute Delete
32.7 kB
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Captcha Recognition</title>
<!-- ONNX Runtime Web -->
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.29.0/dist/ort.min.js"></script>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 30px;
background: #f5f5f5;
font-family: Arial, Helvetica, sans-serif;
}
.container {
width: 900px;
max-width: 100%;
margin: 0 auto;
background: white;
border-radius: 12px;
padding: 30px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}
h1 {
margin-top: 0;
margin-bottom: 25px;
text-align: center;
}
.section {
margin-bottom: 25px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-bottom: 12px;
}
.upload-area {
border: 2px dashed #bbb;
border-radius: 10px;
padding: 35px;
text-align: center;
cursor: pointer;
transition: 0.2s;
}
.upload-area:hover {
border-color: #666;
background: #fafafa;
}
.upload-area.dragover {
border-color: #333;
background: #f0f0f0;
}
#fileInput {
display: none;
}
.preview-container {
display: flex;
flex-wrap: wrap;
gap: 30px;
align-items: flex-start;
}
.preview-box {
flex: 1;
min-width: 280px;
}
.preview-box h3 {
margin-top: 0;
margin-bottom: 10px;
}
canvas {
display: block;
max-width: 100%;
height: auto;
border: 1px solid #ddd;
background: white;
image-rendering: auto;
}
#originalCanvas {
width: 100%;
max-height: 300px;
object-fit: contain;
}
/*
* 预处理后的图片实际是 128x32。
* 为了方便肉眼观察,这里放大显示。
*/
#processedCanvas {
width: 512px;
max-width: 100%;
image-rendering: pixelated;
}
.button-row {
display: flex;
gap: 10px;
margin-top: 20px;
}
button {
border: none;
border-radius: 8px;
padding: 12px 25px;
font-size: 16px;
cursor: pointer;
}
#recognizeBtn {
background: #222;
color: white;
}
#recognizeBtn:hover {
background: #444;
}
#recognizeBtn:disabled {
background: #aaa;
cursor: not-allowed;
}
#clearBtn {
background: #eee;
color: #222;
}
#clearBtn:hover {
background: #ddd;
}
.result-box {
border: 1px solid #ddd;
border-radius: 10px;
padding: 20px;
background: #fafafa;
}
.result-label {
font-size: 14px;
color: #666;
margin-bottom: 8px;
}
#result {
font-size: 32px;
font-weight: bold;
letter-spacing: 4px;
word-break: break-all;
}
.status {
margin-top: 15px;
padding: 10px;
border-radius: 6px;
background: #f0f0f0;
color: #555;
font-family: monospace;
white-space: pre-wrap;
}
.debug {
margin-top: 20px;
padding: 15px;
background: #f7f7f7;
border-radius: 8px;
font-family: monospace;
font-size: 13px;
line-height: 1.6;
white-space: pre-wrap;
overflow-x: auto;
}
.model-status {
padding: 10px 15px;
border-radius: 6px;
background: #f0f0f0;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container">
<h1>验证码识别</h1>
<div class="model-status" id="modelStatus">
正在加载模型...
</div>
<div class="section">
<div class="section-title">
选择验证码图片
</div>
<div class="upload-area" id="uploadArea">
<div>
点击选择图片
</div>
<div style="margin-top: 8px; color: #888;">
或将图片拖拽到这里
</div>
</div>
<input
type="file"
id="fileInput"
accept="image/*"
>
</div>
<div class="section">
<div class="section-title">
图片预处理
</div>
<div class="preview-container">
<div class="preview-box">
<h3>原图</h3>
<canvas
id="originalCanvas"
></canvas>
</div>
<div class="preview-box">
<h3>
模型输入
<span style="font-size: 13px; color: #888;">
128 × 32
</span>
</h3>
<canvas
id="processedCanvas"
width="128"
height="32"
></canvas>
</div>
</div>
</div>
<div class="button-row">
<button
id="recognizeBtn"
disabled
>
识别
</button>
<button
id="clearBtn"
>
清空
</button>
</div>
<div class="section" style="margin-top: 25px;">
<div class="section-title">
识别结果
</div>
<div class="result-box">
<div class="result-label">
Prediction
</div>
<div id="result">
-
</div>
</div>
</div>
<div class="section">
<div class="section-title">
状态
</div>
<div
class="status"
id="status"
>
等待加载模型...
</div>
</div>
<div class="section">
<div class="section-title">
Debug
</div>
<div
class="debug"
id="debug"
>
-
</div>
</div>
</div>
<script>
// ============================================================
// 配置
// ============================================================
const MODEL_URL = 'https://hf-mirror.net/xiaochuan-dev/scu-captcha/resolve/main/model.onnx';
/*
* CTC:
*
* class 0 = blank
* class 1 ~ 20 = 字符
*/
const CHARSET = '2345678abcdefgmnpwxy';
const IMG_H = 32;
const IMG_W = 128;
const BLANK_IDX = 0;
// ============================================================
// DOM
// ============================================================
const fileInput = document.getElementById('fileInput');
const uploadArea = document.getElementById('uploadArea');
const originalCanvas =
document.getElementById('originalCanvas');
const processedCanvas =
document.getElementById('processedCanvas');
const recognizeBtn =
document.getElementById('recognizeBtn');
const clearBtn =
document.getElementById('clearBtn');
const resultElement =
document.getElementById('result');
const statusElement =
document.getElementById('status');
const debugElement =
document.getElementById('debug');
const modelStatus =
document.getElementById('modelStatus');
// ============================================================
// 全局变量
// ============================================================
let session = null;
let currentImage = null;
// ============================================================
// ONNX Runtime 初始化
// ============================================================
ort.env.wasm.numThreads = 1;
ort.env.wasm.simd = true;
async function loadModel() {
try {
statusElement.textContent =
'正在加载 ONNX 模型...';
modelStatus.textContent =
'正在加载模型...';
session = await ort.InferenceSession.create(
MODEL_URL,
{
executionProviders: ['webgpu', 'wasm'],
graphOptimizationLevel: 'all'
}
);
modelStatus.textContent =
'模型加载成功';
statusElement.textContent =
'模型加载成功,可以选择验证码图片。';
debugElement.textContent =
'Model loaded successfully\n\n' +
'Input:\n' +
JSON.stringify(
session.inputNames
) +
'\n\nOutput:\n' +
JSON.stringify(
session.outputNames
);
if (currentImage) {
recognizeBtn.disabled = false;
}
} catch (error) {
console.error(error);
modelStatus.textContent =
'模型加载失败';
statusElement.textContent =
'模型加载失败:\n' +
error.message;
debugElement.textContent =
error.stack || error.toString();
}
}
// ============================================================
// 文件选择
// ============================================================
uploadArea.addEventListener(
'click',
() => {
fileInput.click();
}
);
fileInput.addEventListener(
'change',
event => {
const file =
event.target.files[0];
if (file) {
loadImage(file);
}
}
);
// ============================================================
// 拖拽
// ============================================================
uploadArea.addEventListener(
'dragover',
event => {
event.preventDefault();
uploadArea.classList.add(
'dragover'
);
}
);
uploadArea.addEventListener(
'dragleave',
() => {
uploadArea.classList.remove(
'dragover'
);
}
);
uploadArea.addEventListener(
'drop',
event => {
event.preventDefault();
uploadArea.classList.remove(
'dragover'
);
const file =
event.dataTransfer.files[0];
if (
file &&
file.type.startsWith('image/')
) {
loadImage(file);
}
}
);
// ============================================================
// 加载图片
// ============================================================
function loadImage(file) {
const reader =
new FileReader();
reader.onload = event => {
const img =
new Image();
img.onload = () => {
currentImage = img;
drawOriginalImage(img);
preprocessAndDraw(img);
resultElement.textContent = '-';
if (session) {
recognizeBtn.disabled = false;
}
statusElement.textContent =
`图片加载成功\n` +
`原始尺寸:${img.width} × ${img.height}`;
};
img.onerror = () => {
statusElement.textContent =
'图片加载失败';
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
}
// ============================================================
// 显示原图
// ============================================================
function drawOriginalImage(img) {
const canvas =
originalCanvas;
const ctx =
canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(
0,
0,
canvas.width,
canvas.height
);
ctx.drawImage(
img,
0,
0
);
}
// ============================================================
// Python:
//
// img.convert('L')
//
// resize_keep_ratio()
//
// thumbnail((128,32), LANCZOS)
//
// padding fill=255
//
// ============================================================
function preprocessImage(img) {
/*
* 第一步:
*
* 创建原始图片的 Canvas
*/
const sourceCanvas =
document.createElement('canvas');
sourceCanvas.width =
img.width;
sourceCanvas.height =
img.height;
const sourceCtx =
sourceCanvas.getContext('2d');
sourceCtx.drawImage(
img,
0,
0
);
const imageData =
sourceCtx.getImageData(
0,
0,
img.width,
img.height
);
const width =
img.width;
const height =
img.height;
/*
* 第二步:
*
* RGB -> grayscale
*
* 对应 PIL:
*
* convert('L')
*/
const gray =
new Uint8Array(
width * height
);
for (
let y = 0;
y < height;
y++
) {
for (
let x = 0;
x < width;
x++
) {
const idx =
(y * width + x) * 4;
const r =
imageData.data[idx];
const g =
imageData.data[idx + 1];
const b =
imageData.data[idx + 2];
/*
* PIL RGB -> L 使用的灰度转换
* 与常见 RGB 灰度公式非常接近。
*/
const value =
0.299 * r +
0.587 * g +
0.114 * b;
gray[
y * width + x
] = Math.round(value);
}
}
/*
* 第三步:
*
* PIL:
*
* img.thumbnail((128, 32))
*
* 保持宽高比
*/
const scale =
Math.min(
IMG_W / width,
IMG_H / height
);
const newW =
Math.max(
1,
Math.round(width * scale)
);
const newH =
Math.max(
1,
Math.round(height * scale)
);
/*
* 第四步:
*
* 创建 128x32 白色画布
*
* PIL:
*
* ImageOps.expand(..., fill=255)
*/
const output =
new Float32Array(
IMG_W * IMG_H
);
/*
* 白色 = 255 / 255 = 1
*/
output.fill(1.0);
/*
* 第五步:
*
* LANCZOS resize
*/
for (
let dy = 0;
dy < newH;
dy++
) {
for (
let dx = 0;
dx < newW;
dx++
) {
/*
* resize 后像素中心
* 映射到原图
*/
const srcX =
(dx + 0.5) / scale - 0.5;
const srcY =
(dy + 0.5) / scale - 0.5;
const value =
lanczosSample(
gray,
width,
height,
srcX,
srcY
);
/*
* Python ImageOps.expand:
*
* left = delta_w // 2
* top = delta_h // 2
*/
const offsetX =
Math.floor(
(IMG_W - newW) / 2
);
const offsetY =
Math.floor(
(IMG_H - newH) / 2
);
const dstX =
offsetX + dx;
const dstY =
offsetY + dy;
if (
dstX >= 0 &&
dstX < IMG_W &&
dstY >= 0 &&
dstY < IMG_H
) {
/*
* Python 训练时:
*
* uint8
* ->
* ConvertImageDtype(float32)
*
* 得到 0~1
*/
output[
dstY * IMG_W + dstX
] =
value / 255.0;
}
}
}
return output;
}
// ============================================================
// sinc
// ============================================================
function sinc(x) {
if (Math.abs(x) < 1e-12) {
return 1.0;
}
const p =
Math.PI * x;
return Math.sin(p) / p;
}
// ============================================================
// Lanczos
// ============================================================
function lanczos(
x,
a = 3
) {
x = Math.abs(x);
if (x >= a) {
return 0;
}
if (x < 1e-12) {
return 1;
}
return (
sinc(x) *
sinc(x / a)
);
}
// ============================================================
// Lanczos sampling
// ============================================================
function lanczosSample(
gray,
width,
height,
x,
y
) {
const a = 3;
let sum = 0;
let weightSum = 0;
const xStart =
Math.floor(x) - a + 1;
const xEnd =
Math.floor(x) + a;
const yStart =
Math.floor(y) - a + 1;
const yEnd =
Math.floor(y) + a;
for (
let iy = yStart;
iy <= yEnd;
iy++
) {
if (
iy < 0 ||
iy >= height
) {
continue;
}
const wy =
lanczos(
y - iy,
a
);
for (
let ix = xStart;
ix <= xEnd;
ix++
) {
if (
ix < 0 ||
ix >= width
) {
continue;
}
const wx =
lanczos(
x - ix,
a
);
const weight =
wx * wy;
sum +=
gray[
iy * width + ix
] * weight;
weightSum +=
weight;
}
}
if (
Math.abs(weightSum) < 1e-12
) {
return 255;
}
const value =
sum / weightSum;
return Math.max(
0,
Math.min(
255,
value
)
);
}
// ============================================================
// 绘制预处理后的图片
// ============================================================
function preprocessAndDraw(img) {
const data =
preprocessImage(img);
const canvas =
processedCanvas;
const ctx =
canvas.getContext('2d');
canvas.width =
IMG_W;
canvas.height =
IMG_H;
const outputImage =
ctx.createImageData(
IMG_W,
IMG_H
);
for (
let i = 0;
i < data.length;
i++
) {
/*
* 模型输入是:
*
* 0 = 黑
* 1 = 白
*/
const value =
Math.round(
data[i] * 255
);
outputImage.data[
i * 4
] = value;
outputImage.data[
i * 4 + 1
] = value;
outputImage.data[
i * 4 + 2
] = value;
outputImage.data[
i * 4 + 3
] = 255;
}
ctx.putImageData(
outputImage,
0,
0
);
}
// ============================================================
// CTC Decode
// ============================================================
function ctcDecode(
logits,
T,
numClasses,
blankIdx = 0
) {
let prev =
blankIdx;
const chars = [];
for (
let t = 0;
t < T;
t++
) {
let maxIdx = 0;
let maxVal = -Infinity;
for (
let c = 0;
c < numClasses;
c++
) {
const val =
logits[
t * numClasses + c
];
if (
val > maxVal
) {
maxVal = val;
maxIdx = c;
}
}
const p =
maxIdx;
/*
* CTC:
*
* 连续重复字符只保留一个
*
* blank 不输出
*/
if (
p !== prev &&
p !== blankIdx
) {
const charIdx =
p - 1;
if (
charIdx >= 0 &&
charIdx < CHARSET.length
) {
chars.push(
CHARSET[charIdx]
);
}
}
prev = p;
}
return chars.join('');
}
// ============================================================
// 获取每个 timestep 的预测 class
// ============================================================
function getPredictionDetails(
logits,
T,
numClasses
) {
const details = [];
for (
let t = 0;
t < T;
t++
) {
let maxIdx = 0;
let maxVal = -Infinity;
for (
let c = 0;
c < numClasses;
c++
) {
const value =
logits[
t * numClasses + c
];
if (
value > maxVal
) {
maxVal = value;
maxIdx = c;
}
}
let label;
if (
maxIdx === BLANK_IDX
) {
label = '<blank>';
} else {
const charIdx =
maxIdx - 1;
if (
charIdx >= 0 &&
charIdx < CHARSET.length
) {
label =
CHARSET[charIdx];
} else {
label =
`<class:${maxIdx}>`;
}
}
details.push({
t,
classIndex: maxIdx,
label,
logit: maxVal
});
}
return details;
}
// ============================================================
// 识别
// ============================================================
recognizeBtn.addEventListener(
'click',
recognize
);
async function recognize() {
if (!session) {
statusElement.textContent =
'模型还没有加载完成。';
return;
}
if (!currentImage) {
statusElement.textContent =
'请先选择图片。';
return;
}
try {
recognizeBtn.disabled = true;
statusElement.textContent =
'正在识别...';
/*
* 生成模型输入
*/
const inputData =
preprocessImage(
currentImage
);
/*
* ONNX:
*
* [1, 1, 32, 128]
*/
const inputTensor =
new ort.Tensor(
'float32',
inputData,
[
1,
1,
IMG_H,
IMG_W
]
);
/*
* 推理
*/
const results =
await session.run({
input: inputTensor
});
const outputTensor =
results.output;
const dims =
outputTensor.dims;
/*
* 应该是:
*
* [1, 32, 21]
*/
const batchSize =
dims[0];
const T =
dims[1];
const numClasses =
dims[2];
const logits =
outputTensor.data;
/*
* 当前 batch 必须为 1
*/
if (
batchSize !== 1
) {
throw new Error(
`Unexpected batch size: ${batchSize}`
);
}
/*
* CTC Decode
*/
const prediction =
ctcDecode(
logits,
T,
numClasses,
BLANK_IDX
);
resultElement.textContent =
prediction || '(空)';
/*
* Debug 信息
*/
const details =
getPredictionDetails(
logits,
T,
numClasses
);
let debugText = '';
debugText +=
`Input shape: [1, 1, ${IMG_H}, ${IMG_W}]\n`;
debugText +=
`Output shape: [${batchSize}, ${T}, ${numClasses}]\n`;
debugText +=
`Charset: ${CHARSET}\n`;
debugText +=
`Blank index: ${BLANK_IDX}\n`;
debugText +=
`Prediction: ${prediction}\n\n`;
debugText +=
'CTC timesteps:\n';
for (
const item of details
) {
debugText +=
`t=${String(item.t).padStart(2, '0')} ` +
`class=${String(item.classIndex).padStart(2, '0')} ` +
`label=${item.label} ` +
`logit=${item.logit.toFixed(4)}\n`;
}
debugElement.textContent =
debugText;
statusElement.textContent =
'识别完成。';
} catch (error) {
console.error(error);
statusElement.textContent =
'识别失败:\n' +
error.message;
debugElement.textContent =
error.stack ||
error.toString();
} finally {
recognizeBtn.disabled = false;
}
}
// ============================================================
// 清空
// ============================================================
clearBtn.addEventListener(
'click',
() => {
currentImage = null;
fileInput.value = '';
const originalCtx =
originalCanvas.getContext('2d');
originalCtx.clearRect(
0,
0,
originalCanvas.width,
originalCanvas.height
);
const processedCtx =
processedCanvas.getContext('2d');
processedCtx.clearRect(
0,
0,
IMG_W,
IMG_H
);
resultElement.textContent =
'-';
statusElement.textContent =
session
? '等待选择图片。'
: '等待模型加载。';
debugElement.textContent =
'-';
recognizeBtn.disabled =
true;
}
);
// ============================================================
// 页面加载时加载模型
// ============================================================
loadModel();
</script>
</body>
</html>
```