-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.html
379 lines (353 loc) · 12.4 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>批量发票图片识别导出 Excel</title>
<script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/blueimp-load-image@5.16.0/js/load-image.all.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/tesseract.js@4/dist/tesseract.min.js"></script>
<script src="https://cdn.sheetjs.com/xlsx-0.20.0/package/dist/xlsx.mini.min.js"></script>
<style>
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
#invoice-table thead {
position: sticky;
top: 0;
z-index: 1;
background-color: lightGray;
}
#invoice-table-container {
margin-top: 10px;
max-width: max-content;
max-height: 500px;
overflow: auto;
}
</style>
</head>
<body>
<input
type="file"
id="invoice-input"
accept="image/png, image/jpeg"
multiple
title="选择需要识别的发票图片"
/>
<button id="parse-btn" title="开始识别所有图片">识别</button>
<button id="export-btn" title="导出Excel的XLXS文件">导出Excel</button>
<button id="clear-btn" title="清除已经识别的数据">清除</button>
<button id="reset-btn" title="重启应用">重置</button>
<p id="progress-text"></p>
<div id="invoice-table-container">
<table id="invoice-table"></table>
</div>
<script>
async function initTesseract() {
globalThis.ocrWorker = await Tesseract.createWorker({
langPath:
"https://cdn.jsdelivr.net/gh/naptha/tessdata@gh-pages/4.0.0/",
//logger: (m) => console.log(m),
});
await ocrWorker.loadLanguage("chi_sim");
await ocrWorker.initialize("chi_sim");
}
async function init() {
console.debug("Initializing...");
globalThis.progressText = document.getElementById("progress-text");
updateProgressText("初始化中...");
globalThis.invoiceInput = document.getElementById("invoice-input");
globalThis.invoiceTable = document.getElementById("invoice-table");
globalThis.parseButton = document.getElementById("parse-btn");
globalThis.exportButton = document.getElementById("export-btn");
globalThis.clearButton = document.getElementById("clear-btn");
globalThis.resetButton = document.getElementById("reset-btn");
globalThis.resetButton.disabled = true;
globalThis.clearButton.disabled = true;
globalThis.invoiceInput.disabled = true;
globalThis.parseButton.disabled = true;
globalThis.exportButton.disabled = true;
await initTesseract();
updateProgressText("初始化完成!");
globalThis.invoiceInput.disabled = false;
globalThis.clearButton.disabled = false;
globalThis.resetButton.disabled = false;
console.debug("Initialized");
}
async function reset() {
// https://github.com/naptha/tesseract.js/blob/master/docs/faq.md#how-does-tesseractjs-download-and-keep-traineddata
const store = "keyval-store";
await globalThis.ocrWorker.terminate();
const del = window.indexedDB.deleteDatabase(store);
del.onerror = (e) => {
alert("重置失败");
};
del.onsuccess = (e) => {
alert("重置成功,即将刷新页面");
location.reload();
};
}
function parseInvoiceQRcodeData(canvas) {
const data = {};
try {
let ctx = canvas.getContext("2d");
let imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
let code = jsQR(imgData.data, canvas.width, canvas.height);
console.debug("Parsed QR code data: ", code);
let arrayData = code.data.split(",");
data.code = arrayData[2];
data.num = arrayData[3];
data.amount = arrayData[4];
data.date = arrayData[5];
data.check = arrayData[6];
return data;
} catch (e) {
console.error(e);
throw new Error("二维码识别失败");
}
}
async function parseInvoiceTextData(canvas) {
// TODO: support multi-regexp to capitable with accuracy problem of OCR
const AMOUNT_REGEX = /价\s*税\s*合\s*计.*?\D(\d+(?:\.\d{2})?)\n$/;
const data = {};
try {
const res = await globalThis.ocrWorker.recognize(canvas);
console.debug("Parsed text data: ", res);
const lines = res.data.lines;
// search lines in reverse order
for (let i = lines.length - 1; i >= 0; i--) {
const regRes = AMOUNT_REGEX.exec(lines[i].text);
if (regRes) {
data.amount = regRes[1];
break;
}
}
return data;
} catch (e) {
console.error(e);
throw new Error("文本识别失败");
}
}
async function parseImageInvoiceData(file) {
const data = {
qrCodeData: [],
textData: {},
status: 0,
msg: null,
};
try {
const img = await loadImage(file, { canvas: true });
const canvas = img.image;
data.qrCodeData = parseInvoiceQRcodeData(canvas);
data.textData = await parseInvoiceTextData(canvas);
// TODO: compare qrCodeData and textData to improve accuracy
data.status = 1;
} catch (e) {
console.error(e);
data.msg = e.message;
} finally {
return data;
}
}
async function parseInvoiceData(file) {
const { qrCodeData, textData, status, msg } =
await parseImageInvoiceData(file);
return {
code: qrCodeData.code,
num: qrCodeData.num,
date: qrCodeData.date,
amount: textData.amount,
status: status,
msg: msg,
};
}
async function renderTableRowData(rowData) {
const tr = document.createElement("tr");
const header = globalThis.invoiceTable.rows[0];
console.debug(`Rendering table row`, rowData);
Array.from(header.children).forEach((th) => {
let name = th.getAttribute("data-name");
let id = th.getAttribute("data-id");
let type = th.getAttribute("data-type");
let value = th.getAttribute("data-value") || rowData[id];
let format = th.getAttribute("data-format");
let td = document.createElement("td");
console.debug("Rendering table row column:", name, value);
type ? td.setAttribute("data-t", type) : null;
format ? td.setAttribute("data-z", format) : null;
td.textContent = value;
tr.appendChild(td);
});
globalThis.invoiceTable.appendChild(tr);
}
function clearTable() {
globalThis.invoiceTable.innerHTML = "";
}
async function renderTableHeader(headerData) {
const defaultHeaderData = [
{
name: "发票代码",
id: "code",
type: "s",
value: null,
format: null,
},
{
name: "发票号码",
id: "num",
type: "s",
value: null,
format: null,
},
{
name: "开票日期",
id: "date",
type: "s",
value: null,
format: null,
},
{
name: "价税合计",
id: "amount",
type: "n",
value: null,
format: null,
},
{
name: "文件名",
id: "file",
type: "s",
value: null,
format: null,
},
{
name: "状态",
id: "status",
type: "s",
value: null,
format: null,
},
{
name: "备注",
id: "msg",
type: "s",
value: null,
format: null,
},
];
headerData = headerData || defaultHeaderData;
clearTable();
console.debug("Rendering table header");
const thead = document.createElement("thead");
const tr = document.createElement("tr");
headerData.forEach((h, i) => {
console.debug("Rendering table header column:", h.name);
let th = document.createElement("th");
Object.entries(h).forEach(([k, v]) => {
v ? th.setAttribute(`data-${k}`, v) : null;
});
th.textContent = h.name;
tr.appendChild(th);
});
thead.appendChild(tr);
globalThis.invoiceTable.appendChild(thead);
}
function updateProgressText(text) {
globalThis.progressText.textContent = text;
}
async function parse() {
console.debug("Parsing...");
const invoiceFiles = globalThis.invoiceInput.files;
renderTableHeader();
for (let i = 0; i < invoiceFiles.length; i++) {
let f = invoiceFiles[i];
updateProgressText(
`正在识别第${i + 1}个图片..., 还剩下${
invoiceFiles.length - (i + 1)
}个`
);
console.debug(`Parsing ${f.name}`);
let data = await parseInvoiceData(f);
data["order"] = i + 1;
data["file"] = f.name;
renderTableRowData(data);
}
updateProgressText(`识别完成!共${invoiceFiles.length}个图片`);
console.debug("Parsed!");
}
function exportInvoiceXLSX() {
updateProgressText("正在导出...");
time = new Date()
.toISOString()
.split(".")[0]
.replaceAll("-", "")
.replaceAll(":", "")
.replace("T", "_");
fileName = `invoice_${time}.xlsx`;
console.debug("Exporting to XLSX", fileName);
let worksheet = XLSX.utils.table_to_book(
document.getElementById("invoice-table")
);
XLSX.writeFile(worksheet, `invoice_${time}.xlsx`);
updateProgressText(`已导出Excel文件:${fileName}`);
console.debug("Exported!");
}
function updateParseButtonState() {
if (globalThis.invoiceInput.files.length == 0) {
globalThis.parseButton.disabled = true;
} else {
globalThis.parseButton.disabled = false;
}
}
addEventListener("load", async (e) => {
await init();
globalThis.invoiceInput.addEventListener("change", (e) => {
updateParseButtonState();
updateProgressText(`已选择${e.target.files.length}张发票`);
});
globalThis.parseButton.addEventListener("click", async (e) => {
try {
e.target.disabled = true;
e.target.textContent = "识别中...";
globalThis.invoiceInput.disabled = true;
globalThis.clearButton.disabled = true;
globalThis.exportButton.disabled = true;
await parse();
globalThis.exportButton.disabled = false;
} finally {
e.target.textContent = "识别";
updateParseButtonState();
globalThis.clearButton.disabled = false;
globalThis.invoiceInput.disabled = false;
}
});
globalThis.exportButton.addEventListener("click", (e) => {
try {
e.target.disabled = true;
globalThis.invoiceInput.disabled = true;
globalThis.parseButton.disabled = true;
globalThis.clearButton.disabled = true;
exportInvoiceXLSX();
} finally {
e.target.disabled = false;
globalThis.parseButton.disabled = false;
globalThis.clearButton.disabled = false;
globalThis.invoiceInput.disabled = false;
}
});
globalThis.clearButton.addEventListener("click", (e) => {
clearTable();
globalThis.exportButton.disabled = true;
globalThis.invoiceInput.value = null;
globalThis.invoiceInput.dispatchEvent(new Event("change"));
});
globalThis.resetButton.addEventListener("click", async (e) => {
await reset();
});
});
</script>
</body>
</html>