privacy-redact 0.1.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +195 -0
- package/package.json +19 -7
- package/scripts/copy-assets.mjs +59 -0
- package/src/detect/barcodes.js +166 -0
- package/src/detect/faces.js +81 -0
- package/src/detect/ocr.js +92 -0
- package/src/detect/textRegions.js +241 -0
- package/src/fonts/crimson-pro-300.woff2 +0 -0
- package/src/fonts/crimson-pro-OFL.txt +93 -0
- package/src/fonts/ibm-plex-sans-300.woff2 +0 -0
- package/src/fonts/ibm-plex-sans-400.woff2 +0 -0
- package/src/fonts/ibm-plex-sans-OFL.txt +93 -0
- package/src/host/assets.js +81 -0
- package/src/index.js +13 -0
- package/src/io/exporter.js +62 -0
- package/src/io/loader.js +91 -0
- package/src/io/metadata.js +75 -0
- package/src/main.js +37 -0
- package/src/prefs/scan.js +90 -0
- package/src/render/effects.js +129 -0
- package/src/review/controller.js +840 -0
- package/src/review/element.js +96 -0
- package/src/review/react.js +38 -0
- package/src/review/review.css +566 -0
- package/src/review/template.js +123 -0
- package/src/style.css +748 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 privacy-redact contributors
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
191
|
+
|
|
192
|
+
----------------------------------------------------------------------
|
|
193
|
+
|
|
194
|
+
The first approach came from Hushshot (https://github.com/SYasJ/hushshot)
|
|
195
|
+
by SYasJ, copyright HushShot contributors, under the MIT license.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "privacy-redact",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Library for detecting private content, redacting it, and handling document metadata. Browser components cover OCR, faces, barcodes, and PDF pages.",
|
|
6
6
|
"exports": {
|
|
@@ -17,6 +17,14 @@
|
|
|
17
17
|
"./io/metadata": "./src/io/metadata.js"
|
|
18
18
|
},
|
|
19
19
|
"license": "Apache-2.0",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/gitcommitshow/privacy-redact.git"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/gitcommitshow/privacy-redact#readme",
|
|
25
|
+
"bugs": {
|
|
26
|
+
"url": "https://github.com/gitcommitshow/privacy-redact/issues"
|
|
27
|
+
},
|
|
20
28
|
"files": [
|
|
21
29
|
"src",
|
|
22
30
|
"scripts/copy-assets.mjs",
|
|
@@ -27,8 +35,12 @@
|
|
|
27
35
|
"react-dom": ">=18"
|
|
28
36
|
},
|
|
29
37
|
"peerDependenciesMeta": {
|
|
30
|
-
"react": {
|
|
31
|
-
|
|
38
|
+
"react": {
|
|
39
|
+
"optional": true
|
|
40
|
+
},
|
|
41
|
+
"react-dom": {
|
|
42
|
+
"optional": true
|
|
43
|
+
}
|
|
32
44
|
},
|
|
33
45
|
"scripts": {
|
|
34
46
|
"postinstall": "node scripts/copy-assets.mjs",
|
|
@@ -50,17 +62,17 @@
|
|
|
50
62
|
"jsbarcode": "^3.12.3",
|
|
51
63
|
"playwright": "^1.63.0",
|
|
52
64
|
"qrcode": "^1.5.4",
|
|
53
|
-
"vite": "^
|
|
65
|
+
"vite": "^8.3.2",
|
|
54
66
|
"wait-on": "^9.4.0"
|
|
55
67
|
},
|
|
56
68
|
"dependencies": {
|
|
57
69
|
"@tesseract.js-data/eng": "^1.0.0",
|
|
58
70
|
"@vladmandic/face-api": "^1.7.15",
|
|
59
|
-
"@zxing/library": "^0.
|
|
71
|
+
"@zxing/library": "^0.23.0",
|
|
60
72
|
"exifr": "^7.1.3",
|
|
61
73
|
"pdf-lib": "^1.17.1",
|
|
62
|
-
"pdfjs-dist": "^
|
|
63
|
-
"tesseract.js": "^
|
|
74
|
+
"pdfjs-dist": "^6.3.289",
|
|
75
|
+
"tesseract.js": "^7.0.0"
|
|
64
76
|
},
|
|
65
77
|
"keywords": [
|
|
66
78
|
"privacy",
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Copies the OCR engine, language data, face model and PDF.js fonts out of node_modules into
|
|
2
|
+
// public/vendor so the app is fully self-contained and never touches a CDN at runtime.
|
|
3
|
+
import { cpSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
8
|
+
/**
|
|
9
|
+
* Resolves `p` inside the closest node_modules, walking up from the package root.
|
|
10
|
+
* When this package is installed in another project, its dependencies are hoisted
|
|
11
|
+
* to the host's node_modules instead of living under the package itself.
|
|
12
|
+
* Falls back to the package-local path so the "missing" warning stays meaningful.
|
|
13
|
+
*/
|
|
14
|
+
function nm(p) {
|
|
15
|
+
let dir = root;
|
|
16
|
+
for (;;) {
|
|
17
|
+
const candidate = join(dir, 'node_modules', p);
|
|
18
|
+
if (existsSync(candidate)) return candidate;
|
|
19
|
+
const parent = dirname(dir);
|
|
20
|
+
if (parent === dir) return join(root, 'node_modules', p);
|
|
21
|
+
dir = parent;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const out = (p) => join(root, 'public', 'vendor', p);
|
|
25
|
+
|
|
26
|
+
function copy(src, dest) {
|
|
27
|
+
if (!existsSync(src)) { console.warn(`[assets] missing ${src} – did you run npm install?`); return; }
|
|
28
|
+
mkdirSync(dirname(dest), { recursive: true });
|
|
29
|
+
cpSync(src, dest, { recursive: true });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Tesseract OCR: worker + LSTM-only WASM cores (plain + SIMD) + English model
|
|
33
|
+
copy(nm('tesseract.js/dist/worker.min.js'), out('tesseract/worker.min.js'));
|
|
34
|
+
for (const f of ['tesseract-core-lstm.wasm.js', 'tesseract-core-simd-lstm.wasm.js']) {
|
|
35
|
+
copy(nm(`tesseract.js-core/${f}`), out(`tesseract/${f}`));
|
|
36
|
+
}
|
|
37
|
+
copy(nm('@tesseract.js-data/eng/4.0.0_best_int/eng.traineddata.gz'), out('tesseract/eng.traineddata.gz'));
|
|
38
|
+
|
|
39
|
+
// Face detection model (SSD MobileNet v1)
|
|
40
|
+
const faceModelDir = nm('@vladmandic/face-api/model');
|
|
41
|
+
if (existsSync(faceModelDir)) {
|
|
42
|
+
for (const f of readdirSync(faceModelDir).filter((n) => n.startsWith('ssd_mobilenetv1'))) {
|
|
43
|
+
copy(join(faceModelDir, f), out(`face-models/${f}`));
|
|
44
|
+
}
|
|
45
|
+
} else {
|
|
46
|
+
console.warn(`[assets] missing ${faceModelDir} - did you run npm install?`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// PDF.js fonts + CMaps (needed for PDFs that don't embed their fonts)
|
|
50
|
+
copy(nm('pdfjs-dist/standard_fonts'), out('pdfjs/standard_fonts'));
|
|
51
|
+
copy(nm('pdfjs-dist/cmaps'), out('pdfjs/cmaps'));
|
|
52
|
+
|
|
53
|
+
// Blend fonts (Crimson Pro, IBM Plex Sans) for static pages under public/ such as the wiki,
|
|
54
|
+
// which Vite does not process and so cannot resolve the font imports in src/style.css.
|
|
55
|
+
for (const f of ['crimson-pro-300.woff2', 'ibm-plex-sans-300.woff2', 'ibm-plex-sans-400.woff2']) {
|
|
56
|
+
copy(join(root, 'src', 'fonts', f), out(`fonts/${f}`));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
console.log('[assets] vendored offline assets ready in public/vendor');
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Barcode & QR detection. Uses the browser's native BarcodeDetector when available (Chrome on macOS/Android/ChromeOS),
|
|
3
|
+
* otherwise falls back to ZXing (pure JS). ZXing only reports scan-line points for 1D codes, so we estimate their
|
|
4
|
+
* full height from the image's stripe energy.
|
|
5
|
+
*/
|
|
6
|
+
import {
|
|
7
|
+
MultiFormatReader, BinaryBitmap, HybridBinarizer, RGBLuminanceSource,
|
|
8
|
+
DecodeHintType, BarcodeFormat,
|
|
9
|
+
} from '@zxing/library';
|
|
10
|
+
|
|
11
|
+
function grayscale(canvas) {
|
|
12
|
+
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
|
13
|
+
const { data, width, height } = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
14
|
+
const gray = new Uint8ClampedArray(width * height);
|
|
15
|
+
for (let i = 0, j = 0; j < gray.length; i += 4, j++) gray[j] = (data[i] * 77 + data[i + 1] * 150 + data[i + 2] * 29) >> 8;
|
|
16
|
+
return { gray, width, height };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function nativeDetect(canvas) {
|
|
20
|
+
if (!('BarcodeDetector' in window)) return null;
|
|
21
|
+
try {
|
|
22
|
+
const det = new window.BarcodeDetector();
|
|
23
|
+
const res = await det.detect(canvas);
|
|
24
|
+
return res.map((r) => {
|
|
25
|
+
const xs = r.cornerPoints.map((p) => p.x), ys = r.cornerPoints.map((p) => p.y);
|
|
26
|
+
const x = Math.min(...xs), y = Math.min(...ys);
|
|
27
|
+
return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y, confidence: 0.95 };
|
|
28
|
+
});
|
|
29
|
+
} catch { return null; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Grow a 1D scan line into a box by following rows/columns that still contain bar-like energy. */
|
|
33
|
+
function refineLinear(gray, W, H, p0, p1) {
|
|
34
|
+
const horizontal = Math.abs(p1.x - p0.x) >= Math.abs(p1.y - p0.y);
|
|
35
|
+
const a = horizontal ? Math.min(p0.x, p1.x) : Math.min(p0.y, p1.y);
|
|
36
|
+
const b = horizontal ? Math.max(p0.x, p1.x) : Math.max(p0.y, p1.y);
|
|
37
|
+
const mid = Math.round(horizontal ? (p0.y + p1.y) / 2 : (p0.x + p1.x) / 2);
|
|
38
|
+
const limit = horizontal ? H : W;
|
|
39
|
+
const energy = (k) => {
|
|
40
|
+
let e = 0;
|
|
41
|
+
for (let t = Math.max(1, Math.floor(a)); t < Math.min(horizontal ? W : H, Math.ceil(b)); t++) {
|
|
42
|
+
const i = horizontal ? k * W + t : t * W + k;
|
|
43
|
+
const j = horizontal ? i - 1 : i - W;
|
|
44
|
+
e += Math.abs(gray[i] - gray[j]);
|
|
45
|
+
}
|
|
46
|
+
return e;
|
|
47
|
+
};
|
|
48
|
+
const base = Math.max(1, energy(clampi(mid, 0, limit - 1)));
|
|
49
|
+
let lo = mid, hi = mid, miss = 0;
|
|
50
|
+
for (let k = mid; k >= 0; k--) { if (energy(k) > base * 0.35) { lo = k; miss = 0; } else if (++miss > 3) break; }
|
|
51
|
+
miss = 0;
|
|
52
|
+
for (let k = mid; k < limit; k++) { if (energy(k) > base * 0.35) { hi = k; miss = 0; } else if (++miss > 3) break; }
|
|
53
|
+
// A real 1D code looks (almost) the same on every row across its height; lines of text do not.
|
|
54
|
+
// Compare the binarised scan line with rows at 25% / 75% of the found height.
|
|
55
|
+
const sample = (k) => {
|
|
56
|
+
const v = [];
|
|
57
|
+
for (let t = Math.floor(a); t < Math.ceil(b); t++) v.push(gray[horizontal ? k * W + t : t * W + k]);
|
|
58
|
+
return v;
|
|
59
|
+
};
|
|
60
|
+
const midRow = sample(clampi(mid, 0, limit - 1));
|
|
61
|
+
const thr = (Math.min(...midRow) + Math.max(...midRow)) / 2;
|
|
62
|
+
let coherence = 0;
|
|
63
|
+
if (hi - lo >= 8) {
|
|
64
|
+
const rows = [0.25, 0.75].map((f) => sample(Math.round(lo + (hi - lo) * f)));
|
|
65
|
+
const agree = rows.map((r) => r.reduce((n, v, i) => n + ((v < thr) === (midRow[i] < thr) ? 1 : 0), 0) / r.length);
|
|
66
|
+
coherence = Math.min(...agree);
|
|
67
|
+
}
|
|
68
|
+
const quiet = (b - a) * 0.04 + 4;
|
|
69
|
+
// Human-readable digits are often printed under the bars: extend the box only if there is real ink there.
|
|
70
|
+
const maxCap = Math.ceil((hi - lo + 1) * 0.6);
|
|
71
|
+
let capEnd = hi;
|
|
72
|
+
for (let k = hi + 1; k <= Math.min(limit - 1, hi + maxCap); k++) if (energy(k) > base * 0.12) capEnd = k;
|
|
73
|
+
const cap = capEnd > hi ? capEnd - hi + 3 : 0;
|
|
74
|
+
return horizontal
|
|
75
|
+
? { x: a - quiet, y: lo, w: b - a + quiet * 2, h: hi - lo + 1 + cap, coherence }
|
|
76
|
+
: { x: lo, y: a - quiet, w: hi - lo + 1 + cap, h: b - a + quiet * 2, coherence };
|
|
77
|
+
}
|
|
78
|
+
const clampi = (v, a, b) => Math.max(a, Math.min(b, v));
|
|
79
|
+
|
|
80
|
+
function zxingPass(canvas) {
|
|
81
|
+
const { gray, width, height } = grayscale(canvas);
|
|
82
|
+
const hints = new Map();
|
|
83
|
+
hints.set(DecodeHintType.TRY_HARDER, true);
|
|
84
|
+
hints.set(DecodeHintType.POSSIBLE_FORMATS, [
|
|
85
|
+
BarcodeFormat.QR_CODE, BarcodeFormat.DATA_MATRIX, BarcodeFormat.AZTEC, BarcodeFormat.PDF_417,
|
|
86
|
+
BarcodeFormat.CODE_128, BarcodeFormat.CODE_39, BarcodeFormat.EAN_13, BarcodeFormat.EAN_8,
|
|
87
|
+
BarcodeFormat.UPC_A, BarcodeFormat.UPC_E, BarcodeFormat.ITF, BarcodeFormat.CODABAR,
|
|
88
|
+
]);
|
|
89
|
+
const reader = new MultiFormatReader();
|
|
90
|
+
reader.setHints(hints);
|
|
91
|
+
const found = [];
|
|
92
|
+
for (let iter = 0; iter < 8; iter++) {
|
|
93
|
+
let result;
|
|
94
|
+
try {
|
|
95
|
+
const src = new RGBLuminanceSource(gray, width, height);
|
|
96
|
+
result = reader.decodeWithState(new BinaryBitmap(new HybridBinarizer(src)));
|
|
97
|
+
} catch { break; }
|
|
98
|
+
const pts = result.getResultPoints().map((p) => ({ x: p.getX(), y: p.getY() }));
|
|
99
|
+
if (!pts.length) break;
|
|
100
|
+
let box;
|
|
101
|
+
if (pts.length >= 3 && result.getBarcodeFormat() !== BarcodeFormat.PDF_417) {
|
|
102
|
+
const [bl, tl, tr] = pts;
|
|
103
|
+
const br = { x: bl.x + tr.x - tl.x, y: bl.y + tr.y - tl.y };
|
|
104
|
+
const all = [bl, tl, tr, br];
|
|
105
|
+
const xs = all.map((p) => p.x), ys = all.map((p) => p.y);
|
|
106
|
+
const x = Math.min(...xs), y = Math.min(...ys);
|
|
107
|
+
const w = Math.max(...xs) - x, h = Math.max(...ys) - y;
|
|
108
|
+
const pad = Math.max(w, h) * 0.2 + 3;
|
|
109
|
+
box = { x: x - pad, y: y - pad, w: w + pad * 2, h: h + pad * 2 };
|
|
110
|
+
} else if (pts.length >= 2) {
|
|
111
|
+
box = refineLinear(gray, width, height, pts[0], pts[pts.length - 1]);
|
|
112
|
+
if (box.coherence < 0.85) {
|
|
113
|
+
console.debug('[privacy-redact] ignored a 1D decode that does not look like a barcode', BarcodeFormat[result.getBarcodeFormat()], box.coherence.toFixed(2));
|
|
114
|
+
box.reject = true;
|
|
115
|
+
}
|
|
116
|
+
} else {
|
|
117
|
+
box = { x: pts[0].x - 40, y: pts[0].y - 40, w: 80, h: 80 };
|
|
118
|
+
}
|
|
119
|
+
box.x = clampi(box.x, 0, width); box.y = clampi(box.y, 0, height);
|
|
120
|
+
box.w = Math.min(box.w, width - box.x); box.h = Math.min(box.h, height - box.y);
|
|
121
|
+
if (!box.reject) found.push({ x: box.x, y: box.y, w: box.w, h: box.h, confidence: 0.9 });
|
|
122
|
+
// blank the area so the next pass can find another code
|
|
123
|
+
const fill = 200;
|
|
124
|
+
for (let y = Math.floor(box.y); y < Math.min(height, Math.ceil(box.y + box.h)); y++) {
|
|
125
|
+
gray.fill(fill, y * width + Math.floor(box.x), y * width + Math.min(width, Math.ceil(box.x + box.w)));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return found;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const overlaps = (a, b) => {
|
|
132
|
+
const x0 = Math.max(a.x, b.x), y0 = Math.max(a.y, b.y);
|
|
133
|
+
const x1 = Math.min(a.x + a.w, b.x + b.w), y1 = Math.min(a.y + a.h, b.y + b.h);
|
|
134
|
+
const inter = Math.max(0, x1 - x0) * Math.max(0, y1 - y0);
|
|
135
|
+
return inter > 0.4 * Math.min(a.w * a.h, b.w * b.h);
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/** Soft / resampled codes (typical in screenshots) often only decode at a different scale, so try several. */
|
|
139
|
+
async function zxingDetect(canvas, onProgress) {
|
|
140
|
+
const all = [];
|
|
141
|
+
const scales = [1, 0.5, 0.7, 0.35, 1.5].filter((s) => s === 1 || (canvas.width * s >= 240 && canvas.height * s >= 240 && canvas.width * s <= 4000));
|
|
142
|
+
let i = 0;
|
|
143
|
+
for (const s of scales) {
|
|
144
|
+
let c = canvas;
|
|
145
|
+
if (s !== 1) {
|
|
146
|
+
c = document.createElement('canvas');
|
|
147
|
+
c.width = Math.round(canvas.width * s); c.height = Math.round(canvas.height * s);
|
|
148
|
+
const ctx = c.getContext('2d', { willReadFrequently: true });
|
|
149
|
+
ctx.imageSmoothingQuality = 'high';
|
|
150
|
+
ctx.drawImage(canvas, 0, 0, c.width, c.height);
|
|
151
|
+
}
|
|
152
|
+
for (const b of zxingPass(c)) {
|
|
153
|
+
const box = { x: b.x / s, y: b.y / s, w: b.w / s, h: b.h / s, confidence: b.confidence };
|
|
154
|
+
if (!all.some((o) => overlaps(o, box))) all.push(box);
|
|
155
|
+
}
|
|
156
|
+
onProgress?.(++i / scales.length);
|
|
157
|
+
await new Promise((r) => setTimeout(r)); // keep the UI responsive
|
|
158
|
+
}
|
|
159
|
+
return all;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export async function detectBarcodes(canvas, onProgress) {
|
|
163
|
+
const native = await nativeDetect(canvas);
|
|
164
|
+
if (native && native.length) return native;
|
|
165
|
+
return zxingDetect(canvas, onProgress);
|
|
166
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Face detection – SSD MobileNet v1 running locally via TensorFlow.js (bundled in @vladmandic/face-api).
|
|
3
|
+
* Large images are scanned in overlapping tiles too, so small faces in group photos are not missed.
|
|
4
|
+
*/
|
|
5
|
+
let libPromise = null;
|
|
6
|
+
|
|
7
|
+
async function getLib() {
|
|
8
|
+
if (!libPromise) {
|
|
9
|
+
libPromise = (async () => {
|
|
10
|
+
const faceapi = await import('@vladmandic/face-api/dist/face-api.esm.js');
|
|
11
|
+
// WebGL when the GPU allows it, plain CPU otherwise (never the WASM backend – it would need extra files).
|
|
12
|
+
let ok = false;
|
|
13
|
+
try { ok = await faceapi.tf.setBackend('webgl'); } catch { ok = false; }
|
|
14
|
+
if (!ok) await faceapi.tf.setBackend('cpu');
|
|
15
|
+
await faceapi.tf.ready();
|
|
16
|
+
await faceapi.nets.ssdMobilenetv1.loadFromUri(new URL(import.meta.env.BASE_URL + 'vendor/face-models', window.location.href).href);
|
|
17
|
+
return faceapi;
|
|
18
|
+
})();
|
|
19
|
+
}
|
|
20
|
+
return libPromise;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function iou(a, b) {
|
|
24
|
+
const x0 = Math.max(a.x, b.x), y0 = Math.max(a.y, b.y);
|
|
25
|
+
const x1 = Math.min(a.x + a.w, b.x + b.w), y1 = Math.min(a.y + a.h, b.y + b.h);
|
|
26
|
+
const inter = Math.max(0, x1 - x0) * Math.max(0, y1 - y0);
|
|
27
|
+
return inter / (a.w * a.h + b.w * b.h - inter || 1);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function nms(boxes, thr = 0.4) {
|
|
31
|
+
boxes.sort((a, b) => b.confidence - a.confidence);
|
|
32
|
+
const keep = [];
|
|
33
|
+
for (const b of boxes) {
|
|
34
|
+
if (!keep.some((k) => iou(k, b) > thr || contains(k, b) || contains(b, k))) keep.push(b);
|
|
35
|
+
}
|
|
36
|
+
return keep;
|
|
37
|
+
}
|
|
38
|
+
function contains(a, b) { // b mostly inside a
|
|
39
|
+
const x0 = Math.max(a.x, b.x), y0 = Math.max(a.y, b.y);
|
|
40
|
+
const x1 = Math.min(a.x + a.w, b.x + b.w), y1 = Math.min(a.y + a.h, b.y + b.h);
|
|
41
|
+
return Math.max(0, x1 - x0) * Math.max(0, y1 - y0) > 0.7 * b.w * b.h;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function detectFaces(canvas, onProgress, { minConfidence = 0.55 } = {}) {
|
|
45
|
+
const faceapi = await getLib();
|
|
46
|
+
const opts = new faceapi.SsdMobilenetv1Options({ minConfidence, maxResults: 40 });
|
|
47
|
+
const found = [];
|
|
48
|
+
const W = canvas.width, H = canvas.height;
|
|
49
|
+
|
|
50
|
+
const run = async (sx, sy, sw, sh) => {
|
|
51
|
+
// SSD-MobileNet squashes its input into a square, which distorts faces in wide/tall images and tanks the score.
|
|
52
|
+
// So every window is letterboxed onto a square canvas (top-left aligned, so coordinates map 1:1).
|
|
53
|
+
const side = Math.max(sw, sh);
|
|
54
|
+
const input = document.createElement('canvas');
|
|
55
|
+
input.width = side; input.height = side;
|
|
56
|
+
const ictx = input.getContext('2d');
|
|
57
|
+
ictx.fillStyle = '#808080';
|
|
58
|
+
ictx.fillRect(0, 0, side, side);
|
|
59
|
+
ictx.drawImage(canvas, sx, sy, sw, sh, 0, 0, sw, sh);
|
|
60
|
+
const dets = await faceapi.detectAllFaces(input, opts);
|
|
61
|
+
for (const d of dets) {
|
|
62
|
+
const b = d.box;
|
|
63
|
+
if (b.width < 14 || b.height < 14) continue;
|
|
64
|
+
found.push({ x: sx + b.x, y: sy + b.y, w: b.width, h: b.height, confidence: d.score });
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const windows = [[0, 0, W, H]];
|
|
69
|
+
const longest = Math.max(W, H);
|
|
70
|
+
if (longest > 640) {
|
|
71
|
+
// Small faces score much higher when a tile is scanned at higher effective resolution.
|
|
72
|
+
const n = longest > 2200 ? 3 : 2;
|
|
73
|
+
const tw = Math.round(W / (n - 0.4)), th = Math.round(H / (n - 0.4));
|
|
74
|
+
for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) {
|
|
75
|
+
windows.push([Math.round((i * (W - tw)) / (n - 1)), Math.round((j * (H - th)) / (n - 1)), tw, th]);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
let done = 0;
|
|
79
|
+
for (const w of windows) { await run(...w); onProgress?.(++done / windows.length); }
|
|
80
|
+
return nms(found);
|
|
81
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OCR via Tesseract.js – engine, WASM core and language data are all served locally from /vendor.
|
|
3
|
+
* Returns lines of words in the *original* canvas' pixel coordinates.
|
|
4
|
+
*/
|
|
5
|
+
import { createWorker } from 'tesseract.js';
|
|
6
|
+
|
|
7
|
+
let workerPromise = null;
|
|
8
|
+
let progressCb = null;
|
|
9
|
+
|
|
10
|
+
const abs = (p) => new URL(import.meta.env.BASE_URL + p, window.location.href).href;
|
|
11
|
+
|
|
12
|
+
function getWorker() {
|
|
13
|
+
if (!workerPromise) {
|
|
14
|
+
workerPromise = createWorker('eng', 1, {
|
|
15
|
+
workerPath: abs('vendor/tesseract/worker.min.js'),
|
|
16
|
+
corePath: abs('vendor/tesseract'),
|
|
17
|
+
langPath: abs('vendor/tesseract'),
|
|
18
|
+
gzip: true,
|
|
19
|
+
cacheMethod: 'none',
|
|
20
|
+
logger: (m) => { if (m.status === 'recognizing text' && progressCb) progressCb(m.progress); },
|
|
21
|
+
}).then(async (w) => {
|
|
22
|
+
await w.setParameters({ user_defined_dpi: '300' });
|
|
23
|
+
return w;
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
return workerPromise;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Mean luminance 0-255 sampled on a coarse grid. */
|
|
30
|
+
function meanLuma(canvas) {
|
|
31
|
+
const s = document.createElement('canvas');
|
|
32
|
+
s.width = 64; s.height = 64;
|
|
33
|
+
const c = s.getContext('2d', { willReadFrequently: true });
|
|
34
|
+
c.drawImage(canvas, 0, 0, 64, 64);
|
|
35
|
+
const d = c.getImageData(0, 0, 64, 64).data;
|
|
36
|
+
let sum = 0;
|
|
37
|
+
for (let i = 0; i < d.length; i += 4) sum += 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
|
|
38
|
+
return sum / (d.length / 4);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Scale small screenshots up (Tesseract likes ~30px tall text), huge scans down; invert dark themes. */
|
|
42
|
+
function prepare(canvas) {
|
|
43
|
+
const longest = Math.max(canvas.width, canvas.height);
|
|
44
|
+
let scale = 1;
|
|
45
|
+
if (longest < 1400) scale = Math.min(2.5, 2000 / longest);
|
|
46
|
+
else if (longest > 4200) scale = 4200 / longest;
|
|
47
|
+
const dark = meanLuma(canvas) < 110;
|
|
48
|
+
if (scale === 1 && !dark) return { image: canvas, scale };
|
|
49
|
+
const c = document.createElement('canvas');
|
|
50
|
+
c.width = Math.round(canvas.width * scale);
|
|
51
|
+
c.height = Math.round(canvas.height * scale);
|
|
52
|
+
const ctx = c.getContext('2d');
|
|
53
|
+
ctx.imageSmoothingQuality = 'high';
|
|
54
|
+
if (dark) ctx.filter = 'invert(1) grayscale(1)';
|
|
55
|
+
ctx.drawImage(canvas, 0, 0, c.width, c.height);
|
|
56
|
+
return { image: c, scale };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {HTMLCanvasElement} canvas
|
|
61
|
+
* @param {(p:number)=>void} [onProgress] 0..1
|
|
62
|
+
* @returns {Promise<{words:{text:string,confidence:number,bbox:{x0:number,y0:number,x1:number,y1:number}}[]}[]>}
|
|
63
|
+
*/
|
|
64
|
+
export async function recognizeLines(canvas, onProgress) {
|
|
65
|
+
const worker = await getWorker();
|
|
66
|
+
progressCb = onProgress || null;
|
|
67
|
+
const { image, scale } = prepare(canvas);
|
|
68
|
+
const { data } = await worker.recognize(image, {}, { blocks: true });
|
|
69
|
+
progressCb = null;
|
|
70
|
+
const lines = [];
|
|
71
|
+
for (const block of data.blocks || []) {
|
|
72
|
+
for (const para of block.paragraphs || []) {
|
|
73
|
+
for (const line of para.lines || []) {
|
|
74
|
+
const words = (line.words || [])
|
|
75
|
+
// Drop low-confidence garbage (e.g. "words" OCR hallucinates inside photos) – it would otherwise stretch
|
|
76
|
+
// redaction boxes. Anything containing a digit or "@" is kept, because that is what secrets look like.
|
|
77
|
+
.filter((w) => w.text && w.text.trim() && (w.confidence >= 45 || /[\d@]/.test(w.text)))
|
|
78
|
+
.map((w) => ({
|
|
79
|
+
text: w.text.trim(),
|
|
80
|
+
confidence: w.confidence,
|
|
81
|
+
bbox: { x0: w.bbox.x0 / scale, y0: w.bbox.y0 / scale, x1: w.bbox.x1 / scale, y1: w.bbox.y1 / scale },
|
|
82
|
+
}));
|
|
83
|
+
if (words.length) lines.push({ words });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return lines;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function disposeOcr() {
|
|
91
|
+
if (workerPromise) { const w = await workerPromise; await w.terminate(); workerPromise = null; }
|
|
92
|
+
}
|