constructelligence commited on
Commit
652ad64
·
verified ·
1 Parent(s): ff59ad3

OCR look-alike readings: character-error micro-F1 79.9% -> 89.7%, clean unchanged

Browse files
README.md CHANGED
@@ -65,7 +65,7 @@ model-index:
65
  value: 0.997
66
  name: Micro-F1 (clean)
67
  - type: f1
68
- value: 0.799
69
  name: Micro-F1 (character-error stress)
70
  ---
71
 
@@ -100,7 +100,7 @@ delivered at the wrong voltage or rating, or one that quietly never makes it ont
100
  | **Matching** | Code folding (`O/0`, `I/L/1`, `S/5`, `B/8`, `Z/2`) + voltage-compatibility signal |
101
  | **Quality gate** | Advisory photo check (blur, glare, darkness, resolution) before OCR |
102
  | **Runtime** | Browser · Node · edge — no GPU, no server, no data egress |
103
- | **Field accuracy** | **99.8%** clean / **80.0%** under character-error stress (extraction benchmark) |
104
  | **Licence** | Apache-2.0 |
105
 
106
  ---
@@ -209,13 +209,23 @@ plate lettering. n = 1000. Reproduce with `node tests/nameplates-extraction-benc
209
  | Condition | Exact plate | Micro-F1 | ms/plate |
210
  |---|:---:|:---:|---:|
211
  | clean | **94.1%** | **99.7%** | 0.49 |
212
- | ocr (character-error stress) | 1.1% | **79.9%** | 0.49 |
213
 
214
  Per-field F1 is 100% for manufacturer, type, model, serial, kVA, phase, Hz, MCA, MOCP, refrigerant,
215
  pf, cfm, uHeight, sccr and enclosure in the clean condition; the residual clean misses are a small number of
216
  voltage and `mfgDate` cases. The `ocr` condition is deliberately harsh (per-character flips); low-confidence
217
  fields are surfaced for a human rather than trusted. Per-field tables: `eval/extraction-bench.json`.
218
 
 
 
 
 
 
 
 
 
 
 
219
  ### OCR benchmark — drawn plates through phone-photo degradations
220
 
221
  Plates drawn for several equipment types, each pushed through real-photo degradations (small, blurred, noisy,
 
65
  value: 0.997
66
  name: Micro-F1 (clean)
67
  - type: f1
68
+ value: 0.897
69
  name: Micro-F1 (character-error stress)
70
  ---
71
 
 
100
  | **Matching** | Code folding (`O/0`, `I/L/1`, `S/5`, `B/8`, `Z/2`) + voltage-compatibility signal |
101
  | **Quality gate** | Advisory photo check (blur, glare, darkness, resolution) before OCR |
102
  | **Runtime** | Browser · Node · edge — no GPU, no server, no data egress |
103
+ | **Field accuracy** | **99.7%** clean / **89.7%** under character-error stress (extraction benchmark; was 79.9%) |
104
  | **Licence** | Apache-2.0 |
105
 
106
  ---
 
209
  | Condition | Exact plate | Micro-F1 | ms/plate |
210
  |---|:---:|:---:|---:|
211
  | clean | **94.1%** | **99.7%** | 0.49 |
212
+ | ocr (character-error stress) | **10.2%** <sub>(was 1.1%)</sub> | **89.7%** <sub>(was 79.9%)</sub> | 0.71 |
213
 
214
  Per-field F1 is 100% for manufacturer, type, model, serial, kVA, phase, Hz, MCA, MOCP, refrigerant,
215
  pf, cfm, uHeight, sccr and enclosure in the clean condition; the residual clean misses are a small number of
216
  voltage and `mfgDate` cases. The `ocr` condition is deliberately harsh (per-character flips); low-confidence
217
  fields are surfaced for a human rather than trusted. Per-field tables: `eval/extraction-bench.json`.
218
 
219
+ **Oct 2026: OCR look-alike readings.** Plate lettering is misread one character for another (`M0DEL`, `5/N`,
220
+ `2O23-O4`, `6ENERAT0R`) or split by a stray space (`Westgate Po wer`, `4 15Y/240`). The parser now also tries
221
+ same-length look-alike readings of each line: digits back to letters inside words, letters back to digits next
222
+ to digits (never inside a model or serial code), and one-space rejoins where the result is checkable (a company
223
+ name, a voltage). The raw line is always tried first, so clean plates parse exactly as before (identical clean
224
+ row). On the OCR condition micro-F1 rose **79.9% → 89.7%** and whole-plate exact match **1.1% → 10.2%**; the
225
+ same change was developed on a different corpus seed (7) and confirmed on seeds 20 (this table) and 99 (80.1% →
226
+ 89.5%). Weakest remaining fields under OCR noise: cell count, model and serial number (codes are deliberately
227
+ not rejoined, since a real plate can print the voltage right after the model).
228
+
229
  ### OCR benchmark — drawn plates through phone-photo degradations
230
 
231
  Plates drawn for several equipment types, each pushed through real-photo degradations (small, blurred, noisy,
eval/extraction-bench.json CHANGED
@@ -4,7 +4,7 @@
4
  "n": 1000,
5
  "exactPlate": 0.941,
6
  "microF1": 0.997,
7
- "msPerPlate": 0.48,
8
  "fields": {
9
  "manufacturer": {
10
  "precision": 1,
@@ -149,32 +149,32 @@
149
  "ocr": {
150
  "condition": "ocr",
151
  "n": 1000,
152
- "exactPlate": 0.011,
153
- "microF1": 0.799,
154
- "msPerPlate": 0.49,
155
  "fields": {
156
  "manufacturer": {
157
  "precision": 1,
158
- "recall": 0.72,
159
- "f1": 0.837,
160
  "support": 1000
161
  },
162
  "type": {
163
  "precision": 1,
164
- "recall": 0.518,
165
- "f1": 0.682,
166
  "support": 1000
167
  },
168
  "voltage": {
169
  "precision": 1,
170
- "recall": 0.675,
171
- "f1": 0.806,
172
  "support": 1000
173
  },
174
  "kva": {
175
  "precision": 1,
176
- "recall": 0.622,
177
- "f1": 0.767,
178
  "support": 555
179
  },
180
  "phase": {
@@ -185,26 +185,26 @@
185
  },
186
  "hz": {
187
  "precision": 1,
188
- "recall": 0.786,
189
- "f1": 0.88,
190
  "support": 878
191
  },
192
  "model": {
193
  "precision": 1,
194
- "recall": 0.6,
195
- "f1": 0.75,
196
  "support": 1000
197
  },
198
  "serial": {
199
  "precision": 1,
200
- "recall": 0.627,
201
- "f1": 0.771,
202
  "support": 1000
203
  },
204
  "mfgDate": {
205
  "precision": 1,
206
- "recall": 0.321,
207
- "f1": 0.486,
208
  "support": 878
209
  },
210
  "uHeight": {
@@ -214,39 +214,39 @@
214
  "support": 118
215
  },
216
  "powerW": {
217
- "precision": 0.849,
218
- "recall": 0.619,
219
- "f1": 0.716,
220
  "support": 118
221
  },
222
  "cfm": {
223
  "precision": 1,
224
- "recall": 0.653,
225
- "f1": 0.79,
226
  "support": 225
227
  },
228
  "amps": {
229
- "precision": 0.94,
230
- "recall": 0.809,
231
- "f1": 0.87,
232
  "support": 446
233
  },
234
  "sccr": {
235
  "precision": 1,
236
- "recall": 0.847,
237
- "f1": 0.917,
238
  "support": 124
239
  },
240
  "enclosure": {
241
  "precision": 1,
242
- "recall": 0.815,
243
- "f1": 0.898,
244
  "support": 124
245
  },
246
  "kw": {
247
- "precision": 0.994,
248
- "recall": 0.719,
249
- "f1": 0.835,
250
  "support": 221
251
  },
252
  "pf": {
@@ -263,32 +263,32 @@
263
  },
264
  "mocp": {
265
  "precision": 1,
266
- "recall": 0.707,
267
- "f1": 0.829,
268
  "support": 205
269
  },
270
  "refrigerant": {
271
- "precision": 0.973,
272
- "recall": 0.735,
273
- "f1": 0.837,
274
  "support": 98
275
  },
276
  "batteryType": {
277
  "precision": 1,
278
- "recall": 0.656,
279
- "f1": 0.792,
280
  "support": 122
281
  },
282
  "cells": {
283
  "precision": 1,
284
- "recall": 0.459,
285
- "f1": 0.629,
286
  "support": 122
287
  },
288
  "batteryAh": {
289
- "precision": 0.965,
290
- "recall": 0.672,
291
- "f1": 0.792,
292
  "support": 122
293
  }
294
  }
 
4
  "n": 1000,
5
  "exactPlate": 0.941,
6
  "microF1": 0.997,
7
+ "msPerPlate": 0.64,
8
  "fields": {
9
  "manufacturer": {
10
  "precision": 1,
 
149
  "ocr": {
150
  "condition": "ocr",
151
  "n": 1000,
152
+ "exactPlate": 0.102,
153
+ "microF1": 0.897,
154
+ "msPerPlate": 0.71,
155
  "fields": {
156
  "manufacturer": {
157
  "precision": 1,
158
+ "recall": 0.787,
159
+ "f1": 0.881,
160
  "support": 1000
161
  },
162
  "type": {
163
  "precision": 1,
164
+ "recall": 0.744,
165
+ "f1": 0.853,
166
  "support": 1000
167
  },
168
  "voltage": {
169
  "precision": 1,
170
+ "recall": 0.835,
171
+ "f1": 0.91,
172
  "support": 1000
173
  },
174
  "kva": {
175
  "precision": 1,
176
+ "recall": 0.786,
177
+ "f1": 0.88,
178
  "support": 555
179
  },
180
  "phase": {
 
185
  },
186
  "hz": {
187
  "precision": 1,
188
+ "recall": 0.864,
189
+ "f1": 0.927,
190
  "support": 878
191
  },
192
  "model": {
193
  "precision": 1,
194
+ "recall": 0.739,
195
+ "f1": 0.85,
196
  "support": 1000
197
  },
198
  "serial": {
199
  "precision": 1,
200
+ "recall": 0.751,
201
+ "f1": 0.858,
202
  "support": 1000
203
  },
204
  "mfgDate": {
205
  "precision": 1,
206
+ "recall": 0.82,
207
+ "f1": 0.901,
208
  "support": 878
209
  },
210
  "uHeight": {
 
214
  "support": 118
215
  },
216
  "powerW": {
217
+ "precision": 0.884,
218
+ "recall": 0.907,
219
+ "f1": 0.895,
220
  "support": 118
221
  },
222
  "cfm": {
223
  "precision": 1,
224
+ "recall": 0.849,
225
+ "f1": 0.918,
226
  "support": 225
227
  },
228
  "amps": {
229
+ "precision": 0.941,
230
+ "recall": 0.857,
231
+ "f1": 0.897,
232
  "support": 446
233
  },
234
  "sccr": {
235
  "precision": 1,
236
+ "recall": 0.911,
237
+ "f1": 0.954,
238
  "support": 124
239
  },
240
  "enclosure": {
241
  "precision": 1,
242
+ "recall": 0.847,
243
+ "f1": 0.917,
244
  "support": 124
245
  },
246
  "kw": {
247
+ "precision": 0.995,
248
+ "recall": 0.833,
249
+ "f1": 0.906,
250
  "support": 221
251
  },
252
  "pf": {
 
263
  },
264
  "mocp": {
265
  "precision": 1,
266
+ "recall": 0.849,
267
+ "f1": 0.918,
268
  "support": 205
269
  },
270
  "refrigerant": {
271
+ "precision": 0.977,
272
+ "recall": 0.857,
273
+ "f1": 0.913,
274
  "support": 98
275
  },
276
  "batteryType": {
277
  "precision": 1,
278
+ "recall": 0.861,
279
+ "f1": 0.925,
280
  "support": 122
281
  },
282
  "cells": {
283
  "precision": 1,
284
+ "recall": 0.656,
285
+ "f1": 0.792,
286
  "support": 122
287
  },
288
  "batteryAh": {
289
+ "precision": 0.972,
290
+ "recall": 0.852,
291
+ "f1": 0.908,
292
  "support": 122
293
  }
294
  }
eval/extraction-bench.log CHANGED
@@ -1,5 +1,5 @@
1
 
2
- CLEAN n=1000 exact-plate 94.1% micro-F1 99.7% 0.49 ms/plate
3
  powerW P 94.3 R 99.0 F1 96.6 (100)
4
  voltage P 100.0 R 95.8 F1 97.9 (1000)
5
  kw P 99.2 R 99.6 F1 99.4 (235)
@@ -24,27 +24,27 @@ CLEAN n=1000 exact-plate 94.1% micro-F1 99.7% 0.49 ms/plate
24
  sccr P 100.0 R 100.0 F1 100.0 (111)
25
  enclosure P 100.0 R 100.0 F1 100.0 (111)
26
 
27
- OCR n=1000 exact-plate 1.1% micro-F1 79.9% 0.49 ms/plate
28
- mfgDate P 100.0 R 32.1 F1 48.6 (878)
29
- cells P 100.0 R 45.9 F1 62.9 (122)
30
- type P 100.0 R 51.8 F1 68.2 (1000)
31
- powerW P 84.9 R 61.9 F1 71.6 (118)
32
- model P 100.0 R 60.0 F1 75.0 (1000)
33
- kva P 100.0 R 62.2 F1 76.7 (555)
34
- serial P 100.0 R 62.7 F1 77.1 (1000)
35
- cfm P 100.0 R 65.3 F1 79.0 (225)
36
- batteryType P 100.0 R 65.6 F1 79.2 (122)
37
- batteryAh P 96.5 R 67.2 F1 79.2 (122)
38
- voltage P 100.0 R 67.5 F1 80.6 (1000)
39
- mocp P 100.0 R 70.7 F1 82.9 (205)
40
- kw P 99.4 R 71.9 F1 83.5 (221)
41
- manufacturer P 100.0 R 72.0 F1 83.7 (1000)
42
- refrigerant P 97.3 R 73.5 F1 83.7 (98)
43
- amps P 94.0 R 80.9 F1 87.0 (446)
44
- hz P 100.0 R 78.6 F1 88.0 (878)
45
- enclosure P 100.0 R 81.5 F1 89.8 (124)
46
  mca P 100.0 R 83.4 F1 91.0 (205)
47
- sccr P 100.0 R 84.7 F1 91.7 (124)
 
 
 
 
 
 
48
  uHeight P 97.4 R 95.8 F1 96.6 (118)
49
  phase P 100.0 R 94.0 F1 96.9 (878)
50
  pf P 100.0 R 94.6 F1 97.2 (112)
 
1
 
2
+ CLEAN n=1000 exact-plate 94.1% micro-F1 99.7% 0.64 ms/plate
3
  powerW P 94.3 R 99.0 F1 96.6 (100)
4
  voltage P 100.0 R 95.8 F1 97.9 (1000)
5
  kw P 99.2 R 99.6 F1 99.4 (235)
 
24
  sccr P 100.0 R 100.0 F1 100.0 (111)
25
  enclosure P 100.0 R 100.0 F1 100.0 (111)
26
 
27
+ OCR n=1000 exact-plate 10.2% micro-F1 89.7% 0.71 ms/plate
28
+ cells P 100.0 R 65.6 F1 79.2 (122)
29
+ model P 100.0 R 73.9 F1 85.0 (1000)
30
+ type P 100.0 R 74.4 F1 85.3 (1000)
31
+ serial P 100.0 R 75.1 F1 85.8 (1000)
32
+ kva P 100.0 R 78.6 F1 88.0 (555)
33
+ manufacturer P 100.0 R 78.7 F1 88.1 (1000)
34
+ powerW P 88.4 R 90.7 F1 89.5 (118)
35
+ amps P 94.1 R 85.7 F1 89.7 (446)
36
+ mfgDate P 100.0 R 82.0 F1 90.1 (878)
37
+ kw P 99.5 R 83.3 F1 90.6 (221)
38
+ batteryAh P 97.2 R 85.2 F1 90.8 (122)
39
+ voltage P 100.0 R 83.5 F1 91.0 (1000)
 
 
 
 
 
 
40
  mca P 100.0 R 83.4 F1 91.0 (205)
41
+ refrigerant P 97.7 R 85.7 F1 91.3 (98)
42
+ enclosure P 100.0 R 84.7 F1 91.7 (124)
43
+ cfm P 100.0 R 84.9 F1 91.8 (225)
44
+ mocp P 100.0 R 84.9 F1 91.8 (205)
45
+ batteryType P 100.0 R 86.1 F1 92.5 (122)
46
+ hz P 100.0 R 86.4 F1 92.7 (878)
47
+ sccr P 100.0 R 91.1 F1 95.4 (124)
48
  uHeight P 97.4 R 95.8 F1 96.6 (118)
49
  phase P 100.0 R 94.0 F1 96.9 (878)
50
  pf P 100.0 R 94.6 F1 97.2 (112)
nameplate-model.js CHANGED
@@ -152,29 +152,72 @@ export function parseNameplate(input) {
152
  const fields = {};
153
  // line: index of the OCR line the value came from, so the page can outline it on the photo.
154
  const set = (key, value, conf, line) => { if (fields[key] == null && value != null && value !== '') fields[key] = { value, conf, line }; };
 
 
 
 
 
 
 
 
155
  // Each rule runs over every line in order, so the first line that has the field wins.
156
- const scan = (key, re, map = m => m[1]) => {
 
 
 
 
157
  for (const [i, l] of lines.entries()) {
158
- const m = up(l.text).match(re);
159
- if (m) { const v = map(m); if (v != null && v !== '') { set(key, v, l.conf, i); return; } }
 
 
 
 
 
 
 
 
 
 
160
  }
161
  };
162
 
163
  const CODE = '([A-Z0-9][A-Z0-9\\-\\/\\.]{2,})';
164
- scan('model', new RegExp(`(?:\\bMODEL\\b|\\bMOD\\.|\\bM\\/N\\b|\\bCAT(?:ALOG)?\\.?\\s*(?:NO\\b\\.?|#|NUMBER)|\\bP\\/N\\b|\\bPART\\s*(?:NO\\b\\.?|#|NUMBER))\\s*(?:NO\\b\\.?|NUMBER\\b|#)?\\s*[:#.]?\\s*${CODE}`), m => cleanCode(m[1]));
165
- scan('serial', new RegExp(`(?:\\bSERIAL\\b|\\bSER\\.|\\bS\\/N\\b|\\b5\\/N\\b|\\bSN\\b)\\s*(?:NO\\b\\.?|NUMBER\\b|#)?\\s*[:#.]?\\s*([A-Z0-9][A-Z0-9\\-]{3,})`), m => cleanCode(m[1]));
166
  scan('refrigerant', /\bR[-\s]?(410A|134A|1234ZE|1234YF|1233ZD|513A|514A|515B|454B|468A|449A|407C|452A|455A|245FA|123|32|22|717|744|290|128|503|508B)\b/, m => `R-${m[1]}`);
167
  scan('hz', /\b(50|60)\s*HZ\b|\bHZ\s*[:]?\s*(50|60)\b|\bFREQ(?:UENCY)?\.?\s*[:]?\s*(50|60)\b/, m => +(m[1] || m[2] || m[3]));
168
  scan('phase', /\b([13])\s*-?\s*(?:PH|PHASE|Ø|Φ)\b|\bPH(?:ASE)?\s*[:]?\s*([13])\b/, m => +(m[1] || m[2]));
169
  scan('kva', new RegExp(`${NUM}\\s*KVA\\b|\\bKVA\\s*[:]?\\s*${NUM}`), m => positive(num(m[1] || m[2])));
170
  scan('kw', new RegExp(`${NUM}\\s*E?KW\\b|\\bE?KW\\s*[:]?\\s*${NUM}`), m => positive(num(m[1] || m[2])));
171
  scan('mfgDate', /\b(?:MFG\.?|MANUFACTURED|MFD\.?|BUILD|PROD(?:UCTION)?\.?)\s*(?:DATE)?\s*[:]?\s*(\d{1,2}[/-]\d{2,4}|\d{4}[/-]\d{1,2}(?:[/-]\d{1,2})?|\d{1,2}[/-]\d{1,2}[/-]\d{2,4})/, m => m[1]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
  // Voltage: every voltage on the plate (a transformer or UPS carries more than one).
174
  const volts = [];
175
  let voltLine = null;
176
  for (const [i, l] of lines.entries()) {
177
- const found = voltagesIn(up(l.text));
 
 
 
 
 
 
178
  if (found.values.length) {
179
  for (const v of found.values) if (!volts.includes(v)) volts.push(v);
180
  if (!voltLine) voltLine = { text: found.display, conf: l.conf, line: i };
@@ -239,23 +282,77 @@ export function parseNameplate(input) {
239
  let makerLine = -1;
240
  for (const [i, l] of lines.entries()) {
241
  // "New York" on a supplier's address is not York the maker.
242
- const t = up(l.text).replace(/NEW YORK/g, '');
243
- const maker = MAKERS.find(mk => new RegExp(`\\b${escapeRe(up(mk))}\\b`).test(t));
244
  if (maker) { set('manufacturer', maker, l.conf, i); makerLine = i; break; }
245
  }
246
  if (!fields.manufacturer) {
247
- const i = lines.findIndex(x => COMPANY_LINE.test(up(x.text)) && !/\d{3}/.test(x.text) && x.text.length <= 48);
248
- if (i >= 0) { set('manufacturer', titleCase(lines[i].text.replace(/[^A-Za-z0-9&.,\- ]/g, '').trim()), lines[i].conf, i); makerLine = i; }
 
 
249
  }
250
 
251
  // Equipment type from plate text, excluding the maker line: a vendor called
252
  // "…Transformer Corp" or "…Switchgear Ltd" must not type a chiller plate.
253
- const all = up(lines.filter((_, i) => i !== makerLine).map(l => l.text).join('\n'));
254
- const type = (EQUIPMENT_TYPES.find(([, , re]) => re.test(all)) || [null])[0];
 
255
  const conf = lines.length ? Math.round(lines.reduce((s, l) => s + l.conf, 0) / lines.length) : 0;
256
  return { fields, type, conf, text: lines.map(l => l.text).join('\n'), lines: lines.map(l => ({ text: l.text, conf: l.conf, bbox: l.bbox })) };
257
  }
258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  /**
260
  * Undo the misreads Tesseract makes on plate lettering (seen in tests/nameplates-bench.mjs):
261
  * a serifed "V" read as "Vv", "Y" as "¥", codes and decimals split after their punctuation
 
152
  const fields = {};
153
  // line: index of the OCR line the value came from, so the page can outline it on the photo.
154
  const set = (key, value, conf, line) => { if (fields[key] == null && value != null && value !== '') fields[key] = { value, conf, line }; };
155
+ // OCR look-alike readings of each line (same length, character for character; see foldWords / foldNumbers):
156
+ // labels and words are matched on `words`, numbers and dates read from `nums`. The raw line is tried first,
157
+ // so a clean plate parses exactly as before.
158
+ const views = lines.map(l => {
159
+ const t = up(l.text);
160
+ const words = [...new Set(['I', 'L'].flatMap(one => ['O', 'D'].map(zero => foldWords(t, one, zero))))].filter(v => v !== t);
161
+ return { raw: t, words, nums: [...new Set([foldNumbers(t), ...words.map(foldNumbers)])].filter(v => v !== t) };
162
+ });
163
  // Each rule runs over every line in order, so the first line that has the field wins.
164
+ // kind 'num' (default): numbers/dates may come from the number-folded reading; 'word': labels/words only;
165
+ // 'code': the label may be found in a folded reading but the value is the RAW characters at the same place
166
+ // (a model or serial number legitimately mixes letters and digits).
167
+ const scan = (key, re, map = m => m[1], kind = 'num') => {
168
+ const reD = kind === 'code' ? new RegExp(re.source, re.flags.replace('d', '') + 'd') : null;
169
  for (const [i, l] of lines.entries()) {
170
+ const v = views[i];
171
+ const tries = [v.raw, ...v.words, ...(kind === 'num' ? v.nums : [])];
172
+ for (const t of tries) {
173
+ let m = t.match(reD || re);
174
+ if (!m) continue;
175
+ if (reD && t !== v.raw) {
176
+ const at = m.indices && m.indices.findIndex((ix, g) => g > 0 && ix);
177
+ if (at > 0) { const [a, b] = m.indices[at]; m = [...m]; m[at] = v.raw.slice(a, b); }
178
+ }
179
+ const val = map(m);
180
+ if (val != null && val !== '') { set(key, val, l.conf, i); return; }
181
+ }
182
  }
183
  };
184
 
185
  const CODE = '([A-Z0-9][A-Z0-9\\-\\/\\.]{2,})';
186
+ scan('model', new RegExp(`(?:\\bMODEL\\b|\\bMOD\\.|\\bM\\/N\\b|\\bCAT(?:ALOG)?\\.?\\s*(?:NO\\b\\.?|#|NUMBER)|\\bP\\/N\\b|\\bPART\\s*(?:NO\\b\\.?|#|NUMBER))\\s*(?:NO\\b\\.?|NUMBER\\b|#)?\\s*[:#.]?\\s*${CODE}`), m => cleanCode(m[1]), 'code');
187
+ scan('serial', new RegExp(`(?:\\bSERIAL\\b|\\bSER\\.|\\bS\\/N\\b|\\b5\\/N\\b|\\bSN\\b)\\s*(?:NO\\b\\.?|NUMBER\\b|#)?\\s*[:#.]?\\s*([A-Z0-9][A-Z0-9\\-]{3,})`), m => cleanCode(m[1]), 'code');
188
  scan('refrigerant', /\bR[-\s]?(410A|134A|1234ZE|1234YF|1233ZD|513A|514A|515B|454B|468A|449A|407C|452A|455A|245FA|123|32|22|717|744|290|128|503|508B)\b/, m => `R-${m[1]}`);
189
  scan('hz', /\b(50|60)\s*HZ\b|\bHZ\s*[:]?\s*(50|60)\b|\bFREQ(?:UENCY)?\.?\s*[:]?\s*(50|60)\b/, m => +(m[1] || m[2] || m[3]));
190
  scan('phase', /\b([13])\s*-?\s*(?:PH|PHASE|Ø|Φ)\b|\bPH(?:ASE)?\s*[:]?\s*([13])\b/, m => +(m[1] || m[2]));
191
  scan('kva', new RegExp(`${NUM}\\s*KVA\\b|\\bKVA\\s*[:]?\\s*${NUM}`), m => positive(num(m[1] || m[2])));
192
  scan('kw', new RegExp(`${NUM}\\s*E?KW\\b|\\bE?KW\\s*[:]?\\s*${NUM}`), m => positive(num(m[1] || m[2])));
193
  scan('mfgDate', /\b(?:MFG\.?|MANUFACTURED|MFD\.?|BUILD|PROD(?:UCTION)?\.?)\s*(?:DATE)?\s*[:]?\s*(\d{1,2}[/-]\d{2,4}|\d{4}[/-]\d{1,2}(?:[/-]\d{1,2})?|\d{1,2}[/-]\d{1,2}[/-]\d{2,4})/, m => m[1]);
194
+ // OCR splits a word or a date with a stray space ("BU ILD DAT E 06/2026", "09 /2024", "2O2 5"): allow one space
195
+ // inside the label words and read the value with its spaces removed.
196
+ if (!fields.mfgDate) {
197
+ const w = s => s.split('').join('\\s?');
198
+ const label = new RegExp(`\\b(?:${w('MFG')}|${w('MFD')}|${w('BUILD')}|${w('MANUFACTURED')}|${w('PRODUCTION')}|${w('PROD')})\\.?\\s*(?:${w('DATE')})?\\s*[:.]?`);
199
+ const value = /^(\d{1,2}[/-]\d{4}|\d{1,2}[/-]\d{2}(?![\d])|\d{4}[/-]\d{1,2}(?:[/-]\d{1,2})?|\d{1,2}[/-]\d{1,2}[/-]\d{2,4})/;
200
+ for (const [i, l] of lines.entries()) {
201
+ for (const t of [views[i].raw, ...views[i].nums]) {
202
+ const m = t.match(label);
203
+ const v = m && t.slice(m.index + m[0].length).replace(/\s+/g, '').match(value);
204
+ if (v) { set('mfgDate', v[1], l.conf, i); break; }
205
+ }
206
+ if (fields.mfgDate) break;
207
+ }
208
+ }
209
 
210
  // Voltage: every voltage on the plate (a transformer or UPS carries more than one).
211
  const volts = [];
212
  let voltLine = null;
213
  for (const [i, l] of lines.entries()) {
214
+ let found = voltagesIn(views[i].raw);
215
+ for (const t of views[i].nums) if (!found.values.length) found = voltagesIn(t);
216
+ // A digit run split by a stray space ("4 15Y/240", "2 08 V"): use the rejoined reading only if it finds more.
217
+ for (const t of [views[i].raw, ...views[i].nums]) {
218
+ const joined = t.replace(/(?<=\b\d{1,2}) (?=\d)/g, '');
219
+ if (joined !== t) { const j = voltagesIn(joined); if (j.values.length > found.values.length) found = j; }
220
+ }
221
  if (found.values.length) {
222
  for (const v of found.values) if (!volts.includes(v)) volts.push(v);
223
  if (!voltLine) voltLine = { text: found.display, conf: l.conf, line: i };
 
282
  let makerLine = -1;
283
  for (const [i, l] of lines.entries()) {
284
  // "New York" on a supplier's address is not York the maker.
285
+ const ts = [views[i].raw, ...views[i].words].map(t => t.replace(/NEW YORK/g, ''));
286
+ const maker = MAKERS.find(mk => { const re = new RegExp(`\\b${escapeRe(up(mk))}\\b`); return ts.some(t => re.test(t)); });
287
  if (maker) { set('manufacturer', maker, l.conf, i); makerLine = i; break; }
288
  }
289
  if (!fields.manufacturer) {
290
+ const company = i => [views[i].raw, ...views[i].words].map(t => joinSplit(t, x => COMPANY_LINE.test(x)))
291
+ .find(t => COMPANY_LINE.test(t) && !/\d{3}/.test(t));
292
+ const i = lines.findIndex((x, k) => company(k) && x.text.length <= 48);
293
+ if (i >= 0) { set('manufacturer', titleCase(company(i).replace(/[^A-Za-z0-9&.,\- ]/g, '').trim()), lines[i].conf, i); makerLine = i; }
294
  }
295
 
296
  // Equipment type from plate text, excluding the maker line: a vendor called
297
  // "…Transformer Corp" or "…Switchgear Ltd" must not type a chiller plate.
298
+ const keep = views.filter((_, i) => i !== makerLine);
299
+ const texts = [keep.map(v => v.raw).join('\n'), ...['I', 'L'].map(one => keep.map(v => foldWords(v.raw, one)).join('\n'))];
300
+ const type = (EQUIPMENT_TYPES.find(([, , re]) => texts.some(t => re.test(t))) || [null])[0];
301
  const conf = lines.length ? Math.round(lines.reduce((s, l) => s + l.conf, 0) / lines.length) : 0;
302
  return { fields, type, conf, text: lines.map(l => l.text).join('\n'), lines: lines.map(l => ({ text: l.text, conf: l.conf, bbox: l.bbox })) };
303
  }
304
 
305
+ /** OCR splits a word with a stray space ("Westgate Po wer"): remove up to two single spaces, fewest first, until
306
+ * `ok` holds; the text unchanged if no such join exists. */
307
+ export function joinSplit(t, ok) {
308
+ if (ok(t)) return t;
309
+ const gaps = [...t.matchAll(/(?<=[A-Za-z0-9]) (?=[A-Za-z0-9])/g)].map(m => m.index);
310
+ const cut = (s, at) => s.slice(0, at) + s.slice(at + 1);
311
+ for (const a of gaps) { const u = cut(t, a); if (ok(u)) return u; }
312
+ for (const a of gaps) for (const b of gaps) if (b > a) { const u = cut(cut(t, b), a); if (ok(u)) return u; }
313
+ return t;
314
+ }
315
+
316
+ // OCR look-alikes on plate lettering: O/0, I/1, L/1, S/5, B/8, Z/2, G/6, D/0. Both folds keep the length, so a
317
+ // position in a folded reading is the same position in the raw line.
318
+ const LETTER_OF = { 0: 'O', 5: 'S', 8: 'B', 2: 'Z', 6: 'G' };
319
+ const DIGIT_OF = { O: '0', D: '0', I: '1', L: '1', S: '5', B: '8', Z: '2', G: '6' };
320
+
321
+ /** Digits read inside a word back to letters ("M0DEL" -> MODEL, "5Y5TEM5" -> SYSTEMS): only in tokens that are
322
+ * mostly letters, so "480Y/277V", "R-410A" and "2U" are left alone. `one` / `zero`: the letter a 1 / 0 stands for. */
323
+ export function foldWords(t, one = 'I', zero = 'O') {
324
+ return t.replace(/[A-Za-z0-9]+/g, tok => {
325
+ const L = (tok.match(/[A-Za-z]/g) || []).length, D = (tok.match(/\d/g) || []).length;
326
+ return D && L > D ? tok.replace(/\d/g, d => (d === '1' ? one : d === '0' ? zero : LETTER_OF[d] ?? d)) : tok;
327
+ });
328
+ }
329
+
330
+ /** Look-alike letters touching a digit back to digits ("2O23-O4" -> 2023-04, "3B.5" -> 38.5); a letter with no
331
+ * digit beside it ("65 KAIC", "MODEL") is a letter. Two passes, so "OO5" and "1OOO" both resolve. Codes are left
332
+ * alone: a token with a letters-only part ("VR-1732GW", "CW-9880GB") or three or more letters that are not
333
+ * look-alikes ("NL24ANP7BW") is a model or serial number, where "1732GW" must not become 17,326 W. */
334
+ export function foldNumbers(t) {
335
+ return t.split(/(\s+)/).map(tok => (/\s/.test(tok) || isCode(tok) ? tok : foldNumberToken(tok))).join('');
336
+ }
337
+
338
+ function isCode(tok) {
339
+ if (tok.split(/[-/]/).some(seg => /^[A-Za-z]{2,}$/.test(seg)) && /\d/.test(tok)) return true;
340
+ return (tok.match(/[AC-FH-KMNP-RT-Yac-fh-kmnp-rt-y]/g) || []).length >= 3; // letters with no digit look-alike
341
+ }
342
+
343
+ function foldNumberToken(t) {
344
+ const c = [...t];
345
+ const isD = ch => ch >= '0' && ch <= '9';
346
+ const near = (k, d) => { let j = k + d; while (c[j] === '.' || c[j] === ',') j += d; return isD(c[j] ?? ''); };
347
+ for (const order of [[...c.keys()], [...c.keys()].reverse()]) {
348
+ for (const k of order) {
349
+ const dg = DIGIT_OF[c[k].toUpperCase()];
350
+ if (dg && (isD(c[k - 1] ?? '') || isD(c[k + 1] ?? '') || near(k, -1) || near(k, 1))) c[k] = dg;
351
+ }
352
+ }
353
+ return c.join('');
354
+ }
355
+
356
  /**
357
  * Undo the misreads Tesseract makes on plate lettering (seen in tests/nameplates-bench.mjs):
358
  * a serifed "V" read as "Vv", "Y" as "¥", codes and decimals split after their punctuation
tests/nameplates-extraction-bench.mjs CHANGED
@@ -251,7 +251,8 @@ function corpus(n, seed) {
251
  function main() {
252
  const args = Object.fromEntries(process.argv.slice(2).map(a => a.replace(/^--/, '').split('=')));
253
  const n = +(args.n || 400);
254
- const results = { clean: run('clean', n, 20, !!args.verbose), ocr: run('ocr', n, 20, !!args.verbose) };
 
255
  for (const key of ['clean', 'ocr']) {
256
  const res = results[key];
257
  console.log(`\n${key.toUpperCase()} n=${res.n} exact-plate ${(100 * res.exactPlate).toFixed(1)}% micro-F1 ${(100 * res.microF1).toFixed(1)}% ${res.msPerPlate} ms/plate`);
@@ -259,7 +260,7 @@ function main() {
259
  for (const [k, c] of rows) console.log(` ${k.padEnd(13)} P ${(100 * c.precision).toFixed(1).padStart(5)} R ${(100 * c.recall).toFixed(1).padStart(5)} F1 ${(100 * c.f1).toFixed(1).padStart(5)} (${c.support})`);
260
  }
261
  if (args.json) writeFileSync(args.json, JSON.stringify(results, null, 2));
262
- if (args.dump) writeFileSync(args.dump, corpus(+(args.dumpN || 200), 20).map(x => JSON.stringify(x)).join('\n') + '\n');
263
  }
264
 
265
  if (import.meta.url === `file://${process.argv[1]}`) main();
 
251
  function main() {
252
  const args = Object.fromEntries(process.argv.slice(2).map(a => a.replace(/^--/, '').split('=')));
253
  const n = +(args.n || 400);
254
+ const seed = +(args.seed || 20);
255
+ const results = { clean: run('clean', n, seed, !!args.verbose), ocr: run('ocr', n, seed, !!args.verbose) };
256
  for (const key of ['clean', 'ocr']) {
257
  const res = results[key];
258
  console.log(`\n${key.toUpperCase()} n=${res.n} exact-plate ${(100 * res.exactPlate).toFixed(1)}% micro-F1 ${(100 * res.microF1).toFixed(1)}% ${res.msPerPlate} ms/plate`);
 
260
  for (const [k, c] of rows) console.log(` ${k.padEnd(13)} P ${(100 * c.precision).toFixed(1).padStart(5)} R ${(100 * c.recall).toFixed(1).padStart(5)} F1 ${(100 * c.f1).toFixed(1).padStart(5)} (${c.support})`);
261
  }
262
  if (args.json) writeFileSync(args.json, JSON.stringify(results, null, 2));
263
+ if (args.dump) writeFileSync(args.dump, corpus(+(args.dumpN || 200), seed).map(x => JSON.stringify(x)).join('\n') + '\n');
264
  }
265
 
266
  if (import.meta.url === `file://${process.argv[1]}`) main();