privacy-redact 1.1.0 → 1.2.0

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.
@@ -0,0 +1,33 @@
1
+ /** Hindi: Devanagari labels, digits, and India place names for opt-in Hindi scans. */
2
+ export default {
3
+ schema: 1,
4
+ id: 'hi',
5
+ scripts: ['Devanagari'],
6
+ ocr: ['hin'],
7
+ digits: {
8
+ '०': '0', '१': '1', '२': '2', '३': '3', '४': '4',
9
+ '५': '5', '६': '6', '७': '7', '८': '8', '९': '9',
10
+ },
11
+ labelSuffixes: ['संख्या', 'नंबर', 'नं.', 'क्रमांक'],
12
+ labels: {
13
+ aadhaar: ['आधार'],
14
+ pan: ['पैन', 'स्थायी लेखा संख्या'],
15
+ phone: ['मोबाइल', 'मोबाईल', 'फ़ोन', 'फोन', 'दूरभाष', 'संपर्क'],
16
+ account: ['खाता'],
17
+ dob: ['जन्म तिथि', 'जन्मतिथि', 'जन्म की तारीख'],
18
+ },
19
+ postalLabels: ['पिन', 'पिन कोड', 'पिनकोड'],
20
+ addressCues: [
21
+ 'मकान', 'फ्लैट', 'गली', 'मार्ग', 'सेक्टर', 'नगर', 'कॉलोनी', 'ग्राम', 'तहसील', 'जिला', 'पता',
22
+ ],
23
+ places: {
24
+ IN: [
25
+ 'अंडमान और निकोबार', 'आंध्र प्रदेश', 'अरुणाचल प्रदेश', 'असम', 'बिहार', 'चंडीगढ़',
26
+ 'छत्तीसगढ़', 'दादरा और नगर हवेली', 'दमन और दीव', 'दिल्ली', 'गोवा', 'गुजरात',
27
+ 'हरियाणा', 'हिमाचल प्रदेश', 'जम्मू और कश्मीर', 'झारखंड', 'कर्नाटक', 'केरल',
28
+ 'लद्दाख', 'लक्षद्वीप', 'मध्य प्रदेश', 'महाराष्ट्र', 'मणिपुर', 'मेघालय', 'मिज़ोरम',
29
+ 'नागालैंड', 'ओडिशा', 'पुदुचेरी', 'पंजाब', 'राजस्थान', 'सिक्किम', 'तमिलनाडु',
30
+ 'तेलंगाना', 'त्रिपुरा', 'उत्तर प्रदेश', 'उत्तराखंड', 'पश्चिम बंगाल',
31
+ ],
32
+ },
33
+ };
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Region packs: country formats. Not a public host format in this version.
3
+ * Value shapes feed the labelled-rule compiler; unlabelledRules keep today's regexes.
4
+ */
5
+ import { verhoeff, looksLikePan, PAN_DIGIT_TO_LETTER, PAN_HOLDER_TYPES } from '../checksums.js';
6
+
7
+ const STATES = 'AL|AK|AZ|AR|CA|CO|CT|DE|DC|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY';
8
+ const PROVINCES = 'AB|BC|MB|NB|NL|NS|NT|NU|ON|PE|QC|SK|YT';
9
+ const STREET_SUFFIX_BASE = 'Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Drive|Dr|Lane|Ln|Court|Ct|Way|Place|Pl|Terrace|Ter|Parkway|Pkwy|Circle|Cir|Highway|Hwy|Trail|Trl|Square|Sq|Loop|Alley|Row';
10
+ const STREET_SUFFIX = `${STREET_SUFFIX_BASE}|${STREET_SUFFIX_BASE.toUpperCase()}`;
11
+
12
+ /** Shared street-line rule for US, CA, and GB. */
13
+ const STREET_LINE = {
14
+ type: 'address',
15
+ re: new RegExp(String.raw`\b\d{1,6}[A-Za-z]?\s+(?:(?:N|S|E|W|NE|NW|SE|SW|North|South|East|West|NORTH|SOUTH|EAST|WEST)\.?\s+)?(?:[A-Z0-9][A-Za-z0-9.'\-]*\s+){0,3}?(?:${STREET_SUFFIX})\b\.?(?:\s+(?:NW|NE|SW|SE|N|S|E|W)\b\.?)?(?:,?\s*(?:Apt|Apartment|Suite|Ste|Unit|Fl|Floor|APT|SUITE|STE|UNIT|#)\.?\s*[\w\-]+)?`, 'g'),
16
+ validate: (m) => (/^\d/.test(m) ? 0.85 : 0),
17
+ regions: ['US', 'CA', 'GB'],
18
+ };
19
+
20
+ export const REGION_PACKS = {
21
+ US: {
22
+ id: 'US',
23
+ categories: ['ssn', 'phone', 'address', 'account'],
24
+ valueShapes: {
25
+ ssn: { source: String.raw`([\dXx*\- ]{9,12})`, group: 1, confidence: 0.9 },
26
+ phone: {
27
+ source: String.raw`(\+?\d[\d\s.\-()]{7,16}\d)`,
28
+ group: 1,
29
+ confidence: 0.92,
30
+ validate: (m) => {
31
+ const n = m.replace(/\D/g, '').length;
32
+ return n >= 10 && n <= 15 ? 0.92 : 0;
33
+ },
34
+ },
35
+ },
36
+ postal: { source: String.raw`\d{5}(?:-\d{4})?`, confidence: 0.9 },
37
+ places: STATES.split('|'),
38
+ unlabelledRules: [
39
+ {
40
+ type: 'ssn',
41
+ re: /(?<![\d\-])(?!000|666|9\d\d)\d{3}[\- ](?!00)\d{2}[\- ](?!0000)\d{4}(?![\d\-])/g,
42
+ confidence: 0.95,
43
+ },
44
+ STREET_LINE,
45
+ {
46
+ type: 'address',
47
+ re: new RegExp(String.raw`\b[A-Z][A-Za-z.'\-]+(?:\s[A-Z][A-Za-z.'\-]+){0,3},?\s+(?:${STATES})\.?\s+\d{5}(?:-\d{4})?\b`, 'g'),
48
+ confidence: 0.9,
49
+ },
50
+ {
51
+ type: 'address',
52
+ re: /\bP\.?\s?O\.?\s+Box\s+\d+\b/gi,
53
+ confidence: 0.9,
54
+ },
55
+ {
56
+ type: 'phone',
57
+ re: /(?<![\w@.\-\/])(?:\+?1[\s.\-]?)?(?:\(\d{3}\)\s?|\d{3}[\s.\-])\d{3}[\s.\-]\d{4}(?![\d\-])/g,
58
+ confidence: 0.9,
59
+ },
60
+ ],
61
+ },
62
+
63
+ CA: {
64
+ id: 'CA',
65
+ categories: ['ssn', 'address'],
66
+ valueShapes: {
67
+ ssn: { source: String.raw`([\dXx*\- ]{9,12})`, group: 1, confidence: 0.9 },
68
+ },
69
+ postal: { source: String.raw`[A-Z]\d[A-Z][ \-]?\d[A-Z]\d`, confidence: 0.9 },
70
+ places: PROVINCES.split('|'),
71
+ unlabelledRules: [
72
+ STREET_LINE,
73
+ {
74
+ type: 'address',
75
+ re: new RegExp(String.raw`\b[A-Z][A-Za-z.'\-]+(?:\s[A-Z][A-Za-z.'\-]+){0,3},?\s+(?:${PROVINCES})\s+[A-Z]\d[A-Z][ \-]?\d[A-Z]\d\b`, 'g'),
76
+ confidence: 0.9,
77
+ },
78
+ ],
79
+ },
80
+
81
+ GB: {
82
+ id: 'GB',
83
+ categories: ['address'],
84
+ valueShapes: {},
85
+ postal: { source: String.raw`[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}`, confidence: 0.6 },
86
+ places: [],
87
+ unlabelledRules: [
88
+ STREET_LINE,
89
+ {
90
+ type: 'address',
91
+ re: /\b[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}\b/g,
92
+ confidence: 0.6,
93
+ },
94
+ ],
95
+ },
96
+
97
+ IN: {
98
+ id: 'IN',
99
+ categories: ['aadhaar', 'pan', 'phone', 'address'],
100
+ valueShapes: {
101
+ aadhaar: {
102
+ source: String.raw`(\d{4}[ \-]?\d{4}[ \-]?\d{4})(?!\d)`,
103
+ group: 1,
104
+ confidence: 0.9,
105
+ },
106
+ pan: {
107
+ source: String.raw`([A-Z0-9]{5} ?[A-Z0-9]{4} ?[A-Z0-9|\])!\/\\])(?![A-Za-z0-9])`,
108
+ group: 1,
109
+ confidence: 0.9,
110
+ validate: (m) => (looksLikePan(m.replace(/\s/g, '').toUpperCase().slice(-10)) ? 0.9 : 0),
111
+ },
112
+ phone: {
113
+ source: String.raw`(\+?\d[\d\s.\-()]{7,16}\d)`,
114
+ group: 1,
115
+ confidence: 0.92,
116
+ validate: (m) => {
117
+ const n = m.replace(/\D/g, '').length;
118
+ return n >= 10 && n <= 15 ? 0.92 : 0;
119
+ },
120
+ },
121
+ },
122
+ /** Six digits starting 1-9; never a bare number without a label or place. */
123
+ postal: { source: String.raw`[1-9]\d{5}`, confidence: 0.9 },
124
+ places: [
125
+ 'Andaman and Nicobar', 'Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'Bihar', 'Chandigarh',
126
+ 'Chhattisgarh', 'Dadra and Nagar Haveli', 'Daman and Diu', 'Delhi', 'Goa', 'Gujarat',
127
+ 'Haryana', 'Himachal Pradesh', 'Jammu and Kashmir', 'Jharkhand', 'Karnataka', 'Kerala',
128
+ 'Ladakh', 'Lakshadweep', 'Madhya Pradesh', 'Maharashtra', 'Manipur', 'Meghalaya', 'Mizoram',
129
+ 'Nagaland', 'Odisha', 'Puducherry', 'Punjab', 'Rajasthan', 'Sikkim', 'Tamil Nadu',
130
+ 'Telangana', 'Tripura', 'Uttar Pradesh', 'Uttarakhand', 'West Bengal',
131
+ ],
132
+ unlabelledRules: [
133
+ {
134
+ type: 'aadhaar',
135
+ re: /(?<![\d\-])(?<!\d[ \-])[2-9]\d{3}([ \-]?)\d{4}\1\d{4}(?!\d|[ \-]\d|-)/g,
136
+ validate: (m) => (verhoeff(m.replace(/\D/g, '')) ? 0.95 : 0),
137
+ },
138
+ {
139
+ type: 'pan',
140
+ re: /\b[A-Z0-9]{10}\b/g,
141
+ validate(m) {
142
+ if (!looksLikePan(m, 8)) return 0;
143
+ const fourth = /[A-Z]/.test(m[3]) ? m[3] : PAN_DIGIT_TO_LETTER[m[3]];
144
+ return PAN_HOLDER_TYPES.includes(fourth) ? 0.95 : 0;
145
+ },
146
+ },
147
+ {
148
+ type: 'phone',
149
+ re: /(?<![\w@/])(?:\+91[\s.\-]?)?[6-9]\d{4}[\s.\-]\d{5}(?!\d)/g,
150
+ confidence: 0.88,
151
+ },
152
+ {
153
+ type: 'phone',
154
+ re: /(?<![\w@/.\-])[6-9]\d{9}(?![\d\-@/]|\.\d)/g,
155
+ confidence: 0.75,
156
+ },
157
+ // Landline: 0 + area + subscriber, 10 or 11 digits total.
158
+ {
159
+ type: 'phone',
160
+ re: /(?<![\d])0\d{2,4}[\s.\-]?\d{6,8}(?!\d)/g,
161
+ validate(m) {
162
+ const n = m.replace(/\D/g, '').length;
163
+ return n === 10 || n === 11 ? 0.85 : 0;
164
+ },
165
+ },
166
+ // Masked Aadhaar: XXXX XXXX 1234 (beats masked-card at 0.8).
167
+ {
168
+ type: 'aadhaar',
169
+ re: /(?:[*xX•●·]{4}[ \-]?){2}\d{4}(?!\d)/g,
170
+ confidence: 0.85,
171
+ },
172
+ ],
173
+ },
174
+ };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Default scan scope and helpers to resolve region/language ids into packs.
3
+ * Hindi is opt-in: hosts add 'hi' when documents are in Devanagari.
4
+ */
5
+
6
+ export const DEFAULT_SCOPE = {
7
+ regions: ['US', 'CA', 'GB', 'IN'],
8
+ languages: ['en'],
9
+ };
10
+
11
+ /** Shipped Tesseract language codes always copied into public/vendor. */
12
+ export const SHIPPED_OCR_CODES = ['eng', 'hin'];
13
+
14
+ /** Normalize a scope object; missing fields fall back to the default. */
15
+ export function normalizeScopeInput(scope) {
16
+ if (scope == null) return { ...DEFAULT_SCOPE, regions: [...DEFAULT_SCOPE.regions], languages: [...DEFAULT_SCOPE.languages] };
17
+ if (typeof scope !== 'object' || Array.isArray(scope)) {
18
+ throw new TypeError('createDetector(scope): scope must be an object with regions and languages');
19
+ }
20
+ return {
21
+ regions: scope.regions != null ? scope.regions : [...DEFAULT_SCOPE.regions],
22
+ languages: scope.languages != null ? scope.languages : [...DEFAULT_SCOPE.languages],
23
+ };
24
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Rules that do not depend on country or language. Always included in every scope.
3
+ */
4
+ import { luhn } from './checksums.js';
5
+
6
+ /** Universal detectors: email, cards, IBAN, +phones, and secret prefixes. */
7
+ export const UNIVERSAL_RULES = [
8
+ {
9
+ type: 'email',
10
+ re: /[A-Za-z0-9._%+\-]+[@@¢©®¤][A-Za-z0-9\-]+(?:\.[A-Za-z0-9\-]+)*\.[A-Za-z]{2,}/g,
11
+ confidence: 0.98,
12
+ },
13
+ {
14
+ type: 'card',
15
+ re: /(?<![\d])(?:\d[ \-]?){12,18}\d(?![\d])/g,
16
+ validate(m) {
17
+ const digits = m.replace(/\D/g, '');
18
+ if (digits.length < 13 || digits.length > 19) return 0;
19
+ if (luhn(digits)) return 0.97;
20
+ if (/^\d{4}[ \-]\d{4}[ \-]\d{4}[ \-]\d{4}$/.test(m.trim())) return 0.75;
21
+ if (/^\d{4}[ \-]\d{6}[ \-]\d{5}$/.test(m.trim())) return 0.75;
22
+ return 0;
23
+ },
24
+ },
25
+ {
26
+ type: 'card',
27
+ re: /(?:[*xX•●·]{4}[ \-]?){1,3}\d{4}\b/g,
28
+ confidence: 0.8,
29
+ },
30
+ {
31
+ type: 'phone',
32
+ re: /(?<![\w@.\-\/])\+\d{1,3}[\s.\-]?(?:\(?\d{1,4}\)?[\s.\-]?){2,5}\d{2,4}(?![\d\-])/g,
33
+ validate(m) {
34
+ const n = m.replace(/\D/g, '').length;
35
+ return n >= 8 && n <= 15 ? 0.85 : 0;
36
+ },
37
+ },
38
+ {
39
+ type: 'account',
40
+ re: /\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]{4}){3,7}(?:[ ]?[A-Z0-9]{1,4})?\b/g,
41
+ validate: (m) => (m.replace(/\s/g, '').length >= 15 && /\d/.test(m) ? 0.8 : 0),
42
+ },
43
+ {
44
+ type: 'secret',
45
+ re: /\b(?:sk-[A-Za-z0-9_\-]{20,}|sk_(?:live|test)_[A-Za-z0-9]{16,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|xox[baprs]-[A-Za-z0-9\-]{10,}|AIza[0-9A-Za-z_\-]{30,}|eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,})\b/g,
46
+ confidence: 0.97,
47
+ },
48
+ {
49
+ type: 'secret',
50
+ re: /\b(?:sk|pk|rk)[_\- ](?:live|test)[_\- ][A-Za-z0-9]{16,}/g,
51
+ confidence: 0.9,
52
+ },
53
+ {
54
+ type: 'secret',
55
+ re: /\b(?:password|passwd|pwd|passcode|secret|token|api[_\- ]?key)\s*[:=]\s*(\S{4,})/gi,
56
+ group: 1,
57
+ confidence: 0.85,
58
+ },
59
+ ];
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Validates language packs before they are compiled into a detector.
3
+ */
4
+
5
+ const KNOWN_LABEL_KEYS = new Set([
6
+ 'aadhaar', 'pan', 'ssn', 'phone', 'account', 'dob', 'card', 'email', 'address', 'secret',
7
+ ]);
8
+
9
+ /** Escape a literal so it is safe inside a RegExp source. */
10
+ export function escapeRe(s) {
11
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
12
+ }
13
+
14
+ /**
15
+ * Both NFC and NFD forms of a label, so composed and decomposed Devanagari match.
16
+ * Document text is never normalized; only the pattern lists both forms.
17
+ */
18
+ export function labelForms(label) {
19
+ const nfc = label.normalize('NFC');
20
+ const nfd = label.normalize('NFD');
21
+ return nfc === nfd ? [nfc] : [nfc, nfd];
22
+ }
23
+
24
+ /** Reject unknown or malformed language packs with a named field. */
25
+ export function validateLanguagePack(pack, at = 'language pack') {
26
+ if (!pack || typeof pack !== 'object' || Array.isArray(pack)) {
27
+ throw new TypeError(`${at}: must be an object`);
28
+ }
29
+ if (pack.schema !== 1) throw new TypeError(`${at}: schema must be 1`);
30
+ if (typeof pack.id !== 'string' || !/^[a-z]{2,8}$/.test(pack.id)) {
31
+ throw new TypeError(`${at}: id must be a lowercase language tag`);
32
+ }
33
+ if (!Array.isArray(pack.scripts) || !pack.scripts.length || pack.scripts.some((s) => typeof s !== 'string')) {
34
+ throw new TypeError(`${at} (${pack.id}): scripts must be a non-empty string list`);
35
+ }
36
+ if (!Array.isArray(pack.ocr) || pack.ocr.some((c) => typeof c !== 'string')) {
37
+ throw new TypeError(`${at} (${pack.id}): ocr must be a list of Tesseract codes`);
38
+ }
39
+ if (pack.digits != null) {
40
+ if (typeof pack.digits !== 'object' || Array.isArray(pack.digits)) {
41
+ throw new TypeError(`${at} (${pack.id}): digits must be an object`);
42
+ }
43
+ for (const [from, to] of Object.entries(pack.digits)) {
44
+ if (from.length !== 1 || String(to).length !== 1) {
45
+ throw new TypeError(`${at} (${pack.id}): each digits entry must be one UTF-16 code unit`);
46
+ }
47
+ }
48
+ }
49
+ if (pack.labels != null) {
50
+ if (typeof pack.labels !== 'object' || Array.isArray(pack.labels)) {
51
+ throw new TypeError(`${at} (${pack.id}): labels must be an object`);
52
+ }
53
+ for (const [cat, list] of Object.entries(pack.labels)) {
54
+ if (!KNOWN_LABEL_KEYS.has(cat)) throw new TypeError(`${at} (${pack.id}): unknown label category "${cat}"`);
55
+ if (!Array.isArray(list) || list.some((w) => typeof w !== 'string' || w.length < 2)) {
56
+ throw new TypeError(`${at} (${pack.id}): labels.${cat} entries must be strings of at least 2 characters`);
57
+ }
58
+ }
59
+ }
60
+ for (const field of ['labelSuffixes', 'postalLabels', 'addressCues']) {
61
+ const list = pack[field];
62
+ if (list == null) continue;
63
+ if (!Array.isArray(list) || list.some((w) => typeof w !== 'string' || !w.length)) {
64
+ throw new TypeError(`${at} (${pack.id}): ${field} must be a list of non-empty strings`);
65
+ }
66
+ }
67
+ if (pack.places != null) {
68
+ if (typeof pack.places !== 'object' || Array.isArray(pack.places)) {
69
+ throw new TypeError(`${at} (${pack.id}): places must be an object`);
70
+ }
71
+ for (const [region, list] of Object.entries(pack.places)) {
72
+ if (!Array.isArray(list) || list.some((w) => typeof w !== 'string' || !w.length)) {
73
+ throw new TypeError(`${at} (${pack.id}): places.${region} must be a list of non-empty strings`);
74
+ }
75
+ }
76
+ }
77
+ return pack;
78
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Coverage warnings when input may be in a script the scope does not cover.
3
+ */
4
+
5
+ /** Unicode script name for a code point, or null when not a letter. */
6
+ function scriptOf(cp) {
7
+ try {
8
+ const u = String.fromCodePoint(cp);
9
+ if (!/\p{L}/u.test(u)) return null;
10
+ // Common scripts we care about for warnings. Latin is covered by 'en'.
11
+ if (/\p{Script=Devanagari}/u.test(u)) return 'Devanagari';
12
+ if (/\p{Script=Latin}/u.test(u)) return 'Latin';
13
+ if (/\p{Script=Arabic}/u.test(u)) return 'Arabic';
14
+ if (/\p{Script=Han}/u.test(u)) return 'Han';
15
+ if (/\p{Script=Hiragana}/u.test(u) || /\p{Script=Katakana}/u.test(u)) return 'Japanese';
16
+ if (/\p{Script=Thai}/u.test(u)) return 'Thai';
17
+ if (/\p{Script=Cyrillic}/u.test(u)) return 'Cyrillic';
18
+ return 'Other';
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ /**
25
+ * When the text has at least 20 letters in a script no scoped language lists,
26
+ * report uncovered-script. Does not include document text in the warning.
27
+ */
28
+ export function scriptWarnings(text, coveredScripts) {
29
+ const covered = new Set(coveredScripts);
30
+ const counts = Object.create(null);
31
+ for (const ch of text) {
32
+ const s = scriptOf(ch.codePointAt(0));
33
+ if (!s) continue;
34
+ counts[s] = (counts[s] || 0) + 1;
35
+ }
36
+ const warnings = [];
37
+ for (const [script, n] of Object.entries(counts)) {
38
+ if (n < 20) continue;
39
+ if (covered.has(script)) continue;
40
+ warnings.push({ code: 'uncovered-script', script });
41
+ }
42
+ return warnings;
43
+ }
44
+
45
+ /**
46
+ * When more than half the OCR words on a page were dropped by the confidence
47
+ * filter, the page may be in an unloaded language.
48
+ */
49
+ export function lowConfidencePageWarning(pageIndex, kept, dropped) {
50
+ const total = kept + dropped;
51
+ if (total < 4) return null;
52
+ if (dropped <= total / 2) return null;
53
+ return { code: 'low-confidence-page', page: pageIndex };
54
+ }
package/src/detect/ocr.js CHANGED
@@ -1,13 +1,22 @@
1
1
  /**
2
2
  * OCR via Tesseract.js – engine, WASM core and language data are all served locally from /vendor.
3
3
  * Returns lines of words in the *original* canvas' pixel coordinates.
4
+ *
5
+ * The language string comes from the active detector scope (default `eng`).
6
+ * Changing languages ends the worker and starts a new one.
4
7
  */
5
8
  import { createWorker } from 'tesseract.js';
6
9
  import { coreCandidates, OCR_CORE_PREFERENCES } from './ocrCore.js';
10
+ import { keepOcrWord } from './ocrFilter.js';
11
+ import { defaultDetector } from './patterns.js';
7
12
 
8
13
  let workerPromise = null;
14
+ let workerKey = null;
9
15
  let progressCb = null;
10
16
  let corePreference = 'stable';
17
+ let activeOcrLanguages = defaultDetector.ocrLanguages;
18
+ let activeDigitMap = defaultDetector.digitMap;
19
+ let activeLabelStarters = defaultDetector.labelStarters;
11
20
 
12
21
  const abs = (p) => new URL(import.meta.env.BASE_URL + p, window.location.href).href;
13
22
 
@@ -35,16 +44,41 @@ export function setOcrCorePreference(preference) {
35
44
  corePreference = preference;
36
45
  }
37
46
 
47
+ /**
48
+ * Set the Tesseract language string and filter context from a detector.
49
+ * Restarts the worker when the language string changes.
50
+ */
51
+ export function setOcrScope({ ocrLanguages, digitMap, labelStarters } = {}) {
52
+ const langs = ocrLanguages || 'eng';
53
+ if (langs !== activeOcrLanguages) {
54
+ activeOcrLanguages = langs;
55
+ // Drop the worker so the next scan loads the new language data.
56
+ if (workerPromise) {
57
+ workerPromise.then((w) => w.terminate()).catch(() => {});
58
+ workerPromise = null;
59
+ workerKey = null;
60
+ }
61
+ }
62
+ activeDigitMap = digitMap || null;
63
+ activeLabelStarters = labelStarters || [];
64
+ }
65
+
66
+ /** Language string the next worker will load. */
67
+ export function getOcrLanguages() {
68
+ return activeOcrLanguages;
69
+ }
70
+
38
71
  /**
39
72
  * Start a worker on the first core that loads. We pick the core file ourselves instead of handing
40
73
  * tesseract.js a directory, so a tesseract.js upgrade that asks for a new file name cannot break OCR.
41
74
  */
42
75
  async function startWorker() {
43
76
  const files = coreCandidates(corePreference, { simd: wasmSupports(SIMD_PROBE), relaxedSimd: wasmSupports(RELAXED_SIMD_PROBE) });
77
+ const langs = activeOcrLanguages;
44
78
  let lastError;
45
79
  for (const file of files) {
46
80
  try {
47
- const worker = await createWorker('eng', 1, {
81
+ const worker = await createWorker(langs, 1, {
48
82
  workerPath: abs('vendor/tesseract/worker.min.js'),
49
83
  corePath: abs(`vendor/tesseract/${file}`),
50
84
  langPath: abs('vendor/tesseract'),
@@ -53,9 +87,15 @@ async function startWorker() {
53
87
  logger: (m) => { if (m.status === 'recognizing text' && progressCb) progressCb(m.progress); },
54
88
  });
55
89
  await worker.setParameters({ user_defined_dpi: '300' });
90
+ workerKey = `${file}::${langs}`;
56
91
  return worker;
57
92
  } catch (err) {
58
93
  lastError = err;
94
+ const missing = /failed to load|load language|network|404|traineddata/i.test(String(err?.message || err));
95
+ if (missing) {
96
+ const code = langs.split('+').find(Boolean) || langs;
97
+ throw new Error(`Text reading failed: no OCR data for ${code}`);
98
+ }
59
99
  console.warn(`[privacy-redact] OCR core ${file} did not load, trying the next one`, err);
60
100
  }
61
101
  }
@@ -66,6 +106,7 @@ function getWorker() {
66
106
  if (!workerPromise) {
67
107
  workerPromise = startWorker().catch((err) => {
68
108
  workerPromise = null;
109
+ workerKey = null;
69
110
  throw err;
70
111
  });
71
112
  }
@@ -113,14 +154,16 @@ export async function recognizeLines(canvas, onProgress) {
113
154
  const { image, scale } = prepare(canvas);
114
155
  const { data } = await worker.recognize(image, {}, { blocks: true });
115
156
  progressCb = null;
157
+ const filterOpts = {
158
+ digitMap: activeDigitMap,
159
+ labelStarters: activeLabelStarters,
160
+ };
116
161
  const lines = [];
117
162
  for (const block of data.blocks || []) {
118
163
  for (const para of block.paragraphs || []) {
119
164
  for (const line of para.lines || []) {
120
165
  const words = (line.words || [])
121
- // Drop low-confidence garbage (e.g. "words" OCR hallucinates inside photos) – it would otherwise stretch
122
- // redaction boxes. Anything containing a digit or "@" is kept, because that is what secrets look like.
123
- .filter((w) => w.text && w.text.trim() && (w.confidence >= 45 || /[\d@]/.test(w.text)))
166
+ .filter((w) => keepOcrWord(w, filterOpts))
124
167
  .map((w) => ({
125
168
  text: w.text.trim(),
126
169
  confidence: w.confidence,
@@ -134,5 +177,15 @@ export async function recognizeLines(canvas, onProgress) {
134
177
  }
135
178
 
136
179
  export async function disposeOcr() {
137
- if (workerPromise) { const w = await workerPromise; await w.terminate(); workerPromise = null; }
180
+ if (workerPromise) {
181
+ const w = await workerPromise;
182
+ await w.terminate();
183
+ workerPromise = null;
184
+ workerKey = null;
185
+ }
186
+ }
187
+
188
+ /** Test helper: which core+language key the live worker was started with. */
189
+ export function getOcrWorkerKey() {
190
+ return workerKey;
138
191
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Which OCR words to keep. Pure so it can be tested in Node.
3
+ * A Hindi label read at low confidence is kept so the value after it is still found.
4
+ */
5
+
6
+ /** Map native digits then test for digit or @. */
7
+ function hasSecretChar(text, digitMap) {
8
+ let s = text;
9
+ if (digitMap && Object.keys(digitMap).length) {
10
+ s = '';
11
+ for (const ch of text) s += digitMap[ch] ?? ch;
12
+ }
13
+ return /[\d@]/.test(s);
14
+ }
15
+
16
+ /**
17
+ * Keep a word when confidence is high enough, it looks like a secret character,
18
+ * or it starts a known label in the current scope.
19
+ */
20
+ export function keepOcrWord(word, { minConfidence = 45, digitMap = null, labelStarters = [] } = {}) {
21
+ const text = word?.text?.trim();
22
+ if (!text) return false;
23
+ if ((word.confidence ?? 0) >= minConfidence) return true;
24
+ if (hasSecretChar(text, digitMap)) return true;
25
+ const lower = text.toLowerCase();
26
+ for (const label of labelStarters) {
27
+ if (!label) continue;
28
+ if (text.startsWith(label) || lower.startsWith(label.toLowerCase())) return true;
29
+ }
30
+ return false;
31
+ }